repo_name
stringlengths 7
81
| path
stringlengths 6
242
| copies
stringclasses 53
values | size
stringlengths 2
6
| content
stringlengths 73
737k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 5.44
99.8
| line_max
int64 15
977
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.93
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
CesarValiente/KUnidirectional | app/src/main/kotlin/com/cesarvaliente/kunidirectional/itemslist/ItemsControllerView.kt | 1 | 2482 | /**
* Copyright (C) 2017 Cesar Valiente & Corey Shaw
*
* https://github.com/CesarValiente
* https://github.com/coshaw
*
* 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.cesarvaliente.kunidirectional.itemslist
import com.cesarvaliente.kunidirectional.ControllerView
import com.cesarvaliente.kunidirectional.store.DeleteAction.DeleteItemAction
import com.cesarvaliente.kunidirectional.store.Item
import com.cesarvaliente.kunidirectional.store.Navigation
import com.cesarvaliente.kunidirectional.store.NavigationAction.EditItemScreenAction
import com.cesarvaliente.kunidirectional.store.ReadAction.FetchItemsAction
import com.cesarvaliente.kunidirectional.store.State
import com.cesarvaliente.kunidirectional.store.Store
import com.cesarvaliente.kunidirectional.store.ThreadExecutor
import com.cesarvaliente.kunidirectional.store.UpdateAction.ReorderItemsAction
import com.cesarvaliente.kunidirectional.store.UpdateAction.UpdateFavoriteAction
import java.lang.ref.WeakReference
class ItemsControllerView(
val itemsViewCallback: WeakReference<ItemsViewCallback>,
store: Store,
mainThread: ThreadExecutor? = null)
: ControllerView(store, mainThread) {
fun fetchItems() =
store.dispatch(FetchItemsAction())
fun toEditItemScreen(item: Item) =
store.dispatch(EditItemScreenAction(item))
fun reorderItems(items: List<Item>) =
store.dispatch(ReorderItemsAction(items))
fun changeFavoriteStatus(item: Item) =
store.dispatch(UpdateFavoriteAction(localId = item.localId, favorite = !item.favorite))
fun deleteItem(item: Item) =
store.dispatch(DeleteItemAction(item.localId))
override fun handleState(state: State) {
when (state.navigation) {
Navigation.ITEMS_LIST -> itemsViewCallback.get()?.updateItems(state.itemsListScreen.items)
Navigation.EDIT_ITEM -> itemsViewCallback.get()?.goToEditItem()
}
}
} | apache-2.0 | bbbc2dfad757a310b85ddaaa7ac988d3 | 39.048387 | 102 | 0.760274 | 4.537477 | false | false | false | false |
MGaetan89/ShowsRage | app/src/main/kotlin/com/mgaetan89/showsrage/fragment/ShowOverviewFragment.kt | 1 | 16247 | package com.mgaetan89.showsrage.fragment
import android.app.SearchManager
import android.content.ComponentName
import android.content.Intent
import android.content.res.ColorStateList
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Color
import android.graphics.drawable.Drawable
import android.net.Uri
import android.os.Bundle
import android.support.customtabs.CustomTabsClient
import android.support.customtabs.CustomTabsIntent
import android.support.customtabs.CustomTabsServiceConnection
import android.support.customtabs.CustomTabsSession
import android.support.v4.app.Fragment
import android.support.v4.app.FragmentActivity
import android.support.v4.content.ContextCompat
import android.support.v4.view.ViewCompat
import android.support.v4.widget.SwipeRefreshLayout
import android.support.v7.app.AlertDialog
import android.support.v7.graphics.Palette
import android.text.format.DateUtils
import android.view.LayoutInflater
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import com.mgaetan89.showsrage.Constants
import com.mgaetan89.showsrage.R
import com.mgaetan89.showsrage.activity.MainActivity
import com.mgaetan89.showsrage.extension.deleteShow
import com.mgaetan89.showsrage.extension.getShow
import com.mgaetan89.showsrage.extension.saveShow
import com.mgaetan89.showsrage.extension.toInt
import com.mgaetan89.showsrage.extension.toRelativeDate
import com.mgaetan89.showsrage.helper.GenericCallback
import com.mgaetan89.showsrage.helper.ImageLoader
import com.mgaetan89.showsrage.helper.Utils
import com.mgaetan89.showsrage.model.GenericResponse
import com.mgaetan89.showsrage.model.ImageType
import com.mgaetan89.showsrage.model.Indexer
import com.mgaetan89.showsrage.model.Show
import com.mgaetan89.showsrage.model.SingleShow
import com.mgaetan89.showsrage.network.SickRageApi
import io.realm.Realm
import io.realm.RealmChangeListener
import io.realm.RealmList
import kotlinx.android.synthetic.main.fragment_show_overview.show_airs
import kotlinx.android.synthetic.main.fragment_show_overview.show_banner
import kotlinx.android.synthetic.main.fragment_show_overview.show_fan_art
import kotlinx.android.synthetic.main.fragment_show_overview.show_genre
import kotlinx.android.synthetic.main.fragment_show_overview.show_imdb
import kotlinx.android.synthetic.main.fragment_show_overview.show_language_country
import kotlinx.android.synthetic.main.fragment_show_overview.show_location
import kotlinx.android.synthetic.main.fragment_show_overview.show_name
import kotlinx.android.synthetic.main.fragment_show_overview.show_network
import kotlinx.android.synthetic.main.fragment_show_overview.show_next_episode_date
import kotlinx.android.synthetic.main.fragment_show_overview.show_poster
import kotlinx.android.synthetic.main.fragment_show_overview.show_quality
import kotlinx.android.synthetic.main.fragment_show_overview.show_status
import kotlinx.android.synthetic.main.fragment_show_overview.show_subtitles
import kotlinx.android.synthetic.main.fragment_show_overview.show_the_tvdb
import kotlinx.android.synthetic.main.fragment_show_overview.show_web_search
import kotlinx.android.synthetic.main.fragment_show_overview.swipe_refresh
import retrofit.Callback
import retrofit.RetrofitError
import retrofit.client.Response
import java.lang.ref.WeakReference
class ShowOverviewFragment : Fragment(), Callback<SingleShow>, View.OnClickListener, ImageLoader.OnImageResult, SwipeRefreshLayout.OnRefreshListener, Palette.PaletteAsyncListener, RealmChangeListener<Show> {
private val indexerId by lazy { this.arguments!!.getInt(Constants.Bundle.INDEXER_ID) }
private var pauseMenu: MenuItem? = null
private lateinit var realm: Realm
private var resumeMenu: MenuItem? = null
private var serviceConnection: ServiceConnection? = null
private lateinit var show: Show
private var tabSession: CustomTabsSession? = null
init {
this.setHasOptionsMenu(true)
}
override fun failure(error: RetrofitError?) {
this.swipe_refresh?.isRefreshing = false
error?.printStackTrace()
}
fun getSetShowQualityCallback() = GenericCallback(this.activity)
override fun onChange(show: Show) {
if (!show.isLoaded || !show.isValid) {
return
}
if (this.serviceConnection == null) {
this.context?.let {
this.serviceConnection = ServiceConnection(this)
CustomTabsClient.bindCustomTabsService(it, "com.android.chrome", this.serviceConnection)
}
}
this.activity?.title = show.showName
val nextEpisodeAirDate = show.nextEpisodeAirDate
this.showHidePauseResumeMenus(show.paused == 0)
val airs = show.airs
this.show_airs?.text = this.getString(R.string.airs, if (airs.isNullOrEmpty()) "N/A" else airs)
this.show_airs?.visibility = View.VISIBLE
ImageLoader.load(this.show_banner, SickRageApi.instance.getImageUrl(ImageType.BANNER, show.tvDbId, Indexer.TVDB), false, null, this)
this.show_banner?.contentDescription = show.showName
ImageLoader.load(this.show_fan_art, SickRageApi.instance.getImageUrl(ImageType.FAN_ART, show.tvDbId, Indexer.TVDB), false, null, this)
this.show_fan_art?.contentDescription = show.showName
val genresList = show.genre
if (genresList?.isNotEmpty() == true) {
val genres = genresList.joinToString()
this.show_genre?.text = this.getString(R.string.genre, genres)
this.show_genre?.visibility = View.VISIBLE
} else {
this.show_genre?.visibility = View.GONE
}
this.show_imdb?.visibility = if (show.imdbId.isNullOrEmpty()) View.GONE else View.VISIBLE
this.show_language_country?.text = this.getString(R.string.language_value, show.language)
this.show_language_country?.visibility = View.VISIBLE
val location = show.location
this.show_location?.text = this.getString(R.string.location, if (location.isNullOrEmpty()) "N/A" else location)
this.show_location?.visibility = View.VISIBLE
this.show_name?.text = show.showName
this.show_name?.visibility = View.VISIBLE
if (nextEpisodeAirDate.isEmpty()) {
this.show_next_episode_date?.visibility = View.GONE
} else {
this.show_next_episode_date?.text = this.getString(R.string.next_episode, nextEpisodeAirDate.toRelativeDate("yyyy-MM-dd", DateUtils.DAY_IN_MILLIS))
this.show_next_episode_date?.visibility = View.VISIBLE
}
this.show_network?.text = this.getString(R.string.network, show.network)
this.show_network?.visibility = View.VISIBLE
ImageLoader.load(this.show_poster, SickRageApi.instance.getImageUrl(ImageType.POSTER, show.tvDbId, Indexer.TVDB), false, this, null)
this.show_poster?.contentDescription = show.showName
val quality = show.quality
if ("custom".equals(quality, true)) {
val qualityDetails = show.qualityDetails
val allowed = this.getTranslatedQualities(qualityDetails?.initial, true).joinToString()
val preferred = this.getTranslatedQualities(qualityDetails?.archive, false).joinToString()
this.show_quality?.text = this.getString(R.string.quality_custom, allowed, preferred)
} else {
this.show_quality?.text = this.getString(R.string.quality, quality)
}
this.show_quality?.visibility = View.VISIBLE
if (nextEpisodeAirDate.isEmpty()) {
val status = show.getStatusTranslationResource()
this.show_status?.text = if (status != 0) this.getString(status) else show.status
this.show_status?.visibility = View.VISIBLE
} else {
this.show_status?.visibility = View.GONE
}
this.show_subtitles?.text = this.getString(R.string.subtitles_value, this.getString(if (show.subtitles == 0) R.string.no else R.string.yes))
this.show_subtitles?.visibility = View.VISIBLE
}
override fun onClick(view: View?) {
if (view == null || !this.show.isValid) {
return
}
val activity = this.activity
var color = if (activity != null) ContextCompat.getColor(activity, R.color.primary) else Color.BLUE
color = (activity as? MainActivity)?.themeColors?.primary ?: color
val url = when (view.id) {
R.id.show_imdb -> "http://www.imdb.com/title/${this.show.imdbId}"
R.id.show_the_tvdb -> "http://thetvdb.com/?tab=series&id=${this.show.tvDbId}"
R.id.show_web_search -> {
val intent = Intent(Intent.ACTION_WEB_SEARCH)
intent.putExtra(SearchManager.QUERY, this.show.showName)
this.startActivity(intent)
return
}
else -> return
}
val tabIntent = CustomTabsIntent.Builder(this.tabSession)
.addDefaultShareMenuItem()
.enableUrlBarHiding()
.setCloseButtonIcon(BitmapFactory.decodeResource(this.resources, R.drawable.ic_arrow_back_white_24dp))
.setShowTitle(true)
.setToolbarColor(color)
.build()
tabIntent.launchUrl(this.activity, Uri.parse(url))
}
override fun onCreateOptionsMenu(menu: Menu?, inflater: MenuInflater?) {
inflater?.inflate(R.menu.show_overview, menu)
this.pauseMenu = menu?.findItem(R.id.menu_pause_show)
this.pauseMenu?.isVisible = false
this.resumeMenu = menu?.findItem(R.id.menu_resume_show)
this.resumeMenu?.isVisible = false
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View?
= inflater.inflate(R.layout.fragment_show_overview, container, false)
override fun onDestroy() {
val activity = this.activity
if (activity is MainActivity) {
activity.resetThemeColors()
}
if (this.serviceConnection != null) {
this.context?.unbindService(this.serviceConnection)
}
super.onDestroy()
}
override fun onGenerated(palette: Palette) {
val context = this.context ?: return
val activity = this.activity
val colors = Utils.getThemeColors(context, palette)
val colorPrimary = colors.primary
if (activity is MainActivity) {
activity.themeColors = colors
}
if (colorPrimary == 0) {
return
}
val colorStateList = ColorStateList.valueOf(colorPrimary)
val textColor = Utils.getContrastColor(colorPrimary)
this.show_imdb?.let {
ViewCompat.setBackgroundTintList(it, colorStateList)
it.setTextColor(textColor)
}
this.show_the_tvdb?.let {
ViewCompat.setBackgroundTintList(it, colorStateList)
it.setTextColor(textColor)
}
this.show_web_search?.let {
ViewCompat.setBackgroundTintList(it, colorStateList)
it.setTextColor(textColor)
}
}
override fun onImageError(imageView: ImageView, errorDrawable: Drawable?) {
val parent = imageView.parent
if (parent is View) {
parent.visibility = View.GONE
}
}
override fun onImageReady(imageView: ImageView, resource: Bitmap) {
val parent = imageView.parent
if (parent is View) {
parent.visibility = View.VISIBLE
}
}
override fun onOptionsItemSelected(item: MenuItem?) = when (item?.itemId) {
R.id.menu_change_quality -> {
this.changeQuality()
true
}
R.id.menu_delete_show -> {
this.deleteShow()
true
}
R.id.menu_pause_show -> {
this.pauseOrResumeShow(true)
true
}
R.id.menu_rescan_show -> {
this.rescanShow()
true
}
R.id.menu_resume_show -> {
this.pauseOrResumeShow(false)
true
}
R.id.menu_update_show -> {
this.updateShow()
true
}
else -> super.onOptionsItemSelected(item)
}
override fun onRefresh() {
this.swipe_refresh?.isRefreshing = true
val indexerId = this.arguments?.getInt(Constants.Bundle.INDEXER_ID) ?: return
SickRageApi.instance.services?.getShow(indexerId, this)
}
override fun onResume() {
super.onResume()
this.onRefresh()
}
override fun onStart() {
super.onStart()
this.realm = Realm.getDefaultInstance()
this.show = this.realm.getShow(this.indexerId, this)
}
override fun onStop() {
if (this.show.isValid) {
this.show.removeAllChangeListeners()
}
this.realm.close()
super.onStop()
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
this.show_imdb?.setOnClickListener(this)
this.show_the_tvdb?.setOnClickListener(this)
this.show_web_search?.setOnClickListener(this)
this.swipe_refresh?.setColorSchemeResources(R.color.accent)
this.swipe_refresh?.setOnRefreshListener(this)
this.checkSupportWebSearch()
}
override fun success(singleShow: SingleShow?, response: Response?) {
this.swipe_refresh?.isRefreshing = false
val show = singleShow?.data ?: return
Realm.getDefaultInstance().use {
it.saveShow(show)
}
}
private fun changeQuality() {
ChangeQualityFragment.newInstance(this.indexerId)
.show(this.childFragmentManager, "change_quality")
}
private fun checkSupportWebSearch() {
val webSearchIntent = Intent(Intent.ACTION_WEB_SEARCH)
val manager = this.context?.packageManager
val activities = manager?.queryIntentActivities(webSearchIntent, 0).orEmpty()
this.show_web_search?.visibility = if (activities.isNotEmpty()) View.VISIBLE else View.GONE
}
private fun deleteShow() {
val activity = this.activity
if (activity == null || !this.show.isLoaded) {
return
}
val indexerId = this.indexerId
val callback = DeleteShowCallback(activity, indexerId)
AlertDialog.Builder(activity)
.setTitle(this.getString(R.string.delete_show_title, this.show.showName))
.setMessage(R.string.delete_show_message)
.setPositiveButton(R.string.keep) { _, _ ->
SickRageApi.instance.services?.deleteShow(indexerId, 0, callback)
}
.setNegativeButton(R.string.delete) { _, _ ->
SickRageApi.instance.services?.deleteShow(indexerId, 1, callback)
}
.setNeutralButton(R.string.cancel, null)
.show()
}
private fun getTranslatedQualities(qualities: RealmList<String>?, allowed: Boolean): List<String> {
val translatedQualities = mutableListOf<String>()
if (qualities == null || qualities.isEmpty()) {
return translatedQualities
}
val keys = if (allowed) {
resources.getStringArray(R.array.allowed_qualities_keys).toList()
} else {
resources.getStringArray(R.array.allowed_qualities_keys).toList()
}
val values = if (allowed) {
resources.getStringArray(R.array.allowed_qualities_values).toList()
} else {
resources.getStringArray(R.array.allowed_qualities_values).toList()
}
qualities.forEach {
val position = keys.indexOf(it)
if (position != -1) {
// Skip the "Ignore" first item
translatedQualities.add(values[position + 1])
}
}
return translatedQualities
}
private fun pauseOrResumeShow(pause: Boolean) {
this.showHidePauseResumeMenus(!pause)
SickRageApi.instance.services?.pauseShow(this.indexerId, pause.toInt(), object : GenericCallback(this.activity) {
override fun failure(error: RetrofitError?) {
super.failure(error)
showHidePauseResumeMenus(pause)
}
})
}
private fun rescanShow() {
SickRageApi.instance.services?.rescanShow(this.indexerId, GenericCallback(this.activity))
}
private fun showHidePauseResumeMenus(isPause: Boolean) {
this.pauseMenu?.isVisible = isPause
this.resumeMenu?.isVisible = !isPause
}
private fun updateShow() {
SickRageApi.instance.services?.updateShow(this.indexerId, GenericCallback(this.activity))
}
private class DeleteShowCallback(activity: FragmentActivity, val indexerId: Int) : GenericCallback(activity) {
override fun success(genericResponse: GenericResponse?, response: Response?) {
super.success(genericResponse, response)
Realm.getDefaultInstance().use {
it.deleteShow(this.indexerId)
}
val activity = this.getActivity() ?: return
val intent = Intent(activity, MainActivity::class.java)
activity.startActivity(intent)
}
}
private class ServiceConnection(fragment: ShowOverviewFragment) : CustomTabsServiceConnection() {
private val fragmentReference = WeakReference(fragment)
override fun onCustomTabsServiceConnected(componentName: ComponentName?, customTabsClient: CustomTabsClient?) {
customTabsClient?.warmup(0L)
val fragment = this.fragmentReference.get() ?: return
fragment.tabSession = customTabsClient?.newSession(null)
if (fragment.show.isValid) {
fragment.tabSession?.mayLaunchUrl(Uri.parse("http://www.imdb.com/title/${fragment.show.imdbId}"), null, null)
fragment.tabSession?.mayLaunchUrl(Uri.parse("http://thetvdb.com/?tab=series&id=${fragment.show.tvDbId}"), null, null)
}
}
override fun onServiceDisconnected(name: ComponentName?) {
this.fragmentReference.clear()
}
}
}
| apache-2.0 | b8613f7a04e55d55316267b98f20f04e | 30.670565 | 207 | 0.760079 | 3.674129 | false | false | false | false |
zbeboy/ISY | src/main/java/top/zbeboy/isy/service/system/SystemAlertServiceImpl.kt | 1 | 7023 | package top.zbeboy.isy.service.system
import com.alibaba.fastjson.JSON
import org.jooq.*
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Propagation
import org.springframework.transaction.annotation.Transactional
import org.springframework.util.ObjectUtils
import org.springframework.util.StringUtils
import top.zbeboy.isy.domain.Tables.SYSTEM_ALERT
import top.zbeboy.isy.domain.Tables.SYSTEM_ALERT_TYPE
import top.zbeboy.isy.domain.tables.daos.SystemAlertDao
import top.zbeboy.isy.domain.tables.pojos.SystemAlert
import top.zbeboy.isy.service.util.DateTimeUtils
import top.zbeboy.isy.service.util.SQLQueryUtils
import top.zbeboy.isy.web.bean.system.alert.SystemAlertBean
import top.zbeboy.isy.web.util.PaginationUtils
import java.sql.Timestamp
import java.util.*
import javax.annotation.Resource
/**
* Created by zbeboy 2017-11-07 .
**/
@Service("systemAlertService")
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
open class SystemAlertServiceImpl @Autowired constructor(dslContext: DSLContext) : SystemAlertService {
private val create: DSLContext = dslContext
@Resource
open lateinit var systemAlertDao: SystemAlertDao
override fun findByUsernameAndId(username: String, id: String): Optional<Record> {
return create.select()
.from(SYSTEM_ALERT)
.join(SYSTEM_ALERT_TYPE)
.on(SYSTEM_ALERT.SYSTEM_ALERT_TYPE_ID.eq(SYSTEM_ALERT_TYPE.SYSTEM_ALERT_TYPE_ID))
.where(SYSTEM_ALERT.USERNAME.eq(username).and(SYSTEM_ALERT.SYSTEM_ALERT_ID.eq(id)))
.fetchOptional()
}
override fun findByUsernameAndLinkIdAndSystemAlertTypeId(username: String, linkId: String, systemAlertTypeId: Int): Optional<Record> {
return create.select()
.from(SYSTEM_ALERT)
.where(SYSTEM_ALERT.USERNAME.eq(username).and(SYSTEM_ALERT.LINK_ID.eq(linkId)).and(SYSTEM_ALERT.SYSTEM_ALERT_TYPE_ID.eq(systemAlertTypeId)))
.fetchOptional()
}
override fun findAllByPageForShow(pageNum: Int, pageSize: Int, username: String, isSee: Boolean): Result<Record> {
val b: Byte = if (isSee) {
1
} else {
0
}
return create.select()
.from(SYSTEM_ALERT)
.join(SYSTEM_ALERT_TYPE)
.on(SYSTEM_ALERT.SYSTEM_ALERT_TYPE_ID.eq(SYSTEM_ALERT_TYPE.SYSTEM_ALERT_TYPE_ID))
.where(SYSTEM_ALERT.USERNAME.eq(username).and(SYSTEM_ALERT.IS_SEE.eq(b)))
.orderBy(SYSTEM_ALERT.ALERT_DATE.desc())
.limit((pageNum - 1) * pageSize, pageSize)
.fetch()
}
override fun countAllForShow(username: String, isSee: Boolean): Int {
val b: Byte = if (isSee) {
1
} else {
0
}
val record = create.selectCount()
.from(SYSTEM_ALERT)
.where(SYSTEM_ALERT.USERNAME.eq(username).and(SYSTEM_ALERT.IS_SEE.eq(b)))
.fetchOne()
return record.value1()
}
override fun findAllByPage(paginationUtils: PaginationUtils, systemAlertBean: SystemAlertBean): Result<Record> {
val pageNum = paginationUtils.getPageNum()
val pageSize = paginationUtils.getPageSize()
var a = searchCondition(paginationUtils)
a = otherCondition(a, systemAlertBean)
return create.select()
.from(SYSTEM_ALERT)
.join(SYSTEM_ALERT_TYPE)
.on(SYSTEM_ALERT.SYSTEM_ALERT_TYPE_ID.eq(SYSTEM_ALERT_TYPE.SYSTEM_ALERT_TYPE_ID))
.where(a)
.orderBy(SYSTEM_ALERT.ALERT_DATE.desc())
.limit((pageNum - 1) * pageSize, pageSize)
.fetch()
}
override fun dealData(paginationUtils: PaginationUtils, records: Result<Record>, systemAlertBean: SystemAlertBean): List<SystemAlertBean> {
var systemAlertBeens: List<SystemAlertBean> = ArrayList()
if (records.isNotEmpty) {
systemAlertBeens = records.into(SystemAlertBean::class.java)
systemAlertBeens.forEach { i -> i.alertDateStr = DateTimeUtils.formatDate(i.alertDate, "yyyy年MM月dd日 HH:mm:ss") }
paginationUtils.setTotalDatas(countByCondition(paginationUtils, systemAlertBean))
}
return systemAlertBeens
}
override fun countByCondition(paginationUtils: PaginationUtils, systemAlertBean: SystemAlertBean): Int {
val count: Record1<Int>
var a = searchCondition(paginationUtils)
a = otherCondition(a, systemAlertBean)
count = if (ObjectUtils.isEmpty(a)) {
val selectJoinStep = create.selectCount()
.from(SYSTEM_ALERT)
selectJoinStep.fetchOne()
} else {
val selectConditionStep = create.selectCount()
.from(SYSTEM_ALERT)
.join(SYSTEM_ALERT_TYPE)
.on(SYSTEM_ALERT.SYSTEM_ALERT_TYPE_ID.eq(SYSTEM_ALERT_TYPE.SYSTEM_ALERT_TYPE_ID))
.where(a)
selectConditionStep.fetchOne()
}
return count.value1()
}
@Transactional(propagation = Propagation.REQUIRED, readOnly = false)
override fun save(systemAlert: SystemAlert) {
systemAlertDao.insert(systemAlert)
}
override fun deleteByAlertDate(timestamp: Timestamp) {
create.deleteFrom(SYSTEM_ALERT).where(SYSTEM_ALERT.ALERT_DATE.le(timestamp)).execute()
}
override fun update(systemAlert: SystemAlert) {
systemAlertDao.update(systemAlert)
}
/**
* 搜索条件
*
* @param paginationUtils 分页工具
* @return 条件
*/
fun searchCondition(paginationUtils: PaginationUtils): Condition? {
var a: Condition? = null
val search = JSON.parseObject(paginationUtils.getSearchParams())
if (!ObjectUtils.isEmpty(search)) {
val alertContent = StringUtils.trimWhitespace(search.getString("alertContent"))
if (StringUtils.hasLength(alertContent)) {
a = SYSTEM_ALERT.ALERT_CONTENT.like(SQLQueryUtils.likeAllParam(alertContent))
}
}
return a
}
/**
* 其它条件参数
*
* @param a 搜索条件
* @param systemAlertBean 额外参数
* @return 条件
*/
private fun otherCondition(a: Condition?, systemAlertBean: SystemAlertBean): Condition? {
var condition = a
if (!ObjectUtils.isEmpty(systemAlertBean)) {
if (StringUtils.hasLength(systemAlertBean.username)) {
condition = if (!ObjectUtils.isEmpty(condition)) {
condition!!.and(SYSTEM_ALERT.USERNAME.eq(systemAlertBean.username))
} else {
SYSTEM_ALERT.USERNAME.eq(systemAlertBean.username)
}
}
}
return condition
}
} | mit | d0c705396ce97dddb1336803e8078693 | 38.805714 | 156 | 0.64336 | 4.481982 | false | false | false | false |
Displee/RS2-Cache-Library | src/main/kotlin/com/displee/util/OtherExt.kt | 1 | 1585 | package com.displee.util
import com.displee.cache.index.Index.Companion.WHIRLPOOL_SIZE
import java.io.InputStream
import java.io.OutputStream
private val CRC_TABLE = IntArray(256) {
var crc = it
for (i_84_ in 0..7) {
crc = if (crc and 0x1 == 1) {
crc ushr 1 xor 0x12477cdf.inv()
} else {
crc ushr 1
}
}
crc
}
fun ByteArray.generateCrc(offset: Int = 0, length: Int = size): Int {
var crc = -1
for (i in offset until length) {
crc = crc ushr 8 xor CRC_TABLE[crc xor this[i].toInt() and 0xff]
}
crc = crc xor -0x1
return crc
}
fun ByteArray.generateWhirlpool(offset: Int = 0, length: Int = size): ByteArray {
val source: ByteArray
if (offset > 0) {
source = ByteArray(length)
System.arraycopy(this, offset, source, 0, length)
} else {
source = this
}
val whirlpool = Whirlpool()
whirlpool.NESSIEinit()
whirlpool.NESSIEadd(source, (length * 8).toLong())
val digest = ByteArray(WHIRLPOOL_SIZE)
whirlpool.NESSIEfinalize(digest, 0)
return digest
}
fun InputStream.writeTo(to: OutputStream): Long {
val buf = ByteArray(0x1000)
var total: Long = 0
while (true) {
val r = read(buf)
if (r == -1) {
break
}
to.write(buf, 0, r)
total += r.toLong()
}
return total
}
fun String.hashCode317(): Int {
val upperCaseString = toUpperCase()
var hash = 0
for (element in upperCaseString) {
hash = hash * 61 + element.toInt() - 32
}
return hash
} | mit | 5b59ac6cdfcfd5b25a57b8235bb3f70e | 23.4 | 81 | 0.590536 | 3.561798 | false | false | false | false |
RuneSuite/client | updater-mapper/src/main/java/org/runestar/client/updater/mapper/std/classes/RasterProvider.kt | 1 | 2718 | package org.runestar.client.updater.mapper.std.classes
import org.runestar.client.common.startsWith
import org.runestar.client.updater.mapper.IdentityMapper
import org.runestar.client.updater.mapper.OrderMapper
import org.runestar.client.updater.mapper.DependsOn
import org.runestar.client.updater.mapper.MethodParameters
import org.runestar.client.updater.mapper.and
import org.runestar.client.updater.mapper.predicateOf
import org.runestar.client.updater.mapper.type
import org.runestar.client.updater.mapper.Class2
import org.runestar.client.updater.mapper.Field2
import org.runestar.client.updater.mapper.Instruction2
import org.runestar.client.updater.mapper.Method2
import org.objectweb.asm.Type
import java.awt.Component
import java.awt.Image
@DependsOn(AbstractRasterProvider::class)
class RasterProvider : IdentityMapper.Class() {
override val predicate = predicateOf<Class2> { it.superType == type<AbstractRasterProvider>() }
.and { it.interfaces.isEmpty() }
.and { it.instanceFields.any { it.type == Component::class.type } }
class component0 : IdentityMapper.InstanceField() {
override val predicate = predicateOf<Field2> { it.type == Component::class.type }
}
class image : IdentityMapper.InstanceField() {
override val predicate = predicateOf<Field2> { it.type == Image::class.type }
}
@MethodParameters("x", "y", "width", "height")
@DependsOn(AbstractRasterProvider.draw::class)
class draw : IdentityMapper.InstanceMethod() {
override val predicate = predicateOf<Method2> { it.mark == method<AbstractRasterProvider.draw>().mark }
}
@MethodParameters("x", "y")
@DependsOn(AbstractRasterProvider.drawFull::class)
class drawFull : IdentityMapper.InstanceMethod() {
override val predicate = predicateOf<Method2> { it.mark == method<AbstractRasterProvider.drawFull>().mark }
}
@MethodParameters("graphics", "x", "y", "width", "height")
@DependsOn(draw::class)
class draw0 : OrderMapper.InMethod.Method(draw::class, 0, 1) {
override val predicate = predicateOf<Instruction2> { it.isMethod && it.methodOwner == type<RasterProvider>() }
}
@MethodParameters("graphics", "x", "y")
@DependsOn(drawFull::class)
class drawFull0 : OrderMapper.InMethod.Method(drawFull::class, 0, 1) {
override val predicate = predicateOf<Instruction2> { it.isMethod && it.methodOwner == type<RasterProvider>() }
}
@MethodParameters("c")
class setComponent : IdentityMapper.InstanceMethod() {
override val predicate = predicateOf<Method2> { it.returnType == Type.VOID_TYPE }
.and { it.arguments.startsWith(Component::class.type) }
}
} | mit | f7feebde5dc092ab5be3927b6fe56fe2 | 42.854839 | 118 | 0.72443 | 4.213953 | false | false | false | false |
Virtlink/aesi | pie/src/main/kotlin/com/virtlink/pie/structureoutline/PieStructureOutlineService.kt | 1 | 2339 | package com.virtlink.pie.structureoutline
import com.google.inject.name.Named
import com.virtlink.editorservices.ICancellationToken
import com.virtlink.editorservices.ScopeNames
import com.virtlink.editorservices.Span
import com.virtlink.editorservices.resources.IResourceManager
import com.virtlink.editorservices.structureoutline.*
import com.virtlink.editorservices.symbols.ISymbol
import com.virtlink.pie.IBuildManagerProvider
import mb.pie.runtime.core.BuildApp
import java.io.Serializable
import java.net.URI
class PieStructureOutlineService(
private val buildManagerProvider: IBuildManagerProvider,
private val resourceManager: IResourceManager,
@Named(PieStructureOutlineService.ID) private val builderId: String
) : IStructureOutlineService {
companion object {
const val ID: String = "StructureOutlineBuilder.ID"
}
data class Input(val document: URI) : Serializable
data class StructureOutlineElement(
val children: List<StructureOutlineElement>,
override val label: String,
override val nameSpan: Span? = null,
override val scopes: ScopeNames = ScopeNames(),
override val isLeaf: Boolean? = null)
: IStructureOutlineElement
data class StructureTree(val roots: List<StructureOutlineElement>): Serializable
override fun configure(configuration: IStructureOutlineConfiguration) {
// Nothing to do.
}
override fun getRoots(
document: URI,
cancellationToken: ICancellationToken?)
: IStructureOutlineInfo? {
return StructureOutlineInfo(getTree(document).roots)
}
override fun getChildren(
document: URI,
node: IStructureOutlineElement,
cancellationToken: ICancellationToken?)
: IStructureOutlineInfo? {
return StructureOutlineInfo((node as StructureOutlineElement).children)
}
private fun getTree(document: URI): StructureTree {
val input = PieStructureOutlineService.Input(document)
val project = this.resourceManager.getProjectOf(document)!!
val app = BuildApp<PieStructureOutlineService.Input, StructureTree>(this.builderId, input)
val manager = buildManagerProvider.getBuildManager(project)
return manager.build(app)
}
} | apache-2.0 | ad790d4499868f508c3a543360e65a60 | 36.142857 | 98 | 0.727234 | 5.174779 | false | false | false | false |
apollographql/apollo-android | tests/models-compat/src/commonTest/kotlin/test/StoreTest.kt | 1 | 6917 | package test
import IdCacheKeyGenerator
import codegen.models.HeroAndFriendsWithFragmentsQuery
import codegen.models.HeroAndFriendsWithTypenameQuery
import codegen.models.fragment.HeroWithFriendsFragment
import codegen.models.fragment.HeroWithFriendsFragmentImpl
import codegen.models.fragment.HumanWithIdFragment
import codegen.models.fragment.HumanWithIdFragmentImpl
import com.apollographql.apollo3.ApolloClient
import com.apollographql.apollo3.annotations.ApolloExperimental
import com.apollographql.apollo3.cache.normalized.ApolloStore
import com.apollographql.apollo3.cache.normalized.api.CacheKey
import com.apollographql.apollo3.cache.normalized.api.MemoryCacheFactory
import com.apollographql.apollo3.cache.normalized.store
import com.apollographql.apollo3.mockserver.MockServer
import com.apollographql.apollo3.mockserver.enqueue
import com.apollographql.apollo3.testing.runTest
import testFixtureToUtf8
import kotlin.test.Test
import kotlin.test.assertEquals
@OptIn(ApolloExperimental::class)
class StoreTest {
private lateinit var mockServer: MockServer
private lateinit var apolloClient: ApolloClient
private lateinit var store: ApolloStore
private suspend fun setUp() {
store = ApolloStore(
normalizedCacheFactory = MemoryCacheFactory(),
cacheKeyGenerator = IdCacheKeyGenerator
)
mockServer = MockServer()
apolloClient = ApolloClient.Builder().serverUrl(mockServer.url()).store(store).build()
}
private suspend fun tearDown() {
mockServer.stop()
}
@Test
fun readFragmentFromStore() = runTest(before = { setUp() }, after = { tearDown() }) {
mockServer.enqueue(testFixtureToUtf8("HeroAndFriendsWithTypename.json"))
apolloClient.query(HeroAndFriendsWithTypenameQuery()).execute()
val heroWithFriendsFragment = store.readFragment(
HeroWithFriendsFragmentImpl(),
CacheKey("2001"),
)
assertEquals(heroWithFriendsFragment.id, "2001")
assertEquals(heroWithFriendsFragment.name, "R2-D2")
assertEquals(heroWithFriendsFragment.friends?.size, 3)
assertEquals(heroWithFriendsFragment.friends?.get(0)?.fragments?.humanWithIdFragment?.id, "1000")
assertEquals(heroWithFriendsFragment.friends?.get(0)?.fragments?.humanWithIdFragment?.name, "Luke Skywalker")
assertEquals(heroWithFriendsFragment.friends?.get(1)?.fragments?.humanWithIdFragment?.id, "1002")
assertEquals(heroWithFriendsFragment.friends?.get(1)?.fragments?.humanWithIdFragment?.name, "Han Solo")
assertEquals(heroWithFriendsFragment.friends?.get(2)?.fragments?.humanWithIdFragment?.id, "1003")
assertEquals(heroWithFriendsFragment.friends?.get(2)?.fragments?.humanWithIdFragment?.name, "Leia Organa")
var fragment = store.readFragment(
HumanWithIdFragmentImpl(),
CacheKey("1000"),
)
assertEquals(fragment.id, "1000")
assertEquals(fragment.name, "Luke Skywalker")
fragment = store.readFragment(
HumanWithIdFragmentImpl(),
CacheKey("1002"),
)
assertEquals(fragment.id, "1002")
assertEquals(fragment.name, "Han Solo")
fragment = store.readFragment(
HumanWithIdFragmentImpl(),
CacheKey("1003"),
)
assertEquals(fragment.id, "1003")
assertEquals(fragment.name, "Leia Organa")
}
/**
* Modify the store by writing fragments
*/
@Test
fun fragments() = runTest(before = { setUp() }, after = { tearDown() }) {
mockServer.enqueue(testFixtureToUtf8("HeroAndFriendsNamesWithIDs.json"))
val query = HeroAndFriendsWithFragmentsQuery()
var response = apolloClient.query(query).execute()
assertEquals(response.data?.hero?.__typename, "Droid")
assertEquals(response.data?.hero?.fragments?.heroWithFriendsFragment?.id, "2001")
assertEquals(response.data?.hero?.fragments?.heroWithFriendsFragment?.name, "R2-D2")
assertEquals(response.data?.hero?.fragments?.heroWithFriendsFragment?.friends?.size, 3)
assertEquals(response.data?.hero?.fragments?.heroWithFriendsFragment?.friends?.get(0)?.fragments?.humanWithIdFragment?.id, "1000")
assertEquals(response.data?.hero?.fragments?.heroWithFriendsFragment?.friends?.get(0)?.fragments?.humanWithIdFragment?.name, "Luke Skywalker")
assertEquals(response.data?.hero?.fragments?.heroWithFriendsFragment?.friends?.get(1)?.fragments?.humanWithIdFragment?.id, "1002")
assertEquals(response.data?.hero?.fragments?.heroWithFriendsFragment?.friends?.get(1)?.fragments?.humanWithIdFragment?.name, "Han Solo")
assertEquals(response.data?.hero?.fragments?.heroWithFriendsFragment?.friends?.get(2)?.fragments?.humanWithIdFragment?.id, "1003")
assertEquals(response.data?.hero?.fragments?.heroWithFriendsFragment?.friends?.get(2)?.fragments?.humanWithIdFragment?.name, "Leia Organa")
store.writeFragment(
HeroWithFriendsFragmentImpl(),
CacheKey("2001"),
HeroWithFriendsFragment(
id = "2001",
name = "R222-D222",
friends = listOf(
HeroWithFriendsFragment.Friend(
__typename = "Human",
fragments = HeroWithFriendsFragment.Friend.Fragments(
humanWithIdFragment = HumanWithIdFragment(
id = "1000",
name = "SuperMan"
)
)
),
HeroWithFriendsFragment.Friend(
__typename = "Human",
fragments = HeroWithFriendsFragment.Friend.Fragments(
humanWithIdFragment = HumanWithIdFragment(
id = "1002",
name = "Han Solo"
)
)
),
)
),
)
store.writeFragment(
HumanWithIdFragmentImpl(),
CacheKey("1002"),
HumanWithIdFragment(
id = "1002",
name = "Beast"
),
)
// Values should have changed
response = apolloClient.query(query).execute()
assertEquals(response.data?.hero?.__typename, "Droid")
assertEquals(response.data?.hero?.fragments?.heroWithFriendsFragment?.id, "2001")
assertEquals(response.data?.hero?.fragments?.heroWithFriendsFragment?.name, "R222-D222")
assertEquals(response.data?.hero?.fragments?.heroWithFriendsFragment?.friends?.size, 2)
assertEquals(response.data?.hero?.fragments?.heroWithFriendsFragment?.friends?.get(0)?.fragments?.humanWithIdFragment?.id, "1000")
assertEquals(response.data?.hero?.fragments?.heroWithFriendsFragment?.friends?.get(0)?.fragments?.humanWithIdFragment?.name, "SuperMan")
assertEquals(response.data?.hero?.fragments?.heroWithFriendsFragment?.friends?.get(1)?.fragments?.humanWithIdFragment?.id, "1002")
assertEquals(response.data?.hero?.fragments?.heroWithFriendsFragment?.friends?.get(1)?.fragments?.humanWithIdFragment?.name, "Beast")
}
} | mit | 1f738916554091a0d0c955eb37ebd5e6 | 44.513158 | 146 | 0.704785 | 5.052593 | false | true | false | false |
glodanif/BluetoothChat | app/src/main/kotlin/com/glodanif/bluetoothchat/ui/widget/SettingsPopup.kt | 1 | 5160 | package com.glodanif.bluetoothchat.ui.widget
import android.animation.Animator
import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Color
import android.graphics.Rect
import android.graphics.drawable.ColorDrawable
import android.os.Build
import androidx.annotation.ColorInt
import android.view.Gravity
import android.view.View
import android.view.ViewAnimationUtils
import android.view.WindowManager
import android.widget.ImageView
import android.widget.PopupWindow
import android.widget.TextView
import com.amulyakhare.textdrawable.TextDrawable
import com.glodanif.bluetoothchat.R
import com.glodanif.bluetoothchat.ui.util.EmptyAnimatorListener
import com.glodanif.bluetoothchat.utils.getFirstLetter
import com.glodanif.bluetoothchat.utils.getLayoutInflater
class SettingsPopup(context: Context) : PopupWindow() {
enum class Option {
PROFILE,
IMAGES,
SETTINGS,
ABOUT;
}
private val appearingAnimationDuration = 200L
@ColorInt
private var color = Color.GRAY
private var userName = ""
private var clickListener: ((Option) -> (Unit))? = null
private var rootView: View
private var container: View
private var avatar: ImageView
private var userNameLabel: TextView
private var isDismissing: Boolean = false
fun populateData(userName: String, @ColorInt color: Int) {
this.userName = userName
this.color = color
}
fun setOnOptionClickListener(clickListener: (Option) -> (Unit)) {
this.clickListener = clickListener
}
init {
@SuppressLint("InflateParams")
rootView = context.getLayoutInflater().inflate(R.layout.popup_settings, null)
container = rootView.findViewById(R.id.fl_container)
avatar = rootView.findViewById(R.id.iv_avatar)
userNameLabel = rootView.findViewById(R.id.tv_username)
rootView.findViewById<View>(R.id.ll_user_profile_container).setOnClickListener {
dismiss()
clickListener?.invoke(Option.PROFILE)
}
rootView.findViewById<View>(R.id.ll_images_button).setOnClickListener {
dismiss()
clickListener?.invoke(Option.IMAGES)
}
rootView.findViewById<View>(R.id.ll_settings_button).setOnClickListener {
dismiss()
clickListener?.invoke(Option.SETTINGS)
}
rootView.findViewById<View>(R.id.ll_about_button).setOnClickListener {
dismiss()
clickListener?.invoke(Option.ABOUT)
}
contentView = rootView
}
fun show(anchor: View) {
prepare()
populateUi()
val xPosition: Int
val yPosition: Int
val location = IntArray(2)
anchor.getLocationOnScreen(location)
val anchorRect = Rect(location[0], location[1],
location[0] + anchor.width, location[1] + anchor.height)
xPosition = anchorRect.right + rootView.measuredWidth
yPosition = anchorRect.top
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
container.visibility = View.VISIBLE
}
showAtLocation(anchor, Gravity.NO_GRAVITY, xPosition, yPosition)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
container.post {
if (container.isAttachedToWindow) {
val animator = ViewAnimationUtils.createCircularReveal(container,
container.width, 0, 0f, container.measuredWidth.toFloat())
container.visibility = View.VISIBLE
animator.duration = appearingAnimationDuration
animator.start()
}
}
}
}
override fun dismiss() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && !isDismissing) {
val animator = ViewAnimationUtils.createCircularReveal(container,
container.width, 0, container.measuredWidth.toFloat(), 0f)
container.visibility = View.VISIBLE
animator.addListener(object : EmptyAnimatorListener() {
override fun onAnimationStart(animation: Animator?) {
isDismissing = true
}
override fun onAnimationEnd(animation: Animator?) {
actualDismiss()
}
})
animator.duration = appearingAnimationDuration
animator.start()
} else {
actualDismiss()
}
}
private fun actualDismiss() {
isDismissing = false
super.dismiss()
}
private fun prepare() {
setBackgroundDrawable(ColorDrawable())
width = WindowManager.LayoutParams.WRAP_CONTENT
height = WindowManager.LayoutParams.WRAP_CONTENT
isTouchable = true
isFocusable = true
isOutsideTouchable = true
}
private fun populateUi() {
val drawable = TextDrawable.builder().buildRound(userName.getFirstLetter(), color)
avatar.setImageDrawable(drawable)
userNameLabel.text = userName
}
}
| apache-2.0 | 6ef930291fa290554b14e0da6e8a7ebd | 29.898204 | 90 | 0.645736 | 5.034146 | false | false | false | false |
allotria/intellij-community | platform/lang-impl/src/com/intellij/workspaceModel/ide/impl/legacyBridge/watcher/VirtualFileUrlWatcher.kt | 2 | 9130 | // 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.workspaceModel.ide.impl.legacyBridge.watcher
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.io.FileUtil
import com.intellij.workspaceModel.ide.JpsFileEntitySource
import com.intellij.workspaceModel.ide.WorkspaceModel
import com.intellij.workspaceModel.ide.getInstance
import com.intellij.workspaceModel.storage.*
import com.intellij.workspaceModel.storage.bridgeEntities.*
import com.intellij.workspaceModel.storage.url.VirtualFileUrl
import com.intellij.workspaceModel.storage.url.VirtualFileUrlManager
import kotlin.reflect.KClass
open class VirtualFileUrlWatcher(val project: Project) {
private val virtualFileManager = VirtualFileUrlManager.getInstance(project)
internal var isInsideFilePointersUpdate = false
private set
private val pointers = listOf(
// Library roots
LibraryRootFileWatcher(),
// Library excluded roots
EntityVirtualFileUrlWatcher(
LibraryEntity::class, ModifiableLibraryEntity::class,
propertyName = LibraryEntity::excludedRoots.name,
modificator = { oldVirtualFileUrl, newVirtualFileUrl ->
excludedRoots = excludedRoots - oldVirtualFileUrl
excludedRoots = excludedRoots + newVirtualFileUrl
}
),
// Content root urls
EntityVirtualFileUrlWatcher(
ContentRootEntity::class, ModifiableContentRootEntity::class,
propertyName = ContentRootEntity::url.name,
modificator = { _, newVirtualFileUrl -> url = newVirtualFileUrl }
),
// Content root excluded urls
EntityVirtualFileUrlWatcher(
ContentRootEntity::class, ModifiableContentRootEntity::class,
propertyName = ContentRootEntity::excludedUrls.name,
modificator = { oldVirtualFileUrl, newVirtualFileUrl ->
excludedUrls = excludedUrls - oldVirtualFileUrl
excludedUrls = excludedUrls + newVirtualFileUrl
}
),
// Source roots
EntityVirtualFileUrlWatcher(
SourceRootEntity::class, ModifiableSourceRootEntity::class,
propertyName = SourceRootEntity::url.name,
modificator = { _, newVirtualFileUrl -> url = newVirtualFileUrl }
),
// Java module settings entity compiler output
EntityVirtualFileUrlWatcher(
JavaModuleSettingsEntity::class, ModifiableJavaModuleSettingsEntity::class,
propertyName = JavaModuleSettingsEntity::compilerOutput.name,
modificator = { _, newVirtualFileUrl -> compilerOutput = newVirtualFileUrl }
),
// Java module settings entity compiler output for tests
EntityVirtualFileUrlWatcher(
JavaModuleSettingsEntity::class, ModifiableJavaModuleSettingsEntity::class,
propertyName = JavaModuleSettingsEntity::compilerOutputForTests.name,
modificator = { _, newVirtualFileUrl -> compilerOutputForTests = newVirtualFileUrl }
),
EntitySourceFileWatcher(JpsFileEntitySource.ExactFile::class, { it.file.url }, { source, file -> source.copy(file = file) }),
EntitySourceFileWatcher(JpsFileEntitySource.FileInDirectory::class, { it.directory.url },
{ source, file -> source.copy(directory = file) })
)
fun onVfsChange(oldUrl: String, newUrl: String) {
try {
isInsideFilePointersUpdate = true
val entityWithVirtualFileUrl = mutableListOf<EntityWithVirtualFileUrl>()
WorkspaceModel.getInstance(project).updateProjectModel { diff ->
val oldFileUrl = virtualFileManager.fromUrl(oldUrl)
calculateAffectedEntities(diff, oldFileUrl, entityWithVirtualFileUrl)
oldFileUrl.subTreeFileUrls.map { fileUrl -> calculateAffectedEntities(diff, fileUrl, entityWithVirtualFileUrl) }
val result = entityWithVirtualFileUrl.filter { shouldUpdateThisEntity(it.entity) }.toList()
pointers.forEach { it.onVfsChange(oldUrl, newUrl, result, virtualFileManager, diff) }
}
}
finally {
isInsideFilePointersUpdate = false
}
}
// A workaround to have an opportunity to skip some entities from being updated (for now it's only for Rider to avoid update ContentRoots)
open fun shouldUpdateThisEntity(entity: WorkspaceEntity): Boolean {
return true
}
companion object {
@JvmStatic
fun getInstance(project: Project): VirtualFileUrlWatcher = project.getComponent(VirtualFileUrlWatcher::class.java)
internal fun calculateAffectedEntities(storage: WorkspaceEntityStorage, virtualFileUrl: VirtualFileUrl,
aggregator: MutableList<EntityWithVirtualFileUrl>) {
storage.getVirtualFileUrlIndex().findEntitiesByUrl(virtualFileUrl).forEach {
aggregator.add(EntityWithVirtualFileUrl(it.first, virtualFileUrl, it.second))
}
}
}
}
data class EntityWithVirtualFileUrl(val entity: WorkspaceEntity, val virtualFileUrl: VirtualFileUrl, val propertyName: String)
private interface LegacyFileWatcher {
fun onVfsChange(oldUrl: String, newUrl: String, entitiesWithVFU: List<EntityWithVirtualFileUrl>, virtualFileManager: VirtualFileUrlManager,
diff: WorkspaceEntityStorageBuilder)
}
private class EntitySourceFileWatcher<T : EntitySource>(
val entitySource: KClass<T>,
val containerToUrl: (T) -> String,
val createNewSource: (T, VirtualFileUrl) -> T
) : LegacyFileWatcher {
override fun onVfsChange(oldUrl: String, newUrl: String, entitiesWithVFU: List<EntityWithVirtualFileUrl>, virtualFileManager: VirtualFileUrlManager,
diff: WorkspaceEntityStorageBuilder) {
val entities = diff.entitiesBySource { it::class == entitySource }
for ((entitySource, mapOfEntities) in entities) {
@Suppress("UNCHECKED_CAST")
val urlFromContainer = containerToUrl(entitySource as T)
if (!FileUtil.startsWith(urlFromContainer, oldUrl)) continue
val newVfurl = virtualFileManager.fromUrl(newUrl + urlFromContainer.substring(oldUrl.length))
val newEntitySource = createNewSource(entitySource, newVfurl)
mapOfEntities.values.flatten().forEach { diff.changeSource(it, newEntitySource) }
}
}
}
/**
* Legacy file pointer that can track and update urls stored in a [WorkspaceEntity].
* [entityClass] - class of a [WorkspaceEntity] that contains an url being tracked
* [modifiableEntityClass] - class of modifiable entity of [entityClass]
* [propertyName] - name of the field which contains [VirtualFileUrl]
* [modificator] - function for modifying an entity
* There 2 functions are created for better convenience. You should use only one from them.
*/
private class EntityVirtualFileUrlWatcher<E : WorkspaceEntity, M : ModifiableWorkspaceEntity<E>>(
val entityClass: KClass<E>,
val modifiableEntityClass: KClass<M>,
val propertyName: String,
val modificator: M.(VirtualFileUrl, VirtualFileUrl) -> Unit
) : LegacyFileWatcher {
override fun onVfsChange(oldUrl: String, newUrl: String, entitiesWithVFU: List<EntityWithVirtualFileUrl>, virtualFileManager: VirtualFileUrlManager,
diff: WorkspaceEntityStorageBuilder) {
entitiesWithVFU.filter { entityClass.isInstance(it.entity) && it.propertyName == propertyName }.forEach { entityWithVFU ->
val existingVirtualFileUrl = entityWithVFU.virtualFileUrl
val savedUrl = existingVirtualFileUrl.url
val newTrackedUrl = newUrl + savedUrl.substring(oldUrl.length)
val newContainer = virtualFileManager.fromUrl(newTrackedUrl)
@Suppress("UNCHECKED_CAST")
entityWithVFU.entity as E
diff.modifyEntity(modifiableEntityClass.java, entityWithVFU.entity) {
this.modificator(existingVirtualFileUrl, newContainer)
}
}
}
}
/**
* It's responsible for updating complex case than [VirtualFileUrl] contains not in the entity itself but in internal data class.
* This is about LibraryEntity -> roots (LibraryRoot) -> url (VirtualFileUrl).
*/
private class LibraryRootFileWatcher: LegacyFileWatcher {
private val propertyName = LibraryEntity::roots.name
override fun onVfsChange(oldUrl: String, newUrl: String, entitiesWithVFU: List<EntityWithVirtualFileUrl>, virtualFileManager: VirtualFileUrlManager,
diff: WorkspaceEntityStorageBuilder) {
entitiesWithVFU.filter { LibraryEntity::class.isInstance(it.entity) && it.propertyName == propertyName }.forEach { entityWithVFU ->
val oldVFU = entityWithVFU.virtualFileUrl
val newVFU = virtualFileManager.fromUrl(newUrl + oldVFU.url.substring(oldUrl.length))
entityWithVFU.entity as LibraryEntity
val oldLibraryRoots = diff.resolve(entityWithVFU.entity.persistentId())?.roots?.filter { it.url == oldVFU }
?: error("Incorrect state of the VFU index")
oldLibraryRoots.forEach { oldLibraryRoot ->
val newLibraryRoot = LibraryRoot(newVFU, oldLibraryRoot.type, oldLibraryRoot.inclusionOptions)
diff.modifyEntity(ModifiableLibraryEntity::class.java, entityWithVFU.entity) {
roots = roots - oldLibraryRoot
roots = roots + newLibraryRoot
}
}
}
}
} | apache-2.0 | 56d07eed97a31b6401085fa898c05cc7 | 47.057895 | 150 | 0.742826 | 5.496689 | false | false | false | false |
allotria/intellij-community | plugins/github/src/org/jetbrains/plugins/github/pullrequest/ui/changes/GHPRChangesTreeFactory.kt | 2 | 2840 | // 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 org.jetbrains.plugins.github.pullrequest.ui.changes
import com.intellij.openapi.actionSystem.ActionGroup
import com.intellij.openapi.actionSystem.ActionManager
import com.intellij.openapi.actionSystem.DefaultActionGroup
import com.intellij.openapi.actionSystem.IdeActions
import com.intellij.openapi.project.Project
import com.intellij.openapi.vcs.changes.Change
import com.intellij.openapi.vcs.changes.ui.ChangesTree
import com.intellij.openapi.vcs.changes.ui.TreeActionsToolbarPanel
import com.intellij.openapi.vcs.changes.ui.TreeModelBuilder
import com.intellij.openapi.vcs.changes.ui.VcsTreeModelData
import com.intellij.ui.ExpandableItemsHandler
import com.intellij.ui.SelectionSaver
import com.intellij.util.ui.UIUtil
import com.intellij.util.ui.tree.TreeUtil
import org.jetbrains.plugins.github.ui.util.SingleValueModel
import java.awt.event.FocusAdapter
import java.awt.event.FocusEvent
import javax.swing.JComponent
internal class GHPRChangesTreeFactory(private val project: Project,
private val changesModel: SingleValueModel<out Collection<Change>>) {
fun create(emptyTextText: String): ChangesTree {
val tree = object : ChangesTree(project, false, false) {
override fun rebuildTree() {
updateTreeModel(TreeModelBuilder(project, grouping).setChanges(changesModel.value, null).build())
if (isSelectionEmpty && !isEmpty) TreeUtil.selectFirstNode(this)
}
override fun getData(dataId: String) = super.getData(dataId) ?: VcsTreeModelData.getData(project, this, dataId)
}.apply {
emptyText.text = emptyTextText
}.also {
UIUtil.putClientProperty(it, ExpandableItemsHandler.IGNORE_ITEM_SELECTION, true)
SelectionSaver.installOn(it)
it.addFocusListener(object : FocusAdapter() {
override fun focusGained(e: FocusEvent?) {
if (it.isSelectionEmpty && !it.isEmpty) TreeUtil.selectFirstNode(it)
}
})
}
changesModel.addAndInvokeValueChangedListener(tree::rebuildTree)
return tree
}
companion object {
fun createTreeToolbar(actionManager: ActionManager, treeContainer: JComponent): JComponent {
val changesToolbarActionGroup = actionManager.getAction("Github.PullRequest.Changes.Toolbar") as ActionGroup
val changesToolbar = actionManager.createActionToolbar("ChangesBrowser", changesToolbarActionGroup, true)
val treeActionsGroup = DefaultActionGroup(actionManager.getAction(IdeActions.ACTION_EXPAND_ALL),
actionManager.getAction(IdeActions.ACTION_COLLAPSE_ALL))
return TreeActionsToolbarPanel(changesToolbar, treeActionsGroup, treeContainer)
}
}
} | apache-2.0 | 9928740b530076304d7d330fd54db176 | 47.152542 | 140 | 0.762676 | 4.678748 | false | false | false | false |
leafclick/intellij-community | platform/lang-impl/src/com/intellij/codeInsight/hints/presentation/BackgroundPresentation.kt | 1 | 842 | // 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.codeInsight.hints.presentation
import com.intellij.openapi.editor.markup.TextAttributes
import java.awt.Color
import java.awt.Graphics2D
/**
* Adds background color.
*/
class BackgroundPresentation(
presentation: InlayPresentation,
var color: Color? = null
) : StaticDelegatePresentation(presentation) {
override fun paint(g: Graphics2D, attributes: TextAttributes) {
val backgroundColor = color ?: attributes.backgroundColor
val oldColor = g.color
if (backgroundColor != null) {
g.color = backgroundColor
g.fillRect(0, 0, width, height)
}
try {
presentation.paint(g, attributes)
} finally {
g.color = oldColor
}
}
} | apache-2.0 | 5f6c208ea39672666e3fbcd62a418756 | 29.107143 | 140 | 0.720903 | 4.127451 | false | false | false | false |
romannurik/muzei | source-gallery/src/main/java/com/google/android/apps/muzei/gallery/ChosenPhotoDao.kt | 2 | 11222 | /*
* Copyright 2017 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.muzei.gallery
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Binder
import android.os.Build
import android.provider.DocumentsContract
import android.util.Log
import androidx.lifecycle.LiveData
import androidx.paging.PagingSource
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import androidx.room.Transaction
import com.google.android.apps.muzei.api.provider.ProviderContract
import com.google.android.apps.muzei.gallery.BuildConfig.GALLERY_ART_AUTHORITY
import kotlinx.coroutines.async
import kotlinx.coroutines.awaitAll
import kotlinx.coroutines.coroutineScope
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.util.Date
/**
* Dao for [ChosenPhoto]
*/
@Dao
internal abstract class ChosenPhotoDao {
companion object {
private const val TAG = "ChosenPhotoDao"
}
@get:Query("SELECT * FROM chosen_photos ORDER BY _id DESC")
internal abstract val chosenPhotosPaged: PagingSource<Int, ChosenPhoto>
@get:Query("SELECT * FROM chosen_photos ORDER BY _id DESC")
internal abstract val chosenPhotosLiveData: LiveData<List<ChosenPhoto>>
@get:Query("SELECT * FROM chosen_photos ORDER BY _id DESC")
internal abstract val chosenPhotosBlocking: List<ChosenPhoto>
@Insert(onConflict = OnConflictStrategy.REPLACE)
internal abstract suspend fun insertInternal(chosenPhoto: ChosenPhoto): Long
@Transaction
open suspend fun insert(
context: Context,
chosenPhoto: ChosenPhoto,
callingApplication: String?
): Long = if (persistUriAccess(context, chosenPhoto)) {
val id = insertInternal(chosenPhoto)
if (id != 0L && callingApplication != null) {
val metadata = Metadata(ChosenPhoto.getContentUri(id), Date(),
context.getString(R.string.gallery_shared_from, callingApplication))
GalleryDatabase.getInstance(context).metadataDao().insert(metadata)
}
GalleryScanWorker.enqueueInitialScan(context, listOf(id))
id
} else {
0L
}
@Insert(onConflict = OnConflictStrategy.REPLACE)
internal abstract suspend fun insertAllInternal(chosenPhoto: List<ChosenPhoto>): List<Long>
@Transaction
open suspend fun insertAll(context: Context, uris: Collection<Uri>) {
insertAllInternal(uris
.map { ChosenPhoto(it) }
.filter { persistUriAccess(context, it) }
).run {
if (isNotEmpty()) {
GalleryScanWorker.enqueueInitialScan(context, this)
}
}
}
private fun persistUriAccess(context: Context, chosenPhoto: ChosenPhoto): Boolean {
chosenPhoto.isTreeUri = isTreeUri(chosenPhoto.uri)
if (chosenPhoto.isTreeUri) {
try {
context.contentResolver.takePersistableUriPermission(chosenPhoto.uri,
Intent.FLAG_GRANT_READ_URI_PERMISSION)
} catch (ignored: SecurityException) {
// You can't persist URI permissions from your own app, so this fails.
// We'll still have access to it directly
}
} else {
val haveUriPermission = context.checkUriPermission(chosenPhoto.uri,
Binder.getCallingPid(), Binder.getCallingUid(),
Intent.FLAG_GRANT_READ_URI_PERMISSION) == PackageManager.PERMISSION_GRANTED
// If we only have permission to this URI via URI permissions (rather than directly,
// such as if the URI is from our own app), it is from an external source and we need
// to make sure to gain persistent access to the URI's content
if (haveUriPermission) {
var persistedPermission = false
// Try to persist access to the URI, saving us from having to store a local copy
if (DocumentsContract.isDocumentUri(context, chosenPhoto.uri)) {
try {
context.contentResolver.takePersistableUriPermission(chosenPhoto.uri,
Intent.FLAG_GRANT_READ_URI_PERMISSION)
persistedPermission = true
// If we have a persisted URI permission, we don't need a local copy
val cachedFile = GalleryProvider.getCacheFileForUri(context, chosenPhoto.uri)
if (cachedFile?.exists() == true) {
if (!cachedFile.delete()) {
Log.w(TAG, "Unable to delete $cachedFile")
}
}
} catch (ignored: SecurityException) {
// If we don't have FLAG_GRANT_PERSISTABLE_URI_PERMISSION (such as when using ACTION_GET_CONTENT),
// this will fail. We'll need to make a local copy (handled below)
}
}
if (!persistedPermission) {
// We only need to make a local copy if we weren't able to persist the permission
try {
writeUriToFile(context, chosenPhoto.uri,
GalleryProvider.getCacheFileForUri(context, chosenPhoto.uri))
} catch (e: IOException) {
Log.e(TAG, "Error downloading gallery image ${chosenPhoto.uri}", e)
return false
}
}
}
}
return true
}
private fun isTreeUri(possibleTreeUri: Uri): Boolean {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
return DocumentsContract.isTreeUri(possibleTreeUri)
} else {
try {
// Prior to N we can't directly check if the URI is a tree URI, so we have to just try it
val treeDocumentId = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
DocumentsContract.getTreeDocumentId(possibleTreeUri)
} else {
// No tree URIs prior to Lollipop
return false
}
return treeDocumentId?.isNotEmpty() == true
} catch (e: IllegalArgumentException) {
// Definitely not a tree URI
return false
}
}
}
@Throws(IOException::class)
private fun writeUriToFile(context: Context, uri: Uri, destFile: File?) {
if (destFile == null) {
throw IOException("Invalid destination for $uri")
}
try {
context.contentResolver.openInputStream(uri)?.use { input ->
FileOutputStream(destFile).use { out ->
input.copyTo(out)
}
}
} catch (e: SecurityException) {
throw IOException("Unable to read Uri: $uri", e)
} catch (e: UnsupportedOperationException) {
throw IOException("Unable to read Uri: $uri", e)
}
}
@Query("SELECT * FROM chosen_photos WHERE _id = :id")
internal abstract fun chosenPhotoBlocking(id: Long): ChosenPhoto?
@Query("SELECT * FROM chosen_photos WHERE _id = :id")
abstract suspend fun getChosenPhoto(id: Long): ChosenPhoto?
@Query("SELECT * FROM chosen_photos WHERE _id IN (:ids)")
abstract suspend fun getChosenPhotos(ids: List<Long>): List<ChosenPhoto>
@Query("DELETE FROM chosen_photos WHERE _id IN (:ids)")
internal abstract suspend fun deleteInternal(ids: List<Long>)
@Transaction
open suspend fun delete(context: Context, ids: List<Long>) {
deleteBackingPhotos(context, getChosenPhotos(ids))
deleteInternal(ids)
}
@Query("DELETE FROM chosen_photos")
internal abstract suspend fun deleteAllInternal()
@Transaction
open suspend fun deleteAll(context: Context) {
deleteBackingPhotos(context, chosenPhotosBlocking)
deleteAllInternal()
}
/**
* We can't just simply delete the rows as that won't free up the space occupied by the
* chosen image files for each row being deleted. Instead we have to query
* and manually delete each chosen image file
*/
private suspend fun deleteBackingPhotos(
context: Context,
chosenPhotos: List<ChosenPhoto>
) = coroutineScope {
chosenPhotos.map { chosenPhoto ->
async {
val contentUri = ProviderContract.getContentUri(GALLERY_ART_AUTHORITY)
context.contentResolver.delete(contentUri,
"${ProviderContract.Artwork.METADATA}=?",
arrayOf(chosenPhoto.uri.toString()))
val file = GalleryProvider.getCacheFileForUri(context, chosenPhoto.uri)
if (file?.exists() == true) {
if (!file.delete()) {
Log.w(TAG, "Unable to delete $file")
}
} else {
val uriToRelease = chosenPhoto.uri
val contentResolver = context.contentResolver
val haveUriPermission = context.checkUriPermission(uriToRelease,
Binder.getCallingPid(), Binder.getCallingUid(),
Intent.FLAG_GRANT_READ_URI_PERMISSION) == PackageManager.PERMISSION_GRANTED
if (haveUriPermission) {
// Try to release any persisted URI permission for the imageUri
val persistedUriPermissions = contentResolver.persistedUriPermissions
for (persistedUriPermission in persistedUriPermissions) {
if (persistedUriPermission.uri == uriToRelease) {
try {
contentResolver.releasePersistableUriPermission(
uriToRelease, Intent.FLAG_GRANT_READ_URI_PERMISSION)
} catch (e: SecurityException) {
// Thrown if we don't have permission...despite in being in
// the getPersistedUriPermissions(). Alright then.
}
break
}
}
}
}
}
}.awaitAll()
}
}
| apache-2.0 | 3364cb9978e2d661e86cf9158cedd46f | 41.832061 | 122 | 0.595794 | 5.253745 | false | false | false | false |
leafclick/intellij-community | platform/lang-impl/src/com/intellij/ide/ui/TargetPresentationRightRenderer.kt | 1 | 1988 | // 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.ide.ui
import com.intellij.navigation.TargetPopupPresentation
import com.intellij.ui.components.JBLabel
import com.intellij.ui.speedSearch.SearchAwareRenderer
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.UIUtil
import org.jetbrains.annotations.ApiStatus.Experimental
import java.awt.Component
import javax.swing.JList
import javax.swing.ListCellRenderer
import javax.swing.SwingConstants
@Experimental
internal abstract class TargetPresentationRightRenderer<T> : ListCellRenderer<T>, SearchAwareRenderer<T> {
companion object {
private val ourBorder = JBUI.Borders.emptyRight(UIUtil.getListCellHPadding())
}
protected abstract fun getPresentation(value: T): TargetPopupPresentation?
private val component = JBLabel().apply {
border = ourBorder
horizontalTextPosition = SwingConstants.LEFT
horizontalAlignment = SwingConstants.RIGHT // align icon to the right
}
final override fun getItemSearchString(item: T): String? = getPresentation(item)?.locationText
final override fun getListCellRendererComponent(list: JList<out T>,
value: T,
index: Int,
isSelected: Boolean,
cellHasFocus: Boolean): Component {
component.apply {
text = ""
icon = null
background = UIUtil.getListBackground(isSelected)
foreground = if (isSelected) UIUtil.getListSelectionForeground() else UIUtil.getInactiveTextColor()
font = list.font
}
getPresentation(value)?.let { presentation ->
presentation.rightText?.let { rightText ->
component.text = rightText
component.icon = presentation.rightIcon
}
}
return component
}
}
| apache-2.0 | 5ddb61c7f7946fe445f48d2664112d6f | 37.230769 | 140 | 0.685614 | 5.190601 | false | false | false | false |
code-helix/slatekit | src/lib/kotlin/slatekit-common/src/main/kotlin/slatekit/common/DateTime.kt | 1 | 10117 | /**
* <slate_header>
* url: www.slatekit.com
* git: www.github.com/code-helix/slatekit
* org: www.codehelix.co
* author: Kishore Reddy
* copyright: 2016 CodeHelix Solutions Inc.
* license: refer to website and/or github
* about: A tool-kit, utility library and server-backend
* mantra: Simplicity above all else
* </slate_header>
*/
package slatekit.common
//import java.time.*
import org.threeten.bp.*
import org.threeten.bp.format.DateTimeFormatter
import slatekit.common.ext.atStartOfMonth
import slatekit.common.ext.daysInMonth
import slatekit.common.checks.Check
import java.util.*
/**
* Currently a typealias for the ThreeTenBP ZonedDateTime
* The slatekit.common uses this datetime library instead of Java 8 because:
* 1. slatekit.common is used for android projects
* 2. targets android projects prior to API 26
* 3. Java 8 datetime APIs are not available in android devices older than API 26
*/
typealias DateTime = ZonedDateTime
/**
* DateTimes provides some convenient "static" functions
*
* See the extension methods on the DateTime ( ZonedDateTime )
* which essentially just add additional convenience functions
* for conversion, formatting methods
*
*
* FEATURES
* 1. Zoned : Always uses ZonedDateTime
* 2. Simpler : Simpler usage of Dates/Times/Zones
* 3. Conversion : Simpler conversion to/from time zones
* 4. Idiomatic : Idiomatic way to use DateTime in kotlin
*
*
* EXAMPLES:
* Construction:
* - DateTime.now()
* - DateTime.today()
* - DateTime.of(2017, 7, 1)
*
*
* UTC:
* - val d = DateTime.nowUtc()
* - val d = DateTime.nowAt("Europe/Athens")
*
*
* Conversion
* - val now = DateTime.now()
* - val utc = now.atUtc()
* - val utcl = now.atUtcLocal()
* - val athens = now.at("Europe/Athens")
* - val date = now.date()
* - val time = now.time()
* - val local = now.local()
*
*
* IDIOMATIC
* - val now = DateTime.now()
* - val later = now() + 3.days
* - val before = now() - 3.minutes
* - val duration = now() - later
* - val seconds = now().secondsTo( later )
* - val minutes = now().minutesTo( later )
*
*
* Formatting
* - val now = DateTime.now()
* - val txt = now.toStringYYYYMMDD("-")
* - val txt = now.toStringMMDDYYYY("/")
* - val txt = now.toStringTime(":")
* - val txt = now.toStringNumeric("-")
*
*
*/
class DateTimes {
companion object {
val ZONE = ZoneId.systemDefault()
@JvmStatic
val UTC: ZoneId = ZoneId.of("UTC")
@JvmStatic
val MIN: DateTime = LocalDateTime.MIN.atZone(ZoneId.systemDefault())
@JvmStatic
fun of(d: LocalDateTime): ZonedDateTime = ZonedDateTime.of(d, ZoneId.systemDefault())
@JvmStatic
fun of(d: Date): DateTime = build(d, ZoneId.systemDefault())
@JvmStatic
fun of(d: Date, zoneId: ZoneId): DateTime = build(d, zoneId)
@JvmStatic
fun of(d: LocalDate): DateTime = build(d.year, d.month.value, d.dayOfMonth, zoneId = ZoneId.systemDefault())
/**
* Builds a DateTime ( ZonedDateTime of system zone ) using explicit values.
*/
@JvmStatic
fun of(
year: Int,
month: Int,
day: Int,
hours: Int = 0,
minutes: Int = 0,
seconds: Int = 0,
nano: Int = 0,
zone: String = ""
): DateTime {
val zoneId = if (zone.isNullOrEmpty()) ZoneId.systemDefault() else ZoneId.of(zone)
return build(year, month, day, hours, minutes, seconds, nano, zoneId)
}
/**
* Builds a DateTime ( ZonedDateTime of system zone ) using explicit values.
*/
@JvmStatic
fun of(
year: Int,
month: Int,
day: Int,
hours: Int = 0,
minutes: Int = 0,
seconds: Int = 0,
nano: Int = 0,
zoneId: ZoneId
): DateTime {
return build(year, month, day, hours, minutes, seconds, nano, zoneId)
}
@JvmStatic
fun build(d: LocalDateTime): ZonedDateTime = d.atZone(ZoneId.systemDefault())
@JvmStatic
fun build(date: Date, zone: ZoneId): ZonedDateTime {
//val dateTime = ZonedDateTime.ofInstant(date.toInstant(), zone)
//val date = Instant.ofEpochMilli(date.toInstant().toEpochMilli()))
val calendar = java.util.GregorianCalendar()
calendar.time = date
val year = calendar.get(Calendar.YEAR)
val month = calendar.get(Calendar.MONTH) + 1
val day = calendar.get(Calendar.DAY_OF_MONTH)
val hour = calendar.get(Calendar.HOUR_OF_DAY)
val min = calendar.get(Calendar.MINUTE)
val sec = calendar.get(Calendar.SECOND)
val dateTime = ZonedDateTime.of(year, month, day, hour, min, sec, 0, zone)
return dateTime
}
/**
* Builds a DateTime ( ZonedDateTime of system zone ) using explicit values.
*/
@JvmStatic
fun build(
year: Int,
month: Int,
day: Int,
hours: Int = 0,
minutes: Int = 0,
seconds: Int = 0,
nano: Int = 0,
zoneId: ZoneId
): ZonedDateTime {
return ZonedDateTime.of(year, month, day, hours, minutes, seconds, nano, zoneId)
}
/**
* Builds a DateTime ( ZonedDateTime of system zone ) with current date/time.
*/
@JvmStatic
fun now(): DateTime = ZonedDateTime.now()
/**
* Builds a DateTime ( ZonedDateTime of UTC ) with current date/time.
*/
@JvmStatic
fun nowUtc(): DateTime = ZonedDateTime.now(ZoneId.of("UTC"))
/**
* Builds a DateTime ( ZonedDateTime of UTC ) with current date/time.
*/
@JvmStatic
fun nowAt(zone: String): DateTime = ZonedDateTime.now(ZoneId.of(zone))
/**
* Builds a DateTime ( ZonedDateTime of UTC ) with current date/time.
*/
@JvmStatic
fun nowAt(zone: ZoneId): DateTime = ZonedDateTime.now(zone)
@JvmStatic
fun today(): DateTime {
val now = ZonedDateTime.now()
return of(now.year, now.month.value, now.dayOfMonth)
}
@JvmStatic
fun tomorrow(): DateTime = today().plusDays(1)
@JvmStatic
fun yesterday(): DateTime = today().plusDays(-1)
@JvmStatic
fun daysAgo(days: Long): DateTime = today().plusDays(-1 * days)
@JvmStatic
fun daysFromNow(days: Long): DateTime = today().plusDays(days)
@JvmStatic
fun parse(value: String): DateTime {
// 20190101 ( jan 1 ) 8 chars
// 201901011200 ( jan 1 @12pm ) 12 chars
// 20190101123045 ( jan 1 @12:30:45 pm) 14 chars
if((value.length == 8 || value.length == 12 || value.length == 14) && Check.isNumeric(value)){
return parseNumeric(value)
}
val dt = DateTime.parse(value)
return dt
}
@JvmStatic
fun parseISO(value: String): DateTime {
return DateTime.parse(value, DateTimeFormatter.ISO_OFFSET_DATE_TIME)
}
fun daysInMonth(month:Int, year:Int) : Int {
return Month.of(month).daysInMonth(year)
}
fun startOfCurrentMonth():DateTime {
return DateTimes.now().atStartOfMonth()
}
/** Gets the start of the current days month.
* @return
*/
@JvmStatic
fun closestNextHour(): DateTime {
val now = DateTime.now()
if (now.minute < 30) {
return DateTime.of(now.year, now.monthValue, now.dayOfMonth, now.hour, 30, 0, 0, now.zone)
}
val next = DateTime.of(now.year, now.monthValue, now.dayOfMonth, now.hour, 0, 0, 0, now.zone)
return next.plusHours(1)
}
@JvmStatic
fun parse(text: String, formatter: DateTimeFormatter): DateTime {
val zonedDt = ZonedDateTime.parse(text, formatter)
return zonedDt
}
@JvmStatic
fun parseNumeric(value: String): DateTime {
val text = value.trim()
// Check 1: Empty string ?
val res = if (text.isNullOrEmpty()) {
DateTimes.MIN
} else if (text == "0") {
DateTimes.MIN
}
// Check 2: Date only - no time ?
// yyyymmdd = 8 chars
else if (text.length == 8) {
DateTimes.of(LocalDate.parse(text, DateTimeFormatter.ofPattern("yyyyMMdd")))
}
// Check 3: Date with time
// yyyymmddhhmm = 12chars
else if (text.length == 12) {
val years = text.substring(0, 4).toInt()
val months = text.substring(4, 6).toInt()
val days = text.substring(6, 8).toInt()
val hrs = text.substring(8, 10).toInt()
val mins = text.substring(10, 12).toInt()
val date = of(years, months, days, hrs, mins, 0)
date
}
// Check 4: Date with time with seconds
// yyyymmddhhmmss = 14chars
else if (text.length == 14) {
val years = text.substring(0, 4).toInt()
val months = text.substring(4, 6).toInt()
val days = text.substring(6, 8).toInt()
val hrs = text.substring(8, 10).toInt()
val mins = text.substring(10, 12).toInt()
val secs = text.substring(12, 14).toInt()
val date = of(years, months, days, hrs, mins, secs)
date
} else {
// Unexpected
DateTimes.MIN
}
return res
}
}
}
| apache-2.0 | fbbc9b9fab437e83df6564a913e71e40 | 31.015823 | 116 | 0.547099 | 4.234826 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/formatter/ElvisWithOperationReference.kt | 13 | 464 | infix fun String.concat(other: String): String = this
fun binaryContext(anchor: String?) {
val v1 = "1234567890... add many chars ...1234567890" concat "b"
val v2 = anchor ?: "1234567890... add many chars ...1234567890" concat "b"
val v3 = anchor ?: "1234567890... add many chars ...1234567890" concat "1234567890... add many chars ...1234567890" concat "1234567890... add many chars ...1234567890" concat "b"
}
// SET_INT: WRAP_ELVIS_EXPRESSIONS = 2
| apache-2.0 | 1a11583cee218e172f5ac7320d02cc52 | 57 | 182 | 0.681034 | 3.932203 | false | false | false | false |
smmribeiro/intellij-community | plugins/git4idea/src/git4idea/light/LightGitStatusBarWidget.kt | 1 | 2931 | // 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 git4idea.light
import com.intellij.ide.lightEdit.LightEdit
import com.intellij.ide.lightEdit.LightEditCompatible
import com.intellij.ide.lightEdit.LightEditService
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.text.HtmlBuilder
import com.intellij.openapi.wm.StatusBar
import com.intellij.openapi.wm.StatusBarWidget
import com.intellij.openapi.wm.StatusBarWidgetFactory
import com.intellij.util.Consumer
import git4idea.i18n.GitBundle
import java.awt.Component
import java.awt.event.MouseEvent
private const val ID = "light.edit.git"
private val LOG = Logger.getInstance("#git4idea.light.LightGitStatusBarWidget")
private class LightGitStatusBarWidget(private val lightGitTracker: LightGitTracker) : StatusBarWidget, StatusBarWidget.TextPresentation {
private var statusBar: StatusBar? = null
init {
lightGitTracker.addUpdateListener(object : LightGitTrackerListener {
override fun update() {
statusBar?.updateWidget(ID())
}
}, this)
}
override fun ID(): String = ID
override fun install(statusBar: StatusBar) {
this.statusBar = statusBar
}
override fun getPresentation(): StatusBarWidget.WidgetPresentation = this
override fun getText(): String {
return lightGitTracker.currentLocation?.let { GitBundle.message("git.light.status.bar.text", it) } ?: ""
}
override fun getTooltipText(): String {
val locationText = lightGitTracker.currentLocation?.let { GitBundle.message("git.light.status.bar.tooltip", it) } ?: ""
if (locationText.isBlank()) return locationText
val selectedFile = LightEditService.getInstance().selectedFile
if (selectedFile != null) {
val statusText = lightGitTracker.getFileStatus(selectedFile).getPresentation()
if (statusText.isNotBlank()) return HtmlBuilder().append(locationText).br().append(statusText).toString()
}
return locationText
}
override fun getAlignment(): Float = Component.LEFT_ALIGNMENT
override fun getClickConsumer(): Consumer<MouseEvent>? = null
override fun dispose() = Unit
}
class LightGitStatusBarWidgetFactory: StatusBarWidgetFactory, LightEditCompatible {
override fun getId(): String = ID
override fun getDisplayName(): String = GitBundle.message("git.light.status.bar.display.name")
override fun isAvailable(project: Project): Boolean = LightEdit.owns(project)
override fun createWidget(project: Project): StatusBarWidget {
LOG.assertTrue(LightEdit.owns(project))
return LightGitStatusBarWidget(LightGitTracker.getInstance())
}
override fun disposeWidget(widget: StatusBarWidget) = Disposer.dispose(widget)
override fun canBeEnabledOn(statusBar: StatusBar): Boolean = true
} | apache-2.0 | bc661b9cca76fcb2eb65399f1fa5dda5 | 36.113924 | 140 | 0.773456 | 4.659777 | false | false | false | false |
smmribeiro/intellij-community | plugins/markdown/core/src/org/intellij/plugins/markdown/ui/floating/FloatingToolbar.kt | 1 | 6695 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.intellij.plugins.markdown.ui.floating
import com.intellij.codeInsight.hint.HintManager
import com.intellij.codeInsight.hint.HintManagerImpl
import com.intellij.openapi.Disposable
import com.intellij.openapi.actionSystem.ActionGroup
import com.intellij.openapi.actionSystem.ActionManager
import com.intellij.openapi.actionSystem.ActionPlaces
import com.intellij.openapi.actionSystem.ActionToolbar
import com.intellij.openapi.actionSystem.impl.ActionToolbarImpl
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.event.EditorMouseEvent
import com.intellij.openapi.editor.event.EditorMouseListener
import com.intellij.openapi.editor.event.EditorMouseMotionListener
import com.intellij.psi.PsiDocumentManager
import com.intellij.psi.PsiElement
import com.intellij.psi.util.PsiEditorUtil
import com.intellij.psi.util.PsiUtilCore
import com.intellij.psi.util.elementType
import com.intellij.psi.util.parents
import com.intellij.ui.LightweightHint
import org.intellij.plugins.markdown.lang.MarkdownElementTypes
import org.intellij.plugins.markdown.lang.psi.impl.MarkdownFile
import org.jetbrains.annotations.ApiStatus
import java.awt.Point
import java.awt.event.KeyAdapter
import java.awt.event.KeyEvent
import javax.swing.JComponent
import kotlin.properties.Delegates
@ApiStatus.Internal
open class FloatingToolbar(val editor: Editor, private val actionGroupId: String) : Disposable {
private val mouseListener = MouseListener()
private val keyboardListener = KeyboardListener()
private val mouseMotionListener = MouseMotionListener()
private var hint: LightweightHint? = null
private var buttonSize: Int by Delegates.notNull()
private var lastSelection: String? = null
init {
registerListeners()
}
fun isShown() = hint != null
fun hideIfShown() {
hint?.hide()
}
fun showIfHidden() {
if (hint != null || !canBeShownAtCurrentSelection()) {
return
}
val toolbar = createActionToolbar(editor.contentComponent)
buttonSize = toolbar.maxButtonHeight
val newHint = LightweightHint(toolbar.component)
newHint.setForceShowAsPopup(true)
showOrUpdateLocation(newHint)
newHint.addHintListener { this.hint = null }
this.hint = newHint
}
fun updateLocationIfShown() {
showOrUpdateLocation(hint ?: return)
}
override fun dispose() {
unregisterListeners()
hideIfShown()
hint = null
}
private fun createActionToolbar(targetComponent: JComponent): ActionToolbar {
val group = ActionManager.getInstance().getAction(actionGroupId) as ActionGroup
val toolbar = object: ActionToolbarImpl(ActionPlaces.EDITOR_TOOLBAR, group, true) {
override fun addNotify() {
super.addNotify()
updateActionsImmediately(true)
}
}
toolbar.targetComponent = targetComponent
toolbar.setReservePlaceAutoPopupIcon(false)
return toolbar
}
private fun showOrUpdateLocation(hint: LightweightHint) {
HintManagerImpl.getInstanceImpl().showEditorHint(
hint,
editor,
getHintPosition(hint),
HintManager.HIDE_BY_ESCAPE or HintManager.UPDATE_BY_SCROLLING,
0,
true
)
}
private fun registerListeners() {
editor.addEditorMouseListener(mouseListener)
editor.addEditorMouseMotionListener(mouseMotionListener)
editor.contentComponent.addKeyListener(keyboardListener)
}
private fun unregisterListeners() {
editor.removeEditorMouseListener(mouseListener)
editor.removeEditorMouseMotionListener(mouseMotionListener)
editor.contentComponent.removeKeyListener(keyboardListener)
}
private fun canBeShownAtCurrentSelection(): Boolean {
val file = PsiEditorUtil.getPsiFile(editor)
PsiDocumentManager.getInstance(file.project).commitDocument(editor.document)
val selectionModel = editor.selectionModel
val elementAtStart = PsiUtilCore.getElementAtOffset(file, selectionModel.selectionStart)
val elementAtEnd = PsiUtilCore.getElementAtOffset(file, selectionModel.selectionEnd)
return !(hasIgnoredParent(elementAtStart) || hasIgnoredParent(elementAtEnd))
}
protected open fun hasIgnoredParent(element: PsiElement): Boolean {
if (element.containingFile !is MarkdownFile) {
return true
}
return element.parents(withSelf = true).any { it.elementType in elementsToIgnore }
}
private fun getHintPosition(hint: LightweightHint): Point {
val hintPos = HintManagerImpl.getInstanceImpl().getHintPosition(hint, editor, HintManager.DEFAULT)
// because of `hint.setForceShowAsPopup(true)`, HintManager.ABOVE does not place the hint above
// the hint remains on the line, so we need to move it up ourselves
val dy = -(hint.component.preferredSize.height + verticalGap)
val dx = buttonSize * -2
hintPos.translate(dx, dy)
return hintPos
}
private fun updateOnProbablyChangedSelection(onSelectionChanged: (String) -> Unit) {
val newSelection = editor.selectionModel.selectedText
when (newSelection) {
null -> hideIfShown()
lastSelection -> Unit
else -> onSelectionChanged(newSelection)
}
lastSelection = newSelection
}
private inner class MouseListener : EditorMouseListener {
override fun mouseReleased(e: EditorMouseEvent) {
updateOnProbablyChangedSelection {
if (isShown()) {
updateLocationIfShown()
} else {
showIfHidden()
}
}
}
}
private inner class KeyboardListener : KeyAdapter() {
override fun keyReleased(e: KeyEvent) {
super.keyReleased(e)
if (e.source != editor.contentComponent) {
return
}
updateOnProbablyChangedSelection {
hideIfShown()
}
}
}
private inner class MouseMotionListener : EditorMouseMotionListener {
override fun mouseMoved(e: EditorMouseEvent) {
val visualPosition = e.visualPosition
val hoverSelected = editor.caretModel.allCarets.any {
val beforeSelectionEnd = it.selectionEndPosition.after(visualPosition)
val afterSelectionStart = visualPosition.after(it.selectionStartPosition)
beforeSelectionEnd && afterSelectionStart
}
if (hoverSelected) {
showIfHidden()
}
}
}
companion object {
private const val verticalGap = 2
private val elementsToIgnore = listOf(
MarkdownElementTypes.CODE_FENCE,
MarkdownElementTypes.CODE_BLOCK,
MarkdownElementTypes.CODE_SPAN,
MarkdownElementTypes.HTML_BLOCK,
MarkdownElementTypes.LINK_DESTINATION
)
}
}
| apache-2.0 | aed5a85817ea44636fd05bc8f6c0c707 | 32.475 | 158 | 0.749216 | 4.854967 | false | false | false | false |
smmribeiro/intellij-community | platform/lang-impl/src/com/intellij/util/indexing/roots/IndexableSetContributorFilesIterator.kt | 4 | 2728 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.util.indexing.roots
import com.intellij.navigation.ItemPresentation
import com.intellij.openapi.application.runReadAction
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.ContentIterator
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.vfs.VirtualFileFilter
import com.intellij.util.indexing.IndexableSetContributor
import com.intellij.util.indexing.IndexingBundle
import com.intellij.util.indexing.roots.origin.IndexableSetContributorOriginImpl
import com.intellij.util.indexing.roots.kind.IndexableSetOrigin
internal class IndexableSetContributorFilesIterator(private val indexableSetContributor: IndexableSetContributor,
private val projectAware: Boolean) : IndexableFilesIterator {
override fun getDebugName(): String {
val debugName = getName()?.takeUnless { it.isEmpty() } ?: indexableSetContributor.debugName
return "Indexable set contributor '$debugName' ${if (projectAware) "(project)" else "(non-project)"}"
}
override fun getIndexingProgressText(): String {
val name = getName()
if (!name.isNullOrEmpty()) {
return IndexingBundle.message("indexable.files.provider.indexing.named.provider", name)
}
return IndexingBundle.message("indexable.files.provider.indexing.additional.dependencies")
}
override fun getRootsScanningProgressText(): String {
val name = getName()
if (!name.isNullOrEmpty()) {
return IndexingBundle.message("indexable.files.provider.scanning.files.contributor", name)
}
return IndexingBundle.message("indexable.files.provider.scanning.additional.dependencies")
}
override fun getOrigin(): IndexableSetOrigin = IndexableSetContributorOriginImpl(indexableSetContributor)
private fun getName() = (indexableSetContributor as? ItemPresentation)?.presentableText
override fun iterateFiles(
project: Project,
fileIterator: ContentIterator,
fileFilter: VirtualFileFilter
): Boolean {
val allRoots = collectRoots(project)
return IndexableFilesIterationMethods.iterateRoots(project, allRoots, fileIterator, fileFilter, excludeNonProjectRoots = false)
}
private fun collectRoots(project: Project): MutableSet<VirtualFile> {
val allRoots = runReadAction {
if (projectAware) indexableSetContributor.getAdditionalProjectRootsToIndex(project)
else indexableSetContributor.additionalRootsToIndex
}
return allRoots
}
override fun getRootUrls(project: Project): Set<String> {
return collectRoots(project).map { it.url }.toSet()
}
} | apache-2.0 | b7e37408875e7324c17ed498a11679b7 | 42.31746 | 131 | 0.771628 | 4.969035 | false | false | false | false |
apgv/password-generator | src/main/kotlin/codes/foobar/passwd/domain/PasswordRegex.kt | 1 | 812 | package codes.foobar.passwd.domain
object PasswordRegex {
val A_Z_LOWER_REGEX = "a-z"
val A_Z_UPPER_REGEX = "A-Z"
val NUMBER_REGEX = "0-9"
val SPECIAL_REGEX = "!\"#$%&\\U+0027()*+,-./:;<=>?@[\\]^_`{|}~"
val FULL_REGEX = A_Z_LOWER_REGEX + A_Z_UPPER_REGEX + NUMBER_REGEX + SPECIAL_REGEX
fun pattern(options: Options) =
if (options.atLeastOneTrue()) {
regexOrEmpty(options.lowerCase, A_Z_LOWER_REGEX) +
regexOrEmpty(options.upperCase, A_Z_UPPER_REGEX) +
regexOrEmpty(options.numbers, NUMBER_REGEX) +
regexOrEmpty(options.special, SPECIAL_REGEX)
} else {
FULL_REGEX
}
private fun regexOrEmpty(b: Boolean, regex: String) = if (b) regex else ""
} | mit | affab41cb5bfcb45a157853fba5682f1 | 35.954545 | 85 | 0.549261 | 3.690909 | false | false | false | false |
MilosKozak/AndroidAPS | app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/MedtronicFragment.kt | 3 | 15378 | package info.nightscout.androidaps.plugins.pump.medtronic
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.os.Handler
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import info.nightscout.androidaps.MainApp
import info.nightscout.androidaps.R
import info.nightscout.androidaps.events.EventExtendedBolusChange
import info.nightscout.androidaps.events.EventPumpStatusChanged
import info.nightscout.androidaps.events.EventTempBasalChange
import info.nightscout.androidaps.logging.L
import info.nightscout.androidaps.plugins.bus.RxBus
import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.RileyLinkUtil
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.defs.RileyLinkError
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.defs.RileyLinkServiceState
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.defs.RileyLinkTargetDevice
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.dialog.RileyLinkStatusActivity
import info.nightscout.androidaps.plugins.pump.medtronic.defs.BatteryType
import info.nightscout.androidaps.plugins.pump.medtronic.defs.MedtronicCommandType
import info.nightscout.androidaps.plugins.pump.medtronic.defs.PumpDeviceState
import info.nightscout.androidaps.plugins.pump.medtronic.dialog.MedtronicHistoryActivity
import info.nightscout.androidaps.plugins.pump.medtronic.driver.MedtronicPumpStatus
import info.nightscout.androidaps.plugins.pump.medtronic.events.EventMedtronicDeviceStatusChange
import info.nightscout.androidaps.plugins.pump.medtronic.events.EventMedtronicPumpConfigurationChanged
import info.nightscout.androidaps.plugins.pump.medtronic.events.EventMedtronicPumpValuesChanged
import info.nightscout.androidaps.plugins.pump.medtronic.events.EventRefreshButtonState
import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicUtil
import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin
import info.nightscout.androidaps.queue.Callback
import info.nightscout.androidaps.queue.events.EventQueueChanged
import info.nightscout.androidaps.utils.*
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.CompositeDisposable
import kotlinx.android.synthetic.main.medtronic_fragment.*
import org.slf4j.LoggerFactory
class MedtronicFragment : Fragment() {
private val log = LoggerFactory.getLogger(L.PUMP)
private var disposable: CompositeDisposable = CompositeDisposable()
private val loopHandler = Handler()
private lateinit var refreshLoop: Runnable
init {
refreshLoop = Runnable {
activity?.runOnUiThread { updateGUI() }
loopHandler.postDelayed(refreshLoop, T.mins(1).msecs())
}
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.medtronic_fragment, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
medtronic_pumpstatus.setBackgroundColor(MainApp.gc(R.color.colorInitializingBorder))
medtronic_rl_status.text = MainApp.gs(RileyLinkServiceState.NotStarted.getResourceId(RileyLinkTargetDevice.MedtronicPump))
medtronic_pump_status.setTextColor(Color.WHITE)
medtronic_pump_status.text = "{fa-bed}"
medtronic_history.setOnClickListener {
if (MedtronicUtil.getPumpStatus().verifyConfiguration()) {
startActivity(Intent(context, MedtronicHistoryActivity::class.java))
} else {
MedtronicUtil.displayNotConfiguredDialog(context)
}
}
medtronic_refresh.setOnClickListener {
if (!MedtronicUtil.getPumpStatus().verifyConfiguration()) {
MedtronicUtil.displayNotConfiguredDialog(context)
} else {
medtronic_refresh.isEnabled = false
MedtronicPumpPlugin.getPlugin().resetStatusState()
ConfigBuilderPlugin.getPlugin().commandQueue.readStatus("Clicked refresh", object : Callback() {
override fun run() {
activity?.runOnUiThread { medtronic_refresh?.isEnabled = true }
}
})
}
}
medtronic_stats.setOnClickListener {
if (MedtronicUtil.getPumpStatus().verifyConfiguration()) {
startActivity(Intent(context, RileyLinkStatusActivity::class.java))
} else {
MedtronicUtil.displayNotConfiguredDialog(context)
}
}
}
@Synchronized
override fun onResume() {
super.onResume()
loopHandler.postDelayed(refreshLoop, T.mins(1).msecs())
disposable += RxBus
.toObservable(EventRefreshButtonState::class.java)
.observeOn(AndroidSchedulers.mainThread())
.subscribe({ medtronic_refresh.isEnabled = it.newState }, { FabricPrivacy.logException(it) })
disposable += RxBus
.toObservable(EventMedtronicDeviceStatusChange::class.java)
.observeOn(AndroidSchedulers.mainThread())
.subscribe({
if (L.isEnabled(L.PUMP))
log.info("onStatusEvent(EventMedtronicDeviceStatusChange): {}", it)
setDeviceStatus()
}, { FabricPrivacy.logException(it) })
disposable += RxBus
.toObservable(EventMedtronicPumpValuesChanged::class.java)
.observeOn(AndroidSchedulers.mainThread())
.subscribe({ updateGUI() }, { FabricPrivacy.logException(it) })
disposable += RxBus
.toObservable(EventExtendedBolusChange::class.java)
.observeOn(AndroidSchedulers.mainThread())
.subscribe({ updateGUI() }, { FabricPrivacy.logException(it) })
disposable += RxBus
.toObservable(EventTempBasalChange::class.java)
.observeOn(AndroidSchedulers.mainThread())
.subscribe({ updateGUI() }, { FabricPrivacy.logException(it) })
disposable += RxBus
.toObservable(EventMedtronicPumpConfigurationChanged::class.java)
.observeOn(AndroidSchedulers.mainThread())
.subscribe({
if (L.isEnabled(L.PUMP))
log.debug("EventMedtronicPumpConfigurationChanged triggered")
MedtronicUtil.getPumpStatus().verifyConfiguration()
updateGUI()
}, { FabricPrivacy.logException(it) })
disposable += RxBus
.toObservable(EventPumpStatusChanged::class.java)
.observeOn(AndroidSchedulers.mainThread())
.subscribe({ updateGUI() }, { FabricPrivacy.logException(it) })
disposable += RxBus
.toObservable(EventQueueChanged::class.java)
.observeOn(AndroidSchedulers.mainThread())
.subscribe({ updateGUI() }, { FabricPrivacy.logException(it) })
updateGUI()
}
@Synchronized
override fun onPause() {
super.onPause()
disposable.clear()
loopHandler.removeCallbacks(refreshLoop)
}
@Synchronized
private fun setDeviceStatus() {
val pumpStatus: MedtronicPumpStatus = MedtronicUtil.getPumpStatus()
pumpStatus.rileyLinkServiceState = checkStatusSet(pumpStatus.rileyLinkServiceState,
RileyLinkUtil.getServiceState()) as RileyLinkServiceState?
val resourceId = pumpStatus.rileyLinkServiceState.getResourceId(RileyLinkTargetDevice.MedtronicPump)
val rileyLinkError = RileyLinkUtil.getError()
medtronic_rl_status.text =
when {
pumpStatus.rileyLinkServiceState == RileyLinkServiceState.NotStarted -> MainApp.gs(resourceId)
pumpStatus.rileyLinkServiceState.isConnecting -> "{fa-bluetooth-b spin} " + MainApp.gs(resourceId)
pumpStatus.rileyLinkServiceState.isError && rileyLinkError == null -> "{fa-bluetooth-b} " + MainApp.gs(resourceId)
pumpStatus.rileyLinkServiceState.isError && rileyLinkError != null -> "{fa-bluetooth-b} " + MainApp.gs(rileyLinkError.getResourceId(RileyLinkTargetDevice.MedtronicPump))
else -> "{fa-bluetooth-b} " + MainApp.gs(resourceId)
}
medtronic_rl_status.setTextColor(if (rileyLinkError != null) Color.RED else Color.WHITE)
pumpStatus.rileyLinkError = checkStatusSet(pumpStatus.rileyLinkError, RileyLinkUtil.getError()) as RileyLinkError?
medtronic_errors.text =
pumpStatus.rileyLinkError?.let {
MainApp.gs(it.getResourceId(RileyLinkTargetDevice.MedtronicPump))
} ?: "-"
pumpStatus.pumpDeviceState = checkStatusSet(pumpStatus.pumpDeviceState,
MedtronicUtil.getPumpDeviceState()) as PumpDeviceState?
when (pumpStatus.pumpDeviceState) {
null,
PumpDeviceState.Sleeping -> medtronic_pump_status.text = "{fa-bed} " // + pumpStatus.pumpDeviceState.name());
PumpDeviceState.NeverContacted,
PumpDeviceState.WakingUp,
PumpDeviceState.PumpUnreachable,
PumpDeviceState.ErrorWhenCommunicating,
PumpDeviceState.TimeoutWhenCommunicating,
PumpDeviceState.InvalidConfiguration -> medtronic_pump_status.text = " " + MainApp.gs(pumpStatus.pumpDeviceState.resourceId)
PumpDeviceState.Active -> {
val cmd = MedtronicUtil.getCurrentCommand()
if (cmd == null)
medtronic_pump_status.text = " " + MainApp.gs(pumpStatus.pumpDeviceState.resourceId)
else {
log.debug("Command: " + cmd)
val cmdResourceId = cmd.resourceId
if (cmd == MedtronicCommandType.GetHistoryData) {
medtronic_pump_status.text = MedtronicUtil.frameNumber?.let {
MainApp.gs(cmdResourceId, MedtronicUtil.pageNumber, MedtronicUtil.frameNumber)
}
?: MainApp.gs(R.string.medtronic_cmd_desc_get_history_request, MedtronicUtil.pageNumber)
} else {
medtronic_pump_status.text = " " + (cmdResourceId?.let { MainApp.gs(it) }
?: cmd.getCommandDescription())
}
}
}
else -> log.warn("Unknown pump state: " + pumpStatus.pumpDeviceState)
}
val status = ConfigBuilderPlugin.getPlugin().commandQueue.spannedStatus()
if (status.toString() == "") {
medtronic_queue.visibility = View.GONE
} else {
medtronic_queue.visibility = View.VISIBLE
medtronic_queue.text = status
}
}
private fun checkStatusSet(object1: Any?, object2: Any?): Any? {
return if (object1 == null) {
object2
} else {
if (object1 != object2) {
object2
} else
object1
}
}
// GUI functions
@Synchronized
fun updateGUI() {
if (medtronic_rl_status == null) return
val plugin = MedtronicPumpPlugin.getPlugin()
val pumpStatus = MedtronicUtil.getPumpStatus()
setDeviceStatus()
// last connection
if (pumpStatus.lastConnection != 0L) {
val minAgo = DateUtil.minAgo(pumpStatus.lastConnection)
val min = (System.currentTimeMillis() - pumpStatus.lastConnection) / 1000 / 60
if (pumpStatus.lastConnection + 60 * 1000 > System.currentTimeMillis()) {
medtronic_lastconnection.setText(R.string.combo_pump_connected_now)
medtronic_lastconnection.setTextColor(Color.WHITE)
} else if (pumpStatus.lastConnection + 30 * 60 * 1000 < System.currentTimeMillis()) {
if (min < 60) {
medtronic_lastconnection.text = MainApp.gs(R.string.minago, min)
} else if (min < 1440) {
val h = (min / 60).toInt()
medtronic_lastconnection.text = (MainApp.gq(R.plurals.objective_hours, h, h) + " "
+ MainApp.gs(R.string.ago))
} else {
val h = (min / 60).toInt()
val d = h / 24
// h = h - (d * 24);
medtronic_lastconnection.text = (MainApp.gq(R.plurals.objective_days, d, d) + " "
+ MainApp.gs(R.string.ago))
}
medtronic_lastconnection.setTextColor(Color.RED)
} else {
medtronic_lastconnection.text = minAgo
medtronic_lastconnection.setTextColor(Color.WHITE)
}
}
// last bolus
val bolus = pumpStatus.lastBolusAmount
val bolusTime = pumpStatus.lastBolusTime
if (bolus != null && bolusTime != null) {
val agoMsc = System.currentTimeMillis() - pumpStatus.lastBolusTime.time
val bolusMinAgo = agoMsc.toDouble() / 60.0 / 1000.0
val unit = MainApp.gs(R.string.insulin_unit_shortname)
val ago: String
if (agoMsc < 60 * 1000) {
ago = MainApp.gs(R.string.combo_pump_connected_now)
} else if (bolusMinAgo < 60) {
ago = DateUtil.minAgo(pumpStatus.lastBolusTime.time)
} else {
ago = DateUtil.hourAgo(pumpStatus.lastBolusTime.time)
}
medtronic_lastbolus.text = MainApp.gs(R.string.combo_last_bolus, bolus, unit, ago)
} else {
medtronic_lastbolus.text = ""
}
// base basal rate
medtronic_basabasalrate.text = ("(" + pumpStatus.activeProfileName + ") "
+ MainApp.gs(R.string.pump_basebasalrate, plugin.baseBasalRate))
medtronic_tempbasal.text = TreatmentsPlugin.getPlugin()
.getTempBasalFromHistory(System.currentTimeMillis())?.toStringFull() ?: ""
// battery
if (MedtronicUtil.getBatteryType() == BatteryType.None || pumpStatus.batteryVoltage == null) {
medtronic_pumpstate_battery.text = "{fa-battery-" + pumpStatus.batteryRemaining / 25 + "} "
} else {
medtronic_pumpstate_battery.text = "{fa-battery-" + pumpStatus.batteryRemaining / 25 + "} " + pumpStatus.batteryRemaining + "%" + String.format(" (%.2f V)", pumpStatus.batteryVoltage)
}
SetWarnColor.setColorInverse(medtronic_pumpstate_battery, pumpStatus.batteryRemaining.toDouble(), 25.0, 10.0)
// reservoir
medtronic_reservoir.text = MainApp.gs(R.string.reservoirvalue, pumpStatus.reservoirRemainingUnits, pumpStatus.reservoirFullUnits)
SetWarnColor.setColorInverse(medtronic_reservoir, pumpStatus.reservoirRemainingUnits, 50.0, 20.0)
medtronic_errors.text = pumpStatus.errorInfo
}
}
| agpl-3.0 | b39bd6ab662c4573006a6edc779986f2 | 47.511041 | 197 | 0.644947 | 5.246673 | false | false | false | false |
mdaniel/intellij-community | plugins/kotlin/completion/src/org/jetbrains/kotlin/idea/completion/AllClassesCompletion.kt | 2 | 4980 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.completion
import com.intellij.codeInsight.completion.AllClassesGetter
import com.intellij.codeInsight.completion.CompletionParameters
import com.intellij.codeInsight.completion.PrefixMatcher
import com.intellij.psi.PsiClass
import com.intellij.psi.search.PsiShortNamesCache
import org.jetbrains.kotlin.asJava.classes.KtLightClass
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.descriptors.ClassKind
import org.jetbrains.kotlin.descriptors.ClassifierDescriptorWithTypeParameters
import org.jetbrains.kotlin.idea.base.facet.platform.platform
import org.jetbrains.kotlin.idea.base.psi.kotlinFqName
import org.jetbrains.kotlin.idea.base.utils.fqname.isJavaClassNotToBeUsedInKotlin
import org.jetbrains.kotlin.idea.caches.KotlinShortNamesCache
import org.jetbrains.kotlin.idea.core.KotlinIndicesHelper
import org.jetbrains.kotlin.idea.resolve.ResolutionFacade
import org.jetbrains.kotlin.idea.util.isSyntheticKotlinClass
import org.jetbrains.kotlin.platform.jvm.isJvm
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.resolve.scopes.DescriptorKindFilter
import org.jetbrains.kotlin.resolve.scopes.MemberScope
import org.jetbrains.kotlin.resolve.scopes.getDescriptorsFiltered
class AllClassesCompletion(
private val parameters: CompletionParameters,
private val kotlinIndicesHelper: KotlinIndicesHelper,
private val prefixMatcher: PrefixMatcher,
private val resolutionFacade: ResolutionFacade,
private val kindFilter: (ClassKind) -> Boolean,
private val includeTypeAliases: Boolean,
private val includeJavaClassesNotToBeUsed: Boolean
) {
fun collect(classifierDescriptorCollector: (ClassifierDescriptorWithTypeParameters) -> Unit, javaClassCollector: (PsiClass) -> Unit) {
//TODO: this is a temporary solution until we have built-ins in indices
// we need only nested classes because top-level built-ins are all added through default imports
for (builtInPackage in resolutionFacade.moduleDescriptor.builtIns.builtInPackagesImportedByDefault) {
collectClassesFromScope(builtInPackage.memberScope) {
if (it.containingDeclaration is ClassDescriptor) {
classifierDescriptorCollector(it)
}
}
}
kotlinIndicesHelper.processKotlinClasses(
{ prefixMatcher.prefixMatches(it) },
kindFilter = kindFilter,
processor = classifierDescriptorCollector
)
if (includeTypeAliases) {
kotlinIndicesHelper.processTopLevelTypeAliases(prefixMatcher.asStringNameFilter(), classifierDescriptorCollector)
}
if ((parameters.originalFile as KtFile).platform.isJvm()) {
addAdaptedJavaCompletion(javaClassCollector)
}
}
private fun collectClassesFromScope(scope: MemberScope, collector: (ClassDescriptor) -> Unit) {
for (descriptor in scope.getDescriptorsFiltered(DescriptorKindFilter.CLASSIFIERS)) {
if (descriptor is ClassDescriptor) {
if (kindFilter(descriptor.kind) && prefixMatcher.prefixMatches(descriptor.name.asString())) {
collector(descriptor)
}
collectClassesFromScope(descriptor.unsubstitutedInnerClassesScope, collector)
}
}
}
private fun addAdaptedJavaCompletion(collector: (PsiClass) -> Unit) {
val shortNamesCache = PsiShortNamesCache.EP_NAME.getExtensions(parameters.editor.project).firstOrNull {
it is KotlinShortNamesCache
} as KotlinShortNamesCache?
shortNamesCache?.disableSearch?.set(true)
try {
AllClassesGetter.processJavaClasses(parameters, prefixMatcher, true) { psiClass ->
if (psiClass!! !is KtLightClass) { // Kotlin class should have already been added as kotlin element before
if (psiClass.isSyntheticKotlinClass()) return@processJavaClasses // filter out synthetic classes produced by Kotlin compiler
val kind = when {
psiClass.isAnnotationType -> ClassKind.ANNOTATION_CLASS
psiClass.isInterface -> ClassKind.INTERFACE
psiClass.isEnum -> ClassKind.ENUM_CLASS
else -> ClassKind.CLASS
}
if (kindFilter(kind) && !isNotToBeUsed(psiClass)) {
collector(psiClass)
}
}
}
} finally {
shortNamesCache?.disableSearch?.set(false)
}
}
private fun isNotToBeUsed(javaClass: PsiClass): Boolean {
if (includeJavaClassesNotToBeUsed) return false
val fqName = javaClass.kotlinFqName
return fqName?.isJavaClassNotToBeUsedInKotlin() == true
}
}
| apache-2.0 | 8367bc2cb8ca85b325c195dd71b1bba6 | 45.981132 | 144 | 0.711647 | 5.442623 | false | false | false | false |
mdaniel/intellij-community | platform/platform-impl/src/com/intellij/openapi/wm/impl/ToolWindowManagerImpl.kt | 1 | 81562 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
@file:Suppress("ReplaceGetOrSet", "ReplacePutWithAssignment", "OverridingDeprecatedMember", "ReplaceNegatedIsEmptyWithIsNotEmpty")
package com.intellij.openapi.wm.impl
import com.intellij.diagnostic.LoadingState
import com.intellij.diagnostic.PluginException
import com.intellij.icons.AllIcons
import com.intellij.ide.IdeEventQueue
import com.intellij.ide.UiActivity
import com.intellij.ide.UiActivityMonitor
import com.intellij.ide.actions.ActivateToolWindowAction
import com.intellij.ide.actions.MaximizeActiveDialogAction
import com.intellij.internal.statistic.collectors.fus.actions.persistence.ToolWindowCollector
import com.intellij.notification.impl.NotificationsManagerImpl
import com.intellij.openapi.Disposable
import com.intellij.openapi.MnemonicHelper
import com.intellij.openapi.actionSystem.*
import com.intellij.openapi.actionSystem.ex.AnActionListener
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.EDT
import com.intellij.openapi.application.ModalityState
import com.intellij.openapi.application.asContextElement
import com.intellij.openapi.components.*
import com.intellij.openapi.diagnostic.debug
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.extensions.PluginDescriptor
import com.intellij.openapi.fileEditor.FileEditorManager
import com.intellij.openapi.fileEditor.FileEditorManagerListener
import com.intellij.openapi.fileEditor.ex.FileEditorManagerEx
import com.intellij.openapi.fileEditor.impl.EditorsSplitters
import com.intellij.openapi.keymap.Keymap
import com.intellij.openapi.keymap.KeymapManager
import com.intellij.openapi.keymap.KeymapManagerListener
import com.intellij.openapi.progress.ProcessCanceledException
import com.intellij.openapi.project.*
import com.intellij.openapi.project.ex.ProjectEx
import com.intellij.openapi.ui.FrameWrapper
import com.intellij.openapi.ui.Splitter
import com.intellij.openapi.ui.popup.Balloon
import com.intellij.openapi.ui.popup.JBPopupFactory
import com.intellij.openapi.util.*
import com.intellij.openapi.util.registry.Registry
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.wm.*
import com.intellij.openapi.wm.ex.ToolWindowEx
import com.intellij.openapi.wm.ex.ToolWindowManagerEx
import com.intellij.openapi.wm.ex.ToolWindowManagerListener
import com.intellij.openapi.wm.ex.ToolWindowManagerListener.ToolWindowManagerEventType
import com.intellij.openapi.wm.ex.ToolWindowManagerListener.ToolWindowManagerEventType.Resized
import com.intellij.serviceContainer.NonInjectable
import com.intellij.toolWindow.*
import com.intellij.ui.BalloonImpl
import com.intellij.ui.ClientProperty
import com.intellij.ui.ComponentUtil
import com.intellij.ui.ExperimentalUI
import com.intellij.ui.awt.RelativePoint
import com.intellij.util.BitUtil
import com.intellij.util.EventDispatcher
import com.intellij.util.SingleAlarm
import com.intellij.util.SystemProperties
import com.intellij.util.concurrency.EdtExecutorService
import com.intellij.util.messages.MessageBusConnection
import com.intellij.util.ui.EDT
import com.intellij.util.ui.PositionTracker
import com.intellij.util.ui.StartupUiUtil
import com.intellij.util.ui.UIUtil
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import org.intellij.lang.annotations.JdkConstants
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.annotations.TestOnly
import org.jetbrains.annotations.VisibleForTesting
import java.awt.*
import java.awt.event.*
import java.beans.PropertyChangeListener
import java.util.*
import java.util.concurrent.CancellationException
import java.util.concurrent.TimeUnit
import javax.swing.*
import javax.swing.event.HyperlinkEvent
import javax.swing.event.HyperlinkListener
private val LOG = logger<ToolWindowManagerImpl>()
private typealias Mutation = ((WindowInfoImpl) -> Unit)
@ApiStatus.Internal
open class ToolWindowManagerImpl @NonInjectable @TestOnly internal constructor(val project: Project,
@field:JvmField internal val isNewUi: Boolean,
private val isEdtRequired: Boolean)
: ToolWindowManagerEx(), Disposable {
private val dispatcher = EventDispatcher.create(ToolWindowManagerListener::class.java)
private val state: ToolWindowManagerState
get() = project.service()
private var layoutState
get() = state.layout
set(value) { state.layout = value }
private val idToEntry = HashMap<String, ToolWindowEntry>()
private val activeStack = ActiveStack()
private val sideStack = SideStack()
private val toolWindowPanes = LinkedHashMap<String, ToolWindowPane>()
private var frameState: ProjectFrameHelper?
get() = state.frame
set(value) { state.frame = value }
override var layoutToRestoreLater: DesktopLayout?
get() = state.layoutToRestoreLater
set(value) { state.layoutToRestoreLater = value }
private var currentState = KeyState.WAITING
private val waiterForSecondPress: SingleAlarm?
private val recentToolWindowsState: LinkedList<String>
get() = state.recentToolWindows
@Suppress("LeakingThis")
private val toolWindowSetInitializer = ToolWindowSetInitializer(project, this)
@Suppress("TestOnlyProblems")
constructor(project: Project) : this(project, isNewUi = ExperimentalUI.isNewUI(), isEdtRequired = true)
init {
if (project.isDefault) {
waiterForSecondPress = null
}
else {
waiterForSecondPress = SingleAlarm(
task = Runnable {
if (currentState != KeyState.HOLD) {
resetHoldState()
}
},
delay = SystemProperties.getIntProperty("actionSystem.keyGestureDblClickTime", 650),
parentDisposable = (project as ProjectEx).earlyDisposable
)
if (state.noStateLoaded) {
loadDefault()
}
@Suppress("LeakingThis")
state.scheduledLayout.afterChange(this) { dl ->
dl?.let { toolWindowSetInitializer.scheduleSetLayout(it) }
}
state.scheduledLayout.get()?.let { toolWindowSetInitializer.scheduleSetLayout(it) }
}
}
companion object {
/**
* Setting this [client property][JComponent.putClientProperty] allows specifying 'effective' parent for a component which will be used
* to find a tool window to which component belongs (if any). This can prevent tool windows in non-default view modes (e.g. 'Undock')
* to close when focus is transferred to a component not in tool window hierarchy, but logically belonging to it (e.g. when component
* is added to the window's layered pane).
*
* @see ComponentUtil.putClientProperty
*/
@JvmField
val PARENT_COMPONENT: Key<JComponent> = Key.create("tool.window.parent.component")
@JvmStatic
@ApiStatus.Internal
fun getRegisteredMutableInfoOrLogError(decorator: InternalDecoratorImpl): WindowInfoImpl {
val toolWindow = decorator.toolWindow
return toolWindow.toolWindowManager.getRegisteredMutableInfoOrLogError(toolWindow.id)
}
fun getAdjustedRatio(partSize: Int, totalSize: Int, direction: Int): Float {
var ratio = partSize.toFloat() / totalSize
ratio += (((partSize.toFloat() + direction) / totalSize) - ratio) / 2
return ratio
}
}
fun isToolWindowRegistered(id: String) = idToEntry.containsKey(id)
internal fun getEntry(id: String) = idToEntry.get(id)
internal fun assertIsEdt() {
if (isEdtRequired) {
EDT.assertIsEdt()
}
}
override fun dispose() {
}
@Service(Service.Level.APP)
internal class ToolWindowManagerAppLevelHelper {
companion object {
private fun handleFocusEvent(event: FocusEvent) {
if (event.id == FocusEvent.FOCUS_LOST) {
if (event.oppositeComponent == null || event.isTemporary) {
return
}
val project = IdeFocusManager.getGlobalInstance().lastFocusedFrame?.project ?: return
if (project.isDisposed || project.isDefault) {
return
}
val toolWindowManager = getInstance(project) as ToolWindowManagerImpl
toolWindowManager.revalidateStripeButtons()
val toolWindowId = getToolWindowIdForComponent(event.component) ?: return
val activeEntry = toolWindowManager.idToEntry.get(toolWindowId) ?: return
val windowInfo = activeEntry.readOnlyWindowInfo
// just removed
if (!windowInfo.isVisible) {
return
}
if (!(windowInfo.isAutoHide || windowInfo.type == ToolWindowType.SLIDING)) {
return
}
// let's check that tool window actually loses focus
if (getToolWindowIdForComponent(event.oppositeComponent) != toolWindowId) {
// a toolwindow lost focus
val focusGoesToPopup = JBPopupFactory.getInstance().getParentBalloonFor(event.oppositeComponent) != null
if (!focusGoesToPopup) {
val info = toolWindowManager.getRegisteredMutableInfoOrLogError(toolWindowId)
toolWindowManager.deactivateToolWindow(info, activeEntry)
}
}
}
else if (event.id == FocusEvent.FOCUS_GAINED) {
val component = event.component ?: return
processOpenedProjects { project ->
for (composite in FileEditorManagerEx.getInstanceEx(project).splitters.getAllComposites()) {
if (composite.allEditors.any { SwingUtilities.isDescendingFrom(component, it.component) }) {
(getInstance(project) as ToolWindowManagerImpl).activeStack.clear()
}
}
}
}
}
private inline fun process(processor: (manager: ToolWindowManagerImpl) -> Unit) {
processOpenedProjects { project ->
processor(getInstance(project) as ToolWindowManagerImpl)
}
}
}
private class MyListener : AWTEventListener {
override fun eventDispatched(event: AWTEvent?) {
if (event is FocusEvent) {
handleFocusEvent(event)
}
else if (event is WindowEvent && event.getID() == WindowEvent.WINDOW_LOST_FOCUS) {
process { manager ->
val frame = event.getSource() as? JFrame
if (frame === manager.frameState?.frameOrNull) {
manager.resetHoldState()
}
}
}
}
}
init {
val awtFocusListener = MyListener()
Toolkit.getDefaultToolkit().addAWTEventListener(awtFocusListener, AWTEvent.FOCUS_EVENT_MASK or AWTEvent.WINDOW_FOCUS_EVENT_MASK)
val updateHeadersAlarm = SingleAlarm(Runnable {
processOpenedProjects { project ->
(getInstance(project) as ToolWindowManagerImpl).updateToolWindowHeaders()
}
}, 50, ApplicationManager.getApplication())
val focusListener = PropertyChangeListener { updateHeadersAlarm.cancelAndRequest() }
KeyboardFocusManager.getCurrentKeyboardFocusManager().addPropertyChangeListener("focusOwner", focusListener)
Disposer.register(ApplicationManager.getApplication()) {
KeyboardFocusManager.getCurrentKeyboardFocusManager().removePropertyChangeListener("focusOwner", focusListener)
}
val connection = ApplicationManager.getApplication().messageBus.connect()
connection.subscribe(ProjectManager.TOPIC, object : ProjectManagerListener {
override fun projectClosingBeforeSave(project: Project) {
val manager = (project.serviceIfCreated<ToolWindowManager>() as ToolWindowManagerImpl?) ?: return
for (entry in manager.idToEntry.values) {
manager.saveFloatingOrWindowedState(entry, manager.layoutState.getInfo(entry.id) ?: continue)
}
}
override fun projectClosed(project: Project) {
(project.serviceIfCreated<ToolWindowManager>() as ToolWindowManagerImpl?)?.projectClosed()
}
})
connection.subscribe(KeymapManagerListener.TOPIC, object : KeymapManagerListener {
override fun activeKeymapChanged(keymap: Keymap?) {
process { manager ->
manager.idToEntry.values.forEach {
it.stripeButton?.updatePresentation()
}
}
}
})
connection.subscribe(AnActionListener.TOPIC, object : AnActionListener {
override fun beforeActionPerformed(action: AnAction, event: AnActionEvent) {
process { manager ->
if (manager.currentState != KeyState.HOLD) {
manager.resetHoldState()
}
}
if (ExperimentalUI.isNewUI()) {
if (event.place == ActionPlaces.TOOLWINDOW_TITLE) {
val toolWindowManager = getInstance(event.project!!) as ToolWindowManagerImpl
val toolWindowId = event.dataContext.getData(PlatformDataKeys.TOOL_WINDOW)?.id ?: return
toolWindowManager.activateToolWindow(toolWindowId, null, true)
}
if (event.place == ActionPlaces.TOOLWINDOW_POPUP) {
val toolWindowManager = getInstance(event.project!!) as ToolWindowManagerImpl
val activeEntry = toolWindowManager.idToEntry.get(toolWindowManager.lastActiveToolWindowId ?: return) ?: return
(activeEntry.toolWindow.decorator ?: return).headerToolbar.component.isVisible = true
}
}
}
})
IdeEventQueue.getInstance().addDispatcher(IdeEventQueue.EventDispatcher { event ->
if (event is KeyEvent) {
process { manager ->
manager.dispatchKeyEvent(event)
}
}
false
}, ApplicationManager.getApplication())
}
}
private fun getDefaultToolWindowPane() = toolWindowPanes[WINDOW_INFO_DEFAULT_TOOL_WINDOW_PANE_ID]!!
internal fun getToolWindowPane(paneId: String) = toolWindowPanes[paneId] ?: getDefaultToolWindowPane()
internal fun getToolWindowPane(toolWindow: ToolWindow): ToolWindowPane {
val paneId = if (toolWindow is ToolWindowImpl) {
toolWindow.windowInfo.safeToolWindowPaneId
}
else {
idToEntry.get(toolWindow.id)?.readOnlyWindowInfo?.safeToolWindowPaneId ?: WINDOW_INFO_DEFAULT_TOOL_WINDOW_PANE_ID
}
return getToolWindowPane(paneId)
}
@VisibleForTesting
internal open fun getButtonManager(toolWindow: ToolWindow): ToolWindowButtonManager = getToolWindowPane(toolWindow).buttonManager
internal fun addToolWindowPane(toolWindowPane: ToolWindowPane, parentDisposable: Disposable) {
toolWindowPanes.put(toolWindowPane.paneId, toolWindowPane)
Disposer.register(parentDisposable) {
for (it in idToEntry.values) {
if (it.readOnlyWindowInfo.safeToolWindowPaneId == toolWindowPane.paneId) {
hideToolWindow(id = it.id,
hideSide = false,
moveFocus = false,
removeFromStripe = true,
source = ToolWindowEventSource.CloseAction)
}
}
toolWindowPanes.remove(toolWindowPane.paneId)
}
}
internal fun getToolWindowPanes(): List<ToolWindowPane> = toolWindowPanes.values.toList()
private fun revalidateStripeButtons() {
val buttonManagers = toolWindowPanes.values.mapNotNull { it.buttonManager as? ToolWindowPaneNewButtonManager }
ApplicationManager.getApplication().invokeLater({ buttonManagers.forEach { it.refreshUi() } }, project.disposed)
}
internal fun createNotInHierarchyIterable(paneId: String): Iterable<Component> {
return Iterable {
idToEntry.values.asSequence().mapNotNull {
if (getToolWindowPane(it.toolWindow).paneId == paneId) {
val component = it.toolWindow.decoratorComponent
if (component != null && component.parent == null) component else null
}
else null
}.iterator()
}
}
private fun updateToolWindowHeaders() {
focusManager.doWhenFocusSettlesDown(ExpirableRunnable.forProject(project) {
for (entry in idToEntry.values) {
if (entry.readOnlyWindowInfo.isVisible) {
val decorator = entry.toolWindow.decorator ?: continue
decorator.repaint()
decorator.updateActiveAndHoverState()
}
}
revalidateStripeButtons()
})
}
@Suppress("DEPRECATION")
private fun dispatchKeyEvent(e: KeyEvent): Boolean {
if ((e.keyCode != KeyEvent.VK_CONTROL) && (
e.keyCode != KeyEvent.VK_ALT) && (e.keyCode != KeyEvent.VK_SHIFT) && (e.keyCode != KeyEvent.VK_META)) {
if (e.modifiers == 0) {
resetHoldState()
}
return false
}
if (e.id != KeyEvent.KEY_PRESSED && e.id != KeyEvent.KEY_RELEASED) {
return false
}
val parent = e.component?.let { ComponentUtil.findUltimateParent(it) }
if (parent is IdeFrame) {
if ((parent as IdeFrame).project !== project) {
resetHoldState()
return false
}
}
val vks = getActivateToolWindowVKsMask()
if (vks == 0) {
resetHoldState()
return false
}
val mouseMask = InputEvent.BUTTON1_DOWN_MASK or InputEvent.BUTTON2_DOWN_MASK or InputEvent.BUTTON3_DOWN_MASK
if (BitUtil.isSet(vks, keyCodeToInputMask(e.keyCode)) && (e.modifiersEx and mouseMask) == 0) {
val pressed = e.id == KeyEvent.KEY_PRESSED
val modifiers = e.modifiers
if (areAllModifiersPressed(modifiers, vks) || !pressed) {
processState(pressed)
}
else {
resetHoldState()
}
}
return false
}
private fun resetHoldState() {
currentState = KeyState.WAITING
toolWindowPanes.values.forEach { it.setStripesOverlaid(value = false) }
}
private fun processState(pressed: Boolean) {
if (pressed) {
if (currentState == KeyState.WAITING) {
currentState = KeyState.PRESSED
}
else if (currentState == KeyState.RELEASED) {
currentState = KeyState.HOLD
toolWindowPanes.values.forEach { it.setStripesOverlaid(value = true) }
}
}
else {
if (currentState == KeyState.PRESSED) {
currentState = KeyState.RELEASED
waiterForSecondPress?.cancelAndRequest()
}
else {
resetHoldState()
}
}
}
suspend fun init(frameHelper: ProjectFrameHelper, fileEditorManager: FileEditorManagerEx) {
// Make sure we haven't already created the root tool window pane. We might have created panes for secondary frames, as they get
// registered differently, but we shouldn't have the main pane yet
LOG.assertTrue(!toolWindowPanes.containsKey(WINDOW_INFO_DEFAULT_TOOL_WINDOW_PANE_ID))
doInit(frameHelper, project.messageBus.connect(this), fileEditorManager)
}
@VisibleForTesting
suspend fun doInit(frameHelper: ProjectFrameHelper, connection: MessageBusConnection, fileEditorManager: FileEditorManagerEx) {
connection.subscribe(ToolWindowManagerListener.TOPIC, dispatcher.multicaster)
withContext(Dispatchers.EDT + ModalityState.any().asContextElement()) {
frameState = frameHelper
val toolWindowPane = frameHelper.rootPane!!.toolWindowPane
toolWindowPane.setDocumentComponent(fileEditorManager.component)
// This will be the tool window pane for the default frame, which is not automatically added by the ToolWindowPane constructor. If we're
// reopening other frames, their tool window panes will be already added, but we still need to initialise the tool windows themselves.
toolWindowPanes.put(toolWindowPane.paneId, toolWindowPane)
}
toolWindowSetInitializer.initUi()
connection.subscribe(FileEditorManagerListener.FILE_EDITOR_MANAGER, object : FileEditorManagerListener {
override fun fileClosed(source: FileEditorManager, file: VirtualFile) {
ApplicationManager.getApplication().invokeLater({
focusManager.doWhenFocusSettlesDown(ExpirableRunnable.forProject(project) {
if (!FileEditorManager.getInstance(project).hasOpenFiles()) {
focusToolWindowByDefault()
}
})
}, project.disposed)
}
})
}
@Deprecated("Use {{@link #registerToolWindow(RegisterToolWindowTask)}}")
override fun initToolWindow(bean: ToolWindowEP) {
ApplicationManager.getApplication().assertIsDispatchThread()
initToolWindow(bean, bean.pluginDescriptor)
}
internal fun initToolWindow(bean: ToolWindowEP, plugin: PluginDescriptor) {
val condition = bean.getCondition(plugin)
if (condition != null && !condition.value(project)) {
return
}
val factory = bean.getToolWindowFactory(bean.pluginDescriptor)
if (!factory.isApplicable(project)) {
return
}
// Always add to the default tool window pane
val toolWindowPane = getDefaultToolWindowPaneIfInitialized()
val anchor = getToolWindowAnchor(factory, bean)
@Suppress("DEPRECATION")
val sideTool = (bean.secondary || bean.side) && !isNewUi
val entry = registerToolWindow(RegisterToolWindowTask(
id = bean.id,
icon = findIconFromBean(bean, factory, plugin),
anchor = anchor,
sideTool = sideTool,
canCloseContent = bean.canCloseContents,
canWorkInDumbMode = DumbService.isDumbAware(factory),
shouldBeAvailable = factory.shouldBeAvailable(project),
contentFactory = factory,
stripeTitle = getStripeTitleSupplier(bean.id, plugin)
), toolWindowPane.buttonManager)
project.messageBus.syncPublisher(ToolWindowManagerListener.TOPIC).toolWindowsRegistered(listOf(entry.id), this)
toolWindowPane.buttonManager.getStripeFor(anchor, sideTool).revalidate()
toolWindowPane.validate()
toolWindowPane.repaint()
}
private fun getDefaultToolWindowPaneIfInitialized(): ToolWindowPane {
return toolWindowPanes.get(WINDOW_INFO_DEFAULT_TOOL_WINDOW_PANE_ID)
?: throw IllegalStateException("You must not register toolwindow programmatically so early. " +
"Rework code or use ToolWindowManager.invokeLater")
}
fun projectClosed() {
(frameState ?: return).releaseFrame()
toolWindowPanes.values.forEach { it.putClientProperty(UIUtil.NOT_IN_HIERARCHY_COMPONENTS, null) }
// hide all tool windows - frame maybe reused for another project
for (entry in idToEntry.values) {
try {
removeDecoratorWithoutUpdatingState(entry, layoutState.getInfo(entry.id) ?: continue, dirtyMode = true)
}
catch (e: CancellationException) {
throw e
}
catch (e: ProcessCanceledException) {
throw e
}
catch (e: Throwable) {
LOG.error(e)
}
finally {
Disposer.dispose(entry.disposable)
}
}
toolWindowPanes.values.forEach(ToolWindowPane::reset)
frameState = null
}
private fun loadDefault() {
toolWindowSetInitializer.scheduleSetLayout(ToolWindowDefaultLayoutManager.getInstance().getLayoutCopy())
}
@Deprecated("Use {@link ToolWindowManagerListener#TOPIC}", level = DeprecationLevel.ERROR)
override fun addToolWindowManagerListener(listener: ToolWindowManagerListener) {
dispatcher.addListener(listener)
}
@Deprecated("Use {@link ToolWindowManagerListener#TOPIC}", level = DeprecationLevel.ERROR,
replaceWith = ReplaceWith("project.messageBus.connect(parentDisposable).subscribe(ToolWindowManagerListener.TOPIC, listener)",
"com.intellij.openapi.wm.ex.ToolWindowManagerListener"))
override fun addToolWindowManagerListener(listener: ToolWindowManagerListener, parentDisposable: Disposable) {
project.messageBus.connect(parentDisposable).subscribe(ToolWindowManagerListener.TOPIC, listener)
}
@Deprecated("Use {@link ToolWindowManagerListener#TOPIC}", level = DeprecationLevel.ERROR)
override fun removeToolWindowManagerListener(listener: ToolWindowManagerListener) {
dispatcher.removeListener(listener)
}
override fun activateEditorComponent() {
EditorsSplitters.focusDefaultComponentInSplittersIfPresent(project)
}
open fun activateToolWindow(id: String, runnable: Runnable?, autoFocusContents: Boolean, source: ToolWindowEventSource? = null) {
ApplicationManager.getApplication().assertIsDispatchThread()
val activity = UiActivity.Focus("toolWindow:$id")
UiActivityMonitor.getInstance().addActivity(project, activity, ModalityState.NON_MODAL)
activateToolWindow(idToEntry.get(id)!!, getRegisteredMutableInfoOrLogError(id), autoFocusContents, source)
ApplicationManager.getApplication().invokeLater(Runnable {
runnable?.run()
UiActivityMonitor.getInstance().removeActivity(project, activity)
}, project.disposed)
}
internal fun activateToolWindow(entry: ToolWindowEntry,
info: WindowInfoImpl,
autoFocusContents: Boolean = true,
source: ToolWindowEventSource? = null) {
LOG.debug { "activateToolWindow($entry)" }
if (source != null) {
ToolWindowCollector.getInstance().recordActivation(project, entry.id, info, source)
}
recentToolWindowsState.remove(entry.id)
recentToolWindowsState.add(0, entry.id)
if (!entry.toolWindow.isAvailable) {
// Tool window can be "logically" active but not focused.
// For example, when the user switched to another application. So we just need to bring tool window's window to front.
if (autoFocusContents && !entry.toolWindow.hasFocus) {
entry.toolWindow.requestFocusInToolWindow()
}
return
}
if (!entry.readOnlyWindowInfo.isVisible) {
showToolWindowImpl(entry, info, dirtyMode = false, source = source)
}
if (autoFocusContents && ApplicationManager.getApplication().isActive) {
entry.toolWindow.requestFocusInToolWindow()
}
else {
activeStack.push(entry)
}
fireStateChanged(ToolWindowManagerEventType.ActivateToolWindow)
}
fun getRecentToolWindows(): List<String> = java.util.List.copyOf(recentToolWindowsState)
internal fun updateToolWindow(toolWindow: ToolWindowImpl, component: Component) {
toolWindow.setFocusedComponent(component)
if (toolWindow.isAvailable && !toolWindow.isActive) {
activateToolWindow(toolWindow.id, null, autoFocusContents = true)
}
activeStack.push(idToEntry.get(toolWindow.id) ?: return)
toolWindow.decorator?.headerToolbar?.component?.isVisible = true
}
// mutate operation must use info from layout and not from decorator
internal fun getRegisteredMutableInfoOrLogError(id: String): WindowInfoImpl {
var info = layoutState.getInfo(id)
if (info == null) {
val entry = idToEntry.get(id) ?: throw IllegalStateException("window with id=\"$id\" isn't registered")
// window was registered but stripe button was not shown, so, layout was not added to a list
info = (entry.readOnlyWindowInfo as WindowInfoImpl).copy()
layoutState.addInfo(id, info)
}
return info
}
private fun deactivateToolWindow(info: WindowInfoImpl,
entry: ToolWindowEntry,
dirtyMode: Boolean = false,
mutation: Mutation? = null,
source: ToolWindowEventSource? = null) {
LOG.debug { "deactivateToolWindow(${info.id})" }
setHiddenState(info, entry, source)
mutation?.invoke(info)
updateStateAndRemoveDecorator(info, entry, dirtyMode = dirtyMode)
entry.applyWindowInfo(info.copy())
}
private fun setHiddenState(info: WindowInfoImpl, entry: ToolWindowEntry, source: ToolWindowEventSource?) {
ToolWindowCollector.getInstance().recordHidden(project, info, source)
info.isActiveOnStart = false
info.isVisible = false
activeStack.remove(entry, false)
}
override val toolWindowIds: Array<String>
get() = idToEntry.keys.toTypedArray()
override val toolWindows: List<ToolWindow>
get() = idToEntry.values.map { it.toolWindow }
override val toolWindowIdSet: Set<String>
get() = java.util.Set.copyOf(idToEntry.keys)
override val activeToolWindowId: String?
get() {
EDT.assertIsEdt()
val frame = toolWindowPanes.values.firstOrNull { it.frame.isActive }?.frame ?: frameState?.frameOrNull ?: return null
if (frame.isActive) {
return getToolWindowIdForComponent(frame.mostRecentFocusOwner)
}
else {
// let's check floating and windowed
for (entry in idToEntry.values) {
if (entry.floatingDecorator?.isActive == true || entry.windowedDecorator?.isActive == true) {
return entry.id
}
}
}
return null
}
override val lastActiveToolWindowId: String?
get() = getLastActiveToolWindows().firstOrNull()?.id
internal fun getLastActiveToolWindows(): Sequence<ToolWindow> {
EDT.assertIsEdt()
return (0 until activeStack.persistentSize).asSequence()
.map { activeStack.peekPersistent(it).toolWindow }
.filter { it.isAvailable }
}
/**
* @return windowed decorator for the tool window with specified `ID`.
*/
private fun getWindowedDecorator(id: String) = idToEntry.get(id)?.windowedDecorator
override fun getIdsOn(anchor: ToolWindowAnchor) = getVisibleToolWindowsOn(WINDOW_INFO_DEFAULT_TOOL_WINDOW_PANE_ID, anchor).map { it.id }.toList()
internal fun getToolWindowsOn(paneId: String, anchor: ToolWindowAnchor, excludedId: String): MutableList<ToolWindowEx> {
return getVisibleToolWindowsOn(paneId, anchor)
.filter { it.id != excludedId }
.map { it.toolWindow }
.toMutableList()
}
internal fun getDockedInfoAt(paneId: String, anchor: ToolWindowAnchor?, side: Boolean): WindowInfo? {
return idToEntry.values.asSequence()
.map { it.readOnlyWindowInfo }
.find { it.isVisible && it.isDocked && it.safeToolWindowPaneId == paneId && it.anchor == anchor && it.isSplit == side }
}
override fun getLocationIcon(id: String, fallbackIcon: Icon): Icon {
val info = layoutState.getInfo(id) ?: return fallbackIcon
val type = info.type
if (type == ToolWindowType.FLOATING || type == ToolWindowType.WINDOWED) {
return AllIcons.Actions.MoveToWindow
}
val anchor = info.anchor
val splitMode = info.isSplit
return when (anchor) {
ToolWindowAnchor.BOTTOM -> if (splitMode) AllIcons.Actions.MoveToBottomRight else AllIcons.Actions.MoveToBottomLeft
ToolWindowAnchor.LEFT -> if (splitMode) AllIcons.Actions.MoveToLeftBottom else AllIcons.Actions.MoveToLeftTop
ToolWindowAnchor.RIGHT -> if (splitMode) AllIcons.Actions.MoveToRightBottom else AllIcons.Actions.MoveToRightTop
ToolWindowAnchor.TOP -> if (splitMode) AllIcons.Actions.MoveToTopRight else AllIcons.Actions.MoveToTopLeft
else -> fallbackIcon
}
}
private fun getVisibleToolWindowsOn(paneId: String, anchor: ToolWindowAnchor): Sequence<ToolWindowEntry> {
return idToEntry.values
.asSequence()
.filter { it.toolWindow.isAvailable && it.readOnlyWindowInfo.safeToolWindowPaneId == paneId && it.readOnlyWindowInfo.anchor == anchor }
}
// cannot be ToolWindowEx because of backward compatibility
override fun getToolWindow(id: String?): ToolWindow? {
return idToEntry.get(id ?: return null)?.toolWindow
}
open fun showToolWindow(id: String) {
LOG.debug { "showToolWindow($id)" }
EDT.assertIsEdt()
val entry = idToEntry.get(id) ?: throw IllegalThreadStateException("window with id=\"$id\" is not registered")
if (entry.readOnlyWindowInfo.isVisible) {
LOG.assertTrue(entry.toolWindow.getComponentIfInitialized() != null)
return
}
val info = getRegisteredMutableInfoOrLogError(id)
if (showToolWindowImpl(entry, info, dirtyMode = false)) {
checkInvariants(id)
fireStateChanged(ToolWindowManagerEventType.ShowToolWindow)
}
}
override fun hideToolWindow(id: String, hideSide: Boolean) {
hideToolWindow(id = id, hideSide = hideSide, source = null)
}
open fun hideToolWindow(id: String,
hideSide: Boolean = false,
moveFocus: Boolean = true,
removeFromStripe: Boolean = false,
source: ToolWindowEventSource? = null) {
EDT.assertIsEdt()
val entry = idToEntry.get(id)!!
var moveFocusAfter = moveFocus && entry.toolWindow.isActive
if (!entry.readOnlyWindowInfo.isVisible) {
moveFocusAfter = false
}
val info = getRegisteredMutableInfoOrLogError(id)
val mutation: Mutation? = if (removeFromStripe) {
{
info.isShowStripeButton = false
entry.removeStripeButton()
}
}
else {
null
}
executeHide(entry, info, dirtyMode = false, hideSide = hideSide, mutation = mutation, source = source)
if (removeFromStripe) {
// If we're removing the stripe, reset to the root pane ID. Note that the current value is used during hide
info.toolWindowPaneId = WINDOW_INFO_DEFAULT_TOOL_WINDOW_PANE_ID
}
fireStateChanged(ToolWindowManagerEventType.HideToolWindow)
if (moveFocusAfter) {
activateEditorComponent()
}
revalidateStripeButtons()
}
private fun executeHide(entry: ToolWindowEntry,
info: WindowInfoImpl,
dirtyMode: Boolean,
hideSide: Boolean = false,
mutation: Mutation? = null,
source: ToolWindowEventSource? = null) {
// hide and deactivate
deactivateToolWindow(info, entry, dirtyMode = dirtyMode, mutation = mutation, source = source)
if (hideSide && info.type != ToolWindowType.FLOATING && info.type != ToolWindowType.WINDOWED) {
for (each in getVisibleToolWindowsOn(info.safeToolWindowPaneId, info.anchor)) {
activeStack.remove(each, false)
}
if (isStackEnabled) {
while (!sideStack.isEmpty(info.anchor)) {
sideStack.pop(info.anchor)
}
}
for (otherEntry in idToEntry.values) {
val otherInfo = layoutState.getInfo(otherEntry.id) ?: continue
if (otherInfo.isVisible && otherInfo.safeToolWindowPaneId == info.safeToolWindowPaneId && otherInfo.anchor == info.anchor) {
deactivateToolWindow(otherInfo, otherEntry, dirtyMode = dirtyMode, source = ToolWindowEventSource.HideSide)
}
}
}
else {
// first we have to find tool window that was located at the same side and was hidden
if (isStackEnabled) {
var info2: WindowInfoImpl? = null
while (!sideStack.isEmpty(info.anchor)) {
val storedInfo = sideStack.pop(info.anchor)
if (storedInfo.isSplit != info.isSplit) {
continue
}
val currentInfo = getRegisteredMutableInfoOrLogError(storedInfo.id!!)
// SideStack contains copies of real WindowInfos. It means that
// these stored infos can be invalid. The following loop removes invalid WindowInfos.
if (storedInfo.safeToolWindowPaneId == currentInfo.safeToolWindowPaneId && storedInfo.anchor == currentInfo.anchor
&& storedInfo.type == currentInfo.type && storedInfo.isAutoHide == currentInfo.isAutoHide) {
info2 = storedInfo
break
}
}
if (info2 != null) {
val entry2 = idToEntry[info2.id!!]!!
if (!entry2.readOnlyWindowInfo.isVisible) {
showToolWindowImpl(entry2, info2, dirtyMode = dirtyMode)
}
}
}
activeStack.remove(entry, false)
}
}
/**
* @param dirtyMode if `true` then all UI operations are performed in dirty mode.
*/
private fun showToolWindowImpl(entry: ToolWindowEntry,
toBeShownInfo: WindowInfoImpl,
dirtyMode: Boolean,
source: ToolWindowEventSource? = null): Boolean {
if (!entry.toolWindow.isAvailable) {
return false
}
ToolWindowCollector.getInstance().recordShown(project, source, toBeShownInfo)
toBeShownInfo.isVisible = true
toBeShownInfo.isShowStripeButton = true
val snapshotInfo = toBeShownInfo.copy()
entry.applyWindowInfo(snapshotInfo)
doShowWindow(entry, snapshotInfo, dirtyMode)
if (entry.readOnlyWindowInfo.type == ToolWindowType.WINDOWED && entry.toolWindow.getComponentIfInitialized() != null) {
UIUtil.toFront(ComponentUtil.getWindow(entry.toolWindow.component))
}
return true
}
private fun doShowWindow(entry: ToolWindowEntry, info: WindowInfo, dirtyMode: Boolean) {
if (entry.readOnlyWindowInfo.type == ToolWindowType.FLOATING) {
addFloatingDecorator(entry, info)
}
else if (entry.readOnlyWindowInfo.type == ToolWindowType.WINDOWED) {
addWindowedDecorator(entry, info)
}
else {
// docked and sliding windows
// If there is tool window on the same side then we have to hide it, i.e.
// clear place for tool window to be shown.
//
// We store WindowInfo of hidden tool window in the SideStack (if the tool window
// is docked and not auto-hide one). Therefore, it's possible to restore the
// hidden tool window when showing tool window will be closed.
for (otherEntry in idToEntry.values) {
if (entry.id == otherEntry.id) {
continue
}
val otherInfo = otherEntry.readOnlyWindowInfo
if (otherInfo.isVisible && otherInfo.type == info.type && otherInfo.isSplit == info.isSplit
&& otherInfo.safeToolWindowPaneId == info.safeToolWindowPaneId && otherInfo.anchor == info.anchor) {
val otherLayoutInto = layoutState.getInfo(otherEntry.id)!!
// hide and deactivate tool window
setHiddenState(otherLayoutInto, otherEntry, ToolWindowEventSource.HideOnShowOther)
val otherInfoCopy = otherLayoutInto.copy()
otherEntry.applyWindowInfo(otherInfoCopy)
otherEntry.toolWindow.decoratorComponent?.let { decorator ->
val toolWindowPane = getToolWindowPane(otherInfoCopy.safeToolWindowPaneId)
toolWindowPane.removeDecorator(otherInfoCopy, decorator, false, this)
}
// store WindowInfo into the SideStack
if (isStackEnabled && otherInfo.isDocked && !otherInfo.isAutoHide) {
sideStack.push(otherInfoCopy)
}
}
}
// This check is for testability. The tests don't create UI, so there are no actual panes
if (toolWindowPanes.containsKey(WINDOW_INFO_DEFAULT_TOOL_WINDOW_PANE_ID)) {
val toolWindowPane = getToolWindowPane(info.safeToolWindowPaneId)
toolWindowPane.addDecorator(entry.toolWindow.getOrCreateDecoratorComponent(), info, dirtyMode, this)
}
// remove tool window from the SideStack
if (isStackEnabled) {
sideStack.remove(entry.id)
}
}
if (entry.stripeButton == null) {
val buttonManager = getButtonManager(entry.toolWindow)
entry.stripeButton = buttonManager.createStripeButton(entry.toolWindow, info, task = null)
}
entry.toolWindow.scheduleContentInitializationIfNeeded()
fireToolWindowShown(entry.toolWindow)
}
override fun registerToolWindow(task: RegisterToolWindowTask): ToolWindow {
ApplicationManager.getApplication().assertIsDispatchThread()
// Try to get a previously saved tool window pane, if possible
val toolWindowPane = this.getLayout().getInfo(task.id)?.toolWindowPaneId?.let { getToolWindowPane(it) }
?: getDefaultToolWindowPaneIfInitialized()
val entry = registerToolWindow(task, buttonManager = toolWindowPane.buttonManager)
project.messageBus.syncPublisher(ToolWindowManagerListener.TOPIC).toolWindowsRegistered(listOf(entry.id), this)
toolWindowPane.buttonManager.getStripeFor(entry.toolWindow.anchor, entry.toolWindow.isSplitMode).revalidate()
toolWindowPane.validate()
toolWindowPane.repaint()
fireStateChanged(ToolWindowManagerEventType.RegisterToolWindow)
return entry.toolWindow
}
internal fun registerToolWindow(task: RegisterToolWindowTask, buttonManager: ToolWindowButtonManager): ToolWindowEntry {
LOG.debug { "registerToolWindow($task)" }
if (idToEntry.containsKey(task.id)) {
throw IllegalArgumentException("window with id=\"${task.id}\" is already registered")
}
var info = layoutState.getInfo(task.id)
val isButtonNeeded = task.shouldBeAvailable && (info?.isShowStripeButton ?: !isNewUi)
// do not create layout for New UI - button is not created for toolwindow by default
if (info == null) {
info = layoutState.create(task, isNewUi = isNewUi)
if (isButtonNeeded) {
// we must allocate order - otherwise, on drag-n-drop, we cannot move some tool windows to the end
// because sibling's order is equal to -1, so, always in the end
info.order = layoutState.getMaxOrder(info.safeToolWindowPaneId, task.anchor)
layoutState.addInfo(task.id, info)
}
}
val disposable = Disposer.newDisposable(task.id)
Disposer.register(project, disposable)
val factory = task.contentFactory
val infoSnapshot = info.copy()
if (infoSnapshot.isVisible && (factory == null || !task.shouldBeAvailable)) {
// isVisible cannot be true if contentFactory is null, because we cannot show toolwindow without content
infoSnapshot.isVisible = false
}
val stripeTitle = task.stripeTitle?.get() ?: task.id
val toolWindow = ToolWindowImpl(toolWindowManager = this,
id = task.id,
canCloseContent = task.canCloseContent,
dumbAware = task.canWorkInDumbMode,
component = task.component,
parentDisposable = disposable,
windowInfo = infoSnapshot,
contentFactory = factory,
isAvailable = task.shouldBeAvailable,
stripeTitle = stripeTitle)
if (task.hideOnEmptyContent) {
toolWindow.setToHideOnEmptyContent(true)
}
toolWindow.windowInfoDuringInit = infoSnapshot
try {
factory?.init(toolWindow)
}
catch (e: IllegalStateException) {
LOG.error(PluginException(e, task.pluginDescriptor?.pluginId))
}
finally {
toolWindow.windowInfoDuringInit = null
}
// contentFactory.init can set icon
if (toolWindow.icon == null) {
task.icon?.let {
toolWindow.doSetIcon(it)
}
}
ActivateToolWindowAction.ensureToolWindowActionRegistered(toolWindow, ActionManager.getInstance())
val stripeButton = if (isButtonNeeded) {
buttonManager.createStripeButton(toolWindow, infoSnapshot, task)
}
else {
LOG.debug {
"Button is not created for `${task.id}`" +
"(isShowStripeButton: ${info.isShowStripeButton}, isAvailable: ${task.shouldBeAvailable})"
}
null
}
val entry = ToolWindowEntry(stripeButton, toolWindow, disposable)
idToEntry.put(task.id, entry)
// If preloaded info is visible or active then we have to show/activate the installed
// tool window. This step has sense only for windows which are not in the auto hide
// mode. But if tool window was active but its mode doesn't allow to activate it again
// (for example, tool window is in auto hide mode) then we just activate editor component.
if (stripeButton != null && factory != null /* not null on init tool window from EP */ && infoSnapshot.isVisible) {
showToolWindowImpl(entry, info, dirtyMode = false)
// do not activate tool window that is the part of project frame - default component should be focused
if (infoSnapshot.isActiveOnStart &&
(infoSnapshot.type == ToolWindowType.WINDOWED || infoSnapshot.type == ToolWindowType.FLOATING) &&
ApplicationManager.getApplication().isActive) {
entry.toolWindow.requestFocusInToolWindow()
}
}
return entry
}
@Deprecated("Use ToolWindowFactory and toolWindow extension point")
@Suppress("OverridingDeprecatedMember")
override fun unregisterToolWindow(id: String) {
doUnregisterToolWindow(id)
fireStateChanged(ToolWindowManagerEventType.UnregisterToolWindow)
}
internal fun doUnregisterToolWindow(id: String) {
LOG.debug { "unregisterToolWindow($id)" }
ApplicationManager.getApplication().assertIsDispatchThread()
ActivateToolWindowAction.unregister(id)
val entry = idToEntry.remove(id) ?: return
val toolWindow = entry.toolWindow
val info = layoutState.getInfo(id)
if (info != null) {
// remove decorator and tool button from the screen - removing will also save current bounds
updateStateAndRemoveDecorator(info, entry, false)
// save recent appearance of tool window
activeStack.remove(entry, true)
if (isStackEnabled) {
sideStack.remove(id)
}
entry.removeStripeButton()
val toolWindowPane = getToolWindowPane(info.safeToolWindowPaneId)
toolWindowPane.validate()
toolWindowPane.repaint()
}
if (!project.isDisposed) {
project.messageBus.syncPublisher(ToolWindowManagerListener.TOPIC).toolWindowUnregistered(id, (toolWindow))
}
Disposer.dispose(entry.disposable)
}
private fun updateStateAndRemoveDecorator(state: WindowInfoImpl, entry: ToolWindowEntry, dirtyMode: Boolean) {
saveFloatingOrWindowedState(entry, state)
removeDecoratorWithoutUpdatingState(entry, state, dirtyMode)
}
private fun removeDecoratorWithoutUpdatingState(entry: ToolWindowEntry, state: WindowInfoImpl, dirtyMode: Boolean) {
entry.windowedDecorator?.let {
entry.windowedDecorator = null
Disposer.dispose(it)
return
}
entry.floatingDecorator?.let {
entry.floatingDecorator = null
it.dispose()
return
}
entry.toolWindow.decoratorComponent?.let {
val toolWindowPane = getToolWindowPane(state.safeToolWindowPaneId)
toolWindowPane.removeDecorator(state, it, dirtyMode, this)
return
}
}
private fun saveFloatingOrWindowedState(entry: ToolWindowEntry, info: WindowInfoImpl) {
entry.floatingDecorator?.let {
info.floatingBounds = it.bounds
info.isActiveOnStart = it.isActive
return
}
entry.windowedDecorator?.let { windowedDecorator ->
info.isActiveOnStart = windowedDecorator.isActive
val frame = windowedDecorator.getFrame()
if (frame.isShowing) {
val maximized = (frame as JFrame).extendedState == Frame.MAXIMIZED_BOTH
if (maximized) {
frame.extendedState = Frame.NORMAL
frame.invalidate()
frame.revalidate()
}
val bounds = getRootBounds(frame)
info.floatingBounds = bounds
info.isMaximized = maximized
}
return
}
}
override fun getLayout(): DesktopLayout {
ApplicationManager.getApplication().assertIsDispatchThread()
return layoutState
}
@VisibleForTesting
fun setLayoutOnInit(newLayout: DesktopLayout) {
if (!idToEntry.isEmpty()) {
LOG.error("idToEntry must be empty (idToEntry={\n${idToEntry.entries.joinToString(separator = "\n") { (k, v) -> "$k: $v" }})")
}
layoutState = newLayout
}
override fun setLayout(newLayout: DesktopLayout) {
ApplicationManager.getApplication().assertIsDispatchThread()
if (idToEntry.isEmpty()) {
layoutState = newLayout
return
}
data class LayoutData(val old: WindowInfoImpl, val new: WindowInfoImpl, val entry: ToolWindowEntry)
val list = mutableListOf<LayoutData>()
for (entry in idToEntry.values) {
val old = layoutState.getInfo(entry.id) ?: entry.readOnlyWindowInfo as WindowInfoImpl
val new = newLayout.getInfo(entry.id)
// just copy if defined in the old layout but not in the new
if (new == null) {
newLayout.addInfo(entry.id, old.copy())
}
else if (old != new) {
list.add(LayoutData(old = old, new = new, entry = entry))
}
}
this.layoutState = newLayout
if (list.isEmpty()) {
return
}
for (item in list) {
item.entry.applyWindowInfo(item.new)
if (item.old.isVisible && !item.new.isVisible) {
updateStateAndRemoveDecorator(item.new, item.entry, dirtyMode = true)
}
if (item.old.safeToolWindowPaneId != item.new.safeToolWindowPaneId
|| item.old.anchor != item.new.anchor
|| item.old.order != item.new.order) {
setToolWindowAnchorImpl(item.entry, item.old, item.new, item.new.safeToolWindowPaneId, item.new.anchor, item.new.order)
}
var toShowWindow = false
if (item.old.isSplit != item.new.isSplit) {
val wasVisible = item.old.isVisible
// we should hide the window and show it in a 'new place' to automatically hide possible window that is already located in a 'new place'
if (wasVisible) {
hideToolWindow(item.entry.id)
}
if (wasVisible) {
toShowWindow = true
}
}
if (item.old.type != item.new.type) {
val dirtyMode = item.old.type == ToolWindowType.DOCKED || item.old.type == ToolWindowType.SLIDING
updateStateAndRemoveDecorator(item.old, item.entry, dirtyMode)
if (item.new.isVisible) {
toShowWindow = true
}
}
else if (!item.old.isVisible && item.new.isVisible) {
toShowWindow = true
}
if (toShowWindow) {
doShowWindow(item.entry, item.new, dirtyMode = true)
}
}
val rootPanes = HashSet<JRootPane>()
list.forEach { layoutData ->
getToolWindowPane(layoutData.entry.toolWindow).let { toolWindowPane ->
toolWindowPane.buttonManager.revalidateNotEmptyStripes()
toolWindowPane.validate()
toolWindowPane.repaint()
toolWindowPane.frame.rootPane?.let { rootPanes.add(it) }
}
}
activateEditorComponent()
rootPanes.forEach {
it.revalidate()
it.repaint()
}
fireStateChanged(ToolWindowManagerEventType.SetLayout)
checkInvariants(null)
}
override fun invokeLater(runnable: Runnable) {
if (!toolWindowSetInitializer.addToPendingTasksIfNotInitialized(runnable)) {
ApplicationManager.getApplication().invokeLater(runnable, ModalityState.NON_MODAL, project.disposed)
}
}
override val focusManager: IdeFocusManager
get() = IdeFocusManager.getInstance(project)!!
override fun canShowNotification(toolWindowId: String): Boolean {
val readOnlyWindowInfo = idToEntry.get(toolWindowId)?.readOnlyWindowInfo
val anchor = readOnlyWindowInfo?.anchor ?: return false
val isSplit = readOnlyWindowInfo.isSplit
return toolWindowPanes.values.firstNotNullOfOrNull { it.buttonManager.getStripeFor(anchor, isSplit).getButtonFor(toolWindowId) } != null
}
override fun notifyByBalloon(options: ToolWindowBalloonShowOptions) {
if (isNewUi) {
notifySquareButtonByBalloon(options)
return
}
val entry = idToEntry.get(options.toolWindowId)!!
entry.balloon?.let {
Disposer.dispose(it)
}
val toolWindowPane = getToolWindowPane(entry.toolWindow)
val stripe = toolWindowPane.buttonManager.getStripeFor(entry.readOnlyWindowInfo.anchor, entry.readOnlyWindowInfo.isSplit)
if (!entry.toolWindow.isAvailable) {
entry.toolWindow.isPlaceholderMode = true
stripe.updatePresentation()
stripe.revalidate()
stripe.repaint()
}
val anchor = entry.readOnlyWindowInfo.anchor
val position = Ref(Balloon.Position.below)
when(anchor) {
ToolWindowAnchor.TOP -> position.set(Balloon.Position.below)
ToolWindowAnchor.BOTTOM -> position.set(Balloon.Position.above)
ToolWindowAnchor.LEFT -> position.set(Balloon.Position.atRight)
ToolWindowAnchor.RIGHT -> position.set(Balloon.Position.atLeft)
}
if (!entry.readOnlyWindowInfo.isVisible) {
toolWindowAvailable(entry.toolWindow)
}
val balloon = createBalloon(options, entry)
val button = stripe.getButtonFor(options.toolWindowId)?.getComponent()
LOG.assertTrue(button != null, "Button was not found, popup won't be shown. $options")
if (button == null) {
return
}
val show = Runnable {
val tracker: PositionTracker<Balloon>
if (entry.toolWindow.isVisible &&
(entry.toolWindow.type == ToolWindowType.WINDOWED ||
entry.toolWindow.type == ToolWindowType.FLOATING)) {
tracker = createPositionTracker(entry.toolWindow.component, ToolWindowAnchor.BOTTOM)
}
else if (!button.isShowing) {
tracker = createPositionTracker(toolWindowPane, anchor)
}
else {
tracker = object : PositionTracker<Balloon>(button) {
override fun recalculateLocation(b: Balloon): RelativePoint? {
val otherEntry = idToEntry.get(options.toolWindowId) ?: return null
val stripeButton = otherEntry.stripeButton
if (stripeButton == null || otherEntry.readOnlyWindowInfo.anchor != anchor) {
b.hide()
return null
}
val component = stripeButton.getComponent()
return RelativePoint(component, Point(component.bounds.width / 2, component.height / 2 - 2))
}
}
}
if (!balloon.isDisposed) {
balloon.show(tracker, position.get())
}
}
if (button.isValid) {
show.run()
}
else {
SwingUtilities.invokeLater(show)
}
}
private fun notifySquareButtonByBalloon(options: ToolWindowBalloonShowOptions) {
val entry = idToEntry.get(options.toolWindowId)!!
val existing = entry.balloon
if (existing != null) {
Disposer.dispose(existing)
}
val anchor = entry.readOnlyWindowInfo.anchor
val position = Ref(Balloon.Position.atLeft)
when (anchor) {
ToolWindowAnchor.TOP -> position.set(Balloon.Position.atRight)
ToolWindowAnchor.RIGHT -> position.set(Balloon.Position.atRight)
ToolWindowAnchor.BOTTOM -> position.set(Balloon.Position.atLeft)
ToolWindowAnchor.LEFT -> position.set(Balloon.Position.atLeft)
}
val balloon = createBalloon(options, entry)
val toolWindowPane = getToolWindowPane(entry.readOnlyWindowInfo.safeToolWindowPaneId)
val buttonManager = toolWindowPane.buttonManager as ToolWindowPaneNewButtonManager
var button = buttonManager.getSquareStripeFor(entry.readOnlyWindowInfo.anchor).getButtonFor(options.toolWindowId)?.getComponent()
if (button == null || !button.isShowing) {
button = (buttonManager.getSquareStripeFor(ToolWindowAnchor.LEFT) as? ToolWindowLeftToolbar)?.moreButton!!
position.set(Balloon.Position.atLeft)
}
val show = Runnable {
val tracker: PositionTracker<Balloon>
if (entry.toolWindow.isVisible &&
(entry.toolWindow.type == ToolWindowType.WINDOWED ||
entry.toolWindow.type == ToolWindowType.FLOATING)) {
tracker = createPositionTracker(entry.toolWindow.component, ToolWindowAnchor.BOTTOM)
}
else {
tracker = object : PositionTracker<Balloon>(button) {
override fun recalculateLocation(balloon: Balloon): RelativePoint? {
val otherEntry = idToEntry.get(options.toolWindowId) ?: return null
if (otherEntry.readOnlyWindowInfo.anchor != anchor) {
balloon.hide()
return null
}
return RelativePoint(button,
Point(if (position.get() == Balloon.Position.atRight) 0 else button.bounds.width, button.height / 2))
}
}
}
if (!balloon.isDisposed) {
balloon.show(tracker, position.get())
}
}
if (button.isValid) {
show.run()
}
else {
SwingUtilities.invokeLater(show)
}
}
private fun createPositionTracker(component: Component, anchor: ToolWindowAnchor): PositionTracker<Balloon> {
return object : PositionTracker<Balloon>(component) {
override fun recalculateLocation(balloon: Balloon): RelativePoint {
val bounds = component.bounds
val target = StartupUiUtil.getCenterPoint(bounds, Dimension(1, 1))
when(anchor) {
ToolWindowAnchor.TOP -> target.y = 0
ToolWindowAnchor.BOTTOM -> target.y = bounds.height - 3
ToolWindowAnchor.LEFT -> target.x = 0
ToolWindowAnchor.RIGHT -> target.x = bounds.width
}
return RelativePoint(component, target)
}
}
}
private fun createBalloon(options: ToolWindowBalloonShowOptions, entry: ToolWindowEntry): Balloon {
val listenerWrapper = BalloonHyperlinkListener(options.listener)
val content = options.htmlBody.replace("\n", "<br>")
val balloonBuilder = JBPopupFactory.getInstance()
.createHtmlTextBalloonBuilder(content, options.icon, options.type.titleForeground, options.type.popupBackground, listenerWrapper)
.setBorderColor(options.type.borderColor)
.setHideOnClickOutside(false)
.setHideOnFrameResize(false)
options.balloonCustomizer?.accept(balloonBuilder)
val balloon = balloonBuilder.createBalloon()
if (balloon is BalloonImpl) {
NotificationsManagerImpl.frameActivateBalloonListener(balloon, Runnable {
EdtExecutorService.getScheduledExecutorInstance().schedule({ balloon.setHideOnClickOutside(true) }, 100, TimeUnit.MILLISECONDS)
})
}
listenerWrapper.balloon = balloon
entry.balloon = balloon
Disposer.register(balloon, Disposable {
entry.toolWindow.isPlaceholderMode = false
entry.balloon = null
})
Disposer.register(entry.disposable, balloon)
return balloon
}
override fun getToolWindowBalloon(id: String) = idToEntry[id]?.balloon
override val isEditorComponentActive: Boolean get() = state.isEditorComponentActive
fun setToolWindowAnchor(id: String, anchor: ToolWindowAnchor) {
ApplicationManager.getApplication().assertIsDispatchThread()
setToolWindowAnchor(id, anchor, -1)
}
// used by Rider
@Suppress("MemberVisibilityCanBePrivate")
fun setToolWindowAnchor(id: String, anchor: ToolWindowAnchor, order: Int) {
val entry = idToEntry.get(id)!!
val info = entry.readOnlyWindowInfo
if (anchor == info.anchor && (order == info.order || order == -1)) {
return
}
ApplicationManager.getApplication().assertIsDispatchThread()
setToolWindowAnchorImpl(entry, info, getRegisteredMutableInfoOrLogError(id), info.safeToolWindowPaneId, anchor, order)
getToolWindowPane(info.safeToolWindowPaneId).validateAndRepaint()
fireStateChanged(ToolWindowManagerEventType.SetToolWindowAnchor)
}
fun setVisibleOnLargeStripe(id: String, visible: Boolean) {
val info = getRegisteredMutableInfoOrLogError(id)
info.isShowStripeButton = visible
idToEntry.get(info.id)!!.applyWindowInfo(info.copy())
fireStateChanged(ToolWindowManagerEventType.SetVisibleOnLargeStripe)
}
private fun setToolWindowAnchorImpl(entry: ToolWindowEntry,
currentInfo: WindowInfo,
layoutInfo: WindowInfoImpl,
paneId: String,
anchor: ToolWindowAnchor,
order: Int) {
// Get the current tool window pane, not the one we're aiming for
val toolWindowPane = getToolWindowPane(currentInfo.safeToolWindowPaneId)
// if tool window isn't visible or only order number is changed then just remove/add stripe button
if (!currentInfo.isVisible || (paneId == currentInfo.safeToolWindowPaneId && anchor == currentInfo.anchor) ||
currentInfo.type == ToolWindowType.FLOATING || currentInfo.type == ToolWindowType.WINDOWED) {
doSetAnchor(entry, layoutInfo, paneId, anchor, order)
}
else {
val wasFocused = entry.toolWindow.isActive
// for docked and sliding windows we have to move buttons and window's decorators
layoutInfo.isVisible = false
toolWindowPane.removeDecorator(currentInfo, entry.toolWindow.decoratorComponent, /* dirtyMode = */ true, this)
doSetAnchor(entry, layoutInfo, paneId, anchor, order)
showToolWindowImpl(entry, layoutInfo, false)
if (wasFocused) {
entry.toolWindow.requestFocusInToolWindow()
}
}
}
private fun doSetAnchor(entry: ToolWindowEntry, info: WindowInfoImpl, paneId: String, anchor: ToolWindowAnchor, order: Int) {
entry.removeStripeButton()
for (otherInfo in layoutState.setAnchor(info, paneId, anchor, order)) {
idToEntry.get(otherInfo.id ?: continue)?.toolWindow?.setWindowInfoSilently(otherInfo.copy())
}
entry.toolWindow.applyWindowInfo(info.copy())
entry.stripeButton = getToolWindowPane(paneId).buttonManager.createStripeButton(entry.toolWindow, info, task = null)
}
internal fun setSideTool(id: String, isSplit: Boolean) {
val entry = idToEntry.get(id)
if (entry == null) {
LOG.error("Cannot set side tool: toolwindow $id is not registered")
return
}
if (entry.readOnlyWindowInfo.isSplit != isSplit) {
setSideTool(entry, getRegisteredMutableInfoOrLogError(id), isSplit)
fireStateChanged(ToolWindowManagerEventType.SetSideTool)
}
}
private fun setSideTool(entry: ToolWindowEntry, info: WindowInfoImpl, isSplit: Boolean) {
if (isSplit == info.isSplit) {
return
}
// we should hide the window and show it in a 'new place' to automatically hide possible window that is already located in a 'new place'
hideIfNeededAndShowAfterTask(entry, info) {
info.isSplit = isSplit
for (otherEntry in idToEntry.values) {
otherEntry.applyWindowInfo((layoutState.getInfo(otherEntry.id) ?: continue).copy())
}
}
getToolWindowPane(info.safeToolWindowPaneId).buttonManager.getStripeFor(entry.readOnlyWindowInfo.anchor,
entry.readOnlyWindowInfo.isSplit).revalidate()
}
fun setContentUiType(id: String, type: ToolWindowContentUiType) {
val info = getRegisteredMutableInfoOrLogError(id)
info.contentUiType = type
idToEntry.get(info.id!!)!!.applyWindowInfo(info.copy())
fireStateChanged(ToolWindowManagerEventType.SetContentUiType)
}
internal fun setSideToolAndAnchor(id: String, paneId: String, anchor: ToolWindowAnchor, order: Int, isSplit: Boolean) {
val entry = idToEntry.get(id)!!
val readOnlyInfo = entry.readOnlyWindowInfo
if (paneId == readOnlyInfo.safeToolWindowPaneId && anchor == readOnlyInfo.anchor
&& order == readOnlyInfo.order && readOnlyInfo.isSplit == isSplit) {
return
}
val info = getRegisteredMutableInfoOrLogError(id)
hideIfNeededAndShowAfterTask(entry, info) {
info.isSplit = isSplit
doSetAnchor(entry, info, paneId, anchor, order)
}
fireStateChanged(ToolWindowManagerEventType.SetSideToolAndAnchor)
}
private fun hideIfNeededAndShowAfterTask(entry: ToolWindowEntry,
info: WindowInfoImpl,
source: ToolWindowEventSource? = null,
task: () -> Unit) {
val wasVisible = entry.readOnlyWindowInfo.isVisible
val wasFocused = entry.toolWindow.isActive
if (wasVisible) {
executeHide(entry, info, dirtyMode = true)
}
task()
if (wasVisible) {
ToolWindowCollector.getInstance().recordShown(project, source, info)
info.isVisible = true
val infoSnapshot = info.copy()
entry.applyWindowInfo(infoSnapshot)
doShowWindow(entry, infoSnapshot, dirtyMode = true)
if (wasFocused) {
getShowingComponentToRequestFocus(entry.toolWindow)?.requestFocusInWindow()
}
}
getToolWindowPane(info.safeToolWindowPaneId).validateAndRepaint()
}
protected open fun fireStateChanged(changeType: ToolWindowManagerEventType) {
project.messageBus.syncPublisher(ToolWindowManagerListener.TOPIC).stateChanged(this, changeType)
}
private fun fireToolWindowShown(toolWindow: ToolWindow) {
project.messageBus.syncPublisher(ToolWindowManagerListener.TOPIC).toolWindowShown(toolWindow)
}
internal fun setToolWindowAutoHide(id: String, autoHide: Boolean) {
ApplicationManager.getApplication().assertIsDispatchThread()
val info = getRegisteredMutableInfoOrLogError(id)
if (info.isAutoHide == autoHide) {
return
}
info.isAutoHide = autoHide
val entry = idToEntry.get(id) ?: return
val newInfo = info.copy()
entry.applyWindowInfo(newInfo)
fireStateChanged(ToolWindowManagerEventType.SetToolWindowAutoHide)
}
fun setToolWindowType(id: String, type: ToolWindowType) {
ApplicationManager.getApplication().assertIsDispatchThread()
val entry = idToEntry.get(id)!!
if (entry.readOnlyWindowInfo.type == type) {
return
}
setToolWindowTypeImpl(entry, getRegisteredMutableInfoOrLogError(entry.id), type)
fireStateChanged(ToolWindowManagerEventType.SetToolWindowType)
}
private fun setToolWindowTypeImpl(entry: ToolWindowEntry, info: WindowInfoImpl, type: ToolWindowType) {
if (!entry.readOnlyWindowInfo.isVisible) {
info.type = type
entry.applyWindowInfo(info.copy())
return
}
val dirtyMode = entry.readOnlyWindowInfo.type == ToolWindowType.DOCKED || entry.readOnlyWindowInfo.type == ToolWindowType.SLIDING
updateStateAndRemoveDecorator(info, entry, dirtyMode)
info.type = type
if (type != ToolWindowType.FLOATING && type != ToolWindowType.WINDOWED) {
info.internalType = type
}
val newInfo = info.copy()
entry.applyWindowInfo(newInfo)
doShowWindow(entry, newInfo, dirtyMode)
if (ApplicationManager.getApplication().isActive) {
entry.toolWindow.requestFocusInToolWindow()
}
val frame = frameState!!
val rootPane = frame.rootPane ?: return
rootPane.revalidate()
rootPane.repaint()
}
override fun clearSideStack() {
if (isStackEnabled) {
sideStack.clear()
}
}
internal fun setDefaultState(toolWindow: ToolWindowImpl, anchor: ToolWindowAnchor?, type: ToolWindowType?, floatingBounds: Rectangle?) {
val info = getRegisteredMutableInfoOrLogError(toolWindow.id)
if (info.isFromPersistentSettings) {
return
}
if (floatingBounds != null) {
info.floatingBounds = floatingBounds
}
if (anchor != null) {
toolWindow.setAnchor(anchor, null)
}
if (type != null) {
toolWindow.setType(type, null)
}
}
internal fun setDefaultContentUiType(toolWindow: ToolWindowImpl, type: ToolWindowContentUiType) {
val info = getRegisteredMutableInfoOrLogError(toolWindow.id)
if (info.isFromPersistentSettings) {
return
}
toolWindow.setContentUiType(type, null)
}
internal fun stretchWidth(toolWindow: ToolWindowImpl, value: Int) {
getToolWindowPane(toolWindow).stretchWidth(toolWindow, value)
}
override fun isMaximized(window: ToolWindow) = getToolWindowPane(window).isMaximized(window)
override fun setMaximized(window: ToolWindow, maximized: Boolean) {
if (window.type == ToolWindowType.FLOATING && window is ToolWindowImpl) {
MaximizeActiveDialogAction.doMaximize(idToEntry.get(window.id)?.floatingDecorator)
return
}
if (window.type == ToolWindowType.WINDOWED && window is ToolWindowImpl) {
val decorator = getWindowedDecorator(window.id)
val frame = if (decorator != null && decorator.getFrame() is Frame) decorator.getFrame() as Frame else return
val state = frame.state
if (state == Frame.NORMAL) {
frame.state = Frame.MAXIMIZED_BOTH
}
else if (state == Frame.MAXIMIZED_BOTH) {
frame.state = Frame.NORMAL
}
return
}
getToolWindowPane(window).setMaximized(window, maximized)
}
internal fun stretchHeight(toolWindow: ToolWindowImpl, value: Int) {
getToolWindowPane(toolWindow).stretchHeight(toolWindow, value)
}
private fun addFloatingDecorator(entry: ToolWindowEntry, info: WindowInfo) {
val frame = frameState!!.frameOrNull
val decorator = entry.toolWindow.getOrCreateDecoratorComponent()
val floatingDecorator = FloatingDecorator(frame!!, decorator)
floatingDecorator.apply(info)
entry.floatingDecorator = floatingDecorator
val bounds = info.floatingBounds
if ((bounds != null && bounds.width > 0 && bounds.height > 0 &&
WindowManager.getInstance().isInsideScreenBounds(bounds.x, bounds.y, bounds.width))) {
floatingDecorator.bounds = Rectangle(bounds)
}
else {
// place new frame at the center of main frame if there are no floating bounds
var size = decorator.size
if (size.width == 0 || size.height == 0) {
size = decorator.preferredSize
}
floatingDecorator.size = size
floatingDecorator.setLocationRelativeTo(frame)
}
@Suppress("DEPRECATION")
floatingDecorator.show()
}
private fun addWindowedDecorator(entry: ToolWindowEntry, info: WindowInfo) {
val app = ApplicationManager.getApplication()
if (app.isHeadlessEnvironment || app.isUnitTestMode) {
return
}
val id = entry.id
val decorator = entry.toolWindow.getOrCreateDecoratorComponent()
val windowedDecorator = FrameWrapper(project, title = "${entry.toolWindow.stripeTitle} - ${project.name}", component = decorator)
val window = windowedDecorator.getFrame()
MnemonicHelper.init((window as RootPaneContainer).contentPane)
val shouldBeMaximized = info.isMaximized
val bounds = info.floatingBounds
if ((bounds != null && bounds.width > 0 && (bounds.height > 0) &&
WindowManager.getInstance().isInsideScreenBounds(bounds.x, bounds.y, bounds.width))) {
window.bounds = Rectangle(bounds)
}
else {
// place new frame at the center of main frame if there are no floating bounds
var size = decorator.size
if (size.width == 0 || size.height == 0) {
size = decorator.preferredSize
}
window.size = size
window.setLocationRelativeTo(frameState!!.frameOrNull)
}
entry.windowedDecorator = windowedDecorator
Disposer.register(windowedDecorator, Disposable {
if (idToEntry.get(id)?.windowedDecorator != null) {
hideToolWindow(id, false)
}
})
windowedDecorator.show(false)
val rootPane = (window as RootPaneContainer).rootPane
val rootPaneBounds = rootPane.bounds
val point = rootPane.locationOnScreen
val windowBounds = window.bounds
window.setLocation(2 * windowBounds.x - point.x, 2 * windowBounds.y - point.y)
window.setSize(2 * windowBounds.width - rootPaneBounds.width, 2 * windowBounds.height - rootPaneBounds.height)
if (shouldBeMaximized && window is Frame) {
window.extendedState = Frame.MAXIMIZED_BOTH
}
window.toFront()
}
internal fun toolWindowAvailable(toolWindow: ToolWindowImpl) {
if (!toolWindow.isShowStripeButton) {
return
}
val entry = idToEntry.get(toolWindow.id) ?: return
if (entry.stripeButton == null) {
val buttonManager = getButtonManager(entry.toolWindow)
entry.stripeButton = buttonManager.createStripeButton(entry.toolWindow, entry.readOnlyWindowInfo, task = null)
}
val info = layoutState.getInfo(toolWindow.id)
if (info != null && info.isVisible) {
LOG.assertTrue(!entry.readOnlyWindowInfo.isVisible)
if (showToolWindowImpl(entry = entry, toBeShownInfo = info, dirtyMode = false)) {
fireStateChanged(ToolWindowManagerEventType.ToolWindowAvailable)
}
}
}
internal fun toolWindowUnavailable(toolWindow: ToolWindowImpl) {
val entry = idToEntry.get(toolWindow.id)!!
val moveFocusAfter = toolWindow.isActive && toolWindow.isVisible
val info = getRegisteredMutableInfoOrLogError(toolWindow.id)
executeHide(entry, info, dirtyMode = false, mutation = {
entry.removeStripeButton()
})
fireStateChanged(ToolWindowManagerEventType.ToolWindowUnavailable)
if (moveFocusAfter) {
activateEditorComponent()
}
}
/**
* Spies on IdeToolWindow properties and applies them to the window state.
*/
open fun toolWindowPropertyChanged(toolWindow: ToolWindow, property: ToolWindowProperty) {
val stripeButton = idToEntry.get(toolWindow.id)?.stripeButton
if (stripeButton != null) {
if (property == ToolWindowProperty.ICON) {
stripeButton.updateIcon(toolWindow.icon)
}
else {
stripeButton.updatePresentation()
}
}
ActivateToolWindowAction.updateToolWindowActionPresentation(toolWindow)
}
internal fun activated(toolWindow: ToolWindowImpl, source: ToolWindowEventSource?) {
val info = getRegisteredMutableInfoOrLogError(toolWindow.id)
if (isNewUi) {
val visibleToolWindow = idToEntry.values
.asSequence()
.filter { it.toolWindow.isVisible && it.readOnlyWindowInfo.anchor == info.anchor }
.firstOrNull()
if (visibleToolWindow != null) {
info.weight = visibleToolWindow.readOnlyWindowInfo.weight
}
}
activateToolWindow(entry = idToEntry.get(toolWindow.id)!!, info = info, source = source)
}
/**
* Handles event from decorator and modify weight/floating bounds of the
* tool window depending on decoration type.
*/
fun resized(source: InternalDecoratorImpl) {
if (!source.isShowing) {
// do not recalculate the tool window size if it is not yet shown (and, therefore, has 0,0,0,0 bounds)
return
}
val toolWindow = source.toolWindow
val info = getRegisteredMutableInfoOrLogError(toolWindow.id)
if (info.type == ToolWindowType.FLOATING) {
val owner = SwingUtilities.getWindowAncestor(source)
if (owner != null) {
info.floatingBounds = owner.bounds
}
}
else if (info.type == ToolWindowType.WINDOWED) {
val decorator = getWindowedDecorator(toolWindow.id)
val frame = decorator?.getFrame()
if (frame == null || !frame.isShowing) {
return
}
info.floatingBounds = getRootBounds(frame as JFrame)
info.isMaximized = frame.extendedState == Frame.MAXIMIZED_BOTH
}
else {
// docked and sliding windows
val anchor = if (isNewUi) info.anchor else info.anchor
var another: InternalDecoratorImpl? = null
val wholeSize = getToolWindowPane(toolWindow).rootPane.size
if (source.parent is Splitter) {
var sizeInSplit = if (anchor.isSplitVertically) source.height else source.width
val splitter = source.parent as Splitter
if (splitter.secondComponent === source) {
sizeInSplit += splitter.dividerWidth
another = splitter.firstComponent as InternalDecoratorImpl
}
else {
another = splitter.secondComponent as InternalDecoratorImpl
}
info.sideWeight = getAdjustedRatio(partSize = sizeInSplit,
totalSize = if (anchor.isSplitVertically) splitter.height else splitter.width,
direction = if (splitter.secondComponent === source) -1 else 1)
}
val paneWeight = getAdjustedRatio(partSize = if (anchor.isHorizontal) source.height else source.width,
totalSize = if (anchor.isHorizontal) wholeSize.height else wholeSize.width, direction = 1)
info.weight = paneWeight
if (another != null) {
getRegisteredMutableInfoOrLogError(another.toolWindow.id).weight = paneWeight
}
}
fireStateChanged(Resized)
}
private fun focusToolWindowByDefault() {
var toFocus: ToolWindowEntry? = null
for (each in activeStack.stack) {
if (each.readOnlyWindowInfo.isVisible) {
toFocus = each
break
}
}
if (toFocus == null) {
for (each in activeStack.persistentStack) {
if (each.readOnlyWindowInfo.isVisible) {
toFocus = each
break
}
}
}
if (toFocus != null && !ApplicationManager.getApplication().isDisposed) {
activateToolWindow(toFocus, getRegisteredMutableInfoOrLogError(toFocus.id))
}
}
internal fun setShowStripeButton(id: String, value: Boolean) {
if (isNewUi) {
LOG.info("Ignore setShowStripeButton(id=$id, value=$value) - not applicable for a new UI")
return
}
val entry = idToEntry.get(id) ?: throw IllegalStateException("window with id=\"$id\" isn't registered")
var info = layoutState.getInfo(id)
if (info == null) {
if (!value) {
return
}
// window was registered but stripe button was not shown, so, layout was not added to a list
info = (entry.readOnlyWindowInfo as WindowInfoImpl).copy()
layoutState.addInfo(id, info)
}
if (value == info.isShowStripeButton) {
return
}
info.isShowStripeButton = value
if (!value) {
entry.removeStripeButton()
}
entry.applyWindowInfo(info.copy())
if (value && entry.stripeButton == null) {
val buttonManager = getButtonManager(entry.toolWindow)
entry.stripeButton = buttonManager.createStripeButton(entry.toolWindow, entry.readOnlyWindowInfo, task = null)
}
fireStateChanged(ToolWindowManagerEventType.SetShowStripeButton)
}
private fun checkInvariants(id: String?) {
val app = ApplicationManager.getApplication()
if (!app.isEAP && !app.isInternal) {
return
}
val violations = mutableListOf<String>()
for (entry in idToEntry.values) {
val info = layoutState.getInfo(entry.id) ?: continue
if (!info.isVisible) {
continue
}
if (!app.isHeadlessEnvironment && !app.isUnitTestMode) {
if (info.type == ToolWindowType.FLOATING) {
if (entry.floatingDecorator == null) {
violations.add("Floating window has no decorator: ${entry.id}")
}
}
else if (info.type == ToolWindowType.WINDOWED && entry.windowedDecorator == null) {
violations.add("Windowed window has no decorator: ${entry.id}")
}
}
}
if (violations.isNotEmpty()) {
LOG.error("Invariants failed: \n${violations.joinToString("\n")}\n${if (id == null) "" else "id: $id"}")
}
}
}
private enum class KeyState {
WAITING, PRESSED, RELEASED, HOLD
}
private fun areAllModifiersPressed(@JdkConstants.InputEventMask modifiers: Int, @JdkConstants.InputEventMask mask: Int): Boolean {
return (modifiers xor mask) == 0
}
@Suppress("DEPRECATION")
@JdkConstants.InputEventMask
private fun keyCodeToInputMask(code: Int): Int {
return when (code) {
KeyEvent.VK_SHIFT -> Event.SHIFT_MASK
KeyEvent.VK_CONTROL -> Event.CTRL_MASK
KeyEvent.VK_META -> Event.META_MASK
KeyEvent.VK_ALT -> Event.ALT_MASK
else -> 0
}
}
// We should filter out 'mixed' mask like InputEvent.META_MASK | InputEvent.META_DOWN_MASK
@JdkConstants.InputEventMask
private fun getActivateToolWindowVKsMask(): Int {
if (!LoadingState.COMPONENTS_LOADED.isOccurred) {
return 0
}
if (Registry.`is`("toolwindow.disable.overlay.by.double.key")) {
return 0
}
val baseShortcut = KeymapManager.getInstance().activeKeymap.getShortcuts("ActivateProjectToolWindow")
@Suppress("DEPRECATION")
var baseModifiers = if (SystemInfoRt.isMac) InputEvent.META_MASK else InputEvent.ALT_MASK
for (each in baseShortcut) {
if (each is KeyboardShortcut) {
val keyStroke = each.firstKeyStroke
baseModifiers = keyStroke.modifiers
if (baseModifiers > 0) {
break
}
}
}
// We should filter out 'mixed' mask like InputEvent.META_MASK | InputEvent.META_DOWN_MASK
@Suppress("DEPRECATION")
return baseModifiers and (InputEvent.SHIFT_MASK or InputEvent.CTRL_MASK or InputEvent.META_MASK or InputEvent.ALT_MASK)
}
private val isStackEnabled: Boolean
get() = Registry.`is`("ide.enable.toolwindow.stack")
private fun getRootBounds(frame: JFrame): Rectangle {
val rootPane = frame.rootPane
val bounds = rootPane.bounds
bounds.setLocation(frame.x + rootPane.x, frame.y + rootPane.y)
return bounds
}
private fun getToolWindowIdForComponent(component: Component?): String? {
var c = component
while (c != null) {
if (c is InternalDecoratorImpl) {
return c.toolWindow.id
}
c = ClientProperty.get(c, ToolWindowManagerImpl.PARENT_COMPONENT) ?: c.parent
}
return null
}
private class BalloonHyperlinkListener(private val listener: HyperlinkListener?) : HyperlinkListener {
var balloon: Balloon? = null
override fun hyperlinkUpdate(e: HyperlinkEvent) {
val balloon = balloon
if (balloon != null && e.eventType == HyperlinkEvent.EventType.ACTIVATED) {
balloon.hide()
}
listener?.hyperlinkUpdate(e)
}
} | apache-2.0 | c937bb14063b904ddf49b90cb6b9d033 | 37.220712 | 147 | 0.686901 | 5.044968 | false | false | false | false |
Briseus/Lurker | app/src/main/java/torille/fi/lurkforreddit/subreddits/SubredditsAdapter.kt | 1 | 2331 | package torille.fi.lurkforreddit.subreddits
import android.content.res.ColorStateList
import android.graphics.Color
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.TextView
import torille.fi.lurkforreddit.R
import torille.fi.lurkforreddit.data.models.view.Subreddit
import java.util.*
/**
* [RecyclerView.Adapter] for showing subreddits
*/
internal class SubredditsAdapter internal constructor(
private val mItemListener: SubredditsFragment.SubredditItemListener,
color: Int
) : RecyclerView.Adapter<SubredditsAdapter.ViewHolder>() {
private val mSubreddits: MutableList<Subreddit> = ArrayList(25)
private val mDefaultColor: ColorStateList = ColorStateList.valueOf(color)
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val context = parent.context
val inflater = LayoutInflater.from(context)
val subredditsView = inflater.inflate(R.layout.item_subreddit, parent, false)
return ViewHolder(subredditsView)
}
override fun onBindViewHolder(viewHolder: ViewHolder, position: Int) {
val (_, _, displayName, _, keyColor) = mSubreddits[position]
viewHolder.title.text = displayName
if (keyColor.isNullOrEmpty()) {
viewHolder.colorButton.backgroundTintList = mDefaultColor
} else {
viewHolder.colorButton.backgroundTintList =
ColorStateList.valueOf(Color.parseColor(keyColor))
}
}
internal fun replaceData(subreddits: List<Subreddit>) {
mSubreddits.clear()
mSubreddits.addAll(subreddits)
notifyDataSetChanged()
}
override fun getItemCount(): Int {
return mSubreddits.size
}
internal inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView),
View.OnClickListener {
val title: TextView = itemView.findViewById(R.id.item_subreddit_title)
val colorButton: Button = itemView.findViewById(R.id.item_subreddit_circle)
init {
itemView.setOnClickListener(this)
}
override fun onClick(v: View) {
mItemListener.onSubredditClick(mSubreddits[adapterPosition])
}
}
} | mit | 6af56d3c33936040174da15a90225cbb | 32.797101 | 88 | 0.715573 | 4.917722 | false | false | false | false |
sandipv22/pointer_replacer | ui/magisk/src/main/java/com/afterroot/allusive2/magisk/ZipUtils.kt | 1 | 2834 | /*
* Copyright (C) 2016-2021 Sandip Vaghela
* 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.afterroot.allusive2.magisk
import java.io.File
import java.io.FileInputStream
import java.io.FileOutputStream
import java.io.IOException
import java.io.InputStream
import java.util.zip.ZipEntry
import java.util.zip.ZipInputStream
import java.util.zip.ZipOutputStream
@Throws(IOException::class)
fun File.unzip(toFolder: File, path: String = "", junkPath: Boolean = false) {
inputStream().buffered().use {
it.unzip(toFolder, path, junkPath)
}
}
@Throws(IOException::class)
fun InputStream.unzip(folder: File, path: String, junkPath: Boolean) {
try {
val zin = ZipInputStream(this)
var entry: ZipEntry
while (true) {
entry = zin.nextEntry ?: break
if (!entry.name.startsWith(path) || entry.isDirectory) {
// Ignore directories, only create files
continue
}
val name = if (junkPath)
entry.name.substring(entry.name.lastIndexOf('/') + 1)
else
entry.name
val dest = File(folder, name)
dest.parentFile!!.mkdirs()
FileOutputStream(dest).use { zin.copyTo(it) }
}
} catch (e: IOException) {
e.printStackTrace()
throw e
}
}
var filesListInDir: MutableList<String> = ArrayList()
fun zip(sourceFolder: File, exportPath: String): File {
filesListInDir.clear()
runCatching {
populateFilesList(sourceFolder)
val fos = FileOutputStream(exportPath)
val zos = ZipOutputStream(fos)
for (filePath in filesListInDir) {
val ze = ZipEntry(filePath.substring(sourceFolder.absolutePath.length + 1, filePath.length))
zos.putNextEntry(ze)
val fis = FileInputStream(filePath)
fis.copyTo(zos)
zos.closeEntry()
fis.close()
}
zos.close()
fos.close()
}.onFailure {
it.printStackTrace()
}
return File(exportPath)
}
@Throws(IOException::class)
private fun populateFilesList(dir: File) {
val files = dir.listFiles()
files?.forEach { file ->
if (file.isFile) filesListInDir.add(file.absolutePath) else populateFilesList(file)
}
}
| apache-2.0 | 365cda6775e79328d00397ae32b5bb9b | 30.488889 | 104 | 0.64573 | 4.242515 | false | false | false | false |
dahlstrom-g/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/codeInsight/KotlinExpressionTypeProviderDescriptorsImpl.kt | 2 | 5710 | // 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.codeInsight
import com.intellij.openapi.util.NlsSafe
import org.jetbrains.kotlin.descriptors.CallableDescriptor
import org.jetbrains.kotlin.descriptors.ClassifierDescriptor
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.base.projectStructure.languageVersionSettings
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.caches.resolve.findModuleDescriptor
import org.jetbrains.kotlin.idea.caches.resolve.getResolutionFacade
import org.jetbrains.kotlin.idea.parameterInfo.KotlinIdeDescriptorRenderer
import org.jetbrains.kotlin.idea.resolve.dataFlowValueFactory
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.parents
import org.jetbrains.kotlin.renderer.ClassifierNamePolicy
import org.jetbrains.kotlin.renderer.DescriptorRenderer
import org.jetbrains.kotlin.renderer.ParameterNameRenderingPolicy
import org.jetbrains.kotlin.renderer.RenderingFormat
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.DescriptorUtils
import org.jetbrains.kotlin.resolve.bindingContextUtil.isUsedAsExpression
import org.jetbrains.kotlin.resolve.calls.util.getParameterForArgument
import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall
import org.jetbrains.kotlin.resolve.calls.util.getType
import org.jetbrains.kotlin.resolve.calls.smartcasts.DataFlowInfo
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.expressions.typeInfoFactory.noTypeInfo
class KotlinExpressionTypeProviderDescriptorsImpl : KotlinExpressionTypeProvider() {
private val typeRenderer = KotlinIdeDescriptorRenderer.withOptions {
textFormat = RenderingFormat.HTML
modifiers = emptySet()
parameterNameRenderingPolicy = ParameterNameRenderingPolicy.ONLY_NON_SYNTHESIZED
classifierNamePolicy = object : ClassifierNamePolicy {
override fun renderClassifier(classifier: ClassifierDescriptor, renderer: DescriptorRenderer): String {
if (DescriptorUtils.isAnonymousObject(classifier)) {
return "<" + KotlinBundle.message("type.provider.anonymous.object") + ">"
}
return ClassifierNamePolicy.SHORT.renderClassifier(classifier, renderer)
}
}
}
override fun KtExpression.shouldShowStatementType(): Boolean {
if (parent !is KtBlockExpression) return true
if (parent.children.lastOrNull() == this) {
return isUsedAsExpression(analyze(BodyResolveMode.PARTIAL_WITH_CFA))
}
return false
}
override fun getInformationHint(element: KtExpression): String {
val bindingContext = element.analyze(BodyResolveMode.PARTIAL)
return "<html>${renderExpressionType(element, bindingContext)}</html>"
}
@NlsSafe
private fun renderExpressionType(element: KtExpression, bindingContext: BindingContext): String {
if (element is KtCallableDeclaration) {
val descriptor = bindingContext[BindingContext.DECLARATION_TO_DESCRIPTOR, element] as? CallableDescriptor
if (descriptor != null) {
return descriptor.returnType?.let { typeRenderer.renderType(it) } ?: KotlinBundle.message("type.provider.unknown.type")
}
}
val expressionTypeInfo = bindingContext[BindingContext.EXPRESSION_TYPE_INFO, element] ?: noTypeInfo(DataFlowInfo.EMPTY)
val expressionType = element.getType(bindingContext) ?: getTypeForArgumentName(element, bindingContext)
val result = expressionType?.let { typeRenderer.renderType(it) } ?: return KotlinBundle.message("type.provider.unknown.type")
val dataFlowValueFactory = element.getResolutionFacade().dataFlowValueFactory
val dataFlowValue =
dataFlowValueFactory.createDataFlowValue(element, expressionType, bindingContext, element.findModuleDescriptor())
val types = expressionTypeInfo.dataFlowInfo.getStableTypes(dataFlowValue, element.languageVersionSettings)
if (types.isNotEmpty()) {
return types.joinToString(separator = " & ") { typeRenderer.renderType(it) } +
" " + KotlinBundle.message("type.provider.smart.cast.from", result)
}
val smartCast = bindingContext[BindingContext.SMARTCAST, element]
if (smartCast != null && element is KtReferenceExpression) {
val declaredType = (bindingContext[BindingContext.REFERENCE_TARGET, element] as? CallableDescriptor)?.returnType
if (declaredType != null) {
return result + " " + KotlinBundle.message("type.provider.smart.cast.from", typeRenderer.renderType(declaredType))
}
}
return result
}
private fun getTypeForArgumentName(element: KtExpression, bindingContext: BindingContext): KotlinType? {
val valueArgumentName = (element.parent as? KtValueArgumentName) ?: return null
val argument = valueArgumentName.parent as? KtValueArgument ?: return null
val ktCallExpression = argument.parents.filterIsInstance<KtCallExpression>().firstOrNull() ?: return null
val resolvedCall = ktCallExpression.getResolvedCall(bindingContext) ?: return null
val parameter = resolvedCall.getParameterForArgument(argument) ?: return null
return parameter.type
}
override fun getErrorHint(): String = KotlinBundle.message("type.provider.no.expression.found")
}
| apache-2.0 | 029ffa4beb83d2fd9326e44b5e258797 | 52.364486 | 158 | 0.751839 | 5.277264 | false | false | false | false |
oldcwj/iPing | commons/src/main/kotlin/com/simplemobiletools/commons/dialogs/ConfirmationAdvancedDialog.kt | 1 | 1294 | package com.simplemobiletools.commons.dialogs
import android.content.Context
import android.support.v7.app.AlertDialog
import android.view.LayoutInflater
import com.simplemobiletools.commons.R
import com.simplemobiletools.commons.extensions.setupDialogStuff
import kotlinx.android.synthetic.main.dialog_message.view.*
class ConfirmationAdvancedDialog(context: Context, message: String = "", messageId: Int = R.string.proceed_with_deletion, positive: Int = R.string.yes,
negative: Int, val callback: (result: Boolean) -> Unit) {
var dialog: AlertDialog
init {
val view = LayoutInflater.from(context).inflate(R.layout.dialog_message, null)
view.message.text = if (message.isEmpty()) context.resources.getString(messageId) else message
dialog = AlertDialog.Builder(context)
.setPositiveButton(positive, { dialog, which -> positivePressed() })
.setNegativeButton(negative, { dialog, which -> negativePressed() })
.create().apply {
context.setupDialogStuff(view, this)
}
}
private fun positivePressed() {
dialog.dismiss()
callback(true)
}
private fun negativePressed() {
dialog.dismiss()
callback(false)
}
}
| gpl-3.0 | 1d64f73d0845a072294684aeb95693d3 | 35.971429 | 151 | 0.674652 | 4.621429 | false | false | false | false |
cqjjjzr/Laplacian | Laplacian.Essential.Desktop/src/main/kotlin/charlie/laplacian/output/essential/JavaSoundOutputMethod.kt | 1 | 4704 | package charlie.laplacian.output.essential
import charlie.laplacian.output.*
import java.nio.charset.Charset
import java.util.*
import javax.sound.sampled.*
import javax.sound.sampled.FloatControl.Type.MASTER_GAIN
import kotlin.collections.plusAssign
import kotlin.experimental.and
class JavaSoundOutputMethod : OutputMethod {
override fun init() {}
override fun destroy() {}
override fun openDevice(outputSettings: OutputSettings): OutputDevice
= JavaSoundOutputDevice(outputSettings)
override fun getMetadata(): OutputMethodMetadata = JavaSoundMetadata
override fun getDeviceInfos(): Array<out OutputDeviceInfo> =
AudioSystem.getMixerInfo()
.map { JavaSoundOutputDeviceInfo(AudioSystem.getMixer(it)) }
.filter { it.getAvailableSettings().isNotEmpty() }
.toTypedArray()
}
class JavaSoundOutputDevice(outputSettings: OutputSettings): OutputDevice {
private var audioFormat: AudioFormat? = null
override fun openLine(): OutputLine {
return JavaSoundChannel(audioFormat!!)
}
override fun closeLine(channel: OutputLine) {
if (channel !is JavaSoundChannel) throw ClassCastException()
channel.pause()
channel.dataLine.drain()
channel.dataLine.close()
}
init {
AudioSystem.getMixerInfo()
audioFormat = AudioFormat(
outputSettings.sampleRateHz,
outputSettings.bitDepth,
outputSettings.numChannels,
true,
false)
}
}
class JavaSoundOutputDeviceInfo(private val mixer: Mixer): OutputDeviceInfo {
override fun getName(): String = javaSoundRecoverMessyCode(mixer.mixerInfo.name)
override fun getAvailableSettings(): Array<OutputSettings> =
mixer.sourceLineInfo
.map (AudioSystem::getLine)
.filter { it is SourceDataLine }
.flatMap { (it.lineInfo as DataLine.Info).formats.asIterable() }
.filter { !it.isBigEndian && it.encoding == AudioFormat.Encoding.PCM_SIGNED && it.sampleSizeInBits != 24 }
.map { OutputSettings(it.sampleRate, it.sampleSizeInBits, it.channels) }
.toTypedArray()
}
private val HIGH_IDENTIFY = 0b11000000.toByte()
fun javaSoundRecoverMessyCode(string: String): String {
return String(ArrayList<Byte>().apply buf@ {
string.toByteArray().apply {
var i = 0
while (i < this.size) {
if ((this[i] and HIGH_IDENTIFY) == HIGH_IDENTIFY) {
this@buf += (this[i].toInt() shl 6 or (this[i + 1].toInt() shl 2 ushr 2)).toByte()
i++
} else {
this@buf += this[i]
}
i++
}
}
}.toByteArray(), Charset.forName(System.getProperty("file.encoding")))
}
object JavaSoundMetadata: OutputMethodMetadata {
override fun getName(): String = "Java Sound"
override fun getVersion(): String = "rv1"
override fun getVersionID(): Int = 1
}
class JavaSoundChannel(audioFormat: AudioFormat) : OutputLine {
private val BUFFER_SIZE = 1024
internal val dataLine: SourceDataLine
private val dataLineInfo: DataLine.Info
private var volumeController: JavaSoundVolumeController
override fun mix(pcmData: ByteArray, offset: Int, length: Int) {
dataLine.write(pcmData, offset, length)
}
override fun getVolumeController(): VolumeController = volumeController
override fun setVolumeController(volumeController: VolumeController) {
if (volumeController is JavaSoundVolumeController)
this.volumeController = volumeController
else throw ClassCastException()
}
override fun open() {
dataLine.drain()
dataLine.start()
}
override fun pause() {
dataLine.stop()
}
init {
dataLineInfo = DataLine.Info(SourceDataLine::class.java, audioFormat, BUFFER_SIZE)
dataLine = AudioSystem.getLine(dataLineInfo) as SourceDataLine
dataLine.open(audioFormat)
volumeController = JavaSoundVolumeController()
//audioFormat.getProperty()
}
inner class JavaSoundVolumeController: VolumeController {
private val volumeControl: FloatControl = dataLine.getControl(MASTER_GAIN) as FloatControl
override fun max(): Float = volumeControl.maximum
override fun min(): Float = volumeControl.minimum
override fun current(): Float = volumeControl.value
override fun set(value: Float) {
volumeControl.value = value
}
}
}
| apache-2.0 | 097f3661919aefc0f6dc9ea0df721345 | 31.895105 | 126 | 0.646046 | 4.91023 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/compiler-plugins/kapt/src/org/jetbrains/kotlin/idea/compilerPlugin/kapt/gradleJava/KaptProjectResolverExtension.kt | 4 | 4383 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.compilerPlugin.kapt.gradleJava
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.externalSystem.model.DataNode
import com.intellij.openapi.externalSystem.model.ProjectKeys
import com.intellij.openapi.externalSystem.model.project.*
import com.intellij.openapi.util.Key
import org.gradle.tooling.model.idea.IdeaModule
import org.jetbrains.kotlin.idea.gradleTooling.model.kapt.KaptGradleModel
import org.jetbrains.kotlin.idea.gradleTooling.model.kapt.KaptModelBuilderService
import org.jetbrains.plugins.gradle.model.data.GradleSourceSetData
import org.jetbrains.plugins.gradle.service.project.AbstractProjectResolverExtension
import org.jetbrains.plugins.gradle.util.GradleConstants
@Suppress("unused")
class KaptProjectResolverExtension : AbstractProjectResolverExtension() {
private companion object {
private val LOG = Logger.getInstance(KaptProjectResolverExtension::class.java)
}
override fun getExtraProjectModelClasses(): Set<Class<KaptGradleModel>> {
val isAndroidPluginRequestingKotlinGradleModelKey = Key.findKeyByName("IS_ANDROID_PLUGIN_REQUESTING_KAPT_GRADLE_MODEL_KEY")
if (isAndroidPluginRequestingKotlinGradleModelKey != null && resolverCtx.getUserData(isAndroidPluginRequestingKotlinGradleModelKey) != null) {
return emptySet()
}
return setOf(KaptGradleModel::class.java)
}
override fun getToolingExtensionsClasses() = setOf(KaptModelBuilderService::class.java, Unit::class.java)
override fun populateModuleExtraModels(gradleModule: IdeaModule, ideModule: DataNode<ModuleData>) {
val kaptModel = resolverCtx.getExtraProject(gradleModule, KaptGradleModel::class.java)
if (kaptModel != null && kaptModel.isEnabled) {
for (sourceSet in kaptModel.sourceSets) {
val parentDataNode = ideModule.findParentForSourceSetDataNode(sourceSet.sourceSetName) ?: continue
fun addSourceSet(path: String, type: ExternalSystemSourceType) {
val contentRootData = ContentRootData(GradleConstants.SYSTEM_ID, path)
contentRootData.storePath(type, path)
parentDataNode.createChild(ProjectKeys.CONTENT_ROOT, contentRootData)
}
val sourceType =
if (sourceSet.isTest) ExternalSystemSourceType.TEST_GENERATED else ExternalSystemSourceType.SOURCE_GENERATED
sourceSet.generatedSourcesDirFile?.let { addSourceSet(it.absolutePath, sourceType) }
sourceSet.generatedKotlinSourcesDirFile?.let { addSourceSet(it.absolutePath, sourceType) }
sourceSet.generatedClassesDirFile?.let { generatedClassesDir ->
val libraryData = LibraryData(GradleConstants.SYSTEM_ID, "kaptGeneratedClasses")
val existingNode =
parentDataNode.children.map { (it.data as? LibraryDependencyData)?.target }
.firstOrNull { it?.externalName == libraryData.externalName }
if (existingNode != null) {
existingNode.addPath(LibraryPathType.BINARY, generatedClassesDir.absolutePath)
} else {
libraryData.addPath(LibraryPathType.BINARY, generatedClassesDir.absolutePath)
val libraryDependencyData = LibraryDependencyData(parentDataNode.data, libraryData, LibraryLevel.MODULE)
parentDataNode.createChild(ProjectKeys.LIBRARY_DEPENDENCY, libraryDependencyData)
}
}
}
}
super.populateModuleExtraModels(gradleModule, ideModule)
}
private fun DataNode<ModuleData>.findParentForSourceSetDataNode(sourceSetName: String): DataNode<ModuleData>? {
val moduleName = data.id
for (child in children) {
val gradleSourceSetData = child.data as? GradleSourceSetData ?: continue
if (gradleSourceSetData.id == "$moduleName:$sourceSetName") {
@Suppress("UNCHECKED_CAST")
return child as? DataNode<ModuleData>
}
}
return this
}
}
| apache-2.0 | 09827040581b34f2c98351afe08632a1 | 51.807229 | 158 | 0.699749 | 5.527112 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/psi/patternMatching/AbstractPsiUnifierTest.kt | 4 | 2025 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.psi.patternMatching
import com.intellij.openapi.util.TextRange
import com.intellij.testFramework.LightProjectDescriptor
import org.jetbrains.kotlin.idea.base.psi.unifier.toRange
import org.jetbrains.kotlin.idea.test.DirectiveBasedActionUtils
import org.jetbrains.kotlin.idea.test.KotlinLightCodeInsightFixtureTestCase
import org.jetbrains.kotlin.idea.util.psi.patternMatching.KotlinPsiUnifier
import org.jetbrains.kotlin.idea.util.psi.patternMatching.match
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.parentsWithSelf
import org.jetbrains.kotlin.idea.test.KotlinTestUtils
import java.io.File
abstract class AbstractPsiUnifierTest : KotlinLightCodeInsightFixtureTestCase() {
fun doTest(unused: String) {
fun findPattern(file: KtFile): KtElement {
val selectionModel = myFixture.editor.selectionModel
val start = selectionModel.selectionStart
val end = selectionModel.selectionEnd
val selectionRange = TextRange(start, end)
return file.findElementAt(start)?.parentsWithSelf?.last {
(it is KtExpression || it is KtTypeReference || it is KtWhenCondition)
&& selectionRange.contains(it.textRange ?: TextRange.EMPTY_RANGE)
} as KtElement
}
val file = myFixture.configureByFile(fileName()) as KtFile
DirectiveBasedActionUtils.checkForUnexpectedErrors(file)
val actualText =
findPattern(file).toRange().match(file, KotlinPsiUnifier.DEFAULT).map { it.range.textRange.substring(file.getText()!!) }
.joinToString("\n\n")
KotlinTestUtils.assertEqualsToFile(File(testDataPath, "${fileName()}.match"), actualText)
}
override fun getProjectDescriptor(): LightProjectDescriptor = getProjectDescriptorFromTestName()
}
| apache-2.0 | 11f6fab1404830fd2a255ae22c078392 | 48.390244 | 158 | 0.74321 | 5.037313 | false | true | false | false |
siosio/intellij-community | plugins/kotlin/gradle/gradle-idea/src/org/jetbrains/kotlin/idea/configuration/kotlinResolverUtil.kt | 1 | 2527 | // 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.configuration
import com.intellij.ide.plugins.PluginManagerCore
import com.intellij.ide.util.PropertiesComponent
import com.intellij.notification.Notification
import com.intellij.notification.NotificationAction
import com.intellij.notification.NotificationType
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.extensions.PluginId
import com.intellij.openapi.project.ProjectManager
import com.intellij.openapi.updateSettings.impl.pluginsAdvertisement.installAndEnable
import com.intellij.openapi.updateSettings.impl.pluginsAdvertisement.notificationGroup
import com.intellij.util.PlatformUtils
import org.jetbrains.annotations.NotNull
import org.jetbrains.kotlin.idea.KotlinIdeaGradleBundle
private var isNativeDebugSuggestionEnabled
get() =
PropertiesComponent.getInstance().getBoolean("isNativeDebugSuggestionEnabled", true)
set(value) {
PropertiesComponent.getInstance().setValue("isNativeDebugSuggestionEnabled", value)
}
fun suggestNativeDebug(projectPath: String) {
if (!PlatformUtils.isIdeaUltimate()) return
val pluginId = PluginId.getId("com.intellij.nativeDebug")
if (PluginManagerCore.isPluginInstalled(pluginId)) return
if (!isNativeDebugSuggestionEnabled) return
val projectManager = ProjectManager.getInstance()
val project = projectManager.openProjects.firstOrNull { it.basePath == projectPath } ?: return
notificationGroup
.createNotification(KotlinIdeaGradleBundle.message("notification.title.plugin.suggestion"), KotlinIdeaGradleBundle.message("notification.text.native.debug.provides.debugger.for.kotlin.native"), NotificationType.INFORMATION)
.addAction(object : NotificationAction(KotlinIdeaGradleBundle.message("action.text.install")) {
override fun actionPerformed(e: AnActionEvent, notification: Notification) {
installAndEnable(project, setOf<@NotNull PluginId>(pluginId)) { notification.expire() }
}
})
.addAction(object : NotificationAction(KotlinIdeaGradleBundle.message("action.text.dontShowAgain")) {
override fun actionPerformed(e: AnActionEvent, notification: Notification) {
isNativeDebugSuggestionEnabled = false
notification.expire()
}
})
.notify(project)
}
| apache-2.0 | 506cb471ebc252352cc24f7b8cbf2c5d | 48.54902 | 231 | 0.774436 | 5.32 | false | false | false | false |
jwren/intellij-community | platform/platform-impl/src/com/intellij/openapi/keymap/impl/KeymapImpl.kt | 1 | 31213 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.openapi.keymap.impl
import com.intellij.configurationStore.SchemeDataHolder
import com.intellij.configurationStore.SerializableScheme
import com.intellij.ide.IdeBundle
import com.intellij.ide.plugins.PluginManagerConfigurable
import com.intellij.internal.statistic.collectors.fus.actions.persistence.ActionsCollectorImpl
import com.intellij.notification.Notification
import com.intellij.notification.NotificationAction
import com.intellij.notification.NotificationType
import com.intellij.openapi.actionSystem.*
import com.intellij.openapi.actionSystem.ex.ActionManagerEx
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.ModalityState
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.extensions.PluginId
import com.intellij.openapi.keymap.Keymap
import com.intellij.openapi.keymap.KeymapManagerListener
import com.intellij.openapi.keymap.KeymapUtil
import com.intellij.openapi.keymap.ex.KeymapManagerEx
import com.intellij.openapi.options.ExternalizableSchemeAdapter
import com.intellij.openapi.options.SchemeState
import com.intellij.openapi.options.ShowSettingsUtil
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.ProjectManager
import com.intellij.openapi.project.ProjectManagerListener
import com.intellij.openapi.updateSettings.impl.pluginsAdvertisement.installAndEnable
import com.intellij.openapi.util.InvalidDataException
import com.intellij.openapi.util.NlsContexts
import com.intellij.openapi.util.SystemInfo
import com.intellij.ui.KeyStrokeAdapter
import com.intellij.util.ArrayUtilRt
import com.intellij.util.SmartList
import com.intellij.util.containers.ContainerUtil
import com.intellij.util.containers.mapSmart
import com.intellij.util.containers.nullize
import org.jdom.Element
import java.util.*
import javax.swing.KeyStroke
import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KProperty
private const val KEY_MAP = "keymap"
private const val KEYBOARD_SHORTCUT = "keyboard-shortcut"
private const val KEYBOARD_GESTURE_SHORTCUT = "keyboard-gesture-shortcut"
private const val KEYBOARD_GESTURE_KEY = "keystroke"
private const val KEYBOARD_GESTURE_MODIFIER = "modifier"
private const val KEYSTROKE_ATTRIBUTE = "keystroke"
private const val FIRST_KEYSTROKE_ATTRIBUTE = "first-keystroke"
private const val SECOND_KEYSTROKE_ATTRIBUTE = "second-keystroke"
private const val ACTION = "action"
private const val VERSION_ATTRIBUTE = "version"
private const val PARENT_ATTRIBUTE = "parent"
private const val NAME_ATTRIBUTE = "name"
private const val ID_ATTRIBUTE = "id"
private const val MOUSE_SHORTCUT = "mouse-shortcut"
fun KeymapImpl(name: String, dataHolder: SchemeDataHolder<KeymapImpl>): KeymapImpl {
val result = KeymapImpl(dataHolder)
result.name = name
result.schemeState = SchemeState.UNCHANGED
return result
}
open class KeymapImpl @JvmOverloads constructor(private var dataHolder: SchemeDataHolder<KeymapImpl>? = null)
: ExternalizableSchemeAdapter(), Keymap, SerializableScheme {
private var parent: KeymapImpl? = null
private var unknownParentName: String? = null
open var canModify: Boolean = true
@JvmField
internal var schemeState: SchemeState? = null
override fun getSchemeState(): SchemeState? = schemeState
private val actionIdToShortcuts = HashMap<String, MutableList<Shortcut>>()
get() {
val dataHolder = dataHolder
if (dataHolder != null) {
this.dataHolder = null
readExternal(dataHolder.read())
}
return field
}
private val keymapManager by lazy { KeymapManagerEx.getInstanceEx()!! }
/**
* @return IDs of the action which are specified in the keymap. It doesn't return IDs of action from parent keymap.
*/
val ownActionIds: Array<String>
get() = actionIdToShortcuts.keys.toTypedArray()
private fun <T> cachedShortcuts(mapper: (Shortcut) -> T?): ReadWriteProperty<Any?, Map<T, MutableList<String>>> =
object : ReadWriteProperty<Any?, Map<T, MutableList<String>>> {
private var cache: Map<T, MutableList<String>>? = null
override fun getValue(thisRef: Any?, property: KProperty<*>): Map<T, MutableList<String>> =
cache ?: mapShortcuts(mapper).also { cache = it }
override fun setValue(thisRef: Any?, property: KProperty<*>, value: Map<T, MutableList<String>>) {
cache = null
}
private fun mapShortcuts(mapper: (Shortcut) -> T?): Map<T, MutableList<String>> {
fun addActionToShortcutMap(actionId: String, map: MutableMap<T, MutableList<String>>) {
for (shortcut in getOwnOrBoundShortcuts(actionId)) {
mapper(shortcut)?.let {
val ids = map.getOrPut(it) { SmartList() }
if (!ids.contains(actionId)) {
ids.add(actionId)
}
}
}
}
val map = HashMap<T, MutableList<String>>()
actionIdToShortcuts.keys.forEach { addActionToShortcutMap(it, map) }
keymapManager.boundActions.forEach { addActionToShortcutMap(it, map) }
return map
}
}
private var keystrokeToActionIds: Map<KeyStroke, MutableList<String>> by cachedShortcuts { (it as? KeyboardShortcut)?.firstKeyStroke }
private var mouseShortcutToActionIds: Map<MouseShortcut, MutableList<String>> by cachedShortcuts { it as? MouseShortcut }
private var gestureToActionIds: Map<KeyboardModifierGestureShortcut, MutableList<String>> by cachedShortcuts { it as? KeyboardModifierGestureShortcut }
override fun getPresentableName(): String = name
override fun deriveKeymap(newName: String): KeymapImpl =
if (canModify()) {
val newKeymap = copy()
newKeymap.name = newName
newKeymap
}
else {
val newKeymap = KeymapImpl()
newKeymap.parent = this
newKeymap.name = newName
newKeymap
}
fun copy(): KeymapImpl =
dataHolder?.let { KeymapImpl(name, it) }
?: copyTo(KeymapImpl())
fun copyTo(otherKeymap: KeymapImpl): KeymapImpl {
otherKeymap.cleanShortcutsCache()
otherKeymap.actionIdToShortcuts.clear()
for (entry in actionIdToShortcuts.entries) {
otherKeymap.actionIdToShortcuts[entry.key] = ContainerUtil.copyList(entry.value)
}
// after actionIdToShortcuts (on first access we lazily read itself)
otherKeymap.parent = parent
otherKeymap.name = name
otherKeymap.canModify = canModify()
return otherKeymap
}
override fun getParent(): KeymapImpl? = parent
final override fun canModify(): Boolean = canModify
override fun addShortcut(actionId: String, shortcut: Shortcut) {
val list = actionIdToShortcuts.getOrPut(actionId) {
val result = SmartList<Shortcut>()
val boundShortcuts = keymapManager.getActionBinding(actionId)?.let { actionIdToShortcuts[it] }
if (boundShortcuts != null) {
result.addAll(boundShortcuts)
}
else {
parent?.getMutableShortcutList(actionId)?.mapTo(result) { convertShortcut(it) }
}
result
}
if (!list.contains(shortcut)) {
list.add(shortcut)
}
if (list.areShortcutsEqualToParent(actionId)) {
actionIdToShortcuts.remove(actionId)
}
cleanShortcutsCache()
fireShortcutChanged(actionId)
}
private fun cleanShortcutsCache() {
keystrokeToActionIds = emptyMap()
mouseShortcutToActionIds = emptyMap()
gestureToActionIds = emptyMap()
schemeState = SchemeState.POSSIBLY_CHANGED
}
override fun removeAllActionShortcuts(actionId: String) {
for (shortcut in getShortcuts(actionId)) {
removeShortcut(actionId, shortcut)
}
}
override fun removeShortcut(actionId: String, toDelete: Shortcut) {
val list = actionIdToShortcuts[actionId]
if (list == null) {
val inherited = keymapManager.getActionBinding(actionId)?.let { actionIdToShortcuts[it] }
?: parent?.getMutableShortcutList(actionId)?.mapSmart { convertShortcut(it) }.nullize()
if (inherited != null) {
var newShortcuts: MutableList<Shortcut>? = null
for (itemIndex in 0..inherited.lastIndex) {
val item = inherited[itemIndex]
if (toDelete == item) {
if (newShortcuts == null) {
newShortcuts = SmartList()
for (notAddedItemIndex in 0 until itemIndex) {
newShortcuts.add(inherited[notAddedItemIndex])
}
}
}
else newShortcuts?.add(item)
}
newShortcuts?.let {
actionIdToShortcuts.put(actionId, it)
}
}
}
else {
val index = list.indexOf(toDelete)
if (index >= 0) {
if (parent == null) {
if (list.size == 1) {
actionIdToShortcuts.remove(actionId)
}
else {
list.removeAt(index)
}
}
else {
list.removeAt(index)
if (list.areShortcutsEqualToParent(actionId)) {
actionIdToShortcuts.remove(actionId)
}
}
}
}
cleanShortcutsCache()
fireShortcutChanged(actionId)
}
private fun MutableList<Shortcut>.areShortcutsEqualToParent(actionId: String) =
parent.let { parent -> parent != null && areShortcutsEqual(this, parent.getMutableShortcutList(actionId).mapSmart { convertShortcut(it) }) }
private fun getOwnOrBoundShortcuts(actionId: String): List<Shortcut> {
actionIdToShortcuts[actionId]?.let {
return it
}
val result = SmartList<Shortcut>()
keymapManager.getActionBinding(actionId)?.let {
result.addAll(getOwnOrBoundShortcuts(it))
}
return result
}
private fun getActionIds(shortcut: KeyboardModifierGestureShortcut): List<String> {
// first, get keystrokes from our own map
val list = SmartList<String>()
for ((key, value) in gestureToActionIds) {
if (shortcut.startsWith(key)) {
list.addAll(value)
}
}
if (parent != null) {
val ids = parent!!.getActionIds(shortcut)
if (ids.isNotEmpty()) {
for (id in ids) {
// add actions from the parent keymap only if they are absent in this keymap
if (!actionIdToShortcuts.containsKey(id)) {
list.add(id)
}
}
}
}
sortInRegistrationOrder(list)
return list
}
override fun getActionIds(firstKeyStroke: KeyStroke): Array<String> {
return ArrayUtilRt.toStringArray(getActionIds(firstKeyStroke, { it.keystrokeToActionIds }, KeymapImpl::convertKeyStroke))
}
override fun getActionIds(firstKeyStroke: KeyStroke, secondKeyStroke: KeyStroke?): Array<String> {
val ids = getActionIds(firstKeyStroke)
var actualBindings: MutableList<String>? = null
for (id in ids) {
val shortcuts = getShortcuts(id)
for (shortcut in shortcuts) {
if (shortcut !is KeyboardShortcut) {
continue
}
if (firstKeyStroke == shortcut.firstKeyStroke && secondKeyStroke == shortcut.secondKeyStroke) {
if (actualBindings == null) {
actualBindings = SmartList()
}
actualBindings.add(id)
break
}
}
}
return ArrayUtilRt.toStringArray(actualBindings)
}
override fun getActionIds(shortcut: Shortcut): Array<String> {
return when (shortcut) {
is KeyboardShortcut -> {
val first = shortcut.firstKeyStroke
val second = shortcut.secondKeyStroke
if (second == null) getActionIds(first) else getActionIds(first, second)
}
is MouseShortcut -> ArrayUtilRt.toStringArray(getActionIds(shortcut))
is KeyboardModifierGestureShortcut -> ArrayUtilRt.toStringArray(getActionIds(shortcut))
else -> ArrayUtilRt.EMPTY_STRING_ARRAY
}
}
override fun hasActionId(actionId: String, shortcut: MouseShortcut): Boolean {
var convertedShortcut = shortcut
var keymap = this
do {
val list = keymap.mouseShortcutToActionIds[convertedShortcut]
if (list != null && list.contains(actionId)) {
return true
}
val parent = keymap.parent ?: return false
convertedShortcut = keymap.convertMouseShortcut(shortcut)
keymap = parent
}
while (true)
}
override fun getActionIds(shortcut: MouseShortcut): List<String> {
return getActionIds(shortcut, { it.mouseShortcutToActionIds }, KeymapImpl::convertMouseShortcut)
}
private fun <T> getActionIds(shortcut: T,
shortcutToActionIds: (keymap: KeymapImpl) -> Map<T, MutableList<String>>,
convertShortcut: (keymap: KeymapImpl, shortcut: T) -> T): List<String> {
// first, get keystrokes from our own map
var list = shortcutToActionIds(this)[shortcut]
val parentIds = parent?.getActionIds(convertShortcut(this, shortcut), shortcutToActionIds, convertShortcut) ?: emptyList()
var isOriginalListInstance = list != null
for (id in parentIds) {
// add actions from the parent keymap only if they are absent in this keymap
// do not add parent bind actions, if bind-on action is overwritten in the child
if (actionIdToShortcuts.containsKey(id) || actionIdToShortcuts.containsKey(keymapManager.getActionBinding(id))) {
continue
}
if (list == null) {
list = SmartList()
}
else if (isOriginalListInstance) {
list = SmartList(list)
isOriginalListInstance = false
}
if (!list.contains(id)) {
list.add(id)
}
}
sortInRegistrationOrder(list ?: return emptyList())
return list
}
fun isActionBound(actionId: String): Boolean = keymapManager.boundActions.contains(actionId)
override fun getShortcuts(actionId: String?): Array<Shortcut> =
getMutableShortcutList(actionId).let { if (it.isEmpty()) Shortcut.EMPTY_ARRAY else it.toTypedArray() }
private fun getMutableShortcutList(actionId: String?): List<Shortcut> {
if (actionId == null) {
return emptyList()
}
// it is critical to use convertShortcut - otherwise MacOSDefaultKeymap doesn't convert shortcuts
// todo why not convert on add? why we don't need to convert our own shortcuts?
return actionIdToShortcuts[actionId]
?: keymapManager.getActionBinding(actionId)?.let { actionIdToShortcuts[it] }
?: parent?.getMutableShortcutList(actionId)?.mapSmart { convertShortcut(it) }
?: emptyList()
}
fun getOwnShortcuts(actionId: String): Array<Shortcut> {
val own = actionIdToShortcuts[actionId] ?: return Shortcut.EMPTY_ARRAY
return if (own.isEmpty()) Shortcut.EMPTY_ARRAY else own.toTypedArray()
}
fun hasShortcutDefined(actionId: String): Boolean =
actionIdToShortcuts[actionId] != null || parent?.hasShortcutDefined(actionId) == true
// you must clear `actionIdToShortcuts` before calling
protected open fun readExternal(keymapElement: Element) {
if (KEY_MAP != keymapElement.name) {
throw InvalidDataException("unknown element: $keymapElement")
}
name = keymapElement.getAttributeValue(NAME_ATTRIBUTE)!!
unknownParentName = null
keymapElement.getAttributeValue(PARENT_ATTRIBUTE)?.let { parentSchemeName ->
var parentScheme = findParentScheme(parentSchemeName)
if (parentScheme == null && parentSchemeName == "Default for Mac OS X") {
// https://youtrack.jetbrains.com/issue/RUBY-17767#comment=27-1374197
parentScheme = findParentScheme("Mac OS X")
}
if (parentScheme == null) {
logger<KeymapImpl>().warn("Cannot find parent scheme $parentSchemeName for scheme $name")
unknownParentName = parentSchemeName
notifyAboutMissingKeymap(parentSchemeName, IdeBundle.message("notification.content.cannot.find.parent.keymap", parentSchemeName, name), true)
}
else {
parent = parentScheme as KeymapImpl
canModify = true
}
}
val actionIds = HashSet<String>()
val skipInserts = SystemInfo.isMac && (ApplicationManager.getApplication() == null || !ApplicationManager.getApplication().isUnitTestMode)
for (actionElement in keymapElement.children) {
if (actionElement.name != ACTION) {
throw InvalidDataException("unknown element: $actionElement; Keymap's name=$name")
}
val id = actionElement.getAttributeValue(ID_ATTRIBUTE) ?: throw InvalidDataException("Attribute 'id' cannot be null; Keymap's name=$name")
actionIds.add(id)
val shortcuts = SmartList<Shortcut>()
// creating the list even when there are no shortcuts (empty element means that an action overrides a parent one to clear shortcuts)
actionIdToShortcuts[id] = shortcuts
for (shortcutElement in actionElement.children) {
if (KEYBOARD_SHORTCUT == shortcutElement.name) {
// Parse first keystroke
val firstKeyStrokeStr = shortcutElement.getAttributeValue(FIRST_KEYSTROKE_ATTRIBUTE)
?: throw InvalidDataException("Attribute '$FIRST_KEYSTROKE_ATTRIBUTE' cannot be null; Action's id=$id; Keymap's name=$name")
if (skipInserts && firstKeyStrokeStr.contains("INSERT")) {
continue
}
val firstKeyStroke = KeyStrokeAdapter.getKeyStroke(firstKeyStrokeStr) ?: continue
// Parse second keystroke
var secondKeyStroke: KeyStroke? = null
val secondKeyStrokeStr = shortcutElement.getAttributeValue(SECOND_KEYSTROKE_ATTRIBUTE)
if (secondKeyStrokeStr != null) {
secondKeyStroke = KeyStrokeAdapter.getKeyStroke(secondKeyStrokeStr) ?: continue
}
shortcuts.add(KeyboardShortcut(firstKeyStroke, secondKeyStroke))
}
else if (KEYBOARD_GESTURE_SHORTCUT == shortcutElement.name) {
val strokeText = shortcutElement.getAttributeValue(KEYBOARD_GESTURE_KEY) ?: throw InvalidDataException(
"Attribute '$KEYBOARD_GESTURE_KEY' cannot be null; Action's id=$id; Keymap's name=$name")
val stroke = KeyStrokeAdapter.getKeyStroke(strokeText) ?: continue
val modifierText = shortcutElement.getAttributeValue(KEYBOARD_GESTURE_MODIFIER)
var modifier: KeyboardGestureAction.ModifierType? = null
if (KeyboardGestureAction.ModifierType.dblClick.toString().equals(modifierText, ignoreCase = true)) {
modifier = KeyboardGestureAction.ModifierType.dblClick
}
else if (KeyboardGestureAction.ModifierType.hold.toString().equals(modifierText, ignoreCase = true)) {
modifier = KeyboardGestureAction.ModifierType.hold
}
if (modifier == null) {
throw InvalidDataException("Wrong modifier=$modifierText action id=$id keymap=$name")
}
shortcuts.add(KeyboardModifierGestureShortcut.newInstance(modifier, stroke))
}
else if (MOUSE_SHORTCUT == shortcutElement.name) {
val keystrokeString = shortcutElement.getAttributeValue(KEYSTROKE_ATTRIBUTE)
?: throw InvalidDataException("Attribute 'keystroke' cannot be null; Action's id=$id; Keymap's name=$name")
try {
shortcuts.add(KeymapUtil.parseMouseShortcut(keystrokeString))
}
catch (e: InvalidDataException) {
throw InvalidDataException("Wrong mouse-shortcut: '$keystrokeString'; Action's id=$id; Keymap's name=$name")
}
}
else {
throw InvalidDataException("unknown element: $shortcutElement; Keymap's name=$name")
}
}
}
ActionsCollectorImpl.onActionsLoadedFromKeymapXml(this, actionIds)
cleanShortcutsCache()
}
protected open fun findParentScheme(parentSchemeName: String): Keymap? = keymapManager.schemeManager.findSchemeByName(parentSchemeName)
override fun writeScheme(): Element {
dataHolder?.let {
return it.read()
}
val keymapElement = Element(KEY_MAP)
keymapElement.setAttribute(VERSION_ATTRIBUTE, "1")
keymapElement.setAttribute(NAME_ATTRIBUTE, name)
(parent?.name ?: unknownParentName)?.let {
keymapElement.setAttribute(PARENT_ATTRIBUTE, it)
}
writeOwnActionIds(keymapElement)
schemeState = SchemeState.UNCHANGED
return keymapElement
}
private fun writeOwnActionIds(keymapElement: Element) {
val ownActionIds = ownActionIds
Arrays.sort(ownActionIds)
for (actionId in ownActionIds) {
val shortcuts = actionIdToShortcuts[actionId] ?: continue
val actionElement = Element(ACTION)
actionElement.setAttribute(ID_ATTRIBUTE, actionId)
for (shortcut in shortcuts) {
when (shortcut) {
is KeyboardShortcut -> {
val element = Element(KEYBOARD_SHORTCUT)
element.setAttribute(FIRST_KEYSTROKE_ATTRIBUTE, KeyStrokeAdapter.toString(shortcut.firstKeyStroke))
shortcut.secondKeyStroke?.let {
element.setAttribute(SECOND_KEYSTROKE_ATTRIBUTE, KeyStrokeAdapter.toString(it))
}
actionElement.addContent(element)
}
is MouseShortcut -> {
val element = Element(MOUSE_SHORTCUT)
element.setAttribute(KEYSTROKE_ATTRIBUTE, KeymapUtil.getMouseShortcutString(shortcut))
actionElement.addContent(element)
}
is KeyboardModifierGestureShortcut -> {
val element = Element(KEYBOARD_GESTURE_SHORTCUT)
element.setAttribute(KEYBOARD_GESTURE_SHORTCUT, KeyStrokeAdapter.toString(shortcut.stroke))
element.setAttribute(KEYBOARD_GESTURE_MODIFIER, shortcut.type.name)
actionElement.addContent(element)
}
else -> throw IllegalStateException("unknown shortcut class: $shortcut")
}
}
keymapElement.addContent(actionElement)
}
}
fun clearOwnActionsIds() {
actionIdToShortcuts.clear()
cleanShortcutsCache()
}
fun hasOwnActionId(actionId: String): Boolean = actionIdToShortcuts.containsKey(actionId)
fun clearOwnActionsId(actionId: String) {
actionIdToShortcuts.remove(actionId)
cleanShortcutsCache()
}
override fun getActionIds(): Array<String> = ArrayUtilRt.toStringArray(actionIdList)
override fun getActionIdList(): Set<String> {
val ids = LinkedHashSet<String>()
ids.addAll(actionIdToShortcuts.keys)
var parent = parent
while (parent != null) {
ids.addAll(parent.actionIdToShortcuts.keys)
parent = parent.parent
}
return ids
}
override fun getConflicts(actionId: String, keyboardShortcut: KeyboardShortcut): Map<String, MutableList<KeyboardShortcut>> {
val result = HashMap<String, MutableList<KeyboardShortcut>>()
for (id in getActionIds(keyboardShortcut.firstKeyStroke)) {
if (id == actionId || (actionId.startsWith("Editor") && id == "$${actionId.substring(6)}")) {
continue
}
val useShortcutOf = keymapManager.getActionBinding(id)
if (useShortcutOf != null && useShortcutOf == actionId) {
continue
}
for (shortcut1 in getMutableShortcutList(id)) {
if (shortcut1 !is KeyboardShortcut || shortcut1.firstKeyStroke != keyboardShortcut.firstKeyStroke) {
continue
}
if (keyboardShortcut.secondKeyStroke != null && shortcut1.secondKeyStroke != null && keyboardShortcut.secondKeyStroke != shortcut1.secondKeyStroke) {
continue
}
result.getOrPut(id) { SmartList() }.add(shortcut1)
}
}
return result
}
protected open fun convertKeyStroke(keyStroke: KeyStroke): KeyStroke = keyStroke
protected open fun convertMouseShortcut(shortcut: MouseShortcut): MouseShortcut = shortcut
protected open fun convertShortcut(shortcut: Shortcut): Shortcut = shortcut
private fun fireShortcutChanged(actionId: String) {
ApplicationManager.getApplication().messageBus.syncPublisher(KeymapManagerListener.TOPIC).shortcutChanged(this, actionId)
}
override fun toString(): String = presentableName
override fun equals(other: Any?): Boolean {
if (other !is KeymapImpl) return false
if (other === this) return true
if (name != other.name) return false
if (canModify != other.canModify) return false
if (parent != other.parent) return false
if (actionIdToShortcuts != other.actionIdToShortcuts) return false
return true
}
override fun hashCode(): Int = name.hashCode()
}
private fun sortInRegistrationOrder(ids: MutableList<String>) {
ids.sortWith(ActionManagerEx.getInstanceEx().registrationOrderComparator)
}
// compare two lists in any order
private fun areShortcutsEqual(shortcuts1: List<Shortcut>, shortcuts2: List<Shortcut>): Boolean {
if (shortcuts1.size != shortcuts2.size) {
return false
}
for (shortcut in shortcuts1) {
if (!shortcuts2.contains(shortcut)) {
return false
}
}
return true
}
@Suppress("SpellCheckingInspection") private const val macOSKeymap = "com.intellij.plugins.macoskeymap"
@Suppress("SpellCheckingInspection") private const val gnomeKeymap = "com.intellij.plugins.gnomekeymap"
@Suppress("SpellCheckingInspection") private const val kdeKeymap = "com.intellij.plugins.kdekeymap"
@Suppress("SpellCheckingInspection") private const val xwinKeymap = "com.intellij.plugins.xwinkeymap"
@Suppress("SpellCheckingInspection") private const val eclipseKeymap = "com.intellij.plugins.eclipsekeymap"
@Suppress("SpellCheckingInspection") private const val emacsKeymap = "com.intellij.plugins.emacskeymap"
@Suppress("SpellCheckingInspection") private const val netbeansKeymap = "com.intellij.plugins.netbeanskeymap"
@Suppress("SpellCheckingInspection") private const val qtcreatorKeymap = "com.intellij.plugins.qtcreatorkeymap"
@Suppress("SpellCheckingInspection") private const val resharperKeymap = "com.intellij.plugins.resharperkeymap"
@Suppress("SpellCheckingInspection") private const val sublimeKeymap = "com.intellij.plugins.sublimetextkeymap"
@Suppress("SpellCheckingInspection") private const val visualStudioKeymap = "com.intellij.plugins.visualstudiokeymap"
@Suppress("SpellCheckingInspection") private const val visualStudio2022Keymap = "com.intellij.plugins.visualstudio2022keymap"
@Suppress("SpellCheckingInspection") private const val xcodeKeymap = "com.intellij.plugins.xcodekeymap"
@Suppress("SpellCheckingInspection") private const val visualAssistKeymap = "com.intellij.plugins.visualassistkeymap"
@Suppress("SpellCheckingInspection") private const val riderKeymap = "com.intellij.plugins.riderkeymap"
@Suppress("SpellCheckingInspection") private const val vsCodeKeymap = "com.intellij.plugins.vscodekeymap"
@Suppress("SpellCheckingInspection") private const val vsForMacKeymap = "com.intellij.plugins.vsformackeymap"
internal fun notifyAboutMissingKeymap(keymapName: String, @NlsContexts.NotificationContent message: String, isParent: Boolean) {
val connection = ApplicationManager.getApplication().messageBus.connect()
connection.subscribe(ProjectManager.TOPIC, object : ProjectManagerListener {
override fun projectOpened(project: Project) {
connection.disconnect()
ApplicationManager.getApplication().invokeLater(
{
// TODO remove when PluginAdvertiser implements that
@Suppress("SpellCheckingInspection")
val pluginId = when (keymapName) {
"Mac OS X",
"Mac OS X 10.5+" -> macOSKeymap
"Default for GNOME" -> gnomeKeymap
"Default for KDE" -> kdeKeymap
"Default for XWin" -> xwinKeymap
"Eclipse",
"Eclipse (Mac OS X)" -> eclipseKeymap
"Emacs" -> emacsKeymap
"NetBeans 6.5" -> netbeansKeymap
"QtCreator",
"QtCreator OSX" -> qtcreatorKeymap
"ReSharper",
"ReSharper OSX" -> resharperKeymap
"Sublime Text",
"Sublime Text (Mac OS X)" -> sublimeKeymap
"Visual Studio",
"Visual Studio OSX" -> visualStudioKeymap
"Visual Studio 2022" -> visualStudio2022Keymap
"Visual Assist",
"Visual Assist OSX" -> visualAssistKeymap
"Xcode" -> xcodeKeymap
"Visual Studio for Mac" -> vsForMacKeymap
"Rider",
"Rider OSX"-> riderKeymap
"VSCode",
"VSCode OSX"-> vsCodeKeymap
else -> null
}
val action: AnAction = when (pluginId) {
null -> object : NotificationAction(IdeBundle.message("action.text.search.for.keymap", keymapName)) {
override fun actionPerformed(e: AnActionEvent, notification: Notification) {
//TODO enableSearch("$keymapName /tag:Keymap")?.run()
ShowSettingsUtil.getInstance().showSettingsDialog(e.project, PluginManagerConfigurable::class.java)
}
}
else -> object : NotificationAction(IdeBundle.message("action.text.install.keymap", keymapName)) {
override fun actionPerformed(e: AnActionEvent, notification: Notification) {
val connect = ApplicationManager.getApplication().messageBus.connect()
connect.subscribe(KeymapManagerListener.TOPIC, object: KeymapManagerListener {
override fun keymapAdded(keymap: Keymap) {
ApplicationManager.getApplication().invokeLater {
if (keymap.name == keymapName) {
connect.disconnect()
val successMessage = if (isParent) IdeBundle.message("notification.content.keymap.successfully.installed", keymapName)
else {
KeymapManagerEx.getInstanceEx().activeKeymap = keymap
IdeBundle.message("notification.content.keymap.successfully.activated", keymapName)
}
Notification("KeymapInstalled", successMessage,
NotificationType.INFORMATION).notify(e.project)
}
}
}
})
val plugins = mutableSetOf(PluginId.getId(pluginId))
when (pluginId) {
gnomeKeymap, kdeKeymap -> plugins += PluginId.getId(xwinKeymap)
resharperKeymap -> plugins += PluginId.getId(visualStudioKeymap)
visualAssistKeymap -> plugins += PluginId.getId(visualStudioKeymap)
visualStudio2022Keymap -> plugins += PluginId.getId(visualStudioKeymap)
xcodeKeymap, vsForMacKeymap -> plugins += PluginId.getId(macOSKeymap)
}
installAndEnable(project, plugins) { }
notification.expire()
}
}
}
Notification("KeymapMissing", IdeBundle.message("notification.group.missing.keymap"),
message, NotificationType.ERROR)
.addAction(action)
.notify(project)
},
ModalityState.NON_MODAL)
}
})
}
| apache-2.0 | f709d12a091a8e84a0183017822ca82c | 39.694915 | 158 | 0.683433 | 5.255599 | false | false | false | false |
jwren/intellij-community | plugins/kotlin/analysis/src/org/jetbrains/kotlin/idea/codeInsight/shorten/delayedRequestsWaitingSet.kt | 4 | 5700 | // 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.codeInsight.shorten
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Key
import com.intellij.psi.*
import org.jetbrains.kotlin.asJava.unwrapped
import org.jetbrains.kotlin.idea.caches.resolve.unsafeResolveToDescriptor
import org.jetbrains.kotlin.idea.caches.resolve.util.getJavaMemberDescriptor
import org.jetbrains.kotlin.idea.core.ShortenReferences
import org.jetbrains.kotlin.idea.core.ShortenReferences.Options
import org.jetbrains.kotlin.idea.util.ImportInsertHelper
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.createSmartPointer
import org.jetbrains.kotlin.psi.psiUtil.forEachDescendantOfType
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import java.util.*
interface DelayedRefactoringRequest
class ShorteningRequest(val pointer: SmartPsiElementPointer<KtElement>, val options: Options) : DelayedRefactoringRequest
class ImportRequest(
val elementToImportPointer: SmartPsiElementPointer<PsiElement>,
val filePointer: SmartPsiElementPointer<KtFile>
) : DelayedRefactoringRequest
private var Project.delayedRefactoringRequests: MutableSet<DelayedRefactoringRequest>?
by UserDataProperty(Key.create("DELAYED_REFACTORING_REQUESTS"))
/*
* When one refactoring invokes another this value must be set to false so that shortening wait-set is not cleared
* and previously collected references are processed correctly. Afterwards it must be reset to original value
*/
var Project.ensureNoRefactoringRequestsBeforeRefactoring: Boolean
by NotNullableUserDataProperty(Key.create("ENSURE_NO_REFACTORING_REQUESTS_BEFORE_REFACTORING"), true)
fun Project.runRefactoringAndKeepDelayedRequests(action: () -> Unit) {
val ensureNoRefactoringRequests = ensureNoRefactoringRequestsBeforeRefactoring
try {
ensureNoRefactoringRequestsBeforeRefactoring = false
action()
} finally {
ensureNoRefactoringRequestsBeforeRefactoring = ensureNoRefactoringRequests
}
}
private fun Project.getOrCreateRefactoringRequests(): MutableSet<DelayedRefactoringRequest> {
var requests = delayedRefactoringRequests
if (requests == null) {
requests = LinkedHashSet()
delayedRefactoringRequests = requests
}
return requests
}
fun KtElement.addToShorteningWaitSet(options: Options = Options.DEFAULT) {
assert(ApplicationManager.getApplication()!!.isWriteAccessAllowed) { "Write access needed" }
val project = project
val elementPointer = SmartPointerManager.getInstance(project).createSmartPsiElementPointer(this)
project.getOrCreateRefactoringRequests().add(ShorteningRequest(elementPointer, options))
}
fun addDelayedImportRequest(elementToImport: PsiElement, file: KtFile) {
assert(ApplicationManager.getApplication()!!.isWriteAccessAllowed) { "Write access needed" }
file.project.getOrCreateRefactoringRequests() += ImportRequest(elementToImport.createSmartPointer(), file.createSmartPointer())
}
fun performDelayedRefactoringRequests(project: Project) {
project.delayedRefactoringRequests?.let { requests ->
project.delayedRefactoringRequests = null
PsiDocumentManager.getInstance(project).commitAllDocuments()
val shorteningRequests = ArrayList<ShorteningRequest>()
val importRequests = ArrayList<ImportRequest>()
requests.forEach {
when (it) {
is ShorteningRequest -> shorteningRequests += it
is ImportRequest -> importRequests += it
}
}
val elementToOptions = shorteningRequests.mapNotNull { req -> req.pointer.element?.let { it to req.options } }.toMap()
val elements = elementToOptions.keys
//TODO: this is not correct because it should not shorten deep into the elements!
ShortenReferences { elementToOptions[it] ?: Options.DEFAULT }.process(elements)
val importInsertHelper = ImportInsertHelper.getInstance(project)
for ((file, requestsForFile) in importRequests.groupBy { it.filePointer.element }) {
if (file == null) continue
for (requestForFile in requestsForFile) {
val elementToImport = requestForFile.elementToImportPointer.element?.unwrapped ?: continue
val descriptorToImport = when (elementToImport) {
is KtDeclaration -> elementToImport.unsafeResolveToDescriptor(BodyResolveMode.PARTIAL)
is PsiMember -> elementToImport.getJavaMemberDescriptor()
else -> null
} ?: continue
importInsertHelper.importDescriptor(file, descriptorToImport)
}
}
}
}
private val LOG = Logger.getInstance(Project::class.java.canonicalName)
fun prepareDelayedRequests(project: Project) {
val requests = project.delayedRefactoringRequests
if (project.ensureNoRefactoringRequestsBeforeRefactoring && !requests.isNullOrEmpty()) {
LOG.warn("Waiting set for reference shortening is not empty")
project.delayedRefactoringRequests = null
}
}
var KtElement.isToBeShortened: Boolean? by CopyablePsiUserDataProperty(Key.create("IS_TO_BE_SHORTENED"))
fun KtElement.addToBeShortenedDescendantsToWaitingSet() {
forEachDescendantOfType<KtElement> {
if (it.isToBeShortened == true) {
it.isToBeShortened = null
it.addToShorteningWaitSet()
}
}
} | apache-2.0 | d1c4effac4e8b0dd78f0be1b3c629f19 | 43.193798 | 158 | 0.753158 | 5.352113 | false | false | false | false |
GunoH/intellij-community | platform/workspaceModel/storage/src/com/intellij/workspaceModel/storage/impl/VirtualFileNameStore.kt | 7 | 2410 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.workspaceModel.storage.impl
import com.intellij.openapi.util.SystemInfoRt
import com.intellij.openapi.util.registry.Registry
import com.intellij.util.containers.CollectionFactory
import com.intellij.util.containers.HashingStrategy
import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap
import org.jetbrains.annotations.TestOnly
internal class VirtualFileNameStore {
private val generator = IntIdGenerator()
private val id2NameStore = Int2ObjectOpenHashMap<String>()
private val name2IdStore = run {
val checkSensitivityEnabled = Registry.`is`("ide.new.project.model.index.case.sensitivity", false)
if (checkSensitivityEnabled && !SystemInfoRt.isFileSystemCaseSensitive) return@run CollectionFactory.createCustomHashingStrategyMap<String, IdPerCount>(HashingStrategy.caseInsensitive())
return@run CollectionFactory.createSmallMemoryFootprintMap<String, IdPerCount>()
}
fun generateIdForName(name: String): Int {
val idPerCount = name2IdStore[name]
if (idPerCount != null) {
idPerCount.usageCount++
return idPerCount.id
}
else {
val id = generator.generateId()
name2IdStore[name] = IdPerCount(id, 1)
// Don't convert to links[key] = ... because it *may* became autoboxing
id2NameStore.put(id, name)
return id
}
}
fun removeName(name: String) {
val idPerCount = name2IdStore[name] ?: return
if (idPerCount.usageCount == 1L) {
name2IdStore.remove(name)
id2NameStore.remove(idPerCount.id)
}
else {
idPerCount.usageCount--
}
}
fun getNameForId(id: Int): String? = id2NameStore.get(id)
fun getIdForName(name: String) = name2IdStore[name]?.id
@TestOnly
fun clear() {
name2IdStore.clear()
id2NameStore.clear()
generator.clear()
}
}
private data class IdPerCount(val id: Int, var usageCount: Long) {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as IdPerCount
if (id != other.id) return false
return true
}
override fun hashCode() = 31 * id.hashCode()
}
internal class IntIdGenerator {
private var generator: Int = 0
fun generateId() = ++generator
@TestOnly
fun clear() {
generator = 0
}
} | apache-2.0 | fdc521fad6b164fb1b0e5f609f34a493 | 28.765432 | 190 | 0.718257 | 4.126712 | false | false | false | false |
smmribeiro/intellij-community | platform/platform-impl/src/com/intellij/internal/ml/FeaturesInfo.kt | 9 | 5219 | // 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.internal.ml
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
class FeaturesInfo(override val knownFeatures: Set<String>,
override val binaryFeatures: List<BinaryFeature>,
override val floatFeatures: List<FloatFeature>,
override val categoricalFeatures: List<CategoricalFeature>,
override val featuresOrder: Array<FeatureMapper>,
override val version: String?) : ModelMetadata {
companion object {
private val gson = Gson()
private const val DEFAULT: String = "default"
private const val USE_UNDEFINED: String = "use_undefined"
private fun List<String>.withSafeWeighers(): Set<String> {
val result = this.toMutableSet()
result.add("prox_directoryType")
result.add("kt_prox_directoryType")
result.add("kotlin.unwantedElement")
return result
}
fun buildInfo(reader: ModelMetadataReader): FeaturesInfo {
val knownFeatures = reader.allKnown().fromJson<List<String>>().withSafeWeighers()
val binaryFactors: List<BinaryFeature> = reader.binaryFeatures().fromJson<Map<String, Map<String, Any>>>()
.map { binary(it.key, it.value) }
val doubleFactors = reader.floatFeatures().fromJson<Map<String, Map<String, Any>>>()
.map { float(it.key, it.value) }
val categoricalFactors = reader.categoricalFeatures().fromJson<Map<String, List<String>>>()
.map { categorical(it.key, it.value) }
val order = reader.featureOrderDirect()
val featuresIndex = buildFeaturesIndex(binaryFactors, doubleFactors, categoricalFactors)
return FeaturesInfo(knownFeatures, binaryFactors, doubleFactors, categoricalFactors, buildMappers(featuresIndex, order),
reader.extractVersion())
}
fun binary(name: String, description: Map<String, Any>): BinaryFeature {
val (first, second) = extractBinaryValuesMappings(description)
val default = extractDefaultValue(name, description)
return BinaryFeature(name, first, second, default, allowUndefined(description))
}
fun float(name: String, description: Map<String, Any>): FloatFeature {
val default = extractDefaultValue(name, description)
return FloatFeature(name, default, allowUndefined(description))
}
fun categorical(name: String, categories: List<String>): CategoricalFeature {
return CategoricalFeature(name, categories.toSet())
}
private fun <T> String.fromJson(): T {
val typeToken = object : TypeToken<T>() {}
return gson.fromJson<T>(this, typeToken.type)
}
fun buildFeaturesIndex(vararg featureGroups: List<Feature>): Map<String, Feature> {
fun <T : Feature> MutableMap<String, Feature>.addFeatures(features: List<T>): MutableMap<String, Feature> {
for (feature in features) {
if (feature.name in keys) throw InconsistentMetadataException(
"Ambiguous feature description '${feature.name}': $feature and ${this[feature.name]}")
this[feature.name] = feature
}
return this
}
val index = mutableMapOf<String, Feature>()
for (features in featureGroups) {
index.addFeatures(features)
}
return index
}
private fun allowUndefined(description: Map<String, Any>): Boolean {
val value = description[USE_UNDEFINED]
if (value is Boolean) {
return value
}
return true
}
private fun extractDefaultValue(name: String, description: Map<String, Any>): Double {
return description[DEFAULT].toString().toDoubleOrNull()
?: throw InconsistentMetadataException("Default value not found. Feature name: $name")
}
private fun extractBinaryValuesMappings(description: Map<String, Any>)
: Pair<ValueMapping, ValueMapping> {
val result = mutableListOf<ValueMapping>()
for ((name, value) in description) {
if (name == DEFAULT || name == USE_UNDEFINED) continue
val mappedValue = value.toString().toDoubleOrNull()
if (mappedValue == null) throw InconsistentMetadataException("Mapped value for binary feature should be double")
result += name to mappedValue
}
assert(result.size == 2) { "Binary feature must contains 2 values, but found $result" }
result.sortBy { it.first }
return Pair(result[0], result[1])
}
fun buildMappers(features: Map<String, Feature>,
order: List<String>): Array<FeatureMapper> {
val mappers = mutableListOf<FeatureMapper>()
for (arrayFeatureName in order) {
val name = arrayFeatureName.substringBefore('=')
val suffix = arrayFeatureName.indexOf('=').let { if (it == -1) null else arrayFeatureName.substring(it + 1) }
val mapper = features[name]?.createMapper(suffix) ?: throw InconsistentMetadataException(
"Unexpected feature name in array: $arrayFeatureName")
mappers.add(mapper)
}
return mappers.toTypedArray()
}
}
} | apache-2.0 | 5c3525637bd9a19704161648cf109df6 | 41.439024 | 140 | 0.670627 | 4.618584 | false | false | false | false |
Jire/Charlatano | src/main/kotlin/com/charlatano/scripts/aim/General.kt | 1 | 4656 | /*
* Charlatano: Free and open-source (FOSS) cheat for CS:GO/CS:CO
* Copyright (C) 2017 - Thomas G. P. Nappo, Jonathan Beaudoin
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.charlatano.scripts.aim
import com.charlatano.game.*
import com.charlatano.game.entity.*
import com.charlatano.game.entity.EntityType.Companion.ccsPlayer
import com.charlatano.settings.*
import com.charlatano.utils.*
import java.util.concurrent.atomic.AtomicBoolean
import java.util.concurrent.atomic.AtomicInteger
import java.util.concurrent.atomic.AtomicLong
import kotlin.math.max
val target = AtomicLong(-1)
val bone = AtomicInteger(HEAD_BONE)
val perfect = AtomicBoolean() // only applicable for safe aim
internal fun reset() {
target.set(-1L)
bone.set(HEAD_BONE)
perfect.set(false)
}
internal fun findTarget(position: Angle, angle: Angle, allowPerfect: Boolean,
lockFOV: Int = AIM_FOV, boneID: Int = HEAD_BONE,
yawOnly: Boolean): Player {
var closestFOV = Double.MAX_VALUE
var closestDelta = Double.MAX_VALUE
var closestPlayer = -1L
forEntities(ccsPlayer) result@{
val entity = it.entity
if (entity <= 0 || entity == me || !entity.canShoot()) {
return@result false
}
val ePos: Angle = entity.bones(boneID)
val distance = position.distanceTo(ePos)
val dest = calculateAngle(me, ePos)
val pitchDiff = Math.abs(angle.x - dest.x)
val yawDiff = Math.abs(angle.y - dest.y)
val fov = Math.abs(Math.sin(Math.toRadians(yawDiff)) * distance)
val delta = Math.abs((Math.sin(Math.toRadians(pitchDiff)) + Math.sin(Math.toRadians(yawDiff))) * distance)
if (if (yawOnly) fov <= lockFOV && delta < closestDelta else delta <= lockFOV && delta <= closestDelta) {
closestFOV = fov
closestDelta = delta
closestPlayer = entity
return@result true
} else {
return@result false
}
}
if (closestDelta == Double.MAX_VALUE || closestDelta < 0 || closestPlayer < 0) return -1
if (PERFECT_AIM && allowPerfect && closestFOV <= PERFECT_AIM_FOV && randInt(100 + 1) <= PERFECT_AIM_CHANCE)
perfect.set(true)
return closestPlayer
}
internal fun Entity.inMyTeam() =
!TEAMMATES_ARE_ENEMIES && if (DANGER_ZONE) {
me.survivalTeam().let { it > -1 && it == this.survivalTeam() }
} else me.team() == team()
internal fun Entity.canShoot() = spotted()
&& !dormant()
&& !dead()
&& !inMyTeam()
&& !me.dead()
internal inline fun <R> aimScript(duration: Int, crossinline precheck: () -> Boolean,
crossinline doAim: (destinationAngle: Angle,
currentAngle: Angle, aimSpeed: Int) -> R) = every(duration) {
if (!precheck()) return@every
if (!me.weaponEntity().canFire()) {
reset()
return@every
}
val aim = ACTIVATE_FROM_FIRE_KEY && keyPressed(FIRE_KEY)
val forceAim = keyPressed(FORCE_AIM_KEY)
val pressed = aim or forceAim
var currentTarget = target.get()
if (!pressed) {
reset()
return@every
}
val weapon = me.weapon()
if (!weapon.pistol && !weapon.automatic && !weapon.shotgun && !weapon.sniper) {
reset()
return@every
}
val currentAngle = clientState.angle()
val position = me.position()
if (currentTarget < 0) {
currentTarget = findTarget(position, currentAngle, aim, yawOnly = true)
if (currentTarget <= 0) {
return@every
}
target.set(currentTarget)
}
if (currentTarget == me || !currentTarget.canShoot()) {
reset()
if (TARGET_SWAP_MAX_DELAY > 0) {
Thread.sleep(randLong(TARGET_SWAP_MIN_DELAY, TARGET_SWAP_MAX_DELAY))
}
} else if (currentTarget.onGround() && me.onGround()) {
val boneID = bone.get()
val bonePosition = currentTarget.bones(boneID)
val destinationAngle = calculateAngle(me, bonePosition)
if (AIM_ASSIST_MODE) destinationAngle.finalize(currentAngle, AIM_ASSIST_STRICTNESS / 100.0)
val aimSpeed = AIM_SPEED_MIN + randInt(AIM_SPEED_MAX - AIM_SPEED_MIN)
doAim(destinationAngle, currentAngle, aimSpeed / max(1, CACHE_EXPIRE_MILLIS.toInt() / 4))
}
} | agpl-3.0 | 631cc77d505516de53e5264dff806dd0 | 30.89726 | 115 | 0.684923 | 3.421014 | false | false | false | false |
nicolas-raoul/apps-android-commons | app/src/test/kotlin/fr/free/nrw/commons/upload/FileMetadataUtilsTest.kt | 1 | 2586 | package fr.free.nrw.commons.upload
import androidx.exifinterface.media.ExifInterface.*
import junit.framework.Assert.assertTrue
import org.junit.Test
import java.util.*
/**
* Test cases for FileMetadataUtils
*/
class FileMetadataUtilsTest {
/**
* Test method to verify EXIF tags for "Author"
*/
@Test
fun getTagsFromPrefAuthor() {
val author = FileMetadataUtils.getTagsFromPref("Author")
val authorRef = arrayOf(TAG_ARTIST, TAG_CAMERA_OWNER_NAME);
assertTrue(Arrays.deepEquals(author, authorRef))
}
/**
* Test method to verify EXIF tags for "Location"
*/
@Test
fun getTagsFromPrefLocation() {
val author = FileMetadataUtils.getTagsFromPref("Location")
val authorRef = arrayOf(TAG_GPS_LATITUDE, TAG_GPS_LATITUDE_REF,
TAG_GPS_LONGITUDE, TAG_GPS_LONGITUDE_REF,
TAG_GPS_ALTITUDE, TAG_GPS_ALTITUDE_REF)
assertTrue(Arrays.deepEquals(author, authorRef))
}
/**
* Test method to verify EXIF tags for "Copyright"
*/
@Test
fun getTagsFromPrefCopyWright() {
val author = FileMetadataUtils.getTagsFromPref("Copyright")
val authorRef = arrayOf(TAG_COPYRIGHT)
assertTrue(Arrays.deepEquals(author, authorRef))
}
/**
* Test method to verify EXIF tags for "Camera Model"
*/
@Test
fun getTagsFromPrefCameraModel() {
val author = FileMetadataUtils.getTagsFromPref("Camera Model")
val authorRef = arrayOf(TAG_MAKE, TAG_MODEL)
assertTrue(Arrays.deepEquals(author, authorRef))
}
/**
* Test method to verify EXIF tags for "Lens Model"
*/
@Test
fun getTagsFromPrefLensModel() {
val author = FileMetadataUtils.getTagsFromPref("Lens Model")
val authorRef = arrayOf(TAG_LENS_MAKE, TAG_LENS_MODEL, TAG_LENS_SPECIFICATION)
assertTrue(Arrays.deepEquals(author, authorRef))
}
/**
* Test method to verify EXIF tags for "Serial Numbers"
*/
@Test
fun getTagsFromPrefSerialNumbers() {
val author = FileMetadataUtils.getTagsFromPref("Serial Numbers")
val authorRef = arrayOf(TAG_BODY_SERIAL_NUMBER, TAG_LENS_SERIAL_NUMBER)
assertTrue(Arrays.deepEquals(author, authorRef))
}
/**
* Test method to verify EXIF tags for "Software"
*/
@Test
fun getTagsFromPrefSoftware() {
val author = FileMetadataUtils.getTagsFromPref("Software")
val authorRef = arrayOf(TAG_SOFTWARE)
assertTrue(Arrays.deepEquals(author, authorRef))
}
} | apache-2.0 | 0b216fb70452b8e31acd9b48a4c9413a | 27.428571 | 86 | 0.655452 | 4.601423 | false | true | false | false |
MartinStyk/AndroidApkAnalyzer | app/src/main/java/sk/styk/martin/apkanalyzer/model/statistics/PercentagePair.kt | 1 | 2005 | package sk.styk.martin.apkanalyzer.model.statistics
import android.os.Parcel
import android.os.Parcelable
import sk.styk.martin.apkanalyzer.util.BigDecimalFormatter
import java.math.BigDecimal
class PercentagePair : Parcelable {
var count: Number
var percentage: BigDecimal
constructor(count: Number, total: Int) {
this.count = count
this.percentage = getPercentage(count.toDouble(), total.toDouble())
}
override fun toString(): String {
return count.toString() + " (" + BigDecimalFormatter.getCommonFormat().format(percentage) + "%)"
}
override fun describeContents(): Int {
return 0
}
override fun writeToParcel(dest: Parcel, flags: Int) {
dest.writeSerializable(this.count)
dest.writeSerializable(this.percentage)
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as PercentagePair
if (count != other.count) return false
if (percentage != other.percentage) return false
return true
}
override fun hashCode(): Int {
var result = count.hashCode()
result = 31 * result + percentage.hashCode()
return result
}
private constructor(`in`: Parcel) {
this.count = `in`.readSerializable() as Number
this.percentage = `in`.readSerializable() as BigDecimal
}
companion object {
@JvmField
val CREATOR: Parcelable.Creator<PercentagePair> = object : Parcelable.Creator<PercentagePair> {
override fun createFromParcel(source: Parcel): PercentagePair {
return PercentagePair(source)
}
override fun newArray(size: Int): Array<PercentagePair?> {
return arrayOfNulls(size)
}
}
fun getPercentage(part: Double, whole: Double): BigDecimal {
return BigDecimal(part * 100 / whole)
}
}
} | gpl-3.0 | 6fc99ce39c062d0f6cdfafe703c40412 | 26.861111 | 105 | 0.632918 | 4.796651 | false | false | false | false |
kirimin/mitsumine | app/src/main/java/me/kirimin/mitsumine/mybookmark/MyBookmarkSearchAdapter.kt | 1 | 2203 | package me.kirimin.mitsumine.mybookmark
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ArrayAdapter
import android.widget.TextView
import me.kirimin.mitsumine.R
import me.kirimin.mitsumine._common.domain.model.MyBookmark
class MyBookmarkSearchAdapter(context: Context,
private val onMyBookmarkClick: (v: View, myBookmark: MyBookmark) -> Unit,
private val onMyBookmarkLongClick: (v: View, myBookmark: MyBookmark) -> Unit) : ArrayAdapter<MyBookmark>(context, 0) {
override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
val view: View
val holder: ViewHolder
if (convertView == null) {
view = LayoutInflater.from(context).inflate(R.layout.row_my_bookmarks, null)
holder = ViewHolder(view.findViewById(R.id.card_view),
view.findViewById(R.id.MyBookmarksTitleTextView) as TextView,
view.findViewById(R.id.MyBookmarksContentTextView) as TextView,
view.findViewById(R.id.MyBookmarksUsersTextView) as TextView,
view.findViewById(R.id.MyBookmarksUrlTextView) as TextView)
view.tag = holder
} else {
view = convertView
holder = view.tag as ViewHolder
}
val bookmark = getItem(position)
holder.cardView.tag = bookmark
holder.cardView.setOnClickListener { v -> onMyBookmarkClick(v, v.tag as MyBookmark) }
holder.cardView.setOnLongClickListener { v ->
onMyBookmarkLongClick(v, v.tag as MyBookmark)
false
}
holder.title.text = bookmark.title
holder.contents.text = bookmark.snippet
holder.userCount.text = bookmark.bookmarkCount.toString() + context.getString(R.string.users_lower_case)
holder.url.text = bookmark.linkUrl
return view
}
class ViewHolder(
val cardView: View,
val title: TextView,
val contents: TextView,
val userCount: TextView,
val url: TextView) {
}
}
| apache-2.0 | 2a3ffe8dd46800ed735fa714b8ef1036 | 40.566038 | 148 | 0.647299 | 4.687234 | false | false | false | false |
hazuki0x0/YuzuBrowser | module/bookmark/src/main/java/jp/hazuki/yuzubrowser/bookmark/repository/BookmarkManager.kt | 1 | 10102 | /*
* Copyright (C) 2017-2019 Hazuki
*
* 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 jp.hazuki.yuzubrowser.bookmark.repository
import android.content.Context
import com.squareup.moshi.JsonReader
import com.squareup.moshi.JsonWriter
import jp.hazuki.yuzubrowser.bookmark.item.BookmarkFolder
import jp.hazuki.yuzubrowser.bookmark.item.BookmarkItem
import jp.hazuki.yuzubrowser.bookmark.item.BookmarkSite
import jp.hazuki.yuzubrowser.core.utility.log.ErrorReport
import okio.buffer
import okio.sink
import okio.source
import java.io.File
import java.io.IOException
import java.io.Serializable
import java.util.regex.Pattern
class BookmarkManager private constructor(context: Context) : Serializable {
val file = File(context.getDir("bookmark1", Context.MODE_PRIVATE), "bookmark1.dat")
val root = BookmarkFolder(null, null, -1)
private val siteComparator: Comparator<BookmarkSite> = Comparator { s1, s2 -> s1.url.hashCode().compareTo(s2.url.hashCode()) }
private val siteIndex = ArrayList<BookmarkSite>()
init {
load()
}
companion object {
private var instance: BookmarkManager? = null
@JvmStatic
fun getInstance(context: Context): BookmarkManager {
if (instance == null) {
instance = BookmarkManager(context.applicationContext)
}
return instance!!
}
}
fun load(): Boolean {
root.clear()
if (!file.exists() || file.isDirectory) return true
try {
JsonReader.of(file.source().buffer()).use {
root.readForRoot(it)
createIndex()
return true
}
} catch (e: IOException) {
ErrorReport.printAndWriteLog(e)
}
return false
}
fun save(): Boolean {
file.parentFile?.apply {
if (!exists()) mkdirs()
}
try {
JsonWriter.of(file.sink().buffer()).use {
root.writeForRoot(it)
return true
}
} catch (e: IOException) {
ErrorReport.printAndWriteLog(e)
}
return false
}
fun addFirst(folder: BookmarkFolder, item: BookmarkItem) {
folder.list.add(0, item)
if (item is BookmarkSite) {
addToIndex(item)
}
}
fun add(folder: BookmarkFolder, item: BookmarkItem) {
folder.add(item)
if (item is BookmarkSite) {
addToIndex(item)
}
}
fun moveToFirst(folder: BookmarkFolder, item: BookmarkItem) {
folder.list.remove(item)
folder.list.add(0, item)
}
fun addAll(folder: BookmarkFolder, addList: Collection<BookmarkItem>) {
folder.list.addAll(addList)
addList.filterIsInstance<BookmarkSite>()
.forEach(this::addToIndex)
}
fun remove(folder: BookmarkFolder, item: BookmarkItem) {
remove(folder, folder.list.indexOf(item))
}
fun remove(folder: BookmarkFolder, index: Int) {
val item = folder.list.removeAt(index)
if (item is BookmarkSite) {
removeFromIndex(item)
}
}
fun removeAll(folder: BookmarkFolder, items: List<BookmarkItem>) {
folder.list.removeAll(items)
items.filterIsInstance<BookmarkSite>()
.forEach(this::removeFromIndex)
}
fun removeAll(url: String) {
val it = siteIndex.iterator()
while (it.hasNext()) {
val site = it.next()
if (site.url == url) {
it.remove()
deepRemove(root, site)
}
}
}
private fun deepRemove(folder: BookmarkFolder, item: BookmarkItem): Boolean {
val it = folder.list.iterator()
while (it.hasNext()) {
val child = it.next()
if (child is BookmarkFolder) {
if (deepRemove(child, item))
return true
} else if (child is BookmarkSite) {
if (child == item) {
it.remove()
return true
}
}
}
return false
}
fun moveTo(from: BookmarkFolder, to: BookmarkFolder, siteIndex: Int) {
val item = from.list.removeAt(siteIndex)
to.list.add(item)
if (item is BookmarkFolder) {
item.parent = to
}
}
fun moveAll(from: BookmarkFolder, to: BookmarkFolder, items: List<BookmarkItem>) {
from.list.removeAll(items)
to.list.addAll(items)
items.filterIsInstance<BookmarkFolder>().forEach { it.parent = to }
}
fun search(query: String): List<BookmarkSite> {
val list = mutableListOf<BookmarkSite>()
val pattern = Pattern.compile("[^a-zA-Z]\\Q$query\\E")
search(list, root, pattern)
return list
}
private fun search(list: MutableList<BookmarkSite>, root: BookmarkFolder, pattern: Pattern) {
root.list.forEach {
if (it is BookmarkSite) {
if (pattern.matcher(it.url).find() || pattern.matcher(it.title ?: "").find()) {
list.add(it)
}
}
if (it is BookmarkFolder) {
search(list, it, pattern)
}
}
}
fun isBookmarked(url: String?): Boolean {
if (url == null) return false
var low = 0
var high = siteIndex.size - 1
val hash = url.hashCode()
while (low <= high) {
val mid = (low + high).ushr(1)
val itemHash = siteIndex[mid].url.hashCode()
when {
itemHash < hash -> low = mid + 1
itemHash > hash -> high = mid - 1
else -> {
if (url == siteIndex[mid].url) {
return true
}
for (i in mid - 1 downTo 0) {
val nowHash = siteIndex[i].hashCode()
if (hash != nowHash) {
break
}
if (siteIndex[i].url == url) {
return true
}
}
for (i in mid + 1 until siteIndex.size) {
val nowHash = siteIndex[i].hashCode()
if (hash != nowHash) {
break
}
if (siteIndex[i].url == url) {
return true
}
}
}
}
}
return false
}
operator fun get(id: Long): BookmarkItem? {
return if (id < 0) null else get(id, root)
}
private fun get(id: Long, root: BookmarkFolder): BookmarkItem? {
for (item in root.list) {
if (item.id == id) {
return item
} else if (item is BookmarkFolder) {
val inner = get(id, item)
if (inner != null) {
return inner
}
}
}
return null
}
private fun createIndex() {
siteIndex.clear()
addToIndexFromFolder(root)
}
private fun addToIndexFromFolder(folder: BookmarkFolder) {
folder.list.forEach {
if (it is BookmarkFolder) {
addToIndexFromFolder(it)
}
if (it is BookmarkSite) {
addToIndex(it)
}
}
}
private fun addToIndex(site: BookmarkSite) {
val hash = site.url.hashCode()
val index = siteIndex.binarySearch(site, siteComparator)
if (index < 0) {
siteIndex.add(index.inv(), site)
} else {
if (siteIndex[index] != site) {
for (i in index - 1 downTo 0) {
val itemHash = siteIndex[i].url.hashCode()
if (hash != itemHash) {
break
}
if (siteIndex[i] == site) {
return
}
}
for (i in index + 1 until siteIndex.size) {
val itemHash = siteIndex[i].url.hashCode()
if (hash != itemHash) {
break
}
if (siteIndex[i] == site) {
return
}
}
siteIndex.add(index, site)
}
}
}
private fun removeFromIndex(site: BookmarkSite) {
val hash = site.url.hashCode()
val index = siteIndex.binarySearch(site, siteComparator)
if (index >= 0) {
if (siteIndex[index] == site) {
siteIndex.removeAt(index)
return
}
for (i in index - 1 downTo 0) {
val itemHash = siteIndex[i].url.hashCode()
if (hash != itemHash) {
break
}
if (siteIndex[i] == site) {
siteIndex.removeAt(index)
return
}
}
for (i in index + 1 until siteIndex.size) {
val itemHash = siteIndex[i].url.hashCode()
if (hash != itemHash) {
break
}
if (siteIndex[i] == site) {
siteIndex.removeAt(index)
return
}
}
}
}
}
| apache-2.0 | f6d3ec8a3ca8f00ac6fd01ccd315c63e | 29.065476 | 130 | 0.503564 | 4.826565 | false | false | false | false |
thomasnield/kotlin-statistics | src/main/kotlin/org/nield/kotlinstatistics/Clustering.kt | 1 | 4534 | package org.nield.kotlinstatistics
import org.apache.commons.math3.ml.clustering.*
fun Collection<Pair<Double,Double>>.kMeansCluster(k: Int, maxIterations: Int) = kMeansCluster(k, maxIterations, {it.first}, {it.second})
fun Sequence<Pair<Double,Double>>.kMeansCluster(k: Int, maxIterations: Int) = toList().kMeansCluster(k, maxIterations, {it.first}, {it.second})
inline fun <T> Collection<T>.kMeansCluster(k: Int, maxIterations: Int, crossinline xSelector: (T) -> Double, crossinline ySelector: (T) -> Double) =
asSequence().map { ClusterInput(it, doubleArrayOf(xSelector(it), ySelector(it))) }
.toList()
.let {
KMeansPlusPlusClusterer<ClusterInput<T>>(k,maxIterations)
.cluster(it)
.map {
Centroid((it.center).point.let { DoublePoint(it[0],it[1])}, it.points.map { it.item })
}
}
inline fun <T> Sequence<T>.kMeansCluster(k: Int, maxIterations: Int, crossinline xSelector: (T) -> Double, crossinline ySelector: (T) -> Double) =
toList().kMeansCluster(k,maxIterations,xSelector,ySelector)
inline fun <T> Collection<T>.fuzzyKMeansCluster(k: Int, fuzziness: Double, crossinline xSelector: (T) -> Double, crossinline ySelector: (T) -> Double) =
asSequence().map { ClusterInput(it, doubleArrayOf(xSelector(it), ySelector(it))) }
.toList()
.let {
FuzzyKMeansClusterer<ClusterInput<T>>(k,fuzziness)
.cluster(it)
.map {
Centroid((it.center).point.let { DoublePoint(it[0],it[1])}, it.points.map { it.item })
}
}
inline fun <T> Sequence<T>.fuzzyKMeansCluster(k: Int, fuzziness: Double, crossinline xSelector: (T) -> Double, crossinline ySelector: (T) -> Double) =
toList().fuzzyKMeansCluster(k,fuzziness,xSelector,ySelector)
fun Collection<Pair<Double,Double>>.multiKMeansCluster(k: Int, maxIterations: Int, trialCount: Int) = multiKMeansCluster(k, maxIterations, trialCount, {it.first}, {it.second})
fun Sequence<Pair<Double,Double>>.multiKMeansCluster(k: Int, maxIterations: Int, trialCount: Int) = toList().multiKMeansCluster(k, maxIterations, trialCount, {it.first}, {it.second})
inline fun <T> Sequence<T>.multiKMeansCluster(k: Int, maxIterations: Int, trialCount: Int, crossinline xSelector: (T) -> Double, crossinline ySelector: (T) -> Double) =
toList().multiKMeansCluster(k, maxIterations, trialCount, xSelector, ySelector)
inline fun <T> Collection<T>.multiKMeansCluster(k: Int, maxIterations: Int, trialCount: Int, crossinline xSelector: (T) -> Double, crossinline ySelector: (T) -> Double) =
asSequence().map { ClusterInput(it, doubleArrayOf(xSelector(it), ySelector(it))) }
.toList()
.let { list ->
KMeansPlusPlusClusterer<ClusterInput<T>>(k, maxIterations)
.let {
MultiKMeansPlusPlusClusterer<ClusterInput<T>>(it, trialCount)
.cluster(list)
.map {
Centroid(DoublePoint(-1.0,-1.0), it.points.map { it.item })
}
}
}
inline fun <T> Collection<T>.dbScanCluster(maximumRadius: Double, minPoints: Int, crossinline xSelector: (T) -> Double, crossinline ySelector: (T) -> Double) =
asSequence().map { ClusterInput(it, doubleArrayOf(xSelector(it), ySelector(it))) }
.toList()
.let {
DBSCANClusterer<ClusterInput<T>>(maximumRadius,minPoints)
.cluster(it)
.map {
Centroid(DoublePoint(-1.0,-1.0), it.points.map { it.item })
}
}
inline fun <T> Sequence<T>.dbScanCluster(maximumRadius: Double, minPoints: Int, crossinline xSelector: (T) -> Double, crossinline ySelector: (T) -> Double) =
toList().dbScanCluster(maximumRadius,minPoints,xSelector,ySelector)
class ClusterInput<out T>(val item: T, val location: DoubleArray): Clusterable {
override fun getPoint() = location
}
data class DoublePoint(val x: Double, val y: Double)
data class Centroid<out T>(val center: DoublePoint, val points: List<T>) | apache-2.0 | 756c72df821f14defacc9f406f582584 | 54.987654 | 182 | 0.590428 | 4.389158 | false | false | false | false |
AlmasB/FXGL | fxgl-entity/src/main/kotlin/com/almasb/fxgl/ai/senseai/HearingSenseComponent.kt | 1 | 3700 | /*
* FXGL - JavaFX Game Library. The MIT License (MIT).
* Copyright (c) AlmasB ([email protected]).
* See LICENSE for details.
*/
package com.almasb.fxgl.ai.senseai
import com.almasb.fxgl.ai.senseai.SenseAIState.*
import com.almasb.fxgl.entity.component.Component
import javafx.beans.property.SimpleObjectProperty
import javafx.geometry.Point2D
import kotlin.math.max
/**
* Adds the ability to "hear" "noises" of interest in the game environment.
*
* @author Almas Baimagambetov ([email protected])
*/
class HearingSenseComponent(
/**
* Noise heard outside this radius will be ignored.
*/
var hearingRadius: Double
): Component() {
/**
* Drives the change in [state].
*/
private var alertness = 0.0
/**
* How quickly does the entity lose interest in being alert / aggressive.
*/
var alertnessDecay = 0.1
/**
* Noise heard with volume less than or equal to this value will be ignored.
*/
var noiseVolumeTolerance: Double = 0.0
/**
* When in [SenseAIState.CALM], only a portion of the noise volume will be heard.
* By default the value is 0.5 (=50%).
*/
var calmFactor: Double = 0.5
/**
* Alertness equal to or above this value will trigger state change to [SenseAIState.ALERT].
*/
var alertStateThreshold: Double = 0.5
/**
* Alertness equal to or above this value will trigger state change to [SenseAIState.AGGRESSIVE].
*/
var aggressiveStateThreshold: Double = 0.75
/**
* The position of the last heard noise.
*/
var lastHeardPoint = Point2D.ZERO
private val stateProp = SimpleObjectProperty(CALM)
var state: SenseAIState
get() = stateProp.value
set(value) { stateProp.value = value }
fun stateProperty() = stateProp
override fun onUpdate(tpf: Double) {
alertness = max(0.0, alertness - alertnessDecay * tpf)
if (alertness >= aggressiveStateThreshold) {
state = AGGRESSIVE
} else if (alertness >= alertStateThreshold) {
state = ALERT
} else {
state = CALM
}
}
/**
* Trigger this sense to hear a noise at [point] with given [volume].
* The [volume] diminishes based on distance between [point] and the entity.
* Based on [state], [hearingRadius] and [noiseVolumeTolerance] this noise may be ignored.
*/
fun hearNoise(point: Point2D, volume: Double) {
if (state == CANNOT_BE_DISTURBED)
return
if (volume <= noiseVolumeTolerance)
return
val distance = entity.position.distance(point)
if (distance > hearingRadius)
return
lastHeardPoint = point
val stateVolumeRatio = if (state == CALM) calmFactor else 1.0
val adjustedVolume = volume * (1.0 - (distance / hearingRadius)) * stateVolumeRatio
alertness += adjustedVolume
}
fun alertnessDecay(decayAmount: Double) = this.apply {
this.alertnessDecay = decayAmount
}
fun noiseVolumeTolerance(noiseVolumeTolerance: Double) = this.apply {
this.noiseVolumeTolerance = noiseVolumeTolerance
}
fun calmFactor(calmFactor: Double) = this.apply {
this.calmFactor = calmFactor
}
fun alertStateThreshold(alertThreshold: Double) = this.apply {
this.alertStateThreshold = alertThreshold
}
fun aggressiveStateThreshold(aggressiveStateThreshold: Double) = this.apply {
this.aggressiveStateThreshold = aggressiveStateThreshold
}
fun lastHeardPoint(lastHeardPoint: Point2D) = this.apply {
this.lastHeardPoint = lastHeardPoint
}
} | mit | 230cebc4660e482f167e51c1d438aa3c | 26.414815 | 101 | 0.647568 | 4.272517 | false | false | false | false |
manami-project/manami | manami-app/src/main/kotlin/io/github/manamiproject/manami/app/events/EventfulList.kt | 1 | 6360 | package io.github.manamiproject.manami.app.events
import io.github.manamiproject.manami.app.lists.ListChangedEvent
import io.github.manamiproject.manami.app.lists.ListChangedEvent.EventType.ADDED
import io.github.manamiproject.manami.app.lists.ListChangedEvent.EventType.REMOVED
import java.util.function.Predicate
internal class EventfulList<T>(
private val listType: EventListType,
private val eventBus: EventBus = SimpleEventBus,
private val list: MutableList<T> = mutableListOf(),
) : MutableList<T> by list {
constructor(listType: EventListType, vararg values: T) : this(
listType = listType,
list = values.toMutableList()
)
override fun add(element: T): Boolean {
if (list.contains(element)) {
return false
}
val hasBeenModified = list.add(element)
if (hasBeenModified) {
eventBus.post(
ListChangedEvent(
list = listType,
type = ADDED,
obj = setOf(element)
)
)
}
return hasBeenModified
}
override fun add(index: Int, element: T) {
require(index <= list.size - 1) { "Cannot add on unpopulated index." }
if (list.contains(element)) {
list.remove(element)
list.add(index, element)
} else {
list.add(index, element)
eventBus.post(
ListChangedEvent(
list = listType,
type = ADDED,
obj = setOf(element)
)
)
}
}
override fun addAll(index: Int, elements: Collection<T>): Boolean {
val isModifiable = elements.any { !list.contains(it) }
list.removeAll(elements)
list.addAll(index, elements)
if (isModifiable) {
eventBus.post(
ListChangedEvent(
list = listType,
type = ADDED,
obj = elements.toSet()
)
)
}
return isModifiable
}
override fun addAll(elements: Collection<T>): Boolean {
val elementsToAdd = elements.filterNot { list.contains(it) }
val isModifiable = elementsToAdd.isNotEmpty()
if (isModifiable) {
list.addAll(elementsToAdd)
eventBus.post(
ListChangedEvent(
list = listType,
type = ADDED,
obj = elements.toSet()
)
)
}
return isModifiable
}
override fun remove(element: T): Boolean {
if (!list.contains(element)) {
return false
}
val hasBeenModified = list.remove(element)
if (hasBeenModified) {
eventBus.post(
ListChangedEvent(
list = listType,
type = REMOVED,
obj = setOf(element)
)
)
}
return hasBeenModified
}
override fun removeAll(elements: Collection<T>): Boolean {
val elementsToRemove = elements.filter { list.contains(it) }
val isModifiable = elementsToRemove.isNotEmpty()
if (isModifiable) {
list.removeAll(elementsToRemove)
eventBus.post(
ListChangedEvent(
list = listType,
type = REMOVED,
obj = elementsToRemove.toSet()
)
)
}
return isModifiable
}
override fun removeAt(index: Int): T {
require(index < list.size - 1) { "Cannot remove unpopulated index." }
val returnValue = list.removeAt(index)
eventBus.post(
ListChangedEvent(
list = listType,
type = REMOVED,
obj = setOf(returnValue)
)
)
return returnValue
}
override fun removeIf(filter: Predicate<in T>): Boolean {
val elementsBeingRemoved = list.filter { filter.test(it)}
val isModifiable = elementsBeingRemoved.isNotEmpty()
if (isModifiable) {
list.removeIf(filter)
eventBus.post(
ListChangedEvent(
list = listType,
type = REMOVED,
obj = elementsBeingRemoved.toSet()
)
)
}
return isModifiable
}
override fun retainAll(elements: Collection<T>): Boolean {
val elementsToBeRemoved = list - elements
val isModifiable = elementsToBeRemoved.isNotEmpty()
if (isModifiable) {
list.removeAll(elementsToBeRemoved)
eventBus.post(
ListChangedEvent(
list = listType,
type = REMOVED,
obj = elementsToBeRemoved.toSet()
)
)
}
return isModifiable
}
override fun set(index: Int, element: T): T {
require(index <= list.size - 1) { "Cannot replace entry on unpopulated index." }
val replacedValue = list.set(index, element)
if (replacedValue != element) {
eventBus.post(
ListChangedEvent(
list = listType,
type = REMOVED,
obj = setOf(replacedValue)
)
)
eventBus.post(
ListChangedEvent(
list = listType,
type = ADDED,
obj = setOf(element)
)
)
}
return replacedValue
}
override fun clear() {
if (list.isEmpty()) {
return
}
eventBus.post(
ListChangedEvent(
list = listType,
type = REMOVED,
obj = list.toSet()
)
)
list.clear()
}
override fun toString(): String = list.toString()
override fun equals(other: Any?): Boolean {
if (other == null || other !is EventfulList<*>) return false
if (other === this) return true
return other.toList() == list.toList()
}
override fun hashCode(): Int = list.toList().hashCode()
} | agpl-3.0 | 4adce53a463b75afd1209323860ccb7c | 25.504167 | 88 | 0.50566 | 5.308848 | false | false | false | false |
uber/AutoDispose | static-analysis/autodispose-lint/src/test/kotlin/autodispose2/lint/AutoDisposeDetectorTest.kt | 1 | 48121 | /*
* Copyright (C) 2019. Uber Technologies
*
* 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 autodispose2.lint
import com.android.tools.lint.checks.infrastructure.LintDetectorTest
import com.android.tools.lint.checks.infrastructure.TestFile
import com.android.tools.lint.checks.infrastructure.TestFiles.LibraryReferenceTestFile
import com.android.tools.lint.detector.api.Detector
import com.android.tools.lint.detector.api.Issue
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
import java.io.File
@RunWith(JUnit4::class)
internal class AutoDisposeDetectorTest : LintDetectorTest() {
companion object {
// Stub activity
private val ACTIVITY = java(
"""
package androidx.appcompat.app;
import androidx.lifecycle.LifecycleOwner;
public class AppCompatActivity implements LifecycleOwner {
}
"""
).indented()
// Stub LifecycleOwner
private val LIFECYCLE_OWNER = java(
"""
package androidx.lifecycle;
public interface LifecycleOwner {}
"""
).indented()
// Stub Fragment
private val FRAGMENT = java(
"""
package androidx.fragment.app;
import androidx.lifecycle.LifecycleOwner;
public class Fragment implements LifecycleOwner {}
"""
).indented()
// Stub Scope Provider
private val SCOPE_PROVIDER = kotlin(
"""
package autodispose2
interface ScopeProvider
"""
).indented()
// Stub LifecycleScopeProvider
private val LIFECYCLE_SCOPE_PROVIDER = kotlin(
"""
package autodispose2.lifecycle
import autodispose2.ScopeProvider
interface LifecycleScopeProvider: ScopeProvider
"""
).indented()
// Custom Scope
private val CUSTOM_SCOPE = kotlin(
"""
package autodispose2.sample
class ClassWithCustomScope
"""
).indented()
private val AUTODISPOSE_CONTEXT = kotlin(
"""
package autodispose2
interface AutoDisposeContext
"""
).indented()
private val WITH_SCOPE_PROVIDER = kotlin(
"autodispose2/KotlinExtensions.kt",
"""
@file:JvmName("KotlinExtensions")
package autodispose2
fun withScope(scope: ScopeProvider, body: AutoDisposeContext.() -> Unit) {
}
"""
).indented().within("src/")
private val WITH_SCOPE_COMPLETABLE = kotlin(
"autodispose2/KotlinExtensions.kt",
"""
@file:JvmName("KotlinExtensions")
package autodispose2
import io.reactivex.rxjava3.core.Completable
fun withScope(scope: Completable, body: AutoDisposeContext.() -> Unit) {
}
"""
).indented().within("src/")
private val RX_KOTLIN = kotlin(
"io/reactivex/rxjava3/kotlin/subscribers.kt",
"""
@file:JvmName("subscribers")
package io.reactivex.rxjava3.kotlin
import io.reactivex.rxjava3.core.*
import io.reactivex.rxjava3.disposables.Disposable
fun <G : Any> Observable<G>.subscribeBy(
onNext: (G) -> Unit
): Disposable = subscribe()
"""
).indented().within("src/")
private fun propertiesFile(lenient: Boolean = true, kotlinExtensionFunctions: String? = null): TestFile.PropertyTestFile {
val properties = projectProperties()
properties.property(LENIENT, lenient.toString())
kotlinExtensionFunctions?.also {
properties.property(KOTLIN_EXTENSION_FUNCTIONS, it)
}
properties.to(AutoDisposeDetector.PROPERTY_FILE)
return properties
}
private fun lenientPropertiesFile(lenient: Boolean = true): TestFile.PropertyTestFile {
return propertiesFile(lenient)
}
}
@Test fun observableErrorsOutOnOmittingAutoDispose() {
lint()
.files(
*jars(),
LIFECYCLE_OWNER,
FRAGMENT,
java(
"""
package foo;
import io.reactivex.rxjava3.core.Observable;
import androidx.fragment.app.Fragment;
class ExampleClass extends Fragment {
void names() {
Observable<Integer> obs = Observable.just(1, 2, 3, 4);
obs.subscribe();
}
}
"""
).indented()
)
.run()
.expect(
"""src/foo/ExampleClass.java:8: Error: ${AutoDisposeDetector.LINT_DESCRIPTION} [AutoDispose]
| obs.subscribe();
| ~~~~~~~~~~~~~~~
|1 errors, 0 warnings""".trimMargin()
)
}
@Test fun observableDisposesSubscriptionJava() {
lint()
.files(
*jars(),
java(
"""
package foo;
import io.reactivex.rxjava3.core.Observable;
import autodispose2.AutoDispose;
import autodispose2.ScopeProvider;
class ExampleClass {
private ScopeProvider scopeProvider;
void names() {
Observable<Integer> obs = Observable.just(1, 2, 3, 4);
obs.as(AutoDispose.autoDisposable(scopeProvider)).subscribe();
}
}
"""
).indented()
)
.allowCompilationErrors() // Lint 30 doesn't understand subscribeProxies for some reason
.run()
.expectClean()
}
@Test fun observableSubscribeWithNotHandled() {
lint()
.files(
*jars(),
LIFECYCLE_OWNER,
FRAGMENT,
java(
"""
package foo;
import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.observers.DisposableObserver;
import androidx.fragment.app.Fragment;
class ExampleClass extends Fragment {
void names() {
Observable<Integer> obs = Observable.just(1, 2, 3, 4);
obs.subscribeWith(new DisposableObserver<Integer>() {
@Override
public void onNext(Integer integer) {
}
@Override
public void onError(Throwable e) {}
@Override
public void onComplete() {}
});
}
}
"""
).indented()
)
.run()
.expect(
"""src/foo/ExampleClass.java:9: Error: ${AutoDisposeDetector.LINT_DESCRIPTION} [AutoDispose]
| obs.subscribeWith(new DisposableObserver<Integer>() {
| ^
|1 errors, 0 warnings""".trimMargin()
)
}
@Test fun observableSubscribeWithDisposed() {
lint()
.files(
*jars(),
SCOPE_PROVIDER,
LIFECYCLE_OWNER,
FRAGMENT,
java(
"""
package foo;
import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.observers.DisposableObserver;
import androidx.fragment.app.Fragment;
import autodispose2.AutoDispose;
import autodispose2.ScopeProvider;
class ExampleClass extends Fragment {
ScopeProvider scopeProvider;
void names() {
Observable<Integer> obs = Observable.just(1, 2, 3, 4);
obs.as(AutoDispose.autoDisposable(scopeProvider)).subscribeWith(
new DisposableObserver<Integer>() {
@Override
public void onNext(Integer integer) {
}
@Override
public void onError(Throwable e) {}
@Override
public void onComplete() {}
});
}
}
"""
).indented()
)
.allowCompilationErrors() // Lint 30 doesn't understand subscribeWith for some reason
.run()
.expectClean()
}
@Test fun observableDisposesSubscriptionKotlin() {
lint()
.files(
*jars(),
kotlin(
"""
package foo
import io.reactivex.rxjava3.core.Observable
import autodispose2.autoDispose
import autodispose2.ScopeProvider
class ExampleClass {
lateinit var scopeProvider: ScopeProvider
fun names() {
val obs = Observable.just(1, 2, 3, 4)
obs.autoDispose(scopeProvider).subscribe()
}
}
"""
).indented()
)
.allowCompilationErrors() // Until AGP 7.1.0 https://groups.google.com/g/lint-dev/c/BigCO8sMhKU
.run()
.expectClean()
}
@Test fun singleErrorsOutOnOmittingAutoDispose() {
lint()
.files(
*jars(),
LIFECYCLE_OWNER,
ACTIVITY,
java(
"""
package foo;
import io.reactivex.rxjava3.core.Single;
import androidx.appcompat.app.AppCompatActivity;
class ExampleClass extends AppCompatActivity {
void names() {
Single<Integer> single = Single.just(1);
single.subscribe();
}
}
"""
).indented()
)
.run()
.expect(
"""src/foo/ExampleClass.java:8: Error: ${AutoDisposeDetector.LINT_DESCRIPTION} [AutoDispose]
| single.subscribe();
| ~~~~~~~~~~~~~~~~~~
|1 errors, 0 warnings""".trimMargin()
)
}
@Test fun singleDisposesSubscriptionJava() {
lint()
.files(
*jars(),
java(
"""
package foo;
import io.reactivex.rxjava3.core.Single;
import autodispose2.AutoDispose;
import autodispose2.ScopeProvider;
class ExampleClass {
private ScopeProvider scopeProvider;
void names() {
Single<Integer> single = Single.just(1);
single.as(AutoDispose.autoDisposable(scopeProvider)).subscribe();
}
}
"""
).indented()
)
.allowCompilationErrors() // Lint 30 doesn't understand subscribeProxies for some reason
.run()
.expectClean()
}
@Test fun singleDisposesSubscriptionKotlin() {
lint()
.files(
*jars(),
kotlin(
"""
package foo
import io.reactivex.rxjava3.core.Single
import autodispose2.ScopeProvider
import autodispose2.autoDispose
class ExampleClass {
lateinit var scopeProvider: ScopeProvider
fun names() {
val single = Single.just(1)
single.autoDispose(scopeProvider).subscribe()
}
}
"""
).indented()
)
.allowCompilationErrors() // Until AGP 7.1.0 https://groups.google.com/g/lint-dev/c/BigCO8sMhKU
.run()
.expectClean()
}
@Test fun flowableErrorsOutOnOmittingAutoDispose() {
lint()
.files(
*jars(),
LIFECYCLE_OWNER,
java(
"""
package foo;
import io.reactivex.rxjava3.core.Flowable;
import androidx.lifecycle.LifecycleOwner;
class ExampleClass implements LifecycleOwner {
void names() {
Flowable<Integer> flowable = Flowable.just(1);
flowable.subscribe();
}
}
"""
).indented()
)
.run()
.expect(
"""src/foo/ExampleClass.java:8: Error: ${AutoDisposeDetector.LINT_DESCRIPTION} [AutoDispose]
| flowable.subscribe();
| ~~~~~~~~~~~~~~~~~~~~
|1 errors, 0 warnings""".trimMargin()
)
}
@Test fun flowableDisposesSubscriptionJava() {
lint()
.files(
*jars(),
java(
"""
package foo;
import io.reactivex.rxjava3.core.Flowable;
import autodispose2.AutoDispose;
import autodispose2.ScopeProvider;
class ExampleClass {
private ScopeProvider scopeProvider;
void names() {
Flowable<Integer> flowable = Flowable.just(1, 2, 3, 4);
flowable.as(AutoDispose.autoDisposable(scopeProvider)).subscribe();
}
}
"""
).indented()
)
.allowCompilationErrors() // Lint 30 doesn't understand subscribeProxies for some reason
.run()
.expectClean()
}
@Test fun flowableDisposesSubscriptionKotlin() {
lint()
.files(
*jars(),
LIFECYCLE_SCOPE_PROVIDER,
kotlin(
"""
package foo
import io.reactivex.rxjava3.core.Observable
import autodispose2.autoDispose
import autodispose2.lifecycle.LifecycleScopeProvider
class ExampleClass: LifecycleScopeProvider {
fun names() {
val flowable = Flowable.just(1, 2, 3, 4)
flowable.autoDispose(this).subscribe()
}
}
"""
).indented()
)
.allowCompilationErrors() // Until AGP 7.1.0 https://groups.google.com/g/lint-dev/c/BigCO8sMhKU
.run()
.expectClean()
}
@Test fun completableErrorsOutOnOmittingAutoDispose() {
lint()
.files(
*jars(),
SCOPE_PROVIDER,
kotlin(
"""
package foo
import io.reactivex.rxjava3.core.Completable
import autodispose2.ScopeProvider
class ExampleClass: ScopeProvider {
fun names() {
val completable = Completable.complete()
completable.subscribe()
}
}
"""
).indented()
)
.run()
.expect(
"""src/foo/ExampleClass.kt:8: Error: ${AutoDisposeDetector.LINT_DESCRIPTION} [AutoDispose]
| completable.subscribe()
| ~~~~~~~~~~~~~~~~~~~~~~~
|1 errors, 0 warnings""".trimMargin()
)
}
@Test fun completableSubscriptionNonScopedClass() {
lint()
.files(
*jars(),
java(
"""
package foo;
import io.reactivex.rxjava3.core.Completable;
import autodispose2.ScopeProvider;
class ExampleClass {
private ScopeProvider scopeProvider;
void names() {
Completable completable = Completable.complete();
completable.subscribe();
}
}
"""
).indented()
)
.run()
.expectClean()
}
@Test fun completableDisposesSubscriptionKotlin() {
lint()
.files(
*jars(),
kotlin(
"""
package foo
import io.reactivex.rxjava3.core.Observable
import autodispose2.ScopeProvider
import autodispose2.autoDispose
class ExampleClass {
lateinit var scopeProvider: ScopeProvider
fun names() {
val completable = Completable.complete()
completable.autoDispose(scopeProvider).subscribe()
}
}
"""
).indented()
)
.allowCompilationErrors() // Until AGP 7.1.0 https://groups.google.com/g/lint-dev/c/BigCO8sMhKU
.run()
.expectClean()
}
@Test fun maybeErrorsOutOnOmittingAutoDispose() {
lint()
.files(
*jars(),
LIFECYCLE_OWNER,
ACTIVITY,
kotlin(
"""
package foo
import io.reactivex.rxjava3.core.Maybe
import androidx.appcompat.app.AppCompatActivity
class ExampleClass: AppCompatActivity {
fun names() {
val maybe = Maybe.just(1)
maybe.subscribe()
}
}
"""
).indented()
)
.run()
.expect(
"""src/foo/ExampleClass.kt:8: Error: ${AutoDisposeDetector.LINT_DESCRIPTION} [AutoDispose]
| maybe.subscribe()
| ~~~~~~~~~~~~~~~~~
|1 errors, 0 warnings""".trimMargin()
)
}
@Test fun maybeDisposesSubscriptionJava() {
lint()
.files(
*jars(),
java(
"""
package foo;
import io.reactivex.rxjava3.core.Maybe;
import autodispose2.AutoDispose;
import autodispose2.ScopeProvider;
class ExampleClass {
private ScopeProvider scopeProvider;
void names() {
Maybe<Integer> maybe = Maybe.just(1);
maybe.as(AutoDispose.autoDisposable(scopeProvider)).subscribe();
}
}
"""
).indented()
)
.allowCompilationErrors() // Lint 30 doesn't understand subscribeProxies for some reason
.run()
.expectClean()
}
@Test fun maybeDisposesSubscriptionKotlin() {
lint()
.files(
*jars(),
kotlin(
"""
package foo
import io.reactivex.rxjava3.core.Maybe
import autodispose2.autoDispose
import autodispose2.ScopeProvider
class ExampleClass {
lateinit var scopeProvider: ScopeProvider
fun names() {
val maybe = Maybe.just(2)
maybe.autoDispose(scopeProvider).subscribe()
}
}
"""
).indented()
)
.allowCompilationErrors() // Until AGP 7.1.0 https://groups.google.com/g/lint-dev/c/BigCO8sMhKU
.run()
.expectClean()
}
@Test fun customScopeWithoutAutoDispose() {
val properties = projectProperties()
properties.property(CUSTOM_SCOPE_KEY, "autodispose2.sample.ClassWithCustomScope")
properties.to(AutoDisposeDetector.PROPERTY_FILE)
lint().files(
*jars(),
CUSTOM_SCOPE,
properties,
kotlin(
"""
package autodispose2.sample
import autodispose2.sample.ClassWithCustomScope
import io.reactivex.rxjava3.core.Observable
class MyCustomClass: ClassWithCustomScope {
fun doSomething() {
val observable = Observable.just(1, 2, 3)
observable.subscribe()
}
}
"""
).indented()
)
.run()
.expect(
"""
src/autodispose2/sample/MyCustomClass.kt:8: Error: ${AutoDisposeDetector.LINT_DESCRIPTION} [AutoDispose]
| observable.subscribe()
| ~~~~~~~~~~~~~~~~~~~~~~
|1 errors, 0 warnings""".trimMargin()
)
}
@Test fun customScopeWithAutoDispose() {
val properties = projectProperties()
properties.property(CUSTOM_SCOPE_KEY, "autodispose2.sample.ClassWithCustomScope")
properties.to(AutoDisposeDetector.PROPERTY_FILE)
lint().files(
*jars(),
CUSTOM_SCOPE,
properties,
kotlin(
"""
package autodispose2.sample
import autodispose2.sample.ClassWithCustomScope
import io.reactivex.rxjava3.core.Observable
import autodispose2.autoDispose
import autodispose2.ScopeProvider
class MyCustomClass: ClassWithCustomScope {
lateinit var scopeProvider: ScopeProvider
fun doSomething() {
val observable = Observable.just(1, 2, 3)
observable.autoDispose(scopeProvider).subscribe()
}
}
"""
).indented()
)
.allowCompilationErrors() // Until AGP 7.1.0 https://groups.google.com/g/lint-dev/c/BigCO8sMhKU
.run()
.expectClean()
}
@Test fun emptyCustomScopeWithoutAutoDispose() {
val properties = projectProperties()
properties.to(AutoDisposeDetector.PROPERTY_FILE)
lint().files(
*jars(),
CUSTOM_SCOPE,
properties,
kotlin(
"""
package autodispose2.sample
import autodispose2.sample.ClassWithCustomScope
import io.reactivex.rxjava3.core.Observable
import autodispose2.ScopeProvider
class MyCustomClass: ClassWithCustomScope {
lateinit var scopeProvider: ScopeProvider
fun doSomething() {
val observable = Observable.just(1, 2, 3)
observable.subscribe() // No error since custom scope not defined in properties file.
}
}
"""
).indented()
)
.run()
.expectClean()
}
@Test fun overrideCustomScopeWithoutAutoDispose() {
val properties = projectProperties()
properties.property(CUSTOM_SCOPE_KEY, "autodispose2.sample.ClassWithCustomScope")
properties.property(OVERRIDE_SCOPES, "true")
properties.to(AutoDisposeDetector.PROPERTY_FILE)
lint().files(
*jars(),
LIFECYCLE_OWNER,
ACTIVITY,
properties,
kotlin(
"""
package autodispose2.sample
import autodispose2.sample.ClassWithCustomScope
import androidx.appcompat.app.AppCompatActivity
import io.reactivex.rxjava3.core.Observable
import autodispose2.ScopeProvider
class MyCustomClass: AppCompatActivity {
lateinit var scopeProvider: ScopeProvider
fun doSomething() {
val observable = Observable.just(1, 2, 3)
observable.subscribe() // No error since the scopes are being overriden and only custom ones are considered.
}
}
"""
).indented()
)
.allowCompilationErrors() // TODO or replace with a real sample stub?
.run()
.expectClean()
}
@Test fun overrideCustomScopeWithAutoDispose() {
val properties = projectProperties()
properties.property(CUSTOM_SCOPE_KEY, "autodispose2.sample.ClassWithCustomScope")
properties.property(OVERRIDE_SCOPES, "true")
properties.to(AutoDisposeDetector.PROPERTY_FILE)
lint().files(
*jars(),
CUSTOM_SCOPE,
properties,
kotlin(
"""
package autodispose2.sample
import autodispose2.sample.ClassWithCustomScope
import io.reactivex.rxjava3.core.Observable
import autodispose2.ScopeProvider
import autodispose2.autoDispose
class MyCustomClass: ClassWithCustomScope {
lateinit var scopeProvider: ScopeProvider
fun doSomething() {
val observable = Observable.just(1, 2, 3)
observable.autoDispose(scopeProvider).subscribe()
}
}
"""
).indented()
)
.allowCompilationErrors() // Until AGP 7.1.0 https://groups.google.com/g/lint-dev/c/BigCO8sMhKU
.run()
.expectClean()
}
@Test fun capturedDisposable() {
val propertiesFile = lenientPropertiesFile()
lint().files(
*jars(),
propertiesFile,
LIFECYCLE_OWNER,
ACTIVITY,
kotlin(
"""
package foo
import androidx.appcompat.app.AppCompatActivity
import io.reactivex.rxjava3.core.Observable
class MyActivity: AppCompatActivity {
fun doSomething() {
val disposable = Observable.just(1, 2, 3).subscribe()
}
}
"""
).indented()
)
.run()
.expectClean()
}
@Test fun nestedDisposable() {
val propertiesFile = lenientPropertiesFile()
lint().files(
*jars(),
propertiesFile,
LIFECYCLE_OWNER,
ACTIVITY,
kotlin(
"""
package foo
import androidx.appcompat.app.AppCompatActivity
import io.reactivex.rxjava3.core.Observable
import io.reactivex.rxjava3.disposables.CompositeDisposable
class MyActivity: AppCompatActivity {
private val disposables = CompositeDisposable()
fun doSomething() {
disposables.add(
Observable.just(1, 2, 3).subscribe()
)
}
}
"""
).indented()
)
.run()
.expectClean()
}
@Test fun subscribeWithLambda() {
lint().files(
*jars(),
LIFECYCLE_OWNER,
ACTIVITY,
kotlin(
"""
package foo
import androidx.appcompat.app.AppCompatActivity
import io.reactivex.rxjava3.core.Observable
import io.reactivex.rxjava3.disposables.CompositeDisposable
import io.reactivex.rxjava3.disposables.Disposable
class MyActivity: AppCompatActivity {
private val disposables = CompositeDisposable()
fun doSomething() {
Observable.just(1,2,3).subscribe {}
}
}
"""
).indented()
)
.run()
.expect(
"""src/foo/MyActivity.kt:10: Error: ${AutoDisposeDetector.LINT_DESCRIPTION} [AutoDispose]
| Observable.just(1,2,3).subscribe {}
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|1 errors, 0 warnings""".trimMargin()
)
}
@Test fun checkLenientLintInIfExpression() {
val propertiesFile = lenientPropertiesFile()
lint().files(
*jars(),
propertiesFile,
LIFECYCLE_OWNER,
ACTIVITY,
kotlin(
"""
package foo
import androidx.appcompat.app.AppCompatActivity
import io.reactivex.rxjava3.core.Observable
import io.reactivex.rxjava3.disposables.CompositeDisposable
class MyActivity: AppCompatActivity {
private val disposables = CompositeDisposable()
fun doSomething(flag: Boolean) {
if (flag) {
Observable.just(1).subscribe()
} else {
Observable.just(2).subscribe()
}
}
}
"""
).indented()
)
.run()
.expect(
"""
|src/foo/MyActivity.kt:10: Error: ${AutoDisposeDetector.LINT_DESCRIPTION} [AutoDispose]
| Observable.just(1).subscribe()
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|src/foo/MyActivity.kt:12: Error: ${AutoDisposeDetector.LINT_DESCRIPTION} [AutoDispose]
| Observable.just(2).subscribe()
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|2 errors, 0 warnings""".trimMargin()
)
}
@Test fun checkLenientLintInIfExpressionCaptured() {
val propertiesFile = lenientPropertiesFile()
lint().files(
*jars(),
propertiesFile,
LIFECYCLE_OWNER,
ACTIVITY,
kotlin(
"""
package foo
import androidx.appcompat.app.AppCompatActivity
import io.reactivex.rxjava3.core.Observable
import io.reactivex.rxjava3.disposables.CompositeDisposable
class MyActivity: AppCompatActivity {
private val disposables = CompositeDisposable()
fun doSomething(flag: Boolean) {
val disposable = if (flag) {
Observable.just(1).subscribe()
} else {
Observable.just(2).subscribe()
}
}
}
"""
).indented()
)
.run()
.expectClean()
}
@Test fun checkLenientLintInWhenExpression() {
val propertiesFile = lenientPropertiesFile()
lint().files(
*jars(),
propertiesFile,
LIFECYCLE_OWNER,
ACTIVITY,
kotlin(
"""
package foo
import androidx.appcompat.app.AppCompatActivity
import io.reactivex.rxjava3.core.Observable
import io.reactivex.rxjava3.disposables.CompositeDisposable
class MyActivity: AppCompatActivity {
private val disposables = CompositeDisposable()
fun doSomething(flag: Boolean) {
when (flag) {
true -> Observable.just(1).subscribe()
false -> Observable.just(2).subscribe()
}
}
}
"""
).indented()
)
.run()
.expect(
"""
|src/foo/MyActivity.kt:10: Error: ${AutoDisposeDetector.LINT_DESCRIPTION} [AutoDispose]
| true -> Observable.just(1).subscribe()
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|src/foo/MyActivity.kt:11: Error: ${AutoDisposeDetector.LINT_DESCRIPTION} [AutoDispose]
| false -> Observable.just(2).subscribe()
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|2 errors, 0 warnings""".trimMargin()
)
}
@Test fun checkLenientLintInWhenExpressionCaptured() {
val propertiesFile = lenientPropertiesFile()
lint().files(
*jars(),
propertiesFile,
LIFECYCLE_OWNER,
ACTIVITY,
kotlin(
"""
package foo
import androidx.appcompat.app.AppCompatActivity
import io.reactivex.rxjava3.core.Observable
import io.reactivex.rxjava3.disposables.CompositeDisposable
class MyActivity: AppCompatActivity {
private val disposables = CompositeDisposable()
fun doSomething(flag: Boolean) {
val disposable = when (flag) {
true -> Observable.just(1).subscribe()
false -> Observable.just(2).subscribe()
}
}
}
"""
).indented()
)
.run()
.expectClean()
}
@Test fun checkLenientLintInLambdaWithUnitReturnExpression() {
val propertiesFile = lenientPropertiesFile()
lint().files(
*jars(),
propertiesFile,
LIFECYCLE_OWNER,
ACTIVITY,
kotlin(
"""
package foo
import androidx.appcompat.app.AppCompatActivity
import io.reactivex.rxjava3.core.Observable
import io.reactivex.rxjava3.disposables.CompositeDisposable
class MyActivity: AppCompatActivity {
private val disposables = CompositeDisposable()
fun doSomething() {
val receiveReturnUnitFn: (() -> Unit) -> Unit = {}
receiveReturnUnitFn {
Observable.just(1).subscribe()
}
}
}
"""
).indented()
)
.run()
.expect(
"""
|src/foo/MyActivity.kt:11: Error: ${AutoDisposeDetector.LINT_DESCRIPTION} [AutoDispose]
| Observable.just(1).subscribe()
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|1 errors, 0 warnings""".trimMargin()
)
}
@Test fun checkLenientLintInLambdaWithNonUnitReturnExpression() {
val propertiesFile = lenientPropertiesFile()
lint().files(
*jars(),
propertiesFile,
LIFECYCLE_OWNER,
ACTIVITY,
kotlin(
"""
package foo
import androidx.appcompat.app.AppCompatActivity
import io.reactivex.rxjava3.core.Observable
import io.reactivex.rxjava3.disposables.CompositeDisposable
class MyActivity: AppCompatActivity {
private val disposables = CompositeDisposable()
fun doSomething() {
val receiveReturnAnyFn: (() -> Any) -> Unit = {}
receiveReturnAnyFn {
Observable.just(1).subscribe()
"result"
}
}
}
"""
).indented()
)
.run()
.expect(
"""
|src/foo/MyActivity.kt:11: Error: ${AutoDisposeDetector.LINT_DESCRIPTION} [AutoDispose]
| Observable.just(1).subscribe()
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|1 errors, 0 warnings""".trimMargin()
)
}
@Test fun checkLenientLintInLambdaExpressionCaptured() {
val propertiesFile = lenientPropertiesFile()
lint().files(
*jars(),
propertiesFile,
LIFECYCLE_OWNER,
ACTIVITY,
kotlin(
"""
package foo
import androidx.appcompat.app.AppCompatActivity
import io.reactivex.rxjava3.core.Observable
import io.reactivex.rxjava3.disposables.CompositeDisposable
class MyActivity: AppCompatActivity {
private val disposables = CompositeDisposable()
fun doSomething() {
val receiveReturnAnyFn: (() -> Any) -> Unit = {}
receiveReturnAnyFn {
Observable.just(1).subscribe()
}
}
}
"""
).indented()
)
.run()
.expectClean()
}
@Test fun javaCapturedDisposable() {
val propertiesFile = lenientPropertiesFile()
lint().files(
*jars(),
propertiesFile,
LIFECYCLE_OWNER,
ACTIVITY,
java(
"""
package foo;
import androidx.appcompat.app.AppCompatActivity;
import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.disposables.Disposable;
class MyActivity extends AppCompatActivity {
fun doSomething() {
Disposable disposable = Observable.just(1, 2, 3).subscribe();
}
}
"""
).indented()
)
.run()
.expectClean()
}
@Test fun javaCapturedDisposableWithoutLenientProperty() {
val propertiesFile = lenientPropertiesFile(false)
lint().files(
*jars(),
propertiesFile,
LIFECYCLE_OWNER,
ACTIVITY,
java(
"""
package foo;
import androidx.appcompat.app.AppCompatActivity;
import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.disposables.Disposable;
class MyActivity extends AppCompatActivity {
fun doSomething() {
Disposable disposable = Observable.just(1, 2, 3).subscribe();
}
}
"""
).indented()
)
.run()
.expect(
"""src/foo/MyActivity.java:8: Error: ${AutoDisposeDetector.LINT_DESCRIPTION} [AutoDispose]
| Disposable disposable = Observable.just(1, 2, 3).subscribe();
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|1 errors, 0 warnings""".trimMargin()
)
}
@Test fun subscribeWithCapturedNonDisposableFromMethodReference() {
lint()
.files(
*jars(),
LIFECYCLE_OWNER,
FRAGMENT,
java(
"""
package foo;
import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.observers.DisposableObserver;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.core.Observer;
import androidx.fragment.app.Fragment;
import io.reactivex.rxjava3.functions.Function;
class ExampleClass extends Fragment {
void names() {
Observable<Integer> obs = Observable.just(1, 2, 3, 4);
try {
Observer<Integer> observer = methodReferencable(obs::subscribeWith);
} catch (Exception e){
}
}
Observer<Integer> methodReferencable(Function<Observer<Integer>, Observer<Integer>> func) throws Exception {
return func.apply(new Observer<Integer>() {
@Override public void onSubscribe(Disposable d) {
}
@Override public void onNext(Integer integer) {
}
@Override public void onError(Throwable e) {
}
@Override public void onComplete() {
}
});
}
}
"""
).indented()
)
.run()
.expect(
"""src/foo/ExampleClass.java:13: Error: ${AutoDisposeDetector.LINT_DESCRIPTION} [AutoDispose]
| Observer<Integer> observer = methodReferencable(obs::subscribeWith);
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|1 errors, 0 warnings""".trimMargin()
)
}
@Test fun subscribeWithCapturedDisposableFromMethodReference() {
val propertiesFile = lenientPropertiesFile()
lint()
.files(
*jars(),
propertiesFile,
LIFECYCLE_OWNER,
FRAGMENT,
java(
"""
package foo;
import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.observers.DisposableObserver;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.core.Observer;
import androidx.fragment.app.Fragment;
import io.reactivex.rxjava3.functions.Function;
class ExampleClass extends Fragment {
void names() {
Observable<Integer> obs = Observable.just(1, 2, 3, 4);
try {
Disposable disposable = methodReferencable(obs::subscribeWith);
} catch (Exception e){
}
}
DisposableObserver<Integer> methodReferencable(Function<DisposableObserver<Integer>, DisposableObserver<Integer>> func) throws Exception {
return func.apply(new DisposableObserver<Integer>() {
@Override
public void onNext(Integer integer) {
}
@Override
public void onError(Throwable e) {
}
@Override
public void onComplete() {
}
});
}
}
"""
).indented()
)
.run()
.expectClean()
}
@Test fun kotlinSubscribeWithCapturedNonDisposableFromMethodReference() {
val propertiesFile = lenientPropertiesFile()
lint()
.files(
*jars(),
propertiesFile,
LIFECYCLE_OWNER,
FRAGMENT,
kotlin(
"""
package foo
import io.reactivex.rxjava3.core.Observable
import io.reactivex.rxjava3.observers.DisposableObserver
import io.reactivex.rxjava3.disposables.Disposable
import io.reactivex.rxjava3.core.Observer
import androidx.fragment.app.Fragment
import io.reactivex.rxjava3.functions.Function
class ExampleClass: Fragment {
fun names() {
val observable: Observable<Int> = Observable.just(1)
val observer: Observer<Int> = methodReferencable(Function { observable.subscribeWith(it) })
}
@Throws(Exception::class)
internal fun methodReferencable(func: Function<Observer<Int>, Observer<Int>>): Observer<Int> {
return func.apply(object : Observer<Int> {
override fun onSubscribe(d: Disposable) {
}
override fun onNext(integer: Int) {
}
override fun onError(e: Throwable) {
}
override fun onComplete() {
}
})
}
}
"""
).indented()
)
.run()
.expect(
"""src/foo/ExampleClass.kt:12: Error: ${AutoDisposeDetector.LINT_DESCRIPTION} [AutoDispose]
| val observer: Observer<Int> = methodReferencable(Function { observable.subscribeWith(it) })
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|1 errors, 0 warnings""".trimMargin()
)
}
@Test fun kotlinSubscribeWithCapturedDisposableFromMethodReference() {
val propertiesFile = lenientPropertiesFile()
lint()
.files(
*jars(),
propertiesFile,
LIFECYCLE_OWNER,
FRAGMENT,
kotlin(
"""
package foo
import androidx.fragment.app.Fragment
import io.reactivex.rxjava3.core.Observable
import io.reactivex.rxjava3.core.Observer
import io.reactivex.rxjava3.disposables.Disposable
import io.reactivex.rxjava3.functions.Function
import io.reactivex.rxjava3.observers.DisposableObserver
class ExampleClass: Fragment {
fun names() {
val observable: Observable<Int> = Observable.just(1)
val disposable: Disposable = methodReferencable(Function { observable.subscribeWith(it) })
}
@Throws(Exception::class)
internal fun methodReferencable(func: Function<DisposableObserver<Int>, DisposableObserver<Int>>): DisposableObserver<Int> {
return func.apply(object : DisposableObserver<Int>() {
override fun onNext(integer: Int) {
}
override fun onError(e: Throwable) {
}
override fun onComplete() {
}
})
}
}
"""
).indented()
)
.run()
.expectClean()
}
@Test fun kotlinExtensionFunctionNotConfigured() {
lint()
.files(
*jars(),
LIFECYCLE_OWNER,
RX_KOTLIN,
FRAGMENT,
kotlin(
"""
package foo
import io.reactivex.rxjava3.core.Observable
import io.reactivex.rxjava3.observers.DisposableObserver
import io.reactivex.rxjava3.kotlin.subscribeBy
import androidx.fragment.app.Fragment
class ExampleClass : Fragment() {
fun names() {
val obs = Observable.just(1, 2, 3, 4)
obs.subscribeBy { }
}
}
"""
).indented()
)
.run()
.expectClean()
}
@Test fun kotlinExtensionFunctionNotHandled() {
lint()
.files(
*jars(),
propertiesFile(kotlinExtensionFunctions = "io.reactivex.rxjava3.kotlin.subscribers#subscribeBy"),
LIFECYCLE_OWNER,
RX_KOTLIN,
FRAGMENT,
kotlin(
"""
package foo
import io.reactivex.rxjava3.core.Observable
import io.reactivex.rxjava3.observers.DisposableObserver
import io.reactivex.rxjava3.kotlin.subscribeBy
import androidx.fragment.app.Fragment
class ExampleClass : Fragment() {
fun names() {
val obs = Observable.just(1, 2, 3, 4)
obs.subscribeBy { }
}
}
"""
).indented()
)
.run()
.expect(
"""src/foo/ExampleClass.kt:10: Error: ${AutoDisposeDetector.LINT_DESCRIPTION} [AutoDispose]
| obs.subscribeBy { }
| ~~~~~~~~~~~~~~~~~~~
|1 errors, 0 warnings""".trimMargin()
)
}
@Test fun subscribeWithCapturedNonDisposableType() {
lint()
.files(
*jars(),
LIFECYCLE_OWNER,
FRAGMENT,
java(
"""
package foo;
import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.observers.DisposableObserver;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.core.Observer;
import androidx.fragment.app.Fragment;
class ExampleClass extends Fragment {
void names() {
Observable<Integer> obs = Observable.just(1, 2, 3, 4);
Observer<Integer> disposable = obs.subscribeWith(new Observer<Integer>() {
@Override
public void onSubscribe(Disposable d) {
}
@Override
public void onNext(Integer integer) {
}
@Override
public void onError(Throwable e) {}
@Override
public void onComplete() {}
});
}
}
"""
).indented()
)
.run()
.expect(
"""src/foo/ExampleClass.java:11: Error: ${AutoDisposeDetector.LINT_DESCRIPTION} [AutoDispose]
| Observer<Integer> disposable = obs.subscribeWith(new Observer<Integer>() {
| ^
|1 errors, 0 warnings""".trimMargin()
)
}
@Test fun subscribeWithCapturedDisposable() {
val propertiesFile = lenientPropertiesFile()
lint()
.files(
*jars(),
propertiesFile,
LIFECYCLE_OWNER,
FRAGMENT,
java(
"""
package foo;
import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.observers.DisposableObserver;
import io.reactivex.rxjava3.disposables.Disposable;
import androidx.fragment.app.Fragment;
class ExampleClass extends Fragment {
void names() {
Observable<Integer> obs = Observable.just(1, 2, 3, 4);
Disposable disposable = obs.subscribeWith(new DisposableObserver<Integer>() {
@Override
public void onNext(Integer integer) {
}
@Override
public void onError(Throwable e) {}
@Override
public void onComplete() {}
});
}
}
"""
).indented()
)
.run()
.expectClean()
}
@Test fun withScope_withScopeProvider_missingAutoDispose_shouldError() {
lint()
.files(
*jars(),
SCOPE_PROVIDER,
AUTODISPOSE_CONTEXT,
WITH_SCOPE_PROVIDER,
kotlin(
"""
package foo
import io.reactivex.rxjava3.core.Observable
import autodispose2.ScopeProvider
import autodispose2.autoDispose
import autodispose2.withScope
class ExampleClass {
lateinit var scopeProvider: ScopeProvider
fun names() {
val observable = Observable.just(1)
withScope(scopeProvider) {
observable.subscribe()
}
}
}
"""
).indented()
)
.allowCompilationErrors() // Until AGP 7.1.0 https://groups.google.com/g/lint-dev/c/BigCO8sMhKU
.run()
.expectErrorCount(1)
}
@Test fun withScope_withCompletable_missingAutoDispose_shouldError() {
lint()
.files(
*jars(),
AUTODISPOSE_CONTEXT,
WITH_SCOPE_COMPLETABLE,
kotlin(
"""
package foo
import io.reactivex.rxjava3.core.Completable
import io.reactivex.rxjava3.core.Observable
import autodispose2.withScope
class ExampleClass {
fun names() {
val observable = Observable.just(1)
withScope(Completable.complete()) {
observable.subscribe()
}
}
}
"""
).indented()
)
.allowCompilationErrors() // Until AGP 7.1.0 https://groups.google.com/g/lint-dev/c/BigCO8sMhKU
.run()
.expectErrorCount(1)
}
@Test fun withScope_withScopeProvider_expectClean() {
lint()
.files(
*jars(),
SCOPE_PROVIDER,
AUTODISPOSE_CONTEXT,
WITH_SCOPE_PROVIDER,
kotlin(
"""
package foo
import io.reactivex.rxjava3.core.Observable
import autodispose2.ScopeProvider
import autodispose2.autoDispose
import autodispose2.withScope
class ExampleClass {
lateinit var scopeProvider: ScopeProvider
fun names() {
val observable = Observable.just(1)
withScope(scopeProvider) {
observable.autoDispose().subscribe()
}
}
}
"""
).indented()
)
.allowCompilationErrors() // Until AGP 7.1.0 https://groups.google.com/g/lint-dev/c/BigCO8sMhKU
.run()
.expectClean()
}
@Test fun withScope_withCompletable_expectClean() {
lint()
.files(
*jars(),
AUTODISPOSE_CONTEXT,
WITH_SCOPE_COMPLETABLE,
kotlin(
"""
package foo
import io.reactivex.rxjava3.core.Completable
import autodispose2.autoDispose
import autodispose2.withScope
class ExampleClass {
fun names() {
val observable = Observable.just(1)
withScope(Completable.complete()) {
observable.autoDispose().subscribe()
}
}
}
"""
).indented()
)
.allowCompilationErrors() // Until AGP 7.1.0 https://groups.google.com/g/lint-dev/c/BigCO8sMhKU
.run()
.expectClean()
}
private fun jars(): Array<TestFile> {
val classLoader = AutoDisposeDetector::class.java.classLoader
return arrayOf(
LibraryReferenceTestFile(
File(classLoader.getResource("rxjava-3.1.0.jar")!!.toURI()),
),
LibraryReferenceTestFile(
File(classLoader.getResource("autodispose-2.0.0.jar")!!.toURI())
)
)
}
override fun getDetector(): Detector {
return AutoDisposeDetector()
}
override fun getIssues(): List<Issue> {
return listOf(AutoDisposeDetector.ISSUE)
}
}
| apache-2.0 | cf5198dbdfa140f2f5ab036966654e42 | 27.541518 | 150 | 0.563392 | 5.135646 | false | false | false | false |
zhengjiong/ZJ_KotlinStudy | src/main/kotlin/com/zj/example/kotlin/basicsknowledge/29.CompanionObjectExample伴生对象.kt | 1 | 1220 | package com.zj.example.kotlin.basicsknowledge
/**
* 伴生对象
* Created by zhengjiong
* date: 2017/9/16 17:13
*/
fun main(vararg args: String) {
//minOf是包级函数
val a = minOf(1, 2)
var l = Latitude.ofDouble(1.0)
var l2 = Latitude.ofLatitude(l)
println(l)//1.0
println(l2)//1.0
println(Latitude.TAG)//Latitude
}
/**
* 构造函数设置成private后, 外部就不能在通过Latitude()的方式实例化对象
* companion object 就是伴生对象, 可以对象中的方法都相当于是java中的
* 静态(static)方法和静态(static)对象, 如果想在java中调用伴生对象中的方法需要加注
* 解@JvmStatic(用于方法), @JvmField(用于对象)
*/
class Latitude private constructor(val value: Double) {
/**
* 每个类都可以有一个伴生对象
* 伴生对象的成员全局只有一份,类似java的静态成员
*/
companion object {
@JvmStatic
fun ofDouble(d: Double): Latitude = Latitude(d)
fun ofLatitude(latitude: Latitude) = Latitude(latitude.value)
@JvmField
val TAG: String = "Latitude"
}
override fun toString(): String {
return value.toString()
}
} | mit | dfd50ae0479da0e0cd62a63e1f2db778 | 19.702128 | 69 | 0.645062 | 3.125402 | false | false | false | false |
owntracks/android | project/app/src/gms/java/org/owntracks/android/ui/welcome/PlayFragment.kt | 1 | 3605 | package org.owntracks.android.ui.welcome
import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.activityViewModels
import androidx.fragment.app.viewModels
import com.google.android.gms.common.ConnectionResult
import com.google.android.gms.common.GoogleApiAvailability
import com.google.android.material.snackbar.Snackbar
import dagger.hilt.android.AndroidEntryPoint
import org.owntracks.android.R
import org.owntracks.android.databinding.UiWelcomePlayBinding
import javax.inject.Inject
@AndroidEntryPoint
class PlayFragment @Inject constructor() : WelcomeFragment() {
private val viewModel: WelcomeViewModel by activityViewModels()
private val playFragmentViewModel: PlayFragmentViewModel by viewModels()
private lateinit var binding: UiWelcomePlayBinding
private val googleAPI = GoogleApiAvailability.getInstance()
override fun shouldBeDisplayed(context: Context): Boolean =
googleAPI.isGooglePlayServicesAvailable(context) != ConnectionResult.SUCCESS
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?,
): View? {
binding = UiWelcomePlayBinding.inflate(inflater, container, false)
binding.vm = playFragmentViewModel
binding.lifecycleOwner = this.viewLifecycleOwner
binding.recover.setOnClickListener {
requestFix()
}
return binding.root
}
fun onPlayServicesResolutionResult() {
checkGooglePlayservicesIsAvailable()
}
fun requestFix() {
val result = googleAPI.isGooglePlayServicesAvailable(requireContext())
if (!googleAPI.showErrorDialogFragment(
requireActivity(),
result,
PLAY_SERVICES_RESOLUTION_REQUEST
)
) {
Snackbar.make(
binding.root,
getString(R.string.play_services_not_available),
Snackbar.LENGTH_SHORT
).show()
}
checkGooglePlayservicesIsAvailable()
}
private fun checkGooglePlayservicesIsAvailable() {
val nextEnabled =
when (val result = googleAPI.isGooglePlayServicesAvailable(requireContext())) {
ConnectionResult.SUCCESS -> {
playFragmentViewModel.setPlayServicesAvailable(getString(R.string.play_services_now_available))
true
}
ConnectionResult.SERVICE_VERSION_UPDATE_REQUIRED, ConnectionResult.SERVICE_UPDATING -> {
playFragmentViewModel.setPlayServicesNotAvailable(
true,
getString(R.string.play_services_update_required)
)
false
}
else -> {
playFragmentViewModel.setPlayServicesNotAvailable(
googleAPI.isUserResolvableError(
result
),
getString(R.string.play_services_not_available)
)
false
}
}
if (nextEnabled) {
viewModel.setWelcomeCanProceed()
} else {
viewModel.setWelcomeCannotProceed()
}
}
override fun onResume() {
super.onResume()
checkGooglePlayservicesIsAvailable()
}
companion object {
const val PLAY_SERVICES_RESOLUTION_REQUEST = 1
}
}
| epl-1.0 | 89394abc3fe29cc9975aa3fe0f240171 | 34 | 115 | 0.635229 | 5.786517 | false | false | false | false |
authzee/kotlin-guice | kotlin-guice/src/jmh/kotlin/dev/misfitlabs/kotlinguice4/benchmarks/KotlinStandardInjectorBenchmark.kt | 1 | 2986 | /*
* Copyright (C) 2017 John Leacox
* Copyright (C) 2017 Brian van de Boogaard
*
* 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 dev.misfitlabs.kotlinguice4.benchmarks
import com.google.inject.AbstractModule
import com.google.inject.Guice
import com.google.inject.Key
import com.google.inject.TypeLiteral
import java.util.concurrent.TimeUnit
import org.openjdk.jmh.annotations.Benchmark
import org.openjdk.jmh.annotations.BenchmarkMode
import org.openjdk.jmh.annotations.CompilerControl
import org.openjdk.jmh.annotations.Fork
import org.openjdk.jmh.annotations.Measurement
import org.openjdk.jmh.annotations.Mode
import org.openjdk.jmh.annotations.OutputTimeUnit
import org.openjdk.jmh.annotations.Scope
import org.openjdk.jmh.annotations.State
import org.openjdk.jmh.annotations.Warmup
/**
* Benchmarks showing the performance of Guice bindings from Kotlin without using the kotlin-guice
* library extensions.
*
* @author John Leacox
*/
@Fork(1)
@Warmup(iterations = 10)
@Measurement(iterations = 10)
@State(Scope.Benchmark)
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.MILLISECONDS)
@CompilerControl(CompilerControl.Mode.DONT_INLINE)
open class KotlinStandardInjectorBenchmark {
@Benchmark fun getSimpleInstance() {
val injector = Guice.createInjector(object : AbstractModule() {
override fun configure() {
bind(Simple::class.java).to(SimpleImpl::class.java)
}
})
val instance = injector.getInstance(Simple::class.java)
instance.value()
}
@Benchmark fun getComplexIterableInstance() {
val injector = Guice.createInjector(object : AbstractModule() {
override fun configure() {
bind(object : TypeLiteral<Complex<Iterable<String>>>() {})
.to(object : TypeLiteral<ComplexImpl<Iterable<String>>>() {})
}
})
val instance = injector
.getInstance(Key.get(object : TypeLiteral<Complex<Iterable<String>>>() {}))
instance.value()
}
@Benchmark fun getComplexStringInstance() {
val injector = Guice.createInjector(object : AbstractModule() {
override fun configure() {
bind(object : TypeLiteral<Complex<String>>() {}).to(StringComplexImpl::class.java)
}
})
val instance = injector.getInstance(Key.get(object : TypeLiteral<Complex<String>>() {}))
instance.value()
}
}
| apache-2.0 | 719185ea5aadf5fb0b59a8fcfdae738b | 34.547619 | 98 | 0.703282 | 4.410635 | false | false | false | false |
christophpickl/gadsu | src/main/kotlin/at/cpickl/gadsu/client/view/detail/tab_tcm2.kt | 1 | 4704 | package at.cpickl.gadsu.client.view.detail
import at.cpickl.gadsu.client.Client
import at.cpickl.gadsu.client.xprops.model.XPropEnum
import at.cpickl.gadsu.development.debugColor
import at.cpickl.gadsu.tcm.model.XProps
import at.cpickl.gadsu.view.LiveSearchField
import at.cpickl.gadsu.view.ViewNames
import at.cpickl.gadsu.view.components.ExpandCollapseListener
import at.cpickl.gadsu.view.components.ExpandCollapsePanel
import at.cpickl.gadsu.view.components.panels.GridPanel
import at.cpickl.gadsu.view.components.panels.fillAll
import at.cpickl.gadsu.view.language.Labels
import at.cpickl.gadsu.view.swing.scrolled
import at.cpickl.gadsu.view.tree.TreeSearcher
import at.cpickl.gadsu.view.tree.buildTree
import com.github.christophpickl.kpotpourri.common.logging.LOG
import java.awt.BorderLayout
import java.awt.Color
import java.awt.GridBagConstraints
import javax.swing.BoxLayout
import javax.swing.JButton
import javax.swing.JLabel
import javax.swing.JPanel
class ClientTabTcm2(
initialClient: Client
) : DefaultClientTab(
tabTitle = Labels.Tabs.ClientTcm,
type = ClientTabType.TCM,
scrolled = false
) {
private val container = JPanel().apply {
layout = BorderLayout()
}
private val xpropEnums = listOf(
listOf(XProps.Hungry, XProps.BodyConception),
listOf(XProps.ChiStatus, XProps.Digestion, XProps.Temperature),
listOf(XProps.Impression, XProps.Liquid, XProps.Menstruation, XProps.Sleep)
)
private val viewPanel = TcmViewPanel(xpropEnums)
private val editPanel = TcmEditPanel(xpropEnums)
init {
container.debugColor = Color.RED
c.fillAll()
add(container)
viewPanel.initClient(initialClient)
editPanel.initClient(initialClient)
changeContentTo(editPanel)
editPanel.btnFinishEdit.addActionListener {
changeContentTo(viewPanel)
}
viewPanel.btnStartEdit.addActionListener {
changeContentTo(editPanel)
}
}
override fun isModified(client: Client): Boolean {
// TODO implement me
return false
}
override fun updateFields(client: Client) {
// TODO implement me
}
private fun changeContentTo(panel: JPanel) {
container.removeAll()
container.add(panel, BorderLayout.CENTER)
container.revalidate()
container.repaint()
}
}
private class TcmViewPanel(xpropEnums: List<List<XPropEnum>>) : GridPanel() {
// TODO buttons same width
val btnStartEdit = JButton("Bearbeiten")
init {
add(btnStartEdit)
c.gridy++
c.fillAll()
add(JPanel().apply {
layout = BoxLayout(this, BoxLayout.Y_AXIS)
xpropEnums.forEach {
add(JLabel(it[0].label))
// go through all, and check if client has selected => render label (with header); and note
}
})
}
fun initClient(client: Client) {
println("initClient(client=$client)")
}
}
typealias XPropEnums = List<List<XPropEnum>>
private class TcmEditPanel(xPropEnums: XPropEnums) : GridPanel(), ExpandCollapseListener {
private val log = LOG {}
private val searchField = LiveSearchField(ViewNames.Client.InputTcmSearchField)
val btnFinishEdit = JButton("Fertig")
private val trees = xPropEnums.map { buildTree(it) }
init {
TreeSearcher(searchField, trees) // will work async
debugColor = Color.GREEN
// TODO tree.initSelected
c.weightx = 0.0
add(btnFinishEdit)
c.gridx++
c.fill = GridBagConstraints.HORIZONTAL
c.weightx = 1.0
add(searchField.asComponent())
c.gridx++
c.weightx = 0.0
add(ExpandCollapsePanel(this))
c.gridx = 0
c.gridy++
c.gridwidth = 3
c.fillAll()
add(GridPanel().apply {
c.anchor = GridBagConstraints.NORTH
c.weightx = 0.3
c.weighty = 1.0
c.fill = GridBagConstraints.BOTH
trees.forEach { tree ->
add(tree.scrolled())
c.gridx++
}
})
}
override fun onExpand() {
log.trace { "onExpand()" }
trees.forEach { tree ->
tree.expandAll()
}
}
override fun onCollapse() {
log.trace { "onCollapse()" }
trees.forEach { tree ->
tree.collapseAll()
}
}
fun initClient(client: Client) {
log.trace { "initClient(client)" }
trees.forEach { tree ->
tree.initSelected(client.cprops.map { it.clientValue }.flatten().toSet())
}
}
}
| apache-2.0 | acc7e8fad432ef86e660ab9486ee64f8 | 26.670588 | 107 | 0.639668 | 4.111888 | false | false | false | false |
vanniktech/Emoji | emoji/src/androidMain/kotlin/com/vanniktech/emoji/EmojiTextViews.kt | 1 | 1438 | /*
* Copyright (C) 2016 - Niklas Baudy, Ruben Gees, Mario Đanić and 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.
*/
@file:JvmName("EmojiTextViews")
package com.vanniktech.emoji
import android.util.AttributeSet
import android.widget.TextView
import androidx.annotation.Px
import androidx.annotation.StyleableRes
@Px fun TextView.init(
attrs: AttributeSet?,
@StyleableRes styleable: IntArray,
@StyleableRes emojiSizeAttr: Int,
): Float {
if (!isInEditMode) {
EmojiManager.verifyInstalled()
}
val fontMetrics = paint.fontMetrics
val defaultEmojiSize = fontMetrics.descent - fontMetrics.ascent
val emojiSize: Float = if (attrs == null) {
defaultEmojiSize
} else {
val a = context.obtainStyledAttributes(attrs, styleable)
try {
a.getDimension(emojiSizeAttr, defaultEmojiSize)
} finally {
a.recycle()
}
}
text = text // Reassign.
return emojiSize
}
| apache-2.0 | 83745c193fdb1ca216d3a4b9602fe5f3 | 28.306122 | 78 | 0.731198 | 4.27381 | false | false | false | false |
eugeis/ee | ee-system/src/main/kotlin/ee/system/SocketService.kt | 1 | 426 | package ee.system
open class SocketService : SocketServiceBase {
companion object {
val EMPTY = SocketServiceBase.EMPTY
}
constructor(elName: String = "", category: String = "", dependsOn: MutableList<Service> = arrayListOf(),
dependsOnMe: MutableList<Service> = arrayListOf(), host: String = "", port: Int = 0) : super(elName, category,
dependsOn, dependsOnMe, host, port) {
}
}
| apache-2.0 | 2686e61cda340f253815d7b47808562e | 25.625 | 118 | 0.65493 | 4.26 | false | false | false | false |
DevCharly/kotlin-ant-dsl | src/main/kotlin/com/devcharly/kotlin/ant/util/packagenamemapper.kt | 1 | 2032 | /*
* Copyright 2016 Karl Tauber
*
* 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.devcharly.kotlin.ant
import org.apache.tools.ant.util.PackageNameMapper
/******************************************************************************
DO NOT EDIT - this file was generated
******************************************************************************/
interface IPackageNameMapperNested {
fun packagemapper(
handledirsep: Boolean? = null,
casesensitive: Boolean? = null,
from: String? = null,
to: String? = null)
{
_addPackageNameMapper(PackageNameMapper().apply {
_init(handledirsep, casesensitive, from, to)
})
}
fun _addPackageNameMapper(value: PackageNameMapper)
}
fun IGlobPatternMapperNested.packagemapper(
handledirsep: Boolean? = null,
casesensitive: Boolean? = null,
from: String? = null,
to: String? = null)
{
_addGlobPatternMapper(PackageNameMapper().apply {
_init(handledirsep, casesensitive, from, to)
})
}
fun IFileNameMapperNested.packagemapper(
handledirsep: Boolean? = null,
casesensitive: Boolean? = null,
from: String? = null,
to: String? = null)
{
_addFileNameMapper(PackageNameMapper().apply {
_init(handledirsep, casesensitive, from, to)
})
}
fun PackageNameMapper._init(
handledirsep: Boolean?,
casesensitive: Boolean?,
from: String?,
to: String?)
{
if (handledirsep != null)
setHandleDirSep(handledirsep)
if (casesensitive != null)
setCaseSensitive(casesensitive)
if (from != null)
setFrom(from)
if (to != null)
setTo(to)
}
| apache-2.0 | fde01cf7d5e45174f6f05c8faa5f2555 | 25.736842 | 79 | 0.673228 | 3.89272 | false | false | false | false |
prengifo/VEF-Exchange-Android-App | mobile/src/main/java/melquelolea/vefexchange/data/CoinBaseApi.kt | 1 | 2027 | package melquelolea.vefexchange.data
import android.content.Context
import com.google.gson.JsonObject
import melquelolea.vefexchange.R
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.http.GET
import rx.Observable
/**
* Created by Patrick Rengifo on 11/29/16.
* Definition of the Api to get the data from the exchange
*/
internal object CoinBaseApi {
internal interface ApiInterface {
@GET("prices/spot_rate")
fun bitcoinUSD(): Observable<JsonObject>
}
private var adapter: ApiInterface? = null
fun getClient(context: Context): ApiInterface {
if (adapter == null) {
// Log
val logging = HttpLoggingInterceptor()
// set your desired log level
logging.level = HttpLoggingInterceptor.Level.BASIC
// OkHttpClient
val httpClient = OkHttpClient.Builder()
httpClient.addInterceptor { chain ->
val original = chain.request()
// Customize the request
val request = original.newBuilder()
.header("X-Device", "Android")
.build()
// Customize or return the response
chain.proceed(request)
}
// add logging as last interceptor
httpClient.addInterceptor(logging)
val client = httpClient.build()
val restAdapter = Retrofit.Builder()
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.baseUrl(context.getString(R.string.coinbase_endpoint))
.client(client)
.build()
adapter = restAdapter.create(ApiInterface::class.java)
}
return adapter!!
}
}
| mit | 895e522c11e9bff835700c28124fa86d | 29.253731 | 77 | 0.619635 | 5.292428 | false | false | false | false |
MakinGiants/todayhistory | app/src/main/kotlin/com/makingiants/todayhistory/screens/today/TodayActivity.kt | 1 | 3416 | package com.makingiants.todayhistory.screens.today
import android.os.Bundle
import android.support.v4.widget.SwipeRefreshLayout
import android.support.v7.widget.DefaultItemAnimator
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.Toolbar
import android.view.View
import com.makingiants.today.api.repository.history.pojo.Event
import com.makingiants.todayhistory.R
import com.makingiants.todayhistory.TodayApp
import com.makingiants.todayhistory.utils.SpacesItemDecoration
import com.makingiants.todayhistory.utils.base.BaseActivityView
import com.makingiants.todayhistory.utils.refresh_layout.ScrollEnabler
import com.squareup.picasso.Picasso
import kotlinx.android.synthetic.main.today_activity.*
import javax.inject.Inject
class TodayActivity : BaseActivityView(), TodayView, SwipeRefreshLayout.OnRefreshListener, ScrollEnabler {
@Inject lateinit var presenter: TodayPresenter
val todayAdapter: TodayAdapter by lazy { TodayAdapter(Picasso.with(applicationContext)) }
//<editor-fold desc="Activity">
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.today_activity)
setSupportActionBar(toolbar as Toolbar)
(application as TodayApp).applicationComponent.inject(this)
presenter.attach(this)
}
override fun onDestroy() {
super.onDestroy()
presenter.unAttach()
swipeRefreshLayout.setScrollEnabler(null)
swipeRefreshLayout.setOnRefreshListener(null)
}
//</editor-fold>
//<editor-fold desc="TodayView">
override fun initViews() {
recyclerView.apply {
adapter = todayAdapter
layoutManager = LinearLayoutManager(applicationContext)
itemAnimator = DefaultItemAnimator()
addItemDecoration(SpacesItemDecoration(16))
}
swipeRefreshLayout.apply {
setOnRefreshListener(this@TodayActivity)
setScrollEnabler(this@TodayActivity)
setColorSchemeColors(R.color.colorAccent, R.color.colorPrimary)
}
}
override fun showEvents(events: List<Event>) {
recyclerView.visibility = View.VISIBLE
todayAdapter.setEvents(events)
}
override fun hideEvents() = recyclerView.setVisibility(View.GONE)
override fun showEmptyViewProgress() = progressView.setVisibility(View.VISIBLE)
override fun dismissEmptyViewProgress() = progressView.setVisibility(View.GONE)
override fun showReloadProgress() = swipeRefreshLayout.setRefreshing(true)
override fun dismissReloadProgress() = swipeRefreshLayout.setRefreshing(false)
override fun showErrorView(title: String, message: String) {
errorTitleView.text = title
errorMessageTextView.text = message
errorView.visibility = View.VISIBLE
}
override fun hideErrorView() = errorView.setVisibility(View.GONE)
override fun showErrorToast(message: String) = showToast(message)
override fun showEmptyView() = emptyView.setVisibility(View.VISIBLE)
override fun hideEmptyView() = emptyView.setVisibility(View.GONE)
override fun showErrorDialog(throwable: Throwable) = super.showError(throwable)
//</editor-fold>
//<editor-fold desc="SwipeRefreshLayout.OnRefreshListener">
override fun onRefresh() = presenter.onRefresh()
//</editor-fold>
//<editor-fold desc="ScrollEnabler">
override fun canScrollUp(): Boolean =
recyclerView.visibility === View.VISIBLE && recyclerView.canScrollVertically(-1)
//</editor-fold>
}
| mit | 7be6d3eb2542ee9d48c3c5a016ca3f13 | 32.821782 | 106 | 0.78103 | 4.764296 | false | false | false | false |
ngageoint/mage-android | mage/src/main/java/mil/nga/giat/mage/form/view/MapViewContent.kt | 1 | 8127 | package mil.nga.giat.mage.form.view
import android.content.res.Configuration
import android.graphics.Color
import android.os.Bundle
import androidx.compose.runtime.*
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalLifecycleOwner
import androidx.compose.ui.viewinterop.AndroidView
import androidx.core.content.res.ResourcesCompat
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.preference.PreferenceManager
import com.bumptech.glide.Glide
import com.google.android.gms.maps.CameraUpdateFactory
import com.google.android.gms.maps.MapView
import com.google.android.gms.maps.model.*
import com.google.maps.android.ktx.*
import kotlinx.coroutines.launch
import mil.nga.geopackage.map.geom.GoogleMapShapeConverter
import mil.nga.giat.mage.R
import mil.nga.giat.mage.form.FormState
import mil.nga.giat.mage.form.field.FieldValue
import mil.nga.giat.mage.glide.target.MarkerTarget
import mil.nga.giat.mage.map.annotation.MapAnnotation
import mil.nga.giat.mage.map.annotation.ShapeStyle
import mil.nga.giat.mage.observation.ObservationLocation
import mil.nga.sf.GeometryType
import mil.nga.sf.util.GeometryUtils
data class MapState(val center: LatLng?, val zoom: Float?)
@Composable
fun MapViewContent(
map: MapView,
mapState: MapState,
formState: FormState?,
location: ObservationLocation
) {
val context = LocalContext.current
var mapInitialized by remember(map) { mutableStateOf(false) }
val primaryFieldState = formState?.fields?.find { it.definition.name == formState.definition.primaryMapField }
val primary = (primaryFieldState?.answer as? FieldValue.Text)?.text
val secondaryFieldState = formState?.fields?.find { it.definition.name == formState.definition.secondaryMapField }
val secondary = (secondaryFieldState?.answer as? FieldValue.Text)?.text
LaunchedEffect(map, mapInitialized) {
if (!mapInitialized) {
val googleMap = map.awaitMap()
googleMap.uiSettings.isMapToolbarEnabled = false
if (mapState.center != null && mapState.zoom != null) {
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(mapState.center, mapState.zoom))
}
val preferences = PreferenceManager.getDefaultSharedPreferences(context)
googleMap.mapType = preferences.getInt(context.getString(R.string.baseLayerKey), context.resources.getInteger(R.integer.baseLayerDefaultValue))
val dayNightMode: Int = context.resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK
if (dayNightMode == Configuration.UI_MODE_NIGHT_NO) {
googleMap.setMapStyle(null)
} else {
googleMap.setMapStyle(MapStyleOptions.loadRawResourceStyle(context, R.raw.map_theme_night))
}
mapInitialized = true
}
}
val scope = rememberCoroutineScope()
AndroidView({ map }) { mapView ->
scope.launch {
val googleMap = mapView.awaitMap()
googleMap.clear()
if (location.geometry.geometryType == GeometryType.POINT) {
val centroid = GeometryUtils.getCentroid(location.geometry)
val point = LatLng(centroid.y, centroid.x)
val marker = googleMap.addMarker {
position(point)
visible(false)
}
marker?.tag = formState?.id
if (formState != null) {
Glide.with(context)
.asBitmap()
.load(MapAnnotation.fromObservationProperties(formState.id ?: 0, location.geometry, location.time, location.accuracy, formState.eventId, formState.definition.id, primary, secondary, context))
.error(R.drawable.default_marker)
.into(MarkerTarget(context, marker, 32, 32))
}
if (!location.provider.equals(ObservationLocation.MANUAL_PROVIDER, true) && location.accuracy != null) {
googleMap.addCircle {
fillColor(ResourcesCompat.getColor(context.resources, R.color.accuracy_circle_fill, null))
strokeColor(ResourcesCompat.getColor(context.resources, R.color.accuracy_circle_stroke, null))
strokeWidth(2f)
center(point)
radius(location.accuracy.toDouble())
}
}
} else {
val shape = GoogleMapShapeConverter().toShape(location.geometry).shape
val style = ShapeStyle.fromForm(formState, context)
if (shape is PolylineOptions) {
googleMap.addPolyline {
addAll(shape.points)
width(style.strokeWidth)
color(style.strokeColor)
}
} else if (shape is PolygonOptions) {
googleMap.addPolygon {
addAll(shape.points)
for (hole in shape.holes) {
addHole(hole)
}
strokeWidth(style.strokeWidth)
strokeColor(style.strokeColor)
fillColor(style.fillColor)
}
}
}
googleMap.animateCamera(location.getCameraUpdate(mapView, true, 1.0f / 6))
}
}
}
@Composable
fun MapViewContent(
map: MapView,
location: ObservationLocation
) {
val context = LocalContext.current
var mapInitialized by remember(map) { mutableStateOf(false) }
LaunchedEffect(map, mapInitialized) {
if (!mapInitialized) {
val googleMap = map.awaitMap()
googleMap.uiSettings.isMapToolbarEnabled = false
val preferences = PreferenceManager.getDefaultSharedPreferences(context)
googleMap.mapType = preferences.getInt(context.getString(R.string.baseLayerKey), context.resources.getInteger(R.integer.baseLayerDefaultValue))
val dayNightMode: Int = context.resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK
if (dayNightMode == Configuration.UI_MODE_NIGHT_NO) {
googleMap.setMapStyle(null)
} else {
googleMap.setMapStyle(MapStyleOptions.loadRawResourceStyle(context, R.raw.map_theme_night))
}
mapInitialized = true
}
}
val scope = rememberCoroutineScope()
AndroidView({ map }) { mapView ->
scope.launch {
val googleMap = mapView.awaitMap()
googleMap.clear()
if (location.geometry.geometryType == GeometryType.POINT) {
val centroid = GeometryUtils.getCentroid(location.geometry)
val point = LatLng(centroid.y, centroid.x)
googleMap.addMarker {
position(point)
val color: Int = Color.parseColor("#1E88E5")
val hsv = FloatArray(3)
Color.colorToHSV(color, hsv)
icon(BitmapDescriptorFactory.defaultMarker(hsv[0]))
}
} else {
val shape = GoogleMapShapeConverter().toShape(location.geometry).shape
if (shape is PolylineOptions) {
googleMap.addPolyline {
addAll(shape.points)
}
} else if (shape is PolygonOptions) {
googleMap.addPolygon {
addAll(shape.points)
for (hole in shape.holes) {
addHole(hole)
}
}
}
}
googleMap.moveCamera(location.getCameraUpdate(mapView))
}
}
}
@Composable
fun rememberMapViewWithLifecycle(): MapView {
val context = LocalContext.current
val mapView = remember {
MapView(context).apply {
id = R.id.map
}
}
// Makes MapView follow the lifecycle of this composable
val lifecycleObserver = rememberMapLifecycleObserver(mapView)
val lifecycle = LocalLifecycleOwner.current.lifecycle
DisposableEffect(lifecycle) {
lifecycle.addObserver(lifecycleObserver)
onDispose {
lifecycle.removeObserver(lifecycleObserver)
}
}
return mapView
}
@Composable
private fun rememberMapLifecycleObserver(mapView: MapView): LifecycleEventObserver =
remember(mapView) {
LifecycleEventObserver { _, event ->
when (event) {
Lifecycle.Event.ON_CREATE -> mapView.onCreate(Bundle())
Lifecycle.Event.ON_START -> mapView.onStart()
Lifecycle.Event.ON_RESUME -> mapView.onResume()
Lifecycle.Event.ON_PAUSE -> mapView.onPause()
Lifecycle.Event.ON_STOP -> mapView.onStop()
Lifecycle.Event.ON_DESTROY -> mapView.onDestroy()
else -> throw IllegalStateException()
}
}
} | apache-2.0 | 55c7c62c0c98c96369700b3142e1a400 | 33.88412 | 203 | 0.69263 | 4.492537 | false | false | false | false |
MakinGiants/todayhistory | app/src/main/kotlin/com/makingiants/todayhistory/utils/DateManager.kt | 1 | 1068 | package com.makingiants.todayhistory.utils
import android.os.Parcel
import android.os.Parcelable
import java.util.*
open class DateManager : Parcelable {
internal var mCalendar: Calendar
constructor() {
mCalendar = Calendar.getInstance()
}
open fun getTodayDay(): Int = mCalendar.get(Calendar.DAY_OF_MONTH)
open fun getTodayMonth(): Int = mCalendar.get(Calendar.MONTH)
//<editor-fold desc="Parcelable">
override fun describeContents(): Int {
return 0
}
override fun writeToParcel(dest: Parcel, flags: Int) {
dest.writeSerializable(this.mCalendar)
}
protected constructor(`in`: Parcel) {
this.mCalendar = `in`.readSerializable() as Calendar
}
companion object {
val CREATOR: Parcelable.Creator<DateManager> = object : Parcelable.Creator<DateManager> {
override fun createFromParcel(source: Parcel): DateManager {
return com.makingiants.todayhistory.utils.DateManager(source)
}
override fun newArray(size: Int): Array<out DateManager?> = arrayOfNulls(size)
}
}
//</editor-fold>
}
| mit | 915fdb4a959f22d75c5b52cf98125ea9 | 25.04878 | 93 | 0.713483 | 4.238095 | false | false | false | false |
Bombe/Sone | src/main/kotlin/net/pterodactylus/sone/text/SoneMentionDetector.kt | 1 | 2907 | /**
* Sone - SoneMentionDetector.kt - Copyright © 2019–2020 David ‘Bombe’ Roden
*
* 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 net.pterodactylus.sone.text
import com.google.common.eventbus.*
import net.pterodactylus.sone.core.event.*
import net.pterodactylus.sone.data.*
import net.pterodactylus.sone.database.*
import net.pterodactylus.sone.utils.*
import javax.inject.*
/**
* Listens to [NewPostFoundEvent]s and [NewPostReplyFoundEvent], parses the
* texts and emits a [MentionOfLocalSoneFoundEvent] if a [SoneTextParser]
* finds a [SonePart] that points to a local [Sone].
*/
class SoneMentionDetector @Inject constructor(private val eventBus: EventBus, private val soneTextParser: SoneTextParser, private val postReplyProvider: PostReplyProvider) {
@Subscribe
fun onNewPost(newPostFoundEvent: NewPostFoundEvent) {
newPostFoundEvent.post.let { post ->
post.sone.isLocal.onFalse {
if (post.text.hasLinksToLocalSones()) {
mentionedPosts += post
eventBus.post(MentionOfLocalSoneFoundEvent(post))
}
}
}
}
@Subscribe
fun onNewPostReply(event: NewPostReplyFoundEvent) {
event.postReply.let { postReply ->
postReply.sone.isLocal.onFalse {
if (postReply.text.hasLinksToLocalSones()) {
postReply.post
.also { mentionedPosts += it }
.let(::MentionOfLocalSoneFoundEvent)
?.also(eventBus::post)
}
}
}
}
@Subscribe
fun onPostRemoved(event: PostRemovedEvent) {
unmentionPost(event.post)
}
@Subscribe
fun onPostMarkedKnown(event: MarkPostKnownEvent) {
unmentionPost(event.post)
}
@Subscribe
fun onReplyRemoved(event: PostReplyRemovedEvent) {
event.postReply.post.let {
if ((!it.text.hasLinksToLocalSones() || it.isKnown) && (it.replies.filterNot { it == event.postReply }.none { it.text.hasLinksToLocalSones() && !it.isKnown })) {
unmentionPost(it)
}
}
}
private fun unmentionPost(post: Post) {
if (post in mentionedPosts) {
eventBus.post(MentionOfLocalSoneRemovedEvent(post))
mentionedPosts -= post
}
}
private val mentionedPosts = mutableSetOf<Post>()
private fun String.hasLinksToLocalSones() = soneTextParser.parse(this, null)
.filterIsInstance<SonePart>()
.any { it.sone.isLocal }
private val Post.replies get() = postReplyProvider.getReplies(id)
}
| gpl-3.0 | 634454706cbe1d80e7cec96c75f4c1ca | 29.851064 | 173 | 0.733103 | 3.69898 | false | false | false | false |
vhromada/Catalog-Spring | src/test/kotlin/cz/vhromada/catalog/web/common/SongUtils.kt | 1 | 1647 | package cz.vhromada.catalog.web.common
import cz.vhromada.catalog.entity.Song
import cz.vhromada.catalog.web.fo.SongFO
import org.assertj.core.api.SoftAssertions.assertSoftly
/**
* A class represents utility class for songs.
*
* @author Vladimir Hromada
*/
object SongUtils {
/**
* Returns FO for song.
*
* @return FO for song
*/
fun getSongFO(): SongFO {
return SongFO(id = CatalogUtils.ID,
name = CatalogUtils.NAME,
length = TimeUtils.getTimeFO(),
note = CatalogUtils.NOTE,
position = CatalogUtils.POSITION)
}
/**
* Returns song.
*
* @return song
*/
fun getSong(): Song {
return Song(id = CatalogUtils.ID,
name = CatalogUtils.NAME,
length = CatalogUtils.LENGTH,
note = CatalogUtils.NOTE,
position = CatalogUtils.POSITION)
}
/**
* Asserts song deep equals.
*
* @param expected expected FO for song
* @param actual actual song
*/
fun assertSongDeepEquals(expected: SongFO?, actual: Song?) {
assertSoftly {
it.assertThat(expected).isNotNull
it.assertThat(actual).isNotNull
}
assertSoftly {
it.assertThat(actual!!.id).isEqualTo(expected!!.id)
it.assertThat(actual.name).isEqualTo(expected.name)
TimeUtils.assertTimeDeepEquals(expected.length, actual.length)
it.assertThat(actual.note).isEqualTo(expected.note)
it.assertThat(actual.position).isEqualTo(expected.position)
}
}
}
| mit | 03981d8c969b1000df7ccf149a971d15 | 26.45 | 74 | 0.590771 | 4.600559 | false | false | false | false |
halawata13/ArtichForAndroid | app/src/main/java/net/halawata/artich/model/config/QiitaTagList.kt | 2 | 986 | package net.halawata.artich.model.config
import net.halawata.artich.entity.QiitaTag
import net.halawata.artich.model.Log
import org.json.JSONArray
import org.json.JSONException
class QiitaTagList {
fun parse(content: String, selectedList: ArrayList<String>): ArrayList<QiitaTag>? {
try {
val list = ArrayList<QiitaTag>()
val items = JSONArray(content)
for (i in 0 until (items).length()) {
val row = items.getJSONObject(i)
val title = row.getString("id") ?: break
val selected = selectedList.contains(title)
list.add(QiitaTag(
id = i.toLong(),
title = title,
selected = selected
))
}
list.sortBy { item -> item.title }
return list
} catch (ex: JSONException) {
Log.e(ex.message)
return null
}
}
}
| mit | 6b8d6c4eb8d3768fa333eb15a2600ddd | 25.648649 | 87 | 0.528398 | 4.650943 | false | false | false | false |
mallowigi/a-file-icon-idea | common/src/main/java/com/mallowigi/icons/patchers/AbstractIconPatcher.kt | 1 | 5080 | /*
* The MIT License (MIT)
*
* Copyright (c) 2015-2022 Elior "Mallowigi" Boukhobza
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.mallowigi.icons.patchers
import com.intellij.openapi.util.IconPathPatcher
import com.mallowigi.config.AtomFileIconsConfig
import org.jetbrains.annotations.NonNls
import java.net.URL
/** Base class for [IconPathPatcher]s. */
abstract class AbstractIconPatcher : IconPathPatcher() {
/** The string to append to the final path. */
protected abstract val pathToAppend: @NonNls String
/** The string to remove from the original path. */
protected abstract val pathToRemove: @NonNls String
/** Whether the patcher should be enabled or not. */
var enabled: Boolean = false
/** Singleton instance. */
var instance: AtomFileIconsConfig? = AtomFileIconsConfig.instance
get() {
if (field == null) field = AtomFileIconsConfig.instance
return field
}
private set
/**
* Get the plugin context class loader if an icon needs to be patched
*
* @param path the icon path
* @param originalClassLoader the original class loader
* @return the plugin class loader if the icon needs to be patched, or the original class loader
*/
override fun getContextClassLoader(path: String, originalClassLoader: ClassLoader?): ClassLoader? {
val classLoader = javaClass.classLoader
if (!CL_CACHE.containsKey(path)) CL_CACHE[path] = originalClassLoader
val cachedClassLoader = CL_CACHE[path]
return if (enabled) classLoader else cachedClassLoader
}
/**
* Patch the icon path if there is an icon available
*
* @param path the path to patch
* @param classLoader the classloader of the icon
* @return the patched path to the plugin icon, or the original path if the icon patcher is disabled
*/
override fun patchPath(path: String, classLoader: ClassLoader?): String? {
if (instance == null) return null
val patchedPath = getPatchedPath(path)
return if (!enabled) null else patchedPath
}
/** Check whether a png version of a resource exists. */
private fun getPNG(path: String): URL? {
val replacement = SVG.replace(getReplacement(path), ".png") // NON-NLS
return javaClass.getResource("/$replacement")
}
/**
* Returns the patched path by taking the original path and appending the path to append, and converting to svg
*
* @param path
* @return
*/
@Suppress("kotlin:S1871", "HardCodedStringLiteral")
private fun getPatchedPath(path: String): String? = when {
!enabled -> null
CACHE.containsKey(path) -> CACHE[path]
// First try the svg version of the resource
getSVG(path) != null -> {
CACHE[path] = getReplacement(path)
CACHE[path]
}
// Then try the png version
getPNG(path) != null -> {
CACHE[path] = getReplacement(path)
CACHE[path]
}
else -> null
}
/**
* Replace the path by using the pathToAppend and pathToRemove
*
* @param path
* @return
*/
private fun getReplacement(path: String): String {
val finalPath: String = when {
path.contains(".gif") -> GIF.replace(path, ".svg")
else -> path.replace(".png", ".svg")
}
return (pathToAppend + finalPath.replace(pathToRemove, "")).replace("//", "/") // don't ask
}
/** Check whether a svg version of a resource exists. */
private fun getSVG(path: String): URL? {
val svgFile = PNG.replace(getReplacement(path), ".svg") // NON-NLS
return javaClass.getResource("/$svgFile")
}
companion object {
private val CACHE: MutableMap<String, String> = HashMap(100)
private val CL_CACHE: MutableMap<String, ClassLoader?> = HashMap(100)
private val PNG = ".png".toRegex(RegexOption.LITERAL)
private val SVG = ".svg".toRegex(RegexOption.LITERAL)
private val GIF = ".gif".toRegex(RegexOption.LITERAL)
/** Clear all caches. */
@JvmStatic
fun clearCache() {
CACHE.clear()
CL_CACHE.clear()
}
}
}
| mit | 6778f6340f8adeae3971aa8c8cf397a1 | 34.034483 | 113 | 0.686811 | 4.312394 | false | false | false | false |
ze-pequeno/okhttp | okhttp/src/jvmMain/kotlin/okhttp3/internal/publicsuffix/PublicSuffixDatabase.kt | 3 | 11764 | /*
* Copyright (C) 2017 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package okhttp3.internal.publicsuffix
import java.io.IOException
import java.io.InterruptedIOException
import java.net.IDN
import java.util.concurrent.CountDownLatch
import java.util.concurrent.atomic.AtomicBoolean
import okhttp3.internal.and
import okhttp3.internal.platform.Platform
import okio.GzipSource
import okio.buffer
import okio.source
/**
* A database of public suffixes provided by [publicsuffix.org][publicsuffix_org].
*
* [publicsuffix_org]: https://publicsuffix.org/
*/
class PublicSuffixDatabase {
/** True after we've attempted to read the list for the first time. */
private val listRead = AtomicBoolean(false)
/** Used for concurrent threads reading the list for the first time. */
private val readCompleteLatch = CountDownLatch(1)
// The lists are held as a large array of UTF-8 bytes. This is to avoid allocating lots of strings
// that will likely never be used. Each rule is separated by '\n'. Please see the
// PublicSuffixListGenerator class for how these lists are generated.
// Guarded by this.
private lateinit var publicSuffixListBytes: ByteArray
private lateinit var publicSuffixExceptionListBytes: ByteArray
/**
* Returns the effective top-level domain plus one (eTLD+1) by referencing the public suffix list.
* Returns null if the domain is a public suffix or a private address.
*
* Here are some examples:
*
* ```java
* assertEquals("google.com", getEffectiveTldPlusOne("google.com"));
* assertEquals("google.com", getEffectiveTldPlusOne("www.google.com"));
* assertNull(getEffectiveTldPlusOne("com"));
* assertNull(getEffectiveTldPlusOne("localhost"));
* assertNull(getEffectiveTldPlusOne("mymacbook"));
* ```
*
* @param domain A canonicalized domain. An International Domain Name (IDN) should be punycode
* encoded.
*/
fun getEffectiveTldPlusOne(domain: String): String? {
// We use UTF-8 in the list so we need to convert to Unicode.
val unicodeDomain = IDN.toUnicode(domain)
val domainLabels = splitDomain(unicodeDomain)
val rule = findMatchingRule(domainLabels)
if (domainLabels.size == rule.size && rule[0][0] != EXCEPTION_MARKER) {
return null // The domain is a public suffix.
}
val firstLabelOffset = if (rule[0][0] == EXCEPTION_MARKER) {
// Exception rules hold the effective TLD plus one.
domainLabels.size - rule.size
} else {
// Otherwise the rule is for a public suffix, so we must take one more label.
domainLabels.size - (rule.size + 1)
}
return splitDomain(domain).asSequence().drop(firstLabelOffset).joinToString(".")
}
private fun splitDomain(domain: String): List<String> {
val domainLabels = domain.split('.')
if (domainLabels.last() == "") {
// allow for domain name trailing dot
return domainLabels.dropLast(1)
}
return domainLabels
}
private fun findMatchingRule(domainLabels: List<String>): List<String> {
if (!listRead.get() && listRead.compareAndSet(false, true)) {
readTheListUninterruptibly()
} else {
try {
readCompleteLatch.await()
} catch (_: InterruptedException) {
Thread.currentThread().interrupt() // Retain interrupted status.
}
}
check(::publicSuffixListBytes.isInitialized) {
"Unable to load $PUBLIC_SUFFIX_RESOURCE resource from the classpath."
}
// Break apart the domain into UTF-8 labels, i.e. foo.bar.com turns into [foo, bar, com].
val domainLabelsUtf8Bytes = Array(domainLabels.size) { i -> domainLabels[i].toByteArray() }
// Start by looking for exact matches. We start at the leftmost label. For example, foo.bar.com
// will look like: [foo, bar, com], [bar, com], [com]. The longest matching rule wins.
var exactMatch: String? = null
for (i in domainLabelsUtf8Bytes.indices) {
val rule = publicSuffixListBytes.binarySearch(domainLabelsUtf8Bytes, i)
if (rule != null) {
exactMatch = rule
break
}
}
// In theory, wildcard rules are not restricted to having the wildcard in the leftmost position.
// In practice, wildcards are always in the leftmost position. For now, this implementation
// cheats and does not attempt every possible permutation. Instead, it only considers wildcards
// in the leftmost position. We assert this fact when we generate the public suffix file. If
// this assertion ever fails we'll need to refactor this implementation.
var wildcardMatch: String? = null
if (domainLabelsUtf8Bytes.size > 1) {
val labelsWithWildcard = domainLabelsUtf8Bytes.clone()
for (labelIndex in 0 until labelsWithWildcard.size - 1) {
labelsWithWildcard[labelIndex] = WILDCARD_LABEL
val rule = publicSuffixListBytes.binarySearch(labelsWithWildcard, labelIndex)
if (rule != null) {
wildcardMatch = rule
break
}
}
}
// Exception rules only apply to wildcard rules, so only try it if we matched a wildcard.
var exception: String? = null
if (wildcardMatch != null) {
for (labelIndex in 0 until domainLabelsUtf8Bytes.size - 1) {
val rule = publicSuffixExceptionListBytes.binarySearch(
domainLabelsUtf8Bytes, labelIndex)
if (rule != null) {
exception = rule
break
}
}
}
if (exception != null) {
// Signal we've identified an exception rule.
exception = "!$exception"
return exception.split('.')
} else if (exactMatch == null && wildcardMatch == null) {
return PREVAILING_RULE
}
val exactRuleLabels = exactMatch?.split('.') ?: listOf()
val wildcardRuleLabels = wildcardMatch?.split('.') ?: listOf()
return if (exactRuleLabels.size > wildcardRuleLabels.size) {
exactRuleLabels
} else {
wildcardRuleLabels
}
}
/**
* Reads the public suffix list treating the operation as uninterruptible. We always want to read
* the list otherwise we'll be left in a bad state. If the thread was interrupted prior to this
* operation, it will be re-interrupted after the list is read.
*/
private fun readTheListUninterruptibly() {
var interrupted = false
try {
while (true) {
try {
readTheList()
return
} catch (_: InterruptedIOException) {
Thread.interrupted() // Temporarily clear the interrupted state.
interrupted = true
} catch (e: IOException) {
Platform.get().log("Failed to read public suffix list", Platform.WARN, e)
return
}
}
} finally {
if (interrupted) {
Thread.currentThread().interrupt() // Retain interrupted status.
}
}
}
@Throws(IOException::class)
private fun readTheList() {
var publicSuffixListBytes: ByteArray?
var publicSuffixExceptionListBytes: ByteArray?
val resource =
PublicSuffixDatabase::class.java.getResourceAsStream(PUBLIC_SUFFIX_RESOURCE) ?: return
GzipSource(resource.source()).buffer().use { bufferedSource ->
val totalBytes = bufferedSource.readInt()
publicSuffixListBytes = bufferedSource.readByteArray(totalBytes.toLong())
val totalExceptionBytes = bufferedSource.readInt()
publicSuffixExceptionListBytes = bufferedSource.readByteArray(totalExceptionBytes.toLong())
}
synchronized(this) {
this.publicSuffixListBytes = publicSuffixListBytes!!
this.publicSuffixExceptionListBytes = publicSuffixExceptionListBytes!!
}
readCompleteLatch.countDown()
}
/** Visible for testing. */
fun setListBytes(
publicSuffixListBytes: ByteArray,
publicSuffixExceptionListBytes: ByteArray
) {
this.publicSuffixListBytes = publicSuffixListBytes
this.publicSuffixExceptionListBytes = publicSuffixExceptionListBytes
listRead.set(true)
readCompleteLatch.countDown()
}
companion object {
@JvmField
val PUBLIC_SUFFIX_RESOURCE = "${PublicSuffixDatabase::class.java.simpleName}.gz"
private val WILDCARD_LABEL = byteArrayOf('*'.code.toByte())
private val PREVAILING_RULE = listOf("*")
private const val EXCEPTION_MARKER = '!'
private val instance = PublicSuffixDatabase()
fun get(): PublicSuffixDatabase {
return instance
}
private fun ByteArray.binarySearch(
labels: Array<ByteArray>,
labelIndex: Int
): String? {
var low = 0
var high = size
var match: String? = null
while (low < high) {
var mid = (low + high) / 2
// Search for a '\n' that marks the start of a value. Don't go back past the start of the
// array.
while (mid > -1 && this[mid] != '\n'.code.toByte()) {
mid--
}
mid++
// Now look for the ending '\n'.
var end = 1
while (this[mid + end] != '\n'.code.toByte()) {
end++
}
val publicSuffixLength = mid + end - mid
// Compare the bytes. Note that the file stores UTF-8 encoded bytes, so we must compare the
// unsigned bytes.
var compareResult: Int
var currentLabelIndex = labelIndex
var currentLabelByteIndex = 0
var publicSuffixByteIndex = 0
var expectDot = false
while (true) {
val byte0: Int
if (expectDot) {
byte0 = '.'.code
expectDot = false
} else {
byte0 = labels[currentLabelIndex][currentLabelByteIndex] and 0xff
}
val byte1 = this[mid + publicSuffixByteIndex] and 0xff
compareResult = byte0 - byte1
if (compareResult != 0) break
publicSuffixByteIndex++
currentLabelByteIndex++
if (publicSuffixByteIndex == publicSuffixLength) break
if (labels[currentLabelIndex].size == currentLabelByteIndex) {
// We've exhausted our current label. Either there are more labels to compare, in which
// case we expect a dot as the next character. Otherwise, we've checked all our labels.
if (currentLabelIndex == labels.size - 1) {
break
} else {
currentLabelIndex++
currentLabelByteIndex = -1
expectDot = true
}
}
}
if (compareResult < 0) {
high = mid - 1
} else if (compareResult > 0) {
low = mid + end + 1
} else {
// We found a match, but are the lengths equal?
val publicSuffixBytesLeft = publicSuffixLength - publicSuffixByteIndex
var labelBytesLeft = labels[currentLabelIndex].size - currentLabelByteIndex
for (i in currentLabelIndex + 1 until labels.size) {
labelBytesLeft += labels[i].size
}
if (labelBytesLeft < publicSuffixBytesLeft) {
high = mid - 1
} else if (labelBytesLeft > publicSuffixBytesLeft) {
low = mid + end + 1
} else {
// Found a match.
match = String(this, mid, publicSuffixLength)
break
}
}
}
return match
}
}
}
| apache-2.0 | 9c0af937fbef93c36619fa053f65ee82 | 33.498534 | 100 | 0.652499 | 4.7056 | false | false | false | false |
AerisG222/maw_photos_android | MaWPhotos/src/main/java/us/mikeandwan/photos/ui/controls/categorylist/CategoryListViewModel.kt | 1 | 760 | package us.mikeandwan.photos.ui.controls.categorylist
import androidx.lifecycle.ViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import us.mikeandwan.photos.domain.models.PhotoCategory
import us.mikeandwan.photos.ui.toCategoryWithYearVisibility
class CategoryListViewModel: ViewModel() {
private val _categories = MutableStateFlow(emptyList<CategoryWithYearVisibility>())
val categories = _categories.asStateFlow()
private val _showYear = MutableStateFlow(false)
fun setCategories(items: List<PhotoCategory>) {
_categories.value = items.map { it.toCategoryWithYearVisibility(_showYear.value) }
}
fun setShowYear(doShow: Boolean) {
_showYear.value = doShow
}
} | mit | 187190d9bb189479b862c6a43a0c99c0 | 33.590909 | 90 | 0.778947 | 4.606061 | false | false | false | false |
AerisG222/maw_photos_android | MaWPhotos/src/main/java/us/mikeandwan/photos/ui/screens/photo/PhotoFragmentStateAdapter.kt | 1 | 841 | package us.mikeandwan.photos.ui.screens.photo
import android.os.Bundle
import androidx.fragment.app.Fragment
import androidx.viewpager2.adapter.FragmentStateAdapter
import us.mikeandwan.photos.domain.models.Photo
class PhotoFragmentStateAdapter(fragment: Fragment): FragmentStateAdapter(fragment) {
private var _photos = emptyList<Photo>()
override fun getItemCount(): Int {
return _photos.size
}
override fun createFragment(position: Int): Fragment {
val fragment = PhotoViewHolderFragment()
fragment.arguments = Bundle().apply {
val photo = _photos[position]
putString(PhotoViewHolderFragment.PHOTO_URL, photo.mdUrl)
}
return fragment
}
fun updatePhotoList(photos: List<Photo>) {
_photos = photos
notifyDataSetChanged()
}
} | mit | 59d0cc431d5d78ff6e70edf50f8fa557 | 26.16129 | 85 | 0.699168 | 4.751412 | false | false | false | false |
NordicSemiconductor/Android-nRF-Toolbox | profile_hrs/src/main/java/no/nordicsemi/android/hrs/view/LineChartView.kt | 1 | 7418 | /*
* Copyright (c) 2022, Nordic Semiconductor
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are
* permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list
* of conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its contributors may be
* used to endorse or promote products derived from this software without specific prior
* written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
* OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package no.nordicsemi.android.hrs.view
import android.content.Context
import android.graphics.Color
import android.graphics.DashPathEffect
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.compose.ui.viewinterop.AndroidView
import com.github.mikephil.charting.charts.LineChart
import com.github.mikephil.charting.components.XAxis
import com.github.mikephil.charting.data.Entry
import com.github.mikephil.charting.data.LineData
import com.github.mikephil.charting.data.LineDataSet
import com.github.mikephil.charting.interfaces.datasets.ILineDataSet
import no.nordicsemi.android.hrs.data.HRSData
private const val X_AXIS_ELEMENTS_COUNT = 40f
private const val AXIS_MIN = 0
private const val AXIS_MAX = 300
@Composable
internal fun LineChartView(state: HRSData, zoomIn: Boolean,) {
val items = state.heartRates.takeLast(X_AXIS_ELEMENTS_COUNT.toInt()).reversed()
val isSystemInDarkTheme = isSystemInDarkTheme()
AndroidView(
modifier = Modifier
.fillMaxWidth()
.height(300.dp),
factory = { createLineChartView(isSystemInDarkTheme, it, items, zoomIn) },
update = { updateData(items, it, zoomIn) }
)
}
internal fun createLineChartView(
isDarkTheme: Boolean,
context: Context,
points: List<Int>,
zoomIn: Boolean
): LineChart {
return LineChart(context).apply {
description.isEnabled = false
legend.isEnabled = false
setTouchEnabled(false)
setDrawGridBackground(false)
isDragEnabled = true
setScaleEnabled(false)
setPinchZoom(false)
if (isDarkTheme) {
setBackgroundColor(Color.TRANSPARENT)
xAxis.gridColor = Color.WHITE
xAxis.textColor = Color.WHITE
axisLeft.gridColor = Color.WHITE
axisLeft.textColor = Color.WHITE
} else {
setBackgroundColor(Color.WHITE)
xAxis.gridColor = Color.BLACK
xAxis.textColor = Color.BLACK
axisLeft.gridColor = Color.BLACK
axisLeft.textColor = Color.BLACK
}
xAxis.apply {
xAxis.enableGridDashedLine(10f, 10f, 0f)
axisMinimum = -X_AXIS_ELEMENTS_COUNT
axisMaximum = 0f
setAvoidFirstLastClipping(true)
position = XAxis.XAxisPosition.BOTTOM
}
axisLeft.apply {
enableGridDashedLine(10f, 10f, 0f)
axisMaximum = points.getMax(zoomIn)
axisMinimum = points.getMin(zoomIn)
}
axisRight.isEnabled = false
val entries = points.mapIndexed { i, v ->
Entry(-i.toFloat(), v.toFloat())
}.reversed()
// create a dataset and give it a type
if (data != null && data.dataSetCount > 0) {
val set1 = data!!.getDataSetByIndex(0) as LineDataSet
set1.values = entries
set1.notifyDataSetChanged()
data!!.notifyDataChanged()
notifyDataSetChanged()
} else {
val set1 = LineDataSet(entries, "DataSet 1")
set1.setDrawIcons(false)
set1.setDrawValues(false)
// draw dashed line
// draw dashed line
set1.enableDashedLine(10f, 5f, 0f)
// black lines and points
// black lines and points
if (isDarkTheme) {
set1.color = Color.WHITE
set1.setCircleColor(Color.WHITE)
} else {
set1.color = Color.BLACK
set1.setCircleColor(Color.BLACK)
}
// line thickness and point size
// line thickness and point size
set1.lineWidth = 1f
set1.circleRadius = 3f
// draw points as solid circles
// draw points as solid circles
set1.setDrawCircleHole(false)
// customize legend entry
// customize legend entry
set1.formLineWidth = 1f
set1.formLineDashEffect = DashPathEffect(floatArrayOf(10f, 5f), 0f)
set1.formSize = 15f
// text size of values
// text size of values
set1.valueTextSize = 9f
// draw selection line as dashed
// draw selection line as dashed
set1.enableDashedHighlightLine(10f, 5f, 0f)
val dataSets = ArrayList<ILineDataSet>()
dataSets.add(set1) // add the data sets
// create a data object with the data sets
val data = LineData(dataSets)
// set data
// set data
setData(data)
}
}
}
private fun updateData(points: List<Int>, chart: LineChart, zoomIn: Boolean) {
val entries = points.mapIndexed { i, v ->
Entry(-i.toFloat(), v.toFloat())
}.reversed()
with(chart) {
axisLeft.apply {
axisMaximum = points.getMax(zoomIn)
axisMinimum = points.getMin(zoomIn)
}
if (data != null && data.dataSetCount > 0) {
val set1 = data!!.getDataSetByIndex(0) as LineDataSet
set1.values = entries
set1.notifyDataSetChanged()
data!!.notifyDataChanged()
notifyDataSetChanged()
invalidate()
}
}
}
private fun List<Int>.getMin(zoomIn: Boolean): Float {
return if (zoomIn) {
minOrNull() ?: AXIS_MIN
} else {
AXIS_MIN
}.toFloat()
}
private fun List<Int>.getMax(zoomIn: Boolean): Float {
return if (zoomIn) {
maxOrNull() ?: AXIS_MAX
} else {
AXIS_MAX
}.toFloat()
}
| bsd-3-clause | 721e5de5fb12084577654ab313745ca2 | 31.393013 | 89 | 0.64303 | 4.604593 | false | false | false | false |
wuseal/JsonToKotlinClass | src/main/kotlin/wu/seal/jsontokotlin/interceptor/annotations/gson/AddGsonAnnotationInterceptor.kt | 1 | 1024 | package wu.seal.jsontokotlin.interceptor.annotations.gson
import wu.seal.jsontokotlin.model.classscodestruct.DataClass
import wu.seal.jsontokotlin.model.codeannotations.GsonPropertyAnnotationTemplate
import wu.seal.jsontokotlin.model.codeelements.KPropertyName
import wu.seal.jsontokotlin.interceptor.IKotlinClassInterceptor
import wu.seal.jsontokotlin.model.classscodestruct.KotlinClass
class AddGsonAnnotationInterceptor : IKotlinClassInterceptor<KotlinClass> {
override fun intercept(kotlinClass: KotlinClass): KotlinClass {
return if (kotlinClass is DataClass) {
val addGsonAnnotationProperties = kotlinClass.properties.map {
val camelCaseName = KPropertyName.makeLowerCamelCaseLegalName(it.originName)
it.copy(annotations = GsonPropertyAnnotationTemplate(it.originName).getAnnotations(), name = camelCaseName)
}
kotlinClass.copy(properties = addGsonAnnotationProperties)
} else {
kotlinClass
}
}
}
| gpl-3.0 | 9de6252e1af07850306eb98b153a1aba | 35.571429 | 123 | 0.757813 | 5.251282 | false | false | false | false |
alygin/intellij-rust | src/main/kotlin/org/rust/ide/annotator/fixes/AddMutableFix.kt | 2 | 2406 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.annotator.fixes
import com.intellij.codeInspection.LocalQuickFixAndIntentionActionOnPsiElement
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import org.rust.lang.core.psi.*
import org.rust.lang.core.psi.ext.RsNamedElement
import org.rust.lang.core.psi.ext.parentOfType
import org.rust.lang.core.psi.ext.typeElement
import org.rust.lang.core.types.declaration
class AddMutableFix(val binding: RsNamedElement) : LocalQuickFixAndIntentionActionOnPsiElement(binding) {
override fun getFamilyName(): String = "Make mutable"
override fun getText(): String = "Make `${binding.name}` mutable"
val mutable = true
override fun invoke(project: Project, file: PsiFile, editor: Editor?, startElement: PsiElement, endElement: PsiElement) {
updateMutable(project, binding, mutable)
}
companion object {
fun createIfCompatible(expr: RsExpr): AddMutableFix? {
val declaration = expr.declaration
return if (declaration is RsSelfParameter || declaration is RsPatBinding) {
AddMutableFix(declaration as RsNamedElement)
} else {
null
}
}
}
}
fun updateMutable(project: Project, binding: RsNamedElement, mutable: Boolean = true) {
when (binding) {
is RsPatBinding -> {
val tuple = binding.parentOfType<RsPatTup>()
val parameter = binding.parentOfType<RsValueParameter>()
if (tuple != null && parameter != null) {
return
}
val type = parameter?.typeReference?.typeElement
if (type is RsRefLikeType) {
val newParameterExpr = RsPsiFactory(project)
.createValueParameter(parameter.pat?.text!!, type.typeReference, mutable)
parameter.replace(newParameterExpr)
return
}
val newPatBinding = RsPsiFactory(project).createPatBinding(binding.identifier.text, mutable)
binding.replace(newPatBinding)
}
is RsSelfParameter -> {
val newSelf = RsPsiFactory(project).createSelf(true)
binding.replace(newSelf)
}
}
}
| mit | bad6cd1f9c8300ff2057d3a214d4dd26 | 36.59375 | 125 | 0.664589 | 4.812 | false | false | false | false |
alygin/intellij-rust | src/main/kotlin/org/rust/cargo/toolchain/Rustup.kt | 2 | 3004 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.cargo.toolchain
import com.intellij.execution.configurations.GeneralCommandLine
import com.intellij.execution.process.CapturingProcessHandler
import com.intellij.execution.process.ProcessOutput
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.openapi.vfs.VirtualFile
import org.rust.utils.GeneralCommandLine
import org.rust.utils.fullyRefreshDirectory
import org.rust.utils.seconds
import org.rust.utils.withWorkDirectory
import java.nio.file.Path
private val LOG = Logger.getInstance(Rustup::class.java)
class Rustup(
private val rustup: Path,
private val rustc: Path,
private val projectDirectory: Path
) {
sealed class DownloadResult {
class Ok(val library: VirtualFile) : DownloadResult()
class Err(val error: String) : DownloadResult()
}
fun downloadStdlib(): DownloadResult {
val downloadProcessOutput = GeneralCommandLine(rustup)
.withWorkDirectory(projectDirectory)
.withParameters("component", "add", "rust-src")
.exec()
return if (downloadProcessOutput.exitCode != 0) {
DownloadResult.Err("rustup failed: `${downloadProcessOutput.stderr}`")
} else {
val sources = getStdlibFromSysroot() ?: return DownloadResult.Err("Failed to find stdlib in sysroot")
fullyRefreshDirectory(sources)
DownloadResult.Ok(sources)
}
}
fun getStdlibFromSysroot(): VirtualFile? {
val sysroot = GeneralCommandLine(rustc)
.withCharset(Charsets.UTF_8)
.withWorkDirectory(projectDirectory)
.withParameters("--print", "sysroot")
.exec(5.seconds)
.stdout.trim()
val fs = LocalFileSystem.getInstance()
return fs.refreshAndFindFileByPath(FileUtil.join(sysroot, "lib/rustlib/src/rust/src"))
}
fun createRunCommandLine(channel: RustChannel, varargs: String): GeneralCommandLine =
if (channel.rustupArgument != null) {
GeneralCommandLine(rustup, "run", channel.rustupArgument, varargs)
} else {
GeneralCommandLine(rustup, "run", varargs)
}
private fun GeneralCommandLine.exec(timeoutInMilliseconds: Int? = null): ProcessOutput {
val handler = CapturingProcessHandler(this)
LOG.info("Executing `$commandLineString`")
val output = if (timeoutInMilliseconds != null)
handler.runProcess(timeoutInMilliseconds)
else
handler.runProcess()
if (output.exitCode != 0) {
LOG.warn("Failed to execute `$commandLineString`" +
"\ncode : ${output.exitCode}" +
"\nstdout:\n${output.stdout}" +
"\nstderr:\n${output.stderr}")
}
return output
}
}
| mit | 5221796e70d1cbcda508d68bd93636fd | 33.930233 | 113 | 0.669774 | 4.92459 | false | false | false | false |
JimSeker/ui | Material Design/SupportDesignDemo2_kt/app/src/main/java/edu/cs4730/supportdesigndemo2_kt/DataViewModel.kt | 1 | 1255 | package edu.cs4730.supportdesigndemo2_kt
import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.LiveData
/**
* this is class to hold data so even when the destroy view is called for the fragment
* the data can survive. The left and right fragment are creating their own instance of this object.
*/
class DataViewModel(application: Application) : AndroidViewModel(application) {
private val left: MutableLiveData<String>
private val right: MutableLiveData<String>
val dataLeft: LiveData<String>
get() = left
val dataRight: LiveData<String>
get() = right
val strLeft: String?
get() = left.value
val strRight: String?
get() = right.value
fun setStrLeft(item: String) {
left.value = item
}
fun setStrRight(item: String) {
right.value = item
}
fun appendStrRight(item: String) {
val prev = right.value
right.value = prev + "\n" + item
}
fun appendStrLeft(item: String) {
val prev = left.value
left.value = prev + "\n" + item
}
init {
left = MutableLiveData("left")
right = MutableLiveData("right")
}
} | apache-2.0 | fbdf1611acc2a582ac498ee2f5cafdae | 26.304348 | 102 | 0.659761 | 4.211409 | false | false | false | false |
dataloom/conductor-client | src/main/kotlin/com/openlattice/assembler/processors/DropMaterializedEntitySetProcessor.kt | 1 | 2897 | /*
* Copyright (C) 2019. OpenLattice, Inc.
*
* 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/>.
*
* You can contact the owner of the copyright at [email protected]
*
*
*/
package com.openlattice.assembler.processors
import com.hazelcast.core.Offloadable
import com.hazelcast.spi.impl.executionservice.ExecutionService
import com.kryptnostic.rhizome.hazelcast.processors.AbstractRhizomeEntryProcessor
import com.openlattice.assembler.AssemblerConnectionManager
import com.openlattice.assembler.AssemblerConnectionManagerDependent
import com.openlattice.assembler.EntitySetAssemblyKey
import com.openlattice.assembler.MaterializedEntitySet
@Deprecated("Use Transporter instead")
class DropMaterializedEntitySetProcessor
: AbstractRhizomeEntryProcessor<EntitySetAssemblyKey, MaterializedEntitySet, Void?>(),
AssemblerConnectionManagerDependent<DropMaterializedEntitySetProcessor>,
Offloadable {
@Transient
private var acm: AssemblerConnectionManager? = null
override fun process(entry: MutableMap.MutableEntry<EntitySetAssemblyKey, MaterializedEntitySet?>): Void? {
val entitySetAssemblyKey = entry.key
val materializedEntitySet = entry.value
if (materializedEntitySet == null) {
throw IllegalStateException("Encountered null materialized entity set while trying to drop materialized " +
"entity set for entity set ${entitySetAssemblyKey.entitySetId} in organization " +
"${entitySetAssemblyKey.organizationId}.")
} else {
acm?.dematerializeEntitySets(entitySetAssemblyKey.organizationId, setOf(entitySetAssemblyKey.entitySetId))
?: throw IllegalStateException(AssemblerConnectionManagerDependent.NOT_INITIALIZED)
entry.setValue(null)
}
return null
}
override fun getExecutorName(): String {
return ExecutionService.OFFLOADABLE_EXECUTOR
}
override fun init(acm: AssemblerConnectionManager): DropMaterializedEntitySetProcessor {
this.acm = acm
return this
}
override fun equals(other: Any?): Boolean {
return (other != null && other is DropMaterializedEntitySetProcessor)
}
override fun hashCode(): Int {
return super.hashCode()
}
} | gpl-3.0 | 04ed375cfb1f3b73afcce5f1a773c907 | 39.25 | 119 | 0.740766 | 5.325368 | false | false | false | false |
googlecreativelab/digital-wellbeing-experiments-toolkit | notifications/notifications-listener/app/src/main/java/com/digitalwellbeingexperiments/toolkit/notificationlistener/NotificationListener.kt | 1 | 3446 | // Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// 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.digitalwellbeingexperiments.toolkit.notificationlistener
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.service.notification.NotificationListenerService
import android.service.notification.StatusBarNotification
import android.util.Log
import androidx.localbroadcastmanager.content.LocalBroadcastManager
import com.google.gson.Gson
class NotificationListener : NotificationListenerService() {
companion object {
const val ACTION_REFRESH_UI = "REFRESH"
const val ACTION_CLEAR_DATA = "CLEAR"
const val KEY_NOTIFICATIONS = "key_notifications"
}
//Handles messages from UI (Activity) to background service
private val receiver: BroadcastReceiver = object: BroadcastReceiver(){
override fun onReceive(context: Context?, intent: Intent?) {
Log.w(TAG(), "onReceive() ${intent?.action}")
dataMap.clear()
sendUpdate()
}
}
private val dataMap = HashMap<String, NotificationItem>()
//when user switches ON in Settings
override fun onListenerConnected() {
Log.w(TAG(), "onListenerConnected()")
val currentNotifications = activeNotifications
.filter { sbn -> sbn.packageName != this.packageName }
.map {
createNotificationItem(it)
}.toTypedArray()
currentNotifications.forEach {
dataMap[it.sbnKey] = it
}
sendUpdate()
LocalBroadcastManager.getInstance(this).registerReceiver(receiver,
IntentFilter(ACTION_CLEAR_DATA)
)
}
//when user switches OFF in Settings
override fun onListenerDisconnected() {
Log.w(TAG(), "onListenerDisconnected()")
LocalBroadcastManager.getInstance(this).unregisterReceiver(receiver)
}
override fun onNotificationPosted(sbn: StatusBarNotification) {
if (this.packageName != sbn.packageName) {
Log.w(TAG(), "onNotificationPosted() ${sbn.key}")
val notificationItem = createNotificationItem(sbn)
dataMap[sbn.key] = notificationItem
sendUpdate()
}
}
private fun sendUpdate() {
val intent = Intent(ACTION_REFRESH_UI)
val dataList = dataMap.values.toList()
intent.putExtra(KEY_NOTIFICATIONS, Gson().toJson(dataList))
LocalBroadcastManager.getInstance(this).sendBroadcast(intent)
}
private fun createNotificationItem(sbn: StatusBarNotification): NotificationItem {
return NotificationItem(
sbn.key,
sbn.packageName,
title = "${sbn.getTitleBig()}\n${sbn.getTitle()}".trim(),
text = "${sbn.getText()}\n${sbn.getSubText()}".trim(),
postTime = sbn.postTime
)
}
}
| apache-2.0 | 97f2c30ea4ca75e22c0f00a610a4992e | 36.456522 | 86 | 0.678178 | 4.965418 | false | false | false | false |
Vavassor/Tusky | app/src/main/java/com/keylesspalace/tusky/fragment/preference/AccountPreferencesFragment.kt | 1 | 11163 | /* Copyright 2018 Conny Duck
*
* This file is a part of Tusky.
*
* 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.
*
* Tusky 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 Tusky; if not,
* see <http://www.gnu.org/licenses>. */
package com.keylesspalace.tusky.fragment.preference
import android.content.Intent
import android.graphics.drawable.Drawable
import android.os.Build
import android.os.Bundle
import com.google.android.material.snackbar.Snackbar
import androidx.preference.SwitchPreference
import androidx.preference.ListPreference
import androidx.preference.Preference
import androidx.preference.PreferenceFragmentCompat
import android.util.Log
import android.view.View
import com.keylesspalace.tusky.*
import com.keylesspalace.tusky.appstore.EventHub
import com.keylesspalace.tusky.appstore.PreferenceChangedEvent
import com.keylesspalace.tusky.db.AccountManager
import com.keylesspalace.tusky.di.Injectable
import com.keylesspalace.tusky.entity.Account
import com.keylesspalace.tusky.entity.Status
import com.keylesspalace.tusky.network.MastodonApi
import com.keylesspalace.tusky.util.ThemeUtils
import com.mikepenz.google_material_typeface_library.GoogleMaterial
import com.mikepenz.iconics.IconicsDrawable
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import javax.inject.Inject
class AccountPreferencesFragment : PreferenceFragmentCompat(),
Preference.OnPreferenceChangeListener, Preference.OnPreferenceClickListener,
Injectable {
@Inject
lateinit var accountManager: AccountManager
@Inject
lateinit var mastodonApi: MastodonApi
@Inject
lateinit var eventHub: EventHub
private lateinit var notificationPreference: Preference
private lateinit var tabPreference: Preference
private lateinit var mutedUsersPreference: Preference
private lateinit var blockedUsersPreference: Preference
private lateinit var defaultPostPrivacyPreference: ListPreference
private lateinit var defaultMediaSensitivityPreference: SwitchPreference
private lateinit var alwaysShowSensitiveMediaPreference: SwitchPreference
private lateinit var mediaPreviewEnabledPreference: SwitchPreference
private val iconSize by lazy {resources.getDimensionPixelSize(R.dimen.preference_icon_size)}
override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
addPreferencesFromResource(R.xml.account_preferences)
notificationPreference = findPreference("notificationPreference")
tabPreference = findPreference("tabPreference")
mutedUsersPreference = findPreference("mutedUsersPreference")
blockedUsersPreference = findPreference("blockedUsersPreference")
defaultPostPrivacyPreference = findPreference("defaultPostPrivacy") as ListPreference
defaultMediaSensitivityPreference = findPreference("defaultMediaSensitivity") as SwitchPreference
mediaPreviewEnabledPreference = findPreference("mediaPreviewEnabled") as SwitchPreference
alwaysShowSensitiveMediaPreference = findPreference("alwaysShowSensitiveMedia") as SwitchPreference
notificationPreference.icon = IconicsDrawable(notificationPreference.context, GoogleMaterial.Icon.gmd_notifications).sizePx(iconSize).color(ThemeUtils.getColor(notificationPreference.context, R.attr.toolbar_icon_tint))
mutedUsersPreference.icon = getTintedIcon(R.drawable.ic_mute_24dp)
blockedUsersPreference.icon = IconicsDrawable(blockedUsersPreference.context, GoogleMaterial.Icon.gmd_block).sizePx(iconSize).color(ThemeUtils.getColor(blockedUsersPreference.context, R.attr.toolbar_icon_tint))
notificationPreference.onPreferenceClickListener = this
tabPreference.onPreferenceClickListener = this
mutedUsersPreference.onPreferenceClickListener = this
blockedUsersPreference.onPreferenceClickListener = this
defaultPostPrivacyPreference.onPreferenceChangeListener = this
defaultMediaSensitivityPreference.onPreferenceChangeListener = this
mediaPreviewEnabledPreference.onPreferenceChangeListener = this
alwaysShowSensitiveMediaPreference.onPreferenceChangeListener = this
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
accountManager.activeAccount?.let {
defaultPostPrivacyPreference.value = it.defaultPostPrivacy.serverString()
defaultPostPrivacyPreference.icon = getIconForVisibility(it.defaultPostPrivacy)
defaultMediaSensitivityPreference.isChecked = it.defaultMediaSensitivity
defaultMediaSensitivityPreference.icon = getIconForSensitivity(it.defaultMediaSensitivity)
mediaPreviewEnabledPreference.isChecked = it.mediaPreviewEnabled
alwaysShowSensitiveMediaPreference.isChecked = it.alwaysShowSensitiveMedia
}
}
override fun onPreferenceChange(preference: Preference, newValue: Any): Boolean {
when(preference) {
defaultPostPrivacyPreference -> {
preference.icon = getIconForVisibility(Status.Visibility.byString(newValue as String))
syncWithServer(visibility = newValue)
}
defaultMediaSensitivityPreference -> {
preference.icon = getIconForSensitivity(newValue as Boolean)
syncWithServer(sensitive = newValue)
}
mediaPreviewEnabledPreference -> {
accountManager.activeAccount?.let {
it.mediaPreviewEnabled = newValue as Boolean
accountManager.saveAccount(it)
}
}
alwaysShowSensitiveMediaPreference -> {
accountManager.activeAccount?.let {
it.alwaysShowSensitiveMedia = newValue as Boolean
accountManager.saveAccount(it)
}
}
}
eventHub.dispatch(PreferenceChangedEvent(preference.key))
return true
}
override fun onPreferenceClick(preference: Preference): Boolean {
when(preference) {
notificationPreference -> {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val intent = Intent()
intent.action = "android.settings.APP_NOTIFICATION_SETTINGS"
intent.putExtra("android.provider.extra.APP_PACKAGE", BuildConfig.APPLICATION_ID)
startActivity(intent)
} else {
activity?.let {
val intent = PreferencesActivity.newIntent(it, PreferencesActivity.NOTIFICATION_PREFERENCES)
it.startActivity(intent)
it.overridePendingTransition(R.anim.slide_from_right, R.anim.slide_to_left)
}
}
return true
}
tabPreference -> {
val intent = Intent(context, TabPreferenceActivity::class.java)
activity?.startActivity(intent)
activity?.overridePendingTransition(R.anim.slide_from_right, R.anim.slide_to_left)
return true
}
mutedUsersPreference -> {
val intent = Intent(context, AccountListActivity::class.java)
intent.putExtra("type", AccountListActivity.Type.MUTES)
activity?.startActivity(intent)
activity?.overridePendingTransition(R.anim.slide_from_right, R.anim.slide_to_left)
return true
}
blockedUsersPreference -> {
val intent = Intent(context, AccountListActivity::class.java)
intent.putExtra("type", AccountListActivity.Type.BLOCKS)
activity?.startActivity(intent)
activity?.overridePendingTransition(R.anim.slide_from_right, R.anim.slide_to_left)
return true
}
else -> return false
}
}
private fun syncWithServer(visibility: String? = null, sensitive: Boolean? = null) {
mastodonApi.accountUpdateSource(visibility, sensitive)
.enqueue(object: Callback<Account>{
override fun onResponse(call: Call<Account>, response: Response<Account>) {
val account = response.body()
if(response.isSuccessful && account != null) {
accountManager.activeAccount?.let {
it.defaultPostPrivacy = account.source?.privacy ?: Status.Visibility.PUBLIC
it.defaultMediaSensitivity = account.source?.sensitive ?: false
accountManager.saveAccount(it)
}
} else {
Log.e("AccountPreferences", "failed updating settings on server")
showErrorSnackbar(visibility, sensitive)
}
}
override fun onFailure(call: Call<Account>, t: Throwable) {
Log.e("AccountPreferences", "failed updating settings on server", t)
showErrorSnackbar(visibility, sensitive)
}
})
}
private fun showErrorSnackbar(visibility: String?, sensitive: Boolean?) {
view?.let {view ->
Snackbar.make(view, R.string.pref_failed_to_sync, Snackbar.LENGTH_LONG)
.setAction(R.string.action_retry) { syncWithServer( visibility, sensitive)}
.show()
}
}
private fun getIconForVisibility(visibility: Status.Visibility): Drawable? {
val drawableId = when (visibility) {
Status.Visibility.PRIVATE -> R.drawable.ic_lock_outline_24dp
Status.Visibility.UNLISTED -> R.drawable.ic_lock_open_24dp
else -> R.drawable.ic_public_24dp
}
return getTintedIcon(drawableId)
}
private fun getIconForSensitivity(sensitive: Boolean): Drawable? {
val drawableId = if (sensitive) {
R.drawable.ic_hide_media_24dp
} else {
R.drawable.ic_eye_24dp
}
return getTintedIcon(drawableId)
}
private fun getTintedIcon(iconId: Int): Drawable? {
val drawable = context?.getDrawable(iconId)
ThemeUtils.setDrawableTint(context, drawable, R.attr.toolbar_icon_tint)
return drawable
}
companion object {
fun newInstance(): AccountPreferencesFragment {
return AccountPreferencesFragment()
}
}
}
| gpl-3.0 | 029062f70e6e3d06a6928949e6d4346e | 42.267442 | 226 | 0.675714 | 5.808012 | false | false | false | false |
SirWellington/alchemy-http | src/test/java/tech/sirwellington/alchemy/http/TestRequest.kt | 1 | 2496 | /*
* 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.http
import com.google.gson.JsonElement
import com.google.gson.JsonNull
import sir.wellington.alchemy.collections.maps.Maps
import tech.sirwellington.alchemy.annotations.access.Internal
import tech.sirwellington.alchemy.generator.AlchemyGenerator.Get.one
import tech.sirwellington.alchemy.generator.CollectionGenerators
import tech.sirwellington.alchemy.generator.StringGenerators
import java.net.URL
import java.util.Objects
/**
*
* @author SirWellington
*/
@Internal
internal data class TestRequest(override var queryParams: Map<String, String> = CollectionGenerators.mapOf(StringGenerators.alphabeticStrings(), StringGenerators.alphabeticStrings(), 6),
override var url: URL? = one(Generators.validUrls()),
override var body: JsonElement? = one(Generators.jsonElements()),
override var method: RequestMethod = Constants.DEFAULT_REQUEST_METHOD) : HttpRequest
{
override var requestHeaders: Map<String, String>? = CollectionGenerators.mapOf(StringGenerators.alphabeticStrings(),
StringGenerators.alphabeticStrings(),
20).toMap()
override fun hasBody(): Boolean
{
return body?.let { it != JsonNull.INSTANCE } ?: false
}
override fun hasQueryParams(): Boolean
{
return Maps.isEmpty(queryParams)
}
override fun equals(other: HttpRequest?): Boolean
{
return this == other as Any?
}
override fun hasMethod(): Boolean
{
return Objects.nonNull(method)
}
override fun equals(other: Any?): Boolean
{
val other = other as? HttpRequest ?: return false
return super.equals(other)
}
}
| apache-2.0 | 9f20b23393848b872a701dd6d978d9d0 | 34.642857 | 186 | 0.662525 | 5.040404 | false | false | false | false |
matkoniecz/StreetComplete | app/src/main/java/de/westnordost/streetcomplete/quests/traffic_signals_button/AddTrafficSignalsButton.kt | 1 | 1413 | package de.westnordost.streetcomplete.quests.traffic_signals_button
import de.westnordost.streetcomplete.R
import de.westnordost.streetcomplete.data.osm.osmquests.OsmFilterQuestType
import de.westnordost.streetcomplete.data.osm.edits.update_tags.StringMapChangesBuilder
import de.westnordost.streetcomplete.data.user.achievements.QuestTypeAchievement.PEDESTRIAN
import de.westnordost.streetcomplete.ktx.toYesNo
import de.westnordost.streetcomplete.quests.YesNoQuestAnswerFragment
class AddTrafficSignalsButton : OsmFilterQuestType<Boolean>() {
override val elementFilter = """
nodes with
crossing = traffic_signals
and highway ~ crossing|traffic_signals
and foot != no
and !button_operated
"""
override val commitMessage = "Add whether traffic signals have a button for pedestrians"
override val wikiLink = "Tag:highway=traffic_signals"
override val icon = R.drawable.ic_quest_traffic_lights
override val questTypeAchievements = listOf(PEDESTRIAN)
override fun getTitle(tags: Map<String, String>) = R.string.quest_traffic_signals_button_title
override fun createForm() = YesNoQuestAnswerFragment()
override fun applyAnswerTo(answer: Boolean, changes: StringMapChangesBuilder) {
changes.add("button_operated", answer.toYesNo())
}
override val defaultDisabledMessage = R.string.default_disabled_msg_boring
}
| gpl-3.0 | f3a0147ae27f4d5b51281043252c8d3b | 41.818182 | 98 | 0.771408 | 4.773649 | false | false | false | false |
matkoniecz/StreetComplete | app/src/main/java/de/westnordost/streetcomplete/data/elementfilter/filters/HasDateTagLessOrEqualThan.kt | 1 | 324 | package de.westnordost.streetcomplete.data.elementfilter.filters
import java.time.LocalDate
/** key <= date */
class HasDateTagLessOrEqualThan(key: String, dateFilter: DateFilter): CompareDateTagValue(key, dateFilter) {
override val operator = "<="
override fun compareTo(tagValue: LocalDate) = tagValue <= date
}
| gpl-3.0 | 08237cca26ed5d4db7f1bbabe1fb0254 | 35 | 108 | 0.762346 | 4.438356 | false | false | false | false |
tomatrocho/insapp-android | app/src/main/java/fr/insapp/insapp/activities/PostActivity.kt | 2 | 18046 | package fr.insapp.insapp.activities
import android.app.Activity
import android.content.Context
import android.content.DialogInterface
import android.content.Intent
import android.os.Bundle
import android.text.util.Linkify
import android.util.Log
import android.view.MenuItem
import android.view.View
import android.view.inputmethod.EditorInfo
import android.view.inputmethod.InputMethodManager
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import com.bumptech.glide.Glide
import com.bumptech.glide.RequestManager
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions.withCrossFade
import com.bumptech.glide.request.RequestOptions
import com.google.firebase.analytics.FirebaseAnalytics
import com.varunest.sparkbutton.SparkEventListener
import fr.insapp.insapp.R
import fr.insapp.insapp.adapters.CommentRecyclerViewAdapter
import fr.insapp.insapp.http.ServiceGenerator
import fr.insapp.insapp.models.*
import fr.insapp.insapp.utility.Utils
import kotlinx.android.synthetic.main.activity_post.*
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
/**
* Created by thomas on 12/11/2016.
*/
class PostActivity : AppCompatActivity() {
private lateinit var commentAdapter: CommentRecyclerViewAdapter
private lateinit var post: Post
private var association: Association? = null
private lateinit var requestManager: RequestManager
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
requestManager = Glide.with(this)
val user = Utils.user
// post
if (intent.getParcelableExtra<Post>("post") != null) {
// coming from navigation
this.post = intent.getParcelableExtra("post")
generateActivity()
// mark notification as seen
if (intent.getParcelableExtra<Notification>("notification") != null) {
val notification = intent.getParcelableExtra<Notification>("notification")
if (user != null) {
val call = ServiceGenerator.client.markNotificationAsSeen(user.id, notification.id)
call.enqueue(object : Callback<Notifications> {
override fun onResponse(call: Call<Notifications>, response: Response<Notifications>) {
if (!response.isSuccessful) {
Toast.makeText(this@PostActivity, TAG, Toast.LENGTH_LONG).show()
}
}
override fun onFailure(call: Call<Notifications>, t: Throwable) {
Toast.makeText(this@PostActivity, TAG, Toast.LENGTH_LONG).show()
}
})
} else {
Log.d(TAG, "")
}
}
} else {
// coming from notification
setContentView(R.layout.loading)
ServiceGenerator.client.getPostFromId(intent.getStringExtra("ID"))
.enqueue(object : Callback<Post> {
override fun onResponse(call: Call<Post>, response: Response<Post>) {
val result = response.body()
if (response.isSuccessful && result != null) {
post = result
generateActivity()
} else {
Toast.makeText(this@PostActivity, TAG, Toast.LENGTH_LONG).show()
}
}
override fun onFailure(call: Call<Post>, t: Throwable) {
Toast.makeText(this@PostActivity, R.string.check_internet_connection, Toast.LENGTH_LONG).show()
// Open the application
startActivity(Intent(this@PostActivity, MainActivity::class.java))
finish()
}
})
}
}
private fun generateActivity() {
setContentView(R.layout.activity_post)
// toolbar
setSupportActionBar(post_toolbar)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
val user = Utils.user
val bundle = Bundle()
bundle.putString(FirebaseAnalytics.Param.ITEM_ID, post.id)
bundle.putString(FirebaseAnalytics.Param.ITEM_NAME, post.title)
bundle.putString(FirebaseAnalytics.Param.CONTENT_TYPE, "Post")
bundle.putInt("favorites_count", post.likes.size)
bundle.putInt("comments_count", post.comments.size)
FirebaseAnalytics.getInstance(this).logEvent(FirebaseAnalytics.Event.VIEW_ITEM, bundle)
// hide image if necessary
if (post.image.isEmpty()) {
post_placeholder?.visibility = View.GONE
post_image?.visibility = View.GONE
}
// like button
user?.let {
post_like_button?.setChecked(post.isPostLikedBy(user.id))
}
post_like_counter?.text = post.likes.size.toString()
post_like_button?.setEventListener(object : SparkEventListener {
override fun onEvent(icon: ImageView, buttonState: Boolean) {
if (buttonState) {
post_like_counter?.text = (Integer.valueOf(post_like_counter?.text as String) + 1).toString()
if (user != null) {
val call = ServiceGenerator.client.likePost(post.id, user.id)
call.enqueue(object : Callback<PostInteraction> {
override fun onResponse(call: Call<PostInteraction>, response: Response<PostInteraction>) {
val results = response.body()
if (response.isSuccessful && results != null) {
post = results.post
} else {
Toast.makeText(this@PostActivity, TAG, Toast.LENGTH_LONG).show()
}
}
override fun onFailure(call: Call<PostInteraction>, t: Throwable) {
Toast.makeText(this@PostActivity, TAG, Toast.LENGTH_LONG).show()
}
})
} else {
Log.d(TAG, "Couldn't update the like status: user is null")
}
} else {
post_like_counter?.text = (Integer.valueOf(post_like_counter?.text as String) - 1).toString()
if (Integer.valueOf(post_like_counter?.text as String) < 0) {
post_like_counter?.text = "0"
}
if (user != null) {
val call = ServiceGenerator.client.dislikePost(post.id, user.id)
call.enqueue(object : Callback<PostInteraction> {
override fun onResponse(call: Call<PostInteraction>, response: Response<PostInteraction>) {
val result = response.body()
if (response.isSuccessful && result != null) {
post = result.post
} else {
Toast.makeText(this@PostActivity, TAG, Toast.LENGTH_LONG).show()
}
}
override fun onFailure(call: Call<PostInteraction>, t: Throwable) {
Toast.makeText(this@PostActivity, TAG, Toast.LENGTH_LONG).show()
}
})
} else {
Log.d(TAG, "Couldn't update the like status: user is null")
}
}
}
override fun onEventAnimationEnd(button: ImageView?, buttonState: Boolean) {}
override fun onEventAnimationStart(button: ImageView?, buttonState: Boolean) {}
})
val call = ServiceGenerator.client.getAssociationFromId(post.association)
call.enqueue(object : Callback<Association> {
override fun onResponse(call: Call<Association>, response: Response<Association>) {
if (response.isSuccessful) {
association = response.body()
requestManager
.load(ServiceGenerator.CDN_URL + association!!.profilePicture)
.apply(RequestOptions.circleCropTransform())
.transition(withCrossFade())
.into(post_association_avatar)
// listener
post_association_avatar?.setOnClickListener { startActivity(Intent(this@PostActivity, AssociationActivity::class.java).putExtra("association", association)) }
} else {
Toast.makeText(this@PostActivity, TAG, Toast.LENGTH_LONG).show()
}
}
override fun onFailure(call: Call<Association>, t: Throwable) {
Toast.makeText(this@PostActivity, TAG, Toast.LENGTH_LONG).show()
}
})
post_title?.text = post.title
post_text?.text = post.description
post_date?.text = Utils.displayedDate(post.date)
// view links contained in description
Linkify.addLinks(post_text, Linkify.ALL)
Utils.convertToLinkSpan(this@PostActivity, post_text)
// edit comment adapter
commentAdapter = CommentRecyclerViewAdapter(post.comments, requestManager)
commentAdapter.setOnCommentItemLongClickListener(PostCommentLongClickListener(this@PostActivity, post, commentAdapter))
comment_post_input.setupComponent()
comment_post_input.setOnEditorActionListener(TextView.OnEditorActionListener { textView, actionId, _ ->
if (actionId == EditorInfo.IME_ACTION_SEND) {
// hide keyboard
val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.hideSoftInputFromWindow(textView.windowToken, 0)
val content = comment_post_input.text.toString()
comment_post_input.text.clear()
if (content.isNotBlank()) {
user?.let {
val comment = Comment(null, user.id, content, null, comment_post_input.tags)
Log.d(TAG, comment.toString())
ServiceGenerator.client.commentPost(post.id, comment)
.enqueue(object : Callback<Post> {
override fun onResponse(call: Call<Post>, response: Response<Post>) {
if (response.isSuccessful) {
commentAdapter.addComment(comment)
comment_post_input.tags.clear()
Toast.makeText(this@PostActivity, resources.getText(R.string.write_comment_success), Toast.LENGTH_LONG).show()
} else {
Log.e(TAG, "Couldn't post comment: ${response.code()}")
Toast.makeText(this@PostActivity, TAG, Toast.LENGTH_LONG).show()
}
}
override fun onFailure(call: Call<Post>, t: Throwable) {
Log.e(TAG, "Couldn't post comment: ${t.message}")
Toast.makeText(this@PostActivity, TAG, Toast.LENGTH_LONG).show()
}
})
}
}
return@OnEditorActionListener true
}
false
})
// recycler view
recyclerview_comments_post.setHasFixedSize(true)
recyclerview_comments_post.isNestedScrollingEnabled = false
val layoutManager = LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)
recyclerview_comments_post.layoutManager = layoutManager
recyclerview_comments_post.adapter = commentAdapter
// retrieve the avatar of the user
val id = resources.getIdentifier(Utils.drawableProfileName(user?.promotion, user?.gender), "drawable", packageName)
requestManager
.load(id)
.transition(withCrossFade())
.apply(RequestOptions.circleCropTransform())
.into(comment_post_username_avatar)
// image
if (post.image.isNotEmpty()) {
post_placeholder?.setImageSize(post.imageSize)
requestManager
.load(ServiceGenerator.CDN_URL + post.image)
.transition(withCrossFade())
.into(post_image)
}
}
override fun finish() {
if (::post.isInitialized) {
val sendIntent = Intent()
sendIntent.putExtra("post", post)
setResult(Activity.RESULT_OK, sendIntent)
} else {
setResult(Activity.RESULT_CANCELED)
}
super.finish()
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
android.R.id.home -> {
if (isTaskRoot) {
startActivity(Intent(this@PostActivity, MainActivity::class.java))
} else {
finish()
}
return true
}
}
return super.onOptionsItemSelected(item)
}
companion object {
const val TAG = "PostActivity"
}
class PostCommentLongClickListener(
private val context: Context,
private val post: Post,
private val adapter: CommentRecyclerViewAdapter
): CommentRecyclerViewAdapter.OnCommentItemLongClickListener {
override fun onCommentItemLongClick(comment: Comment) {
val alertDialogBuilder = AlertDialog.Builder(context)
val user = Utils.user
// delete comment
if (user != null) {
if (user.id == comment.user) {
alertDialogBuilder
.setTitle(context.resources.getString(R.string.delete_comment_action))
.setMessage(R.string.delete_comment_are_you_sure)
.setCancelable(true)
.setPositiveButton(context.getString(R.string.positive_button)) { _: DialogInterface, _: Int ->
val call = ServiceGenerator.client.uncommentPost(post.id, comment.id!!)
call.enqueue(object : Callback<Post> {
override fun onResponse(call: Call<Post>, response: Response<Post>) {
val post = response.body()
if (response.isSuccessful && post != null) {
adapter.setComments(post.comments)
} else {
Toast.makeText(context, "PostCommentLongClickListener", Toast.LENGTH_LONG).show()
}
}
override fun onFailure(call: Call<Post>, t: Throwable) {
Toast.makeText(context, "PostCommentLongClickListener", Toast.LENGTH_LONG).show()
}
})
}
.setNegativeButton(context.getString(R.string.negative_button)) { dialogAlert: DialogInterface, _: Int ->
dialogAlert.cancel()
}
.create().show()
}
// report comment
else {
alertDialogBuilder
.setTitle(context.getString(R.string.report_comment_action))
.setMessage(R.string.report_comment_are_you_sure)
.setCancelable(true)
.setPositiveButton(context.getString(R.string.positive_button)) { _: DialogInterface, _: Int ->
val call = ServiceGenerator.client.reportComment(post.id, comment.id!!)
call.enqueue(object : Callback <Void> {
override fun onResponse(call: Call<Void>, response: Response<Void>) {
if (response.isSuccessful) {
Toast.makeText(context, context.getString(R.string.report_comment_success), Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(context, "PostCommentLongClickListener", Toast.LENGTH_LONG).show();
}
}
override fun onFailure(call: Call<Void>, t: Throwable) {
Toast.makeText(context, "PostCommentLongClickListener", Toast.LENGTH_LONG).show();
}
})
}
.setNegativeButton(context.getString(R.string.negative_button)) { dialogAlert: DialogInterface, _: Int ->
dialogAlert.cancel()
}
.create().show()
}
}
}
}
}
fun Post.isPostLikedBy(userID: String): Boolean {
for (idUser in likes)
if (idUser == userID) return true
return false
} | mit | fcdf9922e14e93588a0a4c67a25cf859 | 41.067599 | 178 | 0.532971 | 5.637613 | false | false | false | false |
songzhw/Hello-kotlin | AdvancedJ/src/main/kotlin/msg_queue/demo/HandlerDemo.kt | 1 | 1496 | package msg_queue.demo
import msg_queue.*
import kotlin.concurrent.thread
fun main1(args: Array<String>) {
val handler = object : Handler() {
override fun handleMessage(msg: Message) {
println("szw handler handleMesage(${msg.what})")
}
}
val msg = Message()
msg.what = 11
msg.obj = "test" //要是obj是Object类型, 这就会报错. 正确得是Any类型
handler.sendMessage(msg)
handler.sendMessageDelay(Message(), 1000)
handler.sendMessageDelay(Message(), 2000)
handler.sendMessageDelay(Message(), 4000)
// 省略了Looper.prepare()
println("01")
Looper.loop()
println("02") //=> 这一句永远就不执行了
}
fun main(args: Array<String>) {
// 不加isDaemon=true, 就报错 "Exception in thread "main" java.lang.IllegalThreadStateException"
thread(start = true, isDaemon = true) {
val handler = object : Handler() {
override fun handleMessage(msg: Message) {
println("szw handler handleMesage(${msg.what})")
}
}
val msg = Message()
msg.what = 11
msg.obj = "test" //要是obj是Object类型, 这就会报错. 正确得是Any类型
handler.sendMessage(msg)
println("011")
Looper.loop()
println("022") // 不会执行到这一句
}.join() //加了join, 就一直在等此线程完结. 但此线程因为loop()死循环, 一直不结束, 所以main()方法也一直不结束
} | apache-2.0 | 97ac757fa3d4ce9d1209c7cc3fed436d | 25.714286 | 94 | 0.611621 | 3.525606 | false | false | false | false |
MichaelRocks/Sunny | app/src/main/kotlin/io/michaelrocks/forecast/ui/cities/CitiesActivity.kt | 1 | 2229 | /*
* Copyright 2016 Michael Rozumyanskiy
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.michaelrocks.forecast.ui.cities
import android.app.Activity
import android.content.Intent
import android.databinding.DataBindingUtil
import android.os.Bundle
import io.michaelrocks.forecast.R
import io.michaelrocks.forecast.databinding.CitiesActivityBinding
import io.michaelrocks.forecast.ui.base.BaseActivity
import io.michaelrocks.forecast.ui.common.EXTRA_CITY_ID
import io.michaelrocks.forecast.ui.common.EXTRA_CITY_NAME
import io.michaelrocks.forecast.ui.common.EXTRA_COUNTRY
import io.michaelrocks.forecast.ui.common.vertical
import io.michaelrocks.lightsaber.inject
import javax.inject.Inject
class CitiesActivity : BaseActivity() {
@Inject private val viewModel: CitiesActivityViewModel = inject()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val binding = DataBindingUtil.setContentView<CitiesActivityBinding>(this, R.layout.cities_activity)
binding.model = viewModel.apply {
onChooseCity = { city ->
city?.apply {
val intent = Intent()
intent.putExtra(EXTRA_CITY_ID, id)
intent.putExtra(EXTRA_CITY_NAME, name)
intent.putExtra(EXTRA_COUNTRY, country)
setResult(Activity.RESULT_OK, intent)
}
finish()
}
}
@Suppress("DEPRECATION")
val dividerDrawable = resources.getDrawable(R.drawable.list_divider)
val dividerPadding = resources.getDimensionPixelSize(R.dimen.divider_size)
binding.recycler.addItemDecoration(vertical(dividerDrawable, dividerPadding))
}
override fun onDestroy() {
super.onDestroy()
viewModel.close()
}
}
| apache-2.0 | 4ef04dc2b03ae9f99666b9dad825c1c4 | 34.951613 | 103 | 0.750561 | 4.311412 | false | false | false | false |
wordpress-mobile/WordPress-Stores-Android | fluxc/src/main/java/org/wordpress/android/fluxc/network/rest/wpcom/stats/time/StatsUtils.kt | 2 | 1318 | package org.wordpress.android.fluxc.network.rest.wpcom.stats.time
import org.wordpress.android.fluxc.model.stats.insights.PostingActivityModel.Day
import org.wordpress.android.fluxc.network.utils.CurrentDateUtils
import java.text.SimpleDateFormat
import java.util.Calendar
import java.util.Date
import java.util.Locale
import java.util.TimeZone
import javax.inject.Inject
const val DATE_FORMAT_DAY = "yyyy-MM-dd"
class StatsUtils
@Inject constructor(private val currentDateUtils: CurrentDateUtils) {
fun getFormattedDate(date: Date? = null, timeZone: TimeZone? = null): String {
val dateFormat = SimpleDateFormat(DATE_FORMAT_DAY, Locale.ROOT)
timeZone?.let {
dateFormat.timeZone = timeZone
}
return dateFormat.format(date ?: currentDateUtils.getCurrentDate())
}
fun getFormattedDate(day: Day): String {
val calendar = Calendar.getInstance()
calendar.set(day.year, day.month, day.day)
val dateFormat = SimpleDateFormat(DATE_FORMAT_DAY, Locale.ROOT)
return dateFormat.format(calendar.time)
}
fun fromFormattedDate(date: String): Date? {
if (date.isEmpty()) {
return null
}
val dateFormat = SimpleDateFormat(DATE_FORMAT_DAY, Locale.ROOT)
return dateFormat.parse(date)
}
}
| gpl-2.0 | 4728f8ca07b577749c7f97480771e699 | 33.684211 | 82 | 0.711684 | 4.210863 | false | false | false | false |
Mauin/detekt | detekt-rules/src/test/kotlin/io/gitlab/arturbosch/detekt/rules/naming/MatchingDeclarationNameSpec.kt | 1 | 4404 | package io.gitlab.arturbosch.detekt.rules.naming
import io.gitlab.arturbosch.detekt.test.assertThat
import io.gitlab.arturbosch.detekt.test.compileContentForTest
import io.gitlab.arturbosch.detekt.test.lint
import org.jetbrains.spek.api.Spek
import org.jetbrains.spek.api.dsl.given
import org.jetbrains.spek.api.dsl.it
/**
* @author Artur Bosch
*/
internal class MatchingDeclarationNameSpec : Spek({
given("compliant test cases") {
it("should pass for object declaration") {
val ktFile = compileContentForTest("object O")
ktFile.name = "O.kt"
val findings = MatchingDeclarationName().lint(ktFile)
assertThat(findings).isEmpty()
}
it("should pass for class declaration") {
val ktFile = compileContentForTest("class C")
ktFile.name = "C.kt"
val findings = MatchingDeclarationName().lint(ktFile)
assertThat(findings).isEmpty()
}
it("should pass for interface declaration") {
val ktFile = compileContentForTest("interface I")
ktFile.name = "I.kt"
val findings = MatchingDeclarationName().lint(ktFile)
assertThat(findings).isEmpty()
}
it("should pass for enum declaration") {
val ktFile = compileContentForTest("""
enum class E {
ONE, TWO, THREE
}
""")
ktFile.name = "E.kt"
val findings = MatchingDeclarationName().lint(ktFile)
assertThat(findings).isEmpty()
}
it("should pass for multiple declaration") {
val ktFile = compileContentForTest("""
class C
object O
fun a() = 5
""")
ktFile.name = "MultiDeclarations.kt"
val findings = MatchingDeclarationName().lint(ktFile)
assertThat(findings).isEmpty()
}
it("should pass for class declaration with utility functions") {
val ktFile = compileContentForTest("""
class C
fun a() = 5
fun C.b() = 5
""")
ktFile.name = "C.kt"
val findings = MatchingDeclarationName().lint(ktFile)
assertThat(findings).isEmpty()
}
it("should pass for private class declaration") {
val ktFile = compileContentForTest("""
private class C
fun a() = 5
""")
ktFile.name = "b.kt"
val findings = MatchingDeclarationName().lint(ktFile)
assertThat(findings).isEmpty()
}
it("should pass for a class with a typealias") {
val code = """
typealias Foo = FooImpl
class FooImpl {}"""
val ktFile = compileContentForTest(code)
ktFile.name = "Foo.kt"
val findings = MatchingDeclarationName().lint(ktFile)
assertThat(findings).isEmpty()
}
}
given("non-compliant test cases") {
it("should not pass for object declaration") {
val ktFile = compileContentForTest("object O")
ktFile.name = "Objects.kt"
val findings = MatchingDeclarationName().lint(ktFile)
assertThat(findings).hasLocationStrings("'object O' at (1,1) in /Objects.kt")
}
it("should not pass for class declaration") {
val ktFile = compileContentForTest("class C")
ktFile.name = "Classes.kt"
val findings = MatchingDeclarationName().lint(ktFile)
assertThat(findings).hasLocationStrings("'class C' at (1,1) in /Classes.kt")
}
it("should not pass for class declaration with utility functions") {
val ktFile = compileContentForTest("""
class C
fun a() = 5
fun C.b() = 5
""")
ktFile.name = "ClassUtils.kt"
val findings = MatchingDeclarationName().lint(ktFile)
assertThat(findings).hasLocationStrings("""'
class C
fun a() = 5
fun C.b() = 5
' at (1,1) in /ClassUtils.kt""", trimIndent = true)
}
it("should not pass for interface declaration") {
val ktFile = compileContentForTest("interface I")
ktFile.name = "Not_I.kt"
val findings = MatchingDeclarationName().lint(ktFile)
assertThat(findings).hasLocationStrings("'interface I' at (1,1) in /Not_I.kt")
}
it("should not pass for enum declaration") {
val ktFile = compileContentForTest("""
enum class NOT_E {
ONE, TWO, THREE
}
""")
ktFile.name = "E.kt"
val findings = MatchingDeclarationName().lint(ktFile)
assertThat(findings).hasLocationStrings("""'
enum class NOT_E {
ONE, TWO, THREE
}
' at (1,1) in /E.kt""", trimIndent = true)
}
it("should not pass for a typealias with a different name") {
val code = """
typealias Bar = FooImpl
class FooImpl {}"""
val ktFile = compileContentForTest(code)
ktFile.name = "Foo.kt"
val findings = MatchingDeclarationName().lint(ktFile)
assertThat(findings).hasSize(1)
}
}
})
| apache-2.0 | af8defc64bdea31c4977ab2809eb5a41 | 27.050955 | 81 | 0.676658 | 3.729043 | false | true | false | false |
googlesamples/mlkit | android/translate-showcase/app/src/main/java/com/google/mlkit/showcase/translate/analyzer/TextAnalyzer.kt | 1 | 5390 | /*
* Copyright 2020 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.google.mlkit.showcase.translate.analyzer
import android.content.Context
import android.graphics.Rect
import android.util.Log
import android.widget.Toast
import androidx.camera.core.ImageAnalysis
import androidx.camera.core.ImageProxy
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.MutableLiveData
import com.google.android.gms.tasks.Task
import com.google.mlkit.common.MlKitException
import com.google.mlkit.showcase.translate.util.ImageUtils
import com.google.mlkit.vision.common.InputImage
import com.google.mlkit.vision.text.Text
import com.google.mlkit.vision.text.TextRecognition
import com.google.mlkit.vision.text.latin.TextRecognizerOptions
import java.util.concurrent.Executor
/**
* Analyzes the frames passed in from the camera and returns any detected text within the requested
* crop region.
*/
class TextAnalyzer(
private val context: Context,
lifecycle: Lifecycle,
executor: Executor,
private val result: MutableLiveData<String>,
private val imageCropPercentages: MutableLiveData<Pair<Int, Int>>
) : ImageAnalysis.Analyzer {
private val detector =
TextRecognition.getClient(TextRecognizerOptions.Builder().setExecutor(executor).build())
init {
lifecycle.addObserver(detector)
}
@androidx.camera.core.ExperimentalGetImage
override fun analyze(imageProxy: ImageProxy) {
val mediaImage = imageProxy.image ?: return
val rotationDegrees = imageProxy.imageInfo.rotationDegrees
// We requested a setTargetAspectRatio, but it's not guaranteed that's what the camera
// stack is able to support, so we calculate the actual ratio from the first frame to
// know how to appropriately crop the image we want to analyze.
val imageHeight = mediaImage.height
val imageWidth = mediaImage.width
val actualAspectRatio = imageWidth / imageHeight
val convertImageToBitmap = ImageUtils.convertYuv420888ImageToBitmap(mediaImage)
val cropRect = Rect(0, 0, imageWidth, imageHeight)
// If the image has a way wider aspect ratio than expected, crop less of the height so we
// don't end up cropping too much of the image. If the image has a way taller aspect ratio
// than expected, we don't have to make any changes to our cropping so we don't handle it
// here.
val currentCropPercentages = imageCropPercentages.value ?: return
if (actualAspectRatio > 3) {
val originalHeightCropPercentage = currentCropPercentages.first
val originalWidthCropPercentage = currentCropPercentages.second
imageCropPercentages.value =
Pair(originalHeightCropPercentage / 2, originalWidthCropPercentage)
}
// If the image is rotated by 90 (or 270) degrees, swap height and width when calculating
// the crop.
val cropPercentages = imageCropPercentages.value ?: return
val heightCropPercent = cropPercentages.first
val widthCropPercent = cropPercentages.second
val (widthCrop, heightCrop) = when (rotationDegrees) {
90, 270 -> Pair(heightCropPercent / 100f, widthCropPercent / 100f)
else -> Pair(widthCropPercent / 100f, heightCropPercent / 100f)
}
cropRect.inset(
(imageWidth * widthCrop / 2).toInt(),
(imageHeight * heightCrop / 2).toInt()
)
val croppedBitmap = ImageUtils.rotateAndCrop(convertImageToBitmap, rotationDegrees, cropRect)
recognizeTextOnDevice(InputImage.fromBitmap(croppedBitmap, 0)).addOnCompleteListener {
imageProxy.close()
}
}
private fun recognizeTextOnDevice(
image: InputImage
): Task<Text> {
// Pass image to an ML Kit Vision API
return detector.process(image)
.addOnSuccessListener { visionText ->
// Task completed successfully
result.value = visionText.text
}
.addOnFailureListener { exception ->
// Task failed with an exception
Log.e(TAG, "Text recognition error", exception)
val message = getErrorMessage(exception)
message?.let {
Toast.makeText(context, message, Toast.LENGTH_SHORT).show()
}
}
}
private fun getErrorMessage(exception: Exception): String? {
val mlKitException = exception as? MlKitException ?: return exception.message
return if (mlKitException.errorCode == MlKitException.UNAVAILABLE) {
"Waiting for text recognition model to be downloaded"
} else exception.message
}
companion object {
private const val TAG = "TextAnalyzer"
}
} | apache-2.0 | e286ba369f467a4e1471389c21df6a74 | 39.533835 | 101 | 0.69462 | 4.864621 | false | false | false | false |
PtrTeixeira/cookbook | cookbook/server/src/test/kotlin/data/RecipeDataTest.kt | 2 | 4206 | package com.github.ptrteixeira.cookbook.data
import com.github.ptrteixeira.cookbook.core.RecipeEgg
import com.github.ptrteixeira.cookbook.core.User
import cookbook.server.src.test.kotlin.data.jdbi
import cookbook.server.src.test.kotlin.data.migrate
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.BeforeAll
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import org.slf4j.LoggerFactory
class RecipeDataTest {
private val ID = 0
private val USER = User("test-user")
@Test
fun itReturnsMissingRecipesAsAbsent() {
val result = recipeDao.getRecipe(USER, ID)
assertThat(result)
.isEmpty()
}
@Test
fun whenNoRecipesItReturnsEmptyList() {
val result = recipeDao.getRecipes(USER)
assertThat(result)
.isEmpty()
}
@Test
fun itAllowsRecipesToBeCreated() {
val id = recipeDao.createRecipeKeys(USER, sampleRecipeEgg)
val recipe = recipeDao.getRecipe(USER, id)
.get()
assertThat(recipe)
.isEqualTo(sampleRecipeEgg.toRecipe(id, USER))
}
@Test
fun whenRecipesAddedReturnedListContainsRecipes() {
recipeDao.createRecipeKeys(USER, sampleRecipeEgg)
val allRecipes = recipeDao.getRecipes(USER)
assertThat(allRecipes)
.hasSize(1)
.extracting<String> { it.name }
.containsExactly(sampleRecipeEgg.name)
}
@Test
fun itAllowsRecipesToBeDeleted() {
val id = recipeDao.createRecipeKeys(USER, sampleRecipeEgg)
recipeDao.deleteRecipe(USER, id)
val getResult = recipeDao.getRecipe(USER, id)
assertThat(getResult)
.isEmpty()
}
@Test
fun itAllowsRecipesToBeUpdated() {
val id = recipeDao.createRecipeKeys(USER, sampleRecipeEgg)
val newIngredients = listOf(
"Eggs", "White Sugar", "Brown Sugar",
"Butter", "Flour", "Chocolate Chips"
)
val updated = sampleRecipeEgg.copy(ingredients = newIngredients)
recipeDao.patchRecipeKeys(USER, id, updated)
val getResult = recipeDao.getRecipe(USER, id)
assertThat(getResult)
.contains(updated.toRecipe(id, USER))
assertThat(getResult.get().ingredients)
.containsExactlyInAnyOrder(*newIngredients.toTypedArray())
}
@Test
fun itOnlyListsRecipesForTheGivenUser() {
recipeDao.createRecipeKeys(User("user-1"), sampleRecipeEgg)
assertThat(recipeDao.getRecipes(User("user-2")))
.isEmpty()
assertThat(recipeDao.getRecipes(User("user-1")))
.isNotEmpty()
}
@Test
fun itForbidsAccessToAnotherUsersRecipes() {
val id = recipeDao.createRecipeKeys(User("user-1"), sampleRecipeEgg)
assertThat(recipeDao.getRecipe(User("user-2"), id))
.isEmpty()
assertThat(recipeDao.getRecipe(User("user-1"), id))
.isNotEmpty()
}
@Test
fun itForbidsUpdatesToAnotherUsersRecipes() {
val id = recipeDao.createRecipeKeys(User("user-1"), sampleRecipeEgg)
recipeDao.deleteRecipe(User("user-2"), id)
assertThat(recipeDao.getRecipe(User("user-1"), id))
.isNotEmpty()
}
@BeforeEach
fun truncateTable() {
dbi.withHandle<Unit, Nothing> {
it.createUpdate("DELETE FROM RECIPES")
.execute()
}
}
companion object {
private val logger = LoggerFactory.getLogger(RecipeDataTest::class.java)
private val dbi = jdbi()
private val recipeDao = dbi.onDemand<RecipeData>(RecipeData::class.java)
private val sampleRecipeEgg = RecipeEgg(
name = "Chocolate Chip Cookies",
ingredients = listOf("Chocolate", "Chips", "Cookies"),
instructions = "Mix",
summary = "They were invented right here in Massachusetts, you know",
description = "They're chocolate chip cookies. Waddya want?"
)
@BeforeAll
@JvmStatic
fun migrate() {
logger.info("Running migrations before DaoTest")
migrate(dbi)
}
}
}
| mit | b54c1e7149d0eb2e89f3b04b6ac15b3f | 29.042857 | 81 | 0.636234 | 4.464968 | false | true | false | false |
facebook/flipper | android/src/main/java/com/facebook/flipper/plugins/uidebugger/observers/DecorViewTreeObserver.kt | 1 | 2681 | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
package com.facebook.flipper.plugins.uidebugger.observers
import android.util.Log
import android.view.View
import android.view.ViewTreeObserver
import com.facebook.flipper.plugins.uidebugger.LogTag
import com.facebook.flipper.plugins.uidebugger.common.BitmapPool
import com.facebook.flipper.plugins.uidebugger.core.Context
import com.facebook.flipper.plugins.uidebugger.scheduler.throttleLatest
import java.lang.ref.WeakReference
import kotlinx.coroutines.*
typealias DecorView = View
/** Responsible for subscribing to updates to the content view of an activity */
class DecorViewObserver(val context: Context) : TreeObserver<DecorView>() {
private val throttleTimeMs = 500L
private var nodeRef: WeakReference<View>? = null
private var listener: ViewTreeObserver.OnPreDrawListener? = null
override val type = "DecorView"
private val waitScope = CoroutineScope(Dispatchers.IO)
private val mainScope = CoroutineScope(Dispatchers.Main)
override fun subscribe(node: Any) {
node as View
nodeRef = WeakReference(node)
Log.i(LogTag, "Subscribing to decor view changes")
val throttledUpdate =
throttleLatest<WeakReference<View>?>(throttleTimeMs, waitScope, mainScope) { weakView ->
weakView?.get()?.let { view ->
var snapshotBitmap: BitmapPool.ReusableBitmap? = null
if (view.width > 0 && view.height > 0) {
snapshotBitmap = context.bitmapPool.getBitmap(node.width, node.height)
}
processUpdate(context, view, snapshotBitmap)
}
}
listener =
ViewTreeObserver.OnPreDrawListener {
throttledUpdate(nodeRef)
true
}
node.viewTreeObserver.addOnPreDrawListener(listener)
// It can be the case that the DecorView the current observer owns has already
// drawn. In this case, manually trigger an update.
throttledUpdate(nodeRef)
}
override fun unsubscribe() {
Log.i(LogTag, "Unsubscribing from decor view changes")
listener.let {
nodeRef?.get()?.viewTreeObserver?.removeOnPreDrawListener(it)
listener = null
}
nodeRef = null
}
}
object DecorViewTreeObserverBuilder : TreeObserverBuilder<DecorView> {
override fun canBuildFor(node: Any): Boolean {
return node.javaClass.simpleName.contains("DecorView")
}
override fun build(context: Context): TreeObserver<DecorView> {
Log.i(LogTag, "Building DecorView observer")
return DecorViewObserver(context)
}
}
| mit | c0acc99bc7a9b44ea1f71e5879385e3c | 30.174419 | 96 | 0.722119 | 4.575085 | false | false | false | false |
Anizoptera/BacKT_SQL | src/main/kotlin/azadev/backt/sql/QueryBuilder.kt | 1 | 6901 | @file:Suppress("unused")
package azadev.backt.sql
import azadev.backt.sql.utils.escapeSqlIdentifier
import azadev.backt.sql.utils.escapeSqlLiteral
import java.sql.ResultSet
import java.util.*
class QueryBuilder(
val quoteIdentifiers: Boolean = true
) {
val sb = StringBuilder(15) // SELECT * FROM t
var params: ArrayList<Any?>? = null
val paramArray: Array<Any?> get() = params?.toArray() ?: emptyArray()
var hasSet = false
var hasWhere = false
var hasOnDupUpd = false
var hasOrder = false
fun executeQuery(db: Database): ResultSet {
if (params == null)
return db.executeQuery(toString())
return db.executeQuery(toString(), *paramArray)
}
fun executeUpdate(db: Database): Int {
if (params == null)
return db.executeUpdate(toString())
return db.executeUpdate(toString(), *paramArray)
}
fun executeUpdateWithAutoKeys(db: Database): ResultSet? {
if (params == null)
return db.executeUpdateWithAutoKeys(toString())
return db.executeUpdateWithAutoKeys(toString(), *paramArray)
}
override fun toString() = sb.toString()
fun p(param: Any?): QueryBuilder {
params = (params ?: ArrayList<Any?>(1)).apply { add(param) }
return this
}
fun select(col: String = "*"): QueryBuilder {
if (col == "*")
sb.append("SELECT *")
else
sb.append("SELECT ").appendIdentifier(col)
return this
}
fun select(vararg cols: String): QueryBuilder {
sb.append("SELECT ")
cols.forEachIndexed { i,col ->
if (i > 0) sb.append(',')
sb.appendIdentifier(col)
}
return this
}
fun insert(table: String): QueryBuilder {
sb.append("INSERT INTO ").appendIdentifier(table)
return this
}
fun update(table: String): QueryBuilder {
sb.append("UPDATE ").appendIdentifier(table)
return this
}
fun delete(): QueryBuilder {
sb.append("DELETE")
return this
}
fun from(table: String): QueryBuilder {
sb.append(" FROM ").appendIdentifier(table)
return this
}
fun where(col: String, value: Any) = where0(col, '=', value)
fun wherep(col: String, param: Any) = where0(col, "=?").p(param)
fun whereNot(col: String, value: Any) = where0(col, "<>", value)
fun wherepNot(col: String, param: Any) = where0(col, "<>?").p(param)
fun whereNull(col: String): QueryBuilder {
where0(col)
sb.append(" IS NULL")
return this
}
fun whereNotNull(col: String): QueryBuilder {
where0(col)
sb.append(" IS NOT NULL")
return this
}
fun whereGt(col: String, value: Any) = where0(col, '>', value)
fun wherepGt(col: String, param: Any) = where0(col, ">?").p(param)
fun whereLt(col: String, value: Any) = where0(col, '<', value)
fun wherepLt(col: String, param: Any) = where0(col, "<?").p(param)
fun whereBetween(col: String, min: Any, max: Any): QueryBuilder {
where0(col)
sb.append(" BETWEEN ").appendLiteral(min).append(" AND ").appendLiteral(max)
return this
}
fun wherepBetween(col: String, min: Any, max: Any): QueryBuilder {
return where0(col, " BETWEEN ? AND ?").p(min).p(max)
}
fun whereNotBetween(col: String, min: Any, max: Any): QueryBuilder {
where0(col)
sb.append(" NOT BETWEEN ").appendLiteral(min).append(" AND ").appendLiteral(max)
return this
}
fun wherepNotBetween(col: String, min: Any, max: Any): QueryBuilder {
return where0(col, " NOT BETWEEN ? AND ?").p(min).p(max)
}
fun whereIn(col: String, values: Any): QueryBuilder {
where0(col)
sb.append(" IN (").appendJoined(values).append(')')
return this
}
fun whereNotIn(col: String, values: Any): QueryBuilder {
where0(col)
sb.append(" NOT IN (").appendJoined(values).append(')')
return this
}
private fun where0(col: String, eq: Any? = null, value: Any? = null): QueryBuilder {
if (!hasWhere) {
sb.append(" WHERE ")
hasWhere = true
}
else sb.append(" AND ")
sb.appendIdentifier(col)
when (eq) {
is Char -> sb.append(eq)
is String -> sb.append(eq)
}
if (value != null)
sb.appendLiteral(value)
return this
}
fun orderBy(col: String, desc: Boolean = false): QueryBuilder {
if (!hasOrder) {
sb.append(" ORDER BY ")
hasOrder = true
}
else sb.append(',')
sb.appendIdentifier(col)
if (desc)
sb.append(" DESC")
return this
}
fun limit(num: Int): QueryBuilder {
sb.append(" LIMIT ").append(num)
return this
}
fun set(col: String, value: Any?): QueryBuilder {
return when (value) {
null -> set0(col, "=NULL")
else -> set0(col, '=', value)
}
}
fun setp(col: String, value: Any?): QueryBuilder {
return when (value) {
null -> set(col, null)
else -> set0(col, "=?").p(value)
}
}
private fun set0(col: String, eq: Any, value: Any? = null): QueryBuilder {
appendColValPair(col, eq, value, if (hasSet) ", " else " SET ")
hasSet = true
return this
}
fun onDupUpdate(col: String, value: Any?): QueryBuilder {
return when (value) {
null -> onDupUpdate0(col, "=NULL")
else -> onDupUpdate0(col, '=', value)
}
}
fun onDupUpdatep(col: String, value: Any?): QueryBuilder {
return when (value) {
null -> onDupUpdate(col, value)
else -> onDupUpdate0(col, "=?").p(value)
}
}
private fun onDupUpdate0(col: String, eq: Any, value: Any? = null): QueryBuilder {
appendColValPair(col, eq, value, if (hasOnDupUpd) ", " else " ON DUPLICATE KEY UPDATE ")
hasOnDupUpd = true
return this
}
private fun appendColValPair(col: String, eq: Any, value: Any? = null, prefix: Any): QueryBuilder {
when (prefix) {
is Char -> sb.append(prefix)
is String -> sb.append(prefix)
}
sb.appendIdentifier(col)
when (eq) {
is Char -> sb.append(eq)
is String -> sb.append(eq)
}
if (value != null)
sb.appendLiteral(value)
return this
}
private fun StringBuilder.appendIdentifier(name: String): StringBuilder {
if (quoteIdentifiers) append('`')
append(name.escapeSqlIdentifier())
if (quoteIdentifiers) append('`')
return this
}
private fun StringBuilder.appendLiteral(value: Any): StringBuilder {
// Common types (to avoid "toString" inside StringBuilder)
return when (value) {
is Boolean -> append(if (value) 1 else 0)
is Long -> append(value)
is Int -> append(value)
is Short -> append(value)
is Byte -> append(value)
is Double -> append(value)
is Float -> append(value)
is String -> append('\'').append(value.escapeSqlLiteral()).append('\'')
is Char -> append('\'').apply {
val esc = value.escapeSqlLiteral()
if (esc != null) append(esc)
else append(value)
}.append('\'')
else -> appendLiteral(value.toString())
}
}
private fun StringBuilder.appendJoined(values: Any): StringBuilder {
var i = -1
when (values) {
is Array<*> -> values.forEach {
if (it != null) {
if (++i > 0) sb.append(',')
appendLiteral(it)
}
}
is Iterable<*> -> values.forEach {
if (it != null) {
if (++i > 0) sb.append(',')
appendLiteral(it)
}
}
else -> appendLiteral(values)
}
return this
}
}
| mit | 836171c8d80f0c94401e456f4c651ccd | 22.23569 | 100 | 0.648457 | 3.143964 | false | false | false | false |
jereksel/LibreSubstratum | sublib/compilercommon/src/main/java/com/jereksel/libresubstratumlib/compilercommon/AndroidManifestGenerator.kt | 1 | 2980 | package com.jereksel.libresubstratumlib.compilercommon
class AndroidManifestGenerator(val testing: Boolean = false) {
val metadataOverlayTarget = "Substratum_Target"
val metadataOverlayParent = "Substratum_Parent"
val metadataOverlayType1a = "Substratum_Type1a"
val metadataOverlayType1b = "Substratum_Type1b"
val metadataOverlayType1c = "Substratum_Type1c"
val metadataOverlayType2 = "Substratum_Type2"
val metadataOverlayType3 = "Substratum_Type3"
fun generateManifest(theme: ThemeToCompile): String {
val appId = theme.targetOverlayId
val target = theme.fixedTargetApp
val themeId = theme.targetThemeId
val type1a = theme.getType("a").replace("&", "&")
val type1b = theme.getType("b").replace("&", "&")
val type1c = theme.getType("c").replace("&", "&")
val type2 = theme.getType2().replace("&", "&")
val type3 = theme.getType3().replace("&", "&")
val xmlnsAndroid = if (testing) {
"http://schemas.android.com/apk/lib/$appId"
} else {
"http://schemas.android.com/apk/res/android"
}
//TODO: DSL
return """<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="$xmlnsAndroid" package="$appId"
android:versionCode="${theme.versionCode}" android:versionName="${theme.versionName}">
<overlay android:priority="1" android:targetPackage="$target" />
<application android:label="$appId" allowBackup="false" android:hasCode="false">
<meta-data android:name="$metadataOverlayTarget" android:value="$target" />
<meta-data android:name="$metadataOverlayParent" android:value="$themeId" />
<meta-data android:name="$metadataOverlayType1a" android:value="$type1a" />
<meta-data android:name="$metadataOverlayType1b" android:value="$type1b" />
<meta-data android:name="$metadataOverlayType1c" android:value="$type1c" />
<meta-data android:name="$metadataOverlayType2" android:value="$type2" />
<meta-data android:name="$metadataOverlayType3" android:value="$type3" />
</application>
</manifest>
"""
}
private fun ThemeToCompile.getType(type: String): String {
val t = this.type1.find { it.suffix == type }?.extension ?: return ""
if (t.default) {
return ""
} else {
return t.name
}
}
private fun ThemeToCompile.getType2(): String {
val t = this.type2 ?: return ""
if (t.default) {
return ""
} else {
return t.name
}
}
private fun ThemeToCompile.getType3(): String {
val t = this.type3 ?: return ""
if (t.default) {
return ""
} else {
return t.name
}
}
}
| mit | 2b7d03673bcebd43d49ac052d9605bdd | 33.252874 | 98 | 0.583221 | 4.414815 | false | false | false | false |
nickthecoder/paratask | paratask-core/src/main/kotlin/uk/co/nickthecoder/paratask/parameters/fields/MultipleField.kt | 1 | 4375 | /*
ParaTask Copyright (C) 2017 Nick Robinson
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 uk.co.nickthecoder.paratask.parameters.fields
import javafx.event.EventHandler
import javafx.scene.Node
import javafx.scene.control.Button
import javafx.scene.control.Tooltip
import javafx.scene.layout.HBox
import uk.co.nickthecoder.paratask.gui.ApplicationActions
import uk.co.nickthecoder.paratask.gui.ShortcutHelper
import uk.co.nickthecoder.paratask.parameters.MultipleParameter
import uk.co.nickthecoder.paratask.parameters.Parameter
import uk.co.nickthecoder.paratask.parameters.ParameterEvent
import uk.co.nickthecoder.paratask.parameters.ParameterEventType
import uk.co.nickthecoder.paratask.util.focusNext
class MultipleField<T>(val multipleParameter: MultipleParameter<T, *>)
: ParameterField(multipleParameter), FieldParent {
val addButton = Button("+")
val parametersForm = ParametersForm(multipleParameter, this)
val shortcuts = ShortcutHelper("MultipleField", parametersForm, false)
init {
shortcuts.add(ApplicationActions.ITEM_ADD) { extraValue() }
}
override fun updateError(field: ParameterField) {
parametersForm.updateField(field)
}
override fun updateField(field: ParameterField) {
parametersForm.updateField(field)
}
override fun iterator(): Iterator<ParameterField> = parametersForm.iterator()
override fun createControl(): Node {
addButton.onAction = EventHandler {
extraValue()
}
addButton.tooltip = Tooltip("Add")
parametersForm.styleClass.add("multiple")
// Add 'blank' items, so that the required minimum number of items can be entered.
// The most common scenarios, is adding a single 'blank' item when minItems == 1
while (multipleParameter.minItems > multipleParameter.value.size) {
multipleParameter.newValue()
}
buildContent()
if (isBoxed) {
val box = HBox()
box.styleClass.add("padded-box")
box.children.add(parametersForm)
control = box
} else {
control = parametersForm
}
return control!!
}
fun buildContent() {
parametersForm.clear()
for ((index, innerParameter) in multipleParameter.innerParameters.withIndex()) {
addParameter(innerParameter, index)
}
if (multipleParameter.innerParameters.isEmpty()) {
parametersForm.add(addButton)
}
}
fun addParameter(parameter: Parameter, index: Int): ParameterField {
val result = parametersForm.addParameter(parameter)
val buttons = HBox()
buttons.styleClass.add("multiple-line-buttons")
val addButton = Button("+")
addButton.onAction = EventHandler {
newValue(index + 1)
}
addButton.tooltip = Tooltip("Insert Before")
buttons.children.add(addButton)
val removeButton = Button("-")
removeButton.onAction = EventHandler {
removeAt(index)
}
removeButton.tooltip = Tooltip("Remove")
buttons.children.add(removeButton)
result.plusMinusButtons(buttons)
return result
}
private fun newValue(index: Int) {
val valueParameter = multipleParameter.newValue(index)
parametersForm.findField(valueParameter)?.control?.focusNext()
}
private fun extraValue() {
newValue(multipleParameter.children.size)
}
fun removeAt(index: Int) {
multipleParameter.removeAt(index)
}
override fun parameterChanged(event: ParameterEvent) {
super.parameterChanged(event)
if (event.type == ParameterEventType.STRUCTURAL) {
buildContent()
}
}
}
| gpl-3.0 | 905a3a7076390024656ca3007a549fda | 29.809859 | 90 | 0.686857 | 4.850333 | false | false | false | false |
nemerosa/ontrack | ontrack-ui-graphql/src/test/java/net/nemerosa/ontrack/graphql/AbstractQLKTITJUnit4Support.kt | 1 | 4384 | package net.nemerosa.ontrack.graphql
import com.fasterxml.jackson.databind.JsonNode
import graphql.GraphQL
import net.nemerosa.ontrack.graphql.schema.GraphqlSchemaService
import net.nemerosa.ontrack.graphql.schema.UserError
import net.nemerosa.ontrack.graphql.support.exception
import net.nemerosa.ontrack.it.links.AbstractBranchLinksTestJUnit4Support
import net.nemerosa.ontrack.json.JsonUtils
import net.nemerosa.ontrack.json.isNullOrNullNode
import net.nemerosa.ontrack.json.parse
import org.springframework.beans.factory.annotation.Autowired
import kotlin.test.assertEquals
import kotlin.test.fail
@Deprecated(message = "JUnit is deprecated", replaceWith = ReplaceWith("AbstractQLKTITSupport"))
abstract class AbstractQLKTITJUnit4Support : AbstractBranchLinksTestJUnit4Support() {
@Autowired
private lateinit var schemaService: GraphqlSchemaService
fun run(query: String, variables: Map<String, *> = emptyMap<String, Any>()): JsonNode {
// Task to run
val code = { internalRun(query, variables) }
// Making sure we're at least authenticated
return if (securityService.isLogged) {
code()
} else {
asUser().call(code)
}
}
fun run(query: String, variables: Map<String, *> = emptyMap<String, Any>(), code: (data: JsonNode) -> Unit) {
run(query, variables).let { data ->
code(data)
}
}
private fun internalRun(query: String, variables: Map<String, *> = emptyMap<String, Any>()): JsonNode {
val result = GraphQL
.newGraphQL(schemaService.schema)
.build()
.execute {
it.query(query).variables(variables)
}
val error = result.exception
if (error != null) {
throw error
} else if (result.errors != null && !result.errors.isEmpty()) {
fail(result.errors.joinToString("\n") { it.message })
} else {
val data: Any? = result.getData()
if (data != null) {
return JsonUtils.format(data)
} else {
fail("No data was returned and no error was thrown.")
}
}
}
protected fun assertNoUserError(data: JsonNode, userNodeName: String): JsonNode {
val userNode = data.path(userNodeName)
val errors = userNode.path("errors")
if (!errors.isNullOrNullNode() && errors.isArray && errors.size() > 0) {
errors.forEach { error: JsonNode ->
error.path("exception")
.takeIf { !it.isNullOrNullNode() }
?.let { println("Error exception: ${it.asText()}") }
error.path("location")
.takeIf { !it.isNullOrNullNode() }
?.let { println("Error location: ${it.asText()}") }
fail(error.path("message").asText())
}
}
return userNode
}
protected fun assertUserError(
data: JsonNode,
userNodeName: String,
message: String? = null,
exception: String? = null
) {
val errors = data.path(userNodeName).path("errors")
if (errors.isNullOrNullNode()) {
fail("Excepted the `errors` user node.")
} else if (!errors.isArray) {
fail("Excepted the `errors` user node to be an array.")
} else if (errors.isEmpty) {
fail("Excepted the `errors` user node to be a non-empty array.")
} else {
val error = errors.first()
if (message != null) {
assertEquals(message, error.path("message").asText())
}
if (exception != null) {
assertEquals(exception, error.path("exception").asText())
}
}
}
protected fun checkGraphQLUserErrors(data: JsonNode, field: String): JsonNode {
val payload = data.path(field)
val node = payload.path("errors")
if (node != null && node.isArray && node.size() > 0) {
val error = node.first().parse<UserError>()
throw IllegalStateException(error.toString())
}
return payload
}
protected fun checkGraphQLUserErrors(data: JsonNode, field: String, code: (payload: JsonNode) -> Unit) {
val payload = checkGraphQLUserErrors(data, field)
code(payload)
}
}
| mit | dfcebcd4cf7e7ca58ca42a13a4259fb4 | 36.470085 | 113 | 0.595803 | 4.5762 | false | false | false | false |
hypercube1024/firefly | firefly-net/src/main/kotlin/com/fireflysource/net/http/server/impl/matcher/AbstractRegexMatcher.kt | 1 | 1923 | package com.fireflysource.net.http.server.impl.matcher
import com.fireflysource.net.http.server.Matcher
import com.fireflysource.net.http.server.Router
import java.util.*
import java.util.regex.Pattern
abstract class AbstractRegexMatcher :AbstractMatcher<AbstractRegexMatcher.RegexRule>(), Matcher {
companion object {
const val paramName = "group"
}
class RegexRule(val rule: String) {
val pattern: Pattern = Pattern.compile(rule)
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as RegexRule
return rule == other.rule
}
override fun hashCode(): Int {
return rule.hashCode()
}
}
override fun add(rule: String, router: Router) {
routersMap.computeIfAbsent(RegexRule(rule)) { TreeSet() }.add(router)
}
override fun match(value: String): Matcher.MatchResult? {
if (routersMap.isEmpty()) return null
val routers = TreeSet<Router>()
val parameters = HashMap<Router, Map<String, String>>()
routersMap.forEach { (rule, routerSet) ->
var matcher = rule.pattern.matcher(value)
if (matcher.matches()) {
routers.addAll(routerSet)
matcher = rule.pattern.matcher(value)
val param: MutableMap<String, String> = HashMap()
while (matcher.find()) {
for (i in 1..matcher.groupCount()) {
param["$paramName$i"] = matcher.group(i)
}
}
if (param.isNotEmpty()) {
routerSet.forEach { router -> parameters[router] = param }
}
}
}
return if (routers.isEmpty()) null else Matcher.MatchResult(routers, parameters, matchType)
}
} | apache-2.0 | 8424105545c690ae13d7b2a17714fdc9 | 31.066667 | 99 | 0.579823 | 4.656174 | false | false | false | false |
nemerosa/ontrack | ontrack-job/src/main/java/net/nemerosa/ontrack/job/JobType.kt | 1 | 1022 | package net.nemerosa.ontrack.job
data class JobType(
val category: JobCategory,
val key: String,
val name: String
) {
fun withName(name: String) = JobType(category, key, name)
fun getKey(id: String): JobKey {
return JobKey.of(this, id)
}
override fun toString(): String {
return String.format(
"%s[%s]",
category,
key
)
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is JobType) return false
if (category != other.category) return false
if (key != other.key) return false
return true
}
override fun hashCode(): Int {
var result = category.hashCode()
result = 31 * result + key.hashCode()
return result
}
companion object {
@JvmStatic
fun of(category: JobCategory, key: String): JobType {
return JobType(category, key, key)
}
}
}
| mit | ea47f2e0066d427d42f053a93af910a9 | 20.744681 | 61 | 0.544031 | 4.443478 | false | false | false | false |
06needhamt/Neuroph-Intellij-Plugin | neuroph-plugin/src/com/thomas/needham/neurophidea/core/NetworkTrainer.kt | 1 | 10242 | /*
The MIT License (MIT)
Copyright (c) 2016 Tom Needham
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package com.thomas.needham.neurophidea.core
import com.intellij.ide.util.PropertiesComponent
import com.intellij.openapi.ui.Messages
import com.thomas.needham.neurophidea.Constants.COMMA_DELIMITED
import com.thomas.needham.neurophidea.Constants.NETWORK_TO_TRAIN_LOCATION_KEY
import com.thomas.needham.neurophidea.actions.OpenExistingNetworkConfigurationAction
import com.thomas.needham.neurophidea.actions.ShowTrainNetworkFormAction
import com.thomas.needham.neurophidea.datastructures.LearningRules
import com.thomas.needham.neurophidea.datastructures.NetworkConfiguration
import com.thomas.needham.neurophidea.datastructures.NetworkTypes
import com.thomas.needham.neurophidea.datastructures.TransferFunctions
import com.thomas.needham.neurophidea.exceptions.UnknownLearningRuleException
import com.thomas.needham.neurophidea.exceptions.UnknownNetworkTypeException
import com.thomas.needham.neurophidea.exceptions.UnknownTransferFunctionException
import org.neuroph.core.NeuralNetwork
import org.neuroph.core.learning.SupervisedTrainingElement
import org.neuroph.core.learning.TrainingSet
import org.neuroph.nnet.*
import org.neuroph.nnet.learning.*
import org.neuroph.util.TransferFunctionType
import java.io.*
import java.util.*
/**
* Created by Thomas Needham on 30/05/2016.
*/
class NetworkTrainer {
var network: NeuralNetwork? = null
var trainingSet: TrainingSet<SupervisedTrainingElement?>? = null
var trainingData: DoubleArray? = null
var properties = PropertiesComponent.getInstance()
var inputSize: Int = 0
var outputSize: Int = 0
companion object Data {
var networkPath = ""
var trainingSetPath = ""
var networkConfiguration: NetworkConfiguration? = null
var outputPath = ""
}
constructor(path: String, trainingSet: String) {
networkPath = path
trainingSetPath = trainingSet
networkConfiguration = LoadNetworkConfiguration()
this.trainingSet = LoadTrainingSet()
}
constructor(path: String, trainingData: DoubleArray) {
networkPath = path
this.trainingData = trainingData
networkConfiguration = LoadNetworkConfiguration()
this.trainingSet = CreateTrainingSet()
}
private fun LoadNetworkConfiguration(): NetworkConfiguration? {
val network: NetworkConfiguration?
try {
val file = File(networkPath)
val fis = FileInputStream(file)
val ois = ObjectInputStream(fis)
network = ois.readObject() as NetworkConfiguration?
inputSize = network?.networkLayers?.first()!!
outputSize = network?.networkLayers?.last()!!
return network
} catch (ioe: IOException) {
ioe.printStackTrace(System.err)
Messages.showErrorDialog(OpenExistingNetworkConfigurationAction.project, "Error Reading Network From file", "Error")
return null
} catch (fnfe: FileNotFoundException) {
fnfe.printStackTrace(System.err)
Messages.showErrorDialog(OpenExistingNetworkConfigurationAction.project, "No Network Configuration Found at: ${ShowTrainNetworkFormAction.properties.getValue(NETWORK_TO_TRAIN_LOCATION_KEY, "")}", "Error")
return null
}
}
private fun CreateTrainingSet(): TrainingSet<SupervisedTrainingElement?>? {
if (trainingData == null)
return null
try {
var set = TrainingSet<SupervisedTrainingElement?>(networkConfiguration?.networkLayers?.first()!!, networkConfiguration?.networkLayers?.last()!!)
for (i in 0..trainingData?.size!! step inputSize + outputSize) {
val inputSize = networkConfiguration?.networkLayers?.first()!!
val outputSize = networkConfiguration?.networkLayers?.last()!!
set.addElement(SupervisedTrainingElement(trainingData!!.copyOfRange(i, (i + inputSize)),
trainingData!!.copyOfRange((i + inputSize), (i + inputSize + outputSize))))
}
return set
} catch (ioobe: IndexOutOfBoundsException) {
ioobe.printStackTrace(System.err)
Messages.showErrorDialog(ShowTrainNetworkFormAction.project, "Training data does not contain the correct amount of inputs or outputs", "Error")
return null
}
}
private fun LoadTrainingSet(): TrainingSet<SupervisedTrainingElement?>? {
return TrainingSet.createFromFile(trainingSetPath, inputSize, outputSize, COMMA_DELIMITED) as TrainingSet<SupervisedTrainingElement?>?
}
fun TrainNetwork(): NeuralNetwork? {
var function: TransferFunctionType? = null
when (networkConfiguration?.networkTransferFunction) {
TransferFunctions.Functions.GAUSSIAN -> function = TransferFunctionType.GAUSSIAN
TransferFunctions.Functions.LINEAR -> function = TransferFunctionType.LINEAR
TransferFunctions.Functions.LOG -> function = TransferFunctionType.LOG
TransferFunctions.Functions.RAMP -> function = TransferFunctionType.RAMP
TransferFunctions.Functions.SGN -> function = TransferFunctionType.SGN
TransferFunctions.Functions.SIGMOID -> function = TransferFunctionType.SIGMOID
TransferFunctions.Functions.STEP -> function = TransferFunctionType.STEP
TransferFunctions.Functions.TANH -> function = TransferFunctionType.TANH
TransferFunctions.Functions.TRAPEZOID -> function = TransferFunctionType.TRAPEZOID
else -> UnknownTransferFunctionException("Unknown Transfer Function: ${TransferFunctions.GetClassName(networkConfiguration?.networkTransferFunction!!)}")
}
when (networkConfiguration?.networkType) {
NetworkTypes.Types.ADALINE -> network = Adaline(inputSize)
NetworkTypes.Types.BAM -> BAM(inputSize, outputSize)
NetworkTypes.Types.COMPETITIVE_NETWORK -> network = CompetitiveNetwork(inputSize, outputSize)
NetworkTypes.Types.HOPFIELD -> network = Hopfield(inputSize + outputSize)
NetworkTypes.Types.INSTAR -> network = Instar(inputSize)
NetworkTypes.Types.KOHONEN -> network = Kohonen(inputSize, outputSize)
NetworkTypes.Types.MAX_NET -> network = MaxNet(inputSize + outputSize)
NetworkTypes.Types.MULTI_LAYER_PERCEPTRON -> network = MultiLayerPerceptron(networkConfiguration?.networkLayers?.toList(), function)
NetworkTypes.Types.NEURO_FUZZY_PERCEPTRON -> network = NeuroFuzzyPerceptron(inputSize, Vector<Int>(inputSize), outputSize)
NetworkTypes.Types.NEUROPH -> network = Perceptron(inputSize, outputSize, function)
NetworkTypes.Types.OUTSTAR -> network = Outstar(outputSize)
NetworkTypes.Types.PERCEPTRON -> network = Perceptron(inputSize, outputSize, function)
NetworkTypes.Types.RBF_NETWORK -> network = RbfNetwork(inputSize, inputSize, outputSize)
NetworkTypes.Types.SUPERVISED_HEBBIAN_NETWORK -> network = SupervisedHebbianNetwork(inputSize, outputSize, function)
NetworkTypes.Types.UNSUPERVISED_HEBBIAN_NETWORK -> network = UnsupervisedHebbianNetwork(inputSize, outputSize, function)
else -> UnknownNetworkTypeException("Unknown Network Type: ${NetworkTypes.GetClassName(networkConfiguration?.networkType!!)}")
//TODO add more network types
}
when (networkConfiguration?.networkLearningRule) {
LearningRules.Rules.ANTI_HEBBAN_LEARNING -> network?.learningRule = AntiHebbianLearning()
LearningRules.Rules.BACK_PROPAGATION -> network?.learningRule = BackPropagation()
LearningRules.Rules.BINARY_DELTA_RULE -> network?.learningRule = BinaryDeltaRule()
LearningRules.Rules.BINARY_HEBBIAN_LEARNING -> network?.learningRule = BinaryHebbianLearning()
LearningRules.Rules.COMPETITIVE_LEARNING -> network?.learningRule = CompetitiveLearning()
LearningRules.Rules.DYNAMIC_BACK_PROPAGATION -> network?.learningRule = DynamicBackPropagation()
LearningRules.Rules.GENERALIZED_HEBBIAN_LEARNING -> network?.learningRule = GeneralizedHebbianLearning()
LearningRules.Rules.HOPFIELD_LEARNING -> network?.learningRule = HopfieldLearning()
LearningRules.Rules.INSTAR_LEARNING -> network?.learningRule = InstarLearning()
LearningRules.Rules.KOHONEN_LEARNING -> network?.learningRule = KohonenLearning()
LearningRules.Rules.LMS -> network?.learningRule = LMS()
LearningRules.Rules.MOMENTUM_BACK_PROPAGATION -> network?.learningRule = MomentumBackpropagation()
LearningRules.Rules.OJA_LEARNING -> network?.learningRule = OjaLearning()
LearningRules.Rules.OUTSTAR_LEARNING -> network?.learningRule = OutstarLearning()
LearningRules.Rules.PERCEPTRON_LEARNING -> network?.learningRule = PerceptronLearning()
LearningRules.Rules.RESILIENT_PROPAGATION -> network?.learningRule = ResilientPropagation()
LearningRules.Rules.SIGMOID_DELTA_RULE -> network?.learningRule = SigmoidDeltaRule()
LearningRules.Rules.SIMULATED_ANNEALING_LEARNING -> network?.learningRule = SimulatedAnnealingLearning(network)
LearningRules.Rules.SUPERVISED_HEBBIAN_LEARNING -> network?.learningRule = SupervisedHebbianLearning()
LearningRules.Rules.UNSUPERVISED_HEBBIAN_LEARNING -> network?.learningRule = UnsupervisedHebbianLearning()
else -> UnknownLearningRuleException("Unknown Learning Rule: ${LearningRules.GetClassName(networkConfiguration?.networkLearningRule!!)}")
}
if (trainingSet == null) {
Messages.showErrorDialog("Invalid Training Set", "Error")
return null
}
val outfile = File(networkPath + ".nnet")
properties.setValue(NETWORK_TO_TRAIN_LOCATION_KEY, networkPath)
if (!outfile.exists()) {
outfile.createNewFile()
}
network?.learn(trainingSet)
network?.calculate()
network?.save(networkPath + ".nnet")
return network
}
} | mit | 627547fa09640d689525f2bd67079a59 | 51.528205 | 207 | 0.791447 | 4.480315 | false | true | false | false |
mockk/mockk | modules/mockk/src/commonMain/kotlin/io/mockk/impl/stub/AnswerAnsweringOpportunity.kt | 1 | 1269 | package io.mockk.impl.stub
import io.mockk.*
import io.mockk.impl.InternalPlatform
class AnswerAnsweringOpportunity<T>(
private val matcherStr: () -> String
) : MockKGateway.AnswerOpportunity<T>, Answer<T> {
private var storedAnswer: Answer<T>? = null
private val firstAnswerHandlers = mutableListOf<(Answer<T>) -> Unit>()
private fun getAnswer() = storedAnswer ?: throw MockKException("no answer provided for ${matcherStr()}")
override fun answer(call: Call) = getAnswer().answer(call)
override suspend fun coAnswer(call: Call) = getAnswer().answer(call)
override fun provideAnswer(answer: Answer<T>) {
InternalPlatform.synchronized(this) {
val currentAnswer = this.storedAnswer
this.storedAnswer = if (currentAnswer == null) {
notifyFirstAnswerHandlers(answer)
answer
} else {
ManyAnswersAnswer(listOf(currentAnswer, answer))
}
}
}
private fun notifyFirstAnswerHandlers(answer: Answer<T>) {
firstAnswerHandlers.forEach { it(answer) }
}
fun onFirstAnswer(handler: (Answer<T>) -> Unit) {
InternalPlatform.synchronized(this) {
firstAnswerHandlers.add(handler)
}
}
}
| apache-2.0 | 3cfe7b8b5699b21a51f677cdc139418c | 32.394737 | 109 | 0.646966 | 4.564748 | false | false | false | false |
soywiz/korge | korge/src/commonMain/kotlin/com/soywiz/korge/view/ScaleView.kt | 1 | 1289 | package com.soywiz.korge.view
import com.soywiz.korge.render.*
inline fun Container.scaleView(
width: Int, height: Int, scale: Double = 2.0, filtering: Boolean = false,
callback: @ViewDslMarker Container.() -> Unit = {}
) = ScaleView(width, height, scale, filtering).addTo(this, callback)
class ScaleView(width: Int, height: Int, scale: Double = 2.0, var filtering: Boolean = false) :
FixedSizeContainer(), View.Reference {
init {
this.width = width.toDouble()
this.height = height.toDouble()
this.scale = scale
}
//val once = Once()
override fun renderInternal(ctx: RenderContext) {
val iwidth = width.toInt()
val iheight = height.toInt()
ctx.renderToTexture(iwidth, iheight, render = {
super.renderInternal(ctx)
}, use = { renderTexture ->
ctx.useBatcher { batch ->
batch.drawQuad(
tex = renderTexture,
x = 0f, y = 0f,
width = iwidth.toFloat(),
height = iheight.toFloat(),
m = globalMatrix,
colorMul = renderColorMul,
colorAdd = renderColorAdd,
filtering = filtering,
blendFactors = renderBlendMode.factors
)
}
})
}
}
| apache-2.0 | 95a2940c2b0f58ef12b7af3f26ce32ef | 29.690476 | 95 | 0.577192 | 3.966154 | false | false | false | false |
material-components/material-components-android-motion-codelab | app/src/main/java/com/materialstudies/reply/ui/nav/SemiCircleEdgeCutoutTreatment.kt | 1 | 6328 | /*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.materialstudies.reply.ui.nav
import com.google.android.material.shape.EdgeTreatment
import com.google.android.material.shape.ShapePath
import kotlin.math.atan
import kotlin.math.sqrt
private const val ARC_QUARTER = 90
private const val ARC_HALF = 180
private const val ANGLE_UP = 270
private const val ANGLE_LEFT = 180
/**
* An edge treatment which draws a semicircle cutout at any point along the edge.
*
* @param cutoutMargin Additional width to be added to the [cutoutDiameter], resulting in a
* larger total cutout size.
* @param cutoutRoundedCornerRadius The radius of the each of the corners where the semicircle
* meets the straight edge.
* @param cutoutVerticalOffset The amount the cutout should be lifted up in relation to the circle's
* middle.
* @param cutoutDiameter The diameter of the semicircle to be cutout.
* @param cutoutHorizontalOffset The horizontal offset, from the middle of the edge, where the
* cutout should be drawn.
*/
class SemiCircleEdgeCutoutTreatment(
private var cutoutMargin: Float = 0F,
private var cutoutRoundedCornerRadius: Float = 0F,
private var cutoutVerticalOffset: Float = 0F,
private var cutoutDiameter: Float = 0F,
private var cutoutHorizontalOffset: Float = 0F
) : EdgeTreatment() {
private var cradleDiameter = 0F
private var cradleRadius = 0F
private var roundedCornerOffset = 0F
private var middle = 0F
private var verticalOffset = 0F
private var verticalOffsetRatio = 0F
private var distanceBetweenCenters = 0F
private var distanceBetweenCentersSquared = 0F
private var distanceY = 0F
private var distanceX = 0F
private var leftRoundedCornerCircleX = 0F
private var rightRoundedCornerCircleX = 0F
private var cornerRadiusArcLength = 0F
private var cutoutArcOffset = 0F
init {
require(cutoutVerticalOffset >= 0) {
"cutoutVerticalOffset must be positive but was $cutoutVerticalOffset"
}
}
override fun getEdgePath(
length: Float,
center: Float,
interpolation: Float,
shapePath: ShapePath
) {
if (cutoutDiameter == 0f) {
// There is no cutout to draw.
shapePath.lineTo(length, 0f)
return
}
cradleDiameter = cutoutMargin * 2 + cutoutDiameter
cradleRadius = cradleDiameter / 2f
roundedCornerOffset = interpolation * cutoutRoundedCornerRadius
middle = length / 2f + cutoutHorizontalOffset
verticalOffset = interpolation * cutoutVerticalOffset +
(1 - interpolation) * cradleRadius
verticalOffsetRatio = verticalOffset / cradleRadius
if (verticalOffsetRatio >= 1.0f) {
// Vertical offset is so high that there's no curve to draw in the edge. The circle is
// actually above the edge, so just draw a straight line.
shapePath.lineTo(length, 0f)
return
}
// Calculate the path of the cutout by calculating the location of two adjacent circles. One
// circle is for the rounded corner. If the rounded corner circle radius is 0 the corner
// will not be rounded. The other circle is the cutout.
// Calculate the X distance between the center of the two adjacent circles using pythagorean
// theorem.
distanceBetweenCenters = cradleRadius + roundedCornerOffset
distanceBetweenCentersSquared = distanceBetweenCenters * distanceBetweenCenters
distanceY = verticalOffset + roundedCornerOffset
distanceX = sqrt(
(distanceBetweenCentersSquared - distanceY * distanceY).toDouble()
).toFloat()
// Calculate the x position of the rounded corner circles.
leftRoundedCornerCircleX = middle - distanceX
rightRoundedCornerCircleX = middle + distanceX
// Calculate the arc between the center of the two circles.
cornerRadiusArcLength = Math.toDegrees(
atan((distanceX / distanceY).toDouble())
).toFloat()
cutoutArcOffset = ARC_QUARTER - cornerRadiusArcLength
// Draw the starting line up to the left rounded corner.
shapePath.lineTo(leftRoundedCornerCircleX - roundedCornerOffset, 0f)
// Draw the arc for the left rounded corner circle. The bounding box is the area around the
// circle's center which is at (leftRoundedCornerCircleX, roundedCornerOffset).
shapePath.addArc(
leftRoundedCornerCircleX - roundedCornerOffset,
0f,
leftRoundedCornerCircleX + roundedCornerOffset,
roundedCornerOffset * 2,
ANGLE_UP.toFloat(),
cornerRadiusArcLength)
// Draw the cutout circle.
shapePath.addArc(
middle - cradleRadius,
-cradleRadius - verticalOffset,
middle + cradleRadius,
cradleRadius - verticalOffset,
ANGLE_LEFT - cutoutArcOffset,
cutoutArcOffset * 2 - ARC_HALF)
// Draw an arc for the right rounded corner circle. The bounding box is the area around the
// circle's center which is at (rightRoundedCornerCircleX, roundedCornerOffset).
shapePath.addArc(
rightRoundedCornerCircleX - roundedCornerOffset,
0f,
rightRoundedCornerCircleX + roundedCornerOffset,
roundedCornerOffset * 2,
ANGLE_UP - cornerRadiusArcLength,
cornerRadiusArcLength)
// Draw the ending line after the right rounded corner.
shapePath.lineTo(length, 0f)
}
}
| apache-2.0 | 1d60247f7163934105d21373c071d51b | 39.305732 | 100 | 0.672408 | 5.251452 | false | false | false | false |
Grannath/pardonas-bot | src/main/kotlin/de/grannath/pardona/BotConfiguration.kt | 1 | 3652 | package de.grannath.pardona
import org.springframework.boot.context.properties.ConfigurationProperties
import org.springframework.boot.context.properties.EnableConfigurationProperties
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.stereotype.Component
import sx.blah.discord.api.ClientBuilder
import sx.blah.discord.api.IDiscordClient
import sx.blah.discord.api.events.Event
import sx.blah.discord.api.events.IListener
import sx.blah.discord.handle.impl.events.ReadyEvent
import sx.blah.discord.handle.impl.events.guild.channel.message.MentionEvent
import sx.blah.discord.handle.impl.events.guild.channel.message.MessageEvent
import sx.blah.discord.handle.impl.events.guild.channel.message.MessageReceivedEvent
import java.util.regex.Pattern
@Configuration
@EnableConfigurationProperties
class BotConfiguration {
private val LOGGER by logger()
@Bean(destroyMethod = "logout")
fun discordClient(properties: DiscordProperties): IDiscordClient {
with(properties.token) {
LOGGER.info("Logging in at discord with token {}.",
replaceRange(5, length, "*".repeat(length - 5)))
}
val readyListener = IListener<ReadyEvent> {
LOGGER.info("I'm ready!")
}
val debugListener = IListener<Event> {
LOGGER.debug("Received event of type {}.", it.javaClass.name)
}
return ClientBuilder().withToken(properties.token)
.registerListeners(debugListener, readyListener)
.login()!!
}
@Bean
fun pingPongListener(client: IDiscordClient): IListener<MessageReceivedEvent> {
val listener = IListener<MessageReceivedEvent> {
if (it.message.content == "ping") {
it.message.reply("pong")
}
}
client.dispatcher.registerListener(listener)
return listener
}
}
@Component
class CommandListener(client: IDiscordClient,
val commands: List<Command>) {
init {
client.dispatcher.registerListener(getMentionListener())
client.dispatcher.registerListener(getPrivateListener())
}
private val LOGGER by logger()
private val splitPattern = Pattern.compile("\\p{Blank}+")
private fun getMentionListener() = IListener<MentionEvent> {
if (!it.channel.isPrivate) {
handleIfCommand(it)
}
}
private fun getPrivateListener() = IListener<MessageReceivedEvent> {
if (it.channel.isPrivate) {
handleIfCommand(it)
}
}
private fun handleIfCommand(event: MessageEvent) {
LOGGER.debug("I'm mentioned in {}.", event.message.content)
val split = event.message.content.split(splitPattern).filterIndexed { index, string ->
index != 0 || !string.startsWith("<@")
}
commands.find { it.canHandle(split[0]) }.apply {
if (this == null)
return
LOGGER.debug("Found keyword {}.", split[0])
if (event.channel.isPrivate) {
event.channel.sendMessage(buildReply(split.subList(1, split.size)))
} else {
event.message.reply(buildReply(split.subList(1, split.size)))
}
}
}
}
interface Command {
fun canHandle(keyword: String): Boolean
fun buildReply(args: List<String>): String
}
@ConfigurationProperties("discord")
@Component
class DiscordProperties(var token: String = "",
var clientId: String = "",
var permissions: Int = 0) | bsd-2-clause | d491e259ea3f93df5238830e977b769c | 32.824074 | 94 | 0.657722 | 4.628644 | false | true | false | false |
MimiReader/mimi-reader | mimi-app/src/main/java/com/emogoth/android/phone/mimi/util/GalleryScrollReceiver.kt | 1 | 1719 | package com.emogoth.android.phone.mimi.util
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.util.Log
import io.reactivex.BackpressureStrategy
import io.reactivex.Flowable
import io.reactivex.FlowableEmitter
import io.reactivex.disposables.Disposable
class GalleryScrollReceiver(val boardName: String, val threadId: Long, val positionChangedListener: ((Long) -> (Unit))) : BroadcastReceiver() {
var scrollPositionEmitter: FlowableEmitter<Long>? = null
var scrollPositionObserver: Disposable? = null
val intentFilter: String
get() = createIntentFilter(boardName, threadId)
var id: Long = 0
init {
val flowable: Flowable<Long> = Flowable.create({
scrollPositionEmitter = it
}, BackpressureStrategy.DROP)
scrollPositionObserver = flowable.subscribe({
positionChangedListener.invoke(it)
}, {
Log.e("GalleryScrollReceiver", "Error running GalleryScrollReceiver", it)
})
}
public fun destroy() {
RxUtil.safeUnsubscribe(scrollPositionObserver)
}
override fun onReceive(context: Context?, intent: Intent?) {
if (intent?.extras?.containsKey(SCROLL_ID_FLAG) == true) {
id = intent.extras?.getLong(SCROLL_ID_FLAG) ?: -1
scrollPositionEmitter?.onNext(id)
}
}
companion object {
const val SCROLL_ID_FLAG = "gallery_scroll_position"
private const val SCROLL_INTENT_FILTER = "gallery_scrolled_event"
fun createIntentFilter(boardName: String, threadId: Long): String {
return "${boardName}_${threadId}_${SCROLL_INTENT_FILTER}"
}
}
} | apache-2.0 | eebae42e32537403c52d585bb61bb23b | 31.45283 | 143 | 0.683537 | 4.671196 | false | false | false | false |
soywiz/korge | korge/src/jvmTest/kotlin/com/soywiz/korge/debug/KoruiSample1.kt | 1 | 5298 | package com.soywiz.korge.debug
import com.soywiz.korim.bitmap.*
import com.soywiz.korim.color.*
import com.soywiz.korma.geom.*
import com.soywiz.korma.geom.vector.*
import com.soywiz.korui.*
import com.soywiz.korui.layout.*
import com.soywiz.korui.layout.Size
import com.soywiz.korui.native.*
object KoruiSample2 {
@JvmStatic
fun main(args: Array<String>) {
val window = DEFAULT_UI_FACTORY.createWindow()
val scrollPanel = DEFAULT_UI_FACTORY.createScrollPanel()
val button = DEFAULT_UI_FACTORY.createButton()
button.bounds = RectangleInt(0, 0, 400, 250)
scrollPanel.insertChildAt(-1, button)
scrollPanel.bounds = RectangleInt(0, 0, 300, 300)
window.insertChildAt(-1, scrollPanel)
//window.insertChildAt(-1, button)
window.bounds = RectangleInt(0, 0, 600, 600)
window.visible = true
}
}
/*
object KoruiSample1 {
@JvmStatic
fun main(args: Array<String>) {
/*
val window = defaultKoruiFactory.createWindow()
val button = defaultKoruiFactory.createButton()
defaultKoruiFactory.setBounds(window, 16, 16, 600, 600)
defaultKoruiFactory.setBounds(button, 16, 16, 320, 100)
defaultKoruiFactory.setText(button, "hello")
defaultKoruiFactory.setParent(button, window)
defaultKoruiFactory.setVisible(window, true)
*/
UiApplication(DEFAULT_UI_FACTORY).window(600, 600) {
val crossIcon = NativeImage(16, 16).context2d {
stroke(Colors.RED, lineWidth = 3.0) {
line(0, 0, 16 - 1.5, 16 - 1.5)
line(16 - 1.5, 0, 0, 16 - 1.5)
}
}
menu = UiMenu(listOf(UiMenuItem("hello", listOf(UiMenuItem("world", icon = crossIcon))), UiMenuItem("world")))
layout = UiFillLayout
scrollPanel(xbar = false, ybar = true) {
//run {
layout = VerticalUiLayout
focusable = true
layoutChildrenPadding = 8
//var checked by state { false }
var checked = true
//val checked by ObservableProperty(false)
//var checked: Boolean by ObservableProperty(false)
//var checked2: Boolean by ObservableProperty(false)
println("checked: $checked")
onClick {
focus()
}
//vertical {
run {
//toolbar {
// button("1") { }
// button("2") { }
// button("3") { }
//}
canvas(NativeImage(128, 128).context2d {
stroke(Colors.WHITE, lineWidth = 3.0) {
line(0, 0, 128 - 1.5, 128 - 1.5)
line(128 - 1.5, 0, 0, 128 - 1.5)
}
}) {
}
checkBox("hello", checked = checked) {
//enabled = false
bounds = RectangleInt(16, 16, 320, 32)
onClick {
checked = !checked
//checked = false
//checked = true
}
}
button("save", {
bounds = RectangleInt(16, 64, 320, 32)
}) {
this.showPopupMenu(listOf(UiMenuItem("HELLO", icon = crossIcon)))
}
lateinit var props: UiContainer
button("Properties") {
props.visible = !props.visible
}
props = vertical {
addChild(UiRowEditableValue(app, "position", UiTwoItemEditableValue(app, UiNumberEditableValue(app, 0.0, -1000.0, +1000.0, decimalPlaces = 0), UiNumberEditableValue(app, 0.0, -1000.0, +1000.0))))
addChild(UiRowEditableValue(app, "ratio", UiNumberEditableValue(app, 0.0, min = 0.0, max = 1.0, clampMin = true, clampMax = true)))
addChild(UiRowEditableValue(app, "y", UiListEditableValue(app, listOf("hello", "world"), "world")))
}
tree {
minimumSize = Size(32.pt, 128.pt)
nodeRoot = SimpleUiTreeNode("hello",
(0 until 40).map { SimpleUiTreeNode("world$it") }
)
}
lateinit var vert: UiContainer
label("DEMO") {
icon = crossIcon
onClick {
vert.visible = !vert.visible
icon = if (vert.visible) crossIcon else null
}
}
vert = vertical {
label("HELLO") {}
label("WORLD") {}
button("test")
label("LOL") {}
}
button("TEST") {
}
}
}
}
}
}
*/
| apache-2.0 | cf018e87f3866db562e12ec905e8c055 | 36.842857 | 219 | 0.459419 | 4.914657 | false | false | false | false |
openstreetview/android | app/src/main/java/com/telenav/osv/data/collector/phonedata/collector/BatteryCollector.kt | 1 | 3940 | package com.telenav.osv.data.collector.phonedata.collector
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.BatteryManager
import android.os.Handler
import com.telenav.osv.data.collector.datatype.datatypes.BatteryObject
import com.telenav.osv.data.collector.datatype.util.LibraryUtil
import com.telenav.osv.data.collector.phonedata.manager.PhoneDataListener
/**
* BatteryCollector collects the information about battery status
* It registers a broadcastReceiver in order to monitoring the battery state
*/
class BatteryCollector(private val context: Context, phoneDataListener: PhoneDataListener?, notifyHandler: Handler?) : PhoneCollector(phoneDataListener, notifyHandler) {
/**
* BroadcastReceiver used for detecting any changes on battery
*/
private var batteryBroadcastReceiver: BroadcastReceiver? = null
/**
* Field used to verify if the battery receiver was registerd or not
*/
private var isBatteryReceiverRegisterd = false
/**
* Register a [BroadcastReceiver] for monitoring the battery state.
* Every change of battery state will notify the receiver
*/
fun startCollectingBatteryData() {
if (!isBatteryReceiverRegisterd) {
batteryBroadcastReceiver = object : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
val batteryObject = BatteryObject(getBatteryLevel(intent), getBatteryState(intent), LibraryUtil.PHONE_SENSOR_READ_SUCCESS)
onNewSensorEvent(batteryObject)
}
}
val intentFilter = IntentFilter(Intent.ACTION_BATTERY_CHANGED)
context.registerReceiver(batteryBroadcastReceiver, intentFilter, null, notifyHandler)
isBatteryReceiverRegisterd = true
}
}
/**
* Retrieve the batery level of the device
*
* @param intent Intent used for extracting battery information
* @return The batery level
*/
fun getBatteryLevel(intent: Intent): Float {
val level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1)
val scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1)
return level / scale.toFloat() * 100
}
/**
* Retrieve the batery state (charging or not) of the device
*
* @param intent Intent used for extracting battery information
* @return The battery state
*/
fun getBatteryState(intent: Intent): String {
val state = intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1)
val isCharging = state == BatteryManager.BATTERY_STATUS_CHARGING || state == BatteryManager.BATTERY_STATUS_FULL
val charger = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1)
val usbCharger = charger == BatteryManager.BATTERY_PLUGGED_USB
val accCharger = charger == BatteryManager.BATTERY_PLUGGED_AC
val response = StringBuilder()
if (isCharging) {
response.append(CHARGING_MODE_ON)
if (usbCharger) {
response.append(USB_CHARGING)
} else if (accCharger) {
response.append(ACC_CHARGING)
}
} else {
response.append(CHARGING_MODE_OFF)
}
return response.toString()
}
fun unregisterReceiver() {
if (batteryBroadcastReceiver != null && isBatteryReceiverRegisterd) {
context.unregisterReceiver(batteryBroadcastReceiver)
isBatteryReceiverRegisterd = false
}
}
companion object {
/**
* BleConstants used for determine the battery state
*/
const val CHARGING_MODE_ON = "Battery is charging via "
const val CHARGING_MODE_OFF = "Battery is not charging"
const val USB_CHARGING = "USB"
const val ACC_CHARGING = "ACC"
}
} | lgpl-3.0 | 5663d550ac97d5c30de06882ec5dfaf8 | 38.41 | 169 | 0.677411 | 5.006353 | false | false | false | false |
ffc-nectec/FFC | ffc/src/main/kotlin/ffc/app/person/PersonAdapter.kt | 1 | 3770 | /*
* Copyright (c) 2018 NECTEC
* National Electronics and Computer Technology Center, Thailand
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ffc.app.person
import android.net.Uri
import android.support.v7.widget.RecyclerView
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.LinearLayout
import ffc.android.getString
import ffc.android.layoutInflater
import ffc.android.load
import ffc.app.R
import ffc.app.health.analyze.toIconTitlePair
import ffc.app.util.AdapterClickListener
import ffc.entity.Person
import kotlinx.android.synthetic.main.person_list_item.view.personAgeView
import kotlinx.android.synthetic.main.person_list_item.view.personDeadLabel
import kotlinx.android.synthetic.main.person_list_item.view.personImageView
import kotlinx.android.synthetic.main.person_list_item.view.personNameView
import kotlinx.android.synthetic.main.person_list_item.view.personStatus
import org.jetbrains.anko.dip
import timber.log.Timber
class PersonAdapter(
var persons: List<Person>,
var limit: Int = Int.MAX_VALUE,
onClickDsl: AdapterClickListener<Person>.() -> Unit
) : RecyclerView.Adapter<PersonAdapter.PersonHolder>() {
val listener = AdapterClickListener<Person>().apply(onClickDsl)
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): PersonHolder {
val view = parent.layoutInflater.inflate(R.layout.person_list_item, parent, false)
return PersonHolder(view)
}
override fun getItemCount(): Int {
Timber.d("person size ${persons.size}")
return persons.size.takeIf { it < limit } ?: limit
}
override fun onBindViewHolder(holder: PersonHolder, position: Int) {
holder.bind(persons[position], listener)
}
fun update(update: List<Person>) {
this.persons = update
notifyDataSetChanged()
}
class PersonHolder(view: View) : RecyclerView.ViewHolder(view) {
fun bind(person: Person, listener: AdapterClickListener<Person>) {
with(person) {
itemView.personNameView.text = name
itemView.personAgeView.text = "$age ปี"
itemView.personDeadLabel.visibility = if (isDead) View.VISIBLE else View.GONE
itemView.personImageView.setImageResource(R.drawable.ic_account_circle_black_24dp)
itemView.personStatus.removeAllViews()
person.healthAnalyze?.result?.filterValues { it.haveIssue }?.forEach {
val layoutParam = LinearLayout.LayoutParams(itemView.dip(16), itemView.dip(16)).apply {
marginStart = itemView.dip(4)
marginEnd = itemView.dip(4)
}
val pair = it.value.issue.toIconTitlePair() ?: return@forEach
itemView.personStatus.addView(ImageView(itemView.context).apply {
setImageResource(pair.first)
contentDescription = getString(pair.second)
}, layoutParam)
}
avatarUrl?.let { itemView.personImageView.load(Uri.parse(it)) }
listener.bindOnItemClick(itemView, person)
}
}
}
}
| apache-2.0 | 279b4af6d446fc49ec84361672a3d32a | 39.06383 | 107 | 0.688529 | 4.409836 | false | false | false | false |
BilledTrain380/sporttag-psa | app/psa-runtime-service/psa-service-standard/src/main/kotlin/ch/schulealtendorf/psa/service/standard/entity/CompetitorEntity.kt | 1 | 2436 | /*
* Copyright (c) 2017 by Nicolas Märchy
*
* This file is part of Sporttag PSA.
*
* Sporttag PSA 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.
*
* Sporttag PSA 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 Sporttag PSA. If not, see <http://www.gnu.org/licenses/>.
*
* Diese Datei ist Teil von Sporttag PSA.
*
* Sporttag PSA ist Freie Software: Sie können es unter den Bedingungen
* der GNU General Public License, wie von der Free Software Foundation,
* Version 3 der Lizenz oder (nach Ihrer Wahl) jeder späteren
* veröffentlichten Version, weiterverbreiten und/oder modifizieren.
*
* Sporttag PSA wird in der Hoffnung, dass es nützlich sein wird, aber
* OHNE JEDE GEWÄHRLEISTUNG, bereitgestellt; sogar ohne die implizite
* Gewährleistung der MARKTFÄHIGKEIT oder EIGNUNG FÜR EINEN BESTIMMTEN ZWECK.
* Siehe die GNU General Public License für weitere Details.
*
* Sie sollten eine Kopie der GNU General Public License zusammen mit diesem
* Programm erhalten haben. Wenn nicht, siehe <http://www.gnu.org/licenses/>.
*
*
*/
package ch.schulealtendorf.psa.service.standard.entity
import javax.persistence.CascadeType
import javax.persistence.Entity
import javax.persistence.GeneratedValue
import javax.persistence.GenerationType
import javax.persistence.Id
import javax.persistence.JoinColumn
import javax.persistence.ManyToOne
import javax.persistence.OneToMany
import javax.persistence.Table
import javax.validation.constraints.NotNull
/**
* @author nmaerchy
* @since 2.0.0
*/
@Entity
@Table(name = "COMPETITOR")
data class CompetitorEntity(
@Id
@NotNull
@GeneratedValue(strategy = GenerationType.IDENTITY)
var startnumber: Int? = null,
@NotNull
@ManyToOne
@JoinColumn(name = "fk_PARTICIPANT_id", referencedColumnName = "id")
var participant: ParticipantEntity = ParticipantEntity(),
@OneToMany(cascade = [CascadeType.ALL], mappedBy = "competitor")
var results: Set<ResultEntity> = setOf()
)
| gpl-3.0 | 09459627d0fcba7e0d548eee25d8016f | 33.657143 | 77 | 0.757626 | 4.355476 | false | false | false | false |
vanita5/twittnuker | twittnuker/src/main/kotlin/de/vanita5/twittnuker/fragment/media/ImagePageFragment.kt | 1 | 6916 | /*
* Twittnuker - Twitter client for Android
*
* Copyright (C) 2013-2017 vanita5 <[email protected]>
*
* This program incorporates a modified version of Twidere.
* Copyright (C) 2012-2017 Mariotaku Lee <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.vanita5.twittnuker.fragment.media
import android.content.ContentResolver
import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.net.Uri
import android.os.Bundle
import com.davemorrissey.labs.subscaleview.ImageSource
import com.davemorrissey.labs.subscaleview.SubsamplingScaleImageView
import com.davemorrissey.labs.subscaleview.decoder.SkiaImageDecoder
import org.mariotaku.ktextension.nextPowerOf2
import org.mariotaku.mediaviewer.library.CacheDownloadLoader
import org.mariotaku.mediaviewer.library.subsampleimageview.SubsampleImageViewerFragment
import de.vanita5.twittnuker.TwittnukerConstants.*
import de.vanita5.twittnuker.activity.MediaViewerActivity
import de.vanita5.twittnuker.model.ParcelableMedia
import de.vanita5.twittnuker.model.UserKey
import de.vanita5.twittnuker.util.UriUtils
import de.vanita5.twittnuker.util.media.MediaExtra
import java.io.IOException
import java.lang.ref.WeakReference
class ImagePageFragment : SubsampleImageViewerFragment() {
private val media: ParcelableMedia?
get() = arguments.getParcelable<ParcelableMedia?>(EXTRA_MEDIA)
private val accountKey: UserKey?
get() = arguments.getParcelable<UserKey?>(EXTRA_ACCOUNT_KEY)
private val sizedResultCreator: CacheDownloadLoader.ResultCreator by lazy {
return@lazy SizedResultCreator(context)
}
private var mediaLoadState: Int = 0
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
}
override fun setUserVisibleHint(isVisibleToUser: Boolean) {
super.setUserVisibleHint(isVisibleToUser)
if (isVisibleToUser) {
activity?.invalidateOptionsMenu()
}
}
override fun getDownloadUri(): Uri? {
return media?.media_url?.let(Uri::parse)
}
override fun getDownloadExtra(): Any? {
val mediaExtra = MediaExtra()
mediaExtra.accountKey = accountKey
mediaExtra.fallbackUrl = media?.preview_url
mediaExtra.isSkipUrlReplacing = mediaExtra.fallbackUrl != downloadUri?.toString()
return mediaExtra
}
override fun hasDownloadedData(): Boolean {
return super.hasDownloadedData() && mediaLoadState != State.ERROR
}
override fun onMediaLoadStateChange(@State state: Int) {
mediaLoadState = state
if (userVisibleHint) {
activity?.invalidateOptionsMenu()
}
}
override fun setupImageView(imageView: SubsamplingScaleImageView) {
imageView.maxScale = resources.displayMetrics.density
imageView.setBitmapDecoderClass(PreviewBitmapDecoder::class.java)
imageView.setParallelLoadingEnabled(true)
imageView.setOnClickListener {
val activity = activity as? MediaViewerActivity ?: return@setOnClickListener
activity.toggleBar()
}
}
override fun getImageSource(data: CacheDownloadLoader.Result): ImageSource {
assert(data.cacheUri != null)
if (data !is SizedResult) {
return super.getImageSource(data)
}
val imageSource = ImageSource.uri(data.cacheUri!!)
imageSource.tilingEnabled()
imageSource.dimensions(data.width, data.height)
return imageSource
}
override fun getPreviewImageSource(data: CacheDownloadLoader.Result): ImageSource? {
if (data !is SizedResult) return null
assert(data.cacheUri != null)
return ImageSource.uri(UriUtils.appendQueryParameters(data.cacheUri, QUERY_PARAM_PREVIEW, true))
}
override fun getResultCreator(): CacheDownloadLoader.ResultCreator? {
return sizedResultCreator
}
internal class SizedResult(cacheUri: Uri, val width: Int, val height: Int) : CacheDownloadLoader.Result(cacheUri, null)
internal class SizedResultCreator(context: Context) : CacheDownloadLoader.ResultCreator {
private val weakContext = WeakReference(context)
override fun create(uri: Uri): CacheDownloadLoader.Result {
val context = weakContext.get() ?: return CacheDownloadLoader.Result.getInstance(InterruptedException())
val o = BitmapFactory.Options()
o.inJustDecodeBounds = true
try {
decodeBitmap(context.contentResolver, uri, o)
} catch (e: IOException) {
return CacheDownloadLoader.Result.getInstance(uri)
}
if (o.outWidth > 0 && o.outHeight > 0) {
return SizedResult(uri, o.outWidth, o.outHeight)
}
return CacheDownloadLoader.Result.getInstance(uri)
}
}
class PreviewBitmapDecoder : SkiaImageDecoder() {
@Throws(Exception::class)
override fun decode(context: Context, uri: Uri): Bitmap {
if (AUTHORITY_TWITTNUKER_CACHE == uri.authority && uri.getBooleanQueryParameter(QUERY_PARAM_PREVIEW, false)) {
val o = BitmapFactory.Options()
o.inJustDecodeBounds = true
o.inPreferredConfig = Bitmap.Config.RGB_565
val cr = context.contentResolver
decodeBitmap(cr, uri, o)
val dm = context.resources.displayMetrics
val targetSize = Math.min(1024, Math.max(dm.widthPixels, dm.heightPixels))
val sizeRatio = Math.ceil(Math.max(o.outHeight, o.outWidth) / targetSize.toDouble())
o.inSampleSize = Math.max(1.0, sizeRatio).toInt().nextPowerOf2
o.inJustDecodeBounds = false
return decodeBitmap(cr, uri, o) ?: throw IOException()
}
return super.decode(context, uri)
}
}
companion object {
@Throws(IOException::class)
internal fun decodeBitmap(cr: ContentResolver, uri: Uri, o: BitmapFactory.Options): Bitmap? {
cr.openInputStream(uri).use {
return BitmapFactory.decodeStream(it, null, o)
}
}
}
} | gpl-3.0 | 03c422db5aaac7d8c9b06cc54aea1678 | 37.21547 | 123 | 0.69144 | 4.84993 | false | false | false | false |
ajoz/kotlin-workshop | intro/src/main/kotlin/io/github/ajoz/workshop/intro/Sealeds.kt | 1 | 500 | package io.github.ajoz.workshop.intro
sealed class Option<out T> {
fun <R> map(f: (T) -> R): Option<R> = when (this) {
is None -> None
is Some -> Some(f(value))
}
abstract fun isEmpty(): Boolean
abstract fun isDefined(): Boolean
}
data class Some<out T>(val value: T) : Option<T>() {
override fun isDefined() = true
override fun isEmpty() = false
}
object None : Option<Nothing>() {
override fun isDefined() = false
override fun isEmpty() = true
} | apache-2.0 | 072253e5ab6f4d54570cda02bef6654f | 21.772727 | 55 | 0.612 | 3.546099 | false | false | false | false |
mihmuh/IntelliJConsole | Konsole/src/com/intellij/idekonsole/results/KAnalyzeStacktraceDialog.kt | 1 | 1472 | package com.intellij.idekonsole.results
import com.intellij.ide.IdeBundle
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.DialogWrapper
import com.intellij.unscramble.AnalyzeStacktraceDialog
import com.intellij.unscramble.AnalyzeStacktraceUtil
import java.awt.BorderLayout
import javax.swing.JComponent
import javax.swing.JLabel
import javax.swing.JPanel
/**
* @author simon
*/
class KAnalyzeStacktraceDialog : DialogWrapper {
val project: Project
val text : String
lateinit var myEditorPanel: AnalyzeStacktraceUtil.StacktraceEditorPanel
constructor(project: Project, text:String) : super(project, true) {
this.project = project
this.text = text
this.title = IdeBundle.message("unscramble.dialog.title", *arrayOfNulls<Any>(0))
this.init()
}
override fun createCenterPanel(): JComponent? {
val var1 = JPanel(BorderLayout())
var1.add(JLabel("Stacktrace:"), "North")
this.myEditorPanel = AnalyzeStacktraceUtil.createEditorPanel(this.project, this.myDisposable)
this.myEditorPanel.text = text
var1.add(this.myEditorPanel, "Center")
return var1
}
override fun doOKAction() {
AnalyzeStacktraceUtil.addConsole(this.project, null, "<Stacktrace>", this.myEditorPanel.text)
super.doOKAction()
}
override fun getPreferredFocusedComponent(): JComponent? {
return this.myEditorPanel.editorComponent
}
} | gpl-3.0 | e2711a54636516dbba0c98e512500c4c | 31.733333 | 101 | 0.728261 | 4.474164 | false | false | false | false |
Undin/intellij-rust | src/main/kotlin/org/rust/ide/inspections/RsWrongGenericParametersNumberInspection.kt | 2 | 2367 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.inspections
import com.intellij.openapi.util.text.StringUtil
import org.rust.lang.core.psi.RsFunction
import org.rust.lang.core.psi.RsTypeAlias
import org.rust.lang.core.psi.RsVisitor
import org.rust.lang.core.psi.ext.*
import org.rust.lang.utils.RsDiagnostic
import org.rust.lang.utils.addToHolder
/**
* Inspection that detects the E0049 error.
*/
class RsWrongGenericParametersNumberInspection : RsLocalInspectionTool() {
override fun buildVisitor(holder: RsProblemsHolder, isOnTheFly: Boolean): RsVisitor = object : RsVisitor() {
override fun visitFunction(function: RsFunction) {
checkParameters(holder, function, "type") { typeParameters }
checkParameters(holder, function, "const") { constParameters }
}
override fun visitTypeAlias(alias: RsTypeAlias) {
checkParameters(holder, alias, "type") { typeParameters }
checkParameters(holder, alias, "const") { constParameters }
}
}
private fun <T> checkParameters(
holder: RsProblemsHolder,
item: T,
paramType: String,
getParameters: RsGenericDeclaration.() -> List<RsGenericParameter>
) where T : RsAbstractable, T : RsGenericDeclaration {
val itemName = item.name ?: return
val itemType = when (item) {
is RsFunction -> "Method"
is RsTypeAlias -> "Type"
else -> return
}
val superItem = item.superItem as? RsGenericDeclaration ?: return
val toHighlight = item.typeParameterList ?: item.nameIdentifier ?: return
val typeParameters = item.getParameters()
val superTypeParameters = superItem.getParameters()
if (typeParameters.size == superTypeParameters.size) return
val paramName = "$paramType ${StringUtil.pluralize("parameter", typeParameters.size)}"
val superParamName = "$paramType ${StringUtil.pluralize("parameter", superTypeParameters.size)}"
val problemText = "$itemType `$itemName` has ${typeParameters.size} $paramName " +
"but its trait declaration has ${superTypeParameters.size} $superParamName"
RsDiagnostic.WrongNumberOfGenericParameters(toHighlight, problemText).addToHolder(holder)
}
}
| mit | af99ceb9ad8831e6cab6c50ce4ec9abd | 40.526316 | 112 | 0.690325 | 4.880412 | false | false | false | false |