repo_name
stringlengths 7
79
| path
stringlengths 8
206
| copies
stringclasses 36
values | size
stringlengths 2
6
| content
stringlengths 55
523k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 7.18
99.5
| line_max
int64 16
979
| alpha_frac
float64 0.3
0.87
| ratio
float64 2.01
8.07
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
orgzly/orgzly-android | app/src/main/java/com/orgzly/android/query/sql/SqliteQueryBuilder.kt | 1 | 11770 | package com.orgzly.android.query.sql
import android.content.Context
import android.database.DatabaseUtils
import com.orgzly.android.prefs.AppPreferences
import com.orgzly.android.query.*
import com.orgzly.org.datetime.OrgInterval
import java.util.*
class SqliteQueryBuilder(val context: Context) {
private var where: String = ""
private val arguments: MutableList<String> = ArrayList()
private var having: String = ""
private var order: String = ""
private var hasScheduledCondition = false
private var hasDeadlineCondition = false
private var hasCreatedCondition = false
fun build(query: Query): SqlQuery {
hasScheduledCondition = false
hasDeadlineCondition = false
hasCreatedCondition = false
where = toString(query.condition)
order = buildOrderBy(query.sortOrders)
return SqlQuery(where, arguments, having, order)
}
private fun buildOrderBy(sortOrders: List<SortOrder>): String {
val o = ArrayList<String>()
if (sortOrders.isEmpty()) { // Use default sort order
o.add("book_name")
/* Priority or default priority. */
o.add("COALESCE(priority, '" + AppPreferences.defaultPriority(context) + "')")
o.add("priority IS NULL")
if (hasScheduledCondition) {
o.add("scheduled_time_timestamp IS NULL")
o.add("scheduled_time_start_of_day")
o.add("scheduled_time_hour IS NULL")
o.add("scheduled_time_timestamp")
}
if (hasDeadlineCondition) {
o.add("deadline_time_timestamp IS NULL")
o.add("deadline_time_start_of_day")
o.add("deadline_time_hour IS NULL")
o.add("deadline_time_timestamp")
}
if (hasCreatedCondition) {
o.add("created_at DESC")
}
} else {
sortOrders.forEach { order ->
when (order) {
is SortOrder.Book ->
o.add("book_name" + if (order.desc) " DESC" else "")
is SortOrder.Title ->
o.add("title" + if (order.desc) " DESC" else "")
is SortOrder.Scheduled -> {
o.add("scheduled_time_timestamp IS NULL")
if (order.desc) {
o.add("scheduled_time_start_of_day DESC")
o.add("scheduled_time_hour IS NOT NULL")
o.add("scheduled_time_timestamp DESC")
} else {
o.add("scheduled_time_start_of_day")
o.add("scheduled_time_hour IS NULL")
o.add("scheduled_time_timestamp")
}
}
is SortOrder.Deadline -> {
o.add("deadline_time_timestamp IS NULL")
if (order.desc) {
o.add("deadline_time_start_of_day DESC")
o.add("deadline_time_hour IS NOT NULL")
o.add("deadline_time_timestamp DESC")
} else {
o.add("deadline_time_start_of_day")
o.add("deadline_time_hour IS NULL")
o.add("deadline_time_timestamp")
}
}
is SortOrder.Event -> {
o.add("event_timestamp IS NULL")
if (order.desc) {
o.add("MAX(event_start_of_day) DESC")
o.add("MAX(event_hour) IS NOT NULL")
o.add("MAX(event_timestamp) DESC")
} else {
o.add("MIN(event_start_of_day)")
o.add("MIN(event_hour) IS NULL")
o.add("MIN(event_timestamp)")
}
}
is SortOrder.Created -> {
o.add("created_at IS NULL")
if (order.desc) {
o.add("created_at DESC")
} else {
o.add("created_at")
}
}
is SortOrder.Closed -> {
o.add("closed_time_timestamp IS NULL")
if (order.desc) {
o.add("closed_time_start_of_day DESC")
o.add("closed_time_hour IS NOT NULL")
o.add("closed_time_timestamp DESC")
} else {
o.add("closed_time_start_of_day")
o.add("closed_time_hour IS NULL")
o.add("closed_time_timestamp")
}
}
is SortOrder.Priority -> {
o.add("COALESCE(priority, '" + AppPreferences.defaultPriority(context) + "')" + if (order.desc) " DESC" else "")
o.add("priority" + if (order.desc) " IS NOT NULL" else " IS NULL")
}
is SortOrder.State -> {
val states = AppPreferences.todoKeywordsSet(context)
.union(AppPreferences.doneKeywordsSet(context))
if (states.isNotEmpty()) {
val statesInOrder = if (order.desc) states.reversed() else states
o.add(statesInOrder.foldIndexed("CASE state") { i, str, state ->
"$str WHEN ${DatabaseUtils.sqlEscapeString(state)} THEN $i"
} + " ELSE ${states.size} END")
}
}
is SortOrder.Position -> {
o.add("lft" + if (order.desc) " DESC" else "")
}
}
}
}
/* Always sort by position last. */
o.add("lft")
return o.joinToString(", ")
}
private fun joinConditions(members: List<Condition>, operator: String): String {
return members.joinToString(prefix = "(", separator = " $operator ", postfix = ")") {
toString(it)
}
}
private fun toString(expr: Condition?): String {
fun not(not: Boolean, selection: String): String = if (not) "NOT($selection)" else selection
return when (expr) {
is Condition.InBook -> {
arguments.add(expr.name)
not(expr.not, "book_name = ?")
}
is Condition.HasState -> {
arguments.add(expr.state.uppercase())
not(expr.not, "COALESCE(state, '') = ?")
}
is Condition.HasStateType -> {
when (expr.type) {
StateType.TODO -> {
val states = AppPreferences.todoKeywordsSet(context)
arguments.addAll(states)
not(expr.not, "COALESCE(state, '') IN (" + Collections.nCopies(states.size, "?").joinToString() + ")")
}
StateType.DONE -> {
val states = AppPreferences.doneKeywordsSet(context)
arguments.addAll(states)
not(expr.not, "COALESCE(state, '') IN (" + Collections.nCopies(states.size, "?").joinToString() + ")")
}
StateType.NONE -> not(expr.not, "COALESCE(state, '') = ''")
}
}
is Condition.HasPriority -> {
arguments.add(AppPreferences.defaultPriority(context))
arguments.add(expr.priority)
not(expr.not, "LOWER(COALESCE(NULLIF(priority, ''), ?)) = ?")
}
is Condition.HasSetPriority -> {
arguments.add(expr.priority)
not(expr.not, "LOWER(COALESCE(priority, '')) = ?")
}
is Condition.HasTag -> {
repeat(2) { arguments.add("%${expr.tag}%") }
not(expr.not, "(COALESCE(tags, '') LIKE ? OR COALESCE(inherited_tags, '') LIKE ?)")
}
is Condition.HasOwnTag -> {
arguments.add("%${expr.tag}%")
not(expr.not, "(COALESCE(tags, '') LIKE ?)")
}
is Condition.Event -> {
toInterval("event_timestamp", null, expr.interval, expr.relation)
}
is Condition.Scheduled -> {
hasScheduledCondition = true
toInterval("scheduled_time_timestamp", "scheduled_is_active", expr.interval, expr.relation)
}
is Condition.Deadline -> {
hasDeadlineCondition = true
toInterval("deadline_time_timestamp", "deadline_is_active", expr.interval, expr.relation)
}
is Condition.Created -> {
hasCreatedCondition = true
toInterval("created_at", null, expr.interval, expr.relation)
}
is Condition.Closed -> {
toInterval("closed_time_timestamp", null, expr.interval, expr.relation)
}
is Condition.HasText -> {
repeat(3) { arguments.add("%${expr.text}%") }
"(title LIKE ? OR content LIKE ? OR tags LIKE ?)"
}
is Condition.Or -> joinConditions(expr.operands, "OR")
is Condition.And -> joinConditions(expr.operands, "AND")
null -> "" // No conditions
}
}
private fun toInterval(column: String, isActiveColumn: String?, interval: QueryInterval, relation: Relation): String {
if (interval.none) {
return "$column IS NULL"
}
val (field, value) = getFieldAndValueFromInterval(interval)
val timeFromNow = TimeUtils.timeFromNow(field, value)
val timeFromNowPlusOne = TimeUtils.timeFromNow(field, value, true)
val cond = when (relation) {
Relation.EQ -> "$timeFromNow <= $column AND $column < $timeFromNowPlusOne"
Relation.NE -> "$column < $timeFromNow AND $timeFromNowPlusOne <= $column"
Relation.LT -> "$column < $timeFromNow"
Relation.LE -> "$column < $timeFromNowPlusOne"
Relation.GT -> "$timeFromNowPlusOne <= $column"
Relation.GE -> "$timeFromNow <= $column"
}
val activeOnly = if (isActiveColumn != null) {
"$isActiveColumn = 1 AND "
} else {
""
}
return "($activeOnly$column != 0 AND $cond)"
}
/*
* TODO: Clean this up.
* There's no need to depend on Org-supported units.
* Remove OrgInterval dependency from QueryInterval.
*/
private fun getFieldAndValueFromInterval(interval: QueryInterval): Pair<Int, Int> {
return if (interval.now) {
Pair(Calendar.MILLISECOND, 0)
} else {
val unit = when (interval.unit) {
OrgInterval.Unit.HOUR -> Calendar.HOUR_OF_DAY
OrgInterval.Unit.DAY -> Calendar.DAY_OF_MONTH
OrgInterval.Unit.WEEK -> Calendar.WEEK_OF_YEAR
OrgInterval.Unit.MONTH -> Calendar.MONTH
OrgInterval.Unit.YEAR -> Calendar.YEAR
null -> throw IllegalArgumentException("Interval unit not set")
}
val value = interval.value
Pair(unit, value)
}
}
}
| gpl-3.0 | d833c80dcc4e3e302a4ef7330a902fc5 | 35.666667 | 136 | 0.47825 | 4.788446 | false | false | false | false |
syrop/Wiktor-Navigator | navigator/src/main/kotlin/pl/org/seva/navigator/contact/SeekContactFragment.kt | 1 | 6486 | /*
* Copyright (C) 2017 Wiktor Nizio
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* If you like this program, consider donating bitcoin: bc1qncxh5xs6erq6w4qz3a7xl7f50agrgn3w58dsfp
*/
@file:Suppress("DEPRECATION")
package pl.org.seva.navigator.contact
import android.app.ProgressDialog
import android.app.SearchManager
import android.content.Context
import android.os.Bundle
import android.text.Spannable
import android.text.SpannableString
import android.text.style.ImageSpan
import android.view.*
import androidx.appcompat.widget.SearchView
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import kotlinx.android.synthetic.main.fr_seek_contact.*
import pl.org.seva.navigator.R
import pl.org.seva.navigator.main.data.fb.fbReader
import pl.org.seva.navigator.main.data.fb.fbWriter
import pl.org.seva.navigator.main.extension.observe
import pl.org.seva.navigator.main.NavigatorViewModel
import pl.org.seva.navigator.main.extension.back
import pl.org.seva.navigator.main.extension.toast
import pl.org.seva.navigator.main.extension.viewModel
import pl.org.seva.navigator.profile.loggedInUser
import java.util.*
@Suppress("DEPRECATION")
class SeekContactFragment : Fragment(R.layout.fr_seek_contact) {
private var progress: ProgressDialog? = null
private val searchManager get() =
requireContext().getSystemService(Context.SEARCH_SERVICE) as SearchManager
private val navigatorModel by viewModel<NavigatorViewModel>()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setHasOptionsMenu(true)
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
setPromptText(R.string.seek_contact_press_to_begin)
navigatorModel.query.observe(this) { query ->
if (query.isNotEmpty()) {
navigatorModel.query.value = ""
progress = ProgressDialog.show(context, null, getString(R.string.seek_contact_searching))
fbReader.findContact(query.toLowerCase(Locale.getDefault()))
.subscribe { onContactReceived(it) }
}
}
}
private fun setPromptText(id: Int) {
fun String.insertSearchImage(): SpannableString {
val result = SpannableString(this)
val d = resources.getDrawable(R.drawable.ic_search_black_24dp)
d.setBounds(0, 0, d.intrinsicWidth, d.intrinsicHeight)
val span = ImageSpan(d, ImageSpan.ALIGN_BASELINE)
val idPlaceholder = indexOf(IMAGE_PLACEHOLDER)
if (idPlaceholder >= 0) {
result.setSpan(
span,
idPlaceholder,
idPlaceholder + IMAGE_PLACEHOLDER_LENGTH,
Spannable.SPAN_INCLUSIVE_EXCLUSIVE)
}
return result
}
prompt.text = getString(id).insertSearchImage()
}
override fun onCreateOptionsMenu(menu: Menu, menuInflater: MenuInflater) {
fun MenuItem.prepareSearchView() = with (actionView as SearchView) {
setOnSearchClickListener { prompt.visibility = View.GONE }
setSearchableInfo(searchManager.getSearchableInfo(requireActivity().componentName))
setOnCloseListener {
if (contacts_view.visibility != View.VISIBLE) {
prompt.visibility = View.VISIBLE
}
setPromptText(R.string.seek_contact_press_to_begin)
false
}
}
menuInflater.inflate(R.menu.seek_contact, menu)
val searchMenuItem = menu.findItem(R.id.action_search)
searchMenuItem.collapseActionView()
searchMenuItem.prepareSearchView()
}
override fun onOptionsItemSelected(item: MenuItem): Boolean = when (item.itemId) {
R.id.action_search -> {
prompt.visibility = View.GONE
contacts_view.visibility = View.GONE
requireActivity().onSearchRequested()
true
}
else -> super.onOptionsItemSelected(item)
}
private fun onContactReceived(contact: Contact) {
fun initRecyclerView() {
contacts_view.setHasFixedSize(true)
val lm = LinearLayoutManager(context)
contacts_view.layoutManager = lm
val adapter = ContactSingleAdapter(contact) { selectedContact ->
when {
selectedContact in contacts -> back()
selectedContact.email == loggedInUser.email ->
getString(R.string.seek_contact_cannot_add_yourself).toast()
else -> FriendshipAddDialogBuilder(requireContext())
.setContact(selectedContact)
.setYesAction { contactApprovedAndFinish(selectedContact) }
.setNoAction { back() }
.build()
.show()
}
}
contacts_view.adapter = adapter
}
checkNotNull(progress).cancel()
if (contact.isEmpty) {
prompt.visibility = View.VISIBLE
contacts_view.visibility = View.GONE
setPromptText(R.string.seek_contact_no_user_found)
return
}
prompt.visibility = View.GONE
contacts_view.visibility = View.VISIBLE
initRecyclerView()
}
private fun contactApprovedAndFinish(contact: Contact) {
getString(R.string.seek_contact_waiting_for_party).toast()
fbWriter requestFriendship contact
back()
}
companion object {
private const val IMAGE_PLACEHOLDER = "[image]"
private const val IMAGE_PLACEHOLDER_LENGTH = IMAGE_PLACEHOLDER.length
}
}
| gpl-3.0 | 0608103c864ee707debd49e722c1bec6 | 37.378698 | 105 | 0.651403 | 4.769118 | false | false | false | false |
nobumin/mstdn_light_android | app/src/main/java/view/mstdn/meas/jp/multimstdn/view/SiteListActivity.kt | 1 | 10443 | package view.mstdn.meas.jp.multimstdn.view
import android.app.ProgressDialog
import android.content.Context
import android.os.Bundle
import android.preference.PreferenceManager
import android.support.design.widget.FloatingActionButton
import android.support.v4.widget.SwipeRefreshLayout
import android.support.v7.app.AppCompatActivity
import android.text.Editable
import android.text.TextWatcher
import android.util.Log
import android.widget.EditText
import android.widget.ListView
import android.widget.Toast
import org.apache.http.HttpResponse
import org.json.JSONArray
import view.mstdn.meas.jp.multimstdn.R
import view.mstdn.meas.jp.multimstdn.adapter.SiteListAdapter
import view.mstdn.meas.jp.multimstdn.util.HttpAccesser
import java.io.InputStream
import java.net.URL
import java.util.*
/**
* Created by nobu on 2017/04/22.
*/
class SiteListActivity : AppCompatActivity(), SwipeRefreshLayout.OnRefreshListener {
private var _swipeRefreshLayout: SwipeRefreshLayout? = null
private var _adapter: SiteListAdapter? = null
private var _listView: ListView? = null
private var _filterText: EditText? = null
protected var _floatButton: FloatingActionButton? = null
protected var progressDialog_: ProgressDialog? = null
private val LIST_URL = "https://instances.mastodon.xyz/instances.json"
private var _instanceJson: String? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.site_list_layout)
_swipeRefreshLayout = findViewById(R.id.layout) as SwipeRefreshLayout
_swipeRefreshLayout!!.setOnRefreshListener(this)
_listView = findViewById(R.id.listview) as ListView
_filterText = findViewById(R.id.editText) as EditText
_floatButton = findViewById(R.id.FloatBtn) as FloatingActionButton
_floatButton!!.setOnClickListener {
updateSite(this@SiteListActivity)
finish()
}
_adapter = SiteListAdapter(this)
_listView!!.adapter = _adapter
getSites(this)
updateSiteData()
_filterText!!.addTextChangedListener(object : TextWatcher {
override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}
override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {}
override fun afterTextChanged(s: Editable) {
Log.d("debug", "beforeTextChanged")
if (_instanceJson != null) {
_adapter!!.urlList.clear()
parseJson(s.toString())
} else {
_filterText!!.setText("")
}
}
})
}
override fun onRefresh() {
_swipeRefreshLayout!!.isRefreshing = false
updateSiteData()
}
fun updateSiteData() {
try {
_instanceJson = null
progressDialog_ = ProgressDialog(this)
progressDialog_!!.setMessage("インスタンス一覧取得中...")
progressDialog_!!.setProgressStyle(ProgressDialog.STYLE_SPINNER)
progressDialog_!!.show()
_adapter!!.urlList.clear()
val url = URL(LIST_URL)
val http = HttpAccesser(this, url, false, false, object : HttpAccesser.HttpAccessResponse {
override fun needHeader(): Boolean {
return false
}
override fun header(url: URL, headers: Map<String, List<String>>?, e: Exception?): Boolean {
return false
}
override fun result(response: HttpResponse, `is`: InputStream?, context: Context, accesser: HttpAccesser): Boolean {
if (response.statusLine.statusCode == 200) {
try {
var len = 0
var byteData: ByteArray? = null
val buffer = ByteArray(1024)
while (`is`!!.read(buffer).let{ len = it; it != -1}) {
if (byteData == null) {
byteData = ByteArray(len)
System.arraycopy(buffer, 0, byteData, 0, len)
} else {
val tmp = ByteArray(byteData.size)
System.arraycopy(byteData, 0, tmp, 0, byteData.size)
byteData = ByteArray(byteData.size + len)
System.arraycopy(tmp, 0, byteData, 0, tmp.size)
System.arraycopy(buffer, 0, byteData, tmp.size, len)
}
}
if (progressDialog_ != null) {
progressDialog_!!.dismiss()
progressDialog_ = null
}
if (byteData == null) {
Toast.makeText(this@SiteListActivity, "通信状態を確認してください(null)", Toast.LENGTH_SHORT)
} else {
_instanceJson = java.lang.String(byteData, "UTF-8").toString()
parseJson(null)
}
} catch (e: Exception) {
e.printStackTrace()
}
return true
} else {
if (progressDialog_ != null) {
progressDialog_!!.dismiss()
progressDialog_ = null
}
Toast.makeText(this@SiteListActivity, "通信状態を確認してください(" + response.statusLine.statusCode + ")", Toast.LENGTH_SHORT)
}
return false
}
override fun finished(response: HttpResponse, result: String, context: Context, accesser: HttpAccesser) {
Toast.makeText(this@SiteListActivity, "サイトを選択してください", Toast.LENGTH_SHORT)
}
})
val params = arrayOfNulls<HashMap<String, String>>(1)
params[0] = HashMap<String, String>()
http.execute(*params)
} catch (e: Exception) {
e.printStackTrace()
if (progressDialog_ != null) {
progressDialog_!!.dismiss()
progressDialog_ = null
}
Toast.makeText(this, "通信状態を確認してください", Toast.LENGTH_SHORT)
}
}
protected fun parseJson(filter: String?) {
try {
val json = JSONArray(_instanceJson)
val map = LinkedHashMap<String, Int>()
for (i in 0..json.length() - 1) {
val site = json.getJSONObject(i)
if (site.has("name")) {
val domain = site.getString("name")
var url = "http://"
if (site.has("https_score") && site.get("https_score") != null) {
url = "https://"
} else {
if (!site.has("https_score")) {
Log.d("<NO https_score>", domain)
}
}
url += domain
val userNum = if (site.has("users")) site.getInt("users") else 0
if (!site.has("users")) {
Log.d("<NO users>", domain)
}
if (filter != null && filter.length > 0) {
if (domain.indexOf(filter) >= 0) {
map.put(url, userNum)
}
} else {
map.put(url, userNum)
}
}
}
val mapValuesList = ArrayList<Map.Entry<*, *>>(map.entries)
Collections.sort<Map.Entry<*, *>>(mapValuesList) { entry1, entry2 -> (entry2.value as Int).compareTo(entry1.value as Int) }
for (entry in mapValuesList) {
_adapter!!.urlList.add(entry.key.toString())
}
//TODO
Thread(Runnable { runOnUiThread { _adapter!!.notifyDataSetChanged() } }).start()
} catch (e: Exception) {
Toast.makeText(this@SiteListActivity, "サイトを選択してください", Toast.LENGTH_SHORT)
}
}
companion object {
private val URL_KEY = "mastodon_url_key"
private var _sites: Vector<String>? = null
fun addSite(url: String) {
if (_sites != null && !_sites!!.contains(url)) {
_sites!!.add(url)
}
}
fun getSites(context: Context): Vector<String> {
val sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context)
val jsonStr = sharedPreferences.getString(URL_KEY, "[]")
val sites = Vector<String>()
try {
val json = JSONArray(jsonStr)
if (_sites == null) {
_sites = Vector<String>()
for (i in 0..json.length() - 1) {
_sites!!.add(json.getString(i))
}
}
for (i in 0..json.length() - 1) {
sites.add(json.getString(i))
}
} catch (e: Exception) {
e.printStackTrace()
}
return sites
}
fun isOnSite(url: String): Boolean {
if (_sites == null) {
return false
}
return _sites!!.contains(url)
}
fun removeSite(url: String) {
if (_sites != null && _sites!!.contains(url)) {
_sites!!.remove(url)
}
}
fun updateSite(context: Context) {
val sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context)
val editor = sharedPreferences.edit()
val json = JSONArray()
for (u in _sites!!) {
json.put(u)
}
editor.putString(URL_KEY, json.toString())
editor.commit()
}
}
}
| mit | 432daaf216e835d883894450d5852f22 | 39.058366 | 138 | 0.504711 | 4.956668 | false | false | false | false |
bdelville/bohurt-mapper | common/src/main/java/eu/hithredin/bohurt/common/data/EventData.kt | 1 | 1588 | package eu.hithredin.bohurt.common.data
import com.github.kittinunf.fuel.core.ResponseDeserializable
import com.github.salomonbrys.kotson.fromJson
import com.google.gson.Gson
import eu.hithredin.ktopendatasoft.Coordinates
import eu.hithredin.ktopendatasoft.ListResult
import eu.hithredin.ktopendatasoft.genericType
import java.io.Serializable
import java.util.Date
/**
* Tournament, Open training or other bohurt events
*
* TODO get rid of GSON and avoid this weird null system
*/
data class EventData(
val event_name: String,
val date: Date,
var location: Coordinates,
var link: String?,
val city: String = "",
val country: String = "",
val fight_categories: String = "",
val description: String = "",
var end_date: Date?,
val timestamp: Date
) : Serializable {
class Deserializer : ResponseDeserializable<ListResult<EventData>> {
override fun deserialize(content: String) = Gson().fromJson<ListResult<EventData>>(content)
}
/**
* Sanitize qnd validate after Gson deserialization
*/
fun isValid(): Boolean {
if (event_name == null)
return false
if (location == null) {
if (city == null || country == null)
return false
// TODO geocode with google
}
if (date == null)
return false
if (end_date == null)
end_date = date
if (link!!.startsWith("www")) {
link = "http://${link}"
}
return true
}
}
val ListResultType = genericType<ListResult<EventData>>() | gpl-3.0 | d269df52fdd13ee433a5f015469549a0 | 27.890909 | 99 | 0.639798 | 4.178947 | false | false | false | false |
Assassinss/Jandan-Kotlin | app/src/main/java/me/zsj/dan/ui/adapter/common/LoadingHolder.kt | 1 | 1105 | package me.zsj.dan.ui.adapter.common
import android.support.v7.widget.RecyclerView
import android.view.View
import android.widget.FrameLayout
import android.widget.ProgressBar
import android.widget.TextView
import kotterknife.bindView
import me.zsj.dan.R
/**
* @author zsj
*/
class LoadingHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val loadingContainer: FrameLayout by bindView(R.id.loading_container)
val progressBar: ProgressBar by bindView(R.id.progressBar)
val errorText: TextView by bindView(R.id.error_text)
fun showLoading(holder: LoadingHolder, itemCount: Int, error: Boolean) {
if (itemCount == 1) {
holder.loadingContainer.visibility = View.GONE
} else {
holder.loadingContainer.visibility = View.VISIBLE
if (error) {
holder.errorText.visibility = View.VISIBLE
holder.progressBar.visibility = View.GONE
} else {
holder.errorText.visibility = View.GONE
holder.progressBar.visibility = View.VISIBLE
}
}
}
} | gpl-3.0 | 227e20ac28f60521c0db244b01a45936 | 32.515152 | 76 | 0.675113 | 4.350394 | false | false | false | false |
fluidsonic/jetpack-kotlin | Sources/Extensions/List.kt | 1 | 479 | package com.github.fluidsonic.jetpack
public fun <Element> List<Element>.dropFirst() =
drop(1)
public fun <Element> List<Element>.dropLast() =
dropLast(1)
public fun <Element> List<Element>.equals(other: List<Element>?, isEqual: (Element, Element) -> Boolean): Boolean {
if (other == null || size != other.size) {
return false
}
return indices.all { isEqual(this[it], other[it]) }
}
public fun <Element> MutableList<Element>.removeLast() =
removeAt(count() - 1)
| mit | 940f1e0c2d246b14caf51369676eb062 | 20.772727 | 115 | 0.691023 | 3.280822 | false | false | false | false |
hzsweers/palettehelper | palettehelper/src/main/java/io/sweers/palettehelper/ui/MainActivity.kt | 1 | 17379 | package io.sweers.palettehelper.ui
import android.Manifest
import android.app.Activity
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Bundle
import android.os.Environment
import android.preference.Preference
import android.preference.PreferenceCategory
import android.preference.PreferenceFragment
import android.preference.PreferenceScreen
import android.provider.MediaStore
import android.provider.Settings
import android.support.v4.app.ActivityCompat
import android.support.v7.app.AppCompatActivity
import android.text.Html
import android.util.Patterns
import android.view.View
import android.webkit.WebView
import android.widget.EditText
import android.widget.Toast
import com.afollestad.materialdialogs.MaterialDialog
import io.sweers.palettehelper.PaletteHelperApplication
import io.sweers.palettehelper.R
import io.sweers.palettehelper.util.*
import timber.log.Timber
import java.io.File
import java.io.IOException
import java.text.SimpleDateFormat
import java.util.*
import kotlin.properties.Delegates
public class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
Timber.d("Starting up MainActivity.")
PaletteHelperApplication.mixPanel.trackNav(ANALYTICS_NAV_ENTER, ANALYTICS_NAV_MAIN)
if (savedInstanceState == null) {
fragmentManager.beginTransaction().add(R.id.container, SettingsFragment.newInstance()).commit()
}
}
override fun onDestroy() {
super.onDestroy()
PaletteHelperApplication.mixPanel.flush()
}
public class SettingsFragment : PreferenceFragment() {
private var imagePath: String by Delegates.notNull()
private val REQUEST_LOAD_IMAGE = 1
private val REQUEST_IMAGE_CAPTURE = 2
private val REQUEST_READ_STORAGE_PERMISSION = 3
private val REQUEST_WRITE_STORAGE_PERMISSION = 4
private val REQUEST_APP_SETTINGS = 5
private val EXTRA_PERMISSION_ORIGIN = "permission_origin"
companion object {
public fun newInstance(): SettingsFragment {
return SettingsFragment()
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
Timber.d("Starting up PreferenceFragment.")
retainInstance = true
addPreferencesFromResource(R.xml.main_activity_pref_screen)
// Hide pick intent option if it's not possible. Should be rare though
Timber.d("Checking for pick intent.")
if (createPickIntent() == null) {
Timber.d("No pick option available, disabling.")
(findPreference("pref_key_cat_palette") as PreferenceCategory).removePreference(findPreference("pref_key_open"))
}
// Hide the camera option if it's not possible
Timber.d("Checking for camera intent.")
if (createCameraIntent() == null) {
Timber.d("No camera option available, disabling.")
(findPreference("pref_key_cat_palette") as PreferenceCategory).removePreference(findPreference("pref_key_camera"))
}
}
override fun onPreferenceTreeClick(preferenceScreen: PreferenceScreen, preference: Preference): Boolean {
Timber.d("Clicked preference ${preference.key}")
when (preference.key) {
"pref_key_open" -> {
PaletteHelperApplication.mixPanel.trackNav(ANALYTICS_NAV_MAIN, ANALYTICS_NAV_INTERNAL)
dispatchPickIntent()
return true
}
"pref_key_camera" -> {
PaletteHelperApplication.mixPanel.trackNav(ANALYTICS_NAV_MAIN, ANALYTICS_NAV_CAMERA)
dispatchTakePictureIntent()
return true
}
"pref_key_url" -> {
PaletteHelperApplication.mixPanel.trackNav(ANALYTICS_NAV_MAIN, ANALYTICS_NAV_URL)
val inputView = View.inflate(activity, R.layout.basic_edittext_dialog, null)
val input = inputView.findViewById(R.id.et) as EditText
val clipText = getClipData(activity)
// If there's a URL in the clipboard, guess that that's what they want to retrieve and autofill
if (Patterns.WEB_URL.matcher(clipText).matches()) {
input.setText(clipText)
input.setSelection(clipText.length)
}
MaterialDialog.Builder(activity)
.title(R.string.main_open_url)
.customView(inputView, false)
.positiveText(R.string.dialog_done)
.negativeText(R.string.dialog_cancel)
.autoDismiss(false)
.onPositive { dialog, dialogAction ->
var isValid: Boolean
val inputText: String = input.text.toString().trim().replace(" ", "")
if (Patterns.WEB_URL.matcher(inputText).matches()) {
isValid = true
input.error = ""
} else {
isValid = false
input.error = getString(R.string.main_open_url_error)
}
if (isValid) {
dialog.dismiss()
val intent = Intent(Intent.ACTION_SEND)
intent.setClass(activity, PaletteDetailActivity::class.java)
intent.putExtra(Intent.EXTRA_TEXT, inputText)
startActivity(intent)
}
}
.onNegative { dialog, dialogAction ->
dialog?.dismiss()
}
.show()
return true
}
"pref_key_dev" -> {
MaterialDialog.Builder(activity)
.title(R.string.main_about)
.content(Html.fromHtml(getString(R.string.about_body)))
.positiveText(R.string.dialog_done)
.show()
return true
}
"pref_key_licenses" -> {
val webView = WebView(activity)
webView.loadUrl("file:///android_asset/licenses.html")
MaterialDialog.Builder(activity)
.title(R.string.main_licenses)
.customView(webView, false)
.positiveText(R.string.dialog_done)
.show()
return true
}
"pref_key_source" -> {
val intent = Intent(Intent.ACTION_VIEW)
intent.setData(Uri.parse("https://github.com/hzsweers/palettehelper"))
startActivity(intent)
return true
}
}
return super.onPreferenceTreeClick(preferenceScreen, preference)
}
/**
* For images captured from the camera, we need to create a File first to tell the camera
* where to store the image.
*
* @return the File created for the image to be store under.
*/
fun createImageFile(): File {
Timber.d("Creating imageFile")
// Create an image file name
val timeStamp = SimpleDateFormat("yyyyMMdd_HHmmss").format(Date())
val imageFileName = "JPEG_" + timeStamp + "_"
val storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
val imageFile = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
)
// Save a file: path for use with ACTION_VIEW intents
imagePath = imageFile.absolutePath
return imageFile
}
/**
* This checks to see if there is a suitable activity to handle the `ACTION_PICK` intent
* and returns it if found. `ACTION_PICK` is for picking an image from an external app.
*
* @return A prepared intent if found.
*/
fun createPickIntent(): Intent? {
val picImageIntent = Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
picImageIntent.resolveActivity(activity.packageManager)?.let {
return picImageIntent
}
return null
}
/**
* This checks to see if there is a suitable activity to handle the `ACTION_IMAGE_CAPTURE`
* intent and returns it if found. `ACTION_IMAGE_CAPTURE` is for letting another app take
* a picture from the camera and store it in a file that we specify.
*
* @return A prepared intent if found.
*/
fun createCameraIntent(): Intent? {
val takePictureIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
takePictureIntent.resolveActivity(activity.packageManager)?.let {
return takePictureIntent
}
return null
}
fun dispatchPickIntent() {
if (checkPermission(Manifest.permission.READ_EXTERNAL_STORAGE)) {
val i = createPickIntent()
startActivityForResult(i, REQUEST_LOAD_IMAGE)
} else {
if (ActivityCompat.shouldShowRequestPermissionRationale(activity, Manifest.permission.READ_EXTERNAL_STORAGE)) {
MaterialDialog.Builder(activity)
.content(R.string.permission_request_settings_message)
.autoDismiss(true)
.positiveText(R.string.permission_request_settings)
.onPositive { dialog, dialogAction ->
goToSettings(REQUEST_READ_STORAGE_PERMISSION)
}
.show()
} else {
MaterialDialog.Builder(activity)
.title(R.string.permission_request)
.content(R.string.permission_request_read_storage)
.autoDismiss(true)
.cancelable(false)
.positiveText(R.string.permission_request_next)
.onPositive { dialog, dialogAction ->
requestPermissions(arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE),
REQUEST_READ_STORAGE_PERMISSION)
}
.show()
}
}
}
/**
* This utility function combines the camera intent creation and image file creation, and
* ultimately fires the intent.
*
* @see createCameraIntent()
* @see createImageFile()
*/
fun dispatchTakePictureIntent() {
if (checkPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
val takePictureIntent = createCameraIntent()
// Ensure that there's a camera activity to handle the intent
takePictureIntent?.let {
// Create the File where the photo should go
try {
val imageFile = createImageFile()
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(imageFile))
Timber.d("Dispatching intent to take a picture.")
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE)
} catch (ex: IOException) {
// Error occurred while creating the File
Timber.e(ex, "Error creating image file")
}
}
} else {
if (ActivityCompat.shouldShowRequestPermissionRationale(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
MaterialDialog.Builder(activity)
.content(R.string.permission_request_settings_message)
.autoDismiss(true)
.positiveText(R.string.permission_request_settings)
.onPositive { dialog, dialogAction ->
goToSettings(REQUEST_WRITE_STORAGE_PERMISSION)
}
.show()
} else {
MaterialDialog.Builder(activity)
.title(R.string.permission_request)
.content(R.string.permission_request_write_storage)
.autoDismiss(true)
.cancelable(false)
.positiveText(R.string.permission_request_next)
.onPositive { dialog, dialogAction ->
requestPermissions(arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE),
REQUEST_WRITE_STORAGE_PERMISSION)
}
.show()
}
}
}
private fun goToSettings(extraRequestCode: Int) {
val myAppSettings: Intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS,
Uri.fromParts("package", activity.packageName, null))
.apply {
addCategory(Intent.CATEGORY_DEFAULT)
setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
}
val options: Bundle = Bundle(1).apply { putInt(EXTRA_PERMISSION_ORIGIN, extraRequestCode) }
startActivityForResult(myAppSettings, REQUEST_APP_SETTINGS, options)
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>?, grantResults: IntArray?) {
if (requestCode == REQUEST_WRITE_STORAGE_PERMISSION) {
if (grantResults?.size == 1 && grantResults?.get(0) == PackageManager.PERMISSION_GRANTED) {
dispatchTakePictureIntent()
}
} else if (requestCode == REQUEST_READ_STORAGE_PERMISSION) {
if (grantResults?.size == 1 && grantResults?.get(0) == PackageManager.PERMISSION_GRANTED) {
dispatchPickIntent()
}
} else {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
Timber.d("Received activity result.")
if (resultCode == Activity.RESULT_OK) {
val intent = Intent(activity, PaletteDetailActivity::class.java)
if (requestCode == REQUEST_LOAD_IMAGE && data != null) {
Timber.d("Activity result - loading image from internal storage.")
val selectedImage = data.data
if (selectedImage != null) {
intent.putExtra(PaletteDetailActivity.KEY_URI, selectedImage.toString())
startActivity(intent)
} else {
Toast.makeText(activity, R.string.generic_error, Toast.LENGTH_SHORT).show()
}
} else if (requestCode == REQUEST_IMAGE_CAPTURE) {
Timber.d("Activity result - loading image from camera capture.")
intent.putExtra(PaletteDetailActivity.KEY_CAMERA, imagePath)
startActivity(intent)
} else if (requestCode == REQUEST_APP_SETTINGS) {
// Check permissions again
val originRequest = data?.getIntExtra(EXTRA_PERMISSION_ORIGIN, -1)
if (originRequest == REQUEST_READ_STORAGE_PERMISSION
&& checkPermission(Manifest.permission.READ_EXTERNAL_STORAGE)) {
dispatchPickIntent()
} else if (originRequest == REQUEST_WRITE_STORAGE_PERMISSION
&& checkPermission(Manifest.permission.READ_EXTERNAL_STORAGE)) {
dispatchTakePictureIntent()
}
}
}
}
fun checkPermission(permissionName: String): Boolean {
return ActivityCompat.checkSelfPermission(
activity, permissionName) == PackageManager.PERMISSION_GRANTED
}
}
}
| apache-2.0 | 51024dd02bec9f62978a0724e60d796d | 46.483607 | 130 | 0.540825 | 5.737537 | false | false | false | false |
VerifAPS/verifaps-lib | xml/src/main/kotlin/edu/kit/iti/formal/automation/plcopenxml/IECXMLFacade.kt | 1 | 1495 | package edu.kit.iti.formal.automation.plcopenxml
import edu.kit.iti.formal.util.CodeWriter
import java.io.*
import java.net.URL
import java.nio.file.Path
/**
* @author Alexander Weigl
* @version 1 (15.06.17)
* @version 2 (22.07.18)
*/
object IECXMLFacade {
fun extractPLCOpenXml(url: URL, sink: Writer) {
PCLOpenXMLBuilder(url, CodeWriter(sink)).run()
sink.flush()
}
fun extractPLCOpenXml(filename: String, sink: Writer) = extractPLCOpenXml(File(filename), sink)
fun extractPLCOpenXml(filename: File, sink: Writer) = extractPLCOpenXml(filename.toURI().toURL(), sink)
fun extractPLCOpenXml(filename: Path, sink: Writer) = extractPLCOpenXml(filename.toUri().toURL(), sink)
fun extractPLCOpenXml(filename: URL): String {
val writer = StringWriter()
extractPLCOpenXml(filename, writer)
return writer.toString()
}
fun extractPLCOpenXml(filename: String) = extractPLCOpenXml(File(filename))
fun extractPLCOpenXml(filename: File) = extractPLCOpenXml(filename.toURI().toURL())
fun extractPLCOpenXml(filename: Path) = extractPLCOpenXml(filename.toUri().toURL())
val SFC_KEYWORDS = setOf("step", "end_step", "transition", "end_transition")
fun quoteVariable(name: String): String =
if(name.toLowerCase() in SFC_KEYWORDS) "`$name`" else name
fun quoteStBody(body: String): String {
return body.replace("\\b\\w+\\b".toRegex()) {
quoteVariable(it.value)
}
}
}
| gpl-3.0 | 44346efa227949e97920b5821a243c30 | 33.767442 | 107 | 0.684281 | 3.484848 | false | false | false | false |
kozake/kotlin-koans | src/iv_properties/_32_Properties_.kt | 1 | 478 | package iv_properties
import util.TODO
import util.doc32
class PropertyExample() {
var counter = 0
var propertyWithCounter: Int? = todoTask32()
}
fun todoTask32(): Nothing = TODO(
"""
Task 32.
カスタムsetterをPropertyExample.propertyWithCounterへ追加してください。
'counter'がpropertyWithCounterへ代入する度にカウントされます。
""",
documentation = doc32(),
references = { PropertyExample() }
)
| mit | b073fcdaee758eb140b8dca271301d6a | 20.789474 | 64 | 0.683575 | 3.6 | false | false | false | false |
arcao/Geocaching4Locus | app/src/main/java/com/arcao/geocaching4locus/settings/fragment/FilterPreferenceFragment.kt | 1 | 8177 | package com.arcao.geocaching4locus.settings.fragment
import android.content.SharedPreferences
import androidx.preference.EditTextPreference
import androidx.preference.Preference
import com.arcao.geocaching4locus.R
import com.arcao.geocaching4locus.authentication.util.isPremium
import com.arcao.geocaching4locus.base.constants.AppConstants
import com.arcao.geocaching4locus.base.constants.PrefConstants.FILTER_CACHE_TYPE
import com.arcao.geocaching4locus.base.constants.PrefConstants.FILTER_CACHE_TYPE_PREFIX
import com.arcao.geocaching4locus.base.constants.PrefConstants.FILTER_CONTAINER_TYPE
import com.arcao.geocaching4locus.base.constants.PrefConstants.FILTER_CONTAINER_TYPE_PREFIX
import com.arcao.geocaching4locus.base.constants.PrefConstants.FILTER_DIFFICULTY
import com.arcao.geocaching4locus.base.constants.PrefConstants.FILTER_DIFFICULTY_MAX
import com.arcao.geocaching4locus.base.constants.PrefConstants.FILTER_DIFFICULTY_MIN
import com.arcao.geocaching4locus.base.constants.PrefConstants.FILTER_DISTANCE
import com.arcao.geocaching4locus.base.constants.PrefConstants.FILTER_TERRAIN
import com.arcao.geocaching4locus.base.constants.PrefConstants.FILTER_TERRAIN_MAX
import com.arcao.geocaching4locus.base.constants.PrefConstants.FILTER_TERRAIN_MIN
import com.arcao.geocaching4locus.base.constants.PrefConstants.IMPERIAL_UNITS
import com.arcao.geocaching4locus.base.constants.PrefConstants.SHORT_CACHE_TYPE_NAMES
import com.arcao.geocaching4locus.base.constants.PrefConstants.SHORT_CONTAINER_TYPE_NAMES
import com.arcao.geocaching4locus.base.constants.PrefConstants.UNIT_KM
import com.arcao.geocaching4locus.base.constants.PrefConstants.UNIT_MILES
import com.arcao.geocaching4locus.base.fragment.AbstractPreferenceFragment
import com.arcao.geocaching4locus.data.account.AccountManager
import org.koin.android.ext.android.get
class FilterPreferenceFragment : AbstractPreferenceFragment() {
private val premiumMember: Boolean by lazy {
get<AccountManager>().isPremium
}
private val imperialUnits: Boolean by lazy {
preferences.getBoolean(IMPERIAL_UNITS, false)
}
override val preferenceResource: Int
get() = R.xml.preference_category_filter
override fun preparePreference() {
super.preparePreference()
prepareCacheTypePreference()
prepareContainerTypePreference()
prepareDifficultyPreference()
prepareTerrainPreference()
prepareDistancePreference()
}
override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences, key: String) {
super.onSharedPreferenceChanged(sharedPreferences, key)
when (key) {
FILTER_DISTANCE -> {
preference<EditTextPreference>(key).apply {
summary = if (imperialUnits) {
preparePreferenceSummary(text + UNIT_MILES, R.string.pref_distance_summary_miles)
} else {
preparePreferenceSummary(text + UNIT_KM, R.string.pref_distance_summary_km)
}
}
}
}
}
private fun prepareCacheTypePreference() {
preference<Preference>(FILTER_CACHE_TYPE).apply {
isEnabled = premiumMember
summary = if (premiumMember) prepareCacheTypeSummary() else prepareCacheTypeSummaryBasicMember()
if (!premiumMember) {
applyPremiumTitleSign(this)
}
}
}
private fun prepareContainerTypePreference() {
preference<Preference>(FILTER_CONTAINER_TYPE).apply {
isEnabled = premiumMember
summary = if (premiumMember) prepareContainerTypeSummary() else prepareContainerTypeSummaryBasicMember()
if (!premiumMember) {
applyPremiumTitleSign(this)
}
}
}
private fun prepareDifficultyPreference() {
preference<Preference>(FILTER_DIFFICULTY).apply {
isEnabled = premiumMember
var difficultyMin = "1"
var difficultyMax = "5"
if (premiumMember) {
difficultyMin = preferences.getString(FILTER_DIFFICULTY_MIN, difficultyMin)!!
difficultyMax = preferences.getString(FILTER_DIFFICULTY_MAX, difficultyMax)!!
} else {
applyPremiumTitleSign(this)
}
summary = prepareRatingSummary(difficultyMin, difficultyMax)
}
}
private fun prepareTerrainPreference() {
preference<Preference>(FILTER_TERRAIN).apply {
isEnabled = premiumMember
var terrainMin = "1"
var terrainMax = "5"
if (premiumMember) {
terrainMin = preferences.getString(FILTER_TERRAIN_MIN, terrainMin)!!
terrainMax = preferences.getString(FILTER_TERRAIN_MAX, terrainMax)!!
} else {
applyPremiumTitleSign(this)
}
summary = prepareRatingSummary(terrainMin, terrainMax)
}
}
private fun prepareDistancePreference() {
preference<EditTextPreference>(FILTER_DISTANCE).apply {
// set summary text
summary = if (!imperialUnits) {
preparePreferenceSummary(text + UNIT_KM, R.string.pref_distance_summary_km)
} else {
setDialogMessage(R.string.pref_distance_summary_miles)
preparePreferenceSummary(text + UNIT_MILES, R.string.pref_distance_summary_miles)
}
}
}
private fun prepareRatingSummary(min: CharSequence, max: CharSequence): CharSequence {
return preparePreferenceSummary("$min - $max", 0)
}
private fun prepareCacheTypeSummary(): CharSequence {
val sb = StringBuilder()
var allChecked = true
var noneChecked = true
val len = AppConstants.GEOCACHE_TYPES.size
for (i in 0 until len) {
if (preferences.getBoolean(FILTER_CACHE_TYPE_PREFIX + i, true)) {
noneChecked = false
} else {
allChecked = false
}
}
if (allChecked || noneChecked) {
sb.append(getString(R.string.pref_geocache_type_all))
} else {
for (i in 0 until len) {
if (preferences.getBoolean(FILTER_CACHE_TYPE_PREFIX + i, true)) {
if (sb.isNotEmpty())
sb.append(TEXT_VALUE_SEPARATOR)
sb.append(SHORT_CACHE_TYPE_NAMES[i])
}
}
}
return preparePreferenceSummary(sb.toString(), 0)
}
private fun prepareCacheTypeSummaryBasicMember(): CharSequence {
return preparePreferenceSummary(
SHORT_CACHE_TYPE_NAMES[0] +
TEXT_VALUE_SEPARATOR +
SHORT_CACHE_TYPE_NAMES[8] +
TEXT_VALUE_SEPARATOR +
SHORT_CACHE_TYPE_NAMES[10],
0
)
}
private fun prepareContainerTypeSummary(): CharSequence {
val sb = StringBuilder()
val len = AppConstants.GEOCACHE_SIZES.size
for (i in 0 until len) {
if (preferences.getBoolean(FILTER_CONTAINER_TYPE_PREFIX + i, true)) {
if (sb.isNotEmpty())
sb.append(TEXT_VALUE_SEPARATOR)
sb.append(SHORT_CONTAINER_TYPE_NAMES[i])
}
}
if (sb.isEmpty()) {
for (i in 0 until len) {
if (sb.isNotEmpty())
sb.append(TEXT_VALUE_SEPARATOR)
sb.append(SHORT_CONTAINER_TYPE_NAMES[i])
}
}
return preparePreferenceSummary(sb.toString(), 0)
}
private fun prepareContainerTypeSummaryBasicMember(): CharSequence {
val sb = StringBuilder()
val len = AppConstants.GEOCACHE_SIZES.size
for (i in 0 until len) {
if (sb.isNotEmpty())
sb.append(TEXT_VALUE_SEPARATOR)
sb.append(SHORT_CONTAINER_TYPE_NAMES[i])
}
return preparePreferenceSummary(sb.toString(), 0)
}
companion object {
private const val TEXT_VALUE_SEPARATOR = ", "
}
}
| gpl-3.0 | 4631fb07c86198204d11db7c3579551d | 36.3379 | 116 | 0.645469 | 4.696726 | false | false | false | false |
android/user-interface-samples | CanonicalLayouts/supporting-panel-compose/app/src/main/java/com/example/supportingpanelcompose/ui/SupportingPanelSample.kt | 1 | 3590 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.supportingpanelcompose.ui
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.material3.windowsizeclass.WindowSizeClass
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.window.layout.DisplayFeature
// Create some simple sample data
private val data = mapOf(
"android" to listOf("kotlin", "java", "flutter"),
"kotlin" to listOf("backend", "android", "desktop"),
"desktop" to listOf("kotlin", "java", "flutter"),
"backend" to listOf("kotlin", "java"),
"java" to listOf("backend", "android", "desktop"),
"flutter" to listOf("android", "desktop")
)
@Composable
fun SupportingPanelSample(
windowSizeClass: WindowSizeClass,
displayFeatures: List<DisplayFeature>
) {
var selectedTopic: String by rememberSaveable { mutableStateOf(data.keys.first()) }
SupportingPanel(
main = {
Column(
horizontalAlignment = Alignment.CenterHorizontally,
modifier = Modifier.fillMaxSize()
) {
Text("Main Content", style = MaterialTheme.typography.titleLarge)
Text(selectedTopic)
}
},
supporting = {
Column(
modifier = Modifier.fillMaxSize()
) {
Text("Related Content", style = MaterialTheme.typography.titleLarge)
LazyColumn {
items(
data.getValue(selectedTopic),
key = { it }
) { relatedTopic ->
Box(
Modifier
.fillMaxWidth()
.clickable {
selectedTopic = relatedTopic
}
) {
Text(
text = relatedTopic,
modifier = Modifier
.padding(16.dp)
)
}
}
}
}
},
windowSizeClass = windowSizeClass,
displayFeatures = displayFeatures
)
}
| apache-2.0 | 854675cb4e93097ad02eb60783d0dc27 | 35.262626 | 87 | 0.61337 | 5.218023 | false | false | false | false |
iarchii/trade_app | app/src/main/java/xyz/thecodeside/tradeapp/productlist/ProductViewHolder.kt | 1 | 1309 | package xyz.thecodeside.tradeapp.productlist
import android.support.v7.widget.RecyclerView
import android.view.View
import com.jakewharton.rxbinding2.view.RxView
import kotlinx.android.synthetic.main.circle_item_view.view.*
import xyz.thecodeside.tradeapp.helpers.NumberFormatter
import xyz.thecodeside.tradeapp.helpers.calculateDiff
import xyz.thecodeside.tradeapp.helpers.invisible
import xyz.thecodeside.tradeapp.helpers.show
import xyz.thecodeside.tradeapp.model.MarketStatus
import xyz.thecodeside.tradeapp.model.Product
class ProductViewHolder(private val clickListener: ProductClickListener,
itemView: View) : RecyclerView.ViewHolder(itemView) {
lateinit var product : Product
fun bind(product : Product){
this.product = product
itemView.productNameTv.text = product.displayName
itemView.productPriceTv.text = NumberFormatter.format(product.currentPrice.amount, product.currentPrice.decimals)
val diff = product.calculateDiff()
itemView.productDiffTv.text = NumberFormatter.formatPercent(diff)
if(product.productMarketStatus == MarketStatus.OPEN) itemView.statusIv.invisible() else itemView.statusIv.show()
RxView.clicks(itemView).subscribe({
clickListener.onClick(product)
})
}
} | apache-2.0 | 74d9df173fda0251acbea2a7e7b3001a | 35.388889 | 121 | 0.766998 | 4.545139 | false | false | false | false |
web3j/quorum | src/integration-test/kotlin/org/web3j/quorum/core/Helper.kt | 1 | 5185 | /*
* Copyright 2019 Web3 Labs LTD.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package org.web3j.quorum.core
import org.hamcrest.CoreMatchers.`is`
import org.hamcrest.CoreMatchers.equalTo
import org.junit.Assert
import org.web3j.crypto.WalletUtils
import org.web3j.protocol.http.HttpService
import org.web3j.quorum.enclave.Enclave
import org.web3j.quorum.generated.Greeter
import org.web3j.quorum.generated.HumanStandardToken
import org.web3j.quorum.tx.QuorumTransactionManager
import org.web3j.tx.gas.DefaultGasProvider
import java.io.File
import java.math.BigInteger
/**
* Helper class that implements methods of the tests
* */
open class Helper {
@Throws(Exception::class)
fun testRawTransactionsWithGreeterContract(
sourceNode: Node,
destNode: Node,
keyFile: String,
enclave: Enclave
) {
val quorum = Quorum.build(HttpService(sourceNode.url))
val classLoader = javaClass.classLoader
val credentials = WalletUtils.loadCredentials("", File(classLoader.getResource(keyFile)!!.file))
val transactionManager = QuorumTransactionManager(
quorum,
credentials,
sourceNode.publicKeys[0],
destNode.publicKeys,
enclave)
val greeting = "Hello Quorum world!"
val contract = Greeter.deploy(
quorum,
transactionManager,
BigInteger.ZERO, DefaultGasProvider.GAS_LIMIT,
greeting).send()
Assert.assertThat<String>(contract.greet().send(), `is`<String>(greeting))
}
@Throws(Exception::class)
fun runPrivateHumanStandardTokenTest(
sourceNode: Node,
destNode: Node,
keyFile: String,
enclave: Enclave
) {
val quorum = Quorum.build(HttpService(sourceNode.url))
val classLoader = javaClass.classLoader
val credentials = WalletUtils.loadCredentials("", File(classLoader.getResource(keyFile)!!.file))
val transactionManager = QuorumTransactionManager(
quorum,
credentials,
sourceNode.publicKeys[0],
destNode.publicKeys,
enclave)
var aliceQty = BigInteger.valueOf(1000000)
val aliceAddress = sourceNode.address
val bobAddress = destNode.address
val contract = HumanStandardToken.deploy(quorum, transactionManager,
BigInteger.ZERO, DefaultGasProvider.GAS_LIMIT,
aliceQty, "web3j tokens",
BigInteger.valueOf(18), "w3j$").send()
Assert.assertTrue(contract.isValid)
Assert.assertThat(contract.totalSupply().send(), equalTo<BigInteger>(aliceQty))
Assert.assertThat(contract.balanceOf(sourceNode.address).send(),
equalTo<BigInteger>(aliceQty))
var transferQuantity = BigInteger.valueOf(100000)
val aliceTransferReceipt = contract.transfer(
destNode.address, transferQuantity).send()
val aliceTransferEventValues = contract.getTransferEvents(aliceTransferReceipt)[0]
Assert.assertThat(aliceTransferEventValues._from,
equalTo<String>(aliceAddress))
Assert.assertThat(aliceTransferEventValues._to,
equalTo<String>(bobAddress))
Assert.assertThat(aliceTransferEventValues._value,
equalTo<BigInteger>(transferQuantity))
aliceQty = aliceQty.subtract(transferQuantity)
var bobQty = BigInteger.ZERO
bobQty = bobQty.add(transferQuantity)
Assert.assertThat(contract.balanceOf(sourceNode.address).send(),
equalTo<BigInteger>(aliceQty))
Assert.assertThat(contract.balanceOf(destNode.address).send(),
equalTo<BigInteger>(bobQty))
Assert.assertThat(contract.allowance(
aliceAddress, bobAddress).send(),
equalTo<BigInteger>(BigInteger.ZERO))
transferQuantity = BigInteger.valueOf(50)
val approveReceipt = contract.approve(
destNode.address, transferQuantity).send()
val approvalEventValues = contract.getApprovalEvents(approveReceipt)[0]
Assert.assertThat(approvalEventValues._owner,
equalTo<String>(aliceAddress))
Assert.assertThat(approvalEventValues._spender,
equalTo<String>(bobAddress))
Assert.assertThat(approvalEventValues._value,
equalTo<BigInteger>(transferQuantity))
Assert.assertThat(contract.allowance(
aliceAddress, bobAddress).send(),
equalTo<BigInteger>(transferQuantity))
}
}
| apache-2.0 | e7b61b46f3956e0a099b7715b3e93127 | 34.758621 | 118 | 0.666924 | 4.679603 | false | false | false | false |
LorittaBot/Loritta | discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/cinnamon/discord/interactions/vanilla/economy/pay/PayExecutor.kt | 1 | 10353 | package net.perfectdreams.loritta.cinnamon.discord.interactions.vanilla.economy.pay
import dev.kord.common.DiscordTimestampStyle
import dev.kord.common.entity.ButtonStyle
import dev.kord.common.entity.Snowflake
import dev.kord.common.toMessageFormat
import dev.kord.core.entity.User
import kotlinx.datetime.Clock
import net.perfectdreams.discordinteraktions.common.builder.message.actionRow
import net.perfectdreams.loritta.cinnamon.emotes.Emotes
import net.perfectdreams.loritta.morenitta.LorittaBot
import net.perfectdreams.loritta.cinnamon.discord.interactions.commands.options.LocalizedApplicationCommandOptions
import net.perfectdreams.discordinteraktions.common.commands.options.SlashCommandArguments
import net.perfectdreams.loritta.cinnamon.discord.interactions.SlashContextHighLevelEditableMessage
import net.perfectdreams.loritta.cinnamon.discord.interactions.commands.*
import net.perfectdreams.loritta.cinnamon.discord.interactions.components.interactiveButton
import net.perfectdreams.loritta.cinnamon.discord.interactions.components.loriEmoji
import net.perfectdreams.loritta.cinnamon.discord.interactions.vanilla.economy.ShortenedToLongSonhosAutocompleteExecutor
import net.perfectdreams.loritta.cinnamon.discord.interactions.vanilla.economy.bet.coinflipfriend.AcceptCoinFlipBetFriendButtonExecutor
import net.perfectdreams.loritta.cinnamon.discord.interactions.vanilla.economy.declarations.SonhosCommand
import net.perfectdreams.loritta.cinnamon.discord.utils.SonhosUtils
import net.perfectdreams.loritta.cinnamon.discord.utils.SonhosUtils.appendUserHaventGotDailyTodayOrUpsellSonhosBundles
import net.perfectdreams.loritta.cinnamon.discord.utils.UserId
import net.perfectdreams.loritta.cinnamon.discord.utils.UserUtils
import net.perfectdreams.loritta.i18n.I18nKeysData
import kotlin.time.Duration
import kotlin.time.Duration.Companion.days
import kotlin.time.Duration.Companion.minutes
class PayExecutor(loritta: LorittaBot) : CinnamonSlashCommandExecutor(loritta) {
inner class Options : LocalizedApplicationCommandOptions(loritta) {
val user = user("user", SonhosCommand.PAY_I18N_PREFIX.Options.User.Text)
val quantity = string("quantity", SonhosCommand.PAY_I18N_PREFIX.Options.Quantity.Text) {
autocomplete(ShortenedToLongSonhosAutocompleteExecutor(loritta))
}
val ttlDuration = optionalString("expires_after", SonhosCommand.PAY_I18N_PREFIX.Options.ExpiresAfter.Text) {
choice(I18nKeysData.Time.Minutes(1), "1m")
choice(I18nKeysData.Time.Minutes(5), "5m")
choice(I18nKeysData.Time.Minutes(15), "15m")
choice(I18nKeysData.Time.Hours(1), "1h")
choice(I18nKeysData.Time.Hours(6), "6h")
choice(I18nKeysData.Time.Hours(12), "12h")
choice(I18nKeysData.Time.Hours(24), "24h")
choice(I18nKeysData.Time.Days(3), "3d")
choice(I18nKeysData.Time.Days(7), "7d")
}
}
override val options = Options()
override suspend fun execute(context: ApplicationCommandContext, args: SlashCommandArguments) {
val receiver = args[options.user]
val howMuch = args[options.quantity].toLongOrNull()
val ttlDuration = args[options.ttlDuration]?.let { Duration.parse(it) } ?: 15.minutes
val isLoritta = receiver.id == loritta.config.loritta.discord.applicationId
checkIfSelfAccountIsOldEnough(context)
checkIfOtherAccountIsOldEnough(context, receiver)
// checkIfSelfAccountGotDailyRecently(context)
// Too small
if (howMuch == null || howMuch == 0L)
context.failEphemerally(
context.i18nContext.get(SonhosCommand.PAY_I18N_PREFIX.TryingToTransferZeroSonhos),
Emotes.LoriHmpf
)
if (0L > howMuch)
context.failEphemerally(
context.i18nContext.get(SonhosCommand.PAY_I18N_PREFIX.TryingToTransferLessThanZeroSonhos),
Emotes.LoriHmpf
)
if (context.user.id == receiver.id)
context.failEphemerally(
context.i18nContext.get(SonhosCommand.PAY_I18N_PREFIX.CantTransferToSelf),
Emotes.Error
)
if (UserUtils.handleIfUserIsBanned(loritta, context, receiver))
return
// All prelimary checks have passed, let's defer!
context.deferChannelMessage() // Defer because this sometimes takes too long
val userProfile = loritta.pudding.users.getUserProfile(UserId(context.user.id))
if (userProfile == null || howMuch > userProfile.money) {
context.fail {
styled(
context.i18nContext.get(SonhosUtils.insufficientSonhos(userProfile, howMuch)),
Emotes.LoriSob
)
appendUserHaventGotDailyTodayOrUpsellSonhosBundles(
loritta,
context.i18nContext,
UserId(context.user.id),
"pay",
"transfer-not-enough-sonhos"
)
}
}
// TODO: Loritta is grateful easter egg
// Easter Eggs
val quirkyMessage = when {
howMuch >= 500_000 -> context.i18nContext.get(SonhosCommand.PAY_I18N_PREFIX.RandomQuirkyRichMessages).random()
// tellUserLorittaIsGrateful -> context.locale.getList("commands.command.pay.randomLorittaIsGratefulMessages").random()
else -> null
}
// We WANT to store on the database due to two things:
// 1. We want to control the interaction TTL
// 2. We want to block duplicate transactions by buttom spamming (with this, we can block this on transaction level)
val nowPlusTimeToLive = Clock.System.now() + ttlDuration
val (interactionDataId, data, encodedData) = context.loritta.encodeDataForComponentOnDatabase(
TransferSonhosData(
receiver.id,
context.user.id,
howMuch
),
ttl = ttlDuration
)
val message = context.sendMessage {
styled(
buildString {
append(context.i18nContext.get(SonhosCommand.PAY_I18N_PREFIX.YouAreGoingToTransfer(howMuch, mentionUser(receiver))))
if (quirkyMessage != null) {
append(" ")
append(quirkyMessage)
}
},
Emotes.LoriRich
)
styled(
context.i18nContext.get(SonhosCommand.PAY_I18N_PREFIX.ConfirmTheTransaction(mentionUser(receiver), nowPlusTimeToLive.toMessageFormat(DiscordTimestampStyle.LongDateTime), nowPlusTimeToLive.toMessageFormat(DiscordTimestampStyle.RelativeTime))),
Emotes.LoriZap
)
actionRow {
interactiveButton(
ButtonStyle.Primary,
context.i18nContext.get(SonhosCommand.PAY_I18N_PREFIX.AcceptTransfer),
TransferSonhosButtonExecutor,
encodedData
) {
loriEmoji = Emotes.Handshake
}
interactiveButton(
ButtonStyle.Danger,
context.i18nContext.get(SonhosCommand.PAY_I18N_PREFIX.Cancel),
CancelSonhosTransferButtonExecutor,
context.loritta.encodeDataForComponentOrStoreInDatabase(
CancelSonhosTransferData(
context.user.id,
interactionDataId
)
)
) {
loriEmoji = Emotes.LoriHmpf
}
}
}
if (isLoritta) {
// If it is Loritta, we will mimick that she is *actually* accepting the bet!
TransferSonhosButtonExecutor.acceptSonhos(
loritta,
context,
loritta.config.loritta.discord.applicationId,
SlashContextHighLevelEditableMessage(message),
data
)
}
}
private suspend fun checkIfSelfAccountGotDailyRecently(context: ApplicationCommandContext) {
val now = Clock.System.now()
// Check if the user got daily in the last 14 days before allowing a transaction
val gotDailyRewardInTheLastXDays = context.loritta.pudding.sonhos.getUserLastDailyRewardReceived(
UserId(context.user.id),
now - 14.days
) != null
if (!gotDailyRewardInTheLastXDays)
context.failEphemerally(
context.i18nContext.get(SonhosCommand.PAY_I18N_PREFIX.SelfAccountNeedsToGetDaily(loritta.commandMentions.daily)),
Emotes.LoriSob
)
}
private fun checkIfSelfAccountIsOldEnough(context: ApplicationCommandContext) {
val now = Clock.System.now()
val timestamp = context.user.id.timestamp
val allowedAfterTimestamp = timestamp + (14.days)
if (allowedAfterTimestamp > now) // 14 dias
context.failEphemerally(
context.i18nContext.get(SonhosCommand.PAY_I18N_PREFIX.SelfAccountIsTooNew(allowedAfterTimestamp.toMessageFormat(DiscordTimestampStyle.LongDateTime), allowedAfterTimestamp.toMessageFormat(DiscordTimestampStyle.RelativeTime))),
Emotes.LoriSob
)
}
private fun checkIfOtherAccountIsOldEnough(context: ApplicationCommandContext, target: User) {
val now = Clock.System.now()
val timestamp = target.id.timestamp
val allowedAfterTimestamp = timestamp + (7.days)
if (timestamp + (7.days) > now) // 7 dias
context.failEphemerally {
styled(
context.i18nContext.get(
SonhosCommand.PAY_I18N_PREFIX.OtherAccountIsTooNew(
mentionUser(target),
allowedAfterTimestamp.toMessageFormat(DiscordTimestampStyle.LongDateTime),
allowedAfterTimestamp.toMessageFormat(DiscordTimestampStyle.RelativeTime)
)
),
Emotes.LoriSob
)
}
}
} | agpl-3.0 | 12a655cf28a5569da8bf287397e79624 | 44.213974 | 258 | 0.646479 | 4.84691 | false | false | false | false |
jitsi/jitsi-videobridge | jvb/src/main/kotlin/org/jitsi/videobridge/relay/Relay.kt | 1 | 38067 | /*
* Copyright @ 2018 - present 8x8, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jitsi.videobridge.relay
import org.jitsi.nlj.Features
import org.jitsi.nlj.MediaSourceDesc
import org.jitsi.nlj.PacketHandler
import org.jitsi.nlj.PacketInfo
import org.jitsi.nlj.Transceiver
import org.jitsi.nlj.TransceiverEventHandler
import org.jitsi.nlj.VideoType
import org.jitsi.nlj.format.PayloadType
import org.jitsi.nlj.rtcp.RtcpEventNotifier
import org.jitsi.nlj.rtcp.RtcpListener
import org.jitsi.nlj.rtp.AudioRtpPacket
import org.jitsi.nlj.rtp.RtpExtension
import org.jitsi.nlj.rtp.RtpExtensionType
import org.jitsi.nlj.rtp.SsrcAssociationType
import org.jitsi.nlj.rtp.VideoRtpPacket
import org.jitsi.nlj.srtp.SrtpTransformers
import org.jitsi.nlj.srtp.SrtpUtil
import org.jitsi.nlj.srtp.TlsRole
import org.jitsi.nlj.stats.EndpointConnectionStats
import org.jitsi.nlj.transform.node.ConsumerNode
import org.jitsi.nlj.util.Bandwidth
import org.jitsi.nlj.util.BufferPool
import org.jitsi.nlj.util.LocalSsrcAssociation
import org.jitsi.nlj.util.PacketInfoQueue
import org.jitsi.nlj.util.RemoteSsrcAssociation
import org.jitsi.nlj.util.sumOf
import org.jitsi.rtp.Packet
import org.jitsi.rtp.UnparsedPacket
import org.jitsi.rtp.extensions.looksLikeRtcp
import org.jitsi.rtp.extensions.looksLikeRtp
import org.jitsi.rtp.rtcp.CompoundRtcpPacket
import org.jitsi.rtp.rtcp.RtcpByePacket
import org.jitsi.rtp.rtcp.RtcpHeader
import org.jitsi.rtp.rtcp.RtcpPacket
import org.jitsi.rtp.rtcp.RtcpRrPacket
import org.jitsi.rtp.rtcp.RtcpSdesPacket
import org.jitsi.rtp.rtcp.RtcpSrPacket
import org.jitsi.rtp.rtcp.rtcpfb.RtcpFbPacket
import org.jitsi.rtp.rtcp.rtcpfb.payload_specific_fb.RtcpFbFirPacket
import org.jitsi.rtp.rtcp.rtcpfb.payload_specific_fb.RtcpFbPliPacket
import org.jitsi.rtp.rtp.RtpHeader
import org.jitsi.rtp.rtp.RtpPacket
import org.jitsi.utils.MediaType
import org.jitsi.utils.event.EventEmitter
import org.jitsi.utils.event.SyncEventEmitter
import org.jitsi.utils.logging2.Logger
import org.jitsi.utils.logging2.cdebug
import org.jitsi.utils.logging2.createChildLogger
import org.jitsi.utils.queue.CountingErrorHandler
import org.jitsi.videobridge.AbstractEndpoint
import org.jitsi.videobridge.Conference
import org.jitsi.videobridge.EncodingsManager
import org.jitsi.videobridge.Endpoint
import org.jitsi.videobridge.PotentialPacketHandler
import org.jitsi.videobridge.TransportConfig
import org.jitsi.videobridge.message.BridgeChannelMessage
import org.jitsi.videobridge.message.SourceVideoTypeMessage
import org.jitsi.videobridge.rest.root.debug.EndpointDebugFeatures
import org.jitsi.videobridge.stats.PacketTransitStats
import org.jitsi.videobridge.transport.dtls.DtlsTransport
import org.jitsi.videobridge.transport.ice.IceTransport
import org.jitsi.videobridge.util.ByteBufferPool
import org.jitsi.videobridge.util.TaskPools
import org.jitsi.videobridge.util.looksLikeDtls
import org.jitsi.videobridge.websocket.colibriWebSocketServiceSupplier
import org.jitsi.xmpp.extensions.colibri.WebSocketPacketExtension
import org.jitsi.xmpp.extensions.jingle.DtlsFingerprintPacketExtension
import org.jitsi.xmpp.extensions.jingle.IceUdpTransportPacketExtension
import org.json.simple.JSONObject
import java.time.Clock
import java.time.Instant
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicLong
import java.util.function.Supplier
import kotlin.collections.sumOf
/**
* Models a relay (remote videobridge) in a [Conference].
*/
/* TODO: figure out how best to share code between this and [Endpoint], without multiple inheritance. */
class Relay @JvmOverloads constructor(
/**
* The unique identifier of this [Relay]
*/
val id: String,
/**
* The [Conference] this [Relay] belongs to.
*/
val conference: Conference,
parentLogger: Logger,
/**
* The ID of the mesh to which this [Relay] connection belongs.
* (Note that a bridge can be a member of more than one mesh, but each relay link will belong to only one.)
*/
val meshId: String?,
/**
* True if the ICE agent for this [Relay] will be initialized to serve as a controlling ICE agent, false otherwise.
*/
iceControlling: Boolean,
useUniquePort: Boolean,
clock: Clock = Clock.systemUTC()
) : EncodingsManager.EncodingsUpdateListener, PotentialPacketHandler {
private val eventEmitter: EventEmitter<AbstractEndpoint.EventHandler> = SyncEventEmitter()
/**
* The [Logger] used by the [Relay] class to print debug information.
*/
private val logger = createChildLogger(parentLogger).apply { addContext("relayId", id) }
/**
* A cache of the signaled payload types, since these are only signaled
* at the top level but apply to all relayed endpoints
*/
private val payloadTypes: MutableList<PayloadType> = ArrayList()
/**
* A cache of the signaled rtp extensions, since these are only signaled
* at the top level but apply to all relayed endpoints
*/
private val rtpExtensions: MutableList<RtpExtension> = ArrayList()
/**
* The indicator which determines whether [expire] has been called on this [Relay].
*/
private var expired = false
private val iceTransport = IceTransport(id, iceControlling, useUniquePort, logger, clock)
private val dtlsTransport = DtlsTransport(logger)
private val diagnosticContext = conference.newDiagnosticContext().apply {
put("relay_id", id)
}
private val timelineLogger = logger.createChildLogger("timeline.${this.javaClass.name}")
private val relayedEndpoints = HashMap<String, RelayedEndpoint>()
private val endpointsBySsrc = HashMap<Long, RelayedEndpoint>()
private val endpointsLock = Any()
private val senders = ConcurrentHashMap<String, RelayEndpointSender>()
val statistics = Statistics()
/**
* Listen for RTT updates from [transceiver] and update the ICE stats the first time an RTT is available. Note that
* the RTT is measured via RTCP, since we don't expose response time for STUN requests.
*/
private val rttListener: EndpointConnectionStats.EndpointConnectionStatsListener =
object : EndpointConnectionStats.EndpointConnectionStatsListener {
override fun onRttUpdate(newRttMs: Double) {
if (newRttMs > 0) {
transceiver.removeEndpointConnectionStatsListener(this)
iceTransport.updateStatsOnInitialRtt(newRttMs)
}
}
}
/* This transceiver is only for packets that are not handled by [RelayedEndpoint]s
* or [RelayEndpointSender]s */
val transceiver = Transceiver(
id,
TaskPools.CPU_POOL,
TaskPools.CPU_POOL,
TaskPools.SCHEDULED_POOL,
diagnosticContext,
logger,
TransceiverEventHandlerImpl(),
clock
).apply {
setIncomingPacketHandler(object : ConsumerNode("receiver chain handler") {
override fun consume(packetInfo: PacketInfo) {
[email protected](packetInfo)
}
override fun trace(f: () -> Unit) = f.invoke()
})
addEndpointConnectionStatsListener(rttListener)
setLocalSsrc(MediaType.AUDIO, conference.localAudioSsrc)
setLocalSsrc(MediaType.VIDEO, conference.localVideoSsrc)
rtcpEventNotifier.addRtcpEventListener(
object : RtcpListener {
override fun rtcpPacketReceived(packet: RtcpPacket, receivedTime: Instant?) {
[email protected](packet, receivedTime, null)
}
override fun rtcpPacketSent(packet: RtcpPacket) {
[email protected](packet, null)
}
},
external = true
)
}
/**
* The instance which manages the Colibri messaging (over web sockets).
*/
private val messageTransport = RelayMessageTransport(
this,
Supplier { conference.videobridge.statistics },
conference,
logger
)
init {
conference.encodingsManager.subscribe(this)
setupIceTransport()
setupDtlsTransport()
conference.videobridge.statistics.totalRelays.inc()
}
fun getMessageTransport(): RelayMessageTransport = messageTransport
/**
* The queue we put outgoing SRTP packets onto so they can be sent
* out via the [IceTransport] on an IO thread. This queue is only
* for packets that are not handled by [RelayEndpointSender]s.
*/
private val outgoingSrtpPacketQueue = PacketInfoQueue(
"${javaClass.simpleName}-outgoing-packet-queue",
TaskPools.IO_POOL,
this::doSendSrtp,
TransportConfig.queueSize
).apply {
setErrorHandler(queueErrorCounter)
}
val debugState: JSONObject
get() = JSONObject().apply {
put("iceTransport", iceTransport.getDebugState())
put("dtlsTransport", dtlsTransport.getDebugState())
put("transceiver", transceiver.getNodeStats().toJson())
put("messageTransport", messageTransport.debugState)
val remoteEndpoints = JSONObject()
val endpointsBySsrcMap = JSONObject()
synchronized(endpointsLock) {
for (r in relayedEndpoints.values) {
remoteEndpoints[r.id] = r.debugState
}
for ((s, e) in endpointsBySsrc) {
endpointsBySsrcMap[s] = e.id
}
}
put("remoteEndpoints", remoteEndpoints)
put("endpointsBySsrc", endpointsBySsrcMap)
val endpointSenders = JSONObject()
for (s in senders.values) {
endpointSenders[s.id] = s.getDebugState()
}
put("senders", endpointSenders)
}
private fun setupIceTransport() {
iceTransport.incomingDataHandler = object : IceTransport.IncomingDataHandler {
override fun dataReceived(data: ByteArray, offset: Int, length: Int, receivedTime: Instant) {
// DTLS data will be handled by the DtlsTransport, but SRTP data can go
// straight to the transceiver
if (looksLikeDtls(data, offset, length)) {
// DTLS transport is responsible for making its own copy, because it will manage its own
// buffers
dtlsTransport.dtlsDataReceived(data, offset, length)
} else {
val copy = ByteBufferPool.getBuffer(
length +
RtpPacket.BYTES_TO_LEAVE_AT_START_OF_PACKET +
Packet.BYTES_TO_LEAVE_AT_END_OF_PACKET
)
System.arraycopy(data, offset, copy, RtpPacket.BYTES_TO_LEAVE_AT_START_OF_PACKET, length)
val pktInfo =
RelayedPacketInfo(
UnparsedPacket(copy, RtpPacket.BYTES_TO_LEAVE_AT_START_OF_PACKET, length),
meshId
).apply {
this.receivedTime = receivedTime
}
handleMediaPacket(pktInfo)
}
}
}
iceTransport.eventHandler = object : IceTransport.EventHandler {
override fun connected() {
logger.info("ICE connected")
eventEmitter.fireEvent { iceSucceeded() }
transceiver.setOutgoingPacketHandler(object : PacketHandler {
override fun processPacket(packetInfo: PacketInfo) {
packetInfo.addEvent(SRTP_QUEUE_ENTRY_EVENT)
outgoingSrtpPacketQueue.add(packetInfo)
}
})
TaskPools.IO_POOL.execute(iceTransport::startReadingData)
TaskPools.IO_POOL.execute(dtlsTransport::startDtlsHandshake)
}
override fun failed() {
eventEmitter.fireEvent { iceFailed() }
}
override fun consentUpdated(time: Instant) {
transceiver.packetIOActivity.lastIceActivityInstant = time
}
}
}
private fun setupDtlsTransport() {
dtlsTransport.incomingDataHandler = object : DtlsTransport.IncomingDataHandler {
override fun dtlsAppDataReceived(buf: ByteArray, off: Int, len: Int) {
// TODO [email protected](buf, off, len)
}
}
dtlsTransport.outgoingDataHandler = object : DtlsTransport.OutgoingDataHandler {
override fun sendData(buf: ByteArray, off: Int, len: Int) {
iceTransport.send(buf, off, len)
}
}
dtlsTransport.eventHandler = object : DtlsTransport.EventHandler {
override fun handshakeComplete(
chosenSrtpProtectionProfile: Int,
tlsRole: TlsRole,
keyingMaterial: ByteArray
) {
logger.info("DTLS handshake complete")
setSrtpInformation(chosenSrtpProtectionProfile, tlsRole, keyingMaterial)
scheduleRelayMessageTransportTimeout()
}
}
}
private var srtpTransformers: SrtpTransformers? = null
private fun setSrtpInformation(chosenSrtpProtectionProfile: Int, tlsRole: TlsRole, keyingMaterial: ByteArray) {
val srtpProfileInfo =
SrtpUtil.getSrtpProfileInformationFromSrtpProtectionProfile(chosenSrtpProtectionProfile)
logger.cdebug {
"Transceiver $id creating transformers with:\n" +
"profile info:\n$srtpProfileInfo\n" +
"tls role: $tlsRole"
}
val srtpTransformers = SrtpUtil.initializeTransformer(
srtpProfileInfo,
keyingMaterial,
tlsRole,
logger
)
this.srtpTransformers = srtpTransformers
transceiver.setSrtpInformation(srtpTransformers)
synchronized(endpointsLock) {
relayedEndpoints.values.forEach { it.setSrtpInformation(srtpTransformers) }
}
senders.values.forEach { it.setSrtpInformation(srtpTransformers) }
}
/**
* Sets the remote transport information (ICE candidates, DTLS fingerprints).
*
* @param transportInfo the XML extension which contains the remote
* transport information.
*/
fun setTransportInfo(transportInfo: IceUdpTransportPacketExtension) {
val remoteFingerprints = mutableMapOf<String, String>()
val fingerprintExtensions = transportInfo.getChildExtensionsOfType(DtlsFingerprintPacketExtension::class.java)
fingerprintExtensions.forEach { fingerprintExtension ->
if (fingerprintExtension.hash != null && fingerprintExtension.fingerprint != null) {
remoteFingerprints[fingerprintExtension.hash] = fingerprintExtension.fingerprint
} else {
logger.info("Ignoring empty DtlsFingerprint extension: ${transportInfo.toXML()}")
}
}
dtlsTransport.setRemoteFingerprints(remoteFingerprints)
if (fingerprintExtensions.isNotEmpty()) {
val setup = fingerprintExtensions.first().setup
dtlsTransport.setSetupAttribute(setup)
}
iceTransport.startConnectivityEstablishment(transportInfo)
val websocketExtension = transportInfo.getFirstChildOfType(WebSocketPacketExtension::class.java)
websocketExtension?.url?.let { messageTransport.connectTo(it) }
}
fun describeTransport(): IceUdpTransportPacketExtension {
val iceUdpTransportPacketExtension = IceUdpTransportPacketExtension()
iceTransport.describe(iceUdpTransportPacketExtension)
dtlsTransport.describe(iceUdpTransportPacketExtension)
val wsPacketExtension = WebSocketPacketExtension()
/* TODO: this should be dependent on videobridge.websockets.enabled, if we support that being
* disabled for relay.
*/
if (messageTransport.isActive) {
wsPacketExtension.active = true
} else {
colibriWebSocketServiceSupplier.get()?.let { colibriWebsocketService ->
colibriWebsocketService.getColibriRelayWebSocketUrl(
conference.id,
id,
iceTransport.icePassword
)?.let { wsUrl ->
wsPacketExtension.url = wsUrl
}
}
}
iceUdpTransportPacketExtension.addChildExtension(wsPacketExtension)
logger.cdebug { "Transport description:\n${iceUdpTransportPacketExtension.toXML()}" }
return iceUdpTransportPacketExtension
}
fun setFeature(feature: EndpointDebugFeatures, enabled: Boolean) {
when (feature) {
EndpointDebugFeatures.PCAP_DUMP -> {
transceiver.setFeature(Features.TRANSCEIVER_PCAP_DUMP, enabled)
synchronized(endpointsLock) {
relayedEndpoints.values.forEach { e -> e.setFeature(Features.TRANSCEIVER_PCAP_DUMP, enabled) }
}
senders.values.forEach { s -> s.setFeature(Features.TRANSCEIVER_PCAP_DUMP, enabled) }
}
}
}
fun isFeatureEnabled(feature: EndpointDebugFeatures): Boolean {
return when (feature) {
EndpointDebugFeatures.PCAP_DUMP -> transceiver.isFeatureEnabled(Features.TRANSCEIVER_PCAP_DUMP)
}
}
/**
* Handle media packets that have arrived, using the appropriate endpoint's transceiver.
*/
private fun handleMediaPacket(packetInfo: RelayedPacketInfo) {
if (packetInfo.packet.looksLikeRtp()) {
val ssrc = RtpHeader.getSsrc(packetInfo.packet.buffer, packetInfo.packet.offset)
val ep = getEndpointBySsrc(ssrc)
if (ep != null) {
ep.handleIncomingPacket(packetInfo)
return
} else {
logger.warn { "RTP Packet received for unknown endpoint SSRC $ssrc" }
BufferPool.returnBuffer(packetInfo.packet.buffer)
}
} else if (packetInfo.packet.looksLikeRtcp()) {
val ssrc = RtcpHeader.getSenderSsrc(packetInfo.packet.buffer, packetInfo.packet.offset)
val ep = getEndpointBySsrc(ssrc)
if (ep != null) {
ep.handleIncomingPacket(packetInfo)
return
} else {
/* Handle RTCP from non-endpoint senders on the generic transceiver - it's probably
* from a feedback source.
*/
transceiver.handleIncomingPacket(packetInfo)
}
}
}
/**
* Handle incoming RTP packets which have been fully processed by the
* transceiver's incoming pipeline.
*/
fun handleIncomingPacket(packetInfo: PacketInfo) {
val packet = packetInfo.packet
if (packet is RtpPacket) {
val ep = synchronized(endpointsLock) { endpointsBySsrc[packet.ssrc] }
if (ep != null) {
packetInfo.endpointId = ep.id
}
}
// TODO do we need to set endpointId for RTCP packets? Otherwise handle them?
conference.handleIncomingPacket(packetInfo)
}
override fun onNewSsrcAssociation(
endpointId: String,
primarySsrc: Long,
secondarySsrc: Long,
type: SsrcAssociationType
) {
if (synchronized(endpointsLock) { relayedEndpoints.containsKey(endpointId) }) {
transceiver.addSsrcAssociation(LocalSsrcAssociation(primarySsrc, secondarySsrc, type))
} else {
transceiver.addSsrcAssociation(RemoteSsrcAssociation(primarySsrc, secondarySsrc, type))
}
}
fun doSendSrtp(packetInfo: PacketInfo): Boolean {
packetInfo.addEvent(SRTP_QUEUE_EXIT_EVENT)
PacketTransitStats.packetSent(packetInfo)
packetInfo.sent()
if (timelineLogger.isTraceEnabled && Endpoint.logTimeline()) {
timelineLogger.trace { packetInfo.timeline.toString() }
}
iceTransport.send(packetInfo.packet.buffer, packetInfo.packet.offset, packetInfo.packet.length)
ByteBufferPool.returnBuffer(packetInfo.packet.buffer)
return true
}
/**
* Sends a specific message to the remote side.
*/
fun sendMessage(msg: BridgeChannelMessage) = messageTransport.sendMessage(msg)
fun relayMessageTransportConnected() {
relayedEndpoints.values.forEach { e -> e.relayMessageTransportConnected() }
conference.endpoints.forEach { e ->
if (e is Endpoint || (e is RelayedEndpoint && e.relay.meshId != meshId)) {
e.mediaSources.forEach { msd: MediaSourceDesc ->
// Do not send the initial value for CAMERA, because it's the default
if (msd.videoType != VideoType.CAMERA) {
val videoTypeMsg = SourceVideoTypeMessage(
msd.videoType,
msd.sourceName,
e.id
)
sendMessage(videoTypeMsg)
}
}
}
}
}
fun addRemoteEndpoint(
id: String,
statsId: String?,
audioSources: Collection<AudioSourceDesc>,
videoSources: Collection<MediaSourceDesc>
) {
val ep: RelayedEndpoint
synchronized(endpointsLock) {
if (relayedEndpoints.containsKey(id)) {
logger.warn("Relay already contains remote endpoint with ID $id")
updateRemoteEndpoint(id, audioSources, videoSources)
return
}
ep = RelayedEndpoint(
conference,
this,
id,
logger,
conference.newDiagnosticContext().apply {
put("relay_id", [email protected])
put("endpoint_id", id)
}
)
ep.statsId = statsId
ep.audioSources = audioSources.toTypedArray()
ep.mediaSources = videoSources.toTypedArray()
relayedEndpoints[id] = ep
ep.ssrcs.forEach { ssrc -> endpointsBySsrc[ssrc] = ep }
}
conference.addEndpoints(setOf(ep))
srtpTransformers?.let { ep.setSrtpInformation(it) }
payloadTypes.forEach { payloadType -> ep.addPayloadType(payloadType) }
rtpExtensions.forEach { rtpExtension -> ep.addRtpExtension(rtpExtension) }
setEndpointMediaSources(ep, audioSources, videoSources)
ep.setFeature(Features.TRANSCEIVER_PCAP_DUMP, transceiver.isFeatureEnabled(Features.TRANSCEIVER_PCAP_DUMP))
}
fun updateRemoteEndpoint(
id: String,
audioSources: Collection<AudioSourceDesc>,
videoSources: Collection<MediaSourceDesc>
) {
val ep: RelayedEndpoint
synchronized(endpointsLock) {
ep = relayedEndpoints[id] ?: run {
logger.warn("Endpoint with ID $id not found in relay")
return
}
val oldSsrcs = ep.ssrcs
ep.audioSources = audioSources.toTypedArray()
ep.mediaSources = videoSources.toTypedArray()
val newSsrcs = ep.ssrcs
val removedSsrcs = oldSsrcs.minus(newSsrcs)
val addedSsrcs = newSsrcs.minus(oldSsrcs)
endpointsBySsrc.keys.removeAll(removedSsrcs)
addedSsrcs.forEach { ssrc -> endpointsBySsrc[ssrc] = ep }
}
setEndpointMediaSources(ep, audioSources, videoSources)
}
fun removeRemoteEndpoint(id: String) {
val ep: RelayedEndpoint?
synchronized(endpointsLock) {
ep = relayedEndpoints.remove(id)
if (ep != null) {
endpointsBySsrc.keys.removeAll(ep.ssrcs)
}
}
ep?.expire()
}
private fun getOrCreateRelaySender(endpointId: String): RelayEndpointSender {
synchronized(senders) {
senders[endpointId]?.let { return it }
val s = RelayEndpointSender(
this,
endpointId,
logger,
conference.newDiagnosticContext().apply {
put("relay_id", id)
put("endpoint_id", endpointId)
}
)
srtpTransformers?.let { s.setSrtpInformation(it) }
payloadTypes.forEach { payloadType -> s.addPayloadType(payloadType) }
rtpExtensions.forEach { rtpExtension -> s.addRtpExtension(rtpExtension) }
s.setFeature(Features.TRANSCEIVER_PCAP_DUMP, transceiver.isFeatureEnabled(Features.TRANSCEIVER_PCAP_DUMP))
senders[endpointId] = s
return s
}
}
fun addPayloadType(payloadType: PayloadType) {
transceiver.addPayloadType(payloadType)
payloadTypes.add(payloadType)
synchronized(endpointsLock) {
relayedEndpoints.values.forEach { ep -> ep.addPayloadType(payloadType) }
}
senders.values.forEach { s -> s.addPayloadType(payloadType) }
}
fun addRtpExtension(rtpExtension: RtpExtension) {
/* We don't want to do any BWE for relay-relay channels; also, the sender split confuses things. */
if (rtpExtension.type == RtpExtensionType.TRANSPORT_CC ||
rtpExtension.type == RtpExtensionType.ABS_SEND_TIME
) {
return
}
transceiver.addRtpExtension(rtpExtension)
rtpExtensions.add(rtpExtension)
synchronized(endpointsLock) {
relayedEndpoints.values.forEach { ep -> ep.addRtpExtension(rtpExtension) }
}
senders.values.forEach { s -> s.addRtpExtension(rtpExtension) }
}
private fun setEndpointMediaSources(
ep: RelayedEndpoint,
audioSources: Collection<AudioSourceDesc>,
videoSources: Collection<MediaSourceDesc>
) {
ep.audioSources = audioSources.toTypedArray()
ep.mediaSources = videoSources.toTypedArray()
}
fun getEndpoint(id: String): RelayedEndpoint? = synchronized(endpointsLock) { relayedEndpoints[id] }
fun getEndpointBySsrc(ssrc: Long): RelayedEndpoint? = synchronized(endpointsLock) { endpointsBySsrc[ssrc] }
/**
* Schedule a timeout to fire log a message and track a stat if we don't
* have a relay message transport connected within the timeout.
*/
fun scheduleRelayMessageTransportTimeout() {
TaskPools.SCHEDULED_POOL.schedule(
{
if (!expired) {
if (!messageTransport.isConnected) {
logger.error("RelayMessageTransport still not connected.")
conference.videobridge.statistics.numRelaysNoMessageTransportAfterDelay.inc()
}
}
},
30,
TimeUnit.SECONDS
)
}
/**
* Checks whether a WebSocket connection with a specific password string
* should be accepted for this relay.
* @param password the
* @return {@code true} iff the password matches.
*/
fun acceptWebSocket(password: String): Boolean {
if (iceTransport.icePassword != password) {
logger.warn(
"Incoming web socket request with an invalid password. " +
"Expected: ${iceTransport.icePassword} received $password"
)
return false
}
return true
}
/**
* Get a collection of all of the SSRCs mentioned in an RTCP packet.
*/
private fun getRtcpSsrcs(packet: RtcpPacket): Collection<Long> {
val ssrcs = HashSet<Long>()
ssrcs.add(packet.senderSsrc)
when (packet) {
is CompoundRtcpPacket -> packet.packets.forEach { ssrcs.addAll(getRtcpSsrcs(it)) }
is RtcpFbFirPacket -> ssrcs.add(packet.mediaSenderSsrc) // TODO: support multiple FIRs in a packet
is RtcpFbPacket -> ssrcs.add(packet.mediaSourceSsrc)
is RtcpSrPacket -> packet.reportBlocks.forEach { ssrcs.add(it.ssrc) }
is RtcpRrPacket -> packet.reportBlocks.forEach { ssrcs.add(it.ssrc) }
is RtcpSdesPacket -> packet.sdesChunks.forEach { ssrcs.add(it.ssrc) }
is RtcpByePacket -> ssrcs.addAll(packet.ssrcs)
}
return ssrcs
}
/**
* Call a callback on an [RtcpEventNotifier] once per [RelayedEndpoint] or [RelayEndpointSender] whose
* SSRC is mentioned in an RTCP packet, plus on the Relay's local [Transceiver].
* Do not call the event notifier which was the source of this packet, based on the [endpointId].
*/
private fun doRtcpCallbacks(packet: RtcpPacket, endpointId: String?, callback: (RtcpEventNotifier) -> Unit) {
val ssrcs = getRtcpSsrcs(packet)
val eps = HashSet<String>()
ssrcs.forEach { conference.getEndpointBySsrc(it)?.let { eps.add(it.id) } }
endpointId?.let { eps.remove(it) }
eps.forEach { epId ->
/* Any given ID should only be in one or the other of these sets. */
getEndpoint(epId)?.let { callback(it.rtcpEventNotifier) }
senders[epId]?.let { callback(it.rtcpEventNotifier) }
}
if (endpointId != null) {
callback(transceiver.rtcpEventNotifier)
}
}
fun rtcpPacketReceived(packet: RtcpPacket, receivedTime: Instant?, endpointId: String?) {
doRtcpCallbacks(packet, endpointId) { it.notifyRtcpReceived(packet, receivedTime, external = true) }
}
fun rtcpPacketSent(packet: RtcpPacket, endpointId: String?) {
doRtcpCallbacks(packet, endpointId) { it.notifyRtcpSent(packet, external = true) }
}
/**
* Returns true if this endpoint's transport is 'fully' connected (both ICE and DTLS), false otherwise
*/
private fun isTransportConnected(): Boolean = iceTransport.isConnected() && dtlsTransport.isConnected
/* If we're connected, forward everything that didn't come in over a relay or that came from a different
relay mesh.
TODO: worry about bandwidth limits on relay links? */
override fun wants(packet: PacketInfo): Boolean {
if (!isTransportConnected()) {
return false
}
if (packet is RelayedPacketInfo && packet.meshId == meshId) {
return false
}
return when (packet.packet) {
is VideoRtpPacket, is AudioRtpPacket, is RtcpSrPacket,
is RtcpFbPliPacket, is RtcpFbFirPacket -> {
// We assume that we are only given PLIs/FIRs destined for this
// endpoint. This is because Conference has to find the target
// endpoint (belonging to this relay) anyway, and we would essentially be
// performing the same check twice.
true
}
else -> {
logger.warn("Ignoring an unknown packet type:" + packet.packet.javaClass.simpleName)
false
}
}
}
override fun send(packet: PacketInfo) {
packet.endpointId?.let {
getOrCreateRelaySender(it).sendPacket(packet)
} ?: run {
transceiver.sendPacket(packet)
}
}
fun endpointExpired(id: String) {
val s = senders.remove(id)
s?.expire()
}
val incomingBitrateBps: Double
get() = transceiver.getTransceiverStats().rtpReceiverStats.packetStreamStats.getBitrateBps() +
synchronized(endpointsLock) {
relayedEndpoints.values.sumOf { it.getIncomingStats().getBitrateBps() }
}
val incomingPacketRate: Long
get() = transceiver.getTransceiverStats().rtpReceiverStats.packetStreamStats.packetRate +
synchronized(endpointsLock) {
relayedEndpoints.values.sumOf { it.getIncomingStats().packetRate }
}
val outgoingBitrateBps: Double
get() = transceiver.getTransceiverStats().outgoingPacketStreamStats.getBitrateBps() +
senders.values.sumOf { it.getOutgoingStats().getBitrateBps() }
val outgoingPacketRate: Long
get() = transceiver.getTransceiverStats().outgoingPacketStreamStats.packetRate +
senders.values.sumOf { it.getOutgoingStats().packetRate }
/**
* Updates the conference statistics with value from this endpoint. Since
* the values are cumulative this should execute only once when the endpoint
* expires.
*/
private fun updateStatsOnExpire() {
val conferenceStats = conference.statistics
val transceiverStats = transceiver.getTransceiverStats()
// Add stats from the local transceiver
val incomingStats = transceiverStats.rtpReceiverStats.packetStreamStats
val outgoingStats = transceiverStats.outgoingPacketStreamStats
statistics.bytesReceived.getAndAdd(incomingStats.bytes)
statistics.packetsReceived.getAndAdd(incomingStats.packets)
statistics.bytesSent.getAndAdd(outgoingStats.bytes)
statistics.packetsSent.getAndAdd(outgoingStats.packets)
conferenceStats.apply {
totalRelayBytesReceived.addAndGet(statistics.bytesReceived.get())
totalRelayPacketsReceived.addAndGet(statistics.packetsReceived.get())
totalRelayBytesSent.addAndGet(statistics.bytesSent.get())
totalRelayPacketsSent.addAndGet(statistics.packetsSent.get())
}
conference.videobridge.statistics.apply {
/* TODO: should these be separate stats from the endpoint stats? */
keyframesReceived.addAndGet(transceiverStats.rtpReceiverStats.videoParserStats.numKeyframes.toLong())
layeringChangesReceived.addAndGet(
transceiverStats.rtpReceiverStats.videoParserStats.numLayeringChanges.toLong()
)
val durationActiveVideo = transceiverStats.rtpReceiverStats.incomingStats.ssrcStats.values.filter {
it.mediaType == MediaType.VIDEO
}.sumOf { it.durationActive }
totalVideoStreamMillisecondsReceived.addAndGet(durationActiveVideo.toMillis())
}
}
fun expire() {
expired = true
logger.info("Expiring.")
synchronized(endpointsLock) {
relayedEndpoints.values.forEach { it.expire() }
}
senders.values.forEach { it.expire() }
conference.relayExpired(this)
try {
updateStatsOnExpire()
transceiver.stop()
srtpTransformers?.close()
logger.cdebug { transceiver.getNodeStats().prettyPrint(0) }
logger.cdebug { iceTransport.getDebugState().toJSONString() }
logger.cdebug { dtlsTransport.getDebugState().toJSONString() }
transceiver.teardown()
messageTransport.close()
} catch (t: Throwable) {
logger.error("Exception while expiring: ", t)
}
conference.encodingsManager.unsubscribe(this)
dtlsTransport.stop()
iceTransport.stop()
outgoingSrtpPacketQueue.close()
logger.info("Expired.")
}
companion object {
/**
* Count the number of dropped packets and exceptions.
*/
@JvmField
val queueErrorCounter = CountingErrorHandler()
private const val SRTP_QUEUE_ENTRY_EVENT = "Entered Relay SRTP sender outgoing queue"
private const val SRTP_QUEUE_EXIT_EVENT = "Exited Relay SRTP sender outgoing queue"
}
class Statistics {
val bytesReceived = AtomicLong(0)
val packetsReceived = AtomicLong(0)
val bytesSent = AtomicLong(0)
val packetsSent = AtomicLong(0)
private fun getJson(): JSONObject {
val jsonObject = JSONObject()
jsonObject["bytes_received"] = bytesReceived.get()
jsonObject["bytes_sent"] = bytesSent.get()
jsonObject["packets_received"] = packetsReceived.get()
jsonObject["packets_sent"] = packetsSent.get()
return jsonObject
}
}
private inner class TransceiverEventHandlerImpl : TransceiverEventHandler {
/**
* Forward audio level events from the Transceiver to the conference. We use the same thread, because this fires
* for every packet and we want to avoid the switch. The conference audio level code must not block.
*/
override fun audioLevelReceived(sourceSsrc: Long, level: Long): Boolean {
/* We shouldn't receive audio levels from the local transceiver, since all media should be
* processed by the media endpoints.
*/
logger.warn { "Audio level reported by relay transceiver for source $sourceSsrc" }
return false
}
/**
* Forward bwe events from the Transceiver.
*/
override fun bandwidthEstimationChanged(newValue: Bandwidth) {
logger.cdebug { "Estimated bandwidth is now $newValue" }
/* We don't use BWE for relay connections. */
}
}
interface IncomingRelayPacketHandler {
fun handleIncomingPacket(packetInfo: RelayedPacketInfo)
}
}
| apache-2.0 | 8fa112015afd6b9fce4b84c571e5230d | 38.735908 | 120 | 0.642525 | 4.670798 | false | false | false | false |
wireapp/wire-android | storage/src/androidTest/kotlin/com/waz/zclient/storage/userdatabase/users/UsersTableTestHelper.kt | 1 | 4427 | package com.waz.zclient.storage.userdatabase.users
import android.content.ContentValues
import com.waz.zclient.storage.DbSQLiteOpenHelper
class UsersTableTestHelper private constructor() {
companion object {
private const val USERS_TABLE_NAME = "Users"
private const val USERS_ID_COL = "_id"
private const val USERS_TEAM_ID_COL = "teamId"
private const val USERS_NAME_COL = "name"
private const val USERS_EMAIL_COL = "email"
private const val USERS_PHONE_COL = "phone"
private const val USERS_TRACKING_ID_COL = "tracking_id"
private const val USERS_PICTURE_COL = "picture"
private const val USERS_ACCENT_ID_COL = "accent"
private const val USERS_SKEY_COL = "skey"
private const val USERS_CONNECTION_COL = "connection"
private const val USERS_CONNECTION_TIMESTAMP_COL = "conn_timestamp"
private const val USERS_CONNECTION_MESSAGE_COL = "conn_msg"
private const val USERS_CONVERSATION_COL = "conversation"
private const val USERS_RELATION_COL = "relation"
private const val USERS_TIMESTAMP_COL = "timestamp"
private const val USERS_VERIFIED_COL = "verified"
private const val USERS_DELETED_COL = "deleted"
private const val USERS_AVAILABILITY_COL = "availability"
private const val USERS_HANDLE_COL = "handle"
private const val USERS_PROVIDER_ID_COL = "provider_id"
private const val USERS_INTEGRATION_ID_COL = "integration_id"
private const val USERS_EXPIRES_AT_COL = "expires_at"
private const val USERS_MANAGED_BY_COL = "managed_by"
private const val USERS_SELF_PERMISSIONS_COL = "self_permissions"
private const val USERS_COPY_PERMISSIONS_COL = "copy_permissions"
private const val USERS_CREATED_BY_COL = "created_by"
fun insertUser(
id: String,
teamId: String?,
name: String?,
email: String?,
phone: String?,
trackingId: String?,
picture: String?,
accentId: Int?,
sKey: String?,
connection: String?,
connectionTimestamp: Int?,
connectionMessage: String?,
conversation: String?,
relation: String?,
timestamp: Int?,
verified: String?,
deleted: Boolean?,
availability: Int?,
handle: String?,
providerId: String?,
integrationId: String?,
expiresAt: Int?,
managedBy: String?,
selfPermission: Int?,
copyPermission: Int?,
createdBy: String?,
openHelper: DbSQLiteOpenHelper
) {
val contentValues = ContentValues().also {
it.put(USERS_ID_COL, id)
it.put(USERS_TEAM_ID_COL, teamId)
it.put(USERS_NAME_COL, name)
it.put(USERS_EMAIL_COL, email)
it.put(USERS_PHONE_COL, phone)
it.put(USERS_TRACKING_ID_COL, trackingId)
it.put(USERS_PICTURE_COL, picture)
it.put(USERS_ACCENT_ID_COL, accentId)
it.put(USERS_SKEY_COL, sKey)
it.put(USERS_CONNECTION_COL, connection)
it.put(USERS_CONNECTION_TIMESTAMP_COL, connectionTimestamp)
it.put(USERS_CONNECTION_MESSAGE_COL, connectionMessage)
it.put(USERS_CONVERSATION_COL, conversation)
it.put(USERS_RELATION_COL, relation)
it.put(USERS_TIMESTAMP_COL, timestamp)
it.put(USERS_VERIFIED_COL, verified)
it.put(USERS_DELETED_COL, deleted)
it.put(USERS_AVAILABILITY_COL, availability)
it.put(USERS_HANDLE_COL, handle)
it.put(USERS_PROVIDER_ID_COL, providerId)
it.put(USERS_INTEGRATION_ID_COL, integrationId)
it.put(USERS_EXPIRES_AT_COL, expiresAt)
it.put(USERS_MANAGED_BY_COL, managedBy)
it.put(USERS_SELF_PERMISSIONS_COL, selfPermission)
it.put(USERS_COPY_PERMISSIONS_COL, copyPermission)
it.put(USERS_CREATED_BY_COL, createdBy)
}
openHelper.insertWithOnConflict(
tableName = USERS_TABLE_NAME,
contentValues = contentValues
)
}
}
}
| gpl-3.0 | c5603c81ea4f446dd05464eb5adb00b7 | 42.401961 | 75 | 0.58979 | 4.396226 | false | false | false | false |
vsch/idea-multimarkdown | src/main/java/com/vladsch/md/nav/flex/psi/FlexmarkFrontMatterBlockStubElementType.kt | 1 | 1498 | // Copyright (c) 2017-2020 Vladimir Schneider <[email protected]> Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.vladsch.md.nav.flex.psi
import com.intellij.psi.PsiElement
import com.intellij.psi.stubs.StubElement
import com.intellij.psi.tree.IElementType
import com.vladsch.md.nav.flex.psi.util.FlexTextMapElementTypeProvider
import com.vladsch.md.nav.psi.element.MdPlainTextStubElementType
import com.vladsch.md.nav.psi.util.MdTypes
import com.vladsch.md.nav.psi.util.TextMapElementType
import com.vladsch.md.nav.psi.util.TextMapMatch
class FlexmarkFrontMatterBlockStubElementType(debugName: String) : MdPlainTextStubElementType<FlexmarkFrontMatterBlock, FlexmarkFrontMatterBlockStub>(debugName) {
override fun createPsi(stub: FlexmarkFrontMatterBlockStub) = FlexmarkFrontMatterBlockImpl(stub, this)
override fun getExternalId(): String = "markdown.plain-text-referenceable.flexmark-front-matter"
override fun createStub(parentStub: StubElement<PsiElement>, textMapType: TextMapElementType, textMapMatches: Array<TextMapMatch>, referenceableOffsetInParent: Int): FlexmarkFrontMatterBlockStub = FlexmarkFrontMatterBlockStubImpl(parentStub, textMapType, textMapMatches, referenceableOffsetInParent)
override fun getReferenceableTextType(): IElementType = MdTypes.FLEXMARK_FRONT_MATTER_BLOCK
override fun getTextMapType(): TextMapElementType = FlexTextMapElementTypeProvider.FLEXMARK_FRONT_MATTER
}
| apache-2.0 | 90ab10fb0a5e522da6ca7ede80ab05f9 | 73.9 | 303 | 0.839119 | 4.267806 | false | false | false | false |
Devexperts/lin-check | lincheck/src/main/java/com/devexperts/dxlab/lincheck/verifier/quantitative/QuantitativeRelaxationVerifier.kt | 1 | 5436 | /*-
* #%L
* Lincheck
* %%
* Copyright (C) 2015 - 2018 Devexperts, LLC
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-3.0.html>.
* #L%
*/
package com.devexperts.dxlab.lincheck.verifier.quantitative
import com.devexperts.dxlab.lincheck.Actor
import com.devexperts.dxlab.lincheck.execution.ExecutionResult
import com.devexperts.dxlab.lincheck.execution.ExecutionScenario
import com.devexperts.dxlab.lincheck.verifier.AbstractLTSVerifier
import com.devexperts.dxlab.lincheck.verifier.LTSContext
import com.devexperts.dxlab.lincheck.verifier.get
/**
* This verifier checks for quantitative relaxation contracts, which are introduced
* in the "Quantitative relaxation of concurrent data structures" paper by Henzinger et al.
*
* Requires [QuantitativeRelaxationVerifierConf] annotation on the testing class.
*/
class QuantitativeRelaxationVerifier(scenario: ExecutionScenario, testClass: Class<*>) : AbstractLTSVerifier<ExtendedLTS.State>(scenario, testClass) {
private val relaxationFactor: Int
private val pathCostFunc: PathCostFunction
private val lts: ExtendedLTS
init {
val conf = testClass.getAnnotation(QuantitativeRelaxationVerifierConf::class.java)
requireNotNull(conf) { "No configuration for QuasiLinearizabilityVerifier found" }
relaxationFactor = conf.factor
pathCostFunc = conf.pathCostFunc
lts = ExtendedLTS(conf.costCounter.java, relaxationFactor)
}
override fun createInitialContext(results: ExecutionResult): LTSContext<ExtendedLTS.State> =
QuantitativeRelaxationContext(scenario, lts.initialState, results)
private inner class QuantitativeRelaxationContext(
scenario: ExecutionScenario,
state: ExtendedLTS.State,
executed: IntArray,
val results: ExecutionResult,
val iterativePathCostFunctionCounter: IterativePathCostFunctionCounter
) : LTSContext<ExtendedLTS.State>(scenario, state, executed) {
constructor(scenario: ExecutionScenario, state: ExtendedLTS.State, results: ExecutionResult) :
this(scenario, state, IntArray(scenario.threads + 2), results, pathCostFunc.createIterativePathCostFunctionCounter(relaxationFactor))
override fun nextContexts(threadId: Int): List<QuantitativeRelaxationContext> {
// Check if there are unprocessed actors in the specified thread
if (isCompleted(threadId)) return emptyList()
// Check whether an actor from the specified thread can be executed
// in accordance with the rule that all actors from init part should be
// executed at first, after that all actors from parallel part, and
// all actors from post part should be executed at last.
val legal = when (threadId) {
0 -> true // INIT: we already checked that there is an unprocessed actor
in 1..scenario.threads -> initCompleted // PARALLEL
else -> initCompleted && parallelCompleted // POST
}
if (!legal) return emptyList()
// Check whether the transition is possible in LTS.
val i = executed[threadId]
val actor = scenario[threadId][i]
val result = results[threadId][i]
if (actor.isRelaxed) {
// Get list of possible transitions with their penalty costs.
// Create a new context for each of them with an updated path cost function counters.
val costWithNextCostCounterList = state.nextRelaxed(actor, result)
return costWithNextCostCounterList.mapNotNull {
val nextPathCostFuncCounter = iterativePathCostFunctionCounter.next(it) ?: return@mapNotNull null
nextContext(threadId, lts.getStateForCostCounter(it.nextCostCounter), nextPathCostFuncCounter)
}
} else {
// Get next state similarly to `LinearizabilityVerifier` and
// create a new context with it and the same path cost function counter.
val nextState = state.nextRegular(actor, result) ?: return emptyList()
return listOf(nextContext(threadId, nextState, iterativePathCostFunctionCounter))
}
}
private fun nextContext(threadId: Int, nextState: ExtendedLTS.State, nextIterativePathCostFuncCounter: IterativePathCostFunctionCounter): QuantitativeRelaxationContext {
val nextExecuted = executed.copyOf()
nextExecuted[threadId]++
return QuantitativeRelaxationContext(scenario, nextState, nextExecuted, results, nextIterativePathCostFuncCounter)
}
private val Actor.isRelaxed get() = method.isAnnotationPresent(QuantitativeRelaxed::class.java)
}
} | lgpl-3.0 | 172f2fb4dd395452e69280935e263638 | 50.292453 | 177 | 0.703826 | 4.806366 | false | false | false | false |
Budincsevity/opensubtitles-api | src/test/kotlin/io/github/budincsevity/OpenSubtitlesAPI/util/TestDataProvider.kt | 1 | 9064 | package io.github.budincsevity.OpenSubtitlesAPI.util
import io.github.budincsevity.OpenSubtitlesAPI.model.SearchResult
import io.github.budincsevity.OpenSubtitlesAPI.model.SearchResultData
import io.github.budincsevity.OpenSubtitlesAPI.model.builder.OpenSubtitlesSearchParamsBuilder
import io.github.budincsevity.OpenSubtitlesAPI.model.builder.SearchResultDataBuilder
import io.github.budincsevity.OpenSubtitlesAPI.model.status.OpenSubtitlesStatus
import java.util.*
class TestDataProvider {
fun createTestSearchResult(): SearchResult {
val status = OpenSubtitlesStatus.OK.status
val data = createSearchResultData()
return SearchResult(status, arrayListOf(data))
}
fun createTestErrorSearchResult(): SearchResult {
val status = OpenSubtitlesStatus.UNKNOWN_ERROR.status
val data = createSearchResultData()
return SearchResult(status, arrayListOf(data))
}
private fun createSearchResultData(): SearchResultData {
return SearchResultDataBuilder()
.withSubActualCD("SubActualCD")
.withMovieName("MovieName")
.withSubBad("SubBad")
.withMovieHash("MovieHash")
.withSubFileName("SubFileName")
.withSubSumCD("SubSumCD")
.withZipDownloadLink("ZipDownloadLink")
.withMovieNameEng("MovieNameEng")
.withSubSize("SubSize")
.withIDSubtitleFile("IDSubtitleFile")
.withSubHash("SubHash")
.withSubFeatured("SubFeatured")
.withSubAuthorComment("SubAuthorComment")
.withSubDownloadsCnt("SubDownloadsCnt")
.withSubAddDate("SubAddDate")
.withSubLastTS("SubLastTS")
.withSubAutoTranslation("SubAutoTranslation")
.withMovieReleaseName("MovieReleaseName")
.withSeriesIMDBParent("SeriesIMDBParent")
.withScore("Score")
.withUserNickName("UserNickName")
.withSubHearingImpaired("SubHearingImpaired")
.withSubTSGroup("SubTSGroup")
.withQueryCached("QueryCached")
.withSubLanguageID("SubLanguageID")
.withSubFormat("SubFormat")
.withLanguageName("LanguageName")
.withSubTranslator("SubTranslator")
.withSeriesEpisode("SeriesEpisode")
.withUserRank("UserRank")
.withMovieImdbRating("MovieImdbRating")
.withMovieTimeMS("MovieTimeMS")
.withMovieYear("MovieYear")
.withSubEncoding("SubEncoding")
.withQueryNumber("QueryNumber")
.withSubHD("SubHD")
.withUserID("UserID")
.withMovieByteSize("MovieByteSize")
.withMovieFPS("MovieFPS")
.withSubtitlesLink("SubtitlesLink")
.withIDSubMovieFile("IDSubMovieFile")
.withISO639("ISO639")
.withSeriesSeason("SeriesSeason")
.withSubFromTrusted("SubFromTrusted")
.withSubTSGroupHash("SubTSGroupHash")
.withMatchedBy("MatchedBy")
.withSubDownloadLink("SubDownloadLink")
.withSubRating("SubRating")
.withQueryParameters("QueryParameters")
.withSubComments("SubComments")
.withMovieKind("MovieKind")
.withIDMovie("IDMovie")
.withIDMovieImdb("IDMovieImdb")
.withSubForeignPartsOnly("SubForeignPartsOnly")
.withIDSubtitle("IDSubtitle")
.build()
}
fun createSearchResultMap(): Map<*, *> {
val status = OpenSubtitlesStatus.OK.status
val data = arrayOf<Any>(hashMapOf(
"SubActualCD" to "SubActualCD",
"MovieName" to "MovieName",
"SubBad" to "SubBad",
"MovieHash" to "MovieHash",
"SubFileName" to "SubFileName",
"SubSumCD" to "SubSumCD",
"ZipDownloadLink" to "ZipDownloadLink",
"MovieNameEng" to "MovieNameEng",
"SubSize" to "SubSize",
"IDSubtitleFile" to "IDSubtitleFile",
"SubHash" to "SubHash",
"SubFeatured" to "SubFeatured",
"SubAuthorComment" to "SubAuthorComment",
"SubDownloadsCnt" to "SubDownloadsCnt",
"SubAddDate" to "SubAddDate",
"SubLastTS" to "SubLastTS",
"SubAutoTranslation" to "SubAutoTranslation",
"MovieReleaseName" to "MovieReleaseName",
"SeriesIMDBParent" to "SeriesIMDBParent",
"Score" to "Score",
"UserNickName" to "UserNickName",
"SubHearingImpaired" to "SubHearingImpaired",
"SubTSGroup" to "SubTSGroup",
"QueryCached" to "QueryCached",
"SubLanguageID" to "SubLanguageID",
"SubFormat" to "SubFormat",
"LanguageName" to "LanguageName",
"SubTranslator" to "SubTranslator",
"SeriesEpisode" to "SeriesEpisode",
"UserRank" to "UserRank",
"MovieImdbRating" to "MovieImdbRating",
"MovieTimeMS" to "MovieTimeMS",
"MovieYear" to "MovieYear",
"SubEncoding" to "SubEncoding",
"QueryNumber" to "QueryNumber",
"SubHD" to "SubHD",
"UserID" to "UserID",
"MovieByteSize" to "MovieByteSize",
"MovieFPS" to "MovieFPS",
"SubtitlesLink" to "SubtitlesLink",
"IDSubMovieFile" to "IDSubMovieFile",
"ISO639" to "ISO639",
"SeriesSeason" to "SeriesSeason",
"SubFromTrusted" to "SubFromTrusted",
"SubTSGroupHash" to "SubTSGroupHash",
"MatchedBy" to "MatchedBy",
"SubDownloadLink" to "SubDownloadLink",
"SubRating" to "SubRating",
"QueryParameters" to "QueryParameters",
"SubComments" to "SubComments",
"MovieKind" to "MovieKind",
"IDMovie" to "IDMovie",
"IDMovieImdb" to "IDMovieImdb",
"SubForeignPartsOnly" to "SubForeignPartsOnly",
"IDSubtitle" to "IDSubtitle"))
return hashMapOf("data" to data, "status" to status)
}
fun createErrorSearchResultMap(): Map<*, *> {
return hashMapOf("status" to OpenSubtitlesStatus.UNKNOWN_ERROR.status, "data" to arrayOf(hashMapOf<Any, Any>()))
}
fun createOpenSubtitlesSearchParamBuilderWithMovieHashMovieBytes(): OpenSubtitlesSearchParamsBuilder {
return OpenSubtitlesSearchParamsBuilder()
.withSubLanguageId(Optional.of("eng"))
.withMovieHash(Optional.of("HASH"))
.withMovieByteSize(Optional.of("12345"))
.withQuery(Optional.of("The.Big.Bang.Theory.S10E10.720p.HDTV.X264-DIMENSION[ettv]"))
}
fun createOpenSubtitlesSearchParamBuilderWithQuery(): OpenSubtitlesSearchParamsBuilder {
return OpenSubtitlesSearchParamsBuilder()
.withSubLanguageId(Optional.of("eng"))
.withMovieByteSize(Optional.empty())
.withMovieHash(Optional.empty())
.withTag(Optional.empty())
.withQuery(Optional.of("The.Big.Bang.Theory.S10E10.720p.HDTV.X264-DIMENSION[ettv]"))
}
fun createOpenSubtitlesSearchParamBuilderWithTag(): OpenSubtitlesSearchParamsBuilder {
return OpenSubtitlesSearchParamsBuilder()
.withSubLanguageId(Optional.of("eng"))
.withMovieByteSize(Optional.empty())
.withMovieHash(Optional.empty())
.withTag(Optional.of("Alien"))
.withQuery(Optional.of("The.Big.Bang.Theory.S10E10.720p.HDTV.X264-DIMENSION[ettv]"))
}
fun createOpenSubtitlesSearchParamBuilderWithImdbId(): OpenSubtitlesSearchParamsBuilder {
return OpenSubtitlesSearchParamsBuilder()
.withSubLanguageId(Optional.of("eng"))
.withMovieByteSize(Optional.empty())
.withMovieHash(Optional.empty())
.withTag(Optional.empty())
.withImdbId(Optional.of("555555"))
.withQuery(Optional.of("The.Big.Bang.Theory.S10E10.720p.HDTV.X264-DIMENSION[ettv]"))
}
fun createEmptyOpenSubtitlesSearchParamBuilder(): OpenSubtitlesSearchParamsBuilder {
return OpenSubtitlesSearchParamsBuilder()
.withSubLanguageId(Optional.of("eng"))
.withMovieByteSize(Optional.empty())
.withMovieHash(Optional.empty())
.withTag(Optional.empty())
.withImdbId(Optional.empty())
.withQuery(Optional.empty())
}
}
| mit | 11f9ea97d5340148e4f7153c4d5dc551 | 45.010152 | 120 | 0.588482 | 4.65776 | false | false | false | false |
square/moshi | moshi-kotlin-codegen/src/test/java/com/squareup/moshi/kotlin/codegen/ksp/JsonClassSymbolProcessorTest.kt | 1 | 26582 | /*
* Copyright (C) 2021 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
*
* 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.squareup.moshi.kotlin.codegen.ksp
import com.google.common.truth.Truth.assertThat
import com.squareup.moshi.kotlin.codegen.api.Options.OPTION_GENERATED
import com.squareup.moshi.kotlin.codegen.api.Options.OPTION_GENERATE_PROGUARD_RULES
import com.tschuchort.compiletesting.KotlinCompilation
import com.tschuchort.compiletesting.SourceFile
import com.tschuchort.compiletesting.SourceFile.Companion.java
import com.tschuchort.compiletesting.SourceFile.Companion.kotlin
import com.tschuchort.compiletesting.kspArgs
import com.tschuchort.compiletesting.kspIncremental
import com.tschuchort.compiletesting.kspSourcesDir
import com.tschuchort.compiletesting.symbolProcessorProviders
import org.junit.Ignore
import org.junit.Rule
import org.junit.Test
import org.junit.rules.TemporaryFolder
/** Execute kotlinc to confirm that either files are generated or errors are printed. */
class JsonClassSymbolProcessorTest {
@Rule @JvmField val temporaryFolder: TemporaryFolder = TemporaryFolder()
@Test
fun privateConstructor() {
val result = compile(
kotlin(
"source.kt",
"""
package test
import com.squareup.moshi.JsonClass
@JsonClass(generateAdapter = true)
class PrivateConstructor private constructor(var a: Int, var b: Int) {
fun a() = a
fun b() = b
companion object {
fun newInstance(a: Int, b: Int) = PrivateConstructor(a, b)
}
}
"""
)
)
assertThat(result.exitCode).isEqualTo(KotlinCompilation.ExitCode.COMPILATION_ERROR)
assertThat(result.messages).contains("constructor is not internal or public")
}
@Test
fun privateConstructorParameter() {
val result = compile(
kotlin(
"source.kt",
"""
package test
import com.squareup.moshi.JsonClass
@JsonClass(generateAdapter = true)
class PrivateConstructorParameter(private var a: Int)
"""
)
)
assertThat(result.exitCode).isEqualTo(KotlinCompilation.ExitCode.COMPILATION_ERROR)
assertThat(result.messages).contains("property a is not visible")
}
@Test
fun privateProperties() {
val result = compile(
kotlin(
"source.kt",
"""
package test
import com.squareup.moshi.JsonClass
@JsonClass(generateAdapter = true)
class PrivateProperties {
private var a: Int = -1
private var b: Int = -1
}
"""
)
)
assertThat(result.exitCode).isEqualTo(KotlinCompilation.ExitCode.COMPILATION_ERROR)
assertThat(result.messages).contains("property a is not visible")
}
@Test
fun interfacesNotSupported() {
val result = compile(
kotlin(
"source.kt",
"""
package test
import com.squareup.moshi.JsonClass
@JsonClass(generateAdapter = true)
interface Interface
"""
)
)
assertThat(result.exitCode).isEqualTo(KotlinCompilation.ExitCode.COMPILATION_ERROR)
assertThat(result.messages).contains(
"@JsonClass can't be applied to test.Interface: must be a Kotlin class"
)
}
@Test
fun interfacesDoNotErrorWhenGeneratorNotSet() {
val result = compile(
kotlin(
"source.kt",
"""
package test
import com.squareup.moshi.JsonClass
@JsonClass(generateAdapter = true, generator="customGenerator")
interface Interface
"""
)
)
assertThat(result.exitCode).isEqualTo(KotlinCompilation.ExitCode.OK)
}
@Test
fun abstractClassesNotSupported() {
val result = compile(
kotlin(
"source.kt",
"""
package test
import com.squareup.moshi.JsonClass
@JsonClass(generateAdapter = true)
abstract class AbstractClass(val a: Int)
"""
)
)
assertThat(result.exitCode).isEqualTo(KotlinCompilation.ExitCode.COMPILATION_ERROR)
assertThat(result.messages).contains(
"@JsonClass can't be applied to test.AbstractClass: must not be abstract"
)
}
@Test
fun sealedClassesNotSupported() {
val result = compile(
kotlin(
"source.kt",
"""
package test
import com.squareup.moshi.JsonClass
@JsonClass(generateAdapter = true)
sealed class SealedClass(val a: Int)
"""
)
)
assertThat(result.exitCode).isEqualTo(KotlinCompilation.ExitCode.COMPILATION_ERROR)
assertThat(result.messages).contains(
"@JsonClass can't be applied to test.SealedClass: must not be sealed"
)
}
@Test
fun innerClassesNotSupported() {
val result = compile(
kotlin(
"source.kt",
"""
package test
import com.squareup.moshi.JsonClass
class Outer {
@JsonClass(generateAdapter = true)
inner class InnerClass(val a: Int)
}
"""
)
)
assertThat(result.exitCode).isEqualTo(KotlinCompilation.ExitCode.COMPILATION_ERROR)
assertThat(result.messages).contains(
"@JsonClass can't be applied to test.Outer.InnerClass: must not be an inner class"
)
}
@Test
fun enumClassesNotSupported() {
val result = compile(
kotlin(
"source.kt",
"""
package test
import com.squareup.moshi.JsonClass
@JsonClass(generateAdapter = true)
enum class KotlinEnum {
A, B
}
"""
)
)
assertThat(result.exitCode).isEqualTo(KotlinCompilation.ExitCode.COMPILATION_ERROR)
assertThat(result.messages).contains(
"@JsonClass with 'generateAdapter = \"true\"' can't be applied to test.KotlinEnum: code gen for enums is not supported or necessary"
)
}
// Annotation processors don't get called for local classes, so we don't have the opportunity to
@Ignore
@Test
fun localClassesNotSupported() {
val result = compile(
kotlin(
"source.kt",
"""
package test
import com.squareup.moshi.JsonClass
fun outer() {
@JsonClass(generateAdapter = true)
class LocalClass(val a: Int)
}
"""
)
)
assertThat(result.exitCode).isEqualTo(KotlinCompilation.ExitCode.COMPILATION_ERROR)
assertThat(result.messages).contains(
"@JsonClass can't be applied to LocalClass: must not be local"
)
}
@Test
fun privateClassesNotSupported() {
val result = compile(
kotlin(
"source.kt",
"""
package test
import com.squareup.moshi.JsonClass
@JsonClass(generateAdapter = true)
private class PrivateClass(val a: Int)
"""
)
)
assertThat(result.exitCode).isEqualTo(KotlinCompilation.ExitCode.COMPILATION_ERROR)
assertThat(result.messages).contains(
"@JsonClass can't be applied to test.PrivateClass: must be internal or public"
)
}
@Test
fun objectDeclarationsNotSupported() {
val result = compile(
kotlin(
"source.kt",
"""
package test
import com.squareup.moshi.JsonClass
@JsonClass(generateAdapter = true)
object ObjectDeclaration {
var a = 5
}
"""
)
)
assertThat(result.exitCode).isEqualTo(KotlinCompilation.ExitCode.COMPILATION_ERROR)
assertThat(result.messages).contains(
"@JsonClass can't be applied to test.ObjectDeclaration: must be a Kotlin class"
)
}
@Test
fun objectExpressionsNotSupported() {
val result = compile(
kotlin(
"source.kt",
"""
package test
import com.squareup.moshi.JsonClass
@JsonClass(generateAdapter = true)
val expression = object : Any() {
var a = 5
}
"""
)
)
assertThat(result.exitCode).isEqualTo(KotlinCompilation.ExitCode.COMPILATION_ERROR)
assertThat(result.messages).contains(
"@JsonClass can't be applied to test.expression: must be a Kotlin class"
)
}
@Test
fun requiredTransientConstructorParameterFails() {
val result = compile(
kotlin(
"source.kt",
"""
package test
import com.squareup.moshi.JsonClass
@JsonClass(generateAdapter = true)
class RequiredTransientConstructorParameter(@Transient var a: Int)
"""
)
)
assertThat(result.exitCode).isEqualTo(KotlinCompilation.ExitCode.COMPILATION_ERROR)
assertThat(result.messages).contains(
"No default value for transient/ignored property a"
)
}
@Test
fun requiredIgnoredConstructorParameterFails() {
val result = compile(
kotlin(
"source.kt",
"""
package test
import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass
@JsonClass(generateAdapter = true)
class RequiredTransientConstructorParameter(@Json(ignore = true) var a: Int)
"""
)
)
assertThat(result.exitCode).isEqualTo(KotlinCompilation.ExitCode.COMPILATION_ERROR)
assertThat(result.messages).contains(
"No default value for transient/ignored property a"
)
}
@Test
fun nonPropertyConstructorParameter() {
val result = compile(
kotlin(
"source.kt",
"""
package test
import com.squareup.moshi.JsonClass
@JsonClass(generateAdapter = true)
class NonPropertyConstructorParameter(a: Int, val b: Int)
"""
)
)
assertThat(result.exitCode).isEqualTo(KotlinCompilation.ExitCode.COMPILATION_ERROR)
assertThat(result.messages).contains(
"No property for required constructor parameter a"
)
}
@Test
fun badGeneratedAnnotation() {
val result = prepareCompilation(
kotlin(
"source.kt",
"""
package test
import com.squareup.moshi.JsonClass
@JsonClass(generateAdapter = true)
data class Foo(val a: Int)
"""
)
).apply {
kspArgs[OPTION_GENERATED] = "javax.annotation.GeneratedBlerg"
}.compile()
assertThat(result.messages).contains(
"Invalid option value for $OPTION_GENERATED"
)
}
@Test
fun disableProguardGeneration() {
val compilation = prepareCompilation(
kotlin(
"source.kt",
"""
package test
import com.squareup.moshi.JsonClass
@JsonClass(generateAdapter = true)
data class Foo(val a: Int)
"""
)
).apply {
kspArgs[OPTION_GENERATE_PROGUARD_RULES] = "false"
}
val result = compilation.compile()
assertThat(result.exitCode).isEqualTo(KotlinCompilation.ExitCode.OK)
assertThat(compilation.kspSourcesDir.walkTopDown().filter { it.extension == "pro" }.toList()).isEmpty()
}
@Test
fun multipleErrors() {
val result = compile(
kotlin(
"source.kt",
"""
package test
import com.squareup.moshi.JsonClass
@JsonClass(generateAdapter = true)
class Class1(private var a: Int, private var b: Int)
@JsonClass(generateAdapter = true)
class Class2(private var c: Int)
"""
)
)
assertThat(result.exitCode).isEqualTo(KotlinCompilation.ExitCode.COMPILATION_ERROR)
assertThat(result.messages).contains("property a is not visible")
assertThat(result.messages).contains("property c is not visible")
}
@Test
fun extendPlatformType() {
val result = compile(
kotlin(
"source.kt",
"""
package test
import com.squareup.moshi.JsonClass
import java.util.Date
@JsonClass(generateAdapter = true)
class ExtendsPlatformClass(var a: Int) : Date()
"""
)
)
assertThat(result.messages).contains("supertype java.util.Date is not a Kotlin type")
}
@Test
fun extendJavaType() {
val result = compile(
kotlin(
"source.kt",
"""
package test
import com.squareup.moshi.JsonClass
import com.squareup.moshi.kotlin.codegen.JavaSuperclass
@JsonClass(generateAdapter = true)
class ExtendsJavaType(var b: Int) : JavaSuperclass()
"""
),
java(
"JavaSuperclass.java",
"""
package com.squareup.moshi.kotlin.codegen;
public class JavaSuperclass {
public int a = 1;
}
"""
)
)
assertThat(result.exitCode).isEqualTo(KotlinCompilation.ExitCode.COMPILATION_ERROR)
assertThat(result.messages)
.contains("supertype com.squareup.moshi.kotlin.codegen.JavaSuperclass is not a Kotlin type")
}
@Test
fun nonFieldApplicableQualifier() {
val result = compile(
kotlin(
"source.kt",
"""
package test
import com.squareup.moshi.JsonClass
import com.squareup.moshi.JsonQualifier
import kotlin.annotation.AnnotationRetention.RUNTIME
import kotlin.annotation.AnnotationTarget.PROPERTY
import kotlin.annotation.Retention
import kotlin.annotation.Target
@Retention(RUNTIME)
@Target(PROPERTY)
@JsonQualifier
annotation class UpperCase
@JsonClass(generateAdapter = true)
class ClassWithQualifier(@UpperCase val a: Int)
"""
)
)
// We instantiate directly, no FIELD site target necessary
assertThat(result.exitCode).isEqualTo(KotlinCompilation.ExitCode.OK)
}
@Test
fun nonRuntimeQualifier() {
val result = compile(
kotlin(
"source.kt",
"""
package test
import com.squareup.moshi.JsonClass
import com.squareup.moshi.JsonQualifier
import kotlin.annotation.AnnotationRetention.BINARY
import kotlin.annotation.AnnotationTarget.FIELD
import kotlin.annotation.AnnotationTarget.PROPERTY
import kotlin.annotation.Retention
import kotlin.annotation.Target
@Retention(BINARY)
@Target(PROPERTY, FIELD)
@JsonQualifier
annotation class UpperCase
@JsonClass(generateAdapter = true)
class ClassWithQualifier(@UpperCase val a: Int)
"""
)
)
assertThat(result.exitCode).isEqualTo(KotlinCompilation.ExitCode.COMPILATION_ERROR)
assertThat(result.messages).contains("JsonQualifier @UpperCase must have RUNTIME retention")
}
@Test
fun `TypeAliases with the same backing type should share the same adapter`() {
val result = compile(
kotlin(
"source.kt",
"""
package test
import com.squareup.moshi.JsonClass
typealias FirstName = String
typealias LastName = String
@JsonClass(generateAdapter = true)
data class Person(val firstName: FirstName, val lastName: LastName, val hairColor: String)
"""
)
)
assertThat(result.exitCode).isEqualTo(KotlinCompilation.ExitCode.OK)
// We're checking here that we only generate one `stringAdapter` that's used for both the
// regular string properties as well as the the aliased ones.
// TODO loading compiled classes from results not supported in KSP yet
// val adapterClass = result.classLoader.loadClass("PersonJsonAdapter").kotlin
// assertThat(adapterClass.declaredMemberProperties.map { it.returnType }).containsExactly(
// JsonReader.Options::class.createType(),
// JsonAdapter::class.parameterizedBy(String::class)
// )
}
@Test
fun `Processor should generate comprehensive proguard rules`() {
val compilation = prepareCompilation(
kotlin(
"source.kt",
"""
package testPackage
import com.squareup.moshi.JsonClass
import com.squareup.moshi.JsonQualifier
typealias FirstName = String
typealias LastName = String
@JsonClass(generateAdapter = true)
data class Aliases(val firstName: FirstName, val lastName: LastName, val hairColor: String)
@JsonClass(generateAdapter = true)
data class Simple(val firstName: String)
@JsonClass(generateAdapter = true)
data class Generic<T>(val firstName: T, val lastName: String)
@JsonQualifier
annotation class MyQualifier
@JsonClass(generateAdapter = true)
data class UsingQualifiers(val firstName: String, @MyQualifier val lastName: String)
@JsonClass(generateAdapter = true)
data class MixedTypes(val firstName: String, val otherNames: MutableList<String>)
@JsonClass(generateAdapter = true)
data class DefaultParams(val firstName: String = "")
@JsonClass(generateAdapter = true)
data class Complex<T>(val firstName: FirstName = "", @MyQualifier val names: MutableList<String>, val genericProp: T)
object NestedType {
@JsonQualifier
annotation class NestedQualifier
@JsonClass(generateAdapter = true)
data class NestedSimple(@NestedQualifier val firstName: String)
}
@JsonClass(generateAdapter = true)
class MultipleMasks(
val arg0: Long = 0,
val arg1: Long = 1,
val arg2: Long = 2,
val arg3: Long = 3,
val arg4: Long = 4,
val arg5: Long = 5,
val arg6: Long = 6,
val arg7: Long = 7,
val arg8: Long = 8,
val arg9: Long = 9,
val arg10: Long = 10,
val arg11: Long,
val arg12: Long = 12,
val arg13: Long = 13,
val arg14: Long = 14,
val arg15: Long = 15,
val arg16: Long = 16,
val arg17: Long = 17,
val arg18: Long = 18,
val arg19: Long = 19,
@Suppress("UNUSED_PARAMETER") arg20: Long = 20,
val arg21: Long = 21,
val arg22: Long = 22,
val arg23: Long = 23,
val arg24: Long = 24,
val arg25: Long = 25,
val arg26: Long = 26,
val arg27: Long = 27,
val arg28: Long = 28,
val arg29: Long = 29,
val arg30: Long = 30,
val arg31: Long = 31,
val arg32: Long = 32,
val arg33: Long = 33,
val arg34: Long = 34,
val arg35: Long = 35,
val arg36: Long = 36,
val arg37: Long = 37,
val arg38: Long = 38,
@Transient val arg39: Long = 39,
val arg40: Long = 40,
val arg41: Long = 41,
val arg42: Long = 42,
val arg43: Long = 43,
val arg44: Long = 44,
val arg45: Long = 45,
val arg46: Long = 46,
val arg47: Long = 47,
val arg48: Long = 48,
val arg49: Long = 49,
val arg50: Long = 50,
val arg51: Long = 51,
val arg52: Long = 52,
@Transient val arg53: Long = 53,
val arg54: Long = 54,
val arg55: Long = 55,
val arg56: Long = 56,
val arg57: Long = 57,
val arg58: Long = 58,
val arg59: Long = 59,
val arg60: Long = 60,
val arg61: Long = 61,
val arg62: Long = 62,
val arg63: Long = 63,
val arg64: Long = 64,
val arg65: Long = 65
)
"""
)
)
val result = compilation.compile()
assertThat(result.exitCode).isEqualTo(KotlinCompilation.ExitCode.OK)
compilation.kspSourcesDir.walkTopDown().filter { it.extension == "pro" }.forEach { generatedFile ->
when (generatedFile.nameWithoutExtension) {
"moshi-testPackage.Aliases" -> assertThat(generatedFile.readText()).contains(
"""
-if class testPackage.Aliases
-keepnames class testPackage.Aliases
-if class testPackage.Aliases
-keep class testPackage.AliasesJsonAdapter {
public <init>(com.squareup.moshi.Moshi);
}
""".trimIndent()
)
"moshi-testPackage.Simple" -> assertThat(generatedFile.readText()).contains(
"""
-if class testPackage.Simple
-keepnames class testPackage.Simple
-if class testPackage.Simple
-keep class testPackage.SimpleJsonAdapter {
public <init>(com.squareup.moshi.Moshi);
}
""".trimIndent()
)
"moshi-testPackage.Generic" -> assertThat(generatedFile.readText()).contains(
"""
-if class testPackage.Generic
-keepnames class testPackage.Generic
-if class testPackage.Generic
-keep class testPackage.GenericJsonAdapter {
public <init>(com.squareup.moshi.Moshi,java.lang.reflect.Type[]);
}
""".trimIndent()
)
"moshi-testPackage.UsingQualifiers" -> {
assertThat(generatedFile.readText()).contains(
"""
-if class testPackage.UsingQualifiers
-keepnames class testPackage.UsingQualifiers
-if class testPackage.UsingQualifiers
-keep class testPackage.UsingQualifiersJsonAdapter {
public <init>(com.squareup.moshi.Moshi);
}
""".trimIndent()
)
}
"moshi-testPackage.MixedTypes" -> assertThat(generatedFile.readText()).contains(
"""
-if class testPackage.MixedTypes
-keepnames class testPackage.MixedTypes
-if class testPackage.MixedTypes
-keep class testPackage.MixedTypesJsonAdapter {
public <init>(com.squareup.moshi.Moshi);
}
""".trimIndent()
)
"moshi-testPackage.DefaultParams" -> assertThat(generatedFile.readText()).contains(
"""
-if class testPackage.DefaultParams
-keepnames class testPackage.DefaultParams
-if class testPackage.DefaultParams
-keep class testPackage.DefaultParamsJsonAdapter {
public <init>(com.squareup.moshi.Moshi);
}
-if class testPackage.DefaultParams
-keepnames class kotlin.jvm.internal.DefaultConstructorMarker
-if class testPackage.DefaultParams
-keepclassmembers class testPackage.DefaultParams {
public synthetic <init>(java.lang.String,int,kotlin.jvm.internal.DefaultConstructorMarker);
}
""".trimIndent()
)
"moshi-testPackage.Complex" -> {
assertThat(generatedFile.readText()).contains(
"""
-if class testPackage.Complex
-keepnames class testPackage.Complex
-if class testPackage.Complex
-keep class testPackage.ComplexJsonAdapter {
public <init>(com.squareup.moshi.Moshi,java.lang.reflect.Type[]);
}
-if class testPackage.Complex
-keepnames class kotlin.jvm.internal.DefaultConstructorMarker
-if class testPackage.Complex
-keepclassmembers class testPackage.Complex {
public synthetic <init>(java.lang.String,java.util.List,java.lang.Object,int,kotlin.jvm.internal.DefaultConstructorMarker);
}
""".trimIndent()
)
}
"moshi-testPackage.MultipleMasks" -> assertThat(generatedFile.readText()).contains(
"""
-if class testPackage.MultipleMasks
-keepnames class testPackage.MultipleMasks
-if class testPackage.MultipleMasks
-keep class testPackage.MultipleMasksJsonAdapter {
public <init>(com.squareup.moshi.Moshi);
}
-if class testPackage.MultipleMasks
-keepnames class kotlin.jvm.internal.DefaultConstructorMarker
-if class testPackage.MultipleMasks
-keepclassmembers class testPackage.MultipleMasks {
public synthetic <init>(long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,int,int,int,kotlin.jvm.internal.DefaultConstructorMarker);
}
""".trimIndent()
)
"moshi-testPackage.NestedType.NestedSimple" -> {
assertThat(generatedFile.readText()).contains(
"""
-if class testPackage.NestedType${'$'}NestedSimple
-keepnames class testPackage.NestedType${'$'}NestedSimple
-if class testPackage.NestedType${'$'}NestedSimple
-keep class testPackage.NestedType_NestedSimpleJsonAdapter {
public <init>(com.squareup.moshi.Moshi);
}
""".trimIndent()
)
}
else -> error("Unexpected proguard file! ${generatedFile.name}")
}
}
}
private fun prepareCompilation(vararg sourceFiles: SourceFile): KotlinCompilation {
return KotlinCompilation()
.apply {
workingDir = temporaryFolder.root
inheritClassPath = true
symbolProcessorProviders = listOf(JsonClassSymbolProcessorProvider())
sources = sourceFiles.asList()
verbose = false
kspIncremental = true // The default now
}
}
private fun compile(vararg sourceFiles: SourceFile): KotlinCompilation.Result {
return prepareCompilation(*sourceFiles).compile()
}
}
| apache-2.0 | e932b03557ea658a7bbcc5b108fdc227 | 31.220606 | 426 | 0.609096 | 4.768072 | false | true | false | false |
RyotaMurohoshi/KotLinq | src/main/kotlin/com/muhron/kotlinq/toDictionary.kt | 1 | 1753 | package com.muhron.kotlinq
fun <TSource, TKey> Sequence<TSource>.toDictionary(keySelector: (TSource) -> TKey): Map<TKey, TSource> =
toDictionary(keySelector, { it -> it })
fun <TSource, TKey> Iterable<TSource>.toDictionary(keySelector: (TSource) -> TKey): Map<TKey, TSource> =
toDictionary(keySelector, { it -> it })
fun <TSource, TKey> Array<TSource>.toDictionary(keySelector: (TSource) -> TKey): Map<TKey, TSource> =
toDictionary(keySelector, { it -> it })
fun <TSourceK, TSourceV, TKey> Map<TSourceK, TSourceV>.toDictionary(keySelector: (Map.Entry<TSourceK, TSourceV>) -> TKey): Map<TKey, Map.Entry<TSourceK, TSourceV>> =
toDictionary(keySelector, { it -> it })
fun <TSource, TKey, TElement> Iterable<TSource>.toDictionary(keySelector: (TSource) -> TKey, elementSelector: (TSource) -> TElement): Map<TKey, TElement> =
asSequence().toDictionary(keySelector, elementSelector)
fun <TSource, TKey, TElement> Array<TSource>.toDictionary(keySelector: (TSource) -> TKey, elementSelector: (TSource) -> TElement): Map<TKey, TElement> =
asSequence().toDictionary(keySelector, elementSelector)
fun <TSourceK, TSourceV, TKey, TElement> Map<TSourceK, TSourceV>.toDictionary(keySelector: (Map.Entry<TSourceK, TSourceV>) -> TKey, elementSelector: (Map.Entry<TSourceK, TSourceV>) -> TElement): Map<TKey, TElement> =
asSequence().toDictionary(keySelector, elementSelector)
fun <TSource, TKey, TElement> Sequence<TSource>.toDictionary(keySelector: (TSource) -> TKey, elementSelector: (TSource) -> TElement): Map<TKey, TElement> {
val list = toList()
val result = list.associateBy(keySelector, elementSelector)
require(result.keys.size == list.size) { "duplicate key" }
return result
}
| mit | f6f11967ec27c75cce78df49fb6f73e6 | 53.78125 | 216 | 0.713634 | 3.957111 | false | false | false | false |
valich/intellij-markdown | src/commonMain/kotlin/org/intellij/markdown/parser/markerblocks/providers/BlockQuoteProvider.kt | 1 | 1706 | package org.intellij.markdown.parser.markerblocks.providers
import org.intellij.markdown.parser.LookaheadText
import org.intellij.markdown.parser.MarkerProcessor
import org.intellij.markdown.parser.ProductionHolder
import org.intellij.markdown.parser.constraints.MarkdownConstraints
import org.intellij.markdown.parser.constraints.getCharsEaten
import org.intellij.markdown.parser.markerblocks.MarkerBlock
import org.intellij.markdown.parser.markerblocks.MarkerBlockProvider
import org.intellij.markdown.parser.markerblocks.impl.BlockQuoteMarkerBlock
class BlockQuoteProvider : MarkerBlockProvider<MarkerProcessor.StateInfo> {
override fun createMarkerBlocks(pos: LookaheadText.Position,
productionHolder: ProductionHolder,
stateInfo: MarkerProcessor.StateInfo): List<MarkerBlock> {
// if (Character.isWhitespace(pos.char)) {
// return emptyList()
// }
val currentConstraints = stateInfo.currentConstraints
val nextConstraints = stateInfo.nextConstraints
if (pos.offsetInCurrentLine != currentConstraints.getCharsEaten(pos.currentLine)) {
return emptyList()
}
if (nextConstraints != currentConstraints && nextConstraints.types.lastOrNull() == '>') {
return listOf(BlockQuoteMarkerBlock(nextConstraints, productionHolder.mark()))
} else {
return emptyList()
}
}
override fun interruptsParagraph(pos: LookaheadText.Position, constraints: MarkdownConstraints): Boolean {
// Actually, blockquote may interrupt a paragraph, but we have MarkdownConstraints for these cases
return false
}
} | apache-2.0 | 7adb88bb4a7f4a911b82e9c20391b74d | 46.416667 | 110 | 0.728605 | 5.467949 | false | false | false | false |
septemberboy7/MDetect | mdetect/src/main/java/me/myatminsoe/mdetect/MMTextView.kt | 1 | 1516 | package me.myatminsoe.mdetect
import android.content.Context
import android.util.AttributeSet
import android.widget.TextView
import java.util.concurrent.Executor
class MMTextView : TextView {
constructor(context: Context) : super(context) {
setMMText(text.toString(), null)
}
constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {
setMMText(text.toString(), null)
}
constructor(context: Context, attrs: AttributeSet, defStyle: Int) : super(
context,
attrs,
defStyle
) {
setMMText(text.toString(), null)
}
/**
* Convert the text to proper encoding method and set the text of the TextView
*
* @param unicodeString string in Myanmar Unicode
* @param executor An Executor to do the converting process in the background
* By default will use a default {@link JobExecutor} Implementation
* Passing null will cause the conversion process to run in UI Thread, useful in cases where you
* need immediate result such as RecyclerView items
*/
fun setMMText(unicodeString: String, executor: Executor? = JobExecutor()) {
if (executor == null) {
text = MDetect.getText(unicodeString)
} else {
executor.execute {
val convertedString = MDetect.getText(unicodeString)
this.post {
text = convertedString
}
}
}
}
/**
* method for getting text
* @return CharSequence in Myanmar Unicode
*/
val mmText: CharSequence
get() = MDetect.getText(text.toString())
}
| mit | fe6af94509d242542b2f4fe9080cf59a | 26.563636 | 98 | 0.689974 | 4.199446 | false | false | false | false |
FarbodSalamat-Zadeh/TimetableApp | app/src/main/java/co/timetableapp/ui/base/ItemDetailActivity.kt | 1 | 6418 | /*
* Copyright 2017 Farbod Salamat-Zadeh
*
* 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 co.timetableapp.ui.base
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.support.annotation.LayoutRes
import android.support.v7.app.AppCompatActivity
import android.util.Log
import android.view.Menu
import android.view.MenuItem
import co.timetableapp.R
import co.timetableapp.data.handler.DataNotFoundException
import co.timetableapp.data.handler.TimetableItemHandler
import co.timetableapp.model.TimetableItem
import co.timetableapp.ui.base.ItemDetailActivity.Companion.EXTRA_ITEM
import co.timetableapp.util.UiUtils
/**
* An activity for showing the details of an item (e.g. assignment, class, exam, etc.).
*
* The details are displayed to the user but they cannot be edited here, and must instead be done in
* the corresponding 'edit' activity.
*
* This activity may be started to create a new item, passing no intent data so that [EXTRA_ITEM] is
* null.
*
* @param T the type of the item (e.g. assignment, class, exam)
*
* @see ItemEditActivity
* @see ItemListFragment
*/
abstract class ItemDetailActivity<T : TimetableItem> : AppCompatActivity() {
companion object {
private const val LOG_TAG = "ItemDetailActivity"
/**
* The key for the item of type [T] passed through an intent extra.
* It should be null if we're creating a new item.
*/
internal const val EXTRA_ITEM = "extra_item"
/**
* Request code to use when starting an activity to edit item [T] with a result.
*
* @see onMenuEditClick
*/
internal const val REQUEST_CODE_ITEM_EDIT = 1
}
/**
* The item whose details will be displayed in this activity's UI.
*/
@field:JvmSynthetic // prevent backing methods being visible in Java activities
protected lateinit var mItem: T
/**
* Whether or not we are creating a new item.
*/
@JvmField protected var mIsNew: Boolean = false
protected abstract fun initializeDataHandler(): TimetableItemHandler<T>
protected val mDataHandler: TimetableItemHandler<T> by lazy { initializeDataHandler() }
/**
* The layout resource for the activity layout.
*
* @see setContentView
*/
@LayoutRes
protected abstract fun getLayoutResource(): Int
/**
* When a subclass activity is started, by default, the following will occur when the activity
* gets created:
* - Sets the activity content using a layout resource
* - Initializes the data handler
* - Handles passed intent extras
* - Invokes a function to setup the UI
*
* @see getLayoutResource
* @see initializeDataHandler
* @see onNullExtras
* @see setupLayout
*/
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(getLayoutResource())
val extras = intent.extras
if (extras == null) {
// No item to display - assume we mean to create a new one
mIsNew = true
onNullExtras()
return
}
mItem = extras.getParcelable(EXTRA_ITEM)
setupLayout()
}
/**
* Callback for when intent extras are null.
* This would be invoked when there is no item to display, so we assume to create a new one.
*
* Implementations of this function should start the 'edit' activity passing no intent extras.
*
* @see onMenuEditClick
*/
protected abstract fun onNullExtras()
protected abstract fun setupLayout()
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == REQUEST_CODE_ITEM_EDIT) {
if (resultCode == Activity.RESULT_OK) {
// Get the edited item (if new, it would have the highest id)
val editedItemId = if (mIsNew) {
mDataHandler.getHighestItemId()
} else {
mItem.id
}
try {
mItem = mDataHandler.createFromId(editedItemId)
} catch (e: DataNotFoundException) {
Log.d(LOG_TAG, "Item cannot be found - assume it must have been deleted")
saveDeleteAndClose()
}
if (mIsNew) {
saveEditsAndClose()
} else {
setupLayout()
}
} else if (resultCode == Activity.RESULT_CANCELED) {
if (mIsNew) {
cancelAndClose()
}
}
}
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.menu_item_detail, menu)
UiUtils.tintMenuIcons(this, menu!!, R.id.action_edit)
return true
}
override fun onOptionsItemSelected(item: MenuItem?): Boolean {
when (item!!.itemId) {
R.id.action_edit -> onMenuEditClick()
}
return super.onOptionsItemSelected(item)
}
/**
* Callback for when the 'edit' menu item is clicked.
* Implementations of this function should start the 'edit' activity, sending [mItem] as an
* intent extra.
*
* @see onNullExtras
*/
protected abstract fun onMenuEditClick()
override fun onBackPressed() = saveEditsAndClose()
/**
* Exits this activity without saving changes.
*/
protected abstract fun cancelAndClose()
/**
* Exits this activity after saving changes.
*/
protected abstract fun saveEditsAndClose()
/**
* Exits this activity after saving the item deletion.
*/
protected abstract fun saveDeleteAndClose()
}
| apache-2.0 | 28d7a1118fcab1d46ffe4d47e92c081c | 30.15534 | 100 | 0.637114 | 4.701832 | false | false | false | false |
sksamuel/elasticsearch-river-neo4j | streamops-domain/src/main/kotlin/com/octaldata/domain/structure/primitives.kt | 1 | 814 | package com.octaldata.domain.structure
fun Any.toPrimitive(): Value = when (this) {
is Long -> this.value()
is Int -> this.value()
is Short -> this.value()
is Byte -> this.value()
is String -> this.value()
is Boolean -> this.value()
is Double -> this.value()
is Float -> this.value()
else -> error("Unsupported primitive type $this")
}
fun Long.value(): Value.Int64 = Value.Int64(this)
fun Int.value(): Value.Int64 = Value.Int64(this.toLong())
fun Short.value(): Value.Int64 = Value.Int64(this.toLong())
fun Byte.value(): Value.Int64 = Value.Int64(this.toLong())
fun String.value(): Value.Utf8 = Value.Utf8(this)
fun Boolean.value(): Value.Bool = Value.Bool(this)
fun Double.value(): Value.Float64 = Value.Float64(this)
fun Float.value(): Value.Float64 = Value.Float64(this.toDouble()) | apache-2.0 | 60ec10948476ee40aba4ee5c961aafc2 | 36.045455 | 65 | 0.681818 | 3.243028 | false | false | false | false |
ccomeaux/boardgamegeek4android | app/src/main/java/com/boardgamegeek/sorter/AverageRatingSorter.kt | 1 | 719 | package com.boardgamegeek.sorter
import android.content.Context
import androidx.annotation.StringRes
import com.boardgamegeek.R
import com.boardgamegeek.entities.CollectionItemEntity
import java.text.DecimalFormat
class AverageRatingSorter(context: Context) : RatingSorter(context) {
@StringRes
public override val typeResId = R.string.collection_sort_type_average_rating
@StringRes
override val descriptionResId = R.string.collection_sort_average_rating
override fun sort(items: Iterable<CollectionItemEntity>) = items.sortedByDescending { it.averageRating }
override val displayFormat = DecimalFormat("0.00")
override fun getRating(item: CollectionItemEntity) = item.averageRating
}
| gpl-3.0 | 4366ee7f4de781b0fd663eea345dc3b2 | 33.238095 | 108 | 0.801113 | 4.579618 | false | false | false | false |
sabi0/intellij-community | platform/testGuiFramework/src/com/intellij/testGuiFramework/testCases/PluginTestCase.kt | 1 | 4939 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.testGuiFramework.testCases
import com.intellij.testGuiFramework.fixtures.JDialogFixture
import com.intellij.testGuiFramework.framework.Timeouts
import com.intellij.testGuiFramework.impl.*
import com.intellij.testGuiFramework.impl.GuiTestUtilKt.waitProgressDialogUntilGone
import com.intellij.testGuiFramework.launcher.GuiTestOptions
import com.intellij.testGuiFramework.remote.transport.MessageType
import com.intellij.testGuiFramework.remote.transport.RestartIdeAndResumeContainer
import com.intellij.testGuiFramework.remote.transport.RestartIdeCause
import com.intellij.testGuiFramework.remote.transport.TransportMessage
import org.fest.swing.exception.WaitTimedOutError
import java.io.File
import javax.swing.JDialog
open class PluginTestCase : GuiTestCase() {
val getEnv: String by lazy {
File(System.getenv("WEBSTORM_PLUGINS") ?: throw IllegalArgumentException("WEBSTORM_PLUGINS env variable isn't specified")).absolutePath
}
fun findPlugin(pluginName: String): String {
val f = File(getEnv)
return f.listFiles { _, name ->
name.startsWith(pluginName)
}[0].toString()
}
fun installPluginAndRestart(installPluginsFunction: () -> Unit) {
if (guiTestRule.getTestName() == GuiTestOptions.getResumeTestName() &&
GuiTestOptions.getResumeInfo() == PLUGINS_INSTALLED) {
}
else {
//if plugins are not installed yet
installPluginsFunction()
//send restart message and resume this test to the server
GuiTestThread.client?.send(TransportMessage(MessageType.RESTART_IDE_AND_RESUME, RestartIdeAndResumeContainer(RestartIdeCause.PLUGIN_INSTALLED))) ?: throw Exception(
"Unable to get the client instance to send message.")
//wait until IDE is going to restart
GuiTestUtilKt.waitUntil("IDE will be closed", timeout = Timeouts.defaultTimeout) { false }
}
}
fun installPlugins(vararg pluginNames: String) {
welcomeFrame {
actionLink("Configure").click()
popupMenu("Plugins").clickSearchedItem()
dialog("Plugins") {
button("Install JetBrains plugin...").click()
dialog("Browse JetBrains Plugins ") browsePlugins@ {
pluginNames.forEach { [email protected](it) }
button("Close").click()
}
button("OK")
ensureButtonOkHasPressed(this@PluginTestCase)
}
message("IDE and Plugin Updates") {
button("Postpone").click()
}
}
}
fun installPluginFromDisk(pluginPath: String, pluginName: String) {
welcomeFrame {
actionLink("Configure").click()
popupMenu("Plugins").clickSearchedItem()
dialog("Plugins") {
//Check if plugin has already been installed
try {
table(pluginName, timeout = Timeouts.seconds05).cell(pluginName).click()
button("OK").click()
ensureButtonOkHasPressed(this@PluginTestCase)
}
catch (e: Exception) {
button("Install plugin from disk...").click()
chooseFileInFileChooser(pluginPath)
button("OK").click()
ensureButtonOkHasPressed(this@PluginTestCase)
}
}
try {
message("IDE and Plugin Updates", timeout = Timeouts.seconds05) {
button("Postpone").click()
}
}
catch (e: Exception) {
}
}
}
private fun ensureButtonOkHasPressed(guiTestCase: GuiTestCase) {
val dialogTitle = "Plugins"
try {
GuiTestUtilKt.waitUntilGone(robot = guiTestCase.robot(),
timeout = Timeouts.seconds05,
matcher = GuiTestUtilKt.typeMatcher(
JDialog::class.java) { it.isShowing && it.title == dialogTitle })
}
catch (timeoutError: WaitTimedOutError) {
with(guiTestCase) {
val dialog = JDialogFixture.find(guiTestCase.robot(), dialogTitle)
with(dialog) {
button("OK").clickWhenEnabled()
}
}
}
}
private fun JDialogFixture.installPlugin(pluginName: String) {
table(pluginName).cell(pluginName).click()
button("Install").click()
waitProgressDialogUntilGone(robot(), "Downloading Plugins")
println("$pluginName plugin has been installed")
}
companion object {
const val PLUGINS_INSTALLED = "PLUGINS_INSTALLED"
}
} | apache-2.0 | f0599b6826afe95aad4e791811f45f3d | 35.865672 | 170 | 0.685766 | 4.842157 | false | true | false | false |
SimonVT/cathode | cathode-sync/src/main/java/net/simonvt/cathode/sync/scheduler/ShowTaskScheduler.kt | 1 | 7558 | /*
* Copyright (C) 2013 Simon Vig Therkildsen
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.simonvt.cathode.sync.scheduler
import android.content.ContentValues
import android.content.Context
import androidx.work.WorkManager
import kotlinx.coroutines.launch
import net.simonvt.cathode.api.body.SyncItems
import net.simonvt.cathode.api.util.TimeUtils
import net.simonvt.cathode.common.database.getInt
import net.simonvt.cathode.common.database.getLong
import net.simonvt.cathode.jobqueue.JobManager
import net.simonvt.cathode.provider.DatabaseContract.EpisodeColumns
import net.simonvt.cathode.provider.DatabaseContract.ShowColumns
import net.simonvt.cathode.provider.ProviderSchematic.Episodes
import net.simonvt.cathode.provider.ProviderSchematic.Shows
import net.simonvt.cathode.provider.helper.ShowDatabaseHelper
import net.simonvt.cathode.provider.query
import net.simonvt.cathode.remote.action.shows.AddShowToHistory
import net.simonvt.cathode.remote.action.shows.CalendarHideShow
import net.simonvt.cathode.remote.action.shows.CollectedHideShow
import net.simonvt.cathode.remote.action.shows.DismissShowRecommendation
import net.simonvt.cathode.remote.action.shows.RateShow
import net.simonvt.cathode.remote.action.shows.WatchedHideShow
import net.simonvt.cathode.remote.action.shows.WatchlistShow
import net.simonvt.cathode.settings.TraktLinkSettings
import net.simonvt.cathode.work.enqueueNow
import net.simonvt.cathode.work.enqueueUniqueNow
import net.simonvt.cathode.work.shows.SyncPendingShowsWorker
import net.simonvt.cathode.work.user.SyncWatchedShowsWorker
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class ShowTaskScheduler @Inject constructor(
context: Context,
jobManager: JobManager,
private val workManager: WorkManager,
private val episodeScheduler: EpisodeTaskScheduler,
private val showHelper: ShowDatabaseHelper
) : BaseTaskScheduler(context, jobManager) {
fun collectedNext(showId: Long) {
scope.launch {
val c = context.contentResolver.query(
Episodes.fromShow(showId),
arrayOf(EpisodeColumns.ID, EpisodeColumns.SEASON, EpisodeColumns.EPISODE),
"inCollection=0 AND season<>0",
null,
EpisodeColumns.SEASON + " ASC, " + EpisodeColumns.EPISODE + " ASC LIMIT 1"
)!!
if (c.moveToNext()) {
val episodeId = c.getLong(EpisodeColumns.ID)
episodeScheduler.setIsInCollection(episodeId, true)
}
c.close()
}
}
fun addToHistoryNow(showId: Long) {
addToHistory(showId, System.currentTimeMillis())
}
fun addToHistoryOnRelease(showId: Long) {
addToHistory(showId, SyncItems.TIME_RELEASED)
}
fun addToHistory(showId: Long, watchedAt: Long) {
val isoWhen = TimeUtils.getIsoTime(watchedAt)
addToHistory(showId, isoWhen)
}
fun addToHistory(
showId: Long,
year: Int,
month: Int,
day: Int,
hour: Int,
minute: Int
) {
addToHistory(showId, TimeUtils.getMillis(year, month, day, hour, minute))
}
fun addToHistory(showId: Long, watchedAt: String) {
scope.launch {
if (SyncItems.TIME_RELEASED == watchedAt) {
showHelper.addToHistory(showId, ShowDatabaseHelper.WATCHED_RELEASE)
} else {
showHelper.addToHistory(showId, TimeUtils.getMillis(watchedAt))
}
if (TraktLinkSettings.isLinked(context)) {
val traktId = showHelper.getTraktId(showId)
queue(AddShowToHistory(traktId, watchedAt))
// No documentation on how exactly the trakt endpoint is implemented, so sync after.
workManager.enqueueNow(SyncWatchedShowsWorker::class.java)
}
}
}
fun setIsInWatchlist(showId: Long, inWatchlist: Boolean) {
scope.launch {
val c = context.contentResolver.query(
Shows.withId(showId),
arrayOf(ShowColumns.TRAKT_ID, ShowColumns.EPISODE_COUNT)
)
if (c.moveToFirst()) {
var listedAt: String? = null
var listedAtMillis = 0L
if (inWatchlist) {
listedAt = TimeUtils.getIsoTime()
listedAtMillis = TimeUtils.getMillis(listedAt)
}
val traktId = c.getLong(ShowColumns.TRAKT_ID)
showHelper.setIsInWatchlist(showId, inWatchlist, listedAtMillis)
val episodeCount = c.getInt(ShowColumns.EPISODE_COUNT)
if (episodeCount == 0) {
workManager.enqueueUniqueNow(
SyncPendingShowsWorker.TAG,
SyncPendingShowsWorker::class.java
)
}
if (TraktLinkSettings.isLinked(context)) {
queue(WatchlistShow(traktId, inWatchlist, listedAt))
}
}
c.close()
}
}
fun dismissRecommendation(showId: Long) {
scope.launch {
val traktId = showHelper.getTraktId(showId)
val values = ContentValues()
values.put(ShowColumns.RECOMMENDATION_INDEX, -1)
context.contentResolver.update(Shows.withId(showId), values, null, null)
queue(DismissShowRecommendation(traktId))
}
}
/**
* Rate a show on trakt. Depending on the user settings, this will also send out social updates
* to facebook,
* twitter, and tumblr.
*
* @param showId The database id of the show.
* @param rating A rating betweeo 1 and 10. Use 0 to undo rating.
*/
fun rate(showId: Long, rating: Int) {
scope.launch {
val ratedAt = TimeUtils.getIsoTime()
val ratedAtMillis = TimeUtils.getMillis(ratedAt)
val values = ContentValues()
values.put(ShowColumns.USER_RATING, rating)
values.put(ShowColumns.RATED_AT, ratedAtMillis)
context.contentResolver.update(Shows.withId(showId), values, null, null)
if (TraktLinkSettings.isLinked(context)) {
val traktId = showHelper.getTraktId(showId)
queue(RateShow(traktId, rating, ratedAt))
}
}
}
fun hideFromCalendar(showId: Long, hidden: Boolean) {
scope.launch {
val values = ContentValues()
values.put(ShowColumns.HIDDEN_CALENDAR, hidden)
context.contentResolver.update(Shows.withId(showId), values, null, null)
if (TraktLinkSettings.isLinked(context)) {
val traktId = showHelper.getTraktId(showId)
queue(CalendarHideShow(traktId, hidden))
}
}
}
fun hideFromWatched(showId: Long, hidden: Boolean) {
scope.launch {
val values = ContentValues()
values.put(ShowColumns.HIDDEN_WATCHED, hidden)
context.contentResolver.update(Shows.withId(showId), values, null, null)
if (TraktLinkSettings.isLinked(context)) {
val traktId = showHelper.getTraktId(showId)
queue(WatchedHideShow(traktId, hidden))
}
}
}
fun hideFromCollected(showId: Long, hidden: Boolean) {
scope.launch {
val values = ContentValues()
values.put(ShowColumns.HIDDEN_COLLECTED, hidden)
context.contentResolver.update(Shows.withId(showId), values, null, null)
if (TraktLinkSettings.isLinked(context)) {
val traktId = showHelper.getTraktId(showId)
queue(CollectedHideShow(traktId, hidden))
}
}
}
}
| apache-2.0 | 9b239ae1313e6360cf9f54eced7fb7ed | 32.295154 | 97 | 0.713019 | 4.208241 | false | false | false | false |
SimonVT/cathode | cathode/src/main/java/net/simonvt/cathode/ui/show/SeasonViewModel.kt | 1 | 2697 | /*
* Copyright (C) 2018 Simon Vig Therkildsen
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.simonvt.cathode.ui.show
import android.content.Context
import androidx.lifecycle.LiveData
import net.simonvt.cathode.actions.invokeSync
import net.simonvt.cathode.actions.seasons.SyncSeason
import net.simonvt.cathode.common.data.MappedCursorLiveData
import net.simonvt.cathode.entity.Episode
import net.simonvt.cathode.entity.Season
import net.simonvt.cathode.entitymapper.EpisodeListMapper
import net.simonvt.cathode.entitymapper.EpisodeMapper
import net.simonvt.cathode.entitymapper.SeasonMapper
import net.simonvt.cathode.provider.DatabaseContract.EpisodeColumns
import net.simonvt.cathode.provider.ProviderSchematic.Episodes
import net.simonvt.cathode.provider.ProviderSchematic.Seasons
import net.simonvt.cathode.provider.helper.SeasonDatabaseHelper
import net.simonvt.cathode.provider.helper.ShowDatabaseHelper
import net.simonvt.cathode.ui.RefreshableViewModel
import javax.inject.Inject
class SeasonViewModel @Inject constructor(
private val context: Context,
private val showHelper: ShowDatabaseHelper,
private val seasonHelper: SeasonDatabaseHelper,
private val syncSeason: SyncSeason
) : RefreshableViewModel() {
private var seasonId = -1L
lateinit var season: LiveData<Season>
private set
lateinit var episodes: LiveData<List<Episode>>
private set
fun setSeasonId(seasonId: Long) {
if (this.seasonId == -1L) {
this.seasonId = seasonId
season = MappedCursorLiveData(
context,
Seasons.withId(seasonId),
SeasonMapper.projection,
null,
null,
null,
SeasonMapper
)
episodes = MappedCursorLiveData(
context,
Episodes.fromSeason(seasonId),
EpisodeMapper.projection,
null,
null,
EpisodeColumns.EPISODE + " ASC",
EpisodeListMapper
)
}
}
override suspend fun onRefresh() {
val showId = seasonHelper.getShowId(seasonId)
val traktId = showHelper.getTraktId(showId)
val season = seasonHelper.getNumber(seasonId)
syncSeason.invokeSync(SyncSeason.Params(traktId, season))
}
}
| apache-2.0 | cc5d3198c29378892a747def0c6e4b25 | 31.493976 | 75 | 0.752688 | 4.450495 | false | false | false | false |
andreyfomenkov/green-cat | plugin/src/ru/fomenkov/plugin/util/Util.kt | 1 | 1099 | package ru.fomenkov.plugin.util
import java.io.File
val CURRENT_DIR: String = File("").absolutePath
val DISTINCT_ID = CURRENT_DIR.noTilda().split("/")[2]
val HOME_DIR: String = exec("echo ~").firstOrNull().let { path ->
when {
path.isNullOrBlank() -> error("Failed to get home directory")
else -> path
}
}
fun String.noTilda() = when {
trim().startsWith("~") -> replace("~", HOME_DIR)
else -> this
}
fun formatMillis(value: Long) = when {
value < 1000 -> "$value ms"
else -> "${"%.1f".format(value / 1000f)} sec".replace(",", ".")
}
fun String.isVersionGreaterOrEquals(version: String) = this >= version
fun timeMillis(action: () -> Unit): Long {
val start = System.currentTimeMillis()
action()
val end = System.currentTimeMillis()
return end - start
}
fun isFileSupported(path: String) = path.trim().endsWith(".java") || path.trim().endsWith(".kt")
fun getApiLevel(): Int? {
val output = exec("adb shell getprop ro.build.version.sdk")
if (output.isEmpty()) {
return null
}
return output.first().toIntOrNull()
} | apache-2.0 | 0daba0eef55828b6571dce652eae248d | 25.829268 | 96 | 0.628753 | 3.627063 | false | false | false | false |
hartwigmedical/hmftools | cider/src/test/java/com/hartwig/hmftools/cider/TestUtils.kt | 1 | 2591 | package com.hartwig.hmftools.cider
import com.hartwig.hmftools.cider.layout.ReadLayout
import com.hartwig.hmftools.cider.layout.TestLayoutRead
import htsjdk.samtools.SAMUtils
import java.util.concurrent.atomic.AtomicInteger
object TestUtils
{
const val MIN_BASE_QUALITY = 30.toByte()
// used to assign unique read id
val nextReadId = AtomicInteger(1)
fun createRead(readId: String, seq: String, baseQualityString: String, alignedPosition: Int, firstOfPair: Boolean = true)
: ReadLayout.Read
{
val baseQual = SAMUtils.fastqToPhred(baseQualityString)
// we are aligned at the T
return TestLayoutRead(readId, ReadKey(readId, firstOfPair), seq, baseQual, alignedPosition)
}
// create a very simple layout with just a sequence
fun createLayout(seq: String, minBaseQuality: Byte = MIN_BASE_QUALITY) : ReadLayout
{
val baseQual = SAMUtils.phredToFastq(minBaseQuality * 2).toString().repeat(seq.length)
val read = createRead("createLayout::autoReadId::${nextReadId.getAndIncrement()}", seq, baseQual, 0)
val layout = ReadLayout()
layout.addRead(read, minBaseQuality)
return layout
}
// some genes we can use for testing
val ighJ1 = VJAnchorTemplate(
VJGeneType.IGHJ,
"IGHJ1",
"01",
null,
"GCTGAATACTTCCAGCACTGGGGCCAGGGCACCCTGGTCACCGTCTCCTCAG",
"TGGGGCCAGGGCACCCTGGTCACCGTCTCC",
null)
val ighJ6 = VJAnchorTemplate(
VJGeneType.IGHJ, "IGHJ6","01", null,
"ATTACTACTACTACTACGGTATGGACGTCTGGGGGCAAGGGACCACGGTCACCGTCTCCTCAG",
"TGGGGGCAAGGGACCACGGTCACCGTCTCC",
null)
val ighV1_18 = VJAnchorTemplate(
VJGeneType.IGHV,
"IGHV1-18",
"01",
null,
"CAGGTTCAGCTGGTGCAGTCTGGAGCTGAGGTGAAGAAGCCTGGGGCCTCAGTGAAGGTCTCCTGCAAGGCTTCTGGTTACACCTTTACCAGCTATGGTATCAGCTGGGTGCGACAGGCCCCTGGACAAGGGCTTGAGTGGATGGGATGGATCAGCGCTTACAATGGTAACACAAACTATGCACAGAAGCTCCAGGGCAGAGTCACCATGACCACAGACACATCCACGAGCACAGCCTACATGGAGCTGAGGAGCCTGAGATCTGACGACACGGCCGTGTATTACTGTGCGAGAGA",
"AGATCTGACGACACGGCCGTGTATTACTGT",
null)
val ighV3_7 = VJAnchorTemplate(
VJGeneType.IGHV, "IGHV3-7", "01", null,
"GAGGTGCAGCTGGTGGAGTCTGGGGGAGGCTTGGTCCAGCCTGGGGGGTCCCTGAGACTCTCCTGTGCAGCCTCTGGATTCACCTTTAGTAGCTATTGGATGAGCTGGGTCCGCCAGGCTCCAGGGAAGGGGCTGGAGTGGGTGGCCAACATAAAGCAAGATGGAAGTGAGAAATACTATGTGGACTCTGTGAAGGGCCGATTCACCATCTCCAGAGACAACGCCAAGAACTCACTGTATCTGCAAATGAACAGCCTGAGAGCCGAGGACACGGCTGTGTATTACTGTGCGAGAGA",
"AGAGCCGAGGACACGGCTGTGTATTACTGT",
null)
} | gpl-3.0 | 77f57a4dcbfcb795e2e73e63346fc505 | 39.5 | 307 | 0.7445 | 3.175245 | false | true | false | false |
timusus/Shuttle | app/src/main/java/com/simplecity/amp_library/ui/screens/queue/QueueViewBinder.kt | 1 | 7659 | package com.simplecity.amp_library.ui.screens.queue
import android.text.TextUtils
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import butterknife.BindView
import butterknife.ButterKnife
import com.bumptech.glide.Glide
import com.bumptech.glide.RequestManager
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.simplecity.amp_library.R
import com.simplecity.amp_library.model.Song
import com.simplecity.amp_library.ui.adapters.ViewType
import com.simplecity.amp_library.ui.modelviews.BaseSelectableViewModel
import com.simplecity.amp_library.ui.modelviews.SectionedView
import com.simplecity.amp_library.ui.views.NonScrollImageButton
import com.simplecity.amp_library.utils.PlaceholderProvider
import com.simplecity.amp_library.utils.SettingsManager
import com.simplecity.amp_library.utils.StringUtils
import com.simplecity.amp_library.utils.sorting.SortManager
import com.simplecityapps.recycler_adapter.recyclerview.BaseViewHolder
class QueueViewBinder(
val queueItem: QueueItem,
private val requestManager: RequestManager,
private val sortManager: SortManager,
private val settingsManager: SettingsManager
) :
BaseSelectableViewModel<QueueViewBinder.ViewHolder>(),
SectionedView {
interface ClickListener {
fun onQueueItemClick(position: Int, queueViewBinder: QueueViewBinder)
fun onQueueItemLongClick(position: Int, queueViewBinder: QueueViewBinder): Boolean
fun onQueueItemOverflowClick(position: Int, v: View, queueViewBinder: QueueViewBinder)
fun onStartDrag(holder: ViewHolder)
}
private var showAlbumArt: Boolean = false
var isCurrentTrack: Boolean = false
private var listener: ClickListener? = null
fun setClickListener(listener: ClickListener?) {
this.listener = listener
}
fun showAlbumArt(showAlbumArt: Boolean) {
this.showAlbumArt = showAlbumArt
}
internal fun onItemClick(position: Int) {
listener?.onQueueItemClick(position, this)
}
internal fun onOverflowClick(position: Int, v: View) {
listener?.onQueueItemOverflowClick(position, v, this)
}
internal fun onItemLongClick(position: Int): Boolean {
return listener?.onQueueItemLongClick(position, this) ?: false
}
internal fun onStartDrag(holder: ViewHolder) {
listener?.onStartDrag(holder)
}
override fun getViewType(): Int {
return ViewType.SONG_EDITABLE
}
override fun getLayoutResId(): Int {
return R.layout.list_item_edit
}
override fun bindView(holder: ViewHolder) {
super.bindView(holder)
holder.lineOne.text = queueItem.song.name
holder.lineTwo.text = String.format("%s • %s", queueItem.song.artistName, queueItem.song.albumName)
holder.lineTwo.visibility = View.VISIBLE
holder.lineThree.text = queueItem.song.getDurationLabel(holder.itemView.context)
holder.dragHandle.isActivated = isCurrentTrack
holder.artwork?.let { artwork ->
if (showAlbumArt && settingsManager.showArtworkInQueue()) {
artwork.visibility = View.VISIBLE
requestManager.load<Song>(queueItem.song)
.diskCacheStrategy(DiskCacheStrategy.ALL)
.placeholder(PlaceholderProvider.getInstance(holder.itemView.context).getPlaceHolderDrawable(queueItem.song.albumName, false, settingsManager))
.into(artwork)
} else {
artwork.visibility = View.GONE
}
}
holder.overflowButton.contentDescription = holder.itemView.resources.getString(R.string.btn_options, queueItem.song.name)
}
override fun bindView(holder: ViewHolder, position: Int, payloads: List<*>) {
super.bindView(holder, position, payloads)
holder.dragHandle.isActivated = isCurrentTrack
}
override fun createViewHolder(parent: ViewGroup): ViewHolder {
return ViewHolder(createView(parent))
}
override fun getSectionName(): String {
val sortOrder = sortManager.songsSortOrder
if (sortOrder != SortManager.SongSort.DATE
&& sortOrder != SortManager.SongSort.DURATION
&& sortOrder != SortManager.SongSort.TRACK_NUMBER
) {
var string = ""
var requiresSubstring = true
when (sortOrder) {
SortManager.SongSort.DEFAULT -> string = StringUtils.keyFor(queueItem.song.name)
SortManager.SongSort.NAME -> string = queueItem.song.name
SortManager.SongSort.YEAR -> {
string = queueItem.song.year.toString()
if (string.length != 4) {
string = "-"
} else {
string = string.substring(2, 4)
}
requiresSubstring = false
}
SortManager.SongSort.ALBUM_NAME -> string = StringUtils.keyFor(queueItem.song.albumName)
SortManager.SongSort.ARTIST_NAME -> string = StringUtils.keyFor(queueItem.song.artistName)
}
if (requiresSubstring) {
string = if (!TextUtils.isEmpty(string)) {
string.substring(0, 1).toUpperCase()
} else {
""
}
}
return string
}
return ""
}
override fun areContentsEqual(other: Any): Boolean {
return super.areContentsEqual(other) && if (other is QueueViewBinder) {
queueItem == other.queueItem && isCurrentTrack == other.isCurrentTrack
} else {
false
}
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as QueueViewBinder
if (queueItem != other.queueItem) return false
return true
}
override fun hashCode(): Int {
return queueItem.hashCode()
}
companion object {
const val TAG = "QueueViewBinder"
}
class ViewHolder constructor(itemView: View) : BaseViewHolder<QueueViewBinder>(itemView) {
@BindView(R.id.line_one)
lateinit var lineOne: TextView
@BindView(R.id.line_two)
lateinit var lineTwo: TextView
@BindView(R.id.line_three)
lateinit var lineThree: TextView
@BindView(R.id.btn_overflow)
lateinit var overflowButton: NonScrollImageButton
@BindView(R.id.drag_handle)
lateinit var dragHandle: ImageView
@BindView(R.id.image)
@JvmField
var artwork: ImageView? = null
init {
ButterKnife.bind(this, itemView)
itemView.setOnClickListener { v -> viewModel.onItemClick(adapterPosition) }
itemView.setOnLongClickListener { v -> viewModel.onItemLongClick(adapterPosition) }
overflowButton.setOnClickListener { v -> viewModel.onOverflowClick(adapterPosition, v) }
dragHandle?.setOnTouchListener { v, event ->
if (event.actionMasked == MotionEvent.ACTION_DOWN) {
viewModel.onStartDrag(this)
}
true
}
}
override fun toString(): String {
return "QueueVeewBinder.ViewHolder"
}
override fun recycle() {
super.recycle()
artwork?.let { artwork ->
Glide.clear(artwork)
}
}
}
} | gpl-3.0 | d6c49905e7d8a4b048ecd31173ffb4e2 | 31.587234 | 163 | 0.644508 | 4.858503 | false | false | false | false |
natanieljr/droidmate | project/pcComponents/core/src/main/kotlin/org/droidmate/device/deviceInterface/RobustDevice.kt | 1 | 28393 | // DroidMate, an automated execution generator for Android apps.
// Copyright (C) 2012-2018. Saarland University
//
// 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/>.
//
// Current Maintainers:
// Nataniel Borges Jr. <nataniel dot borges at cispa dot saarland>
// Jenny Hotzkow <jenny dot hotzkow at cispa dot saarland>
//
// Former Maintainers:
// Konrad Jamrozik <jamrozik at st dot cs dot uni-saarland dot de>
//
// web: www.droidmate.org
package org.droidmate.device.deviceInterface
import kotlinx.coroutines.delay
import org.droidmate.configuration.ConfigProperties
import org.droidmate.configuration.ConfigurationWrapper
import org.droidmate.device.AllDeviceAttemptsExhaustedException
import org.droidmate.device.IAndroidDevice
import org.droidmate.device.TcpServerUnreachableException
import org.droidmate.device.android_sdk.IApk
import org.droidmate.device.android_sdk.NoAndroidDevicesAvailableException
import org.droidmate.device.error.DeviceException
import org.droidmate.device.logcat.IApiLogcatMessage
import org.droidmate.device.logcat.IDeviceMessagesReader
import org.droidmate.deviceInterface.communication.TimeFormattedLogMessageI
import org.droidmate.deviceInterface.exploration.ActionType
import org.droidmate.deviceInterface.exploration.DeviceResponse
import org.droidmate.deviceInterface.exploration.ExplorationAction
import org.droidmate.deviceInterface.exploration.GlobalAction
import org.droidmate.exploration.actions.click
import org.droidmate.logging.Markers
import org.droidmate.misc.Utils
import org.slf4j.LoggerFactory
import java.nio.file.Path
import java.time.LocalDateTime
// TODO Very confusing method chain. Simplify
class RobustDevice : IRobustDevice {
override suspend fun pullFile(fileName: String, dstPath: Path, srcPath: String) =
this.device.pullFile(fileName,dstPath,srcPath) // pull may fail because we try to fetch images which were not possible to capture -> no retry here
override suspend fun removeFile(fileName: String, srcPath: String) {
Utils.retryOnException(
{ this.device.removeFile(fileName,srcPath) },
{},
deviceOperationAttempts,
deviceOperationDelay,
"device.removeFile()"
) }
companion object {
private val log by lazy { LoggerFactory.getLogger(RobustDevice::class.java) }
}
private val device: IAndroidDevice
private val cfg: ConfigurationWrapper
private val messagesReader: IDeviceMessagesReader
private val checkAppIsRunningRetryAttempts: Int
private val checkAppIsRunningRetryDelay: Int
private val stopAppRetryAttempts: Int
private val stopAppSuccessCheckDelay: Int
private val checkDeviceAvailableAfterRebootAttempts: Int
private val checkDeviceAvailableAfterRebootFirstDelay: Int
private val checkDeviceAvailableAfterRebootLaterDelays: Int
private val waitForCanRebootDelay: Int
private val deviceOperationAttempts: Int
private val deviceOperationDelay: Int
private val ensureHomeScreenIsDisplayedAttempts = 3
constructor(device: IAndroidDevice, cfg: ConfigurationWrapper) : this(device,
cfg,
cfg[ConfigProperties.DeviceCommunication.checkAppIsRunningRetryAttempts],
cfg[ConfigProperties.DeviceCommunication.checkAppIsRunningRetryDelay],
cfg[ConfigProperties.DeviceCommunication.stopAppRetryAttempts],
cfg[ConfigProperties.DeviceCommunication.stopAppSuccessCheckDelay],
cfg[ConfigProperties.DeviceCommunication.checkDeviceAvailableAfterRebootAttempts],
cfg[ConfigProperties.DeviceCommunication.checkDeviceAvailableAfterRebootFirstDelay],
cfg[ConfigProperties.DeviceCommunication.checkDeviceAvailableAfterRebootLaterDelays],
cfg[ConfigProperties.DeviceCommunication.waitForCanRebootDelay],
cfg[ConfigProperties.DeviceCommunication.deviceOperationAttempts],
cfg[ConfigProperties.DeviceCommunication.deviceOperationDelay],
cfg[ConfigProperties.ApiMonitorServer.monitorUseLogcat])
constructor(device: IAndroidDevice,
cfg: ConfigurationWrapper,
checkAppIsRunningRetryAttempts: Int,
checkAppIsRunningRetryDelay: Int,
stopAppRetryAttempts: Int,
stopAppSuccessCheckDelay: Int,
checkDeviceAvailableAfterRebootAttempts: Int,
checkDeviceAvailableAfterRebootFirstDelay: Int,
checkDeviceAvailableAfterRebootLaterDelays: Int,
waitForCanRebootDelay: Int,
deviceOperationAttempts: Int,
deviceOperationDelay: Int,
monitorUseLogcat: Boolean) {
this.device = device
this.cfg = cfg
this.messagesReader = DeviceMessagesReader(device, monitorUseLogcat)
this.checkAppIsRunningRetryAttempts = checkAppIsRunningRetryAttempts
this.checkAppIsRunningRetryDelay = checkAppIsRunningRetryDelay
this.stopAppRetryAttempts = stopAppRetryAttempts
this.stopAppSuccessCheckDelay = stopAppSuccessCheckDelay
this.checkDeviceAvailableAfterRebootAttempts = checkDeviceAvailableAfterRebootAttempts
this.checkDeviceAvailableAfterRebootFirstDelay = checkDeviceAvailableAfterRebootFirstDelay
this.checkDeviceAvailableAfterRebootLaterDelays = checkDeviceAvailableAfterRebootLaterDelays
this.waitForCanRebootDelay = waitForCanRebootDelay
this.deviceOperationAttempts = deviceOperationAttempts
this.deviceOperationDelay = deviceOperationDelay
assert(checkAppIsRunningRetryAttempts >= 1)
assert(stopAppRetryAttempts >= 1)
assert(checkDeviceAvailableAfterRebootAttempts >= 1)
assert(deviceOperationAttempts >= 1)
assert(checkAppIsRunningRetryDelay >= 0)
assert(stopAppSuccessCheckDelay >= 0)
assert(checkDeviceAvailableAfterRebootFirstDelay >= 0)
assert(checkDeviceAvailableAfterRebootLaterDelays >= 0)
assert(waitForCanRebootDelay >= 0)
assert(deviceOperationDelay >= 0)
}
override suspend fun uninstallApk(apkPackageName: String, ignoreFailure: Boolean) {
if (ignoreFailure)
device.uninstallApk(apkPackageName, ignoreFailure)
else {
try {
device.uninstallApk(apkPackageName, ignoreFailure)
} catch (e: DeviceException) {
val appIsInstalled: Boolean
try {
appIsInstalled = device.hasPackageInstalled(apkPackageName)
} catch (e2: DeviceException) {
throw DeviceException("Uninstalling of $apkPackageName failed with exception E1: '$e'. " +
"Tried to check if the app that was to be uninstalled is still installed, but that also resulted in exception, E2. " +
"Discarding E1 and throwing an exception having as a cause E2", e2)
}
if (appIsInstalled)
throw DeviceException("Uninstalling of $apkPackageName threw an exception (given as cause of this exception) and the app is indeed still installed.", e)
else {
log.debug("Uninstalling of $apkPackageName threw an exception, but the app is no longer installed. Note: this situation has proven to make the uiautomator be unable to dump window hierarchy. Discarding the exception '$e', resetting connection to the device and continuing.")
// Doing .rebootAndRestoreConnection() just hangs the emulator: http://stackoverflow.com/questions/9241667/how-to-reboot-emulator-to-test-action-boot-completed
this.closeConnection()
this.setupConnection()
}
}
}
}
override suspend fun setupConnection() {
rebootIfNecessary("device.setupConnection()", true) { this.device.setupConnection() }
}
override suspend fun clearPackage(apkPackageName: String) {
// Clearing package has to happen more than once, because sometimes after cleaning suddenly the ActivityManager restarts
// one of the activities of the app.
Utils.retryOnFalse({
Utils.retryOnException({ device.clearPackage(apkPackageName) },
{},
deviceOperationAttempts,
deviceOperationDelay,
"clearPackage")
// Sleep here to give the device some time to stop all the processes belonging to the cleared package before checking
// if indeed all of them have been stopped.
delay(this.stopAppSuccessCheckDelay.toLong())
!this.getAppIsRunningRebootingIfNecessary(apkPackageName)
},
this.stopAppRetryAttempts,
/* Retry timeout. Zero, because after seeing the app didn't stop, we immediately clear package again. */
0)
}
private fun DeviceResponse.isSelectAHomeAppDialogBox(): Boolean =
widgets.any { it.text == "Just once" } &&
widgets.any { it.text == "Select a Home app" }
private fun DeviceResponse.isUseLauncherAsHomeDialogBox(): Boolean =
widgets.any { it.text == "Use Launcher as Home" } &&
widgets.any { it.text == "Just once" } &&
widgets.any { it.text == "Always" }
override suspend fun ensureHomeScreenIsDisplayed(): DeviceResponse {
var guiSnapshot = this.getExplorableGuiSnapshot()
if (guiSnapshot.isHomeScreen)
return guiSnapshot
Utils.retryOnFalse({
if (!guiSnapshot.isHomeScreen) {
guiSnapshot = when { //FIXME what are these, are they even still useful?
guiSnapshot.isSelectAHomeAppDialogBox() ->
closeSelectAHomeAppDialogBox(guiSnapshot)
guiSnapshot.isUseLauncherAsHomeDialogBox() ->
closeUseLauncherAsHomeDialogBox(guiSnapshot)
else -> {
perform(GlobalAction(ActionType.PressHome))
}
}
}
guiSnapshot.isHomeScreen
},
ensureHomeScreenIsDisplayedAttempts, /* timeout */ 0)
if (!guiSnapshot.isHomeScreen) {
throw DeviceException("Failed to ensure home screen is displayed. " +
"Pressing 'home' button didn't help. Instead, ended with GUI state of: $guiSnapshot.\n" +
"Full window hierarchy dump:\n" +
guiSnapshot.windowHierarchyDump)
}
return guiSnapshot
}
private suspend fun closeSelectAHomeAppDialogBox(snapshot: DeviceResponse): DeviceResponse {
val launcherWidget = snapshot.widgets.single { it.text == "Launcher" }
perform(launcherWidget.click())
var guiSnapshot = this.getExplorableGuiSnapshot()
if (guiSnapshot.isSelectAHomeAppDialogBox()) {
val justOnceWidget = guiSnapshot.widgets.single { it.text == "Just once" }
perform(justOnceWidget.click())
guiSnapshot = this.getExplorableGuiSnapshot()
}
assert(!guiSnapshot.isSelectAHomeAppDialogBox())
return guiSnapshot
}
private suspend fun closeUseLauncherAsHomeDialogBox(snapshot: DeviceResponse): DeviceResponse {
val justOnceWidget = snapshot.widgets.single { it.text == "Just once" }
perform(justOnceWidget.click())
val guiSnapshot = this.getExplorableGuiSnapshot()
assert(!guiSnapshot.isUseLauncherAsHomeDialogBox())
return guiSnapshot
}
override suspend fun perform(action: ExplorationAction): DeviceResponse {
return Utils.retryOnFalse({
Utils.retryOnException(
{
this.device.perform(action)
},
{ this.restartUiaDaemon(false) },
deviceOperationAttempts,
deviceOperationDelay,
"device.perform(action:$action)"
)
},
{ it.isSuccessful },
deviceOperationAttempts,
deviceOperationDelay)
}
override suspend fun appIsNotRunning(apk: IApk): Boolean {
return Utils.retryOnFalse({ !this.getAppIsRunningRebootingIfNecessary(apk.packageName) },
checkAppIsRunningRetryAttempts,
checkAppIsRunningRetryDelay)
}
@Throws(DeviceException::class)
private suspend fun getAppIsRunningRebootingIfNecessary(packageName: String): Boolean =
rebootIfNecessary("device.appIsRunning(packageName:$packageName)", true) {
this.device.appIsRunning(packageName)
}
@Throws(DeviceException::class)
private suspend fun getExplorableGuiSnapshot(): DeviceResponse {
var guiSnapshot = this.getRetryValidGuiSnapshotRebootingIfNecessary()
guiSnapshot = closeANRIfNecessary(guiSnapshot)
return guiSnapshot
}
private fun DeviceResponse.isAppHasStoppedDialogBox(): Boolean =
widgets.any { it.resourceId == "android:id/aerr_close" } &&
widgets.any { it.resourceId == "android:id/aerr_wait" }
@Throws(DeviceException::class)
private suspend fun closeANRIfNecessary(guiSnapshot: DeviceResponse): DeviceResponse {
if (!guiSnapshot.isAppHasStoppedDialogBox())
return guiSnapshot
assert(guiSnapshot.isAppHasStoppedDialogBox())
var targetWidget = guiSnapshot.widgets.firstOrNull { it.text == "OK" } ?:
guiSnapshot.widgets.first { it.resourceId == "android:id/aerr_close" }
assert(targetWidget.enabled)
log.debug("ANR encountered")
var out = guiSnapshot
Utils.retryOnFalse({
assert(targetWidget.enabled)
device.perform(targetWidget.click())
out = this.getRetryValidGuiSnapshotRebootingIfNecessary()
if (out.isAppHasStoppedDialogBox()) {
targetWidget = guiSnapshot.widgets.firstOrNull { it.text == "OK" } ?:
guiSnapshot.widgets.first { it.resourceId == "android:id/aerr_close" }
log.debug("ANR encountered - again. Failed to properly close it even though its OK widget was enabled.")
false
} else
true
},
deviceOperationAttempts,
deviceOperationDelay)
return out
}
@Throws(DeviceException::class)
private suspend fun getRetryValidGuiSnapshotRebootingIfNecessary(): DeviceResponse =
rebootIfNecessary("device.getRetryValidGuiSnapshot()", true) {
this.getRetryValidGuiSnapshot()
}
@Throws(DeviceException::class)
private suspend fun getRetryValidGuiSnapshot(): DeviceResponse {
try {
return Utils.retryOnException(
{ getValidGuiSnapshot() },
{ restartUiaDaemon(false) },
deviceOperationAttempts,
deviceOperationDelay,
"getValidGuiSnapshot")
} catch (e: DeviceException) {
throw AllDeviceAttemptsExhaustedException("All attempts at getting valid GUI snapshot failed", e)
}
}
@Throws(DeviceException::class)
private suspend fun getValidGuiSnapshot(): DeviceResponse {
// the rebootIfNecessary will reboot on TcpServerUnreachable
return rebootIfNecessary("device.getGuiSnapshot()", true) {
perform(GlobalAction(ActionType.FetchGUI))
}
}
@Throws(DeviceException::class)
private suspend fun <T> rebootIfNecessary(
description: String,
makeSecondAttempt: Boolean,
operationOnDevice: suspend () -> T
): T {
try {
return operationOnDevice.invoke()
} catch (e: Exception) {
if ((e !is TcpServerUnreachableException) and (e !is AllDeviceAttemptsExhaustedException))
throw e
log.warn(Markers.appHealth, "! Attempt to execute '$description' threw an exception: $e. " +
(if (makeSecondAttempt)
"Reconnecting adb, rebooting the device and trying again."
else
"Reconnecting adb, rebooting the device and continuing."))
// Removed by Nataniel
// This is not feasible when using the device farm, upon restart of the ADB server the connection
// to the device is lost and it's assigned a new, random port, which doesn't allow automatic reconnection.
//this.reconnectAdbDiscardingException("Call to reconnectAdb() just before call to rebootAndRestoreConnection() " +
// "failed with: %s. Discarding the exception and continuing wih rebooting.")
//this.reinstallUiAutomatorDaemon()
this.rebootAndRestoreConnection()
if (makeSecondAttempt) {
log.info("Reconnected adb and rebooted successfully. Making second and final attempt at executing '$description'")
try {
val out = operationOnDevice()
log.info("Second attempt at executing '$description' completed successfully.")
return out
} catch (e2: Exception) {
if ((e2 !is TcpServerUnreachableException) and (e2 !is AllDeviceAttemptsExhaustedException))
throw e2
log.warn(Markers.appHealth, "! Second attempt to execute '$description' threw an exception: $e2. " +
"Giving up and rethrowing.")
throw e2
}
} else {
throw e
}
}
}
override suspend fun reboot() {
if (this.device.isAvailable()) {
log.trace("Device is available for rebooting.")
} else {
log.trace("Device not yet available for a reboot. Waiting $waitForCanRebootDelay milliseconds. If the device still won't be available, " +
"assuming it cannot be reached at all.")
delay(this.waitForCanRebootDelay.toLong())
if (this.device.isAvailable())
log.trace("Device can be rebooted after the wait.")
else
throw DeviceException("Device is not available for a reboot, even after the wait. Requesting to stop further apk explorations.", true)
}
log.trace("Rebooting.")
this.device.reboot()
delay(this.checkDeviceAvailableAfterRebootFirstDelay.toLong())
// WISH use "adb wait-for-device"
val rebootResult = Utils.retryOnFalse({
val out = this.device.isAvailable()
if (!out)
log.trace("Device not yet available after rebooting, waiting $checkDeviceAvailableAfterRebootLaterDelays milliseconds and retrying")
out
},
checkDeviceAvailableAfterRebootAttempts,
checkDeviceAvailableAfterRebootLaterDelays)
if (rebootResult) {
assert(this.device.isAvailable())
log.trace("Reboot completed successfully.")
} else {
assert(!this.device.isAvailable())
throw DeviceException("Device is not available after a reboot. Requesting to stop further apk explorations.", true)
}
assert(!this.device.uiaDaemonClientThreadIsAlive())
}
override suspend fun rebootAndRestoreConnection() {
// Removed by Nataniel
// This is not feasible when using the device farm, upon restart of the ADB server the connection
// to the device is lost and it's assigned a new, random port, which doesn't allow automatic reconnection.
}
override suspend fun getAndClearCurrentApiLogs(): List<IApiLogcatMessage> {
return rebootIfNecessary("messagesReader.getAndClearCurrentApiLogs()", true) { this.messagesReader.getAndClearCurrentApiLogs() }
}
override suspend fun closeConnection() {
rebootIfNecessary("closeConnection()", true) { this.device.closeConnection() }
}
override fun toString(): String = "robust-" + this.device.toString()
override suspend fun pushFile(jar: Path) {
Utils.retryOnException(
{ this.device.pushFile(jar) },
{},
deviceOperationAttempts,
deviceOperationDelay,
"device.pushFile(jar:$jar)"
)
}
override suspend fun pushFile(jar: Path, targetFileName: String) {
Utils.retryOnException(
{ this.device.pushFile(jar, targetFileName) },
{},
deviceOperationAttempts,
deviceOperationDelay,
"device.pushFile(jar:$jar, targetFileName:$targetFileName)"
)
}
override suspend fun removeJar(jar: Path) {
Utils.retryOnException(
{ this.device.removeJar(jar) },
{},
deviceOperationAttempts,
deviceOperationDelay,
"device.removeJar(jar:$jar)"
)
}
override suspend fun installApk(apk: Path) {
Utils.retryOnException(
{ this.device.installApk(apk) },
{},
deviceOperationAttempts,
deviceOperationDelay,
"device.installApk(apk:$apk)"
)
}
override suspend fun installApk(apk: IApk) {
Utils.retryOnException(
{ this.device.installApk(apk) },
{},
deviceOperationAttempts,
deviceOperationDelay,
"device.installApk(apk:$apk)"
)
}
override suspend fun isApkInstalled(apkPackageName: String): Boolean {
return Utils.retryOnException(
{ this.device.isApkInstalled(apkPackageName) },
{},
deviceOperationAttempts,
deviceOperationDelay,
"device.isApkInstalled(apkPackageName:$apkPackageName)"
)
}
override suspend fun closeMonitorServers() {
Utils.retryOnException(
{ this.device.closeMonitorServers() },
{},
deviceOperationAttempts,
deviceOperationDelay,
"device.closeMonitorServers()"
)
}
override suspend fun appProcessIsRunning(appPackageName: String): Boolean {
return Utils.retryOnException(
{ this.device.appProcessIsRunning(appPackageName) },
{},
deviceOperationAttempts,
deviceOperationDelay,
"device.appProcessIsRunning(appPackageName:$appPackageName)"
)
}
override suspend fun clearLogcat() {
try {
Utils.retryOnException(
{ this.device.clearLogcat() },
{},
2,
deviceOperationDelay,
"device.clearLogcat()"
)
} catch(e : Throwable){
log.warn("logcat clear failed: ${e.message}")
}
}
override suspend fun stopUiaDaemon(uiaDaemonThreadIsNull: Boolean) {
Utils.retryOnException(
{
try {
this.device.stopUiaDaemon(uiaDaemonThreadIsNull)
} catch (e: TcpServerUnreachableException) {
log.warn("Unable to issue stop command to UIAutomator. Assuming it's no longer running.")
} // retry on other exceptions
},
{},
deviceOperationAttempts,
deviceOperationDelay,
"device.stopUiaDaemon"
)
}
override suspend fun isAvailable(): Boolean {
return Utils.retryOnException(
{
try {
this.device.isAvailable()
} catch (ignored: NoAndroidDevicesAvailableException) {
false
} // retry on other exceptions
},
{},
deviceOperationAttempts,
deviceOperationDelay,
"device.isAvailable()"
)
}
override suspend fun uiaDaemonClientThreadIsAlive(): Boolean {
return Utils.retryOnException(
{ this.device.uiaDaemonClientThreadIsAlive() },
{},
deviceOperationAttempts,
deviceOperationDelay,
"device.uiaDaemonClientThreadIsAlive()"
)
}
override suspend fun restartUiaDaemon(uiaDaemonThreadIsNull: Boolean) {
if (this.uiaDaemonIsRunning()) {
this.stopUiaDaemon(uiaDaemonThreadIsNull)
}
this.startUiaDaemon()
}
override suspend fun startUiaDaemon() {
Utils.retryOnException(
{ this.device.startUiaDaemon() },
{},
deviceOperationAttempts,
deviceOperationDelay,
"device.startUiaDaemon()"
)
}
override suspend fun removeLogcatLogFile() {
Utils.retryOnException(
{ this.device.removeLogcatLogFile() },
{},
deviceOperationAttempts,
deviceOperationDelay,
"device.removeLogcatLogFile()"
)
}
override suspend fun reinstallUiAutomatorDaemon() {
Utils.retryOnException(
{ this.device.reinstallUiAutomatorDaemon() },
{},
deviceOperationAttempts,
deviceOperationDelay,
"device.reinstallUiautomatorDaemon()"
)
}
override suspend fun pushAuxiliaryFiles() {
Utils.retryOnException(
{ this.device.pushAuxiliaryFiles() },
{},
deviceOperationAttempts,
deviceOperationDelay,
"device.pushAuxiliaryFiles()"
)
}
override suspend fun reconnectAdb() {
Utils.retryOnException(
{ this.device.reconnectAdb() },
{},
deviceOperationAttempts,
deviceOperationDelay,
"device.reconnectAdb()"
)
}
override suspend fun executeAdbCommand(command: String, successfulOutput: String, commandDescription: String) {
Utils.retryOnException(
{ this.device.executeAdbCommand(command, successfulOutput, commandDescription) },
{},
deviceOperationAttempts,
deviceOperationDelay,
"device.executeAdbCommand(command:$command, successfulOutput:$successfulOutput, commandDescription:$commandDescription)"
)
}
override suspend fun uiaDaemonIsRunning(): Boolean {
return try {
this.device.uiaDaemonIsRunning()
} catch (e: Exception) {
log.warn("Could not check if UIAutomator daemon is running. Assuming it is not and proceeding")
false
}
}
override suspend fun isPackageInstalled(packageName: String): Boolean {
return Utils.retryOnException(
{ this.device.isPackageInstalled(packageName) },
{},
deviceOperationAttempts,
deviceOperationDelay,
"device.isPackageInstalled(packageName:$packageName)"
)
}
override suspend fun hasPackageInstalled(packageName: String): Boolean {
return Utils.retryOnException(
{ this.device.hasPackageInstalled(packageName) },
{},
deviceOperationAttempts,
deviceOperationDelay,
"device.hasPackageInstalled(packageName:$packageName)"
)
}
override suspend fun readLogcatMessages(messageTag: String): List<TimeFormattedLogMessageI> {
return Utils.retryOnException(
{ this.device.readLogcatMessages(messageTag) },
{},
deviceOperationAttempts,
deviceOperationDelay,
"device.readLogcatMessages(messageTag:$messageTag)"
)
}
override suspend fun readStatements(): List<List<String>> {
return Utils.retryOnException(
{ this.device.readStatements() },
{},
deviceOperationAttempts,
deviceOperationDelay,
"device.readStatements()"
)
}
override suspend fun waitForLogcatMessages(messageTag: String, minMessagesCount: Int, waitTimeout: Int, queryDelay: Int): List<TimeFormattedLogMessageI> {
return Utils.retryOnException(
{ this.device.waitForLogcatMessages(messageTag, minMessagesCount, waitTimeout, queryDelay) },
{},
deviceOperationAttempts,
deviceOperationDelay,
"device.waitForLogcatMessages(messageTag:$messageTag, minMessagesCount:$minMessagesCount, waitTimeout:$waitTimeout, queryDelay:$queryDelay)"
)
}
override suspend fun readAndClearMonitorTcpMessages(): List<List<String>> {
return Utils.retryOnException(
{ this.device.readAndClearMonitorTcpMessages() },
{},
deviceOperationAttempts,
deviceOperationDelay,
"device.readAndClearMonitorTcpMessages()"
)
}
override suspend fun getCurrentTime(): LocalDateTime {
return Utils.retryOnException(
{ this.device.getCurrentTime() },
{},
deviceOperationAttempts,
deviceOperationDelay,
"device.getCurrentTime()"
)
}
override suspend fun anyMonitorIsReachable(): Boolean {
return Utils.retryOnException(
{ this.device.anyMonitorIsReachable() },
{},
deviceOperationAttempts,
deviceOperationDelay,
"device.anyMonitorIsReachable()"
)
}
override suspend fun appIsRunning(appPackageName: String): Boolean {
return Utils.retryOnException(
{ this.device.appIsRunning(appPackageName) },
{},
deviceOperationAttempts,
deviceOperationDelay,
"device.appIsRunning(appPackageName:$appPackageName)"
)
}
override suspend fun resetTimeSync() {
Utils.retryOnException(
{ this.messagesReader.resetTimeSync() },
{},
deviceOperationAttempts,
deviceOperationDelay,
"messagesReader.resetTimeSync()"
)
}
}
| gpl-3.0 | f0af69219bd9893580afc431ef1a4cb1 | 35.308184 | 279 | 0.691508 | 4.423275 | false | false | false | false |
sys1yagi/mastodon4j | mastodon4j/src/test/java/com/sys1yagi/mastodon4j/api/method/MediaTest.kt | 1 | 1137 | package com.sys1yagi.mastodon4j.api.method
import com.sys1yagi.mastodon4j.api.exception.Mastodon4jRequestException
import com.sys1yagi.mastodon4j.extension.emptyRequestBody
import com.sys1yagi.mastodon4j.testtool.MockClient
import okhttp3.MultipartBody
import org.amshove.kluent.shouldEqualTo
import org.amshove.kluent.shouldNotBe
import org.junit.Test
class MediaTest {
@Test
fun postMedia() {
val client = MockClient.mock("attachment.json")
val media = Media(client)
val attachment = media.postMedia(MultipartBody.Part.create(emptyRequestBody())).execute()
attachment.id shouldEqualTo 10
attachment.type shouldEqualTo "video"
attachment.url shouldEqualTo "youtube"
attachment.remoteUrl shouldNotBe null
attachment.previewUrl shouldEqualTo "preview"
attachment.textUrl shouldNotBe null
}
@Test(expected = Mastodon4jRequestException::class)
fun postMediaWithException() {
val client = MockClient.ioException()
val media = Media(client)
media.postMedia(MultipartBody.Part.create(emptyRequestBody())).execute()
}
}
| mit | 6206cf3d4de960e0462cb59d9d2fbb63 | 35.677419 | 97 | 0.743184 | 4.373077 | false | true | false | false |
cloose/luftbild4p3d | src/main/kotlin/org/luftbild4p3d/osm/osmParser.kt | 1 | 708 | package org.luftbild4p3d.osm
import java.io.File
import java.io.StringReader
import javax.xml.bind.JAXBContext
fun parseOsmData(osmData: String): Osm {
val jaxbContext = JAXBContext.newInstance(Osm::class.java)
val unmarshaller = jaxbContext.createUnmarshaller()
return unmarshaller.unmarshal(StringReader(osmData)) as Osm
}
fun parseOsmDataFile(osmDataFileName: String): Osm {
println("Parse OSM data from file: $osmDataFileName")
val jaxbContext = JAXBContext.newInstance(Osm::class.java)
val unmarshaller = jaxbContext.createUnmarshaller()
val osmDataFile = File("$osmDataFileName")
osmDataFile.reader().use {
return unmarshaller.unmarshal(it) as Osm
}
}
| gpl-3.0 | a4ef93458ad0d121ce62899f8436a1a1 | 28.5 | 63 | 0.751412 | 3.593909 | false | false | false | false |
Light-Team/ModPE-IDE-Source | languages/language-c/src/main/kotlin/com/brackeys/ui/language/c/styler/CStyler.kt | 1 | 9106 | /*
* Copyright 2021 Brackeys IDE contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.brackeys.ui.language.c.styler
import android.util.Log
import com.brackeys.ui.language.base.model.SyntaxScheme
import com.brackeys.ui.language.base.span.StyleSpan
import com.brackeys.ui.language.base.span.SyntaxHighlightSpan
import com.brackeys.ui.language.base.styler.LanguageStyler
import com.brackeys.ui.language.base.utils.StylingResult
import com.brackeys.ui.language.base.utils.StylingTask
import com.brackeys.ui.language.c.lexer.CLexer
import com.brackeys.ui.language.c.lexer.CToken
import java.io.IOException
import java.io.StringReader
class CStyler private constructor() : LanguageStyler {
companion object {
private const val TAG = "CStyler"
private var cStyler: CStyler? = null
fun getInstance(): CStyler {
return cStyler ?: CStyler().also {
cStyler = it
}
}
}
private var task: StylingTask? = null
override fun execute(sourceCode: String, syntaxScheme: SyntaxScheme): List<SyntaxHighlightSpan> {
val syntaxHighlightSpans = mutableListOf<SyntaxHighlightSpan>()
val sourceReader = StringReader(sourceCode)
val lexer = CLexer(sourceReader)
while (true) {
try {
when (lexer.advance()) {
CToken.LONG_LITERAL,
CToken.INTEGER_LITERAL,
CToken.FLOAT_LITERAL,
CToken.DOUBLE_LITERAL -> {
val styleSpan = StyleSpan(syntaxScheme.numberColor)
val syntaxHighlightSpan = SyntaxHighlightSpan(styleSpan, lexer.tokenStart, lexer.tokenEnd)
syntaxHighlightSpans.add(syntaxHighlightSpan)
}
CToken.TRIGRAPH,
CToken.EQ,
CToken.PLUS,
CToken.MINUS,
CToken.MULT,
CToken.DIV,
CToken.MOD,
CToken.TILDA,
CToken.LT,
CToken.GT,
CToken.LTLT,
CToken.GTGT,
CToken.EQEQ,
CToken.PLUSEQ,
CToken.MINUSEQ,
CToken.MULTEQ,
CToken.DIVEQ,
CToken.MODEQ,
CToken.ANDEQ,
CToken.OREQ,
CToken.XOREQ,
CToken.GTEQ,
CToken.LTEQ,
CToken.NOTEQ,
CToken.GTGTEQ,
CToken.LTLTEQ,
CToken.XOR,
CToken.AND,
CToken.ANDAND,
CToken.OR,
CToken.OROR,
CToken.QUEST,
CToken.COLON,
CToken.NOT,
CToken.PLUSPLUS,
CToken.MINUSMINUS,
CToken.LPAREN,
CToken.RPAREN,
CToken.LBRACE,
CToken.RBRACE,
CToken.LBRACK,
CToken.RBRACK -> {
val styleSpan = StyleSpan(syntaxScheme.operatorColor)
val syntaxHighlightSpan =
SyntaxHighlightSpan(styleSpan, lexer.tokenStart, lexer.tokenEnd)
syntaxHighlightSpans.add(syntaxHighlightSpan)
}
CToken.SEMICOLON,
CToken.COMMA,
CToken.DOT -> {
continue // skip
}
CToken.AUTO,
CToken.BREAK,
CToken.CASE,
CToken.CONST,
CToken.CONTINUE,
CToken.DEFAULT,
CToken.DO,
CToken.ELSE,
CToken.ENUM,
CToken.EXTERN,
CToken.FOR,
CToken.GOTO,
CToken.IF,
CToken.REGISTER,
CToken.SIZEOF,
CToken.STATIC,
CToken.STRUCT,
CToken.SWITCH,
CToken.TYPEDEF,
CToken.UNION,
CToken.VOLATILE,
CToken.WHILE,
CToken.RETURN -> {
val styleSpan = StyleSpan(syntaxScheme.keywordColor)
val syntaxHighlightSpan =
SyntaxHighlightSpan(styleSpan, lexer.tokenStart, lexer.tokenEnd)
syntaxHighlightSpans.add(syntaxHighlightSpan)
}
CToken.FUNCTION -> {
val styleSpan = StyleSpan(syntaxScheme.methodColor)
val syntaxHighlightSpan =
SyntaxHighlightSpan(styleSpan, lexer.tokenStart, lexer.tokenEnd)
syntaxHighlightSpans.add(syntaxHighlightSpan)
}
CToken.BOOL,
CToken.CHAR,
CToken.DIV_T,
CToken.DOUBLE,
CToken.FLOAT,
CToken.INT,
CToken.LDIV_T,
CToken.LONG,
CToken.SHORT,
CToken.SIGNED,
CToken.SIZE_T,
CToken.UNSIGNED,
CToken.VOID,
CToken.WCHAR_T -> {
val styleSpan = StyleSpan(syntaxScheme.typeColor)
val syntaxHighlightSpan =
SyntaxHighlightSpan(styleSpan, lexer.tokenStart, lexer.tokenEnd)
syntaxHighlightSpans.add(syntaxHighlightSpan)
}
CToken.TRUE,
CToken.FALSE,
CToken.NULL -> {
val styleSpan = StyleSpan(syntaxScheme.langConstColor)
val syntaxHighlightSpan =
SyntaxHighlightSpan(styleSpan, lexer.tokenStart, lexer.tokenEnd)
syntaxHighlightSpans.add(syntaxHighlightSpan)
}
CToken.__DATE__,
CToken.__TIME__,
CToken.__FILE__,
CToken.__LINE__,
CToken.__STDC__,
CToken.PREPROCESSOR -> {
val styleSpan = StyleSpan(syntaxScheme.preprocessorColor)
val syntaxHighlightSpan =
SyntaxHighlightSpan(styleSpan, lexer.tokenStart, lexer.tokenEnd)
syntaxHighlightSpans.add(syntaxHighlightSpan)
}
CToken.DOUBLE_QUOTED_STRING,
CToken.SINGLE_QUOTED_STRING -> {
val styleSpan = StyleSpan(syntaxScheme.stringColor)
val syntaxHighlightSpan =
SyntaxHighlightSpan(styleSpan, lexer.tokenStart, lexer.tokenEnd)
syntaxHighlightSpans.add(syntaxHighlightSpan)
}
CToken.LINE_COMMENT,
CToken.BLOCK_COMMENT -> {
val styleSpan = StyleSpan(syntaxScheme.commentColor)
val syntaxHighlightSpan =
SyntaxHighlightSpan(styleSpan, lexer.tokenStart, lexer.tokenEnd)
syntaxHighlightSpans.add(syntaxHighlightSpan)
}
CToken.IDENTIFIER,
CToken.WHITESPACE,
CToken.BAD_CHARACTER -> {
continue
}
CToken.EOF -> {
break
}
}
} catch (e: IOException) {
Log.e(TAG, e.message, e)
break
}
}
return syntaxHighlightSpans
}
override fun enqueue(sourceCode: String, syntaxScheme: SyntaxScheme, stylingResult: StylingResult) {
task?.cancelTask()
task = StylingTask(
doAsync = { execute(sourceCode, syntaxScheme) },
onSuccess = stylingResult
)
task?.executeTask()
}
override fun cancel() {
task?.cancelTask()
task = null
}
} | apache-2.0 | 868c05df8bb1d12c6fe9294f333a5dd2 | 38.25431 | 114 | 0.480892 | 5.297266 | false | false | false | false |
rsiebert/TVHClient | app/src/main/java/org/tvheadend/tvhclient/ui/features/dvr/timer_recordings/TimerRecordingAddEditFragment.kt | 1 | 11679 | package org.tvheadend.tvhclient.ui.features.dvr.timer_recordings
import android.os.Bundle
import android.view.*
import androidx.core.view.forEach
import androidx.lifecycle.ViewModelProvider
import com.afollestad.materialdialogs.MaterialDialog
import org.tvheadend.data.entity.Channel
import org.tvheadend.data.entity.ServerProfile
import org.tvheadend.tvhclient.R
import org.tvheadend.tvhclient.databinding.TimerRecordingAddEditFragmentBinding
import org.tvheadend.tvhclient.ui.base.BaseFragment
import org.tvheadend.tvhclient.ui.common.interfaces.BackPressedInterface
import org.tvheadend.tvhclient.ui.common.interfaces.HideNavigationDrawerInterface
import org.tvheadend.tvhclient.ui.common.interfaces.LayoutControlInterface
import org.tvheadend.tvhclient.ui.features.dvr.*
import org.tvheadend.tvhclient.util.extensions.afterTextChanged
import org.tvheadend.tvhclient.util.extensions.sendSnackbarMessage
import org.tvheadend.tvhclient.util.extensions.visibleOrGone
import timber.log.Timber
class TimerRecordingAddEditFragment : BaseFragment(), BackPressedInterface, RecordingConfigSelectedListener, DatePickerFragment.Listener, TimePickerFragment.Listener, HideNavigationDrawerInterface {
private lateinit var binding: TimerRecordingAddEditFragmentBinding
private lateinit var timerRecordingViewModel: TimerRecordingViewModel
private lateinit var recordingProfilesList: Array<String>
private var profile: ServerProfile? = null
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
binding = TimerRecordingAddEditFragmentBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
timerRecordingViewModel = ViewModelProvider(requireActivity())[TimerRecordingViewModel::class.java]
if (activity is LayoutControlInterface) {
(activity as LayoutControlInterface).forceSingleScreenLayout()
}
recordingProfilesList = timerRecordingViewModel.getRecordingProfileNames()
profile = timerRecordingViewModel.getRecordingProfile()
timerRecordingViewModel.recordingProfileNameId = getSelectedProfileId(profile, recordingProfilesList)
if (savedInstanceState == null) {
timerRecordingViewModel.loadRecordingByIdSync(arguments?.getString("id", "") ?: "")
}
updateUI()
toolbarInterface.setSubtitle("")
toolbarInterface.setTitle(if (timerRecordingViewModel.recording.id.isNotEmpty())
getString(R.string.edit_recording)
else
getString(R.string.add_recording))
}
private fun updateUI() {
val ctx = context ?: return
binding.isEnabled.visibleOrGone(htspVersion >= 19)
binding.isEnabled.isChecked = timerRecordingViewModel.recording.isEnabled
binding.title.setText(timerRecordingViewModel.recording.title)
binding.name.setText(timerRecordingViewModel.recording.name)
binding.directoryLabel.visibleOrGone(htspVersion >= 19)
binding.directory.visibleOrGone(htspVersion >= 19)
binding.directory.setText(timerRecordingViewModel.recording.directory)
binding.channelName.text = timerRecordingViewModel.recording.channelName ?: getString(R.string.all_channels)
binding.channelName.setOnClickListener {
// Determine if the server supports recording on all channels
val allowRecordingOnAllChannels = htspVersion >= 21
handleChannelListSelection(ctx, timerRecordingViewModel.getChannelList(), allowRecordingOnAllChannels, this@TimerRecordingAddEditFragment)
}
binding.priority.text = getPriorityName(ctx, timerRecordingViewModel.recording.priority)
binding.priority.setOnClickListener {
handlePrioritySelection(ctx, timerRecordingViewModel.recording.priority, this@TimerRecordingAddEditFragment)
}
binding.dvrConfig.visibleOrGone(recordingProfilesList.isNotEmpty())
binding.dvrConfigLabel.visibleOrGone(recordingProfilesList.isNotEmpty())
if (recordingProfilesList.isNotEmpty()) {
binding.dvrConfig.text = recordingProfilesList[timerRecordingViewModel.recordingProfileNameId]
binding.dvrConfig.setOnClickListener {
handleRecordingProfileSelection(ctx, recordingProfilesList, timerRecordingViewModel.recordingProfileNameId, this@TimerRecordingAddEditFragment)
}
}
binding.startTime.text = getTimeStringFromTimeInMillis(timerRecordingViewModel.startTimeInMillis)
binding.startTime.setOnClickListener {
handleTimeSelection(activity, timerRecordingViewModel.startTimeInMillis, this@TimerRecordingAddEditFragment, "startTime")
}
binding.stopTime.text = getTimeStringFromTimeInMillis(timerRecordingViewModel.stopTimeInMillis)
binding.stopTime.setOnClickListener {
handleTimeSelection(activity, timerRecordingViewModel.stopTimeInMillis, this@TimerRecordingAddEditFragment, "stopTime")
}
binding.daysOfWeek.text = getSelectedDaysOfWeekText(ctx, timerRecordingViewModel.recording.daysOfWeek)
binding.daysOfWeek.setOnClickListener {
handleDayOfWeekSelection(ctx, timerRecordingViewModel.recording.daysOfWeek, this@TimerRecordingAddEditFragment)
}
binding.timeEnabled.isChecked = timerRecordingViewModel.isTimeEnabled
handleTimeEnabledClick(binding.timeEnabled.isChecked)
binding.timeEnabled.setOnClickListener {
handleTimeEnabledClick(binding.timeEnabled.isChecked)
}
binding.title.afterTextChanged { timerRecordingViewModel.recording.title = it }
binding.name.afterTextChanged { timerRecordingViewModel.recording.name = it }
binding.directory.afterTextChanged { timerRecordingViewModel.recording.directory = it }
binding.isEnabled.setOnCheckedChangeListener { _, isChecked ->
timerRecordingViewModel.recording.isEnabled = isChecked
}
}
private fun handleTimeEnabledClick(checked: Boolean) {
Timber.d("Setting time enabled ${binding.timeEnabled.isChecked}")
timerRecordingViewModel.isTimeEnabled = checked
binding.startTimeLabel.visibleOrGone(checked)
binding.startTime.visibleOrGone(checked)
binding.startTime.isEnabled = checked
binding.stopTimeLabel.visibleOrGone(checked)
binding.stopTime.visibleOrGone(checked)
binding.stopTime.isEnabled = checked
}
override fun onPrepareOptionsMenu(menu: Menu) {
super.onPrepareOptionsMenu(menu)
menu.forEach { it.isVisible = false }
menu.findItem(R.id.menu_save)?.isVisible = true
menu.findItem(R.id.menu_cancel)?.isVisible = true
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
super.onCreateOptionsMenu(menu, inflater)
inflater.inflate(R.menu.save_cancel_options_menu, menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
android.R.id.home -> {
cancel()
true
}
R.id.menu_save -> {
save()
true
}
R.id.menu_cancel -> {
cancel()
true
}
else -> super.onOptionsItemSelected(item)
}
}
private fun save() {
if (timerRecordingViewModel.recording.title.isNullOrEmpty()) {
context?.sendSnackbarMessage(R.string.error_empty_title)
return
}
val intent = timerRecordingViewModel.getIntentData(requireContext(), timerRecordingViewModel.recording)
// Add the recording profile if available and enabled
if (profile != null && htspVersion >= 16 && binding.dvrConfig.text.isNotEmpty()) {
intent.putExtra("configName", binding.dvrConfig.text.toString())
}
// Update the recording in case the id is not empty, otherwise add a new one.
// When adding a new recording, the id is an empty string as a default.
if (timerRecordingViewModel.recording.id.isNotEmpty()) {
intent.action = "updateTimerecEntry"
intent.putExtra("id", timerRecordingViewModel.recording.id)
} else {
intent.action = "addTimerecEntry"
}
activity?.startService(intent)
//activity?.finish()
activity?.supportFragmentManager?.popBackStack()
}
private fun cancel() {
Timber.d("cancel")
// Show confirmation dialog to cancel
context?.let {
MaterialDialog(it).show {
message(R.string.cancel_add_recording)
positiveButton(R.string.discard) {
//activity?.finish()
Timber.d("discarding popping back stack")
activity?.supportFragmentManager?.popBackStack()
}
negativeButton(R.string.cancel) {
Timber.d("dismissing dialog")
dismiss()
}
}
}
}
override fun onChannelSelected(channel: Channel) {
timerRecordingViewModel.recording.channelId = channel.id
binding.channelName.text = channel.name
}
override fun onPrioritySelected(which: Int) {
timerRecordingViewModel.recording.priority = which
context?.let {
binding.priority.text = getPriorityName(it, timerRecordingViewModel.recording.priority)
}
}
override fun onProfileSelected(which: Int) {
binding.dvrConfig.text = recordingProfilesList[which]
timerRecordingViewModel.recordingProfileNameId = which
}
override fun onTimeSelected(milliSeconds: Long, tag: String?) {
if (tag == "startTime") {
timerRecordingViewModel.startTimeInMillis = milliSeconds
// If the start time is after the stop time, update the stop time with the start value
if (milliSeconds > timerRecordingViewModel.stopTimeInMillis) {
timerRecordingViewModel.stopTimeInMillis = milliSeconds
}
} else if (tag == "stopTime") {
timerRecordingViewModel.stopTimeInMillis = milliSeconds
// If the stop time is before the start time, update the start time with the stop value
if (milliSeconds < timerRecordingViewModel.recording.startTimeInMillis) {
timerRecordingViewModel.startTimeInMillis = milliSeconds
}
}
binding.startTime.text = getTimeStringFromTimeInMillis(timerRecordingViewModel.startTimeInMillis)
binding.stopTime.text = getTimeStringFromTimeInMillis(timerRecordingViewModel.stopTimeInMillis)
}
override fun onDateSelected(milliSeconds: Long, tag: String?) {
// NOP
}
override fun onDaysSelected(selectedDays: Int) {
timerRecordingViewModel.recording.daysOfWeek = selectedDays
context?.let {
binding.daysOfWeek.text = getSelectedDaysOfWeekText(it, selectedDays)
}
}
override fun onBackPressed() {
Timber.d("onBackPressed")
cancel()
}
companion object {
fun newInstance(id: String = ""): TimerRecordingAddEditFragment {
val f = TimerRecordingAddEditFragment()
if (id.isNotEmpty()) {
f.arguments = Bundle().also { it.putString("id", id) }
}
return f
}
}
}
| gpl-3.0 | 8f2f15cd1a9d0d06724bd68c1652ec10 | 41.624088 | 198 | 0.697234 | 5.328011 | false | false | false | false |
marciogranzotto/mqtt-painel-kotlin | app/src/main/java/com/granzotto/mqttpainel/activities/AddEditSensorActivity.kt | 1 | 2900 | package com.granzotto.mqttpainel.activities
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.view.View
import com.granzotto.mqttpainel.R
import com.granzotto.mqttpainel.models.SensorObj
import com.granzotto.mqttpainel.utils.ObjectParcer
import com.pawegio.kandroid.textWatcher
import io.realm.Realm
import kotlinx.android.synthetic.main.activity_add_sensor.*
class AddEditSensorActivity : AppCompatActivity() {
companion object {
const val SENSOR = "edit_sensor"
}
private var topic: String? = null
private var name: String? = null
private var sensor: SensorObj? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_add_sensor)
setUpTextWatchers()
sensor = ObjectParcer.getObject(SENSOR) as SensorObj?
if (sensor == null) {
addButton.setOnClickListener { addSensor() }
addButton.visibility = View.VISIBLE
saveButton.visibility = View.GONE
deleteButton.visibility = View.GONE
} else {
saveButton.setOnClickListener { editSensor() }
deleteButton.setOnClickListener { deleteSensor() }
addButton.visibility = View.GONE
saveButton.visibility = View.VISIBLE
deleteButton.visibility = View.VISIBLE
etName.setText(sensor?.name)
etTopic.setText(sensor?.topic)
}
}
private fun deleteSensor() {
val realm = Realm.getDefaultInstance()
realm.beginTransaction()
sensor?.deleteFromRealm()
realm.commitTransaction()
finish()
}
private fun editSensor() {
val realm = Realm.getDefaultInstance()
realm.beginTransaction()
if (topic != null && topic != sensor?.topic) {
sensor?.deleteFromRealm()
realm.commitTransaction()
addSensor()
return
}
if (name != null) sensor?.name = name!!
realm.commitTransaction()
finish()
}
private fun addSensor() {
val realm = Realm.getDefaultInstance()
realm.beginTransaction()
val sensor = realm.createObject(SensorObj::class.java, topic!!)
sensor.name = name!!
realm.commitTransaction()
finish()
}
private fun setUpTextWatchers() {
etTopic.textWatcher {
afterTextChanged { text ->
topic = text.toString().trim()
shouldEnableButton()
}
}
etName.textWatcher {
afterTextChanged { text ->
name = text.toString().trim()
shouldEnableButton()
}
}
}
private fun shouldEnableButton() {
addButton.isEnabled = !topic.isNullOrEmpty() && !name.isNullOrEmpty()
}
}
| gpl-3.0 | e5d4edb60bc4596070d84909c15af492 | 28.896907 | 77 | 0.616897 | 4.87395 | false | false | false | false |
openHPI/android-app | app/src/main/java/de/xikolo/controllers/downloads/DownloadsAdapter.kt | 1 | 4512 | package de.xikolo.controllers.downloads
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import butterknife.BindView
import butterknife.ButterKnife
import de.xikolo.App
import de.xikolo.R
import de.xikolo.utils.MetaSectionList
import de.xikolo.utils.extensions.asFormattedFileSize
import de.xikolo.utils.extensions.fileCount
import de.xikolo.utils.extensions.folderSize
import java.io.File
class DownloadsAdapter(private val callback: OnDeleteButtonClickedListener) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
companion object {
val TAG: String = DownloadsAdapter::class.java.simpleName
private const val ITEM_VIEW_TYPE_HEADER = 0
private const val ITEM_VIEW_TYPE_ITEM = 1
}
private val sectionList: MetaSectionList<String, Any, List<FolderItem>> =
MetaSectionList()
fun addItem(header: String, folder: List<FolderItem>) {
if (folder.isNotEmpty()) {
sectionList.add(header, folder)
notifyDataSetChanged()
}
}
fun clear() {
sectionList.clear()
notifyDataSetChanged()
}
override fun getItemCount(): Int = sectionList.size
override fun getItemViewType(position: Int): Int {
return if (sectionList.isHeader(position)) {
ITEM_VIEW_TYPE_HEADER
} else {
ITEM_VIEW_TYPE_ITEM
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
return if (viewType == ITEM_VIEW_TYPE_HEADER) {
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.item_header_secondary, parent, false)
view.isEnabled = false
view.setOnClickListener(null)
HeaderViewHolder(view)
} else {
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.item_download_list, parent, false)
view.isEnabled = false
view.setOnClickListener(null)
FolderViewHolder(view)
}
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
if (holder is HeaderViewHolder) {
holder.title.text = sectionList.get(position) as String
} else {
val viewHolder = holder as FolderViewHolder
val folderItem = sectionList.get(position) as FolderItem
val context = App.instance
val dir = File(folderItem.path)
viewHolder.textTitle.text = folderItem.title.replace("_".toRegex(), " ")
val numberOfFiles = dir.fileCount.toLong()
viewHolder.textButtonDelete.setOnClickListener {
callback.onDeleteButtonClicked(
folderItem
)
}
if (numberOfFiles > 0) {
viewHolder.textSubTitle.text = numberOfFiles.toString() + " " + context.getString(R.string.files) + ": " + dir.folderSize.asFormattedFileSize
viewHolder.textButtonDelete.visibility = View.VISIBLE
} else {
viewHolder.textSubTitle.text = numberOfFiles.toString() + " " + context.getString(R.string.files)
viewHolder.textButtonDelete.visibility = View.GONE
}
if (position == itemCount - 1 || sectionList.isHeader(position + 1)) {
viewHolder.viewDivider.visibility = View.INVISIBLE
} else {
viewHolder.viewDivider.visibility = View.VISIBLE
}
}
}
class FolderItem(val title: String, val path: String)
interface OnDeleteButtonClickedListener {
fun onDeleteButtonClicked(item: FolderItem)
}
internal class FolderViewHolder(view: View) : RecyclerView.ViewHolder(view) {
@BindView(R.id.textTitle)
lateinit var textTitle: TextView
@BindView(R.id.textSubTitle)
lateinit var textSubTitle: TextView
@BindView(R.id.buttonDelete)
lateinit var textButtonDelete: TextView
@BindView(R.id.divider)
lateinit var viewDivider: View
init {
ButterKnife.bind(this, view)
}
}
internal class HeaderViewHolder(view: View) : RecyclerView.ViewHolder(view) {
@BindView(R.id.textHeader)
lateinit var title: TextView
init {
ButterKnife.bind(this, view)
}
}
}
| bsd-3-clause | 4e61c82e47dfb6f4bbeaa5ca940eecca | 30.552448 | 157 | 0.638298 | 4.739496 | false | false | false | false |
donald-w/Anki-Android | AnkiDroid/src/main/java/com/ichi2/anki/CustomMaterialTapTargetPromptBuilder.kt | 1 | 4662 | /****************************************************************************************
* *
* Copyright (c) 2021 Shridhar Goel <[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 com.ichi2.anki
import android.app.Activity
import androidx.core.content.ContextCompat
import com.ichi2.anki.PromptBackgroundAdapter.Companion.toPromptBackground
import com.ichi2.utils.DimmedPromptBackgroundDecorator
import uk.co.samuelwall.materialtaptargetprompt.MaterialTapTargetPrompt
import uk.co.samuelwall.materialtaptargetprompt.extras.backgrounds.CirclePromptBackground
import uk.co.samuelwall.materialtaptargetprompt.extras.backgrounds.RectanglePromptBackground
import uk.co.samuelwall.materialtaptargetprompt.extras.focals.CirclePromptFocal
import uk.co.samuelwall.materialtaptargetprompt.extras.focals.RectanglePromptFocal
class CustomMaterialTapTargetPromptBuilder<T>(val activity: Activity, val featureIdentifier: T) : MaterialTapTargetPrompt.Builder(activity) where T : Enum<T>, T : OnboardingFlag {
companion object {
private const val NIGHT_MODE_PREFERENCE = "invertedColors"
}
fun createRectangle(): CustomMaterialTapTargetPromptBuilder<T> {
promptFocal = RectanglePromptFocal()
return this
}
fun createRectangleWithDimmedBackground(): CustomMaterialTapTargetPromptBuilder<T> {
promptBackground = DimmedPromptBackgroundDecorator(RectanglePromptBackground()).toPromptBackground()
return createRectangle()
}
fun createCircle(): CustomMaterialTapTargetPromptBuilder<T> {
promptFocal = CirclePromptFocal()
return this
}
fun createCircleWithDimmedBackground(): CustomMaterialTapTargetPromptBuilder<T> {
promptBackground = DimmedPromptBackgroundDecorator(CirclePromptBackground()).toPromptBackground()
return createCircle()
}
fun setFocalColourResource(focalColourRes: Int): CustomMaterialTapTargetPromptBuilder<T> {
focalColour = ContextCompat.getColor(activity, focalColourRes)
return this
}
/**
* Handle dismissal of a tutorial.
* Currently it happens when the user clicks anywhere while a tutorial is being shown.
* @param tutorialFunction Function which would be called when tutorial is dismissed.
* @return Builder object to allow chaining of method calls
*/
fun setDismissedListener(tutorialFunction: () -> Unit): CustomMaterialTapTargetPromptBuilder<T> {
setPromptStateChangeListener { _, state ->
if (state == MaterialTapTargetPrompt.STATE_DISMISSED) {
tutorialFunction()
}
}
return this
}
/**
* Mark as visited and show the tutorial.
*/
override fun show(): MaterialTapTargetPrompt? {
/* Keep the focal colour as transparent for night mode
so that the contents being highlighted are visible properly */
if (AnkiDroidApp.getSharedPrefs(activity).getBoolean(NIGHT_MODE_PREFERENCE, false)) {
setFocalColourResource(R.color.transparent)
}
// Clicking outside the prompt area should not trigger a click on the underlying view
// This will prevent click on any outside view when user tries to dismiss the feature prompt
captureTouchEventOutsidePrompt = true
OnboardingUtils.setVisited(featureIdentifier, activity)
return super.show()
}
}
| gpl-3.0 | b93de00def2755e1378b10141b2d9e96 | 48.595745 | 179 | 0.626555 | 5.244094 | false | false | false | false |
SirWellington/alchemy-generator | src/main/java/tech/sirwellington/alchemy/generator/BinaryGenerators.kt | 1 | 2895 | /*
* Copyright © 2019. Sir Wellington.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
*
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package tech.sirwellington.alchemy.generator
import org.apache.commons.lang3.RandomUtils
import tech.sirwellington.alchemy.annotations.access.NonInstantiable
import tech.sirwellington.alchemy.annotations.designs.patterns.StrategyPattern
import tech.sirwellington.alchemy.annotations.designs.patterns.StrategyPattern.Role.CONCRETE_BEHAVIOR
import java.nio.ByteBuffer
/**
* [Alchemy Generators][AlchemyGenerator] for raw binary (`byte[]`).
*
* @author SirWellington
*/
@NonInstantiable
@StrategyPattern(role = CONCRETE_BEHAVIOR)
class BinaryGenerators
@Throws(IllegalAccessException::class)
internal constructor()
{
init
{
throw IllegalAccessException("cannot instantiate this class")
}
companion object
{
/**
* Generates binary of the specified length
*
* @param length The size of the byte arrays created.
*
*
* @return A binary generator
*
* @throws IllegalArgumentException If `length < 0`.
*/
@JvmStatic
@Throws(IllegalArgumentException::class)
fun binary(length: Int): AlchemyGenerator<ByteArray>
{
checkThat(length >= 0, "length must be >= 0")
return AlchemyGenerator { RandomUtils.nextBytes(length) }
}
/**
* Generates a [ByteBuffer] of the specified length.
*
* @param size The desired size of the Byte Buffer.
*
* @return
*
* @throws IllegalArgumentException If `size < 0`.
*/
@Throws(IllegalArgumentException::class)
@JvmStatic
fun byteBuffers(size: Int): AlchemyGenerator<ByteBuffer>
{
checkThat(size >= 0, "size must be at least 0")
val delegate = binary(size)
return AlchemyGenerator {
val binary = delegate.get()
ByteBuffer.wrap(binary)
}
}
@JvmStatic
fun bytes(): AlchemyGenerator<Byte>
{
val delegate = binary(1)
return AlchemyGenerator {
val array = delegate.get()
checkThat(array != null && array.isNotEmpty(), "no Byte available to return.")
array[0]
}
}
}
}
| apache-2.0 | 182bee5ab9a5caf80aa068392ca47a4d | 28.232323 | 101 | 0.62716 | 4.752053 | false | false | false | false |
pennlabs/penn-mobile-android | PennMobile/src/main/java/com/pennapps/labs/pennmobile/classes/GSRRoom.kt | 1 | 734 | package com.pennapps.labs.pennmobile.classes
import com.google.gson.annotations.Expose
import com.google.gson.annotations.SerializedName
/**
* Created by Varun on 10/14/2018.
*/
class GSRRoom {
//getters
@SerializedName("capacity")
@Expose
var capacity: Int? = null
@SerializedName("gid")
@Expose
var gid: Int? = null
@SerializedName("lid")
@Expose
var lid: Int? = null
@SerializedName("room_name")
@Expose
var name: String? = null
@SerializedName("id")
@Expose
var room_id: Int? = null
@SerializedName("thumbnail")
@Expose
var thumbnail: String? = null
@SerializedName("availability")
@Expose
var slots: Array<GSRSlot>? = null
} | mit | 2ba3649ccfd6a8a9594d7836059ef9ce | 15.333333 | 49 | 0.640327 | 3.842932 | false | false | false | false |
wikimedia/apps-android-wikipedia | app/src/main/java/org/wikipedia/settings/LogoutPreference.kt | 1 | 1853 | package org.wikipedia.settings
import android.app.Activity
import android.content.Context
import android.util.AttributeSet
import android.widget.Button
import android.widget.TextView
import androidx.appcompat.app.AlertDialog
import androidx.preference.Preference
import androidx.preference.PreferenceViewHolder
import org.wikipedia.R
import org.wikipedia.WikipediaApp
import org.wikipedia.auth.AccountUtil
@Suppress("unused")
class LogoutPreference : Preference {
constructor(ctx: Context, attrs: AttributeSet?, defStyle: Int) : super(ctx, attrs, defStyle)
constructor(ctx: Context, attrs: AttributeSet?) : super(ctx, attrs)
constructor(ctx: Context) : super(ctx)
var activity: Activity? = null
init {
layoutResource = R.layout.view_preference_logout
}
override fun onBindViewHolder(holder: PreferenceViewHolder) {
super.onBindViewHolder(holder)
holder.itemView.isClickable = false
holder.itemView.findViewById<TextView>(R.id.accountName).text = AccountUtil.userName
holder.itemView.findViewById<Button>(R.id.logoutButton).setOnClickListener { view ->
activity?.let {
AlertDialog.Builder(it)
.setMessage(R.string.logout_prompt)
.setNegativeButton(R.string.logout_dialog_cancel_button_text, null)
.setPositiveButton(R.string.preference_title_logout) { _, _ ->
WikipediaApp.instance.logOut()
Prefs.readingListsLastSyncTime = null
Prefs.isReadingListSyncEnabled = false
Prefs.isSuggestedEditsHighestPriorityEnabled = false
it.setResult(SettingsActivity.ACTIVITY_RESULT_LOG_OUT)
it.finish()
}.show()
}
}
}
}
| apache-2.0 | dadedcd31e2456a507cfbb91e9fb9f33 | 38.425532 | 96 | 0.663788 | 4.954545 | false | false | false | false |
pyamsoft/padlock | padlock/src/main/java/com/pyamsoft/padlock/list/LockListViewModel.kt | 1 | 6717 | /*
* Copyright 2019 Peter Kenji Yamanaka
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.pyamsoft.padlock.list
import androidx.annotation.CheckResult
import com.pyamsoft.padlock.api.LockListInteractor
import com.pyamsoft.padlock.api.service.LockServiceInteractor
import com.pyamsoft.padlock.api.service.LockServiceInteractor.ServiceState
import com.pyamsoft.padlock.model.LockState
import com.pyamsoft.padlock.model.LockState.DEFAULT
import com.pyamsoft.padlock.model.LockState.LOCKED
import com.pyamsoft.padlock.model.LockWhitelistedEvent
import com.pyamsoft.padlock.model.db.PadLockDbModels
import com.pyamsoft.padlock.model.list.AppEntry
import com.pyamsoft.padlock.model.list.ListDiffProvider
import com.pyamsoft.padlock.model.list.LockListUpdatePayload
import com.pyamsoft.padlock.model.pin.CreatePinEvent
import com.pyamsoft.padlock.pin.ClearPinPresenterImpl.ClearPinEvent
import com.pyamsoft.pydroid.core.bus.EventBus
import com.pyamsoft.pydroid.core.bus.Listener
import com.pyamsoft.pydroid.core.threads.Enforcer
import com.pyamsoft.pydroid.core.tryDispose
import io.reactivex.Single
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.disposables.Disposables
import io.reactivex.schedulers.Schedulers
import timber.log.Timber
import javax.inject.Inject
class LockListViewModel @Inject internal constructor(
private val enforcer: Enforcer,
private val lockListInteractor: LockListInteractor,
private val serviceInteractor: LockServiceInteractor,
private val lockListBus: EventBus<LockListEvent>,
private val lockWhitelistedBus: Listener<LockWhitelistedEvent>,
private val createPinBus: Listener<CreatePinEvent>,
private val listDiffProvider: ListDiffProvider<AppEntry>
) {
@CheckResult
fun onDatabaseChangeEvent(
onChange: (payload: LockListUpdatePayload) -> Unit,
onError: (error: Throwable) -> Unit
): Disposable {
return lockListInteractor.subscribeForUpdates(listDiffProvider)
.unsubscribeOn(Schedulers.io())
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe({ onChange(it) }, {
Timber.e(it, "Error while subscribed to database changes")
onError(it)
})
}
@CheckResult
fun onLockEvent(
onWhitelist: (event: LockWhitelistedEvent) -> Unit,
onError: (error: Throwable) -> Unit
): Disposable {
val whitelistDisposable = lockWhitelistedBus.listen()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe { onWhitelist(it) }
val errorDisposable = lockListBus.listen()
.flatMapSingle { modifyDatabaseEntry(it.isChecked, it.packageName, it.code, it.isSystem) }
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.doOnError {
Timber.e(it, "Error occurred modifying database entry")
onError(it)
}
.onErrorReturnItem(Unit)
.subscribe()
return object : Disposable {
override fun isDisposed(): Boolean {
return whitelistDisposable.isDisposed && errorDisposable.isDisposed
}
override fun dispose() {
whitelistDisposable.tryDispose()
errorDisposable.tryDispose()
}
}
}
@CheckResult
internal fun onClearPinEvent(onClear: (event: ClearPinEvent) -> Unit): Disposable {
return Disposables.empty()
// return clearPinBus.listen()
// .subscribeOn(Schedulers.io())
// .observeOn(AndroidSchedulers.mainThread())
// .subscribe(onClear)
}
@CheckResult
fun onCreatePinEvent(onCreate: (event: CreatePinEvent) -> Unit): Disposable {
return createPinBus.listen()
.subscribe(onCreate)
}
@CheckResult
private fun modifyDatabaseEntry(
isChecked: Boolean,
packageName: String,
code: String?,
system: Boolean
): Single<Unit> {
return Single.defer {
enforcer.assertNotOnMainThread()
// No whitelisting for modifications from the List
val oldState: LockState
val newState: LockState
if (isChecked) {
oldState = DEFAULT
newState = LOCKED
} else {
oldState = LOCKED
newState = DEFAULT
}
return@defer lockListInteractor.modifyEntry(
oldState, newState, packageName,
PadLockDbModels.PACKAGE_ACTIVITY_NAME, code, system
)
.andThen(Single.just(Unit))
.subscribeOn(Schedulers.io())
.observeOn(Schedulers.io())
}
.subscribeOn(Schedulers.io())
.observeOn(Schedulers.io())
}
@CheckResult
fun onFabStateChange(onChange: (state: ServiceState) -> Unit): Disposable {
return serviceInteractor.observeServiceState()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(onChange)
}
@CheckResult
fun checkFabState(onChecked: (state: ServiceState) -> Unit): Disposable {
return serviceInteractor.isServiceEnabled()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(onChecked)
}
@CheckResult
fun onSystemVisibilityChanged(onChange: (visible: Boolean) -> Unit): Disposable {
return lockListInteractor.watchSystemVisible()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(onChange)
}
fun setSystemVisibility(visible: Boolean) {
lockListInteractor.setSystemVisible(visible)
}
@CheckResult
fun populateList(
force: Boolean,
onPopulateBegin: (forced: Boolean) -> Unit,
onPopulateSuccess: (appList: List<AppEntry>) -> Unit,
onPopulateError: (error: Throwable) -> Unit,
onPopulateComplete: () -> Unit
): Disposable {
return lockListInteractor.fetchAppEntryList(force)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.doAfterTerminate { onPopulateComplete() }
.doOnSubscribe { onPopulateBegin(force) }
.subscribe({ onPopulateSuccess(it) }, {
Timber.e(it, "LockListPresenter populateList error")
onPopulateError(it)
})
}
}
| apache-2.0 | a6d524863b77f29effe7bb62bcd96132 | 32.585 | 98 | 0.7152 | 4.472037 | false | false | false | false |
exponent/exponent | packages/expo-error-recovery/android/src/test/java/expo/modules/errorrecovery/ErrorRecoveryModuleTest.kt | 2 | 2357 | package expo.modules.errorrecovery
import androidx.test.core.app.ApplicationProvider
import org.junit.Assert.assertEquals
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.assertNull
import org.robolectric.RobolectricTestRunner
import org.unimodules.test.core.PromiseMock
import org.unimodules.test.core.assertResolved
private const val RECOVERY_STORE_KEY = "recoveredProps"
@RunWith(RobolectricTestRunner::class)
internal class ErrorRecoveryModuleTest {
@Test
fun `saveRecoveryProps resolves provided promise when props=null`() {
val module = ErrorRecoveryModule(ApplicationProvider.getApplicationContext())
val promise = PromiseMock()
module.saveRecoveryProps(null, promise)
assertResolved(promise)
}
@Test
fun `saveRecoveryProps resolves provided promise with null when props=null`() {
val module = ErrorRecoveryModule(ApplicationProvider.getApplicationContext())
val promise = PromiseMock()
module.saveRecoveryProps(null, promise)
assertResolved(promise)
assertNull(promise.resolveValue)
}
@Test
fun `saveRecoveryProps resolves provided promise when props!=null`() {
val module = ErrorRecoveryModule(ApplicationProvider.getApplicationContext())
val promise = PromiseMock()
module.saveRecoveryProps("coding is fun they said", promise)
assertResolved(promise)
}
@Test
fun `saveRecoveryProps resolves provided promise with null when props!=null`() {
val module = ErrorRecoveryModule(ApplicationProvider.getApplicationContext())
val promise = PromiseMock()
module.saveRecoveryProps("coding is fun they said", promise)
assertResolved(promise)
assertNull(promise.resolveValue)
}
@Test
fun `props are saved when props!=null`() {
val promise = PromiseMock()
val mockProps = "test props"
val module = ErrorRecoveryModule(ApplicationProvider.getApplicationContext())
module.saveRecoveryProps(mockProps, promise)
val constants = module.constants
assertEquals(constants[RECOVERY_STORE_KEY], mockProps)
}
@Test
fun `props are saved when props=null`() {
val promise = PromiseMock()
val module = ErrorRecoveryModule(ApplicationProvider.getApplicationContext())
module.saveRecoveryProps(null, promise)
val constants = module.constants
assertNull(constants[RECOVERY_STORE_KEY])
}
}
| bsd-3-clause | f989d7778c717fac1a75442a9802f401 | 33.661765 | 82 | 0.767501 | 4.621569 | false | true | false | false |
AndroidX/androidx | camera/camera-camera2-pipe-integration/src/test/java/androidx/camera/camera2/pipe/integration/interop/Camera2CameraInfoTest.kt | 3 | 8340 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.camera.camera2.pipe.integration.interop
import android.hardware.camera2.CameraCharacteristics
import android.os.Build
import android.util.Size
import androidx.camera.camera2.pipe.CameraId
import androidx.camera.camera2.pipe.integration.adapter.CameraControlStateAdapter
import androidx.camera.camera2.pipe.integration.adapter.CameraInfoAdapter
import androidx.camera.camera2.pipe.integration.adapter.CameraStateAdapter
import androidx.camera.camera2.pipe.integration.adapter.RobolectricCameraPipeTestRunner
import androidx.camera.camera2.pipe.integration.config.CameraConfig
import androidx.camera.camera2.pipe.integration.impl.CameraCallbackMap
import androidx.camera.camera2.pipe.integration.impl.CameraProperties
import androidx.camera.camera2.pipe.integration.impl.EvCompControl
import androidx.camera.camera2.pipe.integration.impl.TorchControl
import androidx.camera.camera2.pipe.integration.impl.UseCaseThreads
import androidx.camera.camera2.pipe.integration.impl.ZoomControl
import androidx.camera.camera2.pipe.integration.testing.FakeCameraProperties
import androidx.camera.camera2.pipe.integration.testing.FakeEvCompCompat
import androidx.camera.camera2.pipe.integration.testing.FakeZoomCompat
import androidx.camera.camera2.pipe.testing.FakeCameraMetadata
import androidx.camera.core.CameraState
import androidx.camera.core.ExposureState
import androidx.camera.core.ZoomState
import androidx.camera.core.impl.CamcorderProfileProvider
import androidx.camera.core.impl.CameraCaptureCallback
import androidx.camera.core.impl.CameraInfoInternal
import androidx.camera.core.impl.Quirks
import androidx.camera.core.impl.Timebase
import androidx.lifecycle.LiveData
import com.google.common.truth.Truth
import com.google.common.util.concurrent.MoreExecutors
import java.util.concurrent.Executor
import kotlinx.coroutines.CoroutineName
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.asCoroutineDispatcher
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.annotation.Config
@RunWith(RobolectricCameraPipeTestRunner::class)
@Config(minSdk = Build.VERSION_CODES.LOLLIPOP)
@OptIn(ExperimentalCamera2Interop::class)
class Camera2CameraInfoTest {
private val useCaseThreads by lazy {
val executor = MoreExecutors.directExecutor()
val dispatcher = executor.asCoroutineDispatcher()
val cameraScope = CoroutineScope(
SupervisorJob() +
dispatcher +
CoroutineName("UseCaseSurfaceManagerTest")
)
UseCaseThreads(
cameraScope,
executor,
dispatcher
)
}
@Test
fun canGetId_fromCamera2CameraInfo() {
val cameraId = "42"
val camera2CameraInfo =
Camera2CameraInfo.from(createCameraInfoAdapter(cameraId = CameraId(cameraId)))
val extractedId: String = camera2CameraInfo.getCameraId()
// Assert.
Truth.assertThat(extractedId).isEqualTo(cameraId)
}
@Test
fun canExtractCharacteristics_fromCamera2CameraInfo() {
val cameraHardwareLevel = CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_FULL
val camera2CameraInfo = Camera2CameraInfo.from(
createCameraInfoAdapter(
cameraProperties = FakeCameraProperties(
FakeCameraMetadata(
characteristics = mapOf(
CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL to
cameraHardwareLevel
)
)
)
)
)
val hardwareLevel: Int? = camera2CameraInfo.getCameraCharacteristic<Int>(
CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL
)
// Assert.
Truth.assertThat(hardwareLevel).isEqualTo(
CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_FULL
)
}
@Test
fun canGetCamera2CameraInfo() {
val cameraInfoAdapter = createCameraInfoAdapter()
val camera2CameraInfo: Camera2CameraInfo = cameraInfoAdapter.camera2CameraInfo
val resultCamera2CameraInfo: Camera2CameraInfo = Camera2CameraInfo.from(cameraInfoAdapter)
// Assert.
Truth.assertThat(resultCamera2CameraInfo).isEqualTo(camera2CameraInfo)
}
@Test(expected = IllegalArgumentException::class)
fun fromCameraInfoThrows_whenNotCamera2Impl() {
val wrongCameraInfo = object : CameraInfoInternal {
override fun getSensorRotationDegrees(): Int {
throw NotImplementedError("Not used in testing")
}
override fun getSensorRotationDegrees(relativeRotation: Int): Int {
throw NotImplementedError("Not used in testing")
}
override fun hasFlashUnit(): Boolean {
throw NotImplementedError("Not used in testing")
}
override fun getTorchState(): LiveData<Int> {
throw NotImplementedError("Not used in testing")
}
override fun getZoomState(): LiveData<ZoomState> {
throw NotImplementedError("Not used in testing")
}
override fun getExposureState(): ExposureState {
throw NotImplementedError("Not used in testing")
}
override fun getCameraState(): LiveData<CameraState> {
throw NotImplementedError("Not used in testing")
}
override fun getImplementationType(): String {
throw NotImplementedError("Not used in testing")
}
override fun getLensFacing(): Int? {
throw NotImplementedError("Not used in testing")
}
override fun getCameraId(): String {
throw NotImplementedError("Not used in testing")
}
override fun addSessionCaptureCallback(
executor: Executor,
callback: CameraCaptureCallback
) {
throw NotImplementedError("Not used in testing")
}
override fun removeSessionCaptureCallback(callback: CameraCaptureCallback) {
throw NotImplementedError("Not used in testing")
}
override fun getCameraQuirks(): Quirks {
throw NotImplementedError("Not used in testing")
}
override fun getCamcorderProfileProvider(): CamcorderProfileProvider {
throw NotImplementedError("Not used in testing")
}
override fun getTimebase(): Timebase {
throw NotImplementedError("Not used in testing")
}
override fun getSupportedResolutions(format: Int): MutableList<Size> {
throw NotImplementedError("Not used in testing")
}
}
Camera2CameraInfo.from(wrongCameraInfo)
}
private fun createCameraInfoAdapter(
cameraId: CameraId = CameraId("0"),
cameraProperties: CameraProperties = FakeCameraProperties(cameraId = cameraId),
): CameraInfoAdapter {
return CameraInfoAdapter(
cameraProperties,
CameraConfig(cameraId),
CameraStateAdapter(),
CameraControlStateAdapter(
ZoomControl(FakeZoomCompat()),
EvCompControl(FakeEvCompCompat()),
TorchControl(cameraProperties, useCaseThreads),
),
CameraCallbackMap(),
)
}
// TODO: Port https://android-review.googlesource.com/c/platform/frameworks/support/+/1757509
// for extension features.
} | apache-2.0 | 28aa0b627808bb871bcb15b2ff25bb7d | 37.086758 | 98 | 0.683453 | 5.281824 | false | true | false | false |
exponent/exponent | android/versioned-abis/expoview-abi43_0_0/src/main/java/abi43_0_0/expo/modules/speech/LanguageUtils.kt | 2 | 1243 | package abi43_0_0.expo.modules.speech
import java.util.*
// Lazy load the ISO codes into a Map then transform the codes to match other localization patterns in Expo
object LanguageUtils {
private val countryISOCodes: Map<String, Locale> by lazy {
Locale.getISOCountries().map { country ->
val locale = Locale("", country)
locale.getISO3Country().toUpperCase(locale) to locale
}.toMap()
}
private val languageISOCodes: Map<String, Locale> by lazy {
Locale.getISOLanguages().map { language ->
val locale = Locale(language)
locale.getISO3Language() to locale
}.toMap()
}
// NOTE: These helpers are null-unsafe and should be called ONLY with codes
// returned by Locale.getISO3Country() and Locale.getISO3Language() respectively
private fun transformCountryISO(code: String) = countryISOCodes[code]!!.country
private fun transformLanguageISO(code: String) = languageISOCodes[code]!!.language
fun getISOCode(locale: Locale): String {
var language = transformLanguageISO(locale.getISO3Language())
val country = locale.getISO3Country()
if (country != "") {
val countryCode = transformCountryISO(country)
language += "-$countryCode"
}
return language
}
}
| bsd-3-clause | 070120ea2c98b9e99931e8f513a16104 | 35.558824 | 107 | 0.714401 | 4.10231 | false | false | false | false |
Undin/intellij-rust | src/main/kotlin/org/rust/cargo/project/model/impl/CargoProjectImpl.kt | 2 | 31413 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.cargo.project.model.impl
import com.intellij.codeInsight.daemon.DaemonCodeAnalyzer
import com.intellij.execution.RunManager
import com.intellij.ide.impl.isTrusted
import com.intellij.notification.NotificationType
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.invokeAndWaitIfNeeded
import com.intellij.openapi.application.invokeLater
import com.intellij.openapi.application.runWriteAction
import com.intellij.openapi.components.*
import com.intellij.openapi.externalSystem.autoimport.AutoImportProjectTracker
import com.intellij.openapi.externalSystem.autoimport.ExternalSystemProjectTracker
import com.intellij.openapi.fileTypes.FileTypeManager
import com.intellij.openapi.module.Module
import com.intellij.openapi.module.ModuleUtilCore
import com.intellij.openapi.progress.ProcessCanceledException
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.ex.ProjectEx
import com.intellij.openapi.roots.ModuleRootManager
import com.intellij.openapi.roots.ModuleRootModificationUtil
import com.intellij.openapi.roots.ProjectFileIndex
import com.intellij.openapi.roots.ex.ProjectRootManagerEx
import com.intellij.openapi.startup.StartupManager
import com.intellij.openapi.util.EmptyRunnable
import com.intellij.openapi.util.UserDataHolderBase
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.vfs.VirtualFileManager
import com.intellij.openapi.wm.ToolWindowManager
import com.intellij.psi.PsiManager
import com.intellij.util.indexing.LightDirectoryIndex
import com.intellij.util.io.exists
import com.intellij.util.io.systemIndependentPath
import org.jdom.Element
import org.jetbrains.annotations.TestOnly
import org.rust.cargo.CargoConstants
import org.rust.cargo.project.model.*
import org.rust.cargo.project.model.CargoProject.UpdateStatus
import org.rust.cargo.project.model.CargoProjectsService.CargoProjectsListener
import org.rust.cargo.project.model.CargoProjectsService.CargoRefreshStatus
import org.rust.cargo.project.settings.RustProjectSettingsService
import org.rust.cargo.project.settings.RustProjectSettingsService.RustSettingsChangedEvent
import org.rust.cargo.project.settings.RustProjectSettingsService.RustSettingsListener
import org.rust.cargo.project.settings.rustSettings
import org.rust.cargo.project.settings.toolchain
import org.rust.cargo.project.toolwindow.CargoToolWindow.Companion.initializeToolWindow
import org.rust.cargo.project.workspace.*
import org.rust.cargo.runconfig.command.workingDirectory
import org.rust.cargo.toolchain.RsToolchainBase
import org.rust.cargo.util.AutoInjectedCrates
import org.rust.ide.notifications.showBalloon
import org.rust.lang.RsFileType
import org.rust.lang.core.macros.macroExpansionManager
import org.rust.lang.core.macros.proc.ProcMacroServerPool
import org.rust.openapiext.TaskResult
import org.rust.openapiext.isUnitTestMode
import org.rust.openapiext.modules
import org.rust.openapiext.pathAsPath
import org.rust.stdext.AsyncValue
import org.rust.stdext.applyWithSymlink
import org.rust.stdext.exhaustive
import org.rust.stdext.mapNotNullToSet
import org.rust.taskQueue
import java.nio.file.Path
import java.nio.file.Paths
import java.util.concurrent.CompletableFuture
import java.util.concurrent.CompletionException
import java.util.concurrent.atomic.AtomicReference
@State(name = "CargoProjects", storages = [
Storage(StoragePathMacros.WORKSPACE_FILE),
Storage("misc.xml", deprecated = true)
])
open class CargoProjectsServiceImpl(
final override val project: Project
) : CargoProjectsService, PersistentStateComponent<Element>, Disposable {
init {
val newProjectModelImportEnabled = isNewProjectModelImportEnabled
if (newProjectModelImportEnabled) {
@Suppress("LeakingThis")
registerProjectAware(project, this)
}
with(project.messageBus.connect()) {
if (!newProjectModelImportEnabled) {
if (!isUnitTestMode) {
subscribe(VirtualFileManager.VFS_CHANGES, CargoTomlWatcher(this@CargoProjectsServiceImpl, fun() {
if (!project.rustSettings.autoUpdateEnabled) return
refreshAllProjects()
}))
}
subscribe(RustProjectSettingsService.RUST_SETTINGS_TOPIC, object : RustSettingsListener {
override fun rustSettingsChanged(e: RustSettingsChangedEvent) {
if (e.affectsCargoMetadata) {
refreshAllProjects()
}
}
})
}
subscribe(CargoProjectsService.CARGO_PROJECTS_TOPIC, CargoProjectsListener { _, _ ->
StartupManager.getInstance(project).runAfterOpened {
// TODO: provide a proper solution instead of using `invokeLater`
ToolWindowManager.getInstance(project).invokeLater {
initializeToolWindow(project)
}
}
})
}
}
/**
* The heart of the plugin Project model. Care must be taken to ensure
* this is thread-safe, and that refreshes are scheduled after
* set of projects changes.
*/
private val projects = AsyncValue<List<CargoProjectImpl>>(emptyList())
@Suppress("LeakingThis")
private val noProjectMarker = CargoProjectImpl(Paths.get(""), this)
/**
* [directoryIndex] allows to quickly map from a [VirtualFile] to
* a containing [CargoProject].
*/
private val directoryIndex: LightDirectoryIndex<CargoProjectImpl> =
LightDirectoryIndex(project, noProjectMarker) { index ->
val visited = mutableSetOf<VirtualFile>()
fun VirtualFile.put(cargoProject: CargoProjectImpl) {
if (this in visited) return
visited += this
index.putInfo(this, cargoProject)
}
fun CargoWorkspace.Package.put(cargoProject: CargoProjectImpl) {
contentRoot?.put(cargoProject)
outDir?.put(cargoProject)
for (additionalRoot in additionalRoots()) {
additionalRoot.put(cargoProject)
}
for (target in targets) {
target.crateRoot?.parent?.put(cargoProject)
}
}
val lowPriority = mutableListOf<Pair<CargoWorkspace.Package, CargoProjectImpl>>()
for (cargoProject in projects.currentState) {
cargoProject.rootDir?.put(cargoProject)
for (pkg in cargoProject.workspace?.packages.orEmpty()) {
if (pkg.origin == PackageOrigin.WORKSPACE) {
pkg.put(cargoProject)
} else {
lowPriority += pkg to cargoProject
}
}
}
for ((pkg, cargoProject) in lowPriority) {
pkg.put(cargoProject)
}
}
@Suppress("LeakingThis")
private val packageIndex: CargoPackageIndex = CargoPackageIndex(project, this)
override val allProjects: Collection<CargoProject>
get() = projects.currentState
override val hasAtLeastOneValidProject: Boolean
get() = hasAtLeastOneValidProject(allProjects)
// Guarded by the platform RWLock
override var initialized: Boolean = false
private var isLegacyRustNotificationShowed: Boolean = false
private fun registerProjectAware(project: Project, disposable: Disposable) {
// There is no sense to register `CargoExternalSystemProjectAware` for default project.
// Moreover, it may break searchable options building
if (project.isDefault) return
val cargoProjectAware = CargoExternalSystemProjectAware(project)
val projectTracker = ExternalSystemProjectTracker.getInstance(project)
projectTracker.register(cargoProjectAware, disposable)
projectTracker.activate(cargoProjectAware.projectId)
project.messageBus.connect(disposable)
.subscribe(RustProjectSettingsService.RUST_SETTINGS_TOPIC, object : RustSettingsListener {
override fun rustSettingsChanged(e: RustSettingsChangedEvent) {
if (e.affectsCargoMetadata) {
val tracker = AutoImportProjectTracker.getInstance(project)
tracker.markDirty(cargoProjectAware.projectId)
tracker.scheduleProjectRefresh()
}
}
})
}
override fun findProjectForFile(file: VirtualFile): CargoProject? =
file.applyWithSymlink { directoryIndex.getInfoForFile(it).takeIf { info -> info !== noProjectMarker } }
override fun findPackageForFile(file: VirtualFile): CargoWorkspace.Package? =
file.applyWithSymlink(packageIndex::findPackageForFile)
override fun attachCargoProject(manifest: Path): Boolean {
if (isExistingProject(allProjects, manifest)) return false
modifyProjects { projects ->
if (isExistingProject(projects, manifest))
CompletableFuture.completedFuture(projects)
else
doRefresh(project, projects + CargoProjectImpl(manifest, this))
}
return true
}
override fun attachCargoProjects(vararg manifests: Path) {
val manifests2 = manifests.filter { !isExistingProject(allProjects, it) }
if (manifests2.isEmpty()) return
modifyProjects { projects ->
val newManifests3 = manifests2.filter { !isExistingProject(projects, it) }
if (newManifests3.isEmpty())
CompletableFuture.completedFuture(projects)
else
doRefresh(project, projects + newManifests3.map { CargoProjectImpl(it, this) })
}
}
override fun detachCargoProject(cargoProject: CargoProject) {
modifyProjects { projects ->
CompletableFuture.completedFuture(projects.filter { it.manifest != cargoProject.manifest })
}
}
override fun refreshAllProjects(): CompletableFuture<out List<CargoProject>> =
modifyProjects { doRefresh(project, it) }
override fun discoverAndRefresh(): CompletableFuture<out List<CargoProject>> {
val guessManifest = suggestManifests().firstOrNull()
?: return CompletableFuture.completedFuture(projects.currentState)
return modifyProjects { projects ->
if (hasAtLeastOneValidProject(projects)) return@modifyProjects CompletableFuture.completedFuture(projects)
doRefresh(project, listOf(CargoProjectImpl(guessManifest.pathAsPath, this)))
}
}
override fun suggestManifests(): Sequence<VirtualFile> =
project.modules
.asSequence()
.flatMap { ModuleRootManager.getInstance(it).contentRoots.asSequence() }
.mapNotNull { it.findChild(CargoConstants.MANIFEST_FILE) }
/**
* Modifies [CargoProject.userDisabledFeatures] that eventually affects [CargoWorkspace.Package.featureState].
* Note that [CargoProject] is immutable object, so [cargoProject] instance is not mutated by [modifyFeatures]
* invocation. Instead, new [CargoProject] instance is created and replaces this instance in
* [CargoProjectsService.allProjects].
*
* Here we only modify [CargoProject.userDisabledFeatures]. The final feature state
* is inferred in [WorkspaceImpl.inferFeatureState].
*
* See tests in `CargoFeaturesModificationTest`
*/
override fun modifyFeatures(cargoProject: CargoProject, features: Set<PackageFeature>, newState: FeatureState) {
modifyProjectFeatures(cargoProject) { workspace, userDisabledFeatures ->
val packagesByRoots = workspace.packages.associateBy { it.rootDirectory }
val actualFeatures = features.mapNotNullToSet { f ->
packagesByRoots[f.pkg.rootDirectory]?.let { PackageFeature(it, f.name) }
}
when (newState) {
FeatureState.Disabled -> {
// When a user disables a feature, all we have to do is add it into `userDisabledFeatures`.
// The state of dependant features will be inferred in `WorkspaceImpl.inferFeatureState`
for (feature in actualFeatures) {
userDisabledFeatures.setFeatureState(feature, FeatureState.Disabled)
}
}
FeatureState.Enabled -> {
// But when disables, we should ensure `userDisabledFeatures` state is consistent.
//
// For example, consider such a case:
// (let [x] mean the feature was enabled automatically (by default),
// [d] – disabled because of presence in `userDisabledFeatures`,
// [ ] – disabled automatically because of dependency on [d] feature)
//
// [x] f1 = ["f3"]
// [x] f2 = ["f3"]
// [x] f3 = []
//
// Then a user disables `f3`:
// [ ] f1 = ["f3"]
// [ ] f2 = ["f3"]
// [d] f3 = []
// `f1` and `f2` disabled automatically because they depend on `f3`.
//
// Then a user enables `f1`, and this is our case!
// [x] f1 = ["f3"]
// [d] f2 = ["f3"]
// [x] f3 = []
// To enable `f1`, `f3` should be removed from `userDisabledFeatures` (because `f1`
// depends on `f3`). But if we just remove `f3` from `userDisabledFeatures`, `f2` will
// also become enabled, but we don't want it! So we have to remove `f3` and add `f2`
workspace.featureGraph.apply(defaultState = FeatureState.Enabled) {
disableAll(userDisabledFeatures.getDisabledFeatures(workspace.packages))
enableAll(actualFeatures)
}.forEach { (feature, state) ->
if (feature.pkg.origin == PackageOrigin.WORKSPACE) {
userDisabledFeatures.setFeatureState(feature, state)
}
}
}
}.exhaustive
}
}
private fun modifyProjectFeatures(
cargoProject: CargoProject,
action: (CargoWorkspace, MutableUserDisabledFeatures) -> Unit
) {
modifyProjectsLite { projects ->
val oldProject = projects.singleOrNull { it.manifest == cargoProject.manifest }
?: return@modifyProjectsLite projects
val workspace = oldProject.workspace ?: return@modifyProjectsLite projects
val userDisabledFeatures = oldProject.userDisabledFeatures.toMutable()
action(workspace, userDisabledFeatures)
val newProject = oldProject.copy(userDisabledFeatures = userDisabledFeatures)
val newProjects = projects.toMutableList()
// This can't fail because we got `oldProject` from `projects` few lines above
newProjects[newProjects.indexOf(oldProject)] = newProject
newProjects
}
}
/**
* All modifications to project model except for low-level `loadState` should
* go through this method: it makes sure that when we update various IDEA listeners,
* [allProjects] contains fresh projects.
*/
protected fun modifyProjects(
updater: (List<CargoProjectImpl>) -> CompletableFuture<List<CargoProjectImpl>>
): CompletableFuture<List<CargoProjectImpl>> {
val refreshStatusPublisher = project.messageBus.syncPublisher(CargoProjectsService.CARGO_PROJECTS_REFRESH_TOPIC)
val wrappedUpdater = { projects: List<CargoProjectImpl> ->
refreshStatusPublisher.onRefreshStarted()
updater(projects)
}
return projects.updateAsync(wrappedUpdater)
.thenApply { projects ->
invokeAndWaitIfNeeded {
val fileTypeManager = FileTypeManager.getInstance()
runWriteAction {
if (projects.isNotEmpty()) {
checkRustVersion(projects)
// Android RenderScript (from Android plugin) files has the same extension (.rs) as Rust files.
// In some cases, IDEA determines `*.rs` files have RenderScript file type instead of Rust one
// that leads any code insight features don't work in Rust projects.
// See https://youtrack.jetbrains.com/issue/IDEA-237376
//
// It's a hack to provide proper mapping when we are sure that it's Rust project
fileTypeManager.associateExtension(RsFileType, RsFileType.defaultExtension)
}
directoryIndex.resetIndex()
// In unit tests roots change is done by the test framework in most cases
runWithNonLightProject(project) {
ProjectRootManagerEx.getInstanceEx(project)
.makeRootsChange(EmptyRunnable.getInstance(), false, true)
}
project.messageBus.syncPublisher(CargoProjectsService.CARGO_PROJECTS_TOPIC)
.cargoProjectsUpdated(this, projects)
initialized = true
}
}
projects
}.handle { projects, err ->
val status = err?.toRefreshStatus() ?: CargoRefreshStatus.SUCCESS
refreshStatusPublisher.onRefreshFinished(status)
projects
}
}
private fun Throwable.toRefreshStatus(): CargoRefreshStatus {
return when {
this is ProcessCanceledException -> CargoRefreshStatus.CANCEL
this is CompletionException && cause is ProcessCanceledException -> CargoRefreshStatus.CANCEL
else -> CargoRefreshStatus.FAILURE
}
}
private fun modifyProjectsLite(
f: (List<CargoProjectImpl>) -> List<CargoProjectImpl>
): CompletableFuture<List<CargoProjectImpl>> =
projects.updateSync(f)
.thenApply { projects ->
invokeAndWaitIfNeeded {
val psiManager = PsiManager.getInstance(project)
runWriteAction {
directoryIndex.resetIndex()
project.messageBus.syncPublisher(CargoProjectsService.CARGO_PROJECTS_TOPIC)
.cargoProjectsUpdated(this, projects)
psiManager.dropPsiCaches()
DaemonCodeAnalyzer.getInstance(project).restart()
}
}
projects
}
private fun checkRustVersion(projects: List<CargoProjectImpl>) {
val minToolchainVersion = projects.asSequence()
.mapNotNull { it.rustcInfo?.version?.semver }
.minOrNull()
val isUnsupportedRust = minToolchainVersion != null &&
minToolchainVersion < RsToolchainBase.MIN_SUPPORTED_TOOLCHAIN
@Suppress("LiftReturnOrAssignment")
if (isUnsupportedRust) {
if (!isLegacyRustNotificationShowed) {
val content = "Rust <b>$minToolchainVersion</b> is no longer supported. " +
"It may lead to unexpected errors. " +
"Consider upgrading your toolchain to at least <b>${RsToolchainBase.MIN_SUPPORTED_TOOLCHAIN}</b>"
project.showBalloon(content, NotificationType.WARNING)
}
isLegacyRustNotificationShowed = true
} else {
isLegacyRustNotificationShowed = false
}
}
override fun getState(): Element {
val state = Element("state")
for (cargoProject in allProjects) {
val cargoProjectElement = Element("cargoProject")
cargoProjectElement.setAttribute("FILE", cargoProject.manifest.systemIndependentPath)
state.addContent(cargoProjectElement)
}
// Note that if [state] is empty (there are no cargo projects), [noStateLoaded] will be called on the next load
return state
}
override fun loadState(state: Element) {
// [cargoProjects] is non-empty here. Otherwise, [noStateLoaded] is called instead of [loadState]
val cargoProjects = state.getChildren("cargoProject")
val loaded = mutableListOf<CargoProjectImpl>()
val userDisabledFeaturesMap = project.service<UserDisabledFeaturesHolder>()
.takeLoadedUserDisabledFeatures()
for (cargoProject in cargoProjects) {
val file = cargoProject.getAttributeValue("FILE")
val manifest = Paths.get(file)
val userDisabledFeatures = userDisabledFeaturesMap[manifest] ?: UserDisabledFeatures.EMPTY
val newProject = CargoProjectImpl(manifest, this, userDisabledFeatures)
loaded.add(newProject)
}
// Wake the macro expansion service as soon as possible.
project.macroExpansionManager
// Refresh projects via `invokeLater` to avoid model modifications
// while the project is being opened. Use `updateSync` directly
// instead of `modifyProjects` for this reason
projects.updateSync { loaded }
.whenComplete { _, _ ->
val disableRefresh = System.getProperty(CARGO_DISABLE_PROJECT_REFRESH_ON_CREATION, "false").toBooleanStrictOrNull()
if (disableRefresh != true) {
invokeLater {
if (project.isDisposed) return@invokeLater
refreshAllProjects()
}
}
}
}
/**
* Note that [noStateLoaded] is called not only during the first service creation, but on any
* service load if [getState] returned empty state during previous save (i.e. there are no cargo project)
*/
override fun noStateLoaded() {
// Do nothing: in theory, we might try to do [discoverAndRefresh]
// here, but the `RsToolchain` is most likely not ready.
//
// So the actual "Let's guess a project model if it is not imported
// explicitly" happens in [org.rust.ide.notifications.MissingToolchainNotificationProvider]
initialized = true // No lock required b/c it's service init time
// Should be initialized with this service because it stores a part of cargo projects data
project.service<UserDisabledFeaturesHolder>()
}
override fun dispose() {}
override fun toString(): String =
"CargoProjectsService(projects = $allProjects)"
companion object {
const val CARGO_DISABLE_PROJECT_REFRESH_ON_CREATION: String = "cargo.disable.project.refresh.on.creation"
}
}
data class CargoProjectImpl(
override val manifest: Path,
private val projectService: CargoProjectsServiceImpl,
override val userDisabledFeatures: UserDisabledFeatures = UserDisabledFeatures.EMPTY,
val rawWorkspace: CargoWorkspace? = null,
private val stdlib: StandardLibrary? = null,
override val rustcInfo: RustcInfo? = null,
override val workspaceStatus: UpdateStatus = UpdateStatus.NeedsUpdate,
override val stdlibStatus: UpdateStatus = UpdateStatus.NeedsUpdate,
override val rustcInfoStatus: UpdateStatus = UpdateStatus.NeedsUpdate
) : UserDataHolderBase(), CargoProject {
override val project get() = projectService.project
override val procMacroExpanderPath: Path? = rustcInfo?.sysroot?.let { sysroot ->
val toolchain = project.toolchain ?: return@let null
ProcMacroServerPool.findExpanderExecutablePath(toolchain, sysroot)
}
override val workspace: CargoWorkspace? by lazy(LazyThreadSafetyMode.PUBLICATION) {
val rawWorkspace = rawWorkspace ?: return@lazy null
val stdlib = stdlib ?: return@lazy if (!userDisabledFeatures.isEmpty() && isUnitTestMode) {
rawWorkspace.withDisabledFeatures(userDisabledFeatures)
} else {
rawWorkspace
}
rawWorkspace.withStdlib(stdlib, rawWorkspace.cfgOptions, rustcInfo)
.withDisabledFeatures(userDisabledFeatures)
}
override val presentableName: String by lazy {
workspace?.packages?.singleOrNull {
it.origin == PackageOrigin.WORKSPACE && it.rootDirectory == workingDirectory
}?.name ?: workingDirectory.fileName.toString()
}
private val rootDirCache = AtomicReference<VirtualFile>()
override val rootDir: VirtualFile?
get() {
val cached = rootDirCache.get()
if (cached != null && cached.isValid) return cached
val file = LocalFileSystem.getInstance().findFileByIoFile(workingDirectory.toFile())
rootDirCache.set(file)
return file
}
override val workspaceRootDir: VirtualFile? get() = rawWorkspace?.workspaceRoot
@TestOnly
fun setRootDir(dir: VirtualFile) = rootDirCache.set(dir)
// Checks that the project is https://github.com/rust-lang/rust
fun doesProjectLooksLikeRustc(): Boolean {
val workspace = rawWorkspace ?: return false
// "rustc" package was renamed to "rustc_middle" in https://github.com/rust-lang/rust/pull/70536
// so starting with rustc 1.42 a stable way to identify it is to try to find any of some possible packages
val possiblePackages = listOf("rustc", "rustc_middle", "rustc_typeck")
return workspace.findPackageByName(AutoInjectedCrates.STD) != null &&
workspace.findPackageByName(AutoInjectedCrates.CORE) != null &&
possiblePackages.any { workspace.findPackageByName(it) != null }
}
fun withStdlib(result: TaskResult<StandardLibrary>): CargoProjectImpl = when (result) {
is TaskResult.Ok -> copy(stdlib = result.value, stdlibStatus = UpdateStatus.UpToDate)
is TaskResult.Err -> copy(stdlibStatus = UpdateStatus.UpdateFailed(result.reason))
}
fun withWorkspace(result: TaskResult<CargoWorkspace>): CargoProjectImpl = when (result) {
is TaskResult.Ok -> copy(
rawWorkspace = result.value,
workspaceStatus = UpdateStatus.UpToDate,
userDisabledFeatures = userDisabledFeatures.retain(result.value.packages)
)
is TaskResult.Err -> copy(workspaceStatus = UpdateStatus.UpdateFailed(result.reason))
}
fun withRustcInfo(result: TaskResult<RustcInfo>): CargoProjectImpl = when (result) {
is TaskResult.Ok -> copy(rustcInfo = result.value, rustcInfoStatus = UpdateStatus.UpToDate)
is TaskResult.Err -> copy(rustcInfoStatus = UpdateStatus.UpdateFailed(result.reason))
}
override fun toString(): String =
"CargoProject(manifest = $manifest)"
}
val CargoProjectsService.allPackages: Sequence<CargoWorkspace.Package>
get() = allProjects.asSequence().mapNotNull { it.workspace }.flatMap { it.packages.asSequence() }
val CargoProjectsService.allTargets: Sequence<CargoWorkspace.Target>
get() = allPackages.flatMap { it.targets.asSequence() }
private fun hasAtLeastOneValidProject(projects: Collection<CargoProject>) =
projects.any { it.manifest.exists() }
/** Keep in sync with [org.rust.cargo.project.model.impl.deduplicateProjects] */
private fun isExistingProject(projects: Collection<CargoProject>, manifest: Path): Boolean {
if (projects.any { it.manifest == manifest }) return true
return projects.mapNotNull { it.workspace }.flatMap { it.packages }
.filter { it.origin == PackageOrigin.WORKSPACE }
.any { it.rootDirectory == manifest.parent }
}
private fun doRefresh(project: Project, projects: List<CargoProjectImpl>): CompletableFuture<List<CargoProjectImpl>> {
@Suppress("UnstableApiUsage")
if (!project.isTrusted()) return CompletableFuture.completedFuture(projects)
// TODO: get rid of `result` here
val result = if (projects.isEmpty()) {
CompletableFuture.completedFuture(emptyList())
} else {
val result = CompletableFuture<List<CargoProjectImpl>>()
val syncTask = CargoSyncTask(project, projects, result)
project.taskQueue.run(syncTask)
result
}
return result.thenApply { updatedProjects ->
runWithNonLightProject(project) {
setupProjectRoots(project, updatedProjects)
}
updatedProjects
}
}
private inline fun runWithNonLightProject(project: Project, action: () -> Unit) {
if ((project as? ProjectEx)?.isLight != true) {
action()
} else {
check(isUnitTestMode)
}
}
private fun setupProjectRoots(project: Project, cargoProjects: List<CargoProject>) {
invokeAndWaitIfNeeded {
// Initialize services that we use (probably indirectly) in write action below.
// Otherwise, they can be initialized in write action that may lead to deadlock
RunManager.getInstance(project)
ProjectFileIndex.getInstance(project)
runWriteAction {
if (project.isDisposed) return@runWriteAction
ProjectRootManagerEx.getInstanceEx(project).mergeRootsChangesDuring {
for (cargoProject in cargoProjects) {
cargoProject.workspaceRootDir?.setupContentRoots(project) { contentRoot ->
addExcludeFolder("${contentRoot.url}/${CargoConstants.ProjectLayout.target}")
}
if ((cargoProject as? CargoProjectImpl)?.doesProjectLooksLikeRustc() == true) {
cargoProject.workspaceRootDir?.setupContentRoots(project) { contentRoot ->
addExcludeFolder("${contentRoot.url}/build")
}
}
val workspacePackages = cargoProject.workspace?.packages
.orEmpty()
.filter { it.origin == PackageOrigin.WORKSPACE }
for (pkg in workspacePackages) {
pkg.contentRoot?.setupContentRoots(project, ContentEntryWrapper::setup)
}
}
}
}
}
}
private fun VirtualFile.setupContentRoots(project: Project, setup: ContentEntryWrapper.(VirtualFile) -> Unit) {
val packageModule = ModuleUtilCore.findModuleForFile(this, project) ?: return
setupContentRoots(packageModule, setup)
}
private fun VirtualFile.setupContentRoots(packageModule: Module, setup: ContentEntryWrapper.(VirtualFile) -> Unit) {
ModuleRootModificationUtil.updateModel(packageModule) { rootModel ->
val contentEntry = rootModel.contentEntries.singleOrNull() ?: return@updateModel
ContentEntryWrapper(contentEntry).setup(this)
}
}
| mit | a1a6f2a1eec9ba210ab6f64bdcbf4678 | 44.063128 | 131 | 0.651024 | 5.280599 | false | false | false | false |
HabitRPG/habitrpg-android | Habitica/src/main/java/com/habitrpg/android/habitica/ui/views/CollapsibleSectionView.kt | 1 | 5680 | package com.habitrpg.android.habitica.ui.views
import android.content.Context
import android.content.SharedPreferences
import android.graphics.drawable.ColorDrawable
import android.util.AttributeSet
import android.view.View
import android.widget.ImageView
import android.widget.LinearLayout
import androidx.core.content.ContextCompat
import androidx.core.content.edit
import com.habitrpg.android.habitica.R
import com.habitrpg.android.habitica.databinding.ViewCollapsibleSectionBinding
import com.habitrpg.android.habitica.extensions.getThemeColor
import com.habitrpg.android.habitica.extensions.layoutInflater
class CollapsibleSectionView(context: Context, attrs: AttributeSet?) : LinearLayout(context, attrs) {
val infoIconView: ImageView
get() = binding.infoIconView
private val binding = ViewCollapsibleSectionBinding.inflate(context.layoutInflater, this)
private var preferences: SharedPreferences? = null
private val padding = context.resources?.getDimension(R.dimen.spacing_large)?.toInt() ?: 0
private val bottomPadding = context.resources?.getDimension(R.dimen.collapsible_section_padding)?.toInt() ?: 0
var title: CharSequence
get() {
return binding.titleTextView.text
}
set(value) {
binding.titleTextView.text = value
}
private var isCollapsed = false
set(value) {
field = value
if (value) {
hideViews()
} else {
showViews()
}
}
var caretColor: Int = 0
set(value) {
field = value
setCaretImage()
}
var identifier: String? = null
var separatorColor: Int
get() {
return (binding.separator.background as? ColorDrawable)?.color ?: 0
}
set(value) {
binding.separator.setBackgroundColor(value)
}
private fun showViews() {
updatePreferences()
setCaretImage()
(0 until childCount)
.map { getChildAt(it) }
.forEach { it.visibility = View.VISIBLE }
}
private fun hideViews() {
updatePreferences()
setCaretImage()
(2 until childCount)
.map { getChildAt(it) }
.filter { it != binding.sectionTitleView }
.forEach {
it.visibility = View.GONE
}
}
private fun updatePreferences() {
if (identifier == null) {
return
}
preferences?.edit { putBoolean(identifier, isCollapsed) }
}
private fun setCaretImage() {
binding.caretView.setImageBitmap(HabiticaIconsHelper.imageOfCaret(caretColor, isCollapsed))
}
private fun setChildMargins() {
(2 until childCount)
.map { getChildAt(it) }
.filter { it != binding.sectionTitleView }
.forEach {
val lp = it.layoutParams as? LayoutParams
lp?.setMargins(padding, 0, padding, bottomPadding)
it.layoutParams = lp
}
}
override fun onLayout(changed: Boolean, l: Int, t: Int, r: Int, b: Int) {
setChildMargins()
super.onLayout(changed, l, t, r, b)
}
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
var height = 0
measureChildWithMargins(binding.separator, widthMeasureSpec, 0, heightMeasureSpec, height)
height += binding.separator.measuredHeight
measureChildWithMargins(binding.sectionTitleView, widthMeasureSpec, 0, heightMeasureSpec, height)
height += binding.sectionTitleView.measuredHeight
(2 until childCount)
.map { getChildAt(it) }
.forEach {
if (it.visibility != View.GONE) {
measureChildWithMargins(it, widthMeasureSpec, 0, heightMeasureSpec, height)
height += it.measuredHeight + bottomPadding
}
}
if (!isCollapsed) {
height += padding
}
setMeasuredDimension(MeasureSpec.getSize(widthMeasureSpec), height)
}
init {
caretColor = ContextCompat.getColor(context, R.color.black_50_alpha)
orientation = VERTICAL
binding.sectionTitleView.setOnClickListener {
isCollapsed = !isCollapsed
}
val attributes = context.theme?.obtainStyledAttributes(
attrs,
R.styleable.CollapsibleSectionView,
0, 0
)
title = attributes?.getString(R.styleable.CollapsibleSectionView_title) ?: ""
identifier = attributes?.getString(R.styleable.CollapsibleSectionView_identifier)
val color = attributes?.getColor(R.styleable.CollapsibleSectionView_color, 0)
if (color != null && color != 0) {
caretColor = color
binding.titleTextView.setTextColor(color)
}
if (attributes?.getBoolean(R.styleable.CollapsibleSectionView_hasAdditionalInfo, false) == true) {
binding.infoIconView.setImageBitmap(HabiticaIconsHelper.imageOfInfoIcon(context.getThemeColor(R.attr.colorPrimaryOffset)))
} else {
binding.infoIconView.visibility = View.GONE
}
}
override fun onAttachedToWindow() {
super.onAttachedToWindow()
setCaretImage()
setChildMargins()
preferences = context.getSharedPreferences("collapsible_sections", 0)
if (identifier != null && preferences?.getBoolean(identifier, false) == true) {
isCollapsed = true
}
}
fun setCaretOffset(offset: Int) {
binding.caretView.setPadding(0, 0, offset, 0)
}
}
| gpl-3.0 | 93cf9e74a60d09bff1a9ca43c2283970 | 33.424242 | 134 | 0.628873 | 4.952049 | false | false | false | false |
nrizzio/Signal-Android | app/src/main/java/org/thoughtcrime/securesms/stories/viewer/post/StoryBlurLoader.kt | 1 | 3331 | package org.thoughtcrime.securesms.stories.viewer.post
import android.graphics.drawable.Drawable
import android.net.Uri
import android.widget.ImageView
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleOwner
import com.bumptech.glide.load.DataSource
import com.bumptech.glide.load.engine.GlideException
import com.bumptech.glide.request.RequestListener
import com.bumptech.glide.request.target.Target
import org.signal.core.util.logging.Log
import org.thoughtcrime.securesms.blurhash.BlurHash
import org.thoughtcrime.securesms.mms.GlideApp
import org.thoughtcrime.securesms.stories.viewer.page.StoryCache
import org.thoughtcrime.securesms.stories.viewer.page.StoryDisplay
/**
* Responsible for managing the lifecycle around loading a BlurHash
*/
class StoryBlurLoader(
private val lifecycle: Lifecycle,
private val blurHash: BlurHash?,
private val cacheKey: Uri,
private val storyCache: StoryCache,
private val storySize: StoryDisplay.Size,
private val blurImage: ImageView,
private val callback: Callback = NO_OP
) {
companion object {
private val TAG = Log.tag(StoryBlurLoader::class.java)
private val NO_OP = object : Callback {
override fun onBlurLoaded() = Unit
override fun onBlurFailed() = Unit
}
}
private val blurListener = object : StoryCache.Listener {
override fun onResourceReady(resource: Drawable) {
blurImage.setImageDrawable(resource)
callback.onBlurLoaded()
}
override fun onLoadFailed() {
callback.onBlurFailed()
}
}
fun load() {
val cacheValue = storyCache.getFromCache(cacheKey)
if (cacheValue != null) {
loadViaCache(cacheValue)
} else {
loadViaGlide(blurHash, storySize)
}
}
fun clear() {
GlideApp.with(blurImage).clear(blurImage)
blurImage.setImageDrawable(null)
}
private fun loadViaCache(cacheValue: StoryCache.StoryCacheValue) {
Log.d(TAG, "Blur in cache. Loading via cache...")
val blurTarget = cacheValue.blurTarget
if (blurTarget != null) {
blurTarget.addListener(blurListener)
lifecycle.addObserver(OnDestroy { blurTarget.removeListener(blurListener) })
} else {
callback.onBlurFailed()
}
}
private fun loadViaGlide(blurHash: BlurHash?, storySize: StoryDisplay.Size) {
if (blurHash != null) {
GlideApp.with(blurImage)
.load(blurHash)
.override(storySize.width, storySize.height)
.addListener(object : RequestListener<Drawable> {
override fun onLoadFailed(e: GlideException?, model: Any?, target: Target<Drawable>?, isFirstResource: Boolean): Boolean {
callback.onBlurFailed()
return false
}
override fun onResourceReady(resource: Drawable?, model: Any?, target: Target<Drawable>?, dataSource: DataSource?, isFirstResource: Boolean): Boolean {
callback.onBlurLoaded()
return false
}
})
.into(blurImage)
} else {
callback.onBlurFailed()
}
}
interface Callback {
fun onBlurLoaded()
fun onBlurFailed()
}
private inner class OnDestroy(private val onDestroy: () -> Unit) : DefaultLifecycleObserver {
override fun onDestroy(owner: LifecycleOwner) {
onDestroy()
}
}
}
| gpl-3.0 | eeea4888b93c8bbdb7ae3b939e22a867 | 29.281818 | 161 | 0.711798 | 4.287001 | false | false | false | false |
androidx/androidx | buildSrc-tests/src/test/kotlin/androidx/build/MavenUploadHelperTest.kt | 3 | 23061 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.build
import org.junit.Assert.assertEquals
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
@RunWith(JUnit4::class)
class MavenUploadHelperTest {
@Test
fun testSortPomDependencies() {
/* ktlint-disable max-line-length */
val pom = """<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<!-- This module was also published with a richer model, Gradle metadata, -->
<!-- which should be used instead. Do not delete the following line which -->
<!-- is to indicate to Gradle or any Gradle module metadata file consumer -->
<!-- that they should prefer consuming it instead. -->
<!-- do_not_remove: published-with-gradle-metadata -->
<modelVersion>4.0.0</modelVersion>
<groupId>androidx.collection</groupId>
<artifactId>collection-jvm</artifactId>
<version>1.3.0-alpha01</version>
<name>Android Support Library collections</name>
<description>Standalone efficient collections.</description>
<url>https://developer.android.com/jetpack/androidx/releases/collection#1.3.0-alpha01</url>
<inceptionYear>2018</inceptionYear>
<licenses>
<license>
<name>The Apache Software License, Version 2.0</name>
<url>http://www.apache.org/licenses/LICENSE-2.0.txt</url>
<distribution>repo</distribution>
</license>
</licenses>
<developers>
<developer>
<name>The Android Open Source Project</name>
</developer>
</developers>
<scm>
<connection>scm:git:https://android.googlesource.com/platform/frameworks/support</connection>
<url>https://cs.android.com/androidx/platform/frameworks/support</url>
</scm>
<dependencies>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-stdlib-common</artifactId>
<version>1.6.10</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-stdlib</artifactId>
<version>1.6.10</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>androidx.annotation</groupId>
<artifactId>annotation</artifactId>
<version>1.3.0</version>
<scope>compile</scope>
</dependency>
</dependencies>
</project>"""
// Expect that elements in <dependencies> are sorted alphabetically.
val expected = """<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<!-- This module was also published with a richer model, Gradle metadata, -->
<!-- which should be used instead. Do not delete the following line which -->
<!-- is to indicate to Gradle or any Gradle module metadata file consumer -->
<!-- that they should prefer consuming it instead. -->
<!-- do_not_remove: published-with-gradle-metadata -->
<modelVersion>4.0.0</modelVersion>
<groupId>androidx.collection</groupId>
<artifactId>collection-jvm</artifactId>
<version>1.3.0-alpha01</version>
<name>Android Support Library collections</name>
<description>Standalone efficient collections.</description>
<url>https://developer.android.com/jetpack/androidx/releases/collection#1.3.0-alpha01</url>
<inceptionYear>2018</inceptionYear>
<licenses>
<license>
<name>The Apache Software License, Version 2.0</name>
<url>http://www.apache.org/licenses/LICENSE-2.0.txt</url>
<distribution>repo</distribution>
</license>
</licenses>
<developers>
<developer>
<name>The Android Open Source Project</name>
</developer>
</developers>
<scm>
<connection>scm:git:https://android.googlesource.com/platform/frameworks/support</connection>
<url>https://cs.android.com/androidx/platform/frameworks/support</url>
</scm>
<dependencies>
<dependency>
<groupId>androidx.annotation</groupId>
<artifactId>annotation</artifactId>
<version>1.3.0</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-stdlib</artifactId>
<version>1.6.10</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-stdlib-common</artifactId>
<version>1.6.10</version>
<scope>compile</scope>
</dependency>
</dependencies>
</project>"""
/* ktlint-enable max-line-length */
val actual = sortPomDependencies(pom)
assertEquals(expected, actual)
}
@Test
fun testSortGradleMetadataDependencies() {
/* ktlint-disable max-line-length */
val metadata = """
{
"formatVersion": "1.1",
"component": {
"url": "../../collection/1.3.0-alpha01/collection-1.3.0-alpha01.module",
"group": "androidx.collection",
"module": "collection",
"version": "1.3.0-alpha01",
"attributes": {
"org.gradle.status": "release"
}
},
"createdBy": {
"gradle": {
"version": "7.4"
}
},
"variants": [
{
"name": "jvmApiElements-published",
"attributes": {
"org.gradle.category": "library",
"org.gradle.libraryelements": "jar",
"org.gradle.usage": "java-api",
"org.jetbrains.kotlin.platform.type": "jvm"
},
"dependencies": [
{
"group": "org.jetbrains.kotlin",
"module": "kotlin-stdlib",
"version": {
"requires": "1.6.10"
}
},
{
"group": "androidx.annotation",
"module": "annotation",
"version": {
"requires": "1.3.0"
}
},
{
"group": "org.jetbrains.kotlin",
"module": "kotlin-stdlib-common",
"version": {
"requires": "1.6.10"
}
}
],
"files": [
{
"name": "collection-jvm-1.3.0-alpha01.jar",
"url": "collection-jvm-1.3.0-alpha01.jar",
"size": 42271,
"sha512": "b01746682f5499426492ed56cfa10e863b181f0a94e1c97de935a1d68bc1a8da9b60bbc670a71642e4c4ebde0cedbed42f08f6b305bbfa7270b3b1fa76059fa6",
"sha256": "647d39d1ef35b45ff9b4c4b2afd7b0280431223142ededb4ee2d3ff73eb2657a",
"sha1": "11cbbdeaa0540d0cef16567781a99cdf7b34b242",
"md5": "309042f77be5772d725180056e5e97e9"
}
]
},
{
"name": "jvmRuntimeElements-published",
"attributes": {
"org.gradle.category": "library",
"org.gradle.libraryelements": "jar",
"org.gradle.usage": "java-runtime",
"org.jetbrains.kotlin.platform.type": "jvm"
},
"dependencies": [
{
"group": "org.jetbrains.kotlin",
"module": "kotlin-stdlib",
"version": {
"requires": "1.6.10"
}
},
{
"group": "androidx.annotation",
"module": "annotation",
"version": {
"requires": "1.3.0"
}
},
{
"group": "org.jetbrains.kotlin",
"module": "kotlin-stdlib-common",
"version": {
"requires": "1.6.10"
}
}
],
"files": [
{
"name": "collection-jvm-1.3.0-alpha01.jar",
"url": "collection-jvm-1.3.0-alpha01.jar",
"size": 42271,
"sha512": "b01746682f5499426492ed56cfa10e863b181f0a94e1c97de935a1d68bc1a8da9b60bbc670a71642e4c4ebde0cedbed42f08f6b305bbfa7270b3b1fa76059fa6",
"sha256": "647d39d1ef35b45ff9b4c4b2afd7b0280431223142ededb4ee2d3ff73eb2657a",
"sha1": "11cbbdeaa0540d0cef16567781a99cdf7b34b242",
"md5": "309042f77be5772d725180056e5e97e9"
}
]
}
]
}
""".trimIndent()
// Expect that elements in "dependencies" are sorted alphabetically.
val expected = """
{
"formatVersion": "1.1",
"component": {
"url": "../../collection/1.3.0-alpha01/collection-1.3.0-alpha01.module",
"group": "androidx.collection",
"module": "collection",
"version": "1.3.0-alpha01",
"attributes": {
"org.gradle.status": "release"
}
},
"createdBy": {
"gradle": {
"version": "7.4"
}
},
"variants": [
{
"name": "jvmApiElements-published",
"attributes": {
"org.gradle.category": "library",
"org.gradle.libraryelements": "jar",
"org.gradle.usage": "java-api",
"org.jetbrains.kotlin.platform.type": "jvm"
},
"dependencies": [
{
"group": "androidx.annotation",
"module": "annotation",
"version": {
"requires": "1.3.0"
}
},
{
"group": "org.jetbrains.kotlin",
"module": "kotlin-stdlib",
"version": {
"requires": "1.6.10"
}
},
{
"group": "org.jetbrains.kotlin",
"module": "kotlin-stdlib-common",
"version": {
"requires": "1.6.10"
}
}
],
"files": [
{
"name": "collection-jvm-1.3.0-alpha01.jar",
"url": "collection-jvm-1.3.0-alpha01.jar",
"size": 42271,
"sha512": "b01746682f5499426492ed56cfa10e863b181f0a94e1c97de935a1d68bc1a8da9b60bbc670a71642e4c4ebde0cedbed42f08f6b305bbfa7270b3b1fa76059fa6",
"sha256": "647d39d1ef35b45ff9b4c4b2afd7b0280431223142ededb4ee2d3ff73eb2657a",
"sha1": "11cbbdeaa0540d0cef16567781a99cdf7b34b242",
"md5": "309042f77be5772d725180056e5e97e9"
}
]
},
{
"name": "jvmRuntimeElements-published",
"attributes": {
"org.gradle.category": "library",
"org.gradle.libraryelements": "jar",
"org.gradle.usage": "java-runtime",
"org.jetbrains.kotlin.platform.type": "jvm"
},
"dependencies": [
{
"group": "androidx.annotation",
"module": "annotation",
"version": {
"requires": "1.3.0"
}
},
{
"group": "org.jetbrains.kotlin",
"module": "kotlin-stdlib",
"version": {
"requires": "1.6.10"
}
},
{
"group": "org.jetbrains.kotlin",
"module": "kotlin-stdlib-common",
"version": {
"requires": "1.6.10"
}
}
],
"files": [
{
"name": "collection-jvm-1.3.0-alpha01.jar",
"url": "collection-jvm-1.3.0-alpha01.jar",
"size": 42271,
"sha512": "b01746682f5499426492ed56cfa10e863b181f0a94e1c97de935a1d68bc1a8da9b60bbc670a71642e4c4ebde0cedbed42f08f6b305bbfa7270b3b1fa76059fa6",
"sha256": "647d39d1ef35b45ff9b4c4b2afd7b0280431223142ededb4ee2d3ff73eb2657a",
"sha1": "11cbbdeaa0540d0cef16567781a99cdf7b34b242",
"md5": "309042f77be5772d725180056e5e97e9"
}
]
}
]
}
""".trimIndent()
/* ktlint-enable max-line-length */
val actual = sortGradleMetadataDependencies(metadata)
assertEquals(expected, actual)
}
@Test
fun testSortGradleMetadataDependenciesWithConstraints() {
/* ktlint-disable max-line-length */
val metadata = """
{
"formatVersion": "1.1",
"component": {
"group": "androidx.activity",
"module": "activity-ktx",
"version": "1.5.0-alpha03",
"attributes": {
"org.gradle.status": "release"
}
},
"createdBy": {
"gradle": {
"version": "7.4"
}
},
"variants": [
{
"name": "releaseVariantReleaseApiPublication",
"attributes": {
"org.gradle.category": "library",
"org.gradle.dependency.bundling": "external",
"org.gradle.libraryelements": "aar",
"org.gradle.usage": "java-api"
},
"dependencies": [
{
"group": "androidx.activity",
"module": "activity",
"version": {
"requires": "1.5.0-alpha03"
}
},
{
"group": "androidx.core",
"module": "core-ktx",
"version": {
"requires": "1.1.0"
},
"reason": "Mirror activity dependency graph for -ktx artifacts"
},
{
"group": "androidx.lifecycle",
"module": "lifecycle-runtime-ktx",
"version": {
"requires": "2.5.0-alpha03"
},
"reason": "Mirror activity dependency graph for -ktx artifacts"
},
{
"group": "androidx.lifecycle",
"module": "lifecycle-viewmodel-ktx",
"version": {
"requires": "2.5.0-alpha03"
}
},
{
"group": "androidx.savedstate",
"module": "savedstate-ktx",
"version": {
"requires": "1.2.0-alpha01"
},
"reason": "Mirror activity dependency graph for -ktx artifacts"
},
{
"group": "org.jetbrains.kotlin",
"module": "kotlin-stdlib",
"version": {
"requires": "1.6.10"
}
}
],
"files": [
{
"name": "activity-ktx-1.5.0-alpha03.aar",
"url": "activity-ktx-1.5.0-alpha03.aar",
"size": 31645,
"sha512": "d4b175f956cd329698705ab7ecdb080c6668d689bf9ae99e8d7c53baa4383848af73c65e280baabb4938121d5d06367a900b5fc9c072eb29aa86e89b6f0c4595",
"sha256": "e30b007d69f63a2a0c56b5275faea7badf0f80a06caa1c50b2eba7129581793e",
"sha1": "9818a50c9ed22d6c089026f4edd3106b06eb4a4e",
"md5": "186145646501129b4bdfd0f804ba96d9"
}
]
},
{
"name": "releaseVariantReleaseRuntimePublication",
"attributes": {
"org.gradle.category": "library",
"org.gradle.dependency.bundling": "external",
"org.gradle.libraryelements": "aar",
"org.gradle.usage": "java-runtime"
},
"dependencies": [
{
"group": "androidx.activity",
"module": "activity",
"version": {
"requires": "1.5.0-alpha03"
}
},
{
"group": "androidx.core",
"module": "core-ktx",
"version": {
"requires": "1.1.0"
},
"reason": "Mirror activity dependency graph for -ktx artifacts"
},
{
"group": "androidx.lifecycle",
"module": "lifecycle-runtime-ktx",
"version": {
"requires": "2.5.0-alpha03"
},
"reason": "Mirror activity dependency graph for -ktx artifacts"
},
{
"group": "androidx.lifecycle",
"module": "lifecycle-viewmodel-ktx",
"version": {
"requires": "2.5.0-alpha03"
}
},
{
"group": "androidx.savedstate",
"module": "savedstate-ktx",
"version": {
"requires": "1.2.0-alpha01"
},
"reason": "Mirror activity dependency graph for -ktx artifacts"
},
{
"group": "org.jetbrains.kotlin",
"module": "kotlin-stdlib",
"version": {
"requires": "1.6.10"
}
}
],
"files": [
{
"name": "activity-ktx-1.5.0-alpha03.aar",
"url": "activity-ktx-1.5.0-alpha03.aar",
"size": 31645,
"sha512": "d4b175f956cd329698705ab7ecdb080c6668d689bf9ae99e8d7c53baa4383848af73c65e280baabb4938121d5d06367a900b5fc9c072eb29aa86e89b6f0c4595",
"sha256": "e30b007d69f63a2a0c56b5275faea7badf0f80a06caa1c50b2eba7129581793e",
"sha1": "9818a50c9ed22d6c089026f4edd3106b06eb4a4e",
"md5": "186145646501129b4bdfd0f804ba96d9"
}
]
},
{
"name": "sourcesElements",
"attributes": {
"org.gradle.category": "documentation",
"org.gradle.dependency.bundling": "external",
"org.gradle.docstype": "sources",
"org.gradle.usage": "java-runtime"
},
"files": [
{
"name": "activity-ktx-1.5.0-alpha03-sources.jar",
"url": "activity-ktx-1.5.0-alpha03-sources.jar",
"size": 7897,
"sha512": "c484c2a29fdd1896cbdc3613c660eb83acfd8371a800eb8950783a6011623011a336cf2c9c3258119c1f22cb5ea6d9a1513125284cc3be9064a61a38afd0dd30",
"sha256": "a66e48c18dda88d8d94f19b4250067f834d9db01ca8390c26e4530bfd2ad015e",
"sha1": "cc99180305811c77b3fe5e10bfd099e8637bec44",
"md5": "81c0906fb7e820a6ff164add91827fe4"
}
]
}
]
}
""".trimIndent()
// Expect that elements in "dependencies" are sorted alphabetically.
val expected = """
{
"formatVersion": "1.1",
"component": {
"group": "androidx.activity",
"module": "activity-ktx",
"version": "1.5.0-alpha03",
"attributes": {
"org.gradle.status": "release"
}
},
"createdBy": {
"gradle": {
"version": "7.4"
}
},
"variants": [
{
"name": "releaseVariantReleaseApiPublication",
"attributes": {
"org.gradle.category": "library",
"org.gradle.dependency.bundling": "external",
"org.gradle.libraryelements": "aar",
"org.gradle.usage": "java-api"
},
"dependencies": [
{
"group": "androidx.activity",
"module": "activity",
"version": {
"requires": "1.5.0-alpha03"
}
},
{
"group": "androidx.core",
"module": "core-ktx",
"version": {
"requires": "1.1.0"
},
"reason": "Mirror activity dependency graph for -ktx artifacts"
},
{
"group": "androidx.lifecycle",
"module": "lifecycle-runtime-ktx",
"version": {
"requires": "2.5.0-alpha03"
},
"reason": "Mirror activity dependency graph for -ktx artifacts"
},
{
"group": "androidx.lifecycle",
"module": "lifecycle-viewmodel-ktx",
"version": {
"requires": "2.5.0-alpha03"
}
},
{
"group": "androidx.savedstate",
"module": "savedstate-ktx",
"version": {
"requires": "1.2.0-alpha01"
},
"reason": "Mirror activity dependency graph for -ktx artifacts"
},
{
"group": "org.jetbrains.kotlin",
"module": "kotlin-stdlib",
"version": {
"requires": "1.6.10"
}
}
],
"files": [
{
"name": "activity-ktx-1.5.0-alpha03.aar",
"url": "activity-ktx-1.5.0-alpha03.aar",
"size": 31645,
"sha512": "d4b175f956cd329698705ab7ecdb080c6668d689bf9ae99e8d7c53baa4383848af73c65e280baabb4938121d5d06367a900b5fc9c072eb29aa86e89b6f0c4595",
"sha256": "e30b007d69f63a2a0c56b5275faea7badf0f80a06caa1c50b2eba7129581793e",
"sha1": "9818a50c9ed22d6c089026f4edd3106b06eb4a4e",
"md5": "186145646501129b4bdfd0f804ba96d9"
}
]
},
{
"name": "releaseVariantReleaseRuntimePublication",
"attributes": {
"org.gradle.category": "library",
"org.gradle.dependency.bundling": "external",
"org.gradle.libraryelements": "aar",
"org.gradle.usage": "java-runtime"
},
"dependencies": [
{
"group": "androidx.activity",
"module": "activity",
"version": {
"requires": "1.5.0-alpha03"
}
},
{
"group": "androidx.core",
"module": "core-ktx",
"version": {
"requires": "1.1.0"
},
"reason": "Mirror activity dependency graph for -ktx artifacts"
},
{
"group": "androidx.lifecycle",
"module": "lifecycle-runtime-ktx",
"version": {
"requires": "2.5.0-alpha03"
},
"reason": "Mirror activity dependency graph for -ktx artifacts"
},
{
"group": "androidx.lifecycle",
"module": "lifecycle-viewmodel-ktx",
"version": {
"requires": "2.5.0-alpha03"
}
},
{
"group": "androidx.savedstate",
"module": "savedstate-ktx",
"version": {
"requires": "1.2.0-alpha01"
},
"reason": "Mirror activity dependency graph for -ktx artifacts"
},
{
"group": "org.jetbrains.kotlin",
"module": "kotlin-stdlib",
"version": {
"requires": "1.6.10"
}
}
],
"files": [
{
"name": "activity-ktx-1.5.0-alpha03.aar",
"url": "activity-ktx-1.5.0-alpha03.aar",
"size": 31645,
"sha512": "d4b175f956cd329698705ab7ecdb080c6668d689bf9ae99e8d7c53baa4383848af73c65e280baabb4938121d5d06367a900b5fc9c072eb29aa86e89b6f0c4595",
"sha256": "e30b007d69f63a2a0c56b5275faea7badf0f80a06caa1c50b2eba7129581793e",
"sha1": "9818a50c9ed22d6c089026f4edd3106b06eb4a4e",
"md5": "186145646501129b4bdfd0f804ba96d9"
}
]
},
{
"name": "sourcesElements",
"attributes": {
"org.gradle.category": "documentation",
"org.gradle.dependency.bundling": "external",
"org.gradle.docstype": "sources",
"org.gradle.usage": "java-runtime"
},
"files": [
{
"name": "activity-ktx-1.5.0-alpha03-sources.jar",
"url": "activity-ktx-1.5.0-alpha03-sources.jar",
"size": 7897,
"sha512": "c484c2a29fdd1896cbdc3613c660eb83acfd8371a800eb8950783a6011623011a336cf2c9c3258119c1f22cb5ea6d9a1513125284cc3be9064a61a38afd0dd30",
"sha256": "a66e48c18dda88d8d94f19b4250067f834d9db01ca8390c26e4530bfd2ad015e",
"sha1": "cc99180305811c77b3fe5e10bfd099e8637bec44",
"md5": "81c0906fb7e820a6ff164add91827fe4"
}
]
}
]
}
""".trimIndent()
/* ktlint-enable max-line-length */
val actual = sortGradleMetadataDependencies(metadata)
assertEquals(expected, actual)
}
}
| apache-2.0 | 280ccc5d1ac8c10b2858fe252d5d18e6 | 30.808276 | 205 | 0.564633 | 3.306237 | false | false | false | false |
bibaev/stream-debugger-plugin | src/main/java/com/intellij/debugger/streams/ui/impl/PositionsAwareCollectionView.kt | 1 | 2600 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.debugger.streams.ui.impl
import com.intellij.debugger.streams.ui.PaintingListener
import com.intellij.debugger.streams.ui.ValuesPositionsListener
import com.intellij.openapi.application.ApplicationManager
import com.intellij.util.EventDispatcher
/**
* @author Vitaliy.Bibaev
*/
open class PositionsAwareCollectionView(tree: CollectionTree,
private val values: List<ValueWithPositionImpl>)
: CollectionView(tree) {
private val myDispatcher: EventDispatcher<ValuesPositionsListener> = EventDispatcher.create(ValuesPositionsListener::class.java)
init {
instancesTree.addPaintingListener(object : PaintingListener {
override fun componentPainted() {
updateValues()
}
})
}
fun addValuesPositionsListener(listener: ValuesPositionsListener) = myDispatcher.addListener(listener)
private fun updateValues() {
var changed = false
val visibleRect = instancesTree.visibleRect
for (value in values) {
val rect = instancesTree.getRectByValue(value.traceElement)
changed = if (rect == null) {
value.invalidate(changed)
}
else {
value.set(changed, rect.y + rect.height / 2 - visibleRect.y,
visibleRect.intersects(rect), instancesTree.isHighlighted(value.traceElement))
}
}
if (changed) {
ApplicationManager.getApplication().invokeLater({ myDispatcher.multicaster.valuesPositionsChanged() })
}
}
private fun ValueWithPositionImpl.invalidate(modified: Boolean): Boolean {
return when (modified) {
true -> {
setInvalid()
true
}
false -> updateToInvalid()
}
}
private fun ValueWithPositionImpl.set(modified: Boolean, pos: Int, visible: Boolean, highlighted: Boolean): Boolean {
return when (modified) {
true -> {
setProperties(pos, visible, highlighted)
true
}
false -> updateProperties(pos, visible, highlighted)
}
}
} | apache-2.0 | 0c2c7efba513ccf031395460360b84bb | 31.5125 | 130 | 0.700769 | 4.444444 | false | false | false | false |
jvalduvieco/blok | lib/Domain/src/test/kotlin/com/blok/post/RepositoryTest.kt | 1 | 4430 | package test.com.blok.post
import com.blok.common.DatabaseSetup
import com.blok.model.Comment
import com.blok.model.CommentId
import com.blok.model.Post
import com.blok.model.PostId
import com.blok.post.Infrastructure.PostgresPostRepositoryForTesting
import org.junit.Assert.*
import org.junit.Before
import org.junit.Test
import java.time.LocalDateTime
class RepositoryTest {
private val postRepository = PostgresPostRepositoryForTesting(DatabaseSetup())
@Before
fun cleanDatabase() {
postRepository.cleanDatabase()
}
@Test
fun iCanCreateAPost() {
val post: Post = Post(PostId("1373b661-efc9-47a7-938d-088183662c42"), "lorem", "ipsum", LocalDateTime.now(), listOf("latin", "phrases", "test"))
postRepository.save(post)
val postFromDatabase: Post = postRepository.getPost(PostId("1373b661-efc9-47a7-938d-088183662c42"))
assertEquals(post.id, postFromDatabase.id)
assertEquals(post.title, postFromDatabase.title)
assertEquals(post.content, postFromDatabase.content)
assertEquals(post, postFromDatabase)
}
@Test
fun iCanCreateAPostWithNoCategories() {
val post: Post = Post(PostId("1373b661-efc9-47a7-938d-088183662c42"), "lorem", "ipsum", LocalDateTime.now(), listOf())
postRepository.save(post)
val postFromDatabase: Post = postRepository.getPost(PostId("1373b661-efc9-47a7-938d-088183662c42"))
assertEquals(post.id, postFromDatabase.id)
assertEquals(post.title, postFromDatabase.title)
assertEquals(post.content, postFromDatabase.content)
assertEquals(post, postFromDatabase)
}
@Test
fun iCanEditAPost() {
val post: Post = Post.create("A title", "Lorem Ipsum", listOf())
postRepository.save(post)
val editedPost = post.copy(title = "A better title")
postRepository.save(editedPost)
val postFromDatabase: Post = postRepository.getPost(post.id)
assertEquals(postFromDatabase.title, editedPost.title)
}
@Test
fun iCanEditAPostWithCategories() {
val post: Post = Post.create("A title", "Lorem Ipsum", listOf("lorem","ipsum"))
postRepository.save(post)
val editedPost = post.copy(title = "A better title", categories = listOf("lorem","latin"))
postRepository.save(editedPost)
val postFromDatabase: Post = postRepository.getPost(post.id)
assertEquals(postFromDatabase.title, editedPost.title)
assertEquals(postFromDatabase.categories, editedPost.categories)
}
@Test
fun iCanCreateAComment() {
val post: Post = Post(PostId("1373b661-efc9-47a7-938d-088183662c42"), "lorem", "ipsum", LocalDateTime.now(), listOf("latin", "phrases", "test"))
postRepository.save(post)
val comment: Comment = Comment(CommentId(), PostId("1373b661-efc9-47a7-938d-088183662c42"),"lucius", "lorem", LocalDateTime.now(),false)
postRepository.save(comment)
val commentFromDatabase: Comment = postRepository.getAllCommentsOn(PostId("1373b661-efc9-47a7-938d-088183662c42")).first()
assertEquals(comment.post_id, commentFromDatabase.post_id)
assertEquals(comment.id, commentFromDatabase.id)
assertEquals(comment.content, commentFromDatabase.content)
assertEquals(comment.submissionDate, commentFromDatabase.submissionDate)
assertEquals(comment.approved, commentFromDatabase.approved)
assertEquals(comment.author, commentFromDatabase.author)
assertEquals(comment, commentFromDatabase)
}
@Test
fun iCanDeleteAPost() {
val post: Post = Post.create("title", "author", listOf("lorem", "ipsum"))
postRepository.save(post)
postRepository.deletePost(post.id)
assertFalse(postRepository.existPost(post.id))
}
@Test
fun iCanDeleteAPostWithComments() {
val post: Post = Post.create("title", "author", listOf("lorem", "ipsum"))
val comment: Comment = post.addComment("lorem", "author")
var exceptionThrown: Boolean = false
postRepository.save(post)
postRepository.save(comment)
postRepository.deletePost(post.id)
assertFalse(postRepository.existPost(post.id))
try {
assertTrue(postRepository.getAllCommentsOn(post.id).isEmpty())
} catch (e: Throwable) {
exceptionThrown = true
}
assertTrue(exceptionThrown)
}
} | mit | 00ea28e02808d42b4805627b289bbb25 | 44.214286 | 152 | 0.69684 | 3.980234 | false | true | false | false |
Ztiany/AndroidBase | lib_base/src/main/java/com/android/base/app/fragment/Fragments.kt | 1 | 17947 | @file:JvmName("Fragments")
package com.android.base.app.fragment
import android.support.annotation.NonNull
import android.support.v4.app.Fragment
import android.support.v4.app.FragmentActivity
import android.support.v4.app.FragmentManager
import android.support.v4.app.FragmentTransaction
import android.view.View
import com.android.base.app.activity.ActivityDelegate
import com.android.base.app.activity.ActivityDelegateOwner
import com.android.base.app.activity.ActivityStatus
import com.android.base.kotlin.javaClassName
import kotlin.reflect.KClass
/**被此 annotation 标注的方法,表示需要使用 [Fragment] 的全类名作为 [FragmentTransaction] 中相关方法的 flag 参数的实参,比如 add/replace 等*/
annotation class UsingFragmentClassNameAsFlag
@JvmOverloads
fun Fragment.exitFragment(immediate: Boolean = false) {
activity.exitFragment(immediate)
}
@JvmOverloads
fun FragmentActivity?.exitFragment(immediate: Boolean = false) {
if (this == null) {
return
}
val supportFragmentManager = this.supportFragmentManager
val backStackEntryCount = supportFragmentManager.backStackEntryCount
if (backStackEntryCount > 0) {
if (immediate) {
supportFragmentManager.popBackStackImmediate()
} else {
supportFragmentManager.popBackStack()
}
} else {
this.supportFinishAfterTransition()
}
}
/**
* @param clazz the interface container must implemented
* @param <T> Type
* @return the interface context must implemented
*/
fun <T> Fragment.requireContainerImplement(clazz: Class<T>): T? {
if (clazz.isInstance(parentFragment)) {
return clazz.cast(parentFragment)
}
return if (clazz.isInstance(activity)) {
clazz.cast(activity)
} else {
throw RuntimeException("use this Fragment:$this, Activity or Fragment must impl interface :$clazz")
}
}
/**
* @param clazz the interface context must implemented
* @param <T> Type
* @return the interface context must implemented
*/
fun <T> Fragment.requireContextImplement(clazz: Class<T>): T? {
return if (!clazz.isInstance(activity)) {
throw RuntimeException("use this Fragment:$this, Activity must impl interface :$clazz")
} else {
clazz.cast(activity)
}
}
/**
* @param clazz the interface parent must implemented
* @param <T> Type
* @return the interface context must implemented
*/
fun <T> Fragment.requireParentImplement(clazz: Class<T>): T? {
return if (!clazz.isInstance(parentFragment)) {
throw RuntimeException("use this Fragment:$this, ParentFragment must impl interface :$clazz")
} else {
clazz.cast(parentFragment)
}
}
/** 使用 [clazz] 的全限定类名作为 tag 查找 Fragment */
fun <T : Fragment> FragmentManager.findFragmentByTag(clazz: KClass<T>): T? {
@Suppress("UNCHECKED_CAST")
return findFragmentByTag(clazz.java.name) as? T
}
/**
* Fragment 出栈,包括 flag 对应的 Fragment,如果 flag 对应的 Fragment 不在栈中,此方法什么都不做。
*/
@UsingFragmentClassNameAsFlag
fun FragmentManager.popBackUntil(flag: String, immediate: Boolean = false) {
if (immediate) {
popBackStackImmediate(flag, FragmentManager.POP_BACK_STACK_INCLUSIVE)
} else {
popBackStack(flag, FragmentManager.POP_BACK_STACK_INCLUSIVE)
}
}
/**
* Fragment 出栈,不包括 flag 对应的 Fragment,如果 flag 对应的 Fragment 不在栈中,此方法什么都不做。
*/
@UsingFragmentClassNameAsFlag
fun FragmentManager.popBackTo(flag: String, immediate: Boolean = false) {
if (immediate) {
popBackStackImmediate(flag, 0)
} else {
popBackStack(flag, 0)
}
}
/**
* 回到对应的 Fragment,如果 Fragment 在栈中,则该 Fragment 回到栈顶,如果 Fragment 不在栈中,则做一次弹栈操作。
*/
@UsingFragmentClassNameAsFlag
fun FragmentManager.backToFragment(flag: String, immediate: Boolean = false) {
val target = findFragmentByTag(flag)
if (target != null) {
if (isFragmentInStack(target.javaClass)) {
if (immediate) {
popBackStackImmediate(flag, 0)
} else {
popBackStack(flag, 0)
}
} else {
popBackStack()
}
}
}
fun FragmentManager.clearBackStack(immediate: Boolean = false) {
if (immediate) {
this.popBackStackImmediate(null, FragmentManager.POP_BACK_STACK_INCLUSIVE)
} else {
this.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE)
}
}
@UsingFragmentClassNameAsFlag
fun FragmentManager.isFragmentInStack(clazz: Class<out Fragment>): Boolean {
val backStackEntryCount = backStackEntryCount
if (backStackEntryCount == 0) {
return false
}
for (i in 0 until backStackEntryCount) {
if (clazz.name == getBackStackEntryAt(i).name) {
return true
}
}
return false
}
inline fun FragmentManager.inTransaction(func: EnhanceFragmentTransaction.() -> Unit) {
val fragmentTransaction = beginTransaction()
EnhanceFragmentTransaction(this, fragmentTransaction).func()
fragmentTransaction.commit()
}
inline fun FragmentActivity.inFragmentTransaction(func: EnhanceFragmentTransaction.() -> Unit) {
val transaction = supportFragmentManager.beginTransaction()
EnhanceFragmentTransaction(supportFragmentManager, transaction).func()
transaction.commit()
}
fun <T> T.inSafelyFragmentTransaction(
func: EnhanceFragmentTransaction.() -> Unit
): Boolean where T : FragmentActivity, T : ActivityDelegateOwner {
var delegate = findDelegate {
it is SafelyFragmentTransactionActivityDelegate
}as? SafelyFragmentTransactionActivityDelegate
if (delegate == null) {
delegate = SafelyFragmentTransactionActivityDelegate()
addDelegate(delegate)
}
val transaction = supportFragmentManager.beginTransaction()
EnhanceFragmentTransaction(supportFragmentManager, transaction).func()
return delegate.safeCommit(this, transaction)
}
inline fun Fragment.inChildFragmentTransaction(func: EnhanceFragmentTransaction.() -> Unit) {
val transaction = childFragmentManager.beginTransaction()
EnhanceFragmentTransaction(childFragmentManager, transaction).func()
transaction.commit()
}
fun <T> T.inSafelyChildFragmentTransaction(
func: EnhanceFragmentTransaction.() -> Unit
): Boolean where T : Fragment, T : FragmentDelegateOwner {
var delegate: SafelyFragmentTransactionFragmentDelegate? = findDelegate {
it is SafelyFragmentTransactionFragmentDelegate
} as? SafelyFragmentTransactionFragmentDelegate
if (delegate == null) {
delegate = SafelyFragmentTransactionFragmentDelegate()
addDelegate(delegate)
}
val transaction = childFragmentManager.beginTransaction()
EnhanceFragmentTransaction(childFragmentManager, transaction).func()
return delegate.safeCommit(this, transaction)
}
private class SafelyFragmentTransactionActivityDelegate : ActivityDelegate<FragmentActivity> {
private val mPendingTransactions = mutableListOf<FragmentTransaction>()
fun safeCommit(@NonNull activityDelegateOwner: ActivityDelegateOwner, @NonNull transaction: FragmentTransaction): Boolean {
val status = activityDelegateOwner.status
val isCommitterResumed = (status == ActivityStatus.CREATE || status == ActivityStatus.START || status == ActivityStatus.RESUME)
return if (isCommitterResumed) {
transaction.commit()
false
} else {
mPendingTransactions.add(transaction)
true
}
}
override fun onResumeFragments() {
if (mPendingTransactions.isNotEmpty()) {
mPendingTransactions.forEach { it.commit() }
mPendingTransactions.clear()
}
}
}
private class SafelyFragmentTransactionFragmentDelegate : FragmentDelegate<Fragment> {
private val mPendingTransactions = mutableListOf<FragmentTransaction>()
fun safeCommit(@NonNull fragment: Fragment, @NonNull transaction: FragmentTransaction): Boolean {
return if (fragment.isResumed) {
transaction.commit()
false
} else {
mPendingTransactions.add(transaction)
true
}
}
override fun onResume() {
if (mPendingTransactions.isNotEmpty()) {
mPendingTransactions.forEach { it.commit() }
mPendingTransactions.clear()
}
}
}
class EnhanceFragmentTransaction constructor(
private val fragmentManager: FragmentManager,
private val fragmentTransaction: FragmentTransaction
) : FragmentTransaction() {
//------------------------------------------------------------------------------------------------
// extra functions
//------------------------------------------------------------------------------------------------
/**
* 把 [fragment] 添加到回退栈中,并 hide 其他 fragment,
* 如果 [containerId]==0,则使用 [com.android.base.app.BaseKit.setDefaultFragmentContainerId] 中配置的 id,
* 如果 [tag] ==null 则使用 fragment 对应 class 的全限定类名。
*/
fun addWithStack(containerId: Int = 0, fragment: Fragment, tag: String? = null, transition: Boolean = true): EnhanceFragmentTransaction {
//hide top
hideTopFragment()
//set add to stack
val nonnullTag = (tag ?: fragment.javaClassName())
addToBackStack(nonnullTag)
//add
fragmentTransaction.add(confirmLayoutId(containerId), fragment, nonnullTag)
if (transition) {
//set a transition
setOpeningTransition()
}
return this
}
/**
* replace 方式把 [fragment] 添加到回退栈中,如果 [containerId]==0,则使用 [com.android.base.app.BaseKit.setDefaultFragmentContainerId] 中配置的 id,
* 如果 [tag] ==null 则使用 fragment 对应 class 的全限定类名。
*/
fun replaceWithStack(containerId: Int = 0, fragment: Fragment, tag: String? = null, transition: Boolean = true): EnhanceFragmentTransaction {
//set add to stack
val nonnullTag = (tag ?: fragment.javaClassName())
addToBackStack(nonnullTag)
//add
fragmentTransaction.replace(confirmLayoutId(containerId), fragment, nonnullTag)
//set a transition
if (transition) {
setOpeningTransition()
}
return this
}
private fun confirmLayoutId(layoutId: Int): Int {
return if (layoutId == 0) {
FragmentConfig.defaultContainerId()
} else {
layoutId
}
}
/**
* 添加 [fragment],默认使用 [com.android.base.app.BaseKit.setDefaultFragmentContainerId] 中配置的 id,如果 [tag] 为null,则使用 [fragment] 的全限定类。
*/
fun addWithDefaultContainer(fragment: Fragment, tag: String? = null): FragmentTransaction {
val nonnullTag = (tag ?: fragment.javaClassName())
return fragmentTransaction.add(FragmentConfig.defaultContainerId(), fragment, nonnullTag)
}
/**
* 替换为 [fragment],id 使用 [com.android.base.app.BaseKit.setDefaultFragmentContainerId] 中配置的 id,如果 [tag] 为null,则使用 [fragment] 的全限定类名。
*/
fun replaceWithDefaultContainer(fragment: Fragment, tag: String? = null, transition: Boolean = true): FragmentTransaction {
val nonnullTag = (tag ?: fragment.javaClassName())
if (transition) {
setOpeningTransition()
}
return fragmentTransaction.replace(FragmentConfig.defaultContainerId(), fragment, nonnullTag)
}
/**隐藏所有的 fragment */
private fun hideFragments() {
for (fragment in fragmentManager.fragments) {
if (fragment != null && fragment.isVisible) {
fragmentTransaction.hide(fragment)
}
}
}
/**隐藏第一个可见的 fragment */
private fun hideTopFragment() {
fragmentManager.fragments.lastOrNull { it.isVisible }?.let {
fragmentTransaction.hide(it)
}
}
@Suppress
fun setOpeningTransition(): FragmentTransaction {
return fragmentTransaction.setTransition(TRANSIT_FRAGMENT_OPEN)
}
fun setClosingTransition(): FragmentTransaction {
return fragmentTransaction.setTransition(TRANSIT_FRAGMENT_CLOSE)
}
fun setFadingTransition(): FragmentTransaction {
return fragmentTransaction.setTransition(TRANSIT_FRAGMENT_FADE)
}
//------------------------------------------------------------------------------------------------
// original functions
//------------------------------------------------------------------------------------------------
override fun setBreadCrumbShortTitle(res: Int): FragmentTransaction {
return fragmentTransaction.setBreadCrumbShortTitle(res)
}
override fun setBreadCrumbShortTitle(text: CharSequence?): FragmentTransaction {
return fragmentTransaction.setBreadCrumbShortTitle(text)
}
override fun setPrimaryNavigationFragment(fragment: Fragment?): FragmentTransaction {
return fragmentTransaction.setPrimaryNavigationFragment(fragment)
}
override fun runOnCommit(runnable: Runnable): FragmentTransaction {
return fragmentTransaction.runOnCommit(runnable)
}
override fun add(fragment: Fragment, tag: String?): FragmentTransaction {
return fragmentTransaction.add(fragment, tag)
}
override fun add(containerViewId: Int, fragment: Fragment): FragmentTransaction {
return fragmentTransaction.add(containerViewId, fragment)
}
override fun add(containerViewId: Int, fragment: Fragment, tag: String?): FragmentTransaction {
return fragmentTransaction.add(containerViewId, fragment, tag)
}
override fun hide(fragment: Fragment): FragmentTransaction {
return fragmentTransaction.hide(fragment)
}
override fun replace(containerViewId: Int, fragment: Fragment): FragmentTransaction {
return fragmentTransaction.replace(containerViewId, fragment)
}
override fun replace(containerViewId: Int, fragment: Fragment, tag: String?): FragmentTransaction {
return fragmentTransaction.replace(containerViewId, fragment, tag)
}
override fun detach(fragment: Fragment): FragmentTransaction {
return fragmentTransaction.detach(fragment)
}
@Deprecated("")
override fun setAllowOptimization(allowOptimization: Boolean): FragmentTransaction {
return fragmentTransaction.setAllowOptimization(allowOptimization)
}
override fun setCustomAnimations(enter: Int, exit: Int): FragmentTransaction {
return fragmentTransaction.setCustomAnimations(enter, exit)
}
override fun setCustomAnimations(enter: Int, exit: Int, popEnter: Int, popExit: Int): FragmentTransaction {
return fragmentTransaction.setCustomAnimations(enter, exit, popEnter, popExit)
}
override fun addToBackStack(name: String?): FragmentTransaction {
return fragmentTransaction.addToBackStack(name)
}
override fun disallowAddToBackStack(): FragmentTransaction {
return fragmentTransaction.disallowAddToBackStack()
}
override fun setTransitionStyle(styleRes: Int): FragmentTransaction {
return fragmentTransaction.setTransitionStyle(styleRes)
}
override fun setTransition(transit: Int): FragmentTransaction {
return fragmentTransaction.setTransition(transit)
}
override fun attach(fragment: Fragment): FragmentTransaction {
return fragmentTransaction.attach(fragment)
}
override fun show(fragment: Fragment): FragmentTransaction {
return fragmentTransaction.show(fragment)
}
override fun isEmpty(): Boolean {
return fragmentTransaction.isEmpty
}
override fun remove(fragment: Fragment): FragmentTransaction {
return fragmentTransaction.remove(fragment)
}
override fun isAddToBackStackAllowed(): Boolean {
return fragmentTransaction.isAddToBackStackAllowed
}
override fun addSharedElement(sharedElement: View, name: String): FragmentTransaction {
return fragmentTransaction.addSharedElement(sharedElement, name)
}
override fun setBreadCrumbTitle(res: Int): FragmentTransaction {
return fragmentTransaction.setBreadCrumbTitle(res)
}
override fun setBreadCrumbTitle(text: CharSequence?): FragmentTransaction {
return fragmentTransaction.setBreadCrumbTitle(text)
}
override fun setReorderingAllowed(reorderingAllowed: Boolean): FragmentTransaction {
return fragmentTransaction.setReorderingAllowed(reorderingAllowed)
}
@Deprecated("commit will be called automatically")
override fun commit(): Int {
throw UnsupportedOperationException("commit will be called automatically")
}
@Deprecated("commitAllowingStateLoss will be called automatically")
override fun commitAllowingStateLoss(): Int {
throw UnsupportedOperationException("commitAllowingStateLoss will be called automatically")
}
@Deprecated("commitNow will be called automatically", ReplaceWith("throw UnsupportedOperationException(\"commitNow will be called automatically\")"))
override fun commitNow() {
throw UnsupportedOperationException("commitNow will be called automatically")
}
@Deprecated("commitNowAllowingStateLoss will be called automatically", ReplaceWith("throw UnsupportedOperationException(\"commitNowAllowingStateLoss will be called automatically\")"))
override fun commitNowAllowingStateLoss() {
throw UnsupportedOperationException("commitNowAllowingStateLoss will be called automatically")
}
} | apache-2.0 | 85cbc7cdb0948b847b046d5832860fa0 | 33.861723 | 187 | 0.690026 | 5.053748 | false | false | false | false |
Nekromancer/DogSociety | app/src/main/java/pl/ownvision/dogsociety/activities/LoginActivity.kt | 1 | 2376 | package pl.ownvision.dogsociety.activities
import android.app.ProgressDialog
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import com.pawegio.kandroid.d
import com.pawegio.kandroid.longToast
import com.pawegio.kandroid.runDelayedOnUiThread
import kotlinx.android.synthetic.main.activity_login.*
import kotlinx.android.synthetic.main.content_login.*
import pl.ownvision.dogsociety.R
class LoginActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_login)
setSupportActionBar(toolbar)
link_signup.setOnClickListener {
// TODO : Intent do rejestracji
throw NotImplementedError();
}
btn_login.setOnClickListener {
login()
}
}
override fun onBackPressed() {
moveTaskToBack(true)
}
fun login() {
d("Login start")
btn_login.isEnabled = false
if (!validate()) {
onLoginFailed()
return
}
val progressDialog = ProgressDialog(this, R.style.Theme_AppCompat_Dialog_Alert)
progressDialog.isIndeterminate = true
progressDialog.setMessage(getString(R.string.authorizing_progress))
progressDialog.show()
// TODO : Logika logowania
runDelayedOnUiThread(5000) {
progressDialog.dismiss()
onLoginSuccess()
}
}
fun validate(): Boolean {
var valid = true
val email = input_email.text.toString()
val password = input_password.text.toString()
if (email.isEmpty() || !android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
input_email.error = getString(R.string.enter_valid_email)
valid = false
} else {
input_email.error = null
}
if (password.isEmpty() || password.length < 4 || password.length > 15) {
input_password.error = getString(R.string.enter_valid_password)
valid = false;
} else {
input_password.error = null
}
return valid
}
fun onLoginFailed() {
btn_login.isEnabled = true
longToast(getString(R.string.failed_login))
}
fun onLoginSuccess() {
btn_login.isEnabled = true
}
}
| gpl-2.0 | cc4169a4096e0c81e5f1414ef362921b | 25.696629 | 95 | 0.627104 | 4.595745 | false | false | false | false |
minecraft-dev/MinecraftDev | src/main/kotlin/platform/bukkit/BukkitModule.kt | 1 | 7258 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2022 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.platform.bukkit
import com.demonwav.mcdev.facet.MinecraftFacet
import com.demonwav.mcdev.insight.generation.GenerationData
import com.demonwav.mcdev.inspection.IsCancelled
import com.demonwav.mcdev.platform.AbstractModule
import com.demonwav.mcdev.platform.AbstractModuleType
import com.demonwav.mcdev.platform.PlatformType
import com.demonwav.mcdev.platform.bukkit.generation.BukkitGenerationData
import com.demonwav.mcdev.platform.bukkit.util.BukkitConstants
import com.demonwav.mcdev.util.SourceType
import com.demonwav.mcdev.util.addImplements
import com.demonwav.mcdev.util.extendsOrImplements
import com.demonwav.mcdev.util.findContainingMethod
import com.demonwav.mcdev.util.nullable
import com.intellij.lang.jvm.JvmModifier
import com.intellij.openapi.project.Project
import com.intellij.psi.JavaPsiFacade
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiClassType
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiLiteralExpression
import com.intellij.psi.PsiMethod
import com.intellij.psi.PsiMethodCallExpression
import com.intellij.psi.PsiType
import com.intellij.psi.search.GlobalSearchScope
import org.jetbrains.uast.UClass
import org.jetbrains.uast.UIdentifier
import org.jetbrains.uast.toUElementOfType
class BukkitModule<out T : AbstractModuleType<*>> constructor(facet: MinecraftFacet, type: T) : AbstractModule(facet) {
var pluginYml by nullable { facet.findFile("plugin.yml", SourceType.RESOURCE) }
private set
override val type: PlatformType = type.platformType
override val moduleType: T = type
override fun isEventClassValid(eventClass: PsiClass, method: PsiMethod?) =
BukkitConstants.EVENT_CLASS == eventClass.qualifiedName
override fun isStaticListenerSupported(method: PsiMethod) = true
override fun writeErrorMessageForEventParameter(eventClass: PsiClass, method: PsiMethod) =
"Parameter is not a subclass of org.bukkit.event.Event\n" +
"Compiling and running this listener may result in a runtime exception"
override fun doPreEventGenerate(psiClass: PsiClass, data: GenerationData?) {
if (!psiClass.extendsOrImplements(BukkitConstants.LISTENER_CLASS)) {
psiClass.addImplements(BukkitConstants.LISTENER_CLASS)
}
}
override fun generateEventListenerMethod(
containingClass: PsiClass,
chosenClass: PsiClass,
chosenName: String,
data: GenerationData?
): PsiMethod? {
val bukkitData = data as BukkitGenerationData
val method = generateBukkitStyleEventListenerMethod(
chosenClass,
chosenName,
project,
BukkitConstants.HANDLER_ANNOTATION,
bukkitData.isIgnoreCanceled
) ?: return null
if (bukkitData.eventPriority != "NORMAL") {
val list = method.modifierList
val annotation = list.findAnnotation(BukkitConstants.HANDLER_ANNOTATION) ?: return method
val value = JavaPsiFacade.getElementFactory(project)
.createExpressionFromText(
BukkitConstants.EVENT_PRIORITY_CLASS + "." + bukkitData.eventPriority,
annotation
)
annotation.setDeclaredAttributeValue("priority", value)
}
return method
}
override fun checkUselessCancelCheck(expression: PsiMethodCallExpression): IsCancelled? {
val method = expression.findContainingMethod() ?: return null
val annotation = method.modifierList.findAnnotation(BukkitConstants.HANDLER_ANNOTATION) ?: return null
// We are in an event method
val value = annotation.findAttributeValue("ignoreCancelled") as? PsiLiteralExpression ?: return null
if (value.value !is Boolean) {
return null
}
val ignoreCancelled = (value.value as Boolean?)!!
// If we aren't ignoring cancelled then any check for event being cancelled is valid
if (!ignoreCancelled) {
return null
}
val methodExpression = expression.methodExpression
val qualifierExpression = methodExpression.qualifierExpression
val resolve = methodExpression.resolve()
if (qualifierExpression == null) {
return null
}
if (resolve == null) {
return null
}
if (standardSkip(method, qualifierExpression)) {
return null
}
val context = resolve.context as? PsiClass ?: return null
if (!context.extendsOrImplements(BukkitConstants.CANCELLABLE_CLASS)) {
return null
}
if (resolve !is PsiMethod) {
return null
}
if (resolve.name != BukkitConstants.EVENT_ISCANCELLED_METHOD_NAME) {
return null
}
return IsCancelled(
errorString = "Cancellable.isCancelled() check is useless in a method annotated with ignoreCancelled=true.",
fix = {
expression.replace(
JavaPsiFacade.getElementFactory(project).createExpressionFromText(
"false",
expression
)
)
}
)
}
override fun shouldShowPluginIcon(element: PsiElement?): Boolean {
val identifier = element?.toUElementOfType<UIdentifier>()
?: return false
val psiClass = (identifier.uastParent as? UClass)?.javaPsi
?: return false
val pluginInterface = JavaPsiFacade.getInstance(element.project)
.findClass(BukkitConstants.PLUGIN, module.getModuleWithDependenciesAndLibrariesScope(false))
?: return false
return !psiClass.hasModifier(JvmModifier.ABSTRACT) && psiClass.isInheritor(pluginInterface, true)
}
override fun dispose() {
super.dispose()
pluginYml = null
}
companion object {
fun generateBukkitStyleEventListenerMethod(
chosenClass: PsiClass,
chosenName: String,
project: Project,
annotationName: String,
setIgnoreCancelled: Boolean
): PsiMethod? {
val newMethod = JavaPsiFacade.getElementFactory(project).createMethod(chosenName, PsiType.VOID)
val list = newMethod.parameterList
val qName = chosenClass.qualifiedName ?: return null
val parameter = JavaPsiFacade.getElementFactory(project)
.createParameter(
"event",
PsiClassType.getTypeByName(qName, project, GlobalSearchScope.allScope(project))
)
list.add(parameter)
val modifierList = newMethod.modifierList
val annotation = modifierList.addAnnotation(annotationName)
if (setIgnoreCancelled) {
val value = JavaPsiFacade.getElementFactory(project).createExpressionFromText("true", annotation)
annotation.setDeclaredAttributeValue("ignoreCancelled", value)
}
return newMethod
}
}
}
| mit | ab1fde298a24d760676db3f312d9f16a | 34.062802 | 120 | 0.670433 | 5.376296 | false | false | false | false |
takke/DataStats | app/src/main/java/jp/takke/datastats/NotificationPresenter.kt | 1 | 5587 | package jp.takke.datastats
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.app.Service
import android.content.Context
import android.content.Intent
import android.os.Build
import android.view.View
import android.widget.RemoteViews
import androidx.core.app.NotificationCompat
import jp.takke.util.MyLog
import jp.takke.util.TkUtil
import java.lang.ref.WeakReference
internal class NotificationPresenter(service: Service) {
private val mServiceRef: WeakReference<Service> = WeakReference(service)
fun showNotification(visibleOverlayView: Boolean) {
MyLog.d("showNotification")
val service = mServiceRef.get() ?: return
// 通知ウインドウをクリックした際に起動するインテント
val intent = Intent(service, MainActivity::class.java)
val pendingIntent = PendingIntent.getActivity(service, 0, intent,
PendingIntent.FLAG_CANCEL_CURRENT or TkUtil.getPendingIntentImmutableFlagIfOverM())
val builder = NotificationCompat.Builder(service.applicationContext, CHANNEL_ID)
// カスタムレイアウト生成
val notificationLayout = createCustomLayout(service, visibleOverlayView)
builder.setContentIntent(null)
builder.setCustomContentView(notificationLayout)
// Android 12 からは「展開させたくなくても展開できてしまう」ので同じものを設定しておく
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
builder.setCustomBigContentView(notificationLayout)
}
// 端末の通知エリア(上部のアイコンが並ぶ部分)に本アプリのアイコンを表示しないようにemptyなdrawableを指定する
builder.setSmallIcon(R.drawable.transparent_image)
builder.setOngoing(true)
builder.priority = NotificationCompat.PRIORITY_MIN
builder.setContentTitle(service.getString(R.string.resident_service_running))
// builder.setContentText("表示・非表示を切り替える");
builder.setContentIntent(pendingIntent)
service.startForeground(MY_NOTIFICATION_ID, builder.build())
}
private fun createCustomLayout(service: Service, visibleOverlayView: Boolean): RemoteViews {
val notificationLayout = RemoteViews(service.packageName, R.layout.custom_notification)
// Android 12+ ならアイコンは不要(通知エリアが狭いので)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
notificationLayout.setViewVisibility(R.id.app_icon, View.GONE)
}
// show button
if (!visibleOverlayView) {
val switchIntent = Intent(service, SwitchButtonReceiver::class.java)
switchIntent.action = "show"
val switchPendingIntent = PendingIntent.getBroadcast(service, 0, switchIntent, TkUtil.getPendingIntentImmutableFlagIfOverM())
notificationLayout.setOnClickPendingIntent(R.id.show_button, switchPendingIntent)
notificationLayout.setViewVisibility(R.id.show_button, View.VISIBLE)
} else {
notificationLayout.setViewVisibility(R.id.show_button, View.GONE)
}
// hide button
if (visibleOverlayView) {
val switchIntent = Intent(service, SwitchButtonReceiver::class.java)
switchIntent.action = "hide"
val switchPendingIntent = PendingIntent.getBroadcast(service, 0, switchIntent, TkUtil.getPendingIntentImmutableFlagIfOverM())
notificationLayout.setOnClickPendingIntent(R.id.hide_button, switchPendingIntent)
notificationLayout.setViewVisibility(R.id.hide_button, View.VISIBLE)
} else {
notificationLayout.setViewVisibility(R.id.hide_button, View.GONE)
}
// timer (hide and resume) button
if (visibleOverlayView) {
val switchIntent = Intent(service, SwitchButtonReceiver::class.java)
switchIntent.action = "hide_and_resume"
val switchPendingIntent = PendingIntent.getBroadcast(service, 0, switchIntent, TkUtil.getPendingIntentImmutableFlagIfOverM())
notificationLayout.setOnClickPendingIntent(R.id.hide_and_resume_button, switchPendingIntent)
notificationLayout.setViewVisibility(R.id.hide_and_resume_button, View.VISIBLE)
} else {
notificationLayout.setViewVisibility(R.id.hide_and_resume_button, View.INVISIBLE)
}
return notificationLayout
}
fun createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val service = mServiceRef.get() ?: return
val channel = NotificationChannel(CHANNEL_ID, service.getString(R.string.resident_notification),
NotificationManager.IMPORTANCE_LOW)
// invisible on lockscreen
channel.lockscreenVisibility = Notification.VISIBILITY_SECRET
val nm = service.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
nm.createNotificationChannel(channel)
}
}
fun hideNotification() {
MyLog.d("hideNotification")
val service = mServiceRef.get() ?: return
val nm = service.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
nm.cancel(MY_NOTIFICATION_ID)
}
companion object {
private const val MY_NOTIFICATION_ID = 1
private const val CHANNEL_ID = "resident"
}
}
| apache-2.0 | c80e526e254992089bb9f5e8371c4655 | 37.904412 | 137 | 0.705538 | 4.453704 | false | false | false | false |
inorichi/tachiyomi-extensions | src/es/vcpvmp/src/eu/kanade/tachiyomi/extension/es/vcpvmp/VCPVMP.kt | 1 | 18958 | package eu.kanade.tachiyomi.extension.es.vcpvmp
import eu.kanade.tachiyomi.network.GET
import eu.kanade.tachiyomi.source.model.Filter
import eu.kanade.tachiyomi.source.model.FilterList
import eu.kanade.tachiyomi.source.model.Page
import eu.kanade.tachiyomi.source.model.SChapter
import eu.kanade.tachiyomi.source.model.SManga
import eu.kanade.tachiyomi.source.online.ParsedHttpSource
import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
import okhttp3.Request
import org.jsoup.nodes.Document
import org.jsoup.nodes.Element
import rx.Observable
open class VCPVMP(override val name: String, override val baseUrl: String) : ParsedHttpSource() {
override val lang = "es"
override val supportsLatest: Boolean = false
override fun latestUpdatesRequest(page: Int) = throw UnsupportedOperationException("Not used")
override fun latestUpdatesSelector() = throw UnsupportedOperationException("Not used")
override fun latestUpdatesFromElement(element: Element) = throw UnsupportedOperationException("Not used")
override fun latestUpdatesNextPageSelector() = throw UnsupportedOperationException("Not used")
override fun popularMangaRequest(page: Int) = GET("$baseUrl/page/$page", headers)
override fun popularMangaSelector() = "div#ccontent div.gallery"
override fun popularMangaFromElement(element: Element) = SManga.create().apply {
element.select("a.cover").first().let {
setUrlWithoutDomain(it.attr("href"))
title = it.select("div.caption").text()
thumbnail_url = it.select("img").attr("abs:src").substringBefore("?")
}
}
override fun popularMangaNextPageSelector() = "ul.pagination > li.active + li"
override fun mangaDetailsParse(document: Document) = SManga.create().apply {
document.select("div#catag").let {
genre = document.select("div#tagsin > a[rel=tag]").joinToString { it.text() }
status = SManga.UNKNOWN
thumbnail_url = document.select(pageListSelector).firstOrNull()?.attr("abs:src")
}
}
override fun fetchChapterList(manga: SManga): Observable<List<SChapter>> {
return Observable.just(
listOf(
SChapter.create().apply {
name = manga.title
url = manga.url
}
)
)
}
override fun chapterListSelector() = throw UnsupportedOperationException("Not used")
override fun chapterFromElement(element: Element) = throw UnsupportedOperationException("Not used")
protected open val pageListSelector = "div.comicimg img"
override fun pageListParse(document: Document): List<Page> = document.select(pageListSelector)
.mapIndexed { i, img -> Page(i, "", img.attr("abs:src")) }
override fun imageUrlParse(document: Document) = throw UnsupportedOperationException("Not used")
override fun searchMangaRequest(page: Int, query: String, filters: FilterList): Request {
var url = baseUrl.toHttpUrlOrNull()!!.newBuilder()
val isOnVCP = (baseUrl == "https://vercomicsporno.com")
url.addPathSegments("page")
url.addPathSegments(page.toString())
url.addQueryParameter("s", query)
filters.forEach { filter ->
when (filter) {
is Genre -> {
when (filter.toUriPart().isNotEmpty()) {
true -> {
url = baseUrl.toHttpUrlOrNull()!!.newBuilder()
url.addPathSegments(if (isOnVCP) "tags" else "genero")
url.addPathSegments(filter.toUriPart())
url.addPathSegments("page")
url.addPathSegments(page.toString())
}
}
}
is Category -> {
when (filter.toUriPart().isNotEmpty()) {
true -> {
url.addQueryParameter("cat", filter.toUriPart())
}
}
}
}
}
return GET(url.build().toString(), headers)
}
override fun searchMangaSelector() = popularMangaSelector()
override fun searchMangaFromElement(element: Element) = popularMangaFromElement(element)
override fun searchMangaNextPageSelector() = popularMangaNextPageSelector()
override fun getFilterList() = FilterList(
Genre(),
Filter.Separator(),
Category()
)
// Array.from(document.querySelectorAll('div.tagcloud a.tag-cloud-link')).map(a => `Pair("${a.innerText}", "${a.href.replace('https://vercomicsporno.com/etiqueta/', '')}")`).join(',\n')
// from https://vercomicsporno.com/
private class Genre : UriPartFilter(
"Filtrar por categoría",
arrayOf(
Pair("Ver todos", ""),
Pair("Anales", "anales"),
Pair("Comics Porno", "comics-porno"),
Pair("Culonas", "culonas"),
Pair("Doujins", "doujins"),
Pair("Furry", "furry"),
Pair("Incesto", "incesto"),
Pair("Lesbianas", "lesbianas"),
Pair("Madre Hijo", "madre-hijo"),
Pair("Mamadas", "mamadas"),
Pair("Manga Hentai", "manga-hentai"),
Pair("Milfs", "milfs"),
Pair("Milftoon", "milftoon-comics"),
Pair("Orgias", "orgias"),
Pair("Parodias Porno", "parodias-porno"),
Pair("Rubias", "rubias"),
Pair("Series De Tv", "series-de-tv"),
Pair("Tetonas", "tetonas"),
Pair("Trios", "trios"),
Pair("Videojuegos", "videojuegos"),
Pair("Yuri", "yuri-2")
)
)
// Array.from(document.querySelectorAll('form select#cat option.level-0')).map(a => `Pair("${a.innerText}", "${a.value}")`).join(',\n')
// from https://vercomicsporno.com/
private class Category : UriPartFilter(
"Filtrar por categoría",
arrayOf(
Pair("Ver todos", ""),
Pair("5ish", "2853"),
Pair("69", "1905"),
Pair("8muses", "856"),
Pair("Aarokira", "2668"),
Pair("ABBB", "3058"),
Pair("Absurd Stories", "2846"),
Pair("Adam 00", "1698"),
Pair("Aeolus", "2831"),
Pair("Afrobull", "3032"),
Pair("Alcor", "2837"),
Pair("angstrom", "2996"),
Pair("Anonymouse", "2851"),
Pair("Aoino Broom", "3086"),
Pair("Aquarina", "2727"),
Pair("Arabatos", "1780"),
Pair("Aroma Sensei", "2663"),
Pair("Art of jaguar", "167"),
Pair("Atreyu Studio", "3040"),
Pair("Awaerr", "2921"),
Pair("Bakuhaku", "2866"),
Pair("Bashfulbeckon", "2841"),
Pair("Bear123", "2814"),
Pair("Black and White", "361"),
Pair("Black House", "3044"),
Pair("Blackadder", "83"),
Pair("Blacky Chan", "2901"),
Pair("Blargsnarf", "2728"),
Pair("BlueVersusRed", "2963"),
Pair("Bnouait", "2706"),
Pair("Born to Die", "2982"),
Pair("Buena trama", "2579"),
Pair("Buru", "2736"),
Pair("Cagri", "2751"),
Pair("CallMePlisskin", "2960"),
Pair("Catfightcentral", "2691"),
Pair("cecyartbytenshi", "2799"),
Pair("Cheka.art", "2999"),
Pair("Cherry Mouse Street", "2891"),
Pair("cherry-gig", "2679"),
Pair("Chochi", "3085"),
Pair("ClaraLaine", "2697"),
Pair("Clasicos", "2553"),
Pair("Cobatsart", "2729"),
Pair("Comics porno", "6"),
Pair("Comics Porno 3D", "1910"),
Pair("Comics porno mexicano", "511"),
Pair("Comics XXX", "119"),
Pair("CrazyDad3d", "2657"),
Pair("Creeeen", "2922"),
Pair("Croc", "1684"),
Pair("Crock", "3004"),
Pair("Cyberunique", "2801"),
Pair("Danaelus", "3080"),
Pair("DankoDeadZone", "3055"),
Pair("Darkhatboy", "2856"),
Pair("DarkShadow", "2845"),
Pair("DarkToons Cave", "2893"),
Pair("Dasan", "2692"),
Pair("David Willis", "2816"),
Pair("Dboy", "3094"),
Pair("Dconthedancefloor", "2905"),
Pair("Degenerate", "2923"),
Pair("Diathorn", "2894"),
Pair("Dicasty", "2983"),
Pair("Dimedrolly", "3017"),
Pair("Dirtycomics", "2957"),
Pair("DMAYaichi", "2924"),
Pair("Dony", "2769"),
Pair("Doxy", "2698"),
Pair("Drawnsex", "9"),
Pair("DrCockula", "2708"),
Pair("Dude-doodle-do", "2984"),
Pair("ebluberry", "2842"),
Pair("Ecchi Kimochiii", "1948"),
Pair("EcchiFactor 2.0", "1911"),
Pair("Eirhjien", "2817"),
Pair("Eliana Asato", "2878"),
Pair("Ender Selya", "2774"),
Pair("Enessef-UU", "3124"),
Pair("ERN", "3010"),
Pair("Erotibot", "2711"),
Pair("Escoria", "2945"),
Pair("Evil Rick", "2946"),
Pair("FearingFun", "3057"),
Pair("Felsala", "2138"),
Pair("Fetishhand", "2932"),
Pair("Fikomi", "2887"),
Pair("Fixxxer", "2737"),
Pair("FLBL", "3050"),
Pair("Folo", "2762"),
Pair("Forked Tail", "2830"),
Pair("Fotonovelas XXX", "320"),
Pair("Freckles", "3095"),
Pair("Fred Perry", "2832"),
Pair("Freehand", "400"),
Pair("FrozenParody", "1766"),
Pair("Fuckit", "2883"),
Pair("Funsexydragonball", "2786"),
Pair("Futanari", "1732"),
Pair("Futanari Fan", "2787"),
Pair("Garabatoz", "2877"),
Pair("Gerph", "2889"),
Pair("GFI", "3123"),
Pair("Ghettoyouth", "2730"),
Pair("Gilftoon", "2619"),
Pair("Glassfish", "84"),
Pair("GNAW", "3084"),
Pair("Goat-Head", "3011"),
Pair("Greivs", "3136"),
Pair("Grigori", "2775"),
Pair("Grose", "2876"),
Pair("Gundam888", "2681"),
Pair("Hagfish", "2599"),
Pair("Hary Draws", "2752"),
Pair("Hioshiru", "2673"),
Pair("Hmage", "2822"),
Pair("Horny-Oni", "2947"),
Pair("Hoteggs102", "2925"),
Pair("InCase", "1927"),
Pair("Incest Candy", "3126"),
Pair("Incesto 3d", "310"),
Pair("Incognitymous", "2693"),
Pair("Inker Shike", "2895"),
Pair("Interracial", "364"),
Pair("Inusen", "2854"),
Pair("Inuyuru", "2699"),
Pair("isakishi", "2721"),
Pair("Jadenkaiba", "2064"),
Pair("javisuzumiya", "2823"),
Pair("Jay Marvel", "2135"),
Pair("Jay Naylor", "174"),
Pair("Jellcaps", "2818"),
Pair("Jhon Person", "135"),
Pair("Jitsch", "2835"),
Pair("Jkr", "718"),
Pair("JLullaby", "2680"),
Pair("John North", "2927"),
Pair("JohnJoseco", "2906"),
Pair("JooJoo", "3026"),
Pair("Joru", "2798"),
Pair("JZerosk", "2757"),
Pair("K/DA", "2667"),
Pair("Ka-iN", "2874"),
Pair("Kadath", "2700"),
Pair("Kannel", "2836"),
Pair("Kaos", "1994"),
Pair("Karmagik", "2943"),
Pair("Karmakaze", "2968"),
Pair("Katoto Chan", "2916"),
Pair("Kimmundo", "2669"),
Pair("Kinkamashe", "2873"),
Pair("Kinkymation", "2733"),
Pair("Kirtu", "107"),
Pair("Kiselrok", "3075"),
Pair("Kogeikun", "2738"),
Pair("KrasH", "2958"),
Pair("Krazy Krow", "2848"),
Pair("Kumi Pumi", "2771"),
Pair("l", "1"),
Pair("Lady Astaroth", "2722"),
Pair("LaundryMom", "2926"),
Pair("LawyBunne", "2744"),
Pair("Laz", "2933"),
Pair("Lemon Font", "2750"),
Pair("Lewdua", "2734"),
Pair("LilithN", "2991"),
Pair("Locofuria", "2578"),
Pair("Loonyjams", "2935"),
Pair("Los Simpsons XXX", "94"),
Pair("Lumo", "2858"),
Pair("MAD-Project", "2890"),
Pair("Magnificent Sexy Gals", "2942"),
Pair("Manaworld", "85"),
Pair("Manaworldcomics", "164"),
Pair("Manga hentai", "152"),
Pair("Maoukouichi", "2910"),
Pair("Marcos Crot", "3025"),
Pair("Matemi", "2741"),
Pair("Mavruda", "2865"),
Pair("MCC", "2843"),
Pair("Meesh", "2740"),
Pair("Meinfischer", "3063"),
Pair("Melkor Mancin", "169"),
Pair("Meowwithme", "2936"),
Pair("Metal Owl", "2694"),
Pair("Miles-DF", "2864"),
Pair("Milffur", "140"),
Pair("Milftoon", "13"),
Pair("Milftoonbeach", "1712"),
Pair("Milky Bunny", "3066"),
Pair("MissBehaviour", "2997"),
Pair("Mojarte", "1417"),
Pair("Moose", "2939"),
Pair("morganagod", "2917"),
Pair("Moval-X", "2785"),
Pair("Mr. E Comics", "2562"),
Pair("Mr. Estella", "3068"),
Pair("MrPotatoParty", "2712"),
Pair("My Bad Bunny", "2989"),
Pair("Myster Box", "2670"),
Pair("Nastee34", "2930"),
Pair("Neal D Anderson", "2725"),
Pair("nearphotison", "3039"),
Pair("nicekotatsu", "2749"),
Pair("nihaotomita", "2998"),
Pair("Nikipostat", "2824"),
Pair("NiniiDawns", "2937"),
Pair("Nisego", "2768"),
Pair("Norasuko", "2800"),
Pair("Noticias", "1664"),
Pair("nsfyosu", "2859"),
Pair("Nyoronyan", "2758"),
Pair("NyuroraXBigdon", "3134"),
Pair("O-tako Studios", "2723"),
Pair("Oh!Nice", "2896"),
Pair("OldFlameShotgun", "2884"),
Pair("Otomo-San", "2788"),
Pair("Pack Imagenes", "654"),
Pair("Pak009", "2819"),
Pair("Palcomix", "48"),
Pair("Pandora Box", "155"),
Pair("peculiart", "3000"),
Pair("Pegasus Smith", "2682"),
Pair("Personalami", "2789"),
Pair("PeterAndWhitney", "2860"),
Pair("Pia-Sama", "2797"),
Pair("PinkPawg", "2861"),
Pair("Pinktoon", "2868"),
Pair("Pixelboy", "2840"),
Pair("pleasure castle", "3081"),
Pair("Pokeporn", "1914"),
Pair("Polyle", "2952"),
Pair("Poonet", "648"),
Pair("Prism Girls", "1926"),
Pair("Privados", "858"),
Pair("PTDMCA", "2949"),
Pair("QTsunade", "2770"),
Pair("quad", "3051"),
Pair("Quarko-Muon", "2872"),
Pair("Queenchikki", "3062"),
Pair("QueenComplex", "2951"),
Pair("QueenTsunade", "2811"),
Pair("Queervanire", "2871"),
Pair("r_ex", "2898"),
Pair("Raidon-san", "2962"),
Pair("RanmaBooks", "1974"),
Pair("Razter", "2689"),
Pair("recreator 2099", "2671"),
Pair("Redboard", "2803"),
Pair("reddanmanic", "2867"),
Pair("Reinbach", "2888"),
Pair("Relatedguy", "2829"),
Pair("ReloadHB", "3012"),
Pair("Revolverwing", "2790"),
Pair("RickFoxxx", "1411"),
Pair("Rino99", "2934"),
Pair("Ripperelite", "2820"),
Pair("RobCiveCat", "2739"),
Pair("RogueArtLove", "2812"),
Pair("Rousfairly", "2776"),
Pair("Rukasu", "2778"),
Pair("Rupalulu", "3135"),
Pair("SakuSaku Panic", "2907"),
Pair("SaMelodii", "2701"),
Pair("SanePerson", "2683"),
Pair("SatyQ", "3024"),
Pair("Saurian", "2950"),
Pair("Selrock", "2886"),
Pair("Shadako26", "2780"),
Pair("Shadbase", "1713"),
Pair("Shadow2007x", "2781"),
Pair("ShadowFenrir", "3132"),
Pair("Sheela", "2690"),
Pair("Sillygirl", "2129"),
Pair("Sin Porno", "2266"),
Pair("Sinner", "2897"),
Pair("Sinope", "2985"),
Pair("Sirkowski", "2802"),
Pair("Skulltitti", "2918"),
Pair("SleepyGimp", "2911"),
Pair("Slipshine", "2791"),
Pair("Slypon", "2912"),
Pair("Smutichi", "2821"),
Pair("Snaketrap", "2940"),
Pair("Sorje", "2961"),
Pair("Spirale", "2870"),
Pair("Stereoscope Comics", "3054"),
Pair("Stormfeder", "2759"),
Pair("Sun1Sol", "2782"),
Pair("SunsetRiders7", "1705"),
Pair("Super Melons", "2850"),
Pair("Taboolicious", "88"),
Pair("Tease Comix", "2948"),
Pair("Tekuho", "2601"),
Pair("Tentabat", "2862"),
Pair("the dark mangaka", "2783"),
Pair("The Pit", "2792"),
Pair("thegoodbadart", "2684"),
Pair("TheKite", "2825"),
Pair("Theminus", "2828"),
Pair("TheNewGuy", "3018"),
Pair("TheOtherHalf", "2666"),
Pair("Tim Fischer", "2763"),
Pair("Totempole", "2746"),
Pair("TotesFleisch8", "2764"),
Pair("Tovio Rogers", "3056"),
Pair("Tracy Scops", "2648"),
Pair("Transmorpher DDS", "2672"),
Pair("Turtlechan", "2796"),
Pair("TvMx", "2793"),
Pair("Urakan", "3043"),
Pair("Uzonegro", "2695"),
Pair("V3rnon", "2973"),
Pair("Vaiderman", "3031"),
Pair("VentZX", "2575"),
Pair("Vercomicsporno", "1376"),
Pair("Watsup", "2863"),
Pair("Whargleblargle", "2844"),
Pair("Wherewolf", "2685"),
Pair("Witchking00", "1815"),
Pair("Wulfsaga", "2931"),
Pair("Xamrock", "2686"),
Pair("Xierra099", "2702"),
Pair("Xkit", "2703"),
Pair("Y3df", "86"),
Pair("Yamamoto", "3019"),
Pair("Yusioka", "3082"),
Pair("Zillionaire", "2807"),
Pair("Zzomp", "252"),
Pair("ZZZ Comics", "2839")
)
)
}
| apache-2.0 | c2ecbb59191f84e29a8187872c3a3f0e | 37.924025 | 189 | 0.483066 | 3.744025 | false | false | false | false |
HabitRPG/habitica-android | Habitica/src/main/java/com/habitrpg/android/habitica/models/inventory/Quest.kt | 2 | 1336 | package com.habitrpg.android.habitica.models.inventory
import com.habitrpg.android.habitica.models.BaseObject
import com.habitrpg.android.habitica.models.members.Member
import io.realm.RealmList
import io.realm.RealmObject
import io.realm.annotations.PrimaryKey
open class Quest : RealmObject(), BaseObject {
@PrimaryKey
var id: String? = null
set(value) {
field = value
progress?.id = value
}
var key: String = ""
set(value) {
field = value
progress?.key = key
}
var active: Boolean = false
var leader: String? = null
var RSVPNeeded: Boolean = false
var members: RealmList<QuestMember>? = null
var progress: QuestProgress? = null
var participants: RealmList<Member>? = null
var rageStrikes: RealmList<QuestRageStrike>? = null
var completed: String? = null
fun hasRageStrikes(): Boolean {
return rageStrikes?.isNotEmpty() ?: false
}
fun addRageStrike(rageStrike: QuestRageStrike) {
if (rageStrikes == null) {
rageStrikes = RealmList()
}
rageStrikes?.add(rageStrike)
}
val activeRageStrikeNumber: Int
get() {
return rageStrikes?.filter { it.wasHit }?.size ?: 0
}
}
| gpl-3.0 | fd472469927bc3455124fefd31e86626 | 25.833333 | 63 | 0.609281 | 4.498316 | false | false | false | false |
HabitRPG/habitica-android | Habitica/src/main/java/com/habitrpg/android/habitica/models/tasks/RemindersItem.kt | 1 | 3227 | package com.habitrpg.android.habitica.models.tasks
import android.os.Parcel
import android.os.Parcelable
import io.realm.RealmObject
import io.realm.annotations.PrimaryKey
import java.time.Instant
import java.time.LocalDateTime
import java.time.ZoneId
import java.time.ZonedDateTime
import java.time.format.DateTimeFormatter
import java.time.format.DateTimeFormatterBuilder
import java.time.temporal.TemporalAccessor
open class RemindersItem : RealmObject, Parcelable {
@PrimaryKey
var id: String? = null
var startDate: String? = null
var time: String? = null
// Use to store task type before a task is created
var type: String? = null
override fun describeContents(): Int {
return 0
}
override fun writeToParcel(dest: Parcel, flags: Int) {
dest.writeString(id)
dest.writeString(startDate)
dest.writeString(time)
}
companion object CREATOR : Parcelable.Creator<RemindersItem> {
override fun createFromParcel(source: Parcel): RemindersItem = RemindersItem(source)
override fun newArray(size: Int): Array<RemindersItem?> = arrayOfNulls(size)
}
constructor(source: Parcel) {
id = source.readString()
startDate = source.readString()
time = source.readString()
}
constructor()
override fun equals(other: Any?): Boolean {
return if (other is RemindersItem) {
this.id == other.id
} else super.equals(other)
}
override fun hashCode(): Int {
return id?.hashCode() ?: 0
}
fun getZonedDateTime(): ZonedDateTime? {
if (time == null) {
return null
}
val formatter: DateTimeFormatter =
DateTimeFormatterBuilder().append(DateTimeFormatter.ISO_LOCAL_DATE)
.appendPattern("['T'][' ']")
.append(DateTimeFormatter.ISO_LOCAL_TIME)
.appendPattern("[XX]")
.toFormatter()
val parsed: TemporalAccessor = formatter.parseBest(
time,
ZonedDateTime::from, LocalDateTime::from
)
return if (parsed is ZonedDateTime) {
parsed
} else {
val defaultZone: ZoneId = ZoneId.of("UTC")
(parsed as LocalDateTime).atZone(defaultZone)
}
}
fun getLocalZonedDateTimeInstant(): Instant? {
val formatter: DateTimeFormatter =
DateTimeFormatterBuilder().append(DateTimeFormatter.ISO_LOCAL_DATE)
.appendPattern("['T'][' ']")
.append(DateTimeFormatter.ISO_LOCAL_TIME)
.appendPattern("[XX]")
.toFormatter()
val parsed: TemporalAccessor = formatter.parseBest(
time,
ZonedDateTime::from, LocalDateTime::from
)
return if (parsed is ZonedDateTime) {
parsed.withZoneSameLocal(ZoneId.systemDefault())?.toInstant()
} else {
val defaultZone: ZoneId = ZoneId.of("UTC")
(parsed as LocalDateTime).atZone(defaultZone).withZoneSameLocal(ZoneId.systemDefault())?.toInstant()
}
}
}
| gpl-3.0 | 7974d929440e30f0db04301ad10abc85 | 30.27 | 112 | 0.607065 | 4.889394 | false | false | false | false |
StepicOrg/stepic-android | app/src/main/java/org/stepik/android/view/submission/ui/dialog/SubmissionsDialogFragment.kt | 1 | 16605 | package org.stepik.android.view.submission.ui.dialog
import android.app.Dialog
import android.graphics.PorterDuff
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.Window
import android.view.inputmethod.EditorInfo
import androidx.appcompat.content.res.AppCompatResources
import androidx.core.content.ContextCompat
import androidx.core.graphics.drawable.DrawableCompat
import androidx.core.view.isVisible
import androidx.core.widget.addTextChangedListener
import androidx.fragment.app.DialogFragment
import androidx.fragment.app.viewModels
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.LinearLayoutManager
import kotlinx.android.synthetic.main.dialog_submissions.*
import kotlinx.android.synthetic.main.empty_default.*
import kotlinx.android.synthetic.main.error_no_connection_with_button.*
import kotlinx.android.synthetic.main.view_submissions_search_toolbar.*
import kotlinx.android.synthetic.main.view_subtitled_toolbar.*
import org.stepic.droid.R
import org.stepic.droid.base.App
import org.stepic.droid.core.ScreenManager
import org.stepic.droid.preferences.UserPreferences
import org.stepic.droid.ui.util.setTintedNavigationIcon
import org.stepic.droid.ui.util.snackbar
import org.stepik.android.domain.filter.model.SubmissionsFilterQuery
import org.stepik.android.domain.review_instruction.model.ReviewInstructionData
import org.stepik.android.domain.submission.model.SubmissionItem
import org.stepik.android.model.Step
import org.stepik.android.model.Submission
import org.stepik.android.model.attempts.Attempt
import org.stepik.android.model.user.User
import org.stepik.android.presentation.submission.SubmissionsPresenter
import org.stepik.android.presentation.submission.SubmissionsView
import org.stepik.android.view.base.ui.extension.setTintList
import org.stepik.android.view.comment.ui.dialog.SolutionCommentDialogFragment
import org.stepik.android.view.in_app_web_view.ui.dialog.InAppWebViewDialogFragment
import org.stepik.android.view.step_quiz_review.routing.StepQuizReviewDeepLinkBuilder
import org.stepik.android.view.submission.routing.SubmissionDeepLinkBuilder
import org.stepik.android.view.submission.ui.adapter.delegate.SubmissionDataAdapterDelegate
import org.stepik.android.view.ui.delegate.ViewStateDelegate
import ru.nobird.android.core.model.PaginationDirection
import ru.nobird.android.ui.adapterdelegates.dsl.adapterDelegate
import ru.nobird.android.ui.adapters.DefaultDelegateAdapter
import ru.nobird.android.view.base.ui.extension.argument
import ru.nobird.android.view.base.ui.extension.hideKeyboard
import ru.nobird.android.view.base.ui.extension.setOnPaginationListener
import ru.nobird.android.view.base.ui.extension.showIfNotExists
import javax.inject.Inject
class SubmissionsDialogFragment :
DialogFragment(),
SubmissionsView,
SubmissionsQueryFilterDialogFragment.Callback,
InAppWebViewDialogFragment.Callback {
companion object {
const val TAG = "SubmissionsDialogFragment"
private const val ARG_STATUS = "status"
private const val ARG_REVIEW_INSTRUCTION = "review_instruction"
fun newInstance(
step: Step,
isTeacher: Boolean = false,
userId: Long = -1L,
status: Submission.Status? = null,
reviewInstructionData: ReviewInstructionData? = null,
isSelectionEnabled: Boolean = false
): DialogFragment =
SubmissionsDialogFragment()
.apply {
this.step = step
this.isTeacher = isTeacher
this.userId = userId
this.isSelectionEnabled = isSelectionEnabled
this.arguments?.putSerializable(ARG_STATUS, status)
this.arguments?.putParcelable(ARG_REVIEW_INSTRUCTION, reviewInstructionData)
}
}
@Inject
internal lateinit var userPreferences: UserPreferences
@Inject
internal lateinit var viewModelFactory: ViewModelProvider.Factory
@Inject
internal lateinit var screenManager: ScreenManager
@Inject
lateinit var submissionDeepLinkBuilder: SubmissionDeepLinkBuilder
@Inject
internal lateinit var stepQuizReviewDeepLinkBuilder: StepQuizReviewDeepLinkBuilder
private var step: Step by argument()
private var isTeacher: Boolean by argument()
private var userId: Long by argument()
private var isSelectionEnabled: Boolean by argument()
private var status: Submission.Status? = null
private var reviewInstructionData: ReviewInstructionData? = null
private var submissionsFilterQuery = SubmissionsFilterQuery.DEFAULT_QUERY
private val submissionsPresenter: SubmissionsPresenter by viewModels { viewModelFactory }
private lateinit var submissionItemAdapter: DefaultDelegateAdapter<SubmissionItem>
private lateinit var viewContentStateDelegate: ViewStateDelegate<SubmissionsView.ContentState>
private val placeholders = List(10) { SubmissionItem.Placeholder }
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val dialog = super.onCreateDialog(savedInstanceState)
dialog.setCanceledOnTouchOutside(false)
dialog.setCancelable(false)
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE)
return dialog
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setStyle(STYLE_NO_TITLE, R.style.ThemeOverlay_AppTheme_Dialog_Fullscreen)
injectComponent()
status = arguments?.getSerializable(ARG_STATUS) as? Submission.Status
reviewInstructionData = arguments?.getParcelable<ReviewInstructionData>(ARG_REVIEW_INSTRUCTION)
submissionsPresenter.fetchSubmissions(
step.id,
isTeacher,
submissionsFilterQuery.copy(
status = status?.scope,
search = if (userId == -1L) null else resources.getString(R.string.submissions_user_filter, userId)
),
reviewInstructionData?.reviewInstruction
)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? =
inflater.inflate(R.layout.dialog_submissions, container, false)
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
centeredToolbar.isVisible = !isTeacher
searchViewContainer.isVisible = isTeacher
centeredToolbarTitle.setText(if (isSelectionEnabled) R.string.submissions_select_title else R.string.submissions_title)
centeredToolbar.setNavigationOnClickListener { dismiss() }
centeredToolbar.setTintedNavigationIcon(R.drawable.ic_close_dark)
AppCompatResources
.getDrawable(requireContext(), R.drawable.ic_close_dark)
?.setTintList(requireContext(), R.attr.colorControlNormal)
?.let { backIcon.setImageDrawable(it) }
backIcon.setOnClickListener { dismiss() }
clearSearchButton.setOnClickListener {
searchSubmissionsEditText.text?.clear()
fetchSearchQuery()
}
filterIcon.setOnClickListener { submissionsPresenter.onFilterMenuItemClicked() }
searchSubmissionsEditText.background = AppCompatResources
.getDrawable(requireContext(), R.drawable.bg_shape_rounded)
?.mutate()
?.let { DrawableCompat.wrap(it) }
?.also {
DrawableCompat.setTint(it, ContextCompat.getColor(requireContext(), R.color.color_elevation_overlay_1dp))
DrawableCompat.setTintMode(it, PorterDuff.Mode.SRC_IN)
}
viewContentStateDelegate = ViewStateDelegate()
viewContentStateDelegate.addState<SubmissionsView.ContentState.Idle>()
viewContentStateDelegate.addState<SubmissionsView.ContentState.Loading>(swipeRefresh)
viewContentStateDelegate.addState<SubmissionsView.ContentState.NetworkError>(error)
viewContentStateDelegate.addState<SubmissionsView.ContentState.Content>(swipeRefresh)
viewContentStateDelegate.addState<SubmissionsView.ContentState.ContentLoading>(swipeRefresh)
viewContentStateDelegate.addState<SubmissionsView.ContentState.ContentEmpty>(report_empty)
submissionItemAdapter = DefaultDelegateAdapter()
submissionItemAdapter += SubmissionDataAdapterDelegate(
currentUserId = userPreferences.userId,
isTeacher = isTeacher,
isSelectionEnabled = isSelectionEnabled,
reviewInstructionData = reviewInstructionData,
actionListener = object : SubmissionDataAdapterDelegate.ActionListener {
override fun onSubmissionClicked(data: SubmissionItem.Data) {
showSolution(data)
}
override fun onUserClicked(user: User) {
screenManager.openProfile(requireContext(), user.id)
}
override fun onItemClicked(data: SubmissionItem.Data) {
(activity as? Callback
?: parentFragment as? Callback
?: targetFragment as? Callback)
?.onSubmissionSelected(data.submission, data.attempt)
dismiss()
}
override fun onViewSubmissionsClicked(submissionDataItem: SubmissionItem.Data) {
val userIdQuery = resources.getString(R.string.submissions_user_filter, submissionDataItem.user.id)
searchSubmissionsEditText.setText(userIdQuery)
fetchSearchQuery()
}
override fun onSeeSubmissionReviewAction(submissionId: Long) {
val title = getString(R.string.comment_solution_pattern, submissionId)
val url = submissionDeepLinkBuilder.createSubmissionLink(step.id, submissionId)
openInWeb(title, url)
}
override fun onSeeReviewsReviewAction(session: Long) {
val title = getString(R.string.step_quiz_review_taken_title)
val url = stepQuizReviewDeepLinkBuilder.createTakenReviewDeepLink(session)
openInWeb(title, url)
}
}
)
submissionItemAdapter +=
adapterDelegate<SubmissionItem, SubmissionItem.Placeholder>(R.layout.item_submission_placeholder)
with(recycler) {
adapter = submissionItemAdapter
layoutManager = LinearLayoutManager(context)
setOnPaginationListener { paginationDirection ->
if (paginationDirection == PaginationDirection.NEXT) {
submissionsPresenter.fetchNextPage(step.id, isTeacher, reviewInstructionData?.reviewInstruction)
}
}
addItemDecoration(DividerItemDecoration(context, DividerItemDecoration.VERTICAL).apply {
ContextCompat.getDrawable(context, R.drawable.bg_submission_item_divider)?.let(::setDrawable)
})
}
swipeRefresh.setOnRefreshListener { submissionsPresenter.fetchSubmissions(step.id, isTeacher, submissionsFilterQuery, reviewInstructionData?.reviewInstruction, forceUpdate = true) }
tryAgain.setOnClickListener { submissionsPresenter.fetchSubmissions(step.id, isTeacher, submissionsFilterQuery, reviewInstructionData?.reviewInstruction, forceUpdate = true) }
searchSubmissionsEditText.setOnEditorActionListener { _, actionId, _ ->
if (actionId == EditorInfo.IME_ACTION_SEARCH) {
fetchSearchQuery()
return@setOnEditorActionListener true
}
return@setOnEditorActionListener false
}
searchSubmissionsEditText.addTextChangedListener {
if (it.isNullOrEmpty()) {
clearSearchButton.isVisible = false
searchSubmissionsEditText.setPadding(resources.getDimensionPixelSize(R.dimen.submissions_search_padding_left), 0, resources.getDimensionPixelSize(R.dimen.submissions_search_padding_without_text), 0)
} else {
clearSearchButton.isVisible = true
searchSubmissionsEditText.setPadding(resources.getDimensionPixelSize(R.dimen.submissions_search_padding_left), 0, resources.getDimensionPixelSize(R.dimen.submissions_search_padding_with_text), 0)
}
}
val userIdQuery = if (userId == -1L) null else resources.getString(R.string.submissions_user_filter, userId)
userIdQuery?.let { searchSubmissionsEditText.setText(it) }
}
private fun injectComponent() {
App.component()
.submissionComponentBuilder()
.build()
.inject(this)
}
override fun onStart() {
super.onStart()
dialog
?.window
?.let { window ->
window.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)
window.setWindowAnimations(R.style.ThemeOverlay_AppTheme_Dialog_Fullscreen)
}
submissionsPresenter.attachView(this)
}
override fun onStop() {
submissionsPresenter.detachView(this)
super.onStop()
}
override fun setState(state: SubmissionsView.State) {
swipeRefresh.isRefreshing = false
if (state is SubmissionsView.State.Data) {
viewContentStateDelegate.switchState(state.contentState)
filterIcon.setImageResource(getFilterIcon(state.submissionsFilterQuery))
submissionsFilterQuery = state.submissionsFilterQuery
submissionItemAdapter.items =
when (state.contentState) {
is SubmissionsView.ContentState.Loading ->
placeholders
is SubmissionsView.ContentState.Content ->
state.contentState.items
is SubmissionsView.ContentState.ContentLoading ->
state.contentState.items + SubmissionItem.Placeholder
else ->
emptyList()
}
}
}
override fun showNetworkError() {
view?.snackbar(messageRes = R.string.connectionProblems)
}
override fun showSubmissionsFilterDialog(submissionsFilterQuery: SubmissionsFilterQuery) {
SubmissionsQueryFilterDialogFragment
.newInstance(submissionsFilterQuery, isPeerReview = step.actions?.doReview != null)
.showIfNotExists(childFragmentManager, SubmissionsQueryFilterDialogFragment.TAG)
}
override fun onSyncFilterQueryWithParent(submissionsFilterQuery: SubmissionsFilterQuery) {
submissionsPresenter.fetchSubmissions(step.id, isTeacher, submissionsFilterQuery, reviewInstructionData?.reviewInstruction, forceUpdate = true)
}
override fun onDismissed() {
submissionsPresenter.fetchSubmissions(step.id, isTeacher, submissionsFilterQuery, reviewInstructionData?.reviewInstruction, forceUpdate = true)
}
private fun showSolution(submissionItem: SubmissionItem.Data) {
SolutionCommentDialogFragment
.newInstance(step, submissionItem.attempt, submissionItem.submission)
.showIfNotExists(parentFragmentManager, SolutionCommentDialogFragment.TAG)
}
private fun getFilterIcon(updatedSubmissionQuery: SubmissionsFilterQuery): Int =
if (updatedSubmissionQuery == SubmissionsFilterQuery.DEFAULT_QUERY.copy(search = updatedSubmissionQuery.search)) {
R.drawable.ic_filter
} else {
R.drawable.ic_filter_active
}
private fun fetchSearchQuery() {
searchSubmissionsEditText.hideKeyboard()
searchSubmissionsEditText.clearFocus()
submissionsPresenter.fetchSubmissions(
step.id,
isTeacher,
submissionsFilterQuery.copy(search = searchSubmissionsEditText.text?.toString()),
reviewInstructionData?.reviewInstruction,
forceUpdate = true
)
}
private fun openInWeb(title: String, url: String) {
InAppWebViewDialogFragment
.newInstance(title, url, isProvideAuth = true)
.showIfNotExists(childFragmentManager, InAppWebViewDialogFragment.TAG)
}
interface Callback {
fun onSubmissionSelected(submission: Submission, attempt: Attempt)
}
} | apache-2.0 | c942993d9aa1ff10b41d0ce60f9897ad | 44.125 | 214 | 0.704306 | 5.339228 | false | false | false | false |
GKZX-HN/MyGithub | app/src/main/java/com/gkzxhn/mygithub/ui/activity/IssueDetailActivity.kt | 1 | 7313 | package com.gkzxhn.mygithub.ui.activity
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.os.Parcelable
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.Toolbar
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.widget.ImageView
import android.widget.RelativeLayout
import android.widget.TextView
import com.gkzxhn.balabala.base.BaseActivity
import com.gkzxhn.balabala.mvp.contract.BaseView
import com.gkzxhn.mygithub.R
import com.gkzxhn.mygithub.base.App
import com.gkzxhn.mygithub.bean.entity.Icon2Name
import com.gkzxhn.mygithub.bean.info.Comment
import com.gkzxhn.mygithub.constant.IntentConstant
import com.gkzxhn.mygithub.di.module.OAuthModule
import com.gkzxhn.mygithub.extension.dp2px
import com.gkzxhn.mygithub.extension.load
import com.gkzxhn.mygithub.extension.toast
import com.gkzxhn.mygithub.mvp.presenter.IssueDetailPresenter
import com.gkzxhn.mygithub.ui.adapter.IssueDetailAdapter
import com.gkzxhn.mygithub.utils.PopupWindowUtil
import com.ldoublem.loadingviewlib.view.LVGhost
import kotlinx.android.synthetic.main.activity_issue_detail.*
import javax.inject.Inject
/**
* Created by 方 on 2017/10/26.
*/
class IssueDetailActivity: BaseActivity(), BaseView {
private lateinit var adapter : IssueDetailAdapter
private lateinit var loading : LVGhost
@Inject
lateinit var presenter: IssueDetailPresenter
override fun launchActivity(intent: Intent) {
}
override fun showLoading() {
loading = LVGhost(this)
val params = RelativeLayout.LayoutParams(300f.dp2px().toInt(), 150f.dp2px().toInt())
params.addRule(RelativeLayout.CENTER_IN_PARENT)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
loading.elevation = 4f.dp2px()
}
loading.layoutParams = params
loading.startAnim()
ll_issue_detail.addView(loading, 3)
}
override fun hideLoading() {
loading.stopAnim()
ll_issue_detail.removeView(loading)
}
override fun showMessage() {
}
override fun killMyself() {
}
private lateinit var owner: String
private lateinit var name: String
private lateinit var repoName: String
private var number: Int = 0
override fun initView(savedInstanceState: Bundle?) {
setContentView(R.layout.activity_issue_detail)
owner = intent.getStringExtra(IntentConstant.OWNER)
name = intent.getStringExtra(IntentConstant.NAME)
repoName = intent.getStringExtra(IntentConstant.REPO)
number = intent.getIntExtra(IntentConstant.ISSUE_NUM, 0)
val content_tag = intent.getStringExtra(IntentConstant.TYPE)
when (content_tag) {
IntentConstant.OPEN -> {
status_view.setBackgroundResource(R.color.green)
toolbar.setBackgroundResource(R.color.green)
showStatus(true)
}
IntentConstant.CLOSED -> {
status_view.setBackgroundResource(R.color.red)
toolbar.setBackgroundResource(R.color.red)
showStatus(false)
}
else -> {
}
}
initTransition()
setToolBar()
setOnClick()
initRecyclerView()
initReplyView()
presenter.getComments(owner, repoName, number)
}
private fun setOnClick() {
val content_tag = intent.getStringExtra(IntentConstant.TYPE)
iv_closed.setOnClickListener {
when (content_tag) {
IntentConstant.OPEN -> {
presenter.changeIssueStatus(false, owner, repoName, number)
}
IntentConstant.CLOSED -> {
presenter.changeIssueStatus(true, owner, repoName, number)
}
else -> {
}
}
}
}
fun loadingStatusChange(){
iv_closed.visibility = View.GONE
pb_status.visibility = View.VISIBLE
}
fun showStatus(isOpen: Boolean) {
if (isOpen) {
iv_closed.setImageResource(R.drawable.closed)
}else {
iv_closed.setImageResource(R.drawable.open)
}
iv_closed.visibility = View.VISIBLE
pb_status.visibility = View.GONE
}
fun initTransition() {
}
private fun setToolBar() {
val title = intent.getStringExtra(IntentConstant.TITLE)
tv_toolbar_title.text = title
setToolBarBack(true)
}
private fun initReplyView() {
tv_reply.setOnClickListener {
view ->
PopupWindowUtil.liveCommentEdit(this, view, {
confirmed, comment ->
if (TextUtils.isEmpty(comment)) {
toast("您还未输入任何内容")
return@liveCommentEdit
}else{
presenter.postComment(comment)
}
})
}
}
private fun initRecyclerView() {
adapter = IssueDetailAdapter(null)
adapter.openLoadAnimation()
rv_issue_detail.layoutManager = LinearLayoutManager(this)
rv_issue_detail.adapter = adapter
adapter.setOnItemChildClickListener { adapter, view, position ->
when (view.id) {
R.id.img_avatar-> {
gotoUser((adapter.data[position] as Comment).user)
}
else -> {
}
}
}
val headView = LayoutInflater.from(this).inflate(R.layout.issue_head, ll_issue_detail, false)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
headView.transitionName = "transition_comment"
}
adapter.addHeaderView(headView)
val avatar = intent.getStringExtra(IntentConstant.AVATAR)
val time = intent.getStringExtra(IntentConstant.CREATE_TIME).substring(0, 10)
val name = intent.getStringExtra(IntentConstant.NAME)
val body = intent.getStringExtra(IntentConstant.BODY)
val imageView = headView.findViewById<ImageView>(R.id.img_avatar)
imageView.load(this, avatar, R.drawable.default_avatar)
imageView.setOnClickListener {
gotoUser(Icon2Name(avatar, name, ""))
}
headView.findViewById<TextView>(R.id.tv_name).text = name
headView.findViewById<TextView>(R.id.tv_create_time).text = time
headView.findViewById<TextView>(R.id.tv_body).text = body
}
/**
* 跳转个人页
*/
private fun gotoUser(owner: Parcelable) {
val intent = Intent(this, UserActivity::class.java)
val bundle = Bundle()
bundle.putParcelable(IntentConstant.USER, owner)
intent.putExtras(bundle)
startActivity(intent)
}
override fun setupComponent() {
App.getInstance()
.baseComponent
.plus(OAuthModule(this))
.inject(this)
}
override fun getToolbar(): Toolbar? = toolbar
override fun getStatusBar() : View? =status_view
fun loadData(comments: List<Comment>){
adapter.setNewData(comments)
}
fun addComment(comment: Comment) {
adapter.addData(0, comment)
}
} | gpl-3.0 | c591bf56d75cefc49d158301da7cae6c | 30.80786 | 101 | 0.636688 | 4.501236 | false | false | false | false |
CarlosEsco/tachiyomi | app/src/main/java/eu/kanade/data/category/CategoryRepositoryImpl.kt | 1 | 2514 | package eu.kanade.data.category
import eu.kanade.data.DatabaseHandler
import eu.kanade.domain.category.model.Category
import eu.kanade.domain.category.model.CategoryUpdate
import eu.kanade.domain.category.repository.CategoryRepository
import eu.kanade.tachiyomi.Database
import kotlinx.coroutines.flow.Flow
class CategoryRepositoryImpl(
private val handler: DatabaseHandler,
) : CategoryRepository {
override suspend fun get(id: Long): Category? {
return handler.awaitOneOrNull { categoriesQueries.getCategory(id, categoryMapper) }
}
override suspend fun getAll(): List<Category> {
return handler.awaitList { categoriesQueries.getCategories(categoryMapper) }
}
override fun getAllAsFlow(): Flow<List<Category>> {
return handler.subscribeToList { categoriesQueries.getCategories(categoryMapper) }
}
override suspend fun getCategoriesByMangaId(mangaId: Long): List<Category> {
return handler.awaitList {
categoriesQueries.getCategoriesByMangaId(mangaId, categoryMapper)
}
}
override fun getCategoriesByMangaIdAsFlow(mangaId: Long): Flow<List<Category>> {
return handler.subscribeToList {
categoriesQueries.getCategoriesByMangaId(mangaId, categoryMapper)
}
}
override suspend fun insert(category: Category) {
handler.await {
categoriesQueries.insert(
name = category.name,
order = category.order,
flags = category.flags,
)
}
}
override suspend fun updatePartial(update: CategoryUpdate) {
handler.await {
updatePartialBlocking(update)
}
}
override suspend fun updatePartial(updates: List<CategoryUpdate>) {
handler.await(true) {
for (update in updates) {
updatePartialBlocking(update)
}
}
}
private fun Database.updatePartialBlocking(update: CategoryUpdate) {
categoriesQueries.update(
name = update.name,
order = update.order,
flags = update.flags,
categoryId = update.id,
)
}
override suspend fun updateAllFlags(flags: Long?) {
handler.await {
categoriesQueries.updateAllFlags(flags)
}
}
override suspend fun delete(categoryId: Long) {
handler.await {
categoriesQueries.delete(
categoryId = categoryId,
)
}
}
}
| apache-2.0 | d33211428ca7b8123f137679ad51987f | 28.928571 | 91 | 0.645585 | 4.872093 | false | false | false | false |
garmax1/material-flashlight | app/src/main/java/co/garmax/materialflashlight/repositories/SettingsRepository.kt | 1 | 2449 | package co.garmax.materialflashlight.repositories
import android.content.Context
import co.garmax.materialflashlight.features.modes.IntervalStrobeMode
import co.garmax.materialflashlight.features.modes.ModeBase
import co.garmax.materialflashlight.features.modules.ModuleBase
class SettingsRepository(context: Context) {
private val sharedPreferences = context.getSharedPreferences("settings", Context.MODE_PRIVATE)
var isKeepScreenOn: Boolean
get() = sharedPreferences.getBoolean(KEEP_SCREEN_ON, false)
set(isKeepScreenOn) {
sharedPreferences.edit().putBoolean(KEEP_SCREEN_ON, isKeepScreenOn).apply()
}
var isAutoTurnedOn: Boolean
get() = sharedPreferences.getBoolean(AUTO_TURN_ON, false)
set(isAutoTurnOn) {
sharedPreferences.edit().putBoolean(AUTO_TURN_ON, isAutoTurnOn).apply()
}
var mode: ModeBase.Mode
get() {
val mode = sharedPreferences.getString(MODE, null)
return mode?.let { ModeBase.Mode.valueOf(it) } ?: ModeBase.Mode.MODE_TORCH
}
set(mode) {
sharedPreferences.edit().putString(MODE, mode.name).apply()
}
var module: ModuleBase.Module
get() {
val module = sharedPreferences.getString(MODULE, null)
return module?.let { ModuleBase.Module.valueOf(it) }
?: ModuleBase.Module.MODULE_CAMERA_FLASHLIGHT
}
set(module) {
sharedPreferences.edit().putString(MODULE, module.name).apply()
}
var strobeOnPeriod: Int
get() {
return sharedPreferences.getInt(STROBE_ON_PERIOD, IntervalStrobeMode.DEFAULT_STROBE_PERIOD)
}
set(value) {
sharedPreferences.edit().putInt(STROBE_ON_PERIOD, value).apply()
}
var strobeOffPeriod: Int
get() {
return sharedPreferences.getInt(STROBE_OFF_PERIOD, IntervalStrobeMode.DEFAULT_DELAY_PERIOD)
}
set(value) {
sharedPreferences.edit().putInt(STROBE_OFF_PERIOD, value).apply()
}
companion object {
private const val KEEP_SCREEN_ON = "keep_screen_on"
private const val MODE = "mode_name"
private const val MODULE = "module_name"
private const val AUTO_TURN_ON = "auto_turn_on"
private const val STROBE_ON_PERIOD = "strobe_on_period"
private const val STROBE_OFF_PERIOD = "strobe_off_period"
}
} | apache-2.0 | 7cd49379a50783d60d7e35c47f1984b3 | 35.567164 | 103 | 0.652511 | 4.365419 | false | false | false | false |
suchaHassle/kotNES | src/ui/HeavyDisplayPanel.kt | 1 | 639 | package kotNES.ui
import kotNES.Emulator
import java.awt.Color
import java.awt.Dimension
import java.awt.Graphics
import java.awt.Panel
class HeavyDisplayPanel(private var emulator: Emulator) : Panel() {
init {
background = Color.BLACK
val sz = Dimension(emulator.ppu.gameWidth*2, emulator.ppu.gameHeight*2)
maximumSize = sz
minimumSize = sz
size = sz
preferredSize = sz
ignoreRepaint = true
}
override fun addNotify() {
super.addNotify()
emulator.display = this
}
override fun paint(g: Graphics?) {
throw RuntimeException()
}
} | mit | c5ba7c8ffb370a744fbc349ec08daedc | 19.645161 | 79 | 0.643192 | 4.203947 | false | false | false | false |
y20k/trackbook | app/src/main/java/org/y20k/trackbook/TrackingToggleTileService.kt | 1 | 4639 | /*
* TrackingToggleTileService.kt
* Implements the TrackingToggleTileService service
* A TrackingToggleTileService toggles the recording state from a quick settings tile
*
* This file is part of
* TRACKBOOK - Movement Recorder for Android
*
* Copyright (c) 2016-22 - Y20K.org
* Licensed under the MIT-License
* http://opensource.org/licenses/MIT
*
* Trackbook uses osmdroid - OpenStreetMap-Tools for Android
* https://github.com/osmdroid/osmdroid
*/
package org.y20k.trackbook
import android.content.Intent
import android.content.SharedPreferences
import android.graphics.drawable.Icon
import android.os.Build
import android.service.quicksettings.Tile
import android.service.quicksettings.TileService
import org.y20k.trackbook.helpers.LogHelper
import org.y20k.trackbook.helpers.PreferencesHelper
/*
* TrackingToggleTileService class
*/
class TrackingToggleTileService: TileService() {
/* Define log tag */
private val TAG: String = LogHelper.makeLogTag(TrackingToggleTileService::class.java)
/* Main class variables */
private var bound: Boolean = false
private var trackingState: Int = Keys.STATE_TRACKING_NOT
private lateinit var trackerService: TrackerService
/* Overrides onTileAdded from TileService */
override fun onTileAdded() {
super.onTileAdded()
// get saved tracking state
trackingState = PreferencesHelper.loadTrackingState()
// set up tile
updateTile()
}
/* Overrides onTileRemoved from TileService */
override fun onTileRemoved() {
super.onTileRemoved()
}
/* Overrides onStartListening from TileService (tile becomes visible) */
override fun onStartListening() {
super.onStartListening()
// get saved tracking state
trackingState = PreferencesHelper.loadTrackingState()
// set up tile
updateTile()
// register listener for changes in shared preferences
PreferencesHelper.registerPreferenceChangeListener(sharedPreferenceChangeListener)
}
/* Overrides onClick from TileService */
override fun onClick() {
super.onClick()
when (trackingState) {
Keys.STATE_TRACKING_ACTIVE -> stopTracking()
else -> startTracking()
}
}
/* Overrides onStopListening from TileService (tile no longer visible) */
override fun onStopListening() {
super.onStopListening()
// unregister listener for changes in shared preferences
PreferencesHelper.unregisterPreferenceChangeListener(sharedPreferenceChangeListener)
}
/* Overrides onDestroy from Service */
override fun onDestroy() {
super.onDestroy()
}
/* Update quick settings tile */
private fun updateTile() {
val tile: Tile = qsTile
tile.icon = Icon.createWithResource(this, R.drawable.ic_notification_icon_small_24dp)
when (trackingState) {
Keys.STATE_TRACKING_ACTIVE -> {
tile.label = getString(R.string.quick_settings_tile_title_pause)
tile.contentDescription = getString(R.string.descr_quick_settings_tile_title_pause)
tile.state = Tile.STATE_ACTIVE
}
else -> {
tile.label = getString(R.string.quick_settings_tile_title_start)
tile.contentDescription = getString(R.string.descr_quick_settings_tile_title_start)
tile.state = Tile.STATE_INACTIVE
}
}
tile.updateTile()
}
/* Start tracking */
private fun startTracking() {
val intent = Intent(application, TrackerService::class.java)
intent.action = Keys.ACTION_START
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
// ... start service in foreground to prevent it being killed on Oreo
application.startForegroundService(intent)
} else {
application.startService(intent)
}
}
/* Stop tracking */
private fun stopTracking() {
val intent = Intent(application, TrackerService::class.java)
intent.action = Keys.ACTION_STOP
application.startService(intent)
}
/*
* Defines the listener for changes in shared preferences
*/
private val sharedPreferenceChangeListener = SharedPreferences.OnSharedPreferenceChangeListener { sharedPreferences, key ->
when (key) {
Keys.PREF_TRACKING_STATE -> {
trackingState = PreferencesHelper.loadTrackingState()
updateTile()
}
}
}
/*
* End of declaration
*/
} | mit | ab9ae802df64890fd460e1c058432cb7 | 28.935484 | 127 | 0.663721 | 5.020563 | false | false | false | false |
Heiner1/AndroidAPS | omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/packet/PayloadSplitter.kt | 1 | 3525 | package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.packet
import java.lang.Integer.min
import java.util.zip.CRC32
internal class PayloadSplitter(private val payload: ByteArray) {
fun splitInPackets(): List<BlePacket> {
if (payload.size <= FirstBlePacket.CAPACITY_WITH_THE_OPTIONAL_PLUS_ONE_PACKET) {
return splitInOnePacket()
}
val ret = ArrayList<BlePacket>()
val crc32 = payload.crc32()
val middleFragments = (payload.size - FirstBlePacket.CAPACITY_WITH_MIDDLE_PACKETS) / MiddleBlePacket.CAPACITY
val rest =
(
(payload.size - middleFragments * MiddleBlePacket.CAPACITY) -
FirstBlePacket.CAPACITY_WITH_MIDDLE_PACKETS
).toByte()
ret.add(
FirstBlePacket(
fullFragments = middleFragments + 1,
payload = payload.copyOfRange(0, FirstBlePacket.CAPACITY_WITH_MIDDLE_PACKETS)
)
)
for (i in 1..middleFragments) {
val p = payload.copyOfRange(
FirstBlePacket.CAPACITY_WITH_MIDDLE_PACKETS + (i - 1) * MiddleBlePacket.CAPACITY,
FirstBlePacket.CAPACITY_WITH_MIDDLE_PACKETS + i * MiddleBlePacket.CAPACITY
)
ret.add(
MiddleBlePacket(
index = i.toByte(),
payload = p
)
)
}
val end = min(LastBlePacket.CAPACITY, rest.toInt())
ret.add(
LastBlePacket(
index = (middleFragments + 1).toByte(),
size = rest,
payload = payload.copyOfRange(
middleFragments * MiddleBlePacket.CAPACITY + FirstBlePacket.CAPACITY_WITH_MIDDLE_PACKETS,
middleFragments * MiddleBlePacket.CAPACITY + FirstBlePacket.CAPACITY_WITH_MIDDLE_PACKETS + end
),
crc32 = crc32
)
)
if (rest > LastBlePacket.CAPACITY) {
ret.add(
LastOptionalPlusOneBlePacket(
index = (middleFragments + 2).toByte(),
size = (rest - LastBlePacket.CAPACITY).toByte(),
payload = payload.copyOfRange(
middleFragments * MiddleBlePacket.CAPACITY +
FirstBlePacket.CAPACITY_WITH_MIDDLE_PACKETS +
LastBlePacket.CAPACITY,
payload.size
)
)
)
}
return ret
}
private fun splitInOnePacket(): List<BlePacket> {
val ret = ArrayList<BlePacket>()
val crc32 = payload.crc32()
val end = min(FirstBlePacket.CAPACITY_WITHOUT_MIDDLE_PACKETS, payload.size)
ret.add(
FirstBlePacket(
fullFragments = 0,
payload = payload.copyOfRange(0, end),
size = payload.size.toByte(),
crc32 = crc32
)
)
if (payload.size > FirstBlePacket.CAPACITY_WITHOUT_MIDDLE_PACKETS) {
ret.add(
LastOptionalPlusOneBlePacket(
index = 1,
payload = payload.copyOfRange(end, payload.size),
size = (payload.size - end).toByte()
)
)
}
return ret
}
}
internal fun ByteArray.crc32(): Long {
val crc = CRC32()
crc.update(this)
return crc.value
}
| agpl-3.0 | 652896ae609a029aac27631b6f8ad944 | 35.71875 | 117 | 0.530496 | 4.706275 | false | false | false | false |
kevinhinterlong/archwiki-viewer | app/src/main/java/com/jtmcn/archwiki/viewer/WikiClient.kt | 2 | 5070 | package com.jtmcn.archwiki.viewer
import android.os.Handler
import android.view.View
import android.webkit.WebView
import android.webkit.WebViewClient
import android.widget.ProgressBar
import androidx.appcompat.app.ActionBar
import com.jtmcn.archwiki.viewer.data.WikiPage
import com.jtmcn.archwiki.viewer.tasks.Fetch
import com.jtmcn.archwiki.viewer.utils.openLink
import timber.log.Timber
import java.util.*
class WikiClient(private val progressBar: ProgressBar, private val actionBar: ActionBar?, private val webView: WebView) : WebViewClient() {
private val webPageStack = Stack<WikiPage>()
private val loadedUrls = HashSet<String>() // this is used to see if we should restore the scroll position
private var lastLoadedUrl: String? = null //https://stackoverflow.com/questions/11601134/android-webview-function-onpagefinished-is-called-twice
/**
* Get the number of pages that are in the history.
*
* @return number of pages on the stack.
*/
val historyStackSize: Int
get() = webPageStack.size
/**
* Returns null or the current page.
*
* @return The current page
*/
val currentWebPage: WikiPage?
get() = if (webPageStack.size == 0) null else webPageStack.peek()
/*
* Manage page history
*/
private fun addHistory(wikiPage: WikiPage) {
if (webPageStack.size > 0) {
Timber.d("Saving ${currentWebPage?.pageTitle} at ${webView.scrollY}")
currentWebPage!!.scrollPosition = webView.scrollY
}
webPageStack.push(wikiPage)
Timber.i("Adding page ${wikiPage.pageTitle}. Stack size= ${webPageStack.size}")
}
/**
* Loads the html from a [WikiPage] into the webview.
*
* @param wikiPage the page to be loaded.
*/
fun loadWikiHtml(wikiPage: WikiPage) {
webView.loadDataWithBaseURL(
wikiPage.pageUrl,
wikiPage.htmlString,
TEXT_HTML_MIME,
UTF_8,
null
)
setSubtitle(wikiPage.pageTitle)
}
/**
* Intercept url when clicked. If it's part of the wiki load it here.
* If not, open the device's default browser.
*
* @param view webview being loaded into
* @param url url being loaded
* @return true if should override url loading
*/
override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean {
// deprecated until min api 21 is used
if (url.startsWith(ARCHWIKI_BASE)) {
webView.stopLoading()
Fetch.page({
addHistory(it)
loadWikiHtml(currentWebPage!!)
}, url)
showProgress()
return false
} else {
openLink(url, view.context)
return true
}
}
override fun onPageFinished(view: WebView, url: String) {
super.onPageFinished(view, url)
val currentWebPage = currentWebPage
Timber.d("Calling onPageFinished(view, ${currentWebPage?.pageTitle})")
// make sure we're loading the current page and that
// this page's url doesn't have an anchor (only on first page load)
if (url == currentWebPage?.pageUrl && url != lastLoadedUrl) {
if (!isFirstLoad(currentWebPage)) {
Handler().postDelayed({
val scrollY = currentWebPage.scrollPosition
Timber.d("Restoring ${currentWebPage.pageTitle} at $scrollY")
webView.scrollY = scrollY
}, 25)
}
lastLoadedUrl = url
hideProgress()
}
}
private fun isFirstLoad(currentWebPage: WikiPage): Boolean {
return if (loadedUrls.contains(currentWebPage.pageUrl)) {
false
} else {
loadedUrls.add(currentWebPage.pageUrl)
true
}
}
private fun showProgress() {
progressBar.visibility = View.VISIBLE
}
private fun hideProgress() {
progressBar.visibility = View.GONE
}
private fun setSubtitle(title: String?) {
actionBar?.subtitle = title
}
/**
* Go back to the last loaded page.
*/
fun goBackHistory() {
val (pageUrl, pageTitle) = webPageStack.pop()
loadedUrls.remove(pageUrl)
Timber.i("Removing $pageTitle from stack")
val newPage = webPageStack.peek()
loadWikiHtml(newPage)
}
fun refreshPage() {
lastLoadedUrl = null // set to null if page should restore position, otherwise start at top of page
val currentWebPage = currentWebPage
if (currentWebPage != null) {
val scrollPosition = currentWebPage.scrollPosition
val url = currentWebPage.pageUrl
showProgress()
Fetch.page({ wikiPage ->
webPageStack.pop()
webPageStack.push(wikiPage)
wikiPage.scrollPosition = scrollPosition
loadWikiHtml(wikiPage)
}, url)
}
}
} | apache-2.0 | c0f878a9220429455150a10f9aaf48e1 | 30.893082 | 148 | 0.60927 | 4.630137 | false | false | false | false |
bajdcc/jMiniLang | src/main/kotlin/com/bajdcc/LALR1/interpret/module/web/ModuleNetWebServer.kt | 1 | 5255 | package com.bajdcc.LALR1.interpret.module.web
import com.bajdcc.LALR1.grammar.runtime.data.RuntimeMap
import com.bajdcc.LALR1.interpret.module.ModuleNet
import org.apache.log4j.Logger
import java.io.ByteArrayOutputStream
import java.io.IOException
import java.net.InetAddress
import java.net.InetSocketAddress
import java.net.StandardSocketOptions
import java.nio.ByteBuffer
import java.nio.channels.SelectionKey
import java.nio.channels.Selector
import java.nio.channels.ServerSocketChannel
import java.nio.channels.SocketChannel
import java.nio.charset.StandardCharsets.UTF_8
import java.util.concurrent.ConcurrentLinkedDeque
/**
* 【模块】网页服务器
*
* @author bajdcc
*/
class ModuleNetWebServer(private val port: Int) : Runnable {
var isRunning = true
private val queue = ConcurrentLinkedDeque<ModuleNetWebContext>()
fun dequeue(): ModuleNetWebContext? {
return queue.poll()
}
fun hasRequest(): Boolean {
return !queue.isEmpty()
}
fun peekRequest(): RuntimeMap? {
val ctx = queue.peek() ?: return null
return ctx.reqHeader
}
override fun run() {
try {
val selector = Selector.open()
val serverSocketChannel = ServerSocketChannel.open()
val serverSocket = serverSocketChannel.socket()
serverSocket.reuseAddress = true
serverSocket.bind(InetSocketAddress(port))
val address = InetAddress.getLocalHost()
logger.info("Web server ip: " + address.hostAddress)
logger.info("Web server hostname: " + address.hostName)
logger.info("Web server port: $port")
serverSocketChannel.configureBlocking(false)
serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT)
ModuleNet.instance.webServer = this
while (isRunning) {
val readyChannels = selector.select(1000)
if (readyChannels == 0)
continue
val keys = selector.selectedKeys()
val iterator = keys.iterator()
while (iterator.hasNext()) {
val key = iterator.next()
var socketChannel: SocketChannel? = null
try {
if (key.isAcceptable) {
val server = key.channel() as ServerSocketChannel
socketChannel = server.accept()
if (socketChannel != null) {
socketChannel.configureBlocking(false)
socketChannel.register(selector, SelectionKey.OP_READ)
}
} else if (key.isReadable) {
socketChannel = key.channel() as SocketChannel
val requestHeader = handleHeader(socketChannel)
if (requestHeader != null) {
val ctx = ModuleNetWebContext(key)
ctx.setReqHeader(requestHeader)
logger.info(String.format("From: %s, Url: %s",
(socketChannel.remoteAddress as InetSocketAddress).hostString,
ctx.url))
Thread(ModuleNetWebHandler(ctx)).start()
queue.add(ctx)
} else {
socketChannel.close()
}
} else if (key.isWritable) {
socketChannel = key.channel() as SocketChannel
if (socketChannel.getOption(StandardSocketOptions.SO_KEEPALIVE)) {
socketChannel.register(selector, SelectionKey.OP_READ)
} else {
socketChannel.close()
}
}
} catch (e: IOException) {
socketChannel?.close()
e.printStackTrace()
} finally {
iterator.remove()
}
}
}
serverSocket.close()
serverSocketChannel.close()
selector.close()
logger.info("Web server exit")
} catch (e: Exception) {
e.printStackTrace()
}
ModuleNet.instance.webServer = null
}
@Throws(IOException::class)
private fun handleHeader(socketChannel: SocketChannel): String? {
val buffer = ByteBuffer.allocate(1024)
var bytes: ByteArray
val baos = ByteArrayOutputStream()
var size = socketChannel.read(buffer)
while (size > 0) {
bytes = ByteArray(size)
buffer.flip()
buffer.get(bytes)
baos.write(bytes)
buffer.clear()
size = socketChannel.read(buffer)
}
bytes = baos.toByteArray()
return if (bytes.size == 0) null else String(bytes, UTF_8)
}
companion object {
private val logger = Logger.getLogger("web")
}
}
| mit | 5a7851a7ad53da0991368f3753b98514 | 37.792593 | 102 | 0.532175 | 5.530095 | false | false | false | false |
DanilaFe/abacus | core/src/main/kotlin/org/nwapw/abacus/context/MutableEvaluationContext.kt | 1 | 4124 | package org.nwapw.abacus.context
import org.nwapw.abacus.Abacus
import org.nwapw.abacus.exception.NumberReducerException
import org.nwapw.abacus.exception.ReductionException
import org.nwapw.abacus.number.NumberInterface
import org.nwapw.abacus.plugin.NumberImplementation
import org.nwapw.abacus.tree.nodes.*
/**
* A reduction context that is mutable.
*
* @param parent the parent of this context.
* @param numberImplementation the number implementation used in this context.
* @param abacus the abacus instance used.
*/
class MutableEvaluationContext(parent: EvaluationContext? = null,
numberImplementation: NumberImplementation? = null,
abacus: Abacus? = null) :
PluginEvaluationContext(parent, numberImplementation, abacus) {
override var numberImplementation: NumberImplementation? = super.numberImplementation
override var abacus: Abacus? = super.abacus
/**
* Writes data stored in the [other] context over data stored in this one.
* @param other the context from which to copy data.
*/
fun apply(other: EvaluationContext) {
if(other.numberImplementation != null) numberImplementation = other.numberImplementation
for(name in other.variables) {
setVariable(name, other.getVariable(name) ?: continue)
}
for(name in other.definitions) {
setDefinition(name, other.getDefinition(name) ?: continue)
}
}
override fun reduceNode(treeNode: TreeNode, vararg children: Any): NumberInterface {
val oldNumberImplementation = numberImplementation
val abacus = inheritedAbacus
val promotionManager = abacus.promotionManager
val toReturn = when(treeNode){
is NumberNode -> {
inheritedNumberImplementation.instanceForString(treeNode.number)
}
is VariableNode -> {
val variable = getVariable(treeNode.variable)
if(variable != null) return variable
val definition = getDefinition(treeNode.variable)
if(definition != null) return definition.reduce(this)
throw NumberReducerException("variable is not defined.")
}
is NumberUnaryNode -> {
val child = children[0] as NumberInterface
numberImplementation = abacus.pluginManager.interfaceImplementationFor(child.javaClass)
abacus.pluginManager.operatorFor(treeNode.operation)
.apply(this, child)
}
is NumberBinaryNode -> {
val left = children[0] as NumberInterface
val right = children[1] as NumberInterface
val promotionResult = promotionManager.promote(left, right)
numberImplementation = promotionResult.promotedTo
abacus.pluginManager.operatorFor(treeNode.operation).apply(this, *promotionResult.items)
}
is NumberFunctionNode -> {
val promotionResult = promotionManager
.promote(*children.map { it as NumberInterface }.toTypedArray())
numberImplementation = promotionResult.promotedTo
abacus.pluginManager.functionFor(treeNode.callTo).apply(this, *promotionResult.items)
}
is TreeValueUnaryNode -> {
abacus.pluginManager.treeValueOperatorFor(treeNode.operation)
.apply(this, treeNode.applyTo)
}
is TreeValueBinaryNode -> {
abacus.pluginManager.treeValueOperatorFor(treeNode.operation)
.apply(this, treeNode.left, treeNode.right)
}
is TreeValueFunctionNode -> {
abacus.pluginManager.treeValueFunctionFor(treeNode.callTo)
.apply(this, *treeNode.children.toTypedArray())
}
else -> throw ReductionException("unrecognized tree node.")
}
numberImplementation = oldNumberImplementation
return toReturn
}
} | mit | ffab79fe66fb6e38598be5dc7566de22 | 44.32967 | 104 | 0.63773 | 4.927121 | false | false | false | false |
Maccimo/intellij-community | platform/remoteDev-util/src/com/intellij/remoteDev/OsRegistryConfigProvider.kt | 2 | 6921 | package com.intellij.remoteDev
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.util.SystemInfo
import com.intellij.util.EnvironmentUtil
import com.intellij.util.system.CpuArch
import com.sun.jna.platform.win32.*
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.JsonPrimitive
import java.io.File
class OsRegistryConfigProvider(private val configName: String) {
companion object {
private val logger = logger<OsRegistryConfigProvider>()
private const val configJsonFilename = "config.json"
const val etcXdgPath = "/etc/xdg/"
fun getConfigSubDirectoryPath(configName: String) = "JetBrains/$configName"
}
init {
require(!configName.contains(' ')) { "'$configName' should not contains spaces" }
}
class OsRegistrySystemSetting<T>(val value: T, val osOriginLocation: String?) {
val isSetFromOs = osOriginLocation != null
}
private val keyRegex = Regex("^\\w+$")
fun get(key: String): OsRegistrySystemSetting<String>? {
require(key.matches(keyRegex)) { "Key '$key' does not match regex '${keyRegex.pattern}'" }
val systemValue = when {
SystemInfo.isWindows -> getFromRegistry(key)
SystemInfo.isLinux -> getFromXdgConfig(key)
SystemInfo.isMac -> getFromLibraryApplicationSupport(key)
else -> error("Unknown OS")
}
if (systemValue != null) {
logger.info("OS provided value for $key=${systemValue.value} in $configName config, origin=${systemValue.osOriginLocation}")
}
return systemValue
}
// key: SOFTWARE\JetBrains\$configName, value: regValue, value type: REG_SZ
// prio: HKLM64 -> 32 -> HKCU64 -> 32
private fun getFromRegistry(regValue: String): OsRegistrySystemSetting<String>? {
val regKey = "SOFTWARE\\JetBrains\\$configName"
logger.debug("Looking for $regValue in registry $regKey, is32Bit=${CpuArch.isIntel32()}")
// these WOW64 keys are ignored by 32-bit Windows, see https://docs.microsoft.com/en-us/windows/win32/sysinfo/registry-key-security-and-access-rights
val uris = listOf(
"HKLM_64" to { Advapi32Util.registryGetStringValue(WinReg.HKEY_LOCAL_MACHINE, regKey, regValue, WinNT.KEY_WOW64_64KEY) },
"HKLM_32" to { Advapi32Util.registryGetStringValue(WinReg.HKEY_LOCAL_MACHINE, regKey, regValue, WinNT.KEY_WOW64_32KEY) },
"HKCU_64" to { Advapi32Util.registryGetStringValue(WinReg.HKEY_CURRENT_USER, regKey, regValue, WinNT.KEY_WOW64_64KEY) },
"HKCU_32" to { Advapi32Util.registryGetStringValue(WinReg.HKEY_CURRENT_USER, regKey, regValue, WinNT.KEY_WOW64_32KEY) }
)
fun Pair<String, () -> String>.readable() = "${this.first}\\$regKey\\$regValue"
return uris.mapNotNull {
val uri = try {
logger.debug("Searching for ${it.readable()} in registry")
it.second()
}
catch (t: Throwable) {
when (t) {
is Win32Exception -> {
if (t.errorCode == WinError.ERROR_FILE_NOT_FOUND) logger.debug("registry entry not found at ${it.readable()}")
else logger.warn("Failed to get registry entry at ${it.readable()}, HRESULT=${t.hr.toInt()}", t)
}
else -> {
logger.warn("Failed to get registry entry at ${it.readable()}", t)
}
}
null
}
if (uri != null) {
logger.info("Found registry entry at ${it.readable()}, value=$uri")
OsRegistrySystemSetting(uri, it.readable())
}
else {
null
}
}.firstOrNull()
}
// https://specifications.freedesktop.org/basedir-spec/basedir-spec-0.6.html
private fun getFromXdgConfig(key: String): OsRegistrySystemSetting<String>? {
val configDirectoryPath = getConfigSubDirectoryPath(configName)
val env = EnvironmentUtil.getEnvironmentMap()
val home = System.getProperty("user.home")
// non-user writable location first, even if that's wrong according to spec as that's what we want
val configLookupDirs = listOf(etcXdgPath, env["XDG_CONFIG_HOME"] ?: "$home/.config/").toMutableList()
logger.info("Looking for $key in xdg config dirs: $configLookupDirs")
// we already set /etc/xdg as the first one, so no need to default to it
val xdgConfigDirs = (env["XDG_CONFIG_DIRS"] ?: "").split(":").filter { it.isNotEmpty() }
configLookupDirs.addAll(xdgConfigDirs)
return getFromDirectories(key, configLookupDirs.map { File(it) }, configDirectoryPath)
}
private fun getFromDirectories(key: String, dirs: List<File>, configDirectoryPath: String): OsRegistrySystemSetting<String>? =
dirs.mapNotNull {
// get from file with name $key
val valueFromKeyFile = getFromKeyFile(it, configDirectoryPath, key)
if (valueFromKeyFile != null)
return@mapNotNull valueFromKeyFile
// fallback to config.json
val configJsonFile = File(File(it, configDirectoryPath), configJsonFilename)
return@mapNotNull getFromJsonFile(key, configJsonFile)
}.firstOrNull()
private fun getFromKeyFile(it: File, configDirectoryPath: String, key: String): OsRegistrySystemSetting<String>? {
val keyFile = File(File(it, configDirectoryPath), key)
logger.debug("Trying to get $key from file=${keyFile.canonicalPath}")
if (!keyFile.exists()) {
logger.debug("File=${keyFile.canonicalPath} does not exist.")
return null
}
try {
// todo: think about it: should we trim the value?
val keyFileContents = keyFile.readText().trim()
logger.info("Found $key in file=${keyFile.canonicalPath}, value=$keyFileContents")
return OsRegistrySystemSetting(keyFileContents, keyFile.canonicalPath)
} catch (e: Throwable) {
logger.warn("Failed to read setting $key from ${keyFile.canonicalPath}")
return null
}
}
private fun getFromJsonFile(key: String, file: File): OsRegistrySystemSetting<String>? {
logger.debug("Trying to get $key from file=${file.canonicalPath}")
if (!file.exists()) {
logger.debug("File=${file.canonicalPath} does not exist.")
return null
}
return try {
val root = Json.Default.parseToJsonElement(file.readText()) as? JsonObject
val resultValue = (root?.get(key) as? JsonPrimitive)?.content
if (resultValue != null) {
logger.info("Found $key in file=${file.canonicalPath}, value=$resultValue")
OsRegistrySystemSetting(resultValue, file.canonicalPath)
}
else null
}
catch (t: Throwable) {
logger.warn("Failed to read json for $key at location $file", t)
null
}
}
private fun getFromLibraryApplicationSupport(key: String): OsRegistrySystemSetting<String>? {
val home = System.getProperty("user.home")
val dirs = listOf("/", "$home/")
val configDirectoryPath = "Library/Application Support/JetBrains/$configName"
return getFromDirectories(key, dirs.map { File(it) }, configDirectoryPath)
}
} | apache-2.0 | c05ed1d5f48248e74aaa3b81d46b9be3 | 40.202381 | 153 | 0.688918 | 3.966189 | false | true | false | false |
Maccimo/intellij-community | plugins/kotlin/gradle/gradle-tooling/src/org/jetbrains/kotlin/idea/gradleTooling/KotlinMPPGradleModelExtensions.kt | 2 | 1270 | // 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.gradleTooling
import org.jetbrains.kotlin.idea.projectModel.KotlinCompilation
import org.jetbrains.kotlin.idea.projectModel.KotlinCompilationCoordinates
import org.jetbrains.kotlin.idea.projectModel.KotlinSourceSet
fun KotlinMPPGradleModel.getCompilations(sourceSet: KotlinSourceSet): Set<KotlinCompilation> {
return targets.flatMap { target -> target.compilations }
.filter { compilation -> compilationDependsOnSourceSet(compilation, sourceSet) }
.toSet()
}
fun KotlinMPPGradleModel.compilationDependsOnSourceSet(
compilation: KotlinCompilation, sourceSet: KotlinSourceSet
): Boolean {
return compilation.declaredSourceSets.any { sourceSetInCompilation ->
sourceSetInCompilation == sourceSet || sourceSetInCompilation.isDependsOn(this, sourceSet)
}
}
fun KotlinMPPGradleModel.findCompilation(coordinates: KotlinCompilationCoordinates): KotlinCompilation? {
return targets.find { target -> target.name == coordinates.targetName }
?.compilations?.find { compilation -> compilation.name == coordinates.compilationName }
}
| apache-2.0 | fbd2644938934d333ecf296d114ef4f8 | 47.846154 | 158 | 0.792126 | 5.1417 | false | false | false | false |
Jumpaku/JumpakuOthello | api/src/main/kotlin/jumpaku/othello/api/Json.kt | 1 | 2048 | package jumpaku.othello.api
import com.github.salomonbrys.kotson.*
import com.google.gson.JsonElement
import jumpaku.commons.control.Result
import jumpaku.commons.control.result
import jumpaku.othello.game.*
fun updateData(json: JsonElement): Result<UpdateData> = result {
UpdateData(
json["gameId"].string,
when (val n = json["move"].int) {
-1 -> Move.Pass
else -> Move.Place(Pos(n/8, n%8))
}
)
}
fun selectorInput(json: JsonElement): Result<SelectorInput> = result {
SelectorInput(Disc.valueOf(json["selectPlayer"].string), json["board"].let {
Board(
it["darkDiscs"].array.fold(0uL) { d, n -> d or (1uL shl n.int) },
it["lightDiscs"].array.fold(0uL) { d, n -> d or (1uL shl n.int) }
)
})
}
fun Pair<String, Game>.toJson(): JsonElement = this.let { (gameId, gameState) ->
jsonObject("gameId" to gameId, "gameState" to gameState.toJson())
}
fun Move.toJson(): JsonElement = jsonObject("move" to when(this) {
is Move.Pass -> -1
is Move.Place -> pos.row*8 + pos.col
})
fun Game.toJson(): JsonElement = jsonObject(
"board" to jsonObject(
"darkDiscs" to jsonArray((0..63).filter { (1uL shl it) and phase.board.darkBits != 0uL }),
"lightDiscs" to jsonArray((0..63).filter { (1uL shl it) and phase.board.lightBits != 0uL })
),
"history" to jsonArray(history.mapNotNull {
when (it) {
is Move.Pass -> -1
is Move.Place -> it.pos.row*8 + it.pos.col
}
})
) + when (phase) {
is Phase.Completed -> mapOf(
"state" to "Completed",
"darkCount" to phase.darkCount,
"lightCount" to phase.lightCount
)
is Phase.InProgress -> mapOf(
"state" to "InProgress",
"selectPlayer" to phase.player.name,
"availableMoves" to jsonArray(phase.availableMoves.mapNotNull {
when (it) {
is Move.Pass -> -1
is Move.Place -> it.pos.row * 8 + it.pos.col
}
})
)
}
| bsd-2-clause | d60270987f970bc2da417f9dec6c23fa | 30.507692 | 99 | 0.588379 | 3.543253 | false | false | false | false |
mdaniel/intellij-community | plugins/grazie/src/main/kotlin/com/intellij/grazie/remote/LangDownloader.kt | 8 | 2771 | // 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.grazie.remote
import com.intellij.grazie.GrazieConfig
import com.intellij.grazie.GrazieDynamic
import com.intellij.grazie.GraziePlugin
import com.intellij.grazie.ide.notification.GrazieToastNotifications.MISSED_LANGUAGES_GROUP
import com.intellij.grazie.ide.ui.components.dsl.msg
import com.intellij.grazie.jlanguage.Lang
import com.intellij.notification.NotificationType
import com.intellij.openapi.diagnostic.thisLogger
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.project.Project
import com.intellij.util.download.DownloadableFileService
import com.intellij.util.lang.UrlClassLoader
import org.jetbrains.annotations.Nls
import java.nio.file.Path
internal object LangDownloader {
fun download(lang: Lang, project: Project?): Boolean {
// check if language lib already loaded
if (GrazieRemote.isAvailableLocally(lang)) return true
val result = runDownload(lang, project)
// null if canceled or failed, zero result if nothing found
if (!result.isNullOrEmpty()) {
val classLoader = UrlClassLoader.build().parent(GraziePlugin.classLoader)
.files(result).get()
GrazieDynamic.addDynClassLoader(classLoader)
// force reloading available language classes
GrazieConfig.update { it.copy() }
// drop caches, restart highlighting
GrazieConfig.stateChanged(GrazieConfig.get(), GrazieConfig.get())
return true
}
return false
}
private fun runDownload(lang: Lang, project: Project?): List<Path>? {
try {
val presentableName = msg("grazie.settings.proofreading.languages.download.name", lang.nativeName)
return ProgressManager.getInstance().runProcessWithProgressSynchronously<List<Path>, Exception>(
{ doDownload(lang, presentableName) },
presentableName,
false,
project
)
} catch (exception: Throwable) {
thisLogger().error(exception)
val notification = MISSED_LANGUAGES_GROUP.createNotification(
msg("grazie.notification.missing-languages.download.failed.message", lang.nativeName),
NotificationType.ERROR
)
notification.notify(project)
return null
}
}
private fun doDownload(lang: Lang, presentableName: @Nls String): List<Path> {
val downloaderService = DownloadableFileService.getInstance()
val downloader = downloaderService.createDownloader(
listOf(downloaderService.createFileDescription(lang.remote.url, lang.remote.fileName)),
presentableName
)
return downloader.download(GrazieDynamic.dynamicFolder.toFile()).map { it.first.toPath() }
}
}
| apache-2.0 | 2bc4283a2605278d947a6de5e3740320 | 37.486111 | 140 | 0.749188 | 4.618333 | false | true | false | false |
micolous/metrodroid | src/commonMain/kotlin/au/id/micolous/metrodroid/transit/intercode/IntercodeTransaction.kt | 1 | 4774 | /*
* IntercodeTrip.kt
*
* Copyright 2018 Google
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package au.id.micolous.metrodroid.transit.intercode
import au.id.micolous.metrodroid.multi.Parcelize
import au.id.micolous.metrodroid.transit.en1545.*
import au.id.micolous.metrodroid.util.ImmutableByteArray
@Parcelize
internal data class IntercodeTransaction(private val networkId: Int,
override val parsed: En1545Parsed) : En1545Transaction() {
override val lookup: En1545Lookup
get() = IntercodeTransitData.getLookup(networkId)
companion object {
fun parse (data: ImmutableByteArray, networkId: Int): IntercodeTransaction {
val parsed = En1545Parser.parse(data, tripFieldsLocal)
return IntercodeTransaction(parsed.getInt(En1545Transaction.EVENT_NETWORK_ID) ?: networkId,
parsed)
}
private fun tripFields(time: (String) -> En1545FixedInteger) = En1545Container(
En1545FixedInteger.date(En1545Transaction.EVENT),
time(En1545Transaction.EVENT),
En1545Bitmap(
En1545FixedInteger(En1545Transaction.EVENT_DISPLAY_DATA, 8),
En1545FixedInteger(En1545Transaction.EVENT_NETWORK_ID, 24),
En1545FixedInteger(En1545Transaction.EVENT_CODE, 8),
En1545FixedInteger(En1545Transaction.EVENT_RESULT, 8),
En1545FixedInteger(En1545Transaction.EVENT_SERVICE_PROVIDER, 8),
En1545FixedInteger(En1545Transaction.EVENT_NOT_OK_COUNTER, 8),
En1545FixedInteger(En1545Transaction.EVENT_SERIAL_NUMBER, 24),
En1545FixedInteger(En1545Transaction.EVENT_DESTINATION, 16),
En1545FixedInteger(En1545Transaction.EVENT_LOCATION_ID, 16),
En1545FixedInteger(En1545Transaction.EVENT_LOCATION_GATE, 8),
En1545FixedInteger(En1545Transaction.EVENT_DEVICE, 16),
En1545FixedInteger(En1545Transaction.EVENT_ROUTE_NUMBER, 16),
En1545FixedInteger(En1545Transaction.EVENT_ROUTE_VARIANT, 8),
En1545FixedInteger(En1545Transaction.EVENT_JOURNEY_RUN, 16),
En1545FixedInteger(En1545Transaction.EVENT_VEHICLE_ID, 16),
En1545FixedInteger(En1545Transaction.EVENT_VEHICULE_CLASS, 8),
En1545FixedInteger(En1545Transaction.EVENT_LOCATION_TYPE, 5),
En1545FixedString(En1545Transaction.EVENT_EMPLOYEE, 240),
En1545FixedInteger(En1545Transaction.EVENT_LOCATION_REFERENCE, 16),
En1545FixedInteger(En1545Transaction.EVENT_JOURNEY_INTERCHANGES, 8),
En1545FixedInteger(En1545Transaction.EVENT_PERIOD_JOURNEYS, 16),
En1545FixedInteger(En1545Transaction.EVENT_TOTAL_JOURNEYS, 16),
En1545FixedInteger(En1545Transaction.EVENT_JOURNEY_DISTANCE, 16),
En1545FixedInteger(En1545Transaction.EVENT_PRICE_AMOUNT, 16),
En1545FixedInteger(En1545Transaction.EVENT_PRICE_UNIT, 16),
En1545FixedInteger(En1545Transaction.EVENT_CONTRACT_POINTER, 5),
En1545FixedInteger(En1545Transaction.EVENT_AUTHENTICATOR, 16),
En1545Bitmap(
En1545FixedInteger.date(En1545Transaction.EVENT_FIRST_STAMP),
time(En1545Transaction.EVENT_FIRST_STAMP),
En1545FixedInteger(En1545Transaction.EVENT_DATA_SIMULATION, 1),
En1545FixedInteger(En1545Transaction.EVENT_DATA_TRIP, 2),
En1545FixedInteger(En1545Transaction.EVENT_DATA_ROUTE_DIRECTION, 2)
)
)
)
val tripFieldsUtc = tripFields(En1545FixedInteger.Companion::time)
val tripFieldsLocal = tripFields(En1545FixedInteger.Companion::timeLocal)
}
}
| gpl-3.0 | beb2b2c3aa44675e93d4e2dc1ed7ef37 | 55.164706 | 103 | 0.639087 | 4.630456 | false | false | false | false |
JavaEden/Orchid-Core | plugins/OrchidKotlindoc/src/main/kotlin/com/eden/orchid/kotlindoc/menu/KotlinClassDocLinksMenuItemType.kt | 1 | 4583 | package com.eden.orchid.kotlindoc.menu
import com.eden.orchid.api.OrchidContext
import com.eden.orchid.api.options.annotations.BooleanDefault
import com.eden.orchid.api.options.annotations.Description
import com.eden.orchid.api.options.annotations.Option
import com.eden.orchid.api.theme.menus.MenuItem
import com.eden.orchid.api.theme.menus.OrchidMenu
import com.eden.orchid.api.theme.menus.OrchidMenuFactory
import com.eden.orchid.api.theme.pages.OrchidPage
import com.eden.orchid.kotlindoc.model.KotlindocModel
import com.eden.orchid.kotlindoc.page.KotlindocClassPage
@Description(
"Links to the different sections within a Kotlindoc Class page, optionally with their items nested " +
"underneath them.",
name = "Kotlindoc Class Sections"
)
class KotlinClassDocLinksMenuItemType : OrchidMenuFactory("kotlindocClassLinks") {
@Option
@BooleanDefault(false)
@Description(
"Whether to include the items for each category. For example, including a menu item for each " +
"individual constructor as children of 'Constructors' or just a link to the Constructors section."
)
var includeItems: Boolean = false
override fun canBeUsedOnPage(
containingPage: OrchidPage,
menu: OrchidMenu,
possibleMenuItems: List<Map<String, Any>>,
currentMenuItems: List<OrchidMenuFactory>
): Boolean {
return containingPage is KotlindocClassPage
}
override fun getMenuItems(
context: OrchidContext,
page: OrchidPage
): List<MenuItem> {
val model = context.resolve(KotlindocModel::class.java)
val containingPage = page as KotlindocClassPage
val classDoc = containingPage.classDoc
val menuItems = ArrayList<MenuItem>()
val linkData = arrayOf(
LinkData(
{ true },
{ emptyList() },
"Summary",
"summary"
),
LinkData(
{ true },
{ emptyList() },
"Description",
"description"
),
LinkData(
{ classDoc.fields.isNotEmpty() },
{ getFieldLinks(context, model, page) },
"Fields",
"fields"
),
LinkData(
{ classDoc.constructors.isNotEmpty() },
{ getConstructorLinks(context, model, page) },
"Constructors",
"constructors"
),
LinkData(
{ classDoc.methods.isNotEmpty() },
{ getMethodLinks(context, model, page) },
"Methods",
"methods"
)
)
for (item in linkData) {
if (item.matches()) {
val menuItem = MenuItem.Builder(context)
.title(item.title)
.anchor(item.id)
if (includeItems) {
menuItem.children(item.items())
}
menuItems.add(menuItem.build())
}
}
return menuItems
}
private data class LinkData(
val matches: () -> Boolean,
val items: () -> List<MenuItem>,
val title: String,
val id: String
)
private fun getFieldLinks(context: OrchidContext, model: KotlindocModel, page: OrchidPage): List<MenuItem> {
val containingPage = page as KotlindocClassPage
val classDoc = containingPage.classDoc
return classDoc.fields.map {
MenuItem.Builder(context)
.title(it.simpleSignature)
.anchor(model.idFor(it))
.build()
}
}
private fun getConstructorLinks(context: OrchidContext, model: KotlindocModel, page: OrchidPage): List<MenuItem> {
val containingPage = page as KotlindocClassPage
val classDoc = containingPage.classDoc
return classDoc.constructors.map {
MenuItem.Builder(context)
.title(it.simpleSignature)
.anchor(model.idFor(it))
.build()
}
}
private fun getMethodLinks(context: OrchidContext, model: KotlindocModel, page: OrchidPage): List<MenuItem> {
val containingPage = page as KotlindocClassPage
val classDoc = containingPage.classDoc
return classDoc.methods.map {
MenuItem.Builder(context)
.title(it.simpleSignature)
.anchor(model.idFor(it))
.build()
}
}
}
| mit | 3f9b9b95714debdbcc0a19d87755e1c3 | 31.503546 | 118 | 0.583897 | 4.981522 | false | false | false | false |
Firenox89/Shinobooru | app/src/main/java/com/github/firenox89/shinobooru/repo/model/Tag.kt | 1 | 1205 | package com.github.firenox89.shinobooru.repo.model
import android.graphics.Color
import com.github.firenox89.shinobooru.repo.ApiWrapper
import org.json.JSONArray
import org.json.JSONException
import org.json.JSONObject
import org.koin.core.KoinComponent
import org.koin.core.inject
import timber.log.Timber
import java.io.Serializable
/**
* Data class to store the meta information of a tag.
* Contains some utility functions.
*/
data class Tag(
val name: String,
val board: String,
var id: Long = 0L,
var count: Int = 0,
var type: Int = -1,
var ambiguous: Boolean = false) : Serializable {
/**
* Returns a [Color] value as an Int, depending on the tag type.
*
* @return an Int value representing the color.
*/
fun getTextColor(): Int =
when (type) {
0 -> Color.parseColor("#EE8887")
1 -> Color.parseColor("#CCCC00")
3 -> Color.parseColor("#DD00DD")
4 -> Color.parseColor("#00AA00")
5 -> Color.parseColor("#00BBBB")
6 -> Color.parseColor("#FF2020")
else -> Color.parseColor("#EE8887")
}
} | mit | e29e68e8a6ab963ec574cdb2b8556196 | 29.923077 | 68 | 0.604979 | 4.112628 | false | false | false | false |
AsamK/TextSecure | app/src/main/java/org/thoughtcrime/securesms/components/settings/app/privacy/expire/CustomExpireTimerSelectorView.kt | 4 | 2541 | package org.thoughtcrime.securesms.components.settings.app.privacy.expire
import android.content.Context
import android.util.AttributeSet
import android.view.Gravity
import android.widget.LinearLayout
import android.widget.NumberPicker
import org.thoughtcrime.securesms.R
import java.util.concurrent.TimeUnit
/**
* Show number pickers for value and units that are valid for expiration timer.
*/
class CustomExpireTimerSelectorView @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0
) : LinearLayout(context, attrs, defStyleAttr) {
private val valuePicker: NumberPicker
private val unitPicker: NumberPicker
init {
orientation = HORIZONTAL
gravity = Gravity.CENTER
inflate(context, R.layout.custom_expire_timer_selector_view, this)
valuePicker = findViewById(R.id.custom_expire_timer_selector_value)
unitPicker = findViewById(R.id.custom_expire_timer_selector_unit)
valuePicker.minValue = TimerUnit.get(1).minValue
valuePicker.maxValue = TimerUnit.get(1).maxValue
unitPicker.minValue = 0
unitPicker.maxValue = 4
unitPicker.value = 1
unitPicker.wrapSelectorWheel = false
unitPicker.isLongClickable = false
unitPicker.displayedValues = context.resources.getStringArray(R.array.CustomExpireTimerSelectorView__unit_labels)
unitPicker.setOnValueChangedListener { _, _, newValue -> unitChange(newValue) }
}
fun setTimer(timer: Int?) {
if (timer == null || timer == 0) {
return
}
TimerUnit.values()
.find { (timer / it.valueMultiplier) < it.maxValue }
?.let { timerUnit ->
valuePicker.value = (timer / timerUnit.valueMultiplier).toInt()
unitPicker.value = TimerUnit.values().indexOf(timerUnit)
unitChange(unitPicker.value)
}
}
fun getTimer(): Int {
return valuePicker.value * TimerUnit.get(unitPicker.value).valueMultiplier.toInt()
}
private fun unitChange(newValue: Int) {
val timerUnit: TimerUnit = TimerUnit.values()[newValue]
valuePicker.minValue = timerUnit.minValue
valuePicker.maxValue = timerUnit.maxValue
}
private enum class TimerUnit(val minValue: Int, val maxValue: Int, val valueMultiplier: Long) {
SECONDS(1, 59, TimeUnit.SECONDS.toSeconds(1)),
MINUTES(1, 59, TimeUnit.MINUTES.toSeconds(1)),
HOURS(1, 23, TimeUnit.HOURS.toSeconds(1)),
DAYS(1, 6, TimeUnit.DAYS.toSeconds(1)),
WEEKS(1, 4, TimeUnit.DAYS.toSeconds(7));
companion object {
fun get(value: Int) = values()[value]
}
}
}
| gpl-3.0 | 3100026983a3da73e959da8a589ebf4e | 31.164557 | 117 | 0.722944 | 4.001575 | false | false | false | false |
kondroid00/SampleProject_Android | app/src/main/java/com/kondroid/sampleproject/viewmodel/TopViewModel.kt | 1 | 1789 | package com.kondroid.sampleproject.viewmodel
import android.content.Context
import android.databinding.ObservableField
import android.view.View
import com.kondroid.sampleproject.auth.AccountManager
import com.kondroid.sampleproject.helper.makeWeak
import com.kondroid.sampleproject.model.AuthModel
import com.kondroid.sampleproject.request.AuthRequest
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.internal.operators.single.SingleDoOnSuccess
import io.reactivex.observers.DisposableObserver
import io.reactivex.schedulers.Schedulers
/**
* Created by kondo on 2017/09/28.
*/
class TopViewModel(context: Context) : BaseViewModel(context) {
val startButtonVisibility: ObservableField<Int> = ObservableField(View.VISIBLE)
val authModel = AuthModel()
lateinit var onTapStart: () -> Unit
fun login(onSuccess: () -> Unit, onFailed: (e: Throwable) -> Unit) {
if (requesting) return
requesting = true
val weakSelf = makeWeak(this)
val params = AuthRequest.LoginParams(AccountManager.getUserId())
val observable = authModel.login(params)
val d = observable.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe({t ->
weakSelf.get()?.requesting = false
AccountManager.token = t.token
AccountManager.user = t.user
onSuccess()
}, {e ->
weakSelf.get()?.requesting = false
onFailed(e)
}, {
weakSelf.get()?.requesting = false
})
compositeDisposable.add(d)
}
fun tapStart() {
if (requesting) return
onTapStart()
}
} | mit | 97356191d89a6d4a2470faab24ea6de9 | 32.148148 | 83 | 0.650643 | 4.914835 | false | false | false | false |
NiciDieNase/chaosflix | common/src/main/java/de/nicidienase/chaosflix/common/ChaosflixUtil.kt | 1 | 5632 | package de.nicidienase.chaosflix.common
import de.nicidienase.chaosflix.common.mediadata.entities.recording.persistence.Event
import de.nicidienase.chaosflix.common.mediadata.entities.recording.persistence.Recording
import de.nicidienase.chaosflix.common.mediadata.entities.streaming.Stream
object ChaosflixUtil {
fun getOptimalRecording(recordings: List<Recording>, originalLanguage: String): Recording {
val groupedRecordings =
recordings.groupBy { "${if (it.isHighQuality) "HD" else "SD"}-${it.mimeType}" }
return when {
groupedRecordings.keys.contains(HD_MP4) ->
getRecordingForGroup(groupedRecordings[HD_MP4], originalLanguage)
groupedRecordings.keys.contains(HD_WEBM) ->
getRecordingForGroup(groupedRecordings[HD_WEBM], originalLanguage)
groupedRecordings.keys.contains(SD_MP4) ->
getRecordingForGroup(groupedRecordings[SD_MP4], originalLanguage)
groupedRecordings.keys.contains(SD_WEBM) ->
getRecordingForGroup(groupedRecordings[SD_WEBM], originalLanguage)
else -> recordings.first()
}
}
fun getRecordingForThumbs(recordings: List<Recording>): Recording? {
val lqRecordings = recordings.filter { !it.isHighQuality && it.width > 0 }.sortedBy { it.size }
return when {
lqRecordings.isNotEmpty() -> lqRecordings[0]
else -> null
}
}
fun getStringForRecording(recording: Recording): String {
return "${if (recording.isHighQuality) "HD" else "SD"} ${recording.folder} [${recording.language}]"
}
fun getStringForStream(stream: Stream): String {
return "${stream.display}"
}
private fun getRecordingForGroup(group: List<Recording>?, language: String): Recording {
if (group.isNullOrEmpty()) {
error("Got empty or null list, this should not happen!")
}
return when {
group.size == 1 -> group.first()
else -> {
val languageFiltered = group.filter { it.language == language }
val relaxedLanguageFiltered = group.filter { it.language.contains(language) }
when {
languageFiltered.isNotEmpty() -> languageFiltered.first()
relaxedLanguageFiltered.isNotEmpty() -> relaxedLanguageFiltered.first()
else -> group.first()
}
}
}
}
private fun getOrderedRecordings(
recordings: List<Recording>,
originalLanguage: String
): ArrayList<Recording> {
val result = ArrayList<Recording>()
var hqMp4Recordings = recordings
.filter { it.isHighQuality && it.mimeType == "video/mp4" }
.sortedBy { it.language.length }
var lqMp4Recordings = recordings
.filter { !it.isHighQuality && it.mimeType == "video/mp4" }
.sortedBy { it.language.length }
if (originalLanguage.isNotBlank()) {
hqMp4Recordings = hqMp4Recordings.filter { it.language == originalLanguage }
lqMp4Recordings = lqMp4Recordings.filter { it.language == originalLanguage }
}
result.addAll(hqMp4Recordings)
result.addAll(lqMp4Recordings)
return result
}
fun areTagsUsefull(events: List<Event>, acronym: String): Boolean {
val tagList = events.map { it.tags ?: emptyArray() }
.toTypedArray()
.flatten()
.filterNot { it.matches("\\d+".toRegex()) }
.filterNot { it.toLowerCase() == acronym.toLowerCase() }
val tagCount: MutableMap<String, Int> = mutableMapOf()
for (tag in tagList.filterNotNull()) {
tagCount[tag] = tagCount[tag]?.plus(1) ?: 1
}
val usefulTags = tagCount.keys
.filter { tagCount[it]!! < events.size - 1 }
.filter { tagCount[it]!! > 1 }
.filter { it.length >= 3 }
return usefulTags.size > 2
}
fun getStringForTag(tag: String): String {
when (tag) {
"broadcast/chaosradio" -> return "Chaosradio"
"blinkenlights" -> return "Blinkenlights"
"camp" -> return "Camp"
"chaoscologne" -> return "1c2 Chaos Cologne"
"cryptocon" -> return "CryptoCon"
"congress" -> return "Congress"
"denog" -> return "DENOG"
"datenspuren" -> return "Datenspuren"
"easterhegg" -> return "Easterhegg"
"fiffkon" -> return "FifFKon"
"froscon" -> return "FrOSCon"
"gpn" -> return "GPN"
"hackover" -> return "Hackover"
"mrmcd" -> return "MRMCD"
"netzpolitik" -> return "Das ist Netzpolitik!"
"sendezentrum" -> return "Sendezentrum"
"sigint" -> return "SIGINT"
"vcfb" -> return "Vintage Computing Festival Berlin"
"other conferences" -> return "Other Conferences"
else -> return tag
}
}
val orderedConferencesList: List<String> = listOf(
"congress",
"gpn",
"mrmcd",
"broadcast/chaosradio",
"easterhegg",
"camp",
"froscon",
"sendezentrum",
"sigint",
"datenspuren",
"fiffkon",
"cryptocon")
private const val HD_MP4 = "HD-video/mp4"
private const val HD_WEBM = "HD-video/webm"
private const val SD_MP4 = "SD-video/mp4"
private const val SD_WEBM = "SD-video/webm"
}
| mit | b5ca24ab49aa5808c994978efbff6c29 | 38.943262 | 109 | 0.581676 | 4.250566 | false | false | false | false |
ktorio/ktor | ktor-server/ktor-server-core/jvmAndNix/src/io/ktor/server/routing/IgnoreTrailingSlash.kt | 1 | 922 | /*
* 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.routing
import io.ktor.server.application.*
import io.ktor.util.*
private val IgnoreTrailingSlashAttributeKey: AttributeKey<Unit> = AttributeKey("IgnoreTrailingSlashAttributeKey")
internal var ApplicationCall.ignoreTrailingSlash: Boolean
get() = attributes.contains(IgnoreTrailingSlashAttributeKey)
private set(value) = if (value) {
attributes.put(IgnoreTrailingSlashAttributeKey, Unit)
} else {
attributes.remove(IgnoreTrailingSlashAttributeKey)
}
/**
* A plugin that enables ignoring a trailing slash when resolving URLs.
* @see [Application.routing]
*/
public val IgnoreTrailingSlash: ApplicationPlugin<Unit> = createApplicationPlugin("IgnoreTrailingSlash") {
onCall { call ->
call.ignoreTrailingSlash = true
}
}
| apache-2.0 | ed62c789b5354f951eda9aa878ddb6f7 | 31.928571 | 119 | 0.753796 | 4.497561 | false | false | false | false |
onnerby/musikcube | src/musikdroid/app/src/main/java/io/casey/musikcube/remote/ui/shared/activity/BaseActivity.kt | 1 | 5865 | package io.casey.musikcube.remote.ui.shared.activity
import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import android.media.AudioManager
import android.os.Bundle
import android.view.KeyEvent
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import com.uacf.taskrunner.Runner
import com.uacf.taskrunner.Task
import io.casey.musikcube.remote.Application
import io.casey.musikcube.remote.framework.IMixin
import io.casey.musikcube.remote.framework.MixinSet
import io.casey.musikcube.remote.framework.ViewModel
import io.casey.musikcube.remote.injection.DaggerViewComponent
import io.casey.musikcube.remote.injection.ViewComponent
import io.casey.musikcube.remote.ui.browse.fragment.BrowseFragment
import io.casey.musikcube.remote.ui.navigation.Transition
import io.casey.musikcube.remote.ui.settings.constants.Prefs
import io.casey.musikcube.remote.ui.shared.extension.*
import io.casey.musikcube.remote.ui.shared.mixin.PlaybackMixin
import io.casey.musikcube.remote.ui.shared.mixin.RunnerMixin
import io.casey.musikcube.remote.ui.shared.mixin.ViewModelMixin
import io.reactivex.disposables.CompositeDisposable
abstract class BaseActivity : AppCompatActivity(), ViewModel.Provider, Runner.TaskCallbacks {
protected var disposables = CompositeDisposable()
private set
protected var paused = true /* `private set` confuses proguard. sigh */
protected lateinit var prefs: SharedPreferences
private val mixins = MixinSet()
protected val component: ViewComponent =
DaggerViewComponent.builder()
.appComponent(Application.appComponent)
.build()
override fun onCreate(savedInstanceState: Bundle?) {
when (transitionType) {
Transition.Horizontal -> slideNextLeft()
Transition.Vertical -> slideNextUp()
}
component.inject(this)
mixin(RunnerMixin(this, javaClass))
super.onCreate(savedInstanceState)
prefs = getSharedPreferences(Prefs.NAME, Context.MODE_PRIVATE)
volumeControlStream = AudioManager.STREAM_MUSIC
mixins.onCreate(savedInstanceState ?: Bundle())
}
override fun onStart() {
super.onStart()
mixins.onStart()
}
override fun onResume() {
super.onResume()
mixins.onResume()
paused = false
}
override fun onPause() {
hideKeyboard()
super.onPause()
mixins.onPause()
disposables.dispose()
disposables = CompositeDisposable()
paused = true
}
override fun onStop() {
super.onStop()
mixins.onStop()
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
mixins.onActivityResult(requestCode, resultCode, data)
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
mixins.onSaveInstanceState(outState)
}
override fun onDestroy() {
super.onDestroy()
mixins.onDestroy()
}
override fun onBackPressed() {
(top as? IBackHandler)?.let {
if (it.onBackPressed()) {
return
}
}
when {
fm.backStackEntryCount > 1 -> fm.popBackStack()
else -> super.onBackPressed()
}
}
override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
if (mixin(PlaybackMixin::class.java)?.onKeyDown(keyCode) == true) {
return true
}
return super.onKeyDown(keyCode, event)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if (item.itemId == android.R.id.home) {
finish()
return true
}
return super.onOptionsItemSelected(item)
}
override fun onTaskCompleted(taskName: String, taskId: Long, task: Task<*, *>, result: Any) {
}
override fun onTaskError(s: String, l: Long, task: Task<*, *>, throwable: Throwable) {
}
override fun finish() {
super.finish()
when (transitionType) {
Transition.Horizontal -> slideThisRight()
Transition.Vertical -> slideThisDown()
}
}
override fun setContentView(layoutId: Int) {
super.setContentView(layoutId)
setupToolbar()
}
override fun setContentView(view: View?) {
super.setContentView(view)
setupToolbar()
}
override fun setContentView(view: View?, params: ViewGroup.LayoutParams?) {
super.setContentView(view, params)
setupToolbar()
}
private fun setupToolbar() {
toolbar?.let { setSupportActionBar(it) }
}
protected val top: Fragment?
get() {
return when {
fm.backStackEntryCount == 0 ->
fm.findFragmentByTag(BrowseFragment.TAG)
else -> fm.findFragmentByTag(
fm.getBackStackEntryAt(fm.backStackEntryCount - 1).name)
}
}
protected val fm: FragmentManager
get() = supportFragmentManager
protected open val transitionType = Transition.Horizontal
protected val extras: Bundle
get() = intent?.extras ?: Bundle()
override fun <T: ViewModel<*>> createViewModel(): T? = null
protected fun <T: ViewModel<*>> getViewModel(): T? = mixin(ViewModelMixin::class.java)?.get<T>() as T
protected fun <T: IMixin> mixin(mixin: T): T = mixins.add(mixin)
protected fun <T: IMixin> mixin(cls: Class<out T>): T? = mixins.get(cls)
protected val runner: Runner
get() = mixin(RunnerMixin::class.java)!!.runner
}
| bsd-3-clause | 8c79b69f68d0665dabaf4dc68641c3c8 | 29.868421 | 105 | 0.666155 | 4.680766 | false | false | false | false |
inorichi/mangafeed | app/src/main/java/eu/kanade/tachiyomi/ui/manga/track/TrackSheet.kt | 2 | 8720 | package eu.kanade.tachiyomi.ui.manga.track
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import androidx.fragment.app.FragmentManager
import androidx.recyclerview.widget.LinearLayoutManager
import com.google.android.material.bottomsheet.BottomSheetBehavior
import com.google.android.material.datepicker.CalendarConstraints
import com.google.android.material.datepicker.DateValidatorPointBackward
import com.google.android.material.datepicker.DateValidatorPointForward
import com.google.android.material.datepicker.MaterialDatePicker
import eu.kanade.tachiyomi.R
import eu.kanade.tachiyomi.data.database.models.Manga
import eu.kanade.tachiyomi.data.track.EnhancedTrackService
import eu.kanade.tachiyomi.databinding.TrackControllerBinding
import eu.kanade.tachiyomi.source.SourceManager
import eu.kanade.tachiyomi.ui.base.controller.openInBrowser
import eu.kanade.tachiyomi.ui.manga.MangaController
import eu.kanade.tachiyomi.util.lang.launchIO
import eu.kanade.tachiyomi.util.lang.toLocalCalendar
import eu.kanade.tachiyomi.util.lang.toUtcCalendar
import eu.kanade.tachiyomi.util.lang.withUIContext
import eu.kanade.tachiyomi.util.system.copyToClipboard
import eu.kanade.tachiyomi.util.system.toast
import eu.kanade.tachiyomi.widget.sheet.BaseBottomSheetDialog
import uy.kohesive.injekt.Injekt
import uy.kohesive.injekt.api.get
class TrackSheet(
val controller: MangaController,
val manga: Manga,
val fragmentManager: FragmentManager,
private val sourceManager: SourceManager = Injekt.get()
) : BaseBottomSheetDialog(controller.activity!!),
TrackAdapter.OnClickListener,
SetTrackStatusDialog.Listener,
SetTrackChaptersDialog.Listener,
SetTrackScoreDialog.Listener {
private lateinit var binding: TrackControllerBinding
private lateinit var adapter: TrackAdapter
override fun createView(inflater: LayoutInflater): View {
binding = TrackControllerBinding.inflate(layoutInflater)
return binding.root
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
adapter = TrackAdapter(this)
binding.trackRecycler.layoutManager = LinearLayoutManager(context)
binding.trackRecycler.adapter = adapter
adapter.items = controller.presenter.trackList
}
override fun show() {
super.show()
controller.presenter.refreshTrackers()
behavior.state = BottomSheetBehavior.STATE_COLLAPSED
}
fun onNextTrackers(trackers: List<TrackItem>) {
if (this::adapter.isInitialized) {
adapter.items = trackers
adapter.notifyDataSetChanged()
}
}
override fun onOpenInBrowserClick(position: Int) {
val track = adapter.getItem(position)?.track ?: return
if (track.tracking_url.isNotBlank()) {
controller.openInBrowser(track.tracking_url)
}
}
override fun onSetClick(position: Int) {
val item = adapter.getItem(position) ?: return
if (item.service is EnhancedTrackService) {
if (item.track != null) {
controller.presenter.unregisterTracking(item.service)
return
}
if (!item.service.accept(sourceManager.getOrStub(manga.source))) {
controller.presenter.view?.applicationContext?.toast(R.string.source_unsupported)
return
}
launchIO {
try {
item.service.match(manga)?.let { track ->
controller.presenter.registerTracking(track, item.service)
}
?: withUIContext { controller.presenter.view?.applicationContext?.toast(R.string.error_no_match) }
} catch (e: Exception) {
withUIContext { controller.presenter.view?.applicationContext?.toast(R.string.error_no_match) }
}
}
} else {
TrackSearchDialog(controller, item.service, item.track?.tracking_url)
.showDialog(controller.router, TAG_SEARCH_CONTROLLER)
}
}
override fun onTitleLongClick(position: Int) {
adapter.getItem(position)?.track?.title?.let {
controller.activity?.copyToClipboard(it, it)
}
}
override fun onStatusClick(position: Int) {
val item = adapter.getItem(position) ?: return
if (item.track == null) return
SetTrackStatusDialog(controller, this, item).showDialog(controller.router)
}
override fun onChaptersClick(position: Int) {
val item = adapter.getItem(position) ?: return
if (item.track == null) return
SetTrackChaptersDialog(controller, this, item).showDialog(controller.router)
}
override fun onScoreClick(position: Int) {
val item = adapter.getItem(position) ?: return
if (item.track == null || item.service.getScoreList().isEmpty()) return
SetTrackScoreDialog(controller, this, item).showDialog(controller.router)
}
override fun onStartDateEditClick(position: Int) {
val item = adapter.getItem(position) ?: return
if (item.track == null) return
val selection = item.track.started_reading_date.toUtcCalendar()?.timeInMillis
?: MaterialDatePicker.todayInUtcMilliseconds()
// No time travellers allowed
val constraints = CalendarConstraints.Builder().apply {
val finishedMillis = item.track.finished_reading_date.toUtcCalendar()?.timeInMillis
if (finishedMillis != null) {
setValidator(DateValidatorPointBackward.before(finishedMillis))
}
}.build()
val picker = MaterialDatePicker.Builder.datePicker()
.setTitleText(R.string.track_started_reading_date)
.setSelection(selection)
.setCalendarConstraints(constraints)
.build()
picker.addOnPositiveButtonClickListener { utcMillis ->
val result = utcMillis.toLocalCalendar()?.timeInMillis
if (result != null) {
controller.presenter.setTrackerStartDate(item, result)
}
}
picker.show(fragmentManager, null)
}
override fun onFinishDateEditClick(position: Int) {
val item = adapter.getItem(position) ?: return
if (item.track == null) return
val selection = item.track.finished_reading_date.toUtcCalendar()?.timeInMillis
?: MaterialDatePicker.todayInUtcMilliseconds()
// No time travellers allowed
val constraints = CalendarConstraints.Builder().apply {
val startMillis = item.track.started_reading_date.toUtcCalendar()?.timeInMillis
if (startMillis != null) {
setValidator(DateValidatorPointForward.from(startMillis))
}
}.build()
val picker = MaterialDatePicker.Builder.datePicker()
.setTitleText(R.string.track_finished_reading_date)
.setSelection(selection)
.setCalendarConstraints(constraints)
.build()
picker.addOnPositiveButtonClickListener { utcMillis ->
val result = utcMillis.toLocalCalendar()?.timeInMillis
if (result != null) {
controller.presenter.setTrackerFinishDate(item, result)
}
}
picker.show(fragmentManager, null)
}
override fun onStartDateRemoveClick(position: Int) {
val item = adapter.getItem(position) ?: return
if (item.track == null) return
controller.presenter.setTrackerStartDate(item, 0)
}
override fun onFinishDateRemoveClick(position: Int) {
val item = adapter.getItem(position) ?: return
if (item.track == null) return
controller.presenter.setTrackerFinishDate(item, 0)
}
override fun onRemoveItemClick(position: Int) {
val item = adapter.getItem(position) ?: return
if (item.track == null) return
controller.presenter.unregisterTracking(item.service)
}
override fun setStatus(item: TrackItem, selection: Int) {
controller.presenter.setTrackerStatus(item, selection)
}
override fun setChaptersRead(item: TrackItem, chaptersRead: Int) {
controller.presenter.setTrackerLastChapterRead(item, chaptersRead)
}
override fun setScore(item: TrackItem, score: Int) {
controller.presenter.setTrackerScore(item, score)
}
fun getSearchDialog(): TrackSearchDialog? {
return controller.router.getControllerWithTag(TAG_SEARCH_CONTROLLER) as? TrackSearchDialog
}
}
private const val TAG_SEARCH_CONTROLLER = "track_search_controller"
| apache-2.0 | afa00e2b18bf60e2a2bb69da4e4c8981 | 36.748918 | 122 | 0.679817 | 4.73913 | false | false | false | false |
dbrant/apps-android-wikipedia | app/src/main/java/org/wikipedia/bridge/CommunicationBridge.kt | 1 | 6879 | package org.wikipedia.bridge
import android.annotation.SuppressLint
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.webkit.*
import com.google.gson.JsonObject
import org.wikipedia.bridge.JavaScriptActionHandler.setUp
import org.wikipedia.dataclient.RestService
import org.wikipedia.dataclient.ServiceFactory
import org.wikipedia.json.GsonUtil
import org.wikipedia.page.PageTitle
import org.wikipedia.page.PageViewModel
import org.wikipedia.util.UriUtil
import org.wikipedia.util.log.L
/**
* Two-way communications bridge between JS in a WebView and Java.
*
* Messages TO the WebView are sent by calling loadUrl() with the Javascript payload in it.
*
* Messages FROM the WebView are received by leveraging @JavascriptInterface methods.
*/
@SuppressLint("AddJavascriptInterface", "SetJavaScriptEnabled")
class CommunicationBridge constructor(private val communicationBridgeListener: CommunicationBridgeListener) {
private val eventListeners = HashMap<String, MutableList<JSEventListener>>()
private var isMetadataReady = false
private var isPcsReady = false
private val pendingJSMessages = ArrayList<String>()
private val pendingEvals = HashMap<String, ValueCallback<String>>()
fun interface JSEventListener {
fun onMessage(messageType: String, messagePayload: JsonObject?)
}
interface CommunicationBridgeListener {
val webView: WebView
val model: PageViewModel
val isPreview: Boolean
val toolbarMargin: Int
}
init {
communicationBridgeListener.webView.settings.javaScriptEnabled = true
communicationBridgeListener.webView.settings.allowUniversalAccessFromFileURLs = true
communicationBridgeListener.webView.settings.mediaPlaybackRequiresUserGesture = false
communicationBridgeListener.webView.webChromeClient = CommunicatingChrome()
communicationBridgeListener.webView.addJavascriptInterface(PcsClientJavascriptInterface(), "pcsClient")
}
fun onPcsReady() {
isPcsReady = true
flushMessages()
}
fun loadBlankPage() {
communicationBridgeListener.webView.loadUrl("about:blank")
}
fun onMetadataReady() {
isMetadataReady = true
flushMessages()
}
val isLoading: Boolean
get() = !(isMetadataReady && isPcsReady)
fun resetHtml(pageTitle: PageTitle) {
isPcsReady = false
isMetadataReady = false
pendingJSMessages.clear()
pendingEvals.clear()
if (communicationBridgeListener.model.shouldLoadAsMobileWeb()) {
communicationBridgeListener.webView.loadUrl(pageTitle.mobileUri)
} else {
communicationBridgeListener.webView.loadUrl(ServiceFactory.getRestBasePath(pageTitle.wikiSite) +
RestService.PAGE_HTML_ENDPOINT + UriUtil.encodeURL(pageTitle.prefixedText))
}
}
fun cleanup() {
pendingJSMessages.clear()
pendingEvals.clear()
eventListeners.clear()
incomingMessageHandler?.removeCallbacksAndMessages(null)
incomingMessageHandler = null
communicationBridgeListener.webView.webViewClient = WebViewClient()
communicationBridgeListener.webView.removeJavascriptInterface("pcsClient")
// Explicitly load a blank page into the WebView, to stop playback of any media.
loadBlankPage()
}
fun addListener(type: String, listener: JSEventListener) {
if (eventListeners.containsKey(type)) {
eventListeners[type]!!.add(listener)
} else {
val listeners = ArrayList<JSEventListener>()
listeners.add(listener)
eventListeners[type] = listeners
}
}
fun execute(js: String) {
pendingJSMessages.add("javascript:$js")
flushMessages()
}
fun evaluate(js: String, callback: ValueCallback<String>) {
pendingEvals[js] = callback
flushMessages()
}
fun evaluateImmediate(js: String, callback: ValueCallback<String?>?) {
communicationBridgeListener.webView.evaluateJavascript(js, callback)
}
private fun flushMessages() {
if (!isPcsReady || !isMetadataReady) {
return
}
for (jsString in pendingJSMessages) {
communicationBridgeListener.webView.loadUrl(jsString)
}
pendingJSMessages.clear()
for (key in pendingEvals.keys) {
communicationBridgeListener.webView.evaluateJavascript(key, pendingEvals[key])
}
pendingEvals.clear()
}
private var incomingMessageHandler: Handler? = Handler(Looper.getMainLooper(), Handler.Callback { msg ->
val message = msg.obj as BridgeMessage
if (!eventListeners.containsKey(message.action)) {
L.e("No such message type registered: " + message.action)
return@Callback false
}
try {
val listeners: List<JSEventListener> = eventListeners[message.action]!!
for (listener in listeners) {
listener.onMessage(message.action!!, message.data)
}
} catch (e: Exception) {
e.printStackTrace()
L.logRemoteError(e)
}
false
})
private class CommunicatingChrome : WebChromeClient() {
override fun onConsoleMessage(consoleMessage: ConsoleMessage): Boolean {
L.d(consoleMessage.sourceId() + ":" + consoleMessage.lineNumber() + " - " + consoleMessage.message())
return true
}
}
private inner class PcsClientJavascriptInterface {
/**
* Called from Javascript to send a message packet to the Java layer. The message must be
* formatted in JSON, and URL-encoded.
*
* @param message JSON structured message received from the WebView.
*/
@JavascriptInterface
@Synchronized
fun onReceiveMessage(message: String?) {
if (incomingMessageHandler != null) {
val msg = Message.obtain(incomingMessageHandler, MESSAGE_HANDLE_MESSAGE_FROM_JS,
GsonUtil.getDefaultGson().fromJson(message, BridgeMessage::class.java))
incomingMessageHandler!!.sendMessage(msg)
}
}
@get:Synchronized
@get:JavascriptInterface
val setupSettings: String
get() = setUp(communicationBridgeListener.webView.context,
communicationBridgeListener.model.title!!, communicationBridgeListener.isPreview,
communicationBridgeListener.toolbarMargin)
}
private class BridgeMessage {
val action: String? = null
get() = field.orEmpty()
val data: JsonObject? = null
}
companion object {
private const val MESSAGE_HANDLE_MESSAGE_FROM_JS = 1
}
}
| apache-2.0 | a25af10a735fedfdc2cd63aeea43d915 | 35.015707 | 113 | 0.673208 | 5.013848 | false | false | false | false |
simplifycom/simplify-android-sdk-sample | simplify-android/src/main/kotlin/com/simplify/android/sdk/SimplifySecure3DActivity.kt | 2 | 6953 | package com.simplify.android.sdk
import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.Toolbar
import android.webkit.WebChromeClient
import android.webkit.WebResourceRequest
import android.webkit.WebView
import android.webkit.WebViewClient
import androidx.annotation.RequiresApi
import java.lang.IllegalArgumentException
class SimplifySecure3DActivity : AppCompatActivity() {
private lateinit var webView: WebView
private val extraTitle by lazyAndroid { intent.extras?.getString(EXTRA_TITLE) ?: getString(R.string.simplify_3d_secure_authentication) }
private val extraAcsUrl by lazyAndroid { intent.extras?.getString(EXTRA_ACS_URL) ?: "" }
private val extraPaReq by lazyAndroid { intent.extras?.getString(EXTRA_PA_REQ) ?: "" }
private val extraMerchantData by lazyAndroid { intent.extras?.getString(EXTRA_MERCHANT_DATA) ?: "" }
private val extraTermUrl by lazyAndroid { intent.extras?.getString(EXTRA_TERM_URL) ?: "" }
private val startingHtml by lazyAndroid {
resources.openRawResource(R.raw.secure3d1).readBytes().toString(Charsets.UTF_8)
.replace(PLACEHOLDER_ACS_URL, extraAcsUrl.urlEncode())
.replace(PLACEHOLDER_PA_REQ, extraPaReq.urlEncode())
.replace(PLACEHOLDER_MERCHANT_DATA, extraMerchantData.urlEncode())
.replace(PLACEHOLDER_TERM_URL, extraTermUrl.urlEncode())
}
@SuppressLint("SetJavaScriptEnabled")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.simplify_3dsecure)
// if required param missing, back out
if (extraAcsUrl.isEmpty() || extraPaReq.isEmpty() || extraTermUrl.isEmpty() || extraMerchantData.isEmpty()) {
onBackPressed()
return
}
// init toolbar
findViewById<Toolbar>(R.id.toolbar).apply {
setNavigationOnClickListener { onBackPressed() }
title = extraTitle
}
// init web view
webView = findViewById<WebView>(R.id.webview).apply {
webChromeClient = WebChromeClient()
settings.domStorageEnabled = true
settings.javaScriptEnabled = true
webViewClient = buildWebViewClient()
loadData(startingHtml, "text/html", Charsets.UTF_8.name())
}
}
internal fun webViewUrlChanges(uri: Uri) {
when {
REDIRECT_SCHEME.equals(uri.scheme, ignoreCase = true) -> complete(uri)
MAILTO_SCHEME.equals(uri.scheme, ignoreCase = true) -> mailto(uri)
else -> redirect(uri)
}
}
private fun complete(uri: Uri) {
val intent = Intent().apply {
putExtra(EXTRA_RESULT, getResultFromUri(uri))
}
setResult(Activity.RESULT_OK, intent)
finish()
}
private fun mailto(uri: Uri) {
val intent = Intent(Intent.ACTION_SENDTO).apply {
flags = Intent.FLAG_ACTIVITY_NEW_TASK
data = uri
}
startActivity(intent)
}
private fun redirect(uri: Uri) {
webView.loadUrl(uri.toString())
}
private fun getResultFromUri(uri: Uri): String? {
var result: String? = null
uri.queryParameterNames.forEach { param ->
if (REDIRECT_QUERY_PARAM.equals(param, ignoreCase = true)) {
result = uri.getQueryParameter(param)
}
}
return result
}
private fun buildWebViewClient(): WebViewClient {
return object : WebViewClient() {
@Suppress("OverridingDeprecatedMember")
override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean {
webViewUrlChanges(Uri.parse(url))
return true
}
@RequiresApi(Build.VERSION_CODES.LOLLIPOP)
override fun shouldOverrideUrlLoading(view: WebView, request: WebResourceRequest): Boolean {
webViewUrlChanges(request.url)
return true
}
}
}
companion object {
/**
* The ACS URL returned from card token create
*/
const val EXTRA_ACS_URL = "com.simplify.android.sdk.ASC_URL"
/**
* The PaReq returned from card token create
*/
const val EXTRA_PA_REQ = "com.simplify.android.sdk.PA_REQ"
/**
* The Merchant Data (md) returned from card token create
*/
const val EXTRA_MERCHANT_DATA = "com.simplify.android.sdk.MERCHANT_DATA"
/**
* The Termination URL (termUrl) returned from card token create
*/
const val EXTRA_TERM_URL = "com.simplify.android.sdk.TERM_URL"
/**
* An OPTIONAL title to display in the toolbar for this activity
*/
const val EXTRA_TITLE = "com.simplify.android.sdk.TITLE"
/**
* The result data after performing 3DS
*/
const val EXTRA_RESULT = "com.simplify.android.sdk.RESULT"
private const val REDIRECT_SCHEME = "simplifysdk"
private const val REDIRECT_QUERY_PARAM = "result"
private const val MAILTO_SCHEME = "mailto"
private const val PLACEHOLDER_ACS_URL = "{{{acsUrl}}}"
private const val PLACEHOLDER_PA_REQ = "{{{paReq}}}"
private const val PLACEHOLDER_MERCHANT_DATA = "{{{md}}}"
private const val PLACEHOLDER_TERM_URL = "{{{termUrl}}}"
/**
* Construct an intent to the [SimplifySecure3DActivity] activity, adding the relevant 3DS data from the card token as intent extras
*
* @param context The calling context
* @param cardToken The card token used for a 3DS transaction
* @param title An OPTIONAL title to display in the toolbar
* @throws IllegalArgumentException If the card token does not contain valid 3DS data
*/
@JvmOverloads
@JvmStatic
fun buildIntent(context: Context, cardToken: SimplifyMap, title: String? = null): Intent {
if (!cardToken.containsKey("card.secure3DData")) {
throw IllegalArgumentException("The provided card token must contain 3DS data.")
}
return Intent(context, SimplifySecure3DActivity::class.java).apply {
putExtra(EXTRA_ACS_URL, cardToken["card.secure3DData.acsUrl"] as String?)
putExtra(EXTRA_PA_REQ, cardToken["card.secure3DData.paReq"] as String?)
putExtra(EXTRA_MERCHANT_DATA, cardToken["card.secure3DData.md"] as String?)
putExtra(EXTRA_TERM_URL, cardToken["card.secure3DData.termUrl"] as String?)
putExtra(EXTRA_TITLE, title)
}
}
}
} | mit | 83100e636d70889eca4fc586f6c37119 | 35.6 | 140 | 0.635265 | 4.568331 | false | false | false | false |
dahlstrom-g/intellij-community | platform/vcs-impl/src/com/intellij/openapi/vcs/changes/actions/MoveChangesToAnotherListAction.kt | 7 | 8078 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.vcs.changes.actions
import com.intellij.idea.ActionsBundle
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.MessageType
import com.intellij.openapi.util.text.StringUtil
import com.intellij.openapi.vcs.*
import com.intellij.openapi.vcs.changes.*
import com.intellij.openapi.vcs.changes.ui.ChangeListChooser
import com.intellij.openapi.vcs.changes.ui.ChangesListView
import com.intellij.openapi.vcs.changes.ui.ChangesViewContentManager.Companion.LOCAL_CHANGES
import com.intellij.openapi.vcs.changes.ui.ChangesViewContentManager.Companion.getToolWindowFor
import com.intellij.openapi.vcs.ex.LocalRange
import com.intellij.openapi.vcs.ex.PartialLocalLineStatusTracker
import com.intellij.openapi.vcs.ui.VcsBalloonProblemNotifier
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.containers.asJBIterable
import com.intellij.vcsUtil.VcsUtil
import org.jetbrains.annotations.Nls
class MoveChangesToAnotherListAction : AbstractChangeListAction() {
override fun update(e: AnActionEvent) {
val project = e.project
val enabled = project != null && ProjectLevelVcsManager.getInstance(project).hasActiveVcss() &&
ChangeListManager.getInstance(project).areChangeListsEnabled() &&
(!e.getData(ChangesListView.UNVERSIONED_FILE_PATHS_DATA_KEY).asJBIterable().isEmpty() ||
!e.getData(VcsDataKeys.CHANGES).isNullOrEmpty() ||
!e.getData(CommonDataKeys.VIRTUAL_FILE_ARRAY).isNullOrEmpty())
updateEnabledAndVisible(e, enabled)
if (!e.getData(VcsDataKeys.CHANGE_LISTS).isNullOrEmpty()) {
e.presentation.text = ActionsBundle.message("action.ChangesView.Move.Files.text")
}
}
override fun actionPerformed(e: AnActionEvent) {
with(MoveChangesHandler(e.project!!)) {
addChanges(e.getData(VcsDataKeys.CHANGES))
if (isEmpty) {
addChangesForFiles(e.getData(CommonDataKeys.VIRTUAL_FILE_ARRAY))
}
if (isEmpty) {
VcsBalloonProblemNotifier.showOverChangesView(project,
VcsBundle.message("move.to.another.changelist.nothing.selected.notification"),
MessageType.INFO)
return
}
if (!askAndMove(project, changes, unversionedFiles)) return
if (changedFiles.isNotEmpty()) {
selectAndShowFile(project, changedFiles[0])
}
}
}
private fun selectAndShowFile(project: Project, file: VirtualFile) {
val window = getToolWindowFor(project, LOCAL_CHANGES) ?: return
if (!window.isVisible) {
window.activate { ChangesViewManager.getInstance(project).selectFile(file) }
}
}
companion object {
@JvmStatic
fun askAndMove(project: Project, changes: Collection<Change>, unversionedFiles: List<VirtualFile>): Boolean {
if (changes.isEmpty() && unversionedFiles.isEmpty()) return false
val targetList = askTargetList(project, changes)
if (targetList != null) {
val changeListManager = ChangeListManagerEx.getInstanceEx(project)
changeListManager.moveChangesTo(targetList, *changes.toTypedArray())
if (unversionedFiles.isNotEmpty()) {
changeListManager.addUnversionedFiles(targetList, unversionedFiles)
}
return true
}
return false
}
private fun guessPreferredList(lists: Collection<LocalChangeList>): ChangeList? {
val comparator = compareBy<LocalChangeList> { if (it.isDefault) -1 else 0 }
.thenBy { if (it.changes.isEmpty()) -1 else 0 }
.then(ChangesUtil.CHANGELIST_COMPARATOR)
return lists.minWithOrNull(comparator)
}
private fun askTargetList(project: Project, changes: Collection<Change>): LocalChangeList? {
val changeListManager = ChangeListManager.getInstance(project)
val affectedLists = changes.flatMapTo(mutableSetOf()) { changeListManager.getChangeLists(it) }
val sameFileChangeLists = changes.flatMapTo(mutableSetOf()) {
val fileChange = if (it is ChangeListChange) it.change else it
changeListManager.getChangeLists(fileChange)
}
return askTargetChangelist(project, affectedLists, sameFileChangeLists,
ActionsBundle.message("action.ChangesView.Move.text"))
}
@JvmStatic
fun askTargetChangelist(project: Project,
selectedRanges: List<LocalRange>,
tracker: PartialLocalLineStatusTracker): LocalChangeList? {
val changeListManager = ChangeListManager.getInstance(project)
val allChangelists = changeListManager.changeLists
val affectedListIds = selectedRanges.map { range -> range.changelistId }.toSet()
val affectedLists = allChangelists.filter { list -> affectedListIds.contains(list.id) }.toSet()
val sameFileChangeListsIds = tracker.getAffectedChangeListsIds().toSet()
val sameFileChangeLists = allChangelists.filter { list -> sameFileChangeListsIds.contains(list.id) }.toSet()
return askTargetChangelist(project, affectedLists, sameFileChangeLists,
ActionsBundle.message("action.Vcs.MoveChangedLinesToChangelist.text"))
}
private fun askTargetChangelist(project: Project,
affectedLists: Set<LocalChangeList>,
sameFileChangeLists: Set<LocalChangeList>,
title: @Nls String): LocalChangeList? {
val changeListManager = ChangeListManager.getInstance(project)
val allChangelists = changeListManager.changeLists
val nonAffectedLists = if (affectedLists.size == 1) allChangelists - affectedLists else allChangelists
val suggestedLists = nonAffectedLists.ifEmpty { listOf(changeListManager.defaultChangeList) }
val preferredList = (sameFileChangeLists - affectedLists)
.ifEmpty { allChangelists.toSet() - affectedLists }
.ifEmpty { nonAffectedLists }
val defaultSelection = guessPreferredList(preferredList)
val chooser = ChangeListChooser(project, StringUtil.removeEllipsisSuffix(title))
chooser.setChangeLists(suggestedLists)
chooser.setDefaultSelection(defaultSelection)
chooser.show()
return chooser.selectedList
}
}
}
private class MoveChangesHandler(val project: Project) {
private val changeListManager = ChangeListManager.getInstance(project)
val unversionedFiles = mutableListOf<VirtualFile>()
val changedFiles = mutableListOf<VirtualFile>()
val changes = mutableListOf<Change>()
val isEmpty get() = changes.isEmpty() && unversionedFiles.isEmpty()
fun addChanges(changes: Array<Change>?) {
this.changes.addAll(changes.orEmpty())
}
fun addChangesForFiles(files: Array<VirtualFile>?) {
for (file in files.orEmpty()) {
val change = changeListManager.getChange(file)
if (change == null) {
val status = changeListManager.getStatus(file)
if (FileStatus.UNKNOWN == status) {
unversionedFiles.add(file)
changedFiles.add(file)
}
else if (FileStatus.NOT_CHANGED == status && file.isDirectory) {
addChangesUnder(VcsUtil.getFilePath(file))
}
}
else {
val afterPath = ChangesUtil.getAfterPath(change)
if (afterPath != null && afterPath.isDirectory) {
addChangesUnder(afterPath)
}
else {
changes.add(change)
changedFiles.add(file)
}
}
}
}
private fun addChangesUnder(path: FilePath) {
for (change in changeListManager.getChangesIn(path)) {
changes.add(change)
val file = ChangesUtil.getAfterPath(change)?.virtualFile
file?.let { changedFiles.add(it) }
}
}
} | apache-2.0 | 362b05d57aadd665a059464e0fe1e126 | 40.219388 | 140 | 0.697574 | 4.880967 | false | false | false | false |
spotify/heroic | usage-tracking/google/src/main/java/com/spotify/heroic/usagetracking/google/GoogleAnalytics.kt | 1 | 3416 | /*
* 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.usagetracking.google
import com.google.common.hash.Hashing
import com.spotify.heroic.scheduler.Scheduler
import com.spotify.heroic.usagetracking.UsageTracking
import okhttp3.OkHttpClient
import okhttp3.Request
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import java.lang.management.ManagementFactory
import java.util.concurrent.TimeUnit
import javax.inject.Inject
import javax.inject.Named
private val log: Logger = LoggerFactory.getLogger(GoogleAnalytics::class.java)
private val CLIENT = OkHttpClient.Builder()
.connectTimeout(10, TimeUnit.SECONDS)
.writeTimeout(10, TimeUnit.SECONDS)
.readTimeout(10, TimeUnit.SECONDS)
.build()
private val BASE_REQUEST = Request.Builder()
.url("https://www.google-analytics.com/collect")
class GoogleAnalytics @Inject constructor(
@Named("version") val version: String,
@Named("commit") val commit: String,
val scheduler: Scheduler
): UsageTracking {
private val runtimeBean = ManagementFactory.getRuntimeMXBean()
private val clientId: String
private val eventVersion = "$version:$commit"
init {
val hostname = lookupHostname()
clientId = if (hostname == null) "UNKNOWN_HOST"
else Hashing.sha256().hashString(hostname, Charsets.UTF_8).toString()
scheduler.periodically(24, TimeUnit.HOURS, ::reportUptime)
}
override fun reportStartup() {
val event = Event(clientId)
.category("deployment")
.action("startup")
.version(eventVersion)
sendEvent(event)
}
override fun reportClusterSize(size: Int) {
val event = Event(clientId)
.category("deployment")
.action("cluster_refresh")
.version(eventVersion)
.value(size.toString())
sendEvent(event)
}
/**
* Report time, in milliseconds, since the JVM started.
*/
private fun reportUptime() {
val event = Event(clientId)
.category("deployment")
.action("uptime")
.version(eventVersion)
.value(runtimeBean.uptime.toString())
sendEvent(event)
}
private fun sendEvent(event: Event) {
val body = event.build()
log.debug("Sending event to Google Analytics")
CLIENT.newCall(BASE_REQUEST.post(body).build()).execute().use {
r -> {
if (!r.isSuccessful) {
log.error("Failed to send event to Google Analytics: {}", r.code())
}
}
}
}
}
| apache-2.0 | 811cfdccbd8b1a30609412bf0f979b17 | 30.925234 | 87 | 0.671253 | 4.329531 | false | false | false | false |
ediTLJ/novelty | app/src/main/java/ro/edi/novelty/ui/MainActivity.kt | 1 | 7629 | /*
* Copyright 2019 Eduard Scarlat
*
* 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 ro.edi.novelty.ui
import android.content.Intent
import android.os.Bundle
import android.util.DisplayMetrics
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.Toolbar
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.LinearSmoothScroller
import androidx.recyclerview.widget.RecyclerView
import androidx.viewpager2.widget.ViewPager2
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayoutMediator
import com.google.android.material.transition.platform.MaterialContainerTransformSharedElementCallback
import ro.edi.novelty.R
import ro.edi.novelty.ui.adapter.FeedsPagerAdapter
import ro.edi.novelty.ui.viewmodel.FeedsViewModel
import ro.edi.util.applyWindowInsetsMargin
import java.util.*
import timber.log.Timber.Forest.i as logi
class MainActivity : AppCompatActivity(), TabLayout.OnTabSelectedListener {
private val feedsModel: FeedsViewModel by lazy(LazyThreadSafetyMode.NONE) {
ViewModelProvider(
viewModelStore,
defaultViewModelProviderFactory
)[FeedsViewModel::class.java]
}
override fun onCreate(savedInstanceState: Bundle?) {
// attach a callback used to capture the shared elements from this activity
// to be used by the container transform transition
setExitSharedElementCallback(MaterialContainerTransformSharedElementCallback())
// keep system bars (status bar, navigation bar) persistent throughout the transition
window.sharedElementsUseOverlay = false
super.onCreate(savedInstanceState)
window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LAYOUT_STABLE or
View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
setContentView(R.layout.activity_main)
initView()
}
override fun onDestroy() {
val tabs = findViewById<TabLayout>(R.id.tabs)
tabs.removeOnTabSelectedListener(this)
super.onDestroy()
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.menu_main, menu)
menu.findItem(R.id.action_feeds).isVisible = (feedsModel.feeds.value?.size ?: 0) > 0
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.action_feeds -> {
val iFeeds = Intent(application, FeedsActivity::class.java)
iFeeds.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP
startActivity(iFeeds)
}
R.id.action_info -> InfoDialogFragment().show(supportFragmentManager, "dialog_info")
}
return super.onOptionsItemSelected(item)
}
private fun initView() {
val toolbar = findViewById<Toolbar>(R.id.toolbar)
setSupportActionBar(toolbar)
supportActionBar?.setDisplayShowTitleEnabled(false)
toolbar.applyWindowInsetsMargin(
applyLeft = true,
applyTop = false,
applyRight = true,
applyBottom = false
)
val adapter = FeedsPagerAdapter(this, feedsModel)
val pager = findViewById<ViewPager2>(R.id.pager)
pager.adapter = adapter
pager.offscreenPageLimit = 1 // ViewPager2.OFFSCREEN_PAGE_LIMIT_DEFAULT
pager.setCurrentItem(1, false)
val tabs = findViewById<TabLayout>(R.id.tabs)
tabs.applyWindowInsetsMargin(
applyLeft = true,
applyTop = false,
applyRight = true,
applyBottom = false
)
val tabLayoutMediator = TabLayoutMediator(tabs, pager) { tab, page ->
when (page) {
0 -> {
tab.text = getText(R.string.tab_my_news)
tab.tag = 0
}
1 -> {
tab.text = getText(R.string.tab_my_feeds)
tab.tag = 1
}
else -> {
val feed = feedsModel.getFeed(page - 2)
tab.text = feed?.title?.uppercase(Locale.getDefault())
tab.tag = feed?.id
}
}
}
tabLayoutMediator.attach()
tabs.addOnTabSelectedListener(this)
val tvEmpty = findViewById<TextView>(R.id.empty)
feedsModel.feeds.observe(this) { feeds ->
logi("feeds changed: %d feeds", feeds.size)
invalidateOptionsMenu()
pager.adapter?.let { adapter ->
val page = pager.currentItem
val index = feeds.indexOfFirst { it.id == tabs.getTabAt(page)?.tag }
// FIXME test all possible cases here
if (page < 2 || page == index + 2) {
adapter.notifyDataSetChanged()
} else {
// tabLayoutMediator.detach()
pager.currentItem = index + 2
adapter.notifyDataSetChanged()
// tabLayoutMediator.attach()
}
}
if (feeds.isEmpty()) {
tabs.visibility = View.GONE
pager.visibility = View.GONE
tvEmpty.visibility = View.VISIBLE
tvEmpty.setOnClickListener {
val iAdd = Intent(this, FeedInfoActivity::class.java)
startActivity(iAdd)
}
} else {
tabs.visibility = View.VISIBLE
pager.visibility = View.VISIBLE
tvEmpty.visibility = View.GONE
if (tabs.selectedTabPosition == -1) {
tabs.selectTab(tabs.getTabAt(feeds.size + 1))
}
}
}
}
override fun onTabSelected(tab: TabLayout.Tab) {
}
override fun onTabReselected(tab: TabLayout.Tab) {
// TODO don't rely on the tag set by ViewPager2... it might change in future versions
val f = supportFragmentManager.findFragmentByTag("f".plus(tab.tag)) ?: return
val rvNews = f.view?.findViewById<RecyclerView>(R.id.news) ?: return
val layoutManager = rvNews.layoutManager as LinearLayoutManager
val firstVisible = layoutManager.findFirstCompletelyVisibleItemPosition()
val smoothScroller = object : LinearSmoothScroller(this) {
override fun getVerticalSnapPreference(): Int {
return SNAP_TO_START
}
// item height: 88
override fun calculateSpeedPerPixel(displayMetrics: DisplayMetrics): Float {
return 300 / (88f * displayMetrics.density * firstVisible)
}
}
smoothScroller.targetPosition = 0
layoutManager.startSmoothScroll(smoothScroller)
}
override fun onTabUnselected(tab: TabLayout.Tab) {
}
} | apache-2.0 | 9e9f94bea771db1d239ae5a09b0bd649 | 34.821596 | 102 | 0.631275 | 4.944264 | false | false | false | false |
flesire/ontrack | ontrack-ui-graphql/src/main/java/net/nemerosa/ontrack/graphql/schema/GQLRootQueryLabels.kt | 1 | 1718 | package net.nemerosa.ontrack.graphql.schema
import graphql.Scalars.GraphQLString
import graphql.schema.GraphQLFieldDefinition
import net.nemerosa.ontrack.graphql.support.GraphqlUtils.stdList
import net.nemerosa.ontrack.model.labels.LabelManagementService
import org.springframework.stereotype.Component
/**
* Gets the list of labels
*/
@Component
class GQLRootQueryLabels(
private val label: GQLTypeLabel,
private val labelManagementService: LabelManagementService
) : GQLRootQuery {
override fun getFieldDefinition(): GraphQLFieldDefinition =
GraphQLFieldDefinition.newFieldDefinition()
.name("labels")
.description("List of all labels")
.type(stdList(label.typeRef))
.argument {
it.name("category")
.description("Category to look for")
.type(GraphQLString)
}
.argument {
it.name("name")
.description("Name to look for")
.type(GraphQLString)
}
.dataFetcher { environment ->
val category: String? = environment.getArgument("category")
val name: String? = environment.getArgument("name")
if (category != null || name != null) {
labelManagementService.findLabels(category, name)
} else {
labelManagementService.labels
}
}
.build()
} | mit | e1060ca724322bb6f2b99176a32fa662 | 39.928571 | 83 | 0.523865 | 6.270073 | false | false | false | false |
imageprocessor/cv4j | app/src/main/java/com/cv4j/app/activity/UseFilterWithRxActivity.kt | 1 | 1967 | package com.cv4j.app.activity
import android.content.res.Resources
import android.graphics.BitmapFactory
import android.os.Bundle
import com.cv4j.app.R
import com.cv4j.app.app.BaseActivity
import com.cv4j.core.filters.NatureFilter
import com.cv4j.rxjava.RxImageData
import com.cv4j.rxjava.RxImageData.Companion.bitmap
import kotlinx.android.synthetic.main.activity_use_filter_with_rx.*
import thereisnospon.codeview.CodeViewTheme
/**
*
* @FileName:
* com.cv4j.app.activity.UseFilterWithRxActivity
* @author: Tony Shen
* @date: 2020-05-05 20:27
* @version: V1.0 <描述当前版本功能>
*/
class UseFilterWithRxActivity : BaseActivity() {
var title: String? = null
lateinit var rxImageData: RxImageData
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_use_filter_with_rx)
intent.extras?.let {
title = it.getString("Title","")
}?:{
title = ""
}()
toolbar.setOnClickListener {
finish()
}
initViews()
initData()
}
private fun initViews() {
toolbar.title = "< $title"
}
private fun initData() {
val res: Resources = getResources()
val bitmap = BitmapFactory.decodeResource(res, R.drawable.test_io)
rxImageData = bitmap(bitmap)
rxImageData.addFilter(NatureFilter())
.isUseCache(false)
.into(image)
codeview.setTheme(CodeViewTheme.ANDROIDSTUDIO).fillColor()
val code = StringBuilder()
code.append("RxImageData.bitmap(bitmap)")
.append("\r\n")
.append(" .addFilter(new NatureFilter())")
.append("\r\n")
.append(" .into(image)")
codeview.showCode(code.toString())
}
override fun onDestroy() {
super.onDestroy()
rxImageData.recycle()
}
} | apache-2.0 | f8f06b291637934f5276a83d46574c8a | 26.111111 | 74 | 0.625833 | 4.014403 | false | false | false | false |
paplorinc/intellij-community | platform/testGuiFramework/src/com/intellij/testGuiFramework/recorder/compile/ModuleXmlBuilder.kt | 10 | 1444 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.testGuiFramework.recorder.compile
/**
* @author Sergey Karashevich
*/
object ModuleXmlBuilder {
private fun module(function: () -> String): String = """<modules>
${function.invoke()}
</modules>"""
private fun modules(outputDir: String, function: () -> String): String =
"""<module name="main" outputDir="$outputDir" type="java-production">
${function.invoke()}
</module>"""
private fun addSource(path: String) = """<sources path="$path"/>"""
private fun addClasspath(path: String) = """<classpath path="$path"/>"""
fun build(outputDir: String, classPath: List<String>, sourcePath: String): String =
module {
modules(outputDir = outputDir) {
classPath
.map { path -> addClasspath(path) }
.plus(addSource(sourcePath))
.joinToString("\n")
}
}
} | apache-2.0 | bfaca8a19e923d61c41468dc7c8f0893 | 30.413043 | 85 | 0.679363 | 4.222222 | false | false | false | false |
nick-rakoczy/Conductor | conductor-engine/src/main/java/urn/conductor/core/LoadHandler.kt | 1 | 1018 | package urn.conductor.core
import org.apache.logging.log4j.LogManager
import urn.conductor.Engine
import urn.conductor.StandardComplexElementHandler
import urn.conductor.stdlib.xml.Load
import java.nio.file.Files
class LoadHandler : StandardComplexElementHandler<Load> {
private val logger = LogManager.getLogger()
override val handles: Class<Load>
get() = Load::class.java
override fun process(element: Load, engine: Engine, processChild: (Any) -> Unit) {
val charset = element.charset
?.let { charset(it) }
?: Charsets.UTF_8
val sourcePath = engine.getPath(element.src.let(engine::interpolate))
val data = Files.readAllBytes(sourcePath).toString(charset)
val type = element.mode
when (type) {
"text" -> engine.put(element.id, data)
"json" -> engine.put(element.id, engine.gson.fromJson(data, Any::class.java))
"js" -> engine.eval("var ${element.id} = $data;")
}
logger.info("Loaded ${type.toUpperCase()} [${sourcePath.toAbsolutePath().normalize()}] as ${element.id}")
}
}
| gpl-3.0 | ce4a26c2f25f26c3136a3026d68035f6 | 30.8125 | 107 | 0.722004 | 3.462585 | false | false | false | false |
apoi/quickbeer-next | app/src/main/java/quickbeer/android/feature/discover/RecentBeersFragment.kt | 2 | 3471 | package quickbeer.android.feature.discover
import android.os.Bundle
import android.view.View
import androidx.core.view.isVisible
import androidx.fragment.app.viewModels
import androidx.recyclerview.widget.LinearLayoutManager
import dagger.hilt.android.AndroidEntryPoint
import quickbeer.android.R
import quickbeer.android.data.state.State
import quickbeer.android.databinding.ListContentBinding
import quickbeer.android.navigation.Destination
import quickbeer.android.ui.DividerDecoration
import quickbeer.android.ui.adapter.base.ListAdapter
import quickbeer.android.ui.adapter.beer.BeerListModel
import quickbeer.android.ui.adapter.beer.BeerListTypeFactory
import quickbeer.android.ui.base.BaseFragment
import quickbeer.android.ui.base.Resetable
import quickbeer.android.ui.listener.setClickListener
import quickbeer.android.ui.recyclerview.RecycledPoolHolder
import quickbeer.android.ui.recyclerview.RecycledPoolHolder.PoolType
import quickbeer.android.util.ktx.observe
import quickbeer.android.util.ktx.viewBinding
@AndroidEntryPoint
class RecentBeersFragment : BaseFragment(R.layout.list_fragment), Resetable {
private val binding by viewBinding(ListContentBinding::bind)
private val viewModel by viewModels<RecentBeersViewModel>()
private val beersAdapter = ListAdapter<BeerListModel>(BeerListTypeFactory())
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.message.text = getString(R.string.message_start)
binding.recyclerView.apply {
adapter = beersAdapter
layoutManager = LinearLayoutManager(context)
setHasFixedSize(true)
addItemDecoration(DividerDecoration(context))
setClickListener(::onBeerSelected)
setRecycledViewPool(
(activity as RecycledPoolHolder)
.getPool(PoolType.BEER_LIST, beersAdapter::createPool)
)
}
}
override fun onDestroyView() {
binding.recyclerView.adapter = null
super.onDestroyView()
}
override fun observeViewState() {
observe(viewModel.recentBeersState) { state ->
when (state) {
is State.Initial -> Unit
is State.Loading -> {
beersAdapter.setItems(emptyList())
binding.message.isVisible = false
binding.progress.show()
}
is State.Empty -> {
beersAdapter.setItems(emptyList())
binding.message.text = getString(R.string.message_empty)
binding.message.isVisible = true
binding.progress.hide()
}
is State.Success -> {
beersAdapter.setItems(state.value)
binding.message.isVisible = false
binding.progress.hide()
}
is State.Error -> {
beersAdapter.setItems(emptyList())
binding.message.text = getString(R.string.message_error)
binding.message.isVisible = true
binding.progress.hide()
}
}
}
}
private fun onBeerSelected(beer: BeerListModel) {
navigate(Destination.Beer(beer.id))
}
override fun onReset() {
binding.recyclerView.smoothScrollToPosition(0)
}
}
| gpl-3.0 | d4d959b425bda566a2fef923da963a05 | 35.925532 | 80 | 0.66004 | 5.045058 | false | false | false | false |
JetBrains/intellij-community | plugins/devkit/intellij.devkit.themes/src/actions/NewThemeAction.kt | 1 | 6154 | // 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.idea.devkit.themes.actions
import com.intellij.ide.fileTemplates.FileTemplateManager
import com.intellij.ide.fileTemplates.FileTemplateUtil
import com.intellij.ide.ui.UIThemeProvider
import com.intellij.openapi.actionSystem.*
import com.intellij.openapi.command.WriteCommandAction
import com.intellij.openapi.fileEditor.FileEditorManager
import com.intellij.openapi.module.Module
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.ModuleRootManager
import com.intellij.openapi.ui.DialogWrapper
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.vfs.VfsUtil
import com.intellij.psi.PsiDirectory
import com.intellij.psi.PsiFile
import com.intellij.ui.components.JBCheckBox
import com.intellij.ui.components.JBTextField
import com.intellij.ui.components.dialog
import com.intellij.ui.dsl.builder.Cell
import com.intellij.ui.dsl.builder.columns
import com.intellij.ui.dsl.builder.panel
import com.intellij.ui.layout.*
import org.jetbrains.idea.devkit.actions.DevkitActionsUtil
import org.jetbrains.idea.devkit.inspections.quickfix.PluginDescriptorChooser
import org.jetbrains.idea.devkit.module.PluginModuleType
import org.jetbrains.idea.devkit.themes.DevKitThemesBundle
import org.jetbrains.idea.devkit.util.DescriptorUtil
import org.jetbrains.idea.devkit.util.PsiUtil
import java.util.*
//TODO better undo support
class NewThemeAction : AnAction() {
private val THEME_JSON_TEMPLATE = "ThemeJson.json"
private val THEME_PROVIDER_EP_NAME = UIThemeProvider.EP_NAME.name
override fun getActionUpdateThread() = ActionUpdateThread.BGT
override fun actionPerformed(e: AnActionEvent) {
val view = e.getData(LangDataKeys.IDE_VIEW) ?: return
val dir = view.getOrChooseDirectory() ?: return
val module = e.getRequiredData(PlatformCoreDataKeys.MODULE)
val project = module.project
lateinit var name: Cell<JBTextField>
lateinit var isDark: Cell<JBCheckBox>
val panel = panel {
row(DevKitThemesBundle.message("new.theme.dialog.name.text.field.text")) {
name = textField()
.focused()
.columns(30)
.addValidationRule(DevKitThemesBundle.message("new.theme.dialog.name.empty")) { name.component.text.isBlank() }
}
row("") {
isDark = checkBox(DevKitThemesBundle.message("new.theme.dialog.is.dark.checkbox.text")).applyToComponent { isSelected = true }
}
}
val dialog = dialog(DevKitThemesBundle.message("new.theme.dialog.title"), project = project, panel = panel)
dialog.show()
if (dialog.exitCode == DialogWrapper.OK_EXIT_CODE) {
val file = createThemeJson(name.component.text, isDark.component.isSelected, project, dir, module)
view.selectElement(file)
FileEditorManager.getInstance(project).openFile(file.virtualFile, true)
registerTheme(dir, file, module)
}
}
override fun update(e: AnActionEvent) {
val module = e.getData(PlatformCoreDataKeys.MODULE)
e.presentation.isEnabled = module != null && (PluginModuleType.get(module) is PluginModuleType || PsiUtil.isPluginModule(module))
}
private fun createThemeJson(themeName: String,
isDark: Boolean,
project: Project,
dir: PsiDirectory,
module: Module): PsiFile {
val fileName = getThemeJsonFileName(themeName)
val colorSchemeFilename = getThemeColorSchemeFileName(themeName)
val template = FileTemplateManager.getInstance(project).getJ2eeTemplate(THEME_JSON_TEMPLATE)
val editorSchemeProps = Properties()
editorSchemeProps.setProperty("NAME", themeName)
editorSchemeProps.setProperty("PARENT_SCHEME", if (isDark) "Darcula" else "Default")
val editorSchemeTemplate = FileTemplateManager.getInstance(project).getJ2eeTemplate("ThemeEditorColorScheme.xml")
val colorScheme = FileTemplateUtil.createFromTemplate(editorSchemeTemplate, colorSchemeFilename, editorSchemeProps, dir)
val props = Properties()
props.setProperty("NAME", themeName)
props.setProperty("IS_DARK", isDark.toString())
props.setProperty("COLOR_SCHEME_NAME", getSourceRootRelativeLocation(module, colorScheme as PsiFile))
val created = FileTemplateUtil.createFromTemplate(template, fileName, props, dir)
assert(created is PsiFile)
return created as PsiFile
}
private fun getThemeJsonFileName(themeName: String): String {
return FileUtil.sanitizeFileName(themeName) + ".theme.json"
}
private fun getThemeColorSchemeFileName(themeName: String): String {
return FileUtil.sanitizeFileName(themeName) + ".xml"
}
private fun registerTheme(dir: PsiDirectory, file: PsiFile, module: Module) {
val relativeLocation = getSourceRootRelativeLocation(module, file)
val pluginXml = DevkitActionsUtil.choosePluginModuleDescriptor(dir) ?: return
DescriptorUtil.checkPluginXmlsWritable(module.project, pluginXml)
val domFileElement = DescriptorUtil.getIdeaPluginFileElement(pluginXml)
WriteCommandAction.writeCommandAction(module.project, pluginXml).run<Throwable> {
val extensions = PluginDescriptorChooser.findOrCreateExtensionsForEP(domFileElement, THEME_PROVIDER_EP_NAME)
val extensionTag = extensions.addExtension(THEME_PROVIDER_EP_NAME).xmlTag
extensionTag.setAttribute("id", getRandomId())
extensionTag.setAttribute("path", relativeLocation)
}
}
private fun getSourceRootRelativeLocation(module: Module, file: PsiFile): String {
val rootManager = ModuleRootManager.getInstance(module)
val sourceRoots = rootManager.getSourceRoots(false)
val virtualFile = file.virtualFile
var relativeLocation : String? = null
for (sourceRoot in sourceRoots) {
if (!VfsUtil.isAncestor(sourceRoot,virtualFile,true)) continue
relativeLocation = VfsUtil.getRelativeLocation(virtualFile, sourceRoot) ?: continue
break
}
return "/${relativeLocation}"
}
private fun getRandomId() = UUID.randomUUID().toString()
} | apache-2.0 | 8d2ee6ce4b5f39acad5eaf6a2c555988 | 43.927007 | 134 | 0.756906 | 4.561898 | false | false | false | false |
StepicOrg/stepik-android | app/src/main/java/org/stepik/android/presentation/video_player/VideoPlayerPresenter.kt | 2 | 8133 | package org.stepik.android.presentation.video_player
import android.os.Bundle
import com.google.android.exoplayer2.Player
import io.reactivex.Scheduler
import io.reactivex.rxkotlin.plusAssign
import io.reactivex.rxkotlin.subscribeBy
import org.stepic.droid.analytic.AmplitudeAnalytic
import org.stepic.droid.analytic.Analytic
import org.stepic.droid.di.qualifiers.BackgroundScheduler
import org.stepic.droid.di.qualifiers.MainScheduler
import org.stepic.droid.preferences.VideoPlaybackRate
import org.stepik.android.domain.video_player.analytic.VideoQualityChangedEvent
import ru.nobird.android.domain.rx.emptyOnErrorStub
import org.stepik.android.domain.video_player.interactor.VideoPlayerSettingsInteractor
import org.stepik.android.model.VideoUrl
import org.stepik.android.presentation.base.PresenterBase
import org.stepik.android.view.video_player.model.VideoPlayerData
import org.stepik.android.view.video_player.model.VideoPlayerMediaData
import javax.inject.Inject
class VideoPlayerPresenter
@Inject
constructor(
private val analytic: Analytic,
private val videoPlayerSettingsInteractor: VideoPlayerSettingsInteractor,
@BackgroundScheduler
private val backgroundScheduler: Scheduler,
@MainScheduler
private val mainScheduler: Scheduler
) : PresenterBase<VideoPlayerView>() {
companion object {
private const val VIDEO_PLAYER_DATA = "video_player_data"
private const val FULLSCREEN_DATA = "fullscreen_data"
private const val TIMESTAMP_EPS = 1000L
}
private var state: VideoPlayerView.State = VideoPlayerView.State.Idle
set(value) {
field = value
view?.setState(value)
}
private var videoPlayerData: VideoPlayerData? = null
set(value) {
field = value
if (value != null) {
view?.setVideoPlayerData(value)
}
}
private var isLandscapeVideo: Boolean = false
set(value) {
field = value
view?.setIsLandscapeVideo(value)
}
private var isLoading = false
override fun attachView(view: VideoPlayerView) {
super.attachView(view)
videoPlayerData?.let(view::setVideoPlayerData)
view.setIsLandscapeVideo(isLandscapeVideo)
view.setState(state)
}
/**
* Data initialization variants
*/
override fun onRestoreInstanceState(savedInstanceState: Bundle) {
if (videoPlayerData == null) {
videoPlayerData = savedInstanceState.getParcelable(VIDEO_PLAYER_DATA)
}
isLandscapeVideo = savedInstanceState.getBoolean(FULLSCREEN_DATA)
}
fun onMediaData(mediaData: VideoPlayerMediaData, isFromNewIntent: Boolean = false) {
if (videoPlayerData?.mediaData?.externalVideo?.id == mediaData.externalVideo?.id) return
if ((videoPlayerData != null || isLoading) && !isFromNewIntent) return
compositeDisposable += videoPlayerSettingsInteractor
.getVideoPlayerData(mediaData)
.subscribeOn(backgroundScheduler)
.observeOn(mainScheduler)
.doOnSubscribe {
view?.invalidatePlayer()
isLoading = true
}
.doFinally {
isLoading = false
}
.subscribeBy(
onSuccess = { videoPlayerData = it; resolveVideoInBackgroundPopup() },
onError = emptyOnErrorStub
)
}
private fun resolveVideoInBackgroundPopup() {
compositeDisposable += videoPlayerSettingsInteractor
.isFirstVideoPlayback()
.subscribeOn(backgroundScheduler)
.observeOn(mainScheduler)
.subscribeBy(
onSuccess = { isFirstTime ->
if (isFirstTime) {
view?.showPlayInBackgroundPopup()
}
},
onError = emptyOnErrorStub
)
}
/**
* Video properties
*/
fun changeQuality(videoUrl: VideoUrl?) {
val playerData = videoPlayerData
?: return
val url = videoUrl
?.url
?: return
val quality = videoUrl
.quality
?: return
analytic.report(VideoQualityChangedEvent(playerData.videoQuality, quality))
videoPlayerData = playerData.copy(videoUrl = url, videoQuality = quality)
}
fun changePlaybackRate(videoPlaybackRate: VideoPlaybackRate) {
val playerData = this.videoPlayerData
?: return
analytic.reportAmplitudeEvent(
AmplitudeAnalytic.Video.PLAYBACK_SPEED_CHANGED,
mapOf(
AmplitudeAnalytic.Video.Params.SOURCE to playerData.videoPlaybackRate.rateFloat,
AmplitudeAnalytic.Video.Params.TARGET to videoPlaybackRate.rateFloat
)
)
videoPlayerData = playerData.copy(videoPlaybackRate = videoPlaybackRate)
compositeDisposable += videoPlayerSettingsInteractor
.setPlaybackRate(videoPlaybackRate)
.subscribeOn(backgroundScheduler)
.subscribe()
}
fun changeVideoRotation(isRotateVideo: Boolean) {
this.isLandscapeVideo = isRotateVideo
}
fun syncVideoTimestamp(currentPosition: Long, duration: Long) {
val playerData = videoPlayerData
?: return
val timestamp =
if (duration > 0 && currentPosition + TIMESTAMP_EPS >= duration) {
0L
} else {
currentPosition
}
compositeDisposable += videoPlayerSettingsInteractor
.saveVideoTimestamp(playerData.videoId, timestamp)
.subscribeOn(backgroundScheduler)
.subscribeBy(onError = emptyOnErrorStub)
}
/**
* Video player states
*
* [isAutoplayAllowed] - allowed for video
*/
fun onPlayerStateChanged(playbackState: Int, isAutoplayAllowed: Boolean) {
val isAutoplayEnabled = videoPlayerSettingsInteractor.isAutoplayEnabled()
state =
when (val state = state) {
VideoPlayerView.State.Idle ->
if (playbackState == Player.STATE_ENDED && isAutoplayAllowed) {
if (isAutoplayEnabled) {
VideoPlayerView.State.AutoplayPending(0)
} else {
VideoPlayerView.State.AutoplayCancelled
}
} else {
VideoPlayerView.State.Idle
}
else ->
if (playbackState != Player.STATE_ENDED) {
VideoPlayerView.State.Idle
} else {
state
}
}
}
fun onAutoplayProgressChanged(progress: Int) {
state =
if (state is VideoPlayerView.State.AutoplayPending) {
VideoPlayerView.State.AutoplayPending(progress)
} else {
state
}
}
fun onAutoplayNext() {
state =
if (state is VideoPlayerView.State.AutoplayPending || state == VideoPlayerView.State.AutoplayCancelled) {
VideoPlayerView.State.AutoplayNext
} else {
state
}
}
fun stayOnThisStep() {
state = VideoPlayerView.State.Idle
}
fun setAutoplayEnabled(isEnabled: Boolean) {
videoPlayerSettingsInteractor.setAutoplayEnabled(isEnabled)
state =
when (state) {
is VideoPlayerView.State.AutoplayPending ->
VideoPlayerView.State.AutoplayCancelled
is VideoPlayerView.State.AutoplayCancelled ->
VideoPlayerView.State.AutoplayPending(0)
else ->
state
}
}
override fun onSaveInstanceState(outState: Bundle) {
outState.putParcelable(VIDEO_PLAYER_DATA, videoPlayerData)
outState.putBoolean(FULLSCREEN_DATA, isLandscapeVideo)
}
} | apache-2.0 | ff835b7948c20860317e9a07c08b71dd | 32.336066 | 117 | 0.616009 | 5.425617 | false | false | false | false |
allotria/intellij-community | platform/platform-impl/src/com/intellij/openapi/wm/impl/SquareStripeButton.kt | 2 | 5838 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.wm.impl
import com.intellij.icons.AllIcons
import com.intellij.ide.HelpTooltip
import com.intellij.ide.actions.ActivateToolWindowAction
import com.intellij.openapi.actionSystem.*
import com.intellij.openapi.actionSystem.impl.ActionButton
import com.intellij.openapi.project.DumbAware
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.ScalableIcon
import com.intellij.openapi.wm.ToolWindow
import com.intellij.openapi.wm.ToolWindowAnchor
import com.intellij.openapi.wm.WindowManager
import com.intellij.openapi.wm.ex.ToolWindowManagerListener
import com.intellij.ui.PopupHandler
import com.intellij.ui.ToggleActionButton
import com.intellij.ui.UIBundle
import java.awt.Component
import java.awt.Dimension
import java.util.function.Supplier
class SquareStripeButton(val project: Project, val button: StripeButton) :
ActionButton(SquareAnActionButton(project, button), createPresentation(button), ActionPlaces.TOOLWINDOW_TOOLBAR_BAR, Dimension(40, 40)) {
init {
addMouseListener(object : PopupHandler() {
override fun invokePopup(component: Component, x: Int, y: Int) {
showPopup(component, x, y)
}
})
}
override fun updateToolTipText() {
HelpTooltip().
setTitle(button.toolWindow.stripeTitle).
setLocation(getAlignment(button.toolWindow.largeStripeAnchor)).
setShortcut(ActionManager.getInstance().getKeyboardShortcut(ActivateToolWindowAction.getActionIdForToolWindow(button.id))).
setInitialDelay(0).setHideDelay(0).
installOn(this)
}
private fun showPopup(component: Component?, x: Int, y: Int) {
val popupMenu = ActionManager.getInstance().createActionPopupMenu(ActionPlaces.TOOLWINDOW_POPUP,
createPopupGroup(project, button.pane, button.toolWindow))
popupMenu.component.show(component, x, y)
}
companion object {
private fun createPresentation(button: StripeButton) =
Presentation(button.text).apply {
icon = button.icon ?: AllIcons.Toolbar.Unknown
scaleIcon()
isEnabledAndVisible = true
}
private fun Presentation.scaleIcon() {
if (icon is ScalableIcon) icon = (icon as ScalableIcon).scale(1.4f)
}
private fun createPopupGroup(project: Project, toolWindowsPane: ToolWindowsPane, toolWindow: ToolWindow) = DefaultActionGroup()
.apply {
add(HideAction(toolWindowsPane, toolWindow))
addSeparator()
add(createMoveGroup(project, toolWindowsPane, toolWindow))
}
@JvmStatic
fun createMoveGroup(project: Project, _toolWindowsPane: ToolWindowsPane? = null, toolWindow: ToolWindow): DefaultActionGroup {
var toolWindowsPane = _toolWindowsPane
if (toolWindowsPane == null) {
toolWindowsPane = (WindowManager.getInstance() as? WindowManagerImpl)?.getProjectFrameRootPane(project)?.toolWindowPane
if (toolWindowsPane == null) return DefaultActionGroup()
}
return DefaultActionGroup.createPopupGroup(Supplier { UIBundle.message("tool.window.new.stripe.move.to.action.group.name") })
.apply {
add(MoveToAction(toolWindowsPane, toolWindow, ToolWindowAnchor.LEFT))
add(MoveToAction(toolWindowsPane, toolWindow, ToolWindowAnchor.RIGHT))
add(MoveToAction(toolWindowsPane, toolWindow, ToolWindowAnchor.BOTTOM))
}
}
private fun getAlignment(anchor: ToolWindowAnchor) =
when (anchor) {
ToolWindowAnchor.RIGHT -> HelpTooltip.Alignment.LEFT
ToolWindowAnchor.TOP -> HelpTooltip.Alignment.LEFT
ToolWindowAnchor.LEFT -> HelpTooltip.Alignment.RIGHT
ToolWindowAnchor.BOTTOM -> HelpTooltip.Alignment.RIGHT
else -> HelpTooltip.Alignment.RIGHT
}
}
private class MoveToAction(val toolWindowsPane: ToolWindowsPane, val toolWindow: ToolWindow, val anchor: ToolWindowAnchor) :
AnAction(anchor.capitalizedDisplayName), DumbAware {
override fun actionPerformed(e: AnActionEvent) {
toolWindowsPane.onStripeButtonRemoved(e.project!!, toolWindow)
toolWindow.isVisibleOnLargeStripe = true
toolWindow.largeStripeAnchor = anchor
}
override fun update(e: AnActionEvent) {
e.presentation.isEnabledAndVisible = toolWindow.largeStripeAnchor != anchor
}
}
private class HideAction(val toolWindowsPane: ToolWindowsPane, val toolWindow: ToolWindow) :
AnAction(UIBundle.message("tool.window.new.stripe.hide.action.name")), DumbAware {
override fun actionPerformed(e: AnActionEvent) {
toolWindowsPane.onStripeButtonRemoved(e.project!!, toolWindow)
toolWindow.isVisibleOnLargeStripe = false
(toolWindow as? ToolWindowImpl)?.toolWindowManager?.hideToolWindow(toolWindow.id, false, true, ToolWindowEventSource.SquareStripeButton)
}
}
private class SquareAnActionButton(val project: Project, val button: StripeButton) : ToggleActionButton(button.text, null), DumbAware {
override fun isSelected(e: AnActionEvent): Boolean {
e.presentation.icon = button.toolWindow.icon ?: AllIcons.Toolbar.Unknown
e.presentation.scaleIcon()
return button.toolWindow.isVisible
}
override fun setSelected(e: AnActionEvent, state: Boolean) {
if (e.project!!.isDisposed) return
val manager = button.toolWindow.toolWindowManager
if (!state) {
manager.hideToolWindow(button.id, false, true, ToolWindowEventSource.SquareStripeButton)
}
else {
manager.activated(button.toolWindow, ToolWindowEventSource.SquareStripeButton)
}
project.messageBus.syncPublisher(ToolWindowManagerListener.TOPIC).stateChanged(manager)
}
}
} | apache-2.0 | 343a12aef6fd399ff5312f1579fd2627 | 41.933824 | 142 | 0.737924 | 4.785246 | false | false | false | false |
leafclick/intellij-community | platform/vcs-log/impl/src/com/intellij/vcs/log/history/FileHistoryFilterer.kt | 1 | 12751 | // 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.vcs.log.history
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.util.UnorderedPair
import com.intellij.openapi.vcs.AbstractVcs
import com.intellij.openapi.vcs.FilePath
import com.intellij.openapi.vcs.ProjectLevelVcsManager
import com.intellij.openapi.vcs.VcsException
import com.intellij.openapi.vcs.history.VcsCachingHistory
import com.intellij.openapi.vcs.history.VcsFileRevision
import com.intellij.openapi.vcs.history.VcsFileRevisionEx
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.containers.MultiMap
import com.intellij.vcs.log.CommitId
import com.intellij.vcs.log.Hash
import com.intellij.vcs.log.VcsLogFilterCollection
import com.intellij.vcs.log.VcsLogStructureFilter
import com.intellij.vcs.log.data.CompressedRefs
import com.intellij.vcs.log.data.DataPack
import com.intellij.vcs.log.data.VcsLogData
import com.intellij.vcs.log.graph.GraphCommit
import com.intellij.vcs.log.graph.GraphCommitImpl
import com.intellij.vcs.log.graph.PermanentGraph
import com.intellij.vcs.log.graph.impl.facade.PermanentGraphImpl
import com.intellij.vcs.log.history.FileHistoryPaths.fileHistory
import com.intellij.vcs.log.impl.HashImpl
import com.intellij.vcs.log.util.StopWatch
import com.intellij.vcs.log.util.VcsLogUtil
import com.intellij.vcs.log.util.findBranch
import com.intellij.vcs.log.visible.*
import com.intellij.vcs.log.visible.filters.VcsLogFilterObject
internal class FileHistoryFilterer(logData: VcsLogData) : VcsLogFilterer {
private val project = logData.project
private val logProviders = logData.logProviders
private val storage = logData.storage
private val index = logData.index
private val indexDataGetter = index.dataGetter!!
private val vcsLogFilterer = VcsLogFiltererImpl(logProviders, storage, logData.topCommitsCache,
logData.commitDetailsGetter, index)
override fun filter(dataPack: DataPack,
oldVisiblePack: VisiblePack,
sortType: PermanentGraph.SortType,
filters: VcsLogFilterCollection,
commitCount: CommitCountStage): Pair<VisiblePack, CommitCountStage> {
val filePath = getFilePath(filters) ?: return vcsLogFilterer.filter(dataPack, oldVisiblePack, sortType, filters, commitCount)
LOG.assertTrue(!filePath.isDirectory)
val root = VcsLogUtil.getActualRoot(project, filePath)!!
return MyWorker(root, filePath, getHash(filters)).filter(dataPack, oldVisiblePack, sortType, filters, commitCount)
}
override fun canFilterEmptyPack(filters: VcsLogFilterCollection): Boolean = true
private inner class MyWorker constructor(private val root: VirtualFile,
private val filePath: FilePath,
private val hash: Hash?) {
fun filter(dataPack: DataPack,
oldVisiblePack: VisiblePack,
sortType: PermanentGraph.SortType,
filters: VcsLogFilterCollection,
commitCount: CommitCountStage): Pair<VisiblePack, CommitCountStage> {
val start = System.currentTimeMillis()
if (index.isIndexed(root) && dataPack.isFull) {
val visiblePack = filterWithIndex(dataPack, oldVisiblePack, sortType, filters,
commitCount == CommitCountStage.INITIAL)
LOG.debug(StopWatch.formatTime(System.currentTimeMillis() - start) + " for computing history for $filePath with index")
if (checkNotEmpty(dataPack, visiblePack, true)) {
return Pair(visiblePack, commitCount)
}
}
ProjectLevelVcsManager.getInstance(project).getVcsFor(root)?.let { vcs ->
if (vcs.vcsHistoryProvider != null) {
return@filter try {
val visiblePack = filterWithProvider(vcs, dataPack, sortType, filters)
LOG.debug(StopWatch.formatTime(System.currentTimeMillis() - start) +
" for computing history for $filePath with history provider")
checkNotEmpty(dataPack, visiblePack, false)
Pair(visiblePack, commitCount)
}
catch (e: VcsException) {
LOG.error(e)
vcsLogFilterer.filter(dataPack, oldVisiblePack, sortType, filters, commitCount)
}
}
}
LOG.warn("Could not find vcs or history provider for file $filePath")
return vcsLogFilterer.filter(dataPack, oldVisiblePack, sortType, filters, commitCount)
}
private fun checkNotEmpty(dataPack: DataPack, visiblePack: VisiblePack, withIndex: Boolean): Boolean {
if (!dataPack.isFull) {
LOG.debug("Data pack is not full while computing file history for $filePath\n" +
"Found ${visiblePack.visibleGraph.visibleCommitCount} commits")
return true
}
else if (visiblePack.visibleGraph.visibleCommitCount == 0) {
LOG.warn("Empty file history from ${if (withIndex) "index" else "provider"} for $filePath")
return false
}
return true
}
@Throws(VcsException::class)
private fun filterWithProvider(vcs: AbstractVcs,
dataPack: DataPack,
sortType: PermanentGraph.SortType,
filters: VcsLogFilterCollection): VisiblePack {
val revisionNumber = if (hash != null) VcsLogUtil.convertToRevisionNumber(hash) else null
val revisions = VcsCachingHistory.collect(vcs, filePath, revisionNumber)
if (revisions.isEmpty()) return VisiblePack.EMPTY
if (dataPack.isFull) {
val pathsMap = HashMap<Int, MaybeDeletedFilePath>()
for (revision in revisions) {
val revisionEx = revision as VcsFileRevisionEx
pathsMap[getIndex(revision)] = MaybeDeletedFilePath(revisionEx.path, revisionEx.isDeleted)
}
val visibleGraph = vcsLogFilterer.createVisibleGraph(dataPack, sortType, null, pathsMap.keys)
return VisiblePack(dataPack, visibleGraph, false, filters, FileHistory(pathsMap))
}
val commits = ArrayList<GraphCommit<Int>>(revisions.size)
val pathsMap = HashMap<Int, MaybeDeletedFilePath>()
for (revision in revisions) {
val index = getIndex(revision)
val revisionEx = revision as VcsFileRevisionEx
pathsMap[index] = MaybeDeletedFilePath(revisionEx.path, revisionEx.isDeleted)
commits.add(GraphCommitImpl.createCommit(index, emptyList(), revision.getRevisionDate().time))
}
val refs = getFilteredRefs(dataPack)
val fakeDataPack = DataPack.build(commits, refs, mapOf(root to logProviders[root]), storage, false)
val visibleGraph = vcsLogFilterer.createVisibleGraph(fakeDataPack, sortType, null,
null/*no need to filter here, since we do not have any extra commits in this pack*/)
return VisiblePack(fakeDataPack, visibleGraph, false, filters, FileHistory(pathsMap))
}
private fun getFilteredRefs(dataPack: DataPack): Map<VirtualFile, CompressedRefs> {
val compressedRefs = dataPack.refsModel.allRefsByRoot[root] ?: CompressedRefs(emptySet(), storage)
return mapOf(Pair(root, compressedRefs))
}
private fun getIndex(revision: VcsFileRevision): Int {
return storage.getCommitIndex(HashImpl.build(revision.revisionNumber.asString()), root)
}
private fun filterWithIndex(dataPack: DataPack,
oldVisiblePack: VisiblePack,
sortType: PermanentGraph.SortType,
filters: VcsLogFilterCollection,
isInitial: Boolean): VisiblePack {
val oldFileHistory = oldVisiblePack.fileHistory
if (isInitial) {
return filterWithIndex(dataPack, filters, sortType, oldFileHistory.commitToRename,
FileHistory(emptyMap(), processedAdditionsDeletions = oldFileHistory.processedAdditionsDeletions))
}
val renames = collectRenamesFromProvider(oldFileHistory)
return filterWithIndex(dataPack, filters, sortType, renames.union(oldFileHistory.commitToRename), oldFileHistory)
}
private fun filterWithIndex(dataPack: DataPack,
filters: VcsLogFilterCollection,
sortType: PermanentGraph.SortType,
oldRenames: MultiMap<UnorderedPair<Int>, Rename>,
oldFileHistory: FileHistory): VisiblePack {
val matchingHeads = vcsLogFilterer.getMatchingHeads(dataPack.refsModel, setOf(root), filters)
val data = indexDataGetter.createFileHistoryData(filePath).build(oldRenames)
val permanentGraph = dataPack.permanentGraph
if (permanentGraph !is PermanentGraphImpl) {
val visibleGraph = vcsLogFilterer.createVisibleGraph(dataPack, sortType, matchingHeads, data.getCommits())
return VisiblePack(dataPack, visibleGraph, false, filters, FileHistory(data.buildPathsMap()))
}
if (matchingHeads.matchesNothing() || data.isEmpty) {
return VisiblePack.EMPTY
}
val commit = (hash ?: getHead(dataPack))?.let { storage.getCommitIndex(it, root) }
val historyBuilder = FileHistoryBuilder(commit, filePath, data, oldFileHistory)
val visibleGraph = permanentGraph.createVisibleGraph(sortType, matchingHeads, data.getCommits(), historyBuilder)
val fileHistory = historyBuilder.fileHistory
return VisiblePack(dataPack, visibleGraph, fileHistory.unmatchedAdditionsDeletions.isNotEmpty(), filters, fileHistory)
}
private fun collectRenamesFromProvider(fileHistory: FileHistory): MultiMap<UnorderedPair<Int>, Rename> {
if (fileHistory.unmatchedAdditionsDeletions.isEmpty()) return MultiMap.empty()
val start = System.currentTimeMillis()
val handler = logProviders[root]?.fileHistoryHandler ?: return MultiMap.empty()
val renames = fileHistory.unmatchedAdditionsDeletions.mapNotNull {
val parentHash = storage.getCommitId(it.parent)!!.hash
val childHash = storage.getCommitId(it.child)!!.hash
if (it.isAddition) handler.getRename(root, it.filePath, parentHash, childHash)
else handler.getRename(root, it.filePath, childHash, parentHash)
}.map { r ->
Rename(r.filePath1, r.filePath2, storage.getCommitIndex(r.hash1, root), storage.getCommitIndex(r.hash2, root))
}
LOG.debug("Found ${renames.size} renames for ${fileHistory.unmatchedAdditionsDeletions.size} addition-deletions in " +
StopWatch.formatTime(System.currentTimeMillis() - start))
val result = MultiMap.createSmart<UnorderedPair<Int>, Rename>()
renames.forEach { result.putValue(it.commits, it) }
return result
}
private fun getHead(pack: DataPack): Hash? {
return pack.refsModel.findBranch(VcsLogUtil.HEAD, root)?.commitHash
}
}
private fun getHash(filters: VcsLogFilterCollection): Hash? {
val fileHistoryFilter = getStructureFilter(filters) as? VcsLogFileHistoryFilter
if (fileHistoryFilter != null) {
return fileHistoryFilter.hash
}
val revisionFilter = filters.get(VcsLogFilterCollection.REVISION_FILTER)
return revisionFilter?.heads?.singleOrNull()?.hash
}
companion object {
private val LOG = Logger.getInstance(FileHistoryFilterer::class.java)
private fun getStructureFilter(filters: VcsLogFilterCollection) = filters.detailsFilters.singleOrNull() as? VcsLogStructureFilter
fun getFilePath(filters: VcsLogFilterCollection): FilePath? {
val filter = getStructureFilter(filters) ?: return null
return filter.files.singleOrNull()
}
@JvmStatic
fun createFilters(path: FilePath,
revision: Hash?,
root: VirtualFile,
showAllBranches: Boolean): VcsLogFilterCollection {
val fileFilter = VcsLogFileHistoryFilter(path, revision)
val revisionFilter = when {
showAllBranches -> null
revision != null -> VcsLogFilterObject.fromCommit(CommitId(revision, root))
else -> VcsLogFilterObject.fromBranch(VcsLogUtil.HEAD)
}
return VcsLogFilterObject.collection(fileFilter, revisionFilter)
}
}
}
private fun <K : Any?, V : Any?> MultiMap<K, V>.union(map: MultiMap<K, V>): MultiMap<K, V> {
if (isEmpty) return map
if (map.isEmpty) return this
return MultiMap.createSmart<K, V>().also {
it.putAllValues(this)
it.putAllValues(map)
}
}
| apache-2.0 | 0c54dd1a536fa98dc997e451c253e6f8 | 46.401487 | 143 | 0.69375 | 5.339615 | false | false | false | false |
leafclick/intellij-community | platform/configuration-store-impl/src/schemeManager/SchemeFileTracker.kt | 1 | 5932 | // 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.configurationStore.schemeManager
import com.intellij.configurationStore.LOG
import com.intellij.configurationStore.StoreReloadManager
import com.intellij.configurationStore.StoreReloadManagerImpl
import com.intellij.openapi.diagnostic.debug
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.text.StringUtil
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.vfs.newvfs.BulkFileListener
import com.intellij.openapi.vfs.newvfs.events.VFileContentChangeEvent
import com.intellij.openapi.vfs.newvfs.events.VFileCreateEvent
import com.intellij.openapi.vfs.newvfs.events.VFileDeleteEvent
import com.intellij.openapi.vfs.newvfs.events.VFileEvent
import com.intellij.util.SmartList
import com.intellij.util.io.systemIndependentPath
internal class SchemeFileTracker(private val schemeManager: SchemeManagerImpl<Any, Any>, private val project: Project) : BulkFileListener {
private val applicator = SchemeChangeApplicator(schemeManager)
override fun after(events: MutableList<out VFileEvent>) {
val list = SmartList<SchemeChangeEvent>()
for (event in events) {
if (event.requestor is SchemeManagerImpl<*, *>) {
continue
}
when (event) {
is VFileContentChangeEvent -> {
val file = event.file
if (isMyFileWithoutParentCheck(file) && isMyDirectory(file.parent)) {
LOG.debug { "CHANGED ${file.path}" }
list.add(UpdateScheme(file))
}
}
is VFileCreateEvent -> {
if (event.isDirectory) {
handleDirectoryCreated(event, list)
}
else if (schemeManager.canRead(event.childName) && isMyDirectory(event.parent)) {
val virtualFile = event.file
LOG.debug { "CREATED ${event.path} (virtualFile: ${if (virtualFile == null) "not " else ""}found)" }
virtualFile?.let {
list.add(AddScheme(it))
}
}
}
is VFileDeleteEvent -> {
val file = event.file
if (file.isDirectory) {
handleDirectoryDeleted(file, list)
}
else if (isMyFileWithoutParentCheck(file) && isMyDirectory(file.parent)) {
LOG.debug { "DELETED ${file.path}" }
list.add(RemoveScheme(file.name))
}
}
}
}
if (list.isNotEmpty()) {
(StoreReloadManager.getInstance() as StoreReloadManagerImpl).registerChangedSchemes(list, applicator, project)
}
}
private fun isMyFileWithoutParentCheck(file: VirtualFile) = schemeManager.canRead(file.nameSequence)
@Suppress("MoveVariableDeclarationIntoWhen")
private fun isMyDirectory(parent: VirtualFile): Boolean {
val virtualDirectory = schemeManager.cachedVirtualDirectory
return when (virtualDirectory) {
null -> schemeManager.ioDirectory.systemIndependentPath == parent.path
else -> virtualDirectory == parent
}
}
private fun handleDirectoryDeleted(file: VirtualFile, list: SmartList<SchemeChangeEvent>) {
if (!StringUtil.equals(file.nameSequence, schemeManager.ioDirectory.fileName.toString())) {
return
}
LOG.debug { "DIR DELETED ${file.path}" }
if (file == schemeManager.virtualDirectory) {
list.add(RemoveAllSchemes())
}
}
private fun handleDirectoryCreated(event: VFileCreateEvent, list: MutableList<SchemeChangeEvent>) {
if (event.childName != schemeManager.ioDirectory.fileName.toString()) {
return
}
val dir = schemeManager.virtualDirectory
val virtualFile = event.file
if (virtualFile != dir) {
return
}
LOG.debug { "DIR CREATED ${virtualFile?.path}" }
for (file in dir!!.children) {
if (isMyFileWithoutParentCheck(file)) {
list.add(AddScheme(file))
}
}
}
}
internal data class UpdateScheme(override val file: VirtualFile) : SchemeChangeEvent, SchemeAddOrUpdateEvent {
override fun execute(schemaLoader: Lazy<SchemeLoader<Any, Any>>, schemeManager: SchemeManagerImpl<Any, Any>) {
}
}
private data class AddScheme(override val file: VirtualFile) : SchemeChangeEvent, SchemeAddOrUpdateEvent {
override fun execute(schemaLoader: Lazy<SchemeLoader<Any, Any>>, schemeManager: SchemeManagerImpl<Any, Any>) {
if (!file.isValid) {
return
}
val readScheme = readSchemeFromFile(file, schemaLoader.value, schemeManager) ?: return
val readSchemeKey = schemeManager.processor.getSchemeKey(readScheme)
val existingScheme = schemeManager.findSchemeByName(readSchemeKey) ?: return
if (schemeManager.schemeListManager.readOnlyExternalizableSchemes.get(
schemeManager.processor.getSchemeKey(existingScheme)) !== existingScheme) {
LOG.warn("Ignore incorrect VFS create scheme event: schema ${readSchemeKey} is already exists")
return
}
}
}
internal data class RemoveScheme(val fileName: String) : SchemeChangeEvent {
override fun execute(schemaLoader: Lazy<SchemeLoader<Any, Any>>, schemeManager: SchemeManagerImpl<Any, Any>) {
LOG.assertTrue(!schemaLoader.isInitialized())
// do not schedule scheme file removing because file was already removed
val scheme = schemeManager.removeFirstScheme(isScheduleToDelete = false) {
fileName == getSchemeFileName(schemeManager, it)
} ?: return
schemeManager.processor.onSchemeDeleted(scheme)
}
}
internal class RemoveAllSchemes : SchemeChangeEvent {
override fun execute(schemaLoader: Lazy<SchemeLoader<Any, Any>>, schemeManager: SchemeManagerImpl<Any, Any>) {
LOG.assertTrue(!schemaLoader.isInitialized())
schemeManager.cachedVirtualDirectory = null
// do not schedule scheme file removing because files were already removed
schemeManager.removeExternalizableSchemesFromRuntimeState()
}
} | apache-2.0 | 9590ec21d804241b564311f99583e03e | 37.777778 | 140 | 0.714599 | 4.693038 | false | false | false | false |
leafclick/intellij-community | platform/statistics/uploader/src/com/intellij/internal/statistic/eventLog/LogEvents.kt | 1 | 5172 | // 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.internal.statistic.eventLog
import com.intellij.internal.statistic.eventLog.StatisticsEventEscaper.escapeFieldName
import java.util.*
fun newLogEvent(session: String,
build: String,
bucket: String,
time: Long,
groupId: String,
groupVersion: String,
recorderVersion: String,
event: LogEventAction): LogEvent {
return LogEvent(session, build, bucket, time, groupId, groupVersion, recorderVersion, event)
}
fun newLogEvent(session: String,
build: String,
bucket: String,
time: Long,
groupId: String,
groupVersion: String,
recorderVersion: String,
eventId: String,
isState: Boolean = false): LogEvent {
val event = LogEventAction(StatisticsEventEscaper.escape(eventId), isState, 1)
return LogEvent(session, build, bucket, time, groupId, groupVersion, recorderVersion, event)
}
open class LogEvent(session: String,
build: String,
bucket: String,
eventTime: Long,
groupId: String,
groupVersion: String,
recorderVersion: String,
eventAction: LogEventAction) {
val recorderVersion: String = StatisticsEventEscaper.escape(recorderVersion)
val session: String = StatisticsEventEscaper.escape(session)
val build: String = StatisticsEventEscaper.escape(build)
val bucket: String = StatisticsEventEscaper.escape(bucket)
val time: Long = eventTime
val group: LogEventGroup = LogEventGroup(StatisticsEventEscaper.escape(groupId), StatisticsEventEscaper.escape(groupVersion))
val event: LogEventAction = eventAction
fun shouldMerge(next: LogEvent): Boolean {
if (session != next.session) return false
if (bucket != next.bucket) return false
if (build != next.build) return false
if (recorderVersion != next.recorderVersion) return false
if (group.id != next.group.id) return false
if (group.version != next.group.version) return false
if (!event.shouldMerge(next.event)) return false
return true
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as LogEvent
if (session != other.session) return false
if (bucket != other.bucket) return false
if (build != other.build) return false
if (time != other.time) return false
if (group != other.group) return false
if (recorderVersion != other.recorderVersion) return false
if (event != other.event) return false
return true
}
override fun hashCode(): Int {
var result = session.hashCode()
result = 31 * result + bucket.hashCode()
result = 31 * result + build.hashCode()
result = 31 * result + time.hashCode()
result = 31 * result + group.hashCode()
result = 31 * result + recorderVersion.hashCode()
result = 31 * result + event.hashCode()
return result
}
}
class LogEventGroup(val id: String, val version: String) {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as LogEventGroup
if (id != other.id) return false
if (version != other.version) return false
return true
}
override fun hashCode(): Int {
var result = id.hashCode()
result = 31 * result + version.hashCode()
return result
}
}
class LogEventAction(val id: String, var state: Boolean = false, var count: Int = 1) {
var data: MutableMap<String, Any> = Collections.emptyMap()
fun increment() {
count++
}
fun isEventGroup(): Boolean {
return count > 1
}
fun shouldMerge(next: LogEventAction): Boolean {
if (state || next.state) return false
if (id != next.id) return false
if (data != next.data) return false
return true
}
fun addData(key: String, value: Any) {
if (data.isEmpty()) {
data = HashMap()
}
val escapedValue = when (value) {
is String -> StatisticsEventEscaper.escape(value)
is List<*> -> value.map { if (it is String) StatisticsEventEscaper.escape(it) else it }
else -> value
}
data[escapeFieldName(key)] = escapedValue
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as LogEventAction
if (id != other.id) return false
if (count != other.count) return false
if (data != other.data) return false
return true
}
override fun hashCode(): Int {
var result = id.hashCode()
result = 31 * result + count
result = 31 * result + data.hashCode()
return result
}
}
@Deprecated("Use StatisticsEventEscaper#escape", ReplaceWith("StatisticsEventEscaper.escape(str)"))
fun escape(str: String): String {
return StatisticsEventEscaper.escape(str)
} | apache-2.0 | a6ab029f4998c71fa016adeb12df6822 | 30.351515 | 140 | 0.648685 | 4.435678 | false | false | false | false |
illuzor/Mighty-Preferences | mightypreferences/src/main/kotlin/com/illuzor/mightypreferences/converters.kt | 1 | 1513 | package com.illuzor.mightypreferences
internal fun <T> arrayToString(array: Array<T>, separator: String = ","): String {
if (array.isEmpty()) return ""
return array.joinToString(separator) { it.toString() }
}
internal inline fun <reified T> stringToArray(
string: String,
type: String,
separator: String = ","
): Array<T> {
if (string.isEmpty()) return emptyArray()
return string.split(separator).map { typeFromString(it, type) as T }.toTypedArray()
}
internal fun <K, V> mapToString(
map: Map<K, V>,
separator1: String = ":",
separator2: String = ","
): String {
if (map.isEmpty()) return ""
return map.asSequence().joinToString(separator2) { (key, value) ->
"$key$separator1$value"
}
}
internal inline fun <reified K, reified V> stringToMap(
string: String,
keyType: String,
valueType: String,
separator1: String = ":",
separator2: String = ","
): Map<K, V> {
if (string.isEmpty()) return mapOf()
return string.split(separator2).map {
val pair = it.split(separator1)
typeFromString(pair[0], keyType) as K to typeFromString(pair[1], valueType) as V
}.toMap()
}
private fun typeFromString(str: String, type: String): Any =
when (type) {
"Boolean" -> str.toBoolean()
"Byte" -> str.toByte()
"Short" -> str.toShort()
"Integer" -> str.toInt()
"Long" -> str.toLong()
"Float" -> str.toFloat()
"Double" -> str.toDouble()
else -> str
}
| mit | f5fb4401634a7067e210abe7328ca645 | 28.096154 | 88 | 0.608063 | 3.645783 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.