repo_name
stringlengths
7
79
path
stringlengths
8
206
copies
stringclasses
36 values
size
stringlengths
2
6
content
stringlengths
55
523k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
7.18
99.5
line_max
int64
16
979
alpha_frac
float64
0.3
0.87
ratio
float64
2.01
8.07
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
brandonpas/Set-list
app/src/main/java/com/gmail/pasquarelli/brandon/setlist/tab_setlists/view/SetListFragment.kt
1
4684
package com.gmail.pasquarelli.brandon.setlist.tab_setlists.view import android.os.Bundle import android.support.v4.app.Fragment import android.support.v7.widget.LinearLayoutManager 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.Toast import com.gmail.pasquarelli.brandon.setlist.R import com.gmail.pasquarelli.brandon.setlist.SetListApplication import com.gmail.pasquarelli.brandon.setlist.tab_setlists.model.SetList import com.gmail.pasquarelli.brandon.setlist.tab_setlists.viewmodel.SetListsViewModel import io.reactivex.CompletableObserver import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.disposables.CompositeDisposable import io.reactivex.disposables.Disposable import io.reactivex.schedulers.Schedulers import kotlinx.android.synthetic.main.set_lists_layout.* import timber.log.Timber class SetListFragment: Fragment() { // ViewModels lateinit var setListsViewModel: SetListsViewModel // Views and adapters var listView: RecyclerView? = null var button: Button? = null lateinit var listAdapter: SetListAdapter // RxJava lateinit var compDisposable: CompositeDisposable override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? { return inflater?.inflate(R.layout.set_lists_layout, container, false) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setListsViewModel = (activity.application as SetListApplication).setListsViewModel } override fun onResume() { super.onResume() initViews() bind() } override fun onPause() { super.onPause() unbind() } fun initViews() { listView = setListRecyclerview listAdapter = SetListAdapter(setListsViewModel) listView?.adapter = listAdapter listView?.layoutManager = LinearLayoutManager(context) // Test Button; just to provide an example of using RxJava and observables button = test_button button?.setOnClickListener { Timber.v("main thread ${Thread.currentThread().id}") setListsViewModel.addTestData() .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(SetListSaveResult()) } } /** * Subscribe to any observables that the [SetListFragment] needs. */ fun bind() { Timber.v("bind() called") compDisposable = CompositeDisposable() compDisposable.add(setListsViewModel.getTestVMArray() .subscribeOn(Schedulers.computation()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(this::updateAdapter)) } /** * Clear all subscriptions. */ fun unbind() { Timber.v("unbind() called") compDisposable.dispose() } /** * Callback for when the [setListsViewModel] array is updated (observable emits a change). */ fun updateAdapter(list: MutableList<SetList>){ Timber.v("updateAdapter() called") listAdapter.notifyDataSetChanged() } /** * Standard API to display a toast message * * @param message String to be displayed in the Toast message * @param duration Either [Toast.LENGTH_LONG] or [Toast.LENGTH_SHORT] */ fun displayToast(message: String, duration: Int) { Toast.makeText(activity, message, duration).show() } /** * An observer to be used when saving a new set list. Use as a callback to do something when the new list is saved * or encounters an error while saving. */ inner class SetListSaveResult : CompletableObserver { // Callback for when the setListsViewModel addTestData() method is called and the Completable completes successfully. override fun onComplete() { Timber.v("Saved on background thread; now back on main thread. Thread ${Thread.currentThread().id}") } override fun onSubscribe(d: Disposable) {} // Callback for when the setListsViewModel addTestData() method is called and the Completable encounters an error. override fun onError(e: Throwable) { Timber.v("Error on background thread; now back on main thread. Thread ${Thread.currentThread().id}") Timber.v("Error Message: ${e.message}") displayToast("Gracefully encountered error while saving.", Toast.LENGTH_LONG) } } }
gpl-3.0
27124e6b052f0e5e5dda9f44492bf22f
34.763359
138
0.688301
4.925342
false
false
false
false
ccomeaux/boardgamegeek4android
app/src/main/java/com/boardgamegeek/ui/viewmodel/CollectionViewViewModel.kt
1
14810
package com.boardgamegeek.ui.viewmodel import android.app.Application import android.content.SharedPreferences import androidx.core.content.pm.ShortcutManagerCompat import androidx.core.os.bundleOf import androidx.lifecycle.* import com.boardgamegeek.BggApplication import com.boardgamegeek.entities.CollectionItemEntity import com.boardgamegeek.entities.CollectionViewEntity import com.boardgamegeek.entities.CollectionViewFilterEntity import com.boardgamegeek.extensions.* import com.boardgamegeek.extensions.CollectionView.DEFAULT_DEFAULT_ID import com.boardgamegeek.filterer.CollectionFilterer import com.boardgamegeek.filterer.CollectionFiltererFactory import com.boardgamegeek.livedata.Event import com.boardgamegeek.provider.BggContract import com.boardgamegeek.repository.CollectionItemRepository import com.boardgamegeek.repository.CollectionViewRepository import com.boardgamegeek.repository.PlayRepository import com.boardgamegeek.sorter.CollectionSorterFactory import com.boardgamegeek.ui.CollectionActivity import com.google.firebase.analytics.FirebaseAnalytics import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import java.util.concurrent.TimeUnit class CollectionViewViewModel(application: Application) : AndroidViewModel(application) { private val firebaseAnalytics = FirebaseAnalytics.getInstance(getApplication()) private val viewRepository = CollectionViewRepository(getApplication()) private val itemRepository = CollectionItemRepository(getApplication()) private val playRepository = PlayRepository(getApplication()) private val prefs: SharedPreferences by lazy { application.preferences() } val defaultViewId get() = prefs[CollectionView.PREFERENCES_KEY_DEFAULT_ID, DEFAULT_DEFAULT_ID] ?: DEFAULT_DEFAULT_ID private val collectionFiltererFactory: CollectionFiltererFactory by lazy { CollectionFiltererFactory(application) } private val collectionSorterFactory: CollectionSorterFactory by lazy { CollectionSorterFactory(application) } private val syncTimestamp = MutableLiveData<Long>() private val viewsTimestamp = MutableLiveData<Long>() private val _sortType = MutableLiveData<Int>() private val _addedFilters = MutableLiveData<List<CollectionFilterer>>() private val _removedFilterTypes = MutableLiveData<List<Int>>() private val _effectiveSortType = MediatorLiveData<Int>() val effectiveSortType: LiveData<Int> get() = _effectiveSortType private val _effectiveFilters = MediatorLiveData<List<CollectionFilterer>>() val effectiveFilters: LiveData<List<CollectionFilterer>> get() = _effectiveFilters private val _items = MediatorLiveData<List<CollectionItemEntity>>() val items: LiveData<List<CollectionItemEntity>> get() = _items private val _allItems: LiveData<List<CollectionItemEntity>> = syncTimestamp.switchMap { liveData { try { emit(itemRepository.load()) _isRefreshing.postValue(true) itemRepository.refresh() emit(itemRepository.load()) } catch (e: Exception) { _errorMessage.postValue(Event(e.localizedMessage.ifEmpty { "Error loading collection" })) } finally { _isRefreshing.postValue(false) } } } private val _errorMessage = MediatorLiveData<Event<String>>() val errorMessage: LiveData<Event<String>> get() = _errorMessage private val _isFiltering = MediatorLiveData<Boolean>() val isFiltering: LiveData<Boolean> get() = _isFiltering private val _isRefreshing = MediatorLiveData<Boolean>() val isRefreshing: LiveData<Boolean> get() = _isRefreshing private val _selectedViewId = MutableLiveData<Long>() val selectedViewId: LiveData<Long> get() = _selectedViewId val views: LiveData<List<CollectionViewEntity>> = viewsTimestamp.switchMap { liveData { emit(viewRepository.load()) } } private val selectedView: LiveData<CollectionViewEntity> = _selectedViewId.switchMap { liveData { _sortType.value = CollectionSorterFactory.TYPE_UNKNOWN _addedFilters.value = emptyList() _removedFilterTypes.value = emptyList() emit(viewRepository.load(it)) } } val selectedViewName: LiveData<String> = selectedView.map { it.name } init { refreshViews() viewModelScope.launch { initMediators() } _selectedViewId.value = defaultViewId } private suspend fun initMediators() = withContext(Dispatchers.Default) { _effectiveSortType.addSource(selectedView) { createEffectiveSort(it, _sortType.value) } _effectiveSortType.addSource(_sortType) { createEffectiveSort(selectedView.value, it) } _effectiveFilters.addSource(selectedView) { createEffectiveFilters( it, _addedFilters.value.orEmpty(), _removedFilterTypes.value.orEmpty() ) } _effectiveFilters.addSource(_addedFilters) { createEffectiveFilters( selectedView.value, it, _removedFilterTypes.value.orEmpty() ) } _effectiveFilters.addSource(_removedFilterTypes) { createEffectiveFilters( selectedView.value, _addedFilters.value.orEmpty(), it ) } _items.addSource(effectiveFilters) { filterAndSortItems(filters = it) } _items.addSource(effectiveSortType) { filterAndSortItems(sortType = it) } _items.addSource(_allItems) { filterAndSortItems(itemList = it.orEmpty()) } } fun selectView(viewId: Long) { if (_selectedViewId.value != viewId) { _isFiltering.postValue(true) viewModelScope.launch { viewRepository.updateShortcuts(viewId) } _selectedViewId.value = viewId } } fun findViewId(viewName: String) = views.value?.find { it.name == viewName }?.id ?: BggContract.INVALID_ID.toLong() fun setSort(sortType: Int) { val type = when (sortType) { CollectionSorterFactory.TYPE_UNKNOWN -> CollectionSorterFactory.TYPE_DEFAULT else -> sortType } if (_sortType.value != type) { _isFiltering.postValue(true) _sortType.value = type } } fun addFilter(filter: CollectionFilterer) { viewModelScope.launch(Dispatchers.Default) { _isFiltering.postValue(true) if (filter.isValid) { val removedFilters = _removedFilterTypes.value.orEmpty().toMutableList() if (removedFilters.remove(filter.type)) { _removedFilterTypes.postValue(removedFilters) } val filters = _addedFilters.value.orEmpty().toMutableList() filters.apply { remove(filter) add(filter) } firebaseAnalytics.logEvent( "Filter", bundleOf( FirebaseAnalytics.Param.CONTENT_TYPE to "Collection", "FilterBy" to filter.type.toString() ) ) _addedFilters.postValue(filters) } } } fun removeFilter(type: Int) { viewModelScope.launch(Dispatchers.Default) { _isFiltering.postValue(true) val filters = _addedFilters.value.orEmpty().toMutableList() filters.find { it.type == type }?.let { if (filters.remove(it)) { _addedFilters.postValue(filters) } } val removedFilters = _removedFilterTypes.value.orEmpty().toMutableList() removedFilters.apply { remove(type) add(type) } _removedFilterTypes.postValue(removedFilters) } } private fun createEffectiveFilters( loadedView: CollectionViewEntity?, addedFilters: List<CollectionFilterer>, removedFilterTypes: List<Int> ) { viewModelScope.launch(Dispatchers.Default) { // inflate filters val loadedFilters = mutableListOf<CollectionFilterer>() for ((type, data) in loadedView?.filters.orEmpty()) { val filter = collectionFiltererFactory.create(type) filter?.inflate(data) if (filter?.isValid == true) { loadedFilters.add(filter) } } val addedTypes = addedFilters.map { af -> af.type } val filters: MutableList<CollectionFilterer> = mutableListOf() loadedFilters.forEach { lf -> if (!addedTypes.contains(lf.type) && !removedFilterTypes.contains(lf.type)) filters.add(lf) } addedFilters.forEach { af -> if (!removedFilterTypes.contains(af.type)) filters.add(af) } _effectiveFilters.postValue(filters) } } private fun createEffectiveSort(loadedView: CollectionViewEntity?, sortType: Int?) { _effectiveSortType.value = if (sortType == null || sortType == CollectionSorterFactory.TYPE_UNKNOWN) { loadedView?.sortType ?: CollectionSorterFactory.TYPE_DEFAULT } else { sortType } } private fun filterAndSortItems( itemList: List<CollectionItemEntity>? = _allItems.value, filters: List<CollectionFilterer> = effectiveFilters.value.orEmpty(), sortType: Int = effectiveSortType.value ?: CollectionSorterFactory.TYPE_DEFAULT, ) { if (itemList == null) return viewModelScope.launch(Dispatchers.Default) { var list = itemList.asSequence() if (_selectedViewId.value == DEFAULT_DEFAULT_ID && filters.none { it.type == CollectionFiltererFactory.TYPE_STATUS }) { list = list.filter { (prefs.isStatusSetToSync(COLLECTION_STATUS_OWN) && it.own) || (prefs.isStatusSetToSync(COLLECTION_STATUS_PREVIOUSLY_OWNED) && it.previouslyOwned) || (prefs.isStatusSetToSync(COLLECTION_STATUS_FOR_TRADE) && it.forTrade) || (prefs.isStatusSetToSync(COLLECTION_STATUS_WANT_IN_TRADE) && it.wantInTrade) || (prefs.isStatusSetToSync(COLLECTION_STATUS_WANT_TO_BUY) && it.wantToPlay) || (prefs.isStatusSetToSync(COLLECTION_STATUS_WISHLIST) && it.wishList) || (prefs.isStatusSetToSync(COLLECTION_STATUS_WANT_TO_PLAY) && it.wantToPlay) || (prefs.isStatusSetToSync(COLLECTION_STATUS_PREORDERED) && it.preOrdered) || (prefs.isStatusSetToSync(COLLECTION_STATUS_PLAYED) && it.numberOfPlays > 1) || (prefs.isStatusSetToSync(COLLECTION_STATUS_RATED) && it.rating > 0.0) || (prefs.isStatusSetToSync(COLLECTION_STATUS_COMMENTED) && it.comment.isNotBlank()) || (prefs.isStatusSetToSync(COLLECTION_STATUS_HAS_PARTS) && it.hasPartsList.isNotBlank()) || (prefs.isStatusSetToSync(COLLECTION_STATUS_WANT_PARTS) && it.wantPartsList.isNotBlank()) }.asSequence() } filters.forEach { f -> list = list.filter { f.filter(it) }.asSequence() } val sorter = collectionSorterFactory.create(sortType) _items.postValue(sorter?.sort(list.toList()) ?: list.toList()) } } fun refresh(): Boolean { return if ((syncTimestamp.value ?: 0).isOlderThan(1, TimeUnit.MINUTES)) { syncTimestamp.postValue(System.currentTimeMillis()) true } else false } fun insert(name: String, isDefault: Boolean) { viewModelScope.launch { val view = CollectionViewEntity( id = 0L, //ignored name = name, sortType = effectiveSortType.value ?: CollectionSorterFactory.TYPE_DEFAULT, filters = effectiveFilters.value?.map { CollectionViewFilterEntity(it.type, it.deflate()) }, ) val viewId = viewRepository.insertView(view) refreshViews() setOrRemoveDefault(viewId, isDefault) selectView(viewId) } } fun update(isDefault: Boolean) { viewModelScope.launch { val view = CollectionViewEntity( id = _selectedViewId.value ?: BggContract.INVALID_ID.toLong(), name = selectedViewName.value.orEmpty(), sortType = effectiveSortType.value ?: CollectionSorterFactory.TYPE_DEFAULT, filters = effectiveFilters.value?.map { CollectionViewFilterEntity(it.type, it.deflate()) }, ) viewRepository.updateView(view) refreshViews() setOrRemoveDefault(view.id, isDefault) } } fun deleteView(viewId: Long) { viewModelScope.launch { viewRepository.deleteView(viewId) refreshViews() if (viewId == _selectedViewId.value) { selectView(defaultViewId) } } } private fun refreshViews() { viewsTimestamp.postValue(System.currentTimeMillis()) } fun logQuickPlay(gameId: Int, gameName: String) { viewModelScope.launch { playRepository.logQuickPlay(gameId, gameName) } } private fun setOrRemoveDefault(viewId: Long, isDefault: Boolean) { if (isDefault) { prefs[CollectionView.PREFERENCES_KEY_DEFAULT_ID] = viewId } else if (viewId == defaultViewId) { prefs.remove(CollectionView.PREFERENCES_KEY_DEFAULT_ID) } } fun createShortcut() { viewModelScope.launch(Dispatchers.Default) { val context = getApplication<BggApplication>().applicationContext val viewId = _selectedViewId.value ?: BggContract.INVALID_ID.toLong() val viewName = selectedViewName.value.orEmpty() if (ShortcutManagerCompat.isRequestPinShortcutSupported(context)) { val info = CollectionActivity.createShortcutInfo(context, viewId, viewName) ShortcutManagerCompat.requestPinShortcut(context, info, null) } } } }
gpl-3.0
34602a4b62634006f38f93a62d1ce917
39.244565
131
0.621945
5.016938
false
false
false
false
ccomeaux/boardgamegeek4android
app/src/main/java/com/boardgamegeek/ui/MechanicCollectionFragment.kt
1
3069
package com.boardgamegeek.ui import android.os.Bundle import android.view.* import androidx.core.view.isVisible import androidx.fragment.app.Fragment import androidx.fragment.app.activityViewModels import com.boardgamegeek.R import com.boardgamegeek.databinding.FragmentLinkedCollectionBinding import com.boardgamegeek.ui.adapter.LinkedCollectionAdapter import com.boardgamegeek.ui.viewmodel.MechanicViewModel import com.boardgamegeek.ui.viewmodel.MechanicViewModel.CollectionSort import java.util.* class MechanicCollectionFragment : Fragment() { private var _binding: FragmentLinkedCollectionBinding? = null private val binding get() = _binding!! private var sortType = CollectionSort.RATING private val adapter: LinkedCollectionAdapter by lazy { LinkedCollectionAdapter() } private val viewModel by activityViewModels<MechanicViewModel>() @Suppress("RedundantNullableReturnType") override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { _binding = FragmentLinkedCollectionBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) setHasOptionsMenu(true) binding.recyclerView.setHasFixedSize(true) binding.recyclerView.adapter = adapter binding.emptyMessage.text = getString(R.string.empty_linked_collection, getString(R.string.title_mechanic).lowercase(Locale.getDefault())) binding.swipeRefresh.setOnRefreshListener { viewModel.refresh() } viewModel.sort.observe(viewLifecycleOwner) { sortType = it activity?.invalidateOptionsMenu() } viewModel.collection.observe(viewLifecycleOwner) { adapter.items = it.orEmpty() binding.emptyMessage.isVisible = adapter.items.isEmpty() binding.recyclerView.isVisible = adapter.items.isNotEmpty() binding.swipeRefresh.isRefreshing = false binding.progressView.hide() } } override fun onDestroyView() { super.onDestroyView() _binding = null } override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { inflater.inflate(R.menu.linked_collection, menu) } override fun onPrepareOptionsMenu(menu: Menu) { menu.findItem( when (sortType) { CollectionSort.NAME -> R.id.menu_sort_name CollectionSort.RATING -> R.id.menu_sort_rating } )?.isChecked = true super.onPrepareOptionsMenu(menu) } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { R.id.menu_sort_name -> viewModel.setSort(CollectionSort.NAME) R.id.menu_sort_rating -> viewModel.setSort(CollectionSort.RATING) R.id.menu_refresh -> viewModel.refresh() else -> return super.onOptionsItemSelected(item) } return true } }
gpl-3.0
a52fb736f88f809ebe4674ba7cec5714
37.848101
146
0.703161
4.879173
false
false
false
false
WijayaPrinting/wp-javafx
openpss-client-javafx/src/com/hendraanggrian/openpss/ui/price/EditDigitalPriceDialog.kt
1
2194
package com.hendraanggrian.openpss.ui.price import com.hendraanggrian.openpss.FxComponent import com.hendraanggrian.openpss.R2 import com.hendraanggrian.openpss.api.OpenPSSApi import com.hendraanggrian.openpss.schema.DigitalPrice import javafx.beans.property.ReadOnlyDoubleWrapper import javafx.beans.value.ObservableValue import kotlinx.coroutines.CoroutineScope import ktfx.cells.textFieldCellFactory import ktfx.coroutines.onEditCommit import ktfx.text.buildStringConverter @Suppress("UNCHECKED_CAST") class EditDigitalPriceDialog( component: FxComponent ) : EditPriceDialog<DigitalPrice>(component, R2.string.digital_print_price) { init { getString(R2.string.one_side_price)<Double> { minWidth = 128.0 style = "-fx-alignment: center-right;" setCellValueFactory { ReadOnlyDoubleWrapper(it.value.oneSidePrice) as ObservableValue<Double> } textFieldCellFactory(buildStringConverter { fromString { it.toDoubleOrNull() ?: 0.0 } }) onEditCommit { cell -> val digital = cell.rowValue OpenPSSApi.editDigitalPrice(digital.apply { oneSidePrice = cell.newValue }) } } getString(R2.string.two_side_price)<Double> { minWidth = 128.0 style = "-fx-alignment: center-right;" setCellValueFactory { ReadOnlyDoubleWrapper(it.value.twoSidePrice) as ObservableValue<Double> } textFieldCellFactory(buildStringConverter { fromString { it.toDoubleOrNull() ?: 0.0 } }) onEditCommit { cell -> val digital = cell.rowValue OpenPSSApi.editDigitalPrice(digital.apply { twoSidePrice = cell.newValue }) } } } override suspend fun CoroutineScope.refresh(): List<DigitalPrice> = OpenPSSApi.getDigitalPrices() override suspend fun CoroutineScope.add(name: String): DigitalPrice? = OpenPSSApi.addDigitalPrice(DigitalPrice.new(name)) override suspend fun CoroutineScope.delete(selected: DigitalPrice): Boolean = OpenPSSApi.deleteDigitalPrice(selected.id) }
apache-2.0
90f6acd8deb38c7d6bc5e0996894de08
38.890909
107
0.678669
4.514403
false
false
false
false
wordpress-mobile/WordPress-Stores-Android
plugins/woocommerce/src/main/kotlin/org/wordpress/android/fluxc/persistence/dao/CouponsDao.kt
2
1874
package org.wordpress.android.fluxc.persistence.dao import androidx.room.Dao import androidx.room.Insert import androidx.room.OnConflictStrategy import androidx.room.Query import androidx.room.Transaction import kotlinx.coroutines.flow.Flow import org.wordpress.android.fluxc.persistence.entity.CouponEmailEntity import org.wordpress.android.fluxc.persistence.entity.CouponEntity import org.wordpress.android.fluxc.persistence.entity.CouponWithEmails @Dao interface CouponsDao { @Transaction @Query("SELECT * FROM Coupons WHERE siteId = :siteId ORDER BY dateCreated DESC") fun observeCoupons(siteId: Long): Flow<List<CouponWithEmails>> @Transaction @Query("SELECT * FROM Coupons " + "WHERE siteId = :siteId AND id IN (:couponIds) ORDER BY dateCreated DESC") suspend fun getCoupons(siteId: Long, couponIds: List<Long>): List<CouponWithEmails> @Transaction @Query("SELECT * FROM Coupons WHERE siteId = :siteId AND id = :couponId") fun observeCoupon(siteId: Long, couponId: Long): Flow<CouponWithEmails?> @Transaction @Query("SELECT * FROM Coupons WHERE siteId = :siteId AND id = :couponId") suspend fun getCoupon(siteId: Long, couponId: Long): CouponWithEmails? @Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun insertOrUpdateCoupon(entity: CouponEntity): Long @Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun insertOrUpdateCouponEmail(entity: CouponEmailEntity): Long @Query("DELETE FROM Coupons WHERE siteId = :siteId AND id = :couponId") suspend fun deleteCoupon(siteId: Long, couponId: Long) @Query("DELETE FROM Coupons WHERE siteId = :siteId") suspend fun deleteAllCoupons(siteId: Long) @Query("SELECT COUNT(*) FROM CouponEmails WHERE siteId = :siteId AND couponId = :couponId") suspend fun getEmailCount(siteId: Long, couponId: Long): Int }
gpl-2.0
28e486095d21808dc688a9ae779bbd84
39.73913
95
0.757204
3.936975
false
false
false
false
PKRoma/github-android
app/src/main/java/com/github/pockethub/android/ui/issue/IssuesViewActivity.kt
5
10658
/* * Copyright (c) 2015 PocketHub * * 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.github.pockethub.android.ui.issue import android.content.Intent import android.content.Intent.FLAG_ACTIVITY_CLEAR_TOP import android.content.Intent.FLAG_ACTIVITY_SINGLE_TOP import android.os.Bundle import android.view.MenuItem import com.github.pockethub.android.Intents.Builder import com.github.pockethub.android.Intents.EXTRA_ISSUE_NUMBERS import com.github.pockethub.android.Intents.EXTRA_POSITION import com.github.pockethub.android.Intents.EXTRA_REPOSITORIES import com.github.pockethub.android.Intents.EXTRA_REPOSITORY import com.github.pockethub.android.R import com.github.pockethub.android.core.issue.IssueStore import com.github.pockethub.android.core.issue.IssueUtils import com.github.pockethub.android.rx.AutoDisposeUtils import com.github.pockethub.android.ui.DialogResultListener import com.github.pockethub.android.ui.base.BaseActivity import com.github.pockethub.android.ui.helpers.PagerHandler import com.github.pockethub.android.ui.repo.RepositoryViewActivity import com.github.pockethub.android.ui.user.UriLauncherActivity import com.github.pockethub.android.util.InfoUtils import com.meisolsson.githubsdk.core.ServiceGenerator import com.meisolsson.githubsdk.model.Issue import com.meisolsson.githubsdk.model.Repository import com.meisolsson.githubsdk.model.User import com.meisolsson.githubsdk.service.repositories.RepositoryService import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.schedulers.Schedulers import kotlinx.android.synthetic.main.activity_pager.* import java.util.ArrayList import javax.inject.Inject /** * Activity to display a collection of issues or pull requests in a pager */ class IssuesViewActivity : BaseActivity(), DialogResultListener { @Inject lateinit var store: IssueStore private var issueNumbers: IntArray? = null private var pullRequests: BooleanArray? = null private var repoIds: ArrayList<Repository>? = null private var repo: Repository? = null private var user: User? = null private var canWrite: Boolean = false private var pagerHandler: PagerHandler<IssuesPagerAdapter>? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_pager) issueNumbers = intent.getIntArrayExtra(EXTRA_ISSUE_NUMBERS) pullRequests = intent.getBooleanArrayExtra(EXTRA_PULL_REQUESTS) repoIds = intent.getParcelableArrayListExtra(EXTRA_REPOSITORIES) repo = intent.getParcelableExtra(EXTRA_REPOSITORY) val actionBar = supportActionBar!! actionBar.setDisplayHomeAsUpEnabled(true) if (repo != null) { actionBar.subtitle = InfoUtils.createRepoId(repo!!) user = repo!!.owner() } // Load avatar if single issue and user is currently unset or missing // avatar URL if (repo == null) { val temp = if (repo != null) repo else repoIds!![0] ServiceGenerator.createService(this, RepositoryService::class.java) .getRepository(temp!!.owner()!!.login(), temp.name()) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .`as`(AutoDisposeUtils.bindToLifecycle(this)) .subscribe { response -> repositoryLoaded(response.body()!!) } } else { repositoryLoaded(repo!!) } } override fun onDestroy() { super.onDestroy() lifecycle.removeObserver(pagerHandler!!) } private fun repositoryLoaded(repo: Repository) { val permission = repo.permissions() canWrite = permission != null && (permission.admin()!! || permission.push()!!) invalidateOptionsMenu() configurePager() } private fun configurePager() { val initialPosition = intent.getIntExtra(EXTRA_POSITION, -1) val adapter = if (repo != null) { IssuesPagerAdapter(this, repo, issueNumbers, canWrite) } else { IssuesPagerAdapter(this, repoIds, issueNumbers, store, canWrite) } pagerHandler = PagerHandler(this, vp_pages, adapter) pagerHandler!!.onPagedChanged = this::onPageChange lifecycle.addObserver(pagerHandler!!) vp_pages.scheduleSetItem(initialPosition, pagerHandler) } private fun updateTitle(position: Int) { val number = issueNumbers!![position] val pullRequest = pullRequests!![position] supportActionBar!!.title = if (pullRequest) { getString(R.string.pull_request_title) + number } else { getString(R.string.issue_title) + number } } private fun onPageChange(position: Int) { if (repo != null) { updateTitle(position) return } if (repoIds == null) { return } val actionBar = supportActionBar!! repo = repoIds!![position] if (repo != null) { updateTitle(position) actionBar.subtitle = InfoUtils.createRepoId(repo!!) val issue = store.getIssue(repo, issueNumbers!![position]) if (issue != null) { val fullRepo = issue.repository() if (fullRepo?.owner() != null) { user = fullRepo.owner() } else { actionBar.setLogo(null) } } else { actionBar.setLogo(null) } } else { actionBar.subtitle = null actionBar.setLogo(null) } } override fun onDialogResult(requestCode: Int, resultCode: Int, arguments: Bundle) { pagerHandler!!.adapter .onDialogResult(vp_pages.currentItem, requestCode, resultCode, arguments) } override fun startActivity(intent: Intent) { val converted = UriLauncherActivity.convert(intent) if (converted != null) { super.startActivity(converted) } else { super.startActivity(intent) } } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { android.R.id.home -> { var repository = repo if (repository == null) { val position = vp_pages.currentItem val repoId = repoIds!![position] val issue = store.getIssue(repoId, issueNumbers!![position]) if (issue != null) { repository = issue.repository() } } if (repository != null) { val intent = RepositoryViewActivity.createIntent(repository) intent.addFlags(FLAG_ACTIVITY_CLEAR_TOP or FLAG_ACTIVITY_SINGLE_TOP) startActivity(intent) } return true } else -> return super.onOptionsItemSelected(item) } } companion object { private val EXTRA_PULL_REQUESTS = "pullRequests" /** * Create an intent to show a single issue * * @param issue * @return intent */ fun createIntent(issue: Issue): Intent { return createIntent(listOf(issue), 0) } /** * Create an intent to show issue * * @param issue * @param repository * @return intent */ fun createIntent(issue: Issue, repository: Repository): Intent { return createIntent(listOf(issue), repository, 0) } /** * Create an intent to show issues with an initial selected issue * * @param issues * @param repository * @param position * @return intent */ fun createIntent(issues: Collection<Issue>, repository: Repository, position: Int): Intent { val numbers = IntArray(issues.size) val pullRequests = BooleanArray(issues.size) for ((index, issue) in issues.withIndex()) { numbers[index] = issue.number()!! pullRequests[index] = IssueUtils.isPullRequest(issue) } return Builder("issues.VIEW").add(EXTRA_ISSUE_NUMBERS, numbers) .add(EXTRA_REPOSITORY, repository) .add(EXTRA_POSITION, position) .add(EXTRA_PULL_REQUESTS, pullRequests).toIntent() } /** * Create an intent to show issues with an initial selected issue * * @param issues * @param position * @return intent */ fun createIntent(issues: Collection<Issue>, position: Int): Intent { val count = issues.size val numbers = IntArray(count) val pullRequests = BooleanArray(count) val repos = ArrayList<Repository>(count) for ((index, issue) in issues.withIndex()) { numbers[index] = issue.number()!! pullRequests[index] = IssueUtils.isPullRequest(issue) var repoId: Repository? = null val issueRepo = issue.repository() if (issueRepo != null) { val owner = issueRepo.owner() if (owner != null) { repoId = InfoUtils.createRepoFromData(owner.login(), issueRepo.name()) } } if (repoId == null) { repoId = InfoUtils.createRepoFromUrl(issue.htmlUrl()) } repos.add(repoId!!) } val builder = Builder("issues.VIEW") builder.add(EXTRA_ISSUE_NUMBERS, numbers) builder.add(EXTRA_REPOSITORIES, repos) builder.add(EXTRA_POSITION, position) builder.add(EXTRA_PULL_REQUESTS, pullRequests) return builder.toIntent() } } }
apache-2.0
069ce22fd9e72e4a7266fa9d24519286
34.765101
94
0.610809
4.90023
false
false
false
false
FirebaseExtended/auth-without-play-services
app/src/main/java/com/google/firebase/nongmsauth/utils/IdTokenParser.kt
1
3188
/** * Copyright 2019 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.firebase.nongmsauth.utils import android.text.TextUtils import com.google.android.gms.common.util.Base64Utils import com.google.firebase.FirebaseException import org.json.JSONArray import org.json.JSONException import org.json.JSONObject import java.io.UnsupportedEncodingException import java.nio.charset.Charset class IdTokenParser { companion object { fun parseIdToken(idToken: String): Map<String, Any> { val parts = idToken.split(".").toList() if (parts.size < 2) { return mapOf() } val encodedToken = parts[1] return try { val decodedToken = String(Base64Utils.decodeUrlSafeNoPadding(encodedToken), Charset.defaultCharset()) parseRawUserInfo(decodedToken) ?: mapOf() } catch (e: UnsupportedEncodingException) { mapOf() } } @Throws(JSONException::class) fun toMap(json: JSONObject): Map<String, Any> { val map = mutableMapOf<String, Any>() val keyItr = json.keys() while (keyItr.hasNext()) { val key = keyItr.next() // Value can be a primitive, a map, or a list var value = json.get(key) if (value is JSONArray) { value = toList(value) } else if (value is JSONObject) { value = toMap(value) } map[key] = value } return map } @Throws(JSONException::class) fun toList(array: JSONArray): List<Any> { val list = mutableListOf<Any>() for (i in 0 until array.length()) { var value = array.get(i) if (value is JSONArray) { value = toList(value) } else if (value is JSONObject) { value = toMap(value) } list.add(value) } return list } private fun parseRawUserInfo(rawUserInfo: String): Map<String, Any>? { if (TextUtils.isEmpty(rawUserInfo)) { return null } try { val jsonObject = JSONObject(rawUserInfo) return if (jsonObject !== JSONObject.NULL) { toMap(jsonObject) } else { null } } catch (e: Exception) { throw FirebaseException(e.message!!) } } } }
apache-2.0
0c51b491b70ddd154b473caf0afd462a
30.564356
117
0.551443
4.744048
false
false
false
false
debop/debop4k
debop4k-timeperiod/src/main/kotlin/debop4k/timeperiod/calendars/DateAdd.kt
1
10794
/* * Copyright (c) 2016. Sunghyouk Bae <[email protected]> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package debop4k.timeperiod.calendars import debop4k.core.loggerOf import debop4k.timeperiod.* import debop4k.timeperiod.calendars.SeekBoundaryMode.Next import debop4k.timeperiod.timelines.TimeGapCalculator import org.joda.time.DateTime import org.joda.time.Duration /** * 특정 일자로부터 미래로(Forward)로 특정 기간을 이후의 일자를 계산합니다. * 특정 기간 산정을 탐색을 통해 수행합니다. * * @author [email protected] */ open class DateAdd { private val log = loggerOf(javaClass) companion object { @JvmStatic fun of(): DateAdd = DateAdd() } protected val _includePeriods: TimePeriodCollection = TimePeriodCollection() protected val _excludePeriods: TimePeriodCollection = TimePeriodCollection() open protected val includePeriods: TimePeriodCollection get() = _includePeriods open protected val excludePeriods: TimePeriodCollection get() = _excludePeriods /** * 시작 일자로부터 offset 기간이 지난 일자를 계산합니다. (기간에 포함될 기간과 제외할 기간을 명시적으로 지정해 놓을 수 있습니다.) * * @param start 시작 일자 * @param offset 기간 * @param seekBoundary 마지막 일자 포함 여부 * @return 시작 일자로부터 offset 기간 이후의 일자 */ @JvmOverloads open fun add(start: DateTime, offset: Duration, seekBoundary: SeekBoundaryMode = Next): DateTime? { log.debug("Add start={}, offset={}, seekBoundary={}", start, offset, seekBoundary) // 예외 조건이 없으면 단순 계산으로 처리 if (_includePeriods.isEmpty() && _excludePeriods.isEmpty()) { return start.plus(offset) } val end = if (offset < Duration.ZERO) calculateEnd(start, offset.negated(), SeekDirection.Backward, seekBoundary) else calculateEnd(start, offset, SeekDirection.Forward, seekBoundary) log.debug("Add Results. end={}, remaining={}", end.first, end.second) return end.first } /** * 시작 일자로부터 offset 기간 이전의 일자를 계산합니다. (기간에 포함될 기간과 제외할 기간을 명시적으로 지정해 놓을 수 있습니다.) * * @param start 시작 일자 * @param offset 기간 * @param seekBoundary 마지막 일자 포함 여부 * @return 시작 일자로부터 offset 기간 이전의 일자 */ @JvmOverloads open fun subtract(start: DateTime, offset: Duration, seekBoundary: SeekBoundaryMode = Next): DateTime? { log.debug("Subtract start={}, offset={}, seekBoundary={}", start, offset, seekBoundary) // 예외 조건이 없으면 단순 계산으로 처리 if (_includePeriods.isEmpty() && _excludePeriods.isEmpty()) { return start - offset } val end = if (offset < Duration.ZERO) calculateEnd(start, offset.negated(), SeekDirection.Forward, seekBoundary) else calculateEnd(start, offset, SeekDirection.Backward, seekBoundary) log.debug("Subtract Results. end={}, remaining={}", end.first, end.second) return end.first } @JvmOverloads open protected fun calculateEnd(start: DateTime, offset: Duration?, seekDir: SeekDirection, seekBoundary: SeekBoundaryMode = SeekBoundaryMode.Next): Pair<DateTime?, Duration?> { require((offset?.millis ?: 0L) >= 0L) { "offset 값은 0 이상이어야 합니다. offset=$offset" } log.debug("calculateEnd start={}, offset={}, seekDir={}, seekBoundary={}", start, offset, seekDir, seekBoundary) val searchPeriods = TimePeriodCollection.of(_includePeriods.periods) if (searchPeriods.isEmpty()) { searchPeriods += TimeRange.AnyTime } // available periods var availablePeriods = getAvailablePeriods(searchPeriods) if (availablePeriods.isEmpty()) { return Pair(null, offset) } val periodCombiner = TimePeriodCombiner<TimeRange>() availablePeriods = periodCombiner.combinePeriods(availablePeriods) val startPeriod = if (seekDir == SeekDirection.Forward) findNextPeriod(start, availablePeriods) else findPrevPeriod(start, availablePeriods) // 첫 시작 기간이 없다면 중단합니다. if (startPeriod.first == null) { return Pair(null, offset) } if (offset == Duration.ZERO) { return Pair(startPeriod.second, offset) } log.debug("startPeriod={}, offset={}", startPeriod, offset) return if (seekDir == SeekDirection.Forward) findPeriodForward(availablePeriods, offset, startPeriod.first, startPeriod.second, seekBoundary) else findPeriodBackward(availablePeriods, offset, startPeriod.first, startPeriod.second, seekBoundary) } private fun getAvailablePeriods(searchPeriods: ITimePeriodCollection): ITimePeriodCollection { val availablePeriods = TimePeriodCollection() if (_excludePeriods.isEmpty()) { availablePeriods.addAll(searchPeriods) } else { val gapCalculator = TimeGapCalculator<TimeRange>() for (p in searchPeriods) { if (_excludePeriods.hasOverlapPeriods(p)) { for (gap in gapCalculator.gaps(_excludePeriods, p)) { availablePeriods += gap } } else { availablePeriods += p } } } log.debug("availablePeriods={}", availablePeriods) return availablePeriods } private fun findPeriodForward(availablePeriods: ITimePeriodCollection, remaining: Duration?, startPeriod: ITimePeriod?, seekMoment: DateTime, seekBoundary: SeekBoundaryMode): Pair<DateTime?, Duration?> { log.trace("findPeriodForward remaining={}", remaining) var _seekMoment = seekMoment var _remaining = remaining // DateTime end = null; val startIndex = availablePeriods.indexOf(startPeriod) val length = availablePeriods.size for (i in startIndex until length) { val gap = availablePeriods[i] val gapRemaining = Duration(_seekMoment, gap.end) log.trace("gap={}, gamRemaining={}, remaning={}, seekMoment={}", gap, gapRemaining, _remaining, _seekMoment) val isTargetPeriod = if (seekBoundary == SeekBoundaryMode.Fill) gapRemaining >= _remaining else gapRemaining > _remaining if (isTargetPeriod) { log.debug("find datetime={}", _seekMoment.plus(_remaining)) return Pair(_seekMoment.plus(_remaining), null) } _remaining = _remaining?.minus(gapRemaining) if (i < length - 1) _seekMoment = availablePeriods[i + 1].start } log.debug("해당 일자를 찾지 못했습니다. remaining={}", _remaining) return Pair(null, _remaining) } private fun findPeriodBackward(availablePeriods: ITimePeriodCollection, remaining: Duration?, startPeriod: ITimePeriod?, seekMoment: DateTime, seekBoundary: SeekBoundaryMode): Pair<DateTime?, Duration?> { log.trace("findPeriodBackward remaining={}", remaining) // DateTime end = null; val startIndex = availablePeriods.indexOf(startPeriod) var _seekMoment = seekMoment var _remaining = remaining (startIndex downTo 0).forEach { i -> val gap = availablePeriods[i] val gapRemaining = Duration(gap.start, _seekMoment) log.trace("gap={}, gamRemaining={}, remaning={}, seekMoment={}", gap, gapRemaining, _remaining, _seekMoment) val isTargetPeriod = if (seekBoundary == SeekBoundaryMode.Fill) gapRemaining >= _remaining else gapRemaining > _remaining if (isTargetPeriod) { log.trace("find datetime={}", _seekMoment.minus(_remaining)) return Pair(_seekMoment.minus(_remaining), null) } _remaining = _remaining?.minus(gapRemaining) if (i > 0) { _seekMoment = availablePeriods[i - 1].end } } log.debug("해당 일자를 찾지 못했습니다. remaining={}", _remaining) return Pair(null, _remaining) } private fun findNextPeriod(start: DateTime, periods: Collection<ITimePeriod>): Pair<ITimePeriod?, DateTime> { var nearest: ITimePeriod? = null var moment = start var diff = MaxDuration log.trace("find next period. start={}, periods={}", start, periods) periods.forEach { period -> if (period.end >= start) { // start 가 기간와 속한다면 if (period.hasInside(start)) { return Pair(period, start) } // 근처 값이 아니라면 포기 val periodToMoment = Duration(start, period.end) if (periodToMoment < diff) { diff = periodToMoment nearest = period moment = period.start } } } return Pair(nearest, moment) } private fun findPrevPeriod(start: DateTime, periods: Collection<ITimePeriod>): Pair<ITimePeriod?, DateTime> { var nearest: ITimePeriod? = null var moment = start var diff = MaxDuration log.trace("find prev period. start={}, periods={}", start, periods) periods.forEach { period -> if (period.start <= start) { // start 가 기간와 속한다면 if (period.hasInside(start)) { return Pair(period, start) } // 근처 값이 아니라면 포기 val periodToMoment = Duration(start, period.end) if (periodToMoment < diff) { diff = periodToMoment nearest = period moment = period.end } } } return Pair(nearest, moment) } }
apache-2.0
034456404d2f762d619e2cf411ecab8f
31.250794
119
0.619118
4.169951
false
false
false
false
ykrank/S1-Next
app/src/main/java/me/ykrank/s1next/view/dialog/LoadBlackListFromWebDialogFragment.kt
1
3728
package me.ykrank.s1next.view.dialog import android.app.Dialog import android.content.DialogInterface import android.os.Bundle import androidx.annotation.MainThread import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.view.Window import com.github.ykrank.androidautodispose.AndroidRxDispose import com.github.ykrank.androidlifecycle.event.FragmentEvent import com.github.ykrank.androidtools.extension.toast import com.github.ykrank.androidtools.util.RxJavaUtil import me.ykrank.s1next.App import me.ykrank.s1next.data.User import me.ykrank.s1next.data.api.S1Service import me.ykrank.s1next.data.api.model.WebBlackListInfo import me.ykrank.s1next.data.db.BlackListDbWrapper import me.ykrank.s1next.data.db.dbmodel.BlackList import me.ykrank.s1next.databinding.DialogLoadBlacklistFromWebBinding import me.ykrank.s1next.util.ErrorUtil import javax.inject.Inject /** * A dialog lets user load website blacklist. */ class LoadBlackListFromWebDialogFragment : BaseDialogFragment() { @Inject lateinit var s1Service: S1Service @Inject lateinit var mUser: User @Inject lateinit var blackListDbWrapper: BlackListDbWrapper private lateinit var binding: DialogLoadBlacklistFromWebBinding override fun onCreate(savedInstanceState: Bundle?) { App.appComponent.inject(this) super.onCreate(savedInstanceState) } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { binding = DialogLoadBlacklistFromWebBinding.inflate(inflater, container, false) loadNextPage() return binding.root } override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { val dialog = super.onCreateDialog(savedInstanceState) dialog.window?.requestFeature(Window.FEATURE_NO_TITLE) return dialog } override fun onStart() { super.onStart() dialog?.window?.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT) } @MainThread private fun loadNextPage(page: Int = 1) { s1Service.getWebBlackList(mUser.uid, page) .map { WebBlackListInfo.fromHtml(it) } .map { it.users.forEach { pair -> blackListDbWrapper.saveBlackList(BlackList(pair.first, pair.second, BlackList.HIDE_POST, BlackList.HIDE_FORUM)) } it } .compose(RxJavaUtil.iOSingleTransformer()) .to(AndroidRxDispose.withSingle(this, FragmentEvent.DESTROY)) .subscribe({ binding.max = it.max binding.progress = it.page if (it.max > it.page) { loadNextPage(it.page + 1) }else{ [email protected]() } }, { val activity = activity ?: return@subscribe activity.toast(ErrorUtil.parse(activity, it)) }) } override fun onDismiss(dialog: DialogInterface) { super.onDismiss(dialog) val parentFragment = parentFragment if (parentFragment is DialogInterface.OnDismissListener) { (parentFragment as DialogInterface.OnDismissListener).onDismiss(dialog) } } companion object { val TAG: String = LoadBlackListFromWebDialogFragment::class.java.name fun newInstance(): LoadBlackListFromWebDialogFragment { val fragment = LoadBlackListFromWebDialogFragment() return fragment } } }
apache-2.0
c163cd4d2fa461e6fa37ea116092dc3b
33.518519
135
0.672747
4.718987
false
false
false
false
renyuneyun/Easer
app/src/main/java/ryey/easer/core/EaserStatusWidget.kt
1
3319
/* * Copyright (c) 2016 - 2019 Rui Zhao <[email protected]> * * This file is part of Easer. * * Easer 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. * * Easer 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 Easer. If not, see <http://www.gnu.org/licenses/>. */ package ryey.easer.core import android.app.PendingIntent import android.appwidget.AppWidgetManager import android.appwidget.AppWidgetProvider import android.content.ComponentName import android.content.Context import android.content.Intent import android.widget.RemoteViews import ryey.easer.R import ryey.easer.core.ui.MainActivity /** * Implementation of App Widget functionality. */ class EaserStatusWidget : AppWidgetProvider() { override fun onUpdate(context: Context, appWidgetManager: AppWidgetManager, appWidgetIds: IntArray) { // There may be multiple widgets active, so update all of them for (appWidgetId in appWidgetIds) { updateAppWidget(context, appWidgetManager, appWidgetId) } } override fun onEnabled(context: Context) { // Enter relevant functionality for when the first widget is created } override fun onDisabled(context: Context) { // Enter relevant functionality for when the last widget is disabled } override fun onReceive(context: Context?, intent: Intent?) { if (ACTION_CLICK == intent?.action || EHService.ACTION_STATE_CHANGED == intent?.action) { val views = createViews(context) AppWidgetManager.getInstance(context) .updateAppWidget(ComponentName(context!!, EaserStatusWidget::class.java), views) } else { super.onReceive(context, intent) } } companion object { const val ACTION_CLICK = "ryey.easer.core.EaserStatusWidget.ACTION_CLICK" private fun createViews(context: Context?): RemoteViews { val views = RemoteViews(context?.packageName, R.layout.easer_status_widget) if (EHService.isRunning()) { views.setImageViewResource(R.id.appwidget_status, R.drawable.ic_status_positive) } else { views.setImageViewResource(R.id.appwidget_status, R.drawable.ic_status_negative) } val intent = Intent(context, MainActivity::class.java) val pendingIntent = PendingIntent.getActivity(context, 0, intent, 0) views.setOnClickPendingIntent(R.id.layout, pendingIntent) views.setOnClickPendingIntent(R.id.appwidget_status, pendingIntent) return views } internal fun updateAppWidget(context: Context, appWidgetManager: AppWidgetManager, appWidgetId: Int) { val views = createViews(context) appWidgetManager.updateAppWidget(appWidgetId, views) } } }
gpl-3.0
012a1eba216ce4d9485bbd2061fa2f57
37.149425
105
0.68605
4.648459
false
false
false
false
googlesamples/mlkit
android/vision-quickstart/app/src/main/java/com/google/mlkit/vision/demo/kotlin/facemeshdetector/FaceMeshGraphic.kt
1
4975
/* * Copyright 2022 Google LLC. 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.vision.demo.kotlin.facemeshdetector import android.graphics.Canvas import android.graphics.Color import android.graphics.Paint import android.graphics.RectF import com.google.mlkit.vision.common.PointF3D import com.google.mlkit.vision.demo.GraphicOverlay import com.google.mlkit.vision.demo.preference.PreferenceUtils import com.google.mlkit.vision.facemesh.FaceMesh import com.google.mlkit.vision.facemesh.FaceMeshDetectorOptions import com.google.mlkit.vision.facemesh.FaceMeshPoint /** * Graphic instance for rendering face position and mesh info within the associated graphic overlay * view. */ class FaceMeshGraphic(overlay: GraphicOverlay, private val faceMesh: FaceMesh) : GraphicOverlay.Graphic(overlay) { private val positionPaint: Paint private val boxPaint: Paint private val useCase: Int private var zMin: Float private var zMax: Float @FaceMesh.ContourType private val DISPLAY_CONTOURS = intArrayOf( FaceMesh.FACE_OVAL, FaceMesh.LEFT_EYEBROW_TOP, FaceMesh.LEFT_EYEBROW_BOTTOM, FaceMesh.RIGHT_EYEBROW_TOP, FaceMesh.RIGHT_EYEBROW_BOTTOM, FaceMesh.LEFT_EYE, FaceMesh.RIGHT_EYE, FaceMesh.UPPER_LIP_TOP, FaceMesh.UPPER_LIP_BOTTOM, FaceMesh.LOWER_LIP_TOP, FaceMesh.LOWER_LIP_BOTTOM, FaceMesh.NOSE_BRIDGE ) /** Draws the face annotations for position on the supplied canvas. */ override fun draw(canvas: Canvas) { // Draws the bounding box. val rect = RectF(faceMesh.boundingBox) // If the image is flipped, the left will be translated to right, and the right to left. val x0 = translateX(rect.left) val x1 = translateX(rect.right) rect.left = Math.min(x0, x1) rect.right = Math.max(x0, x1) rect.top = translateY(rect.top) rect.bottom = translateY(rect.bottom) canvas.drawRect(rect, boxPaint) // Draw face mesh val points = if (useCase == USE_CASE_CONTOUR_ONLY) getContourPoints(faceMesh) else faceMesh.allPoints val triangles = faceMesh.allTriangles zMin = Float.MAX_VALUE zMax = Float.MIN_VALUE for (point in points) { zMin = Math.min(zMin, point.position.z) zMax = Math.max(zMax, point.position.z) } // Draw face mesh points for (point in points) { updatePaintColorByZValue( positionPaint, canvas, /* visualizeZ= */true, /* rescaleZForVisualization= */true, point.position.z, zMin, zMax) canvas.drawCircle( translateX(point.position.x), translateY(point.position.y), FACE_POSITION_RADIUS, positionPaint ) } if (useCase == FaceMeshDetectorOptions.FACE_MESH) { // Draw face mesh triangles for (triangle in triangles) { val point1 = triangle.allPoints[0].position val point2 = triangle.allPoints[1].position val point3 = triangle.allPoints[2].position drawLine(canvas, point1, point2) drawLine(canvas, point1, point3) drawLine(canvas, point2, point3) } } } private fun drawLine(canvas: Canvas, point1: PointF3D, point2: PointF3D) { updatePaintColorByZValue( positionPaint, canvas, /* visualizeZ= */true, /* rescaleZForVisualization= */true, (point1.z + point2.z) / 2, zMin, zMax) canvas.drawLine( translateX(point1.x), translateY(point1.y), translateX(point2.x), translateY(point2.y), positionPaint ) } private fun getContourPoints(faceMesh: FaceMesh): List<FaceMeshPoint> { val contourPoints: MutableList<FaceMeshPoint> = ArrayList() for (type in DISPLAY_CONTOURS) { contourPoints.addAll(faceMesh.getPoints(type)) } return contourPoints } companion object { private const val USE_CASE_CONTOUR_ONLY = 999 private const val FACE_POSITION_RADIUS = 8.0f private const val BOX_STROKE_WIDTH = 5.0f } init { val selectedColor = Color.WHITE positionPaint = Paint() positionPaint.color = selectedColor boxPaint = Paint() boxPaint.color = selectedColor boxPaint.style = Paint.Style.STROKE boxPaint.strokeWidth = BOX_STROKE_WIDTH useCase = PreferenceUtils.getFaceMeshUseCase(applicationContext) zMin = java.lang.Float.MAX_VALUE zMax = java.lang.Float.MIN_VALUE } }
apache-2.0
bc21541d710d8466d4b8e5ba214185e6
29.709877
99
0.691859
3.768939
false
false
false
false
McPringle/moodini
src/main/kotlin/ch/fihlon/moodini/server/business/question/boundary/QuestionsResource.kt
1
2112
/* * Moodini * Copyright (C) 2016-2017 Marcus Fihlon * * 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 ch.fihlon.moodini.server.business.question.boundary import ch.fihlon.moodini.server.business.question.control.QuestionService import ch.fihlon.moodini.server.business.question.entity.Question import java.io.File import java.time.LocalDateTime import javax.inject.Inject import javax.servlet.http.HttpServletRequest import javax.validation.Valid import javax.ws.rs.GET import javax.ws.rs.POST import javax.ws.rs.Path import javax.ws.rs.Produces import javax.ws.rs.core.Context import javax.ws.rs.core.MediaType import javax.ws.rs.core.Response import javax.ws.rs.core.UriInfo @Path("questions") @Produces(MediaType.APPLICATION_JSON) class QuestionsResource @Inject constructor(private val questionService: QuestionService) { @POST fun create(@Valid question: Question, @Context request: HttpServletRequest, @Context info: UriInfo): Response { val questionToSave = question.copy(ipAddress = request.remoteAddr, created = LocalDateTime.now()) val newQuestion = questionService.create(questionToSave) val questionId = newQuestion.questionId val uri = info.absolutePathBuilder.path(File.separator + questionId).build() return Response.created(uri).build() } @GET fun read(): Response { val questions = questionService.read() return Response.ok(questions).build() } }
agpl-3.0
2cc2a1106e1311f3429e175b2d0a8b71
35.413793
105
0.747633
4.015209
false
false
false
false
didi/DoraemonKit
Android/app/src/main/java/com/didichuxing/doraemondemo/comm/CommFragmentActivity.kt
1
1827
package com.didichuxing.doraemondemo.comm import android.os.Bundle import android.view.View import android.view.Window import android.widget.TextView import androidx.activity.viewModels import androidx.appcompat.app.AppCompatActivity import androidx.fragment.app.viewModels import androidx.lifecycle.Observer import androidx.lifecycle.SavedStateViewModelFactory import com.didichuxing.doraemondemo.R /** * ================================================ * 作 者:jint(金台) * 版 本:1.0 * 创建日期:3/11/21-15:14 * 描 述: * 修订历史: * ================================================ */ class CommFragmentActivity : AppCompatActivity() { var fragmentClass: Class<out CommBaseFragment>? = null private val viewModel: CommViewModel by viewModels() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_comm) initTitleBar() initFragment() } private fun initFragment() { val bundle = intent.extras bundle?.let { if (bundle.get(CommLauncher.FRAGMENT_CLASS) != null) { fragmentClass = bundle[CommLauncher.FRAGMENT_CLASS] as Class<out CommBaseFragment>? fragmentClass?.let { supportFragmentManager .beginTransaction() .add(R.id.container_view, it.newInstance()) .commit() } } } } private fun initTitleBar() { findViewById<View>(R.id.iv_back).setOnClickListener { finish() } viewModel.getTitle().observe(this, Observer<String> { findViewById<TextView>(R.id.tv_title).text = it }) } }
apache-2.0
c25b205d8826a754ee42572b67897b56
26.84375
99
0.587872
4.826558
false
false
false
false
graphql-java/graphql-java-tools
src/main/kotlin/graphql/kickstart/tools/relay/RelayConnectionFactory.kt
1
4004
package graphql.kickstart.tools.relay import graphql.kickstart.tools.TypeDefinitionFactory import graphql.language.* class RelayConnectionFactory : TypeDefinitionFactory { override fun create(existing: MutableList<Definition<*>>): List<Definition<*>> { val connectionDirectives = findConnectionDirectives(existing) if (connectionDirectives.isEmpty()) { // do not add Relay definitions unless needed return emptyList() } val definitions = mutableListOf<Definition<*>>() val definitionsByName = existing.filterIsInstance<TypeDefinition<*>>() .associateBy { it.name } .toMutableMap() connectionDirectives .flatMap { createDefinitions(it) } .forEach { if (!definitionsByName.containsKey(it.name)) { definitionsByName[it.name] = it definitions.add(it) } } if (!definitionsByName.containsKey("PageInfo")) { definitions.add(createPageInfo()) } return definitions } private fun findConnectionDirectives(definitions: List<Definition<*>>): List<DirectiveWithField> { return definitions.filterIsInstance<ObjectTypeDefinition>() .flatMap { it.fieldDefinitions } .flatMap { it.directivesWithField() } .filter { it.name == "connection" } } private fun createDefinitions(directive: DirectiveWithField): List<ObjectTypeDefinition> { val definitions = mutableListOf<ObjectTypeDefinition>() definitions.add(createConnectionDefinition(directive.getTypeName())) definitions.add(createEdgeDefinition(directive.getTypeName(), directive.forTypeName())) return definitions.toList() } private fun createConnectionDefinition(type: String): ObjectTypeDefinition = ObjectTypeDefinition.newObjectTypeDefinition() .name(type) .fieldDefinition(FieldDefinition("edges", ListType(TypeName(type + "Edge")))) .fieldDefinition(FieldDefinition("pageInfo", TypeName("PageInfo"))) .build() private fun createEdgeDefinition(connectionType: String, nodeType: String): ObjectTypeDefinition = ObjectTypeDefinition.newObjectTypeDefinition() .name(connectionType + "Edge") .fieldDefinition(FieldDefinition("cursor", TypeName("String"))) .fieldDefinition(FieldDefinition("node", TypeName(nodeType))) .build() private fun createPageInfo(): ObjectTypeDefinition = ObjectTypeDefinition.newObjectTypeDefinition() .name("PageInfo") .fieldDefinition(FieldDefinition("hasPreviousPage", NonNullType(TypeName("Boolean")))) .fieldDefinition(FieldDefinition("hasNextPage", NonNullType(TypeName("Boolean")))) .fieldDefinition(FieldDefinition("startCursor", TypeName("String"))) .fieldDefinition(FieldDefinition("endCursor", TypeName("String"))) .build() private fun Directive.forTypeName(): String { return (this.getArgument("for").value as StringValue).value } private fun Directive.withField(field: FieldDefinition): DirectiveWithField { return DirectiveWithField(field, this.name, this.arguments, this.sourceLocation, this.comments) } private fun FieldDefinition.directivesWithField(): List<DirectiveWithField> { return this.directives.map { it.withField(this) } } class DirectiveWithField(val field: FieldDefinition, name: String, arguments: List<Argument>, sourceLocation: SourceLocation, comments: List<Comment>) : Directive(name, arguments, sourceLocation, comments, IgnoredChars.EMPTY, emptyMap()) { fun getTypeName(): String { val type = field.type if (type is NonNullType) { return (type.type as TypeName).name } return (field.type as TypeName).name } } }
mit
d7c532b07593bde92dbb733198aefaed
41.595745
243
0.661838
5.367292
false
false
false
false
tasks/tasks
app/src/main/java/org/tasks/billing/PurchaseActivity.kt
1
4495
package org.tasks.billing import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.os.Bundle import androidx.activity.compose.setContent import androidx.compose.runtime.mutableStateOf import androidx.compose.ui.window.Dialog import androidx.lifecycle.lifecycleScope import com.google.android.material.composethemeadapter.MdcTheme import dagger.hilt.android.AndroidEntryPoint import kotlinx.coroutines.launch import org.tasks.LocalBroadcastManager import org.tasks.R import org.tasks.analytics.Firebase import org.tasks.compose.PurchaseText.PurchaseText import org.tasks.extensions.Context.toast import org.tasks.injection.InjectingAppCompatActivity import org.tasks.preferences.Preferences import org.tasks.themes.Theme import javax.inject.Inject @AndroidEntryPoint class PurchaseActivity : InjectingAppCompatActivity(), OnPurchasesUpdated { @Inject lateinit var theme: Theme @Inject lateinit var billingClient: BillingClient @Inject lateinit var localBroadcastManager: LocalBroadcastManager @Inject lateinit var inventory: Inventory @Inject lateinit var preferences: Preferences @Inject lateinit var firebase: Firebase private var currentSubscription: Purchase? = null private val purchaseReceiver: BroadcastReceiver = object : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { setup() } } private val nameYourPrice = mutableStateOf(false) private val sliderPosition = mutableStateOf(-1f) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val github = intent?.extras?.getBoolean(EXTRA_GITHUB) ?: false theme.applyToContext(this) savedInstanceState?.let { nameYourPrice.value = it.getBoolean(EXTRA_NAME_YOUR_PRICE) sliderPosition.value = it.getFloat(EXTRA_PRICE) } setContent { MdcTheme { Dialog(onDismissRequest = { finish() }) { PurchaseText( nameYourPrice = nameYourPrice, sliderPosition = sliderPosition, github = github, solidButton = firebase.moreOptionsSolid, badge = firebase.moreOptionsBadge, onDisplayed = { firebase.logEvent(R.string.event_showed_purchase_dialog) }, subscribe = this::purchase, ) } } } } override fun onStart() { super.onStart() localBroadcastManager.registerPurchaseReceiver(purchaseReceiver) lifecycleScope.launch { try { billingClient.queryPurchases(throwError = true) } catch (e: Exception) { toast(e.message) } } } override fun onStop() { super.onStop() localBroadcastManager.unregisterReceiver(purchaseReceiver) } private fun setup() { currentSubscription = inventory.subscription.value if (sliderPosition.value < 0) { sliderPosition.value = currentSubscription ?.subscriptionPrice ?.coerceAtMost(25) ?.toFloat() ?: 10f } } private fun purchase(price: Int, monthly: Boolean) = lifecycleScope.launch { val newSku = String.format("%s_%02d", if (monthly) "monthly" else "annual", price) try { billingClient.initiatePurchaseFlow( this@PurchaseActivity, newSku, BillingClientImpl.TYPE_SUBS, currentSubscription?.takeIf { it.sku != newSku } ) } catch (e: Exception) { [email protected](e.message) } } override fun onPurchasesUpdated(success: Boolean) { if (success) { setResult(RESULT_OK) finish() } } override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) outState.putFloat(EXTRA_PRICE, sliderPosition.value) outState.putBoolean(EXTRA_NAME_YOUR_PRICE, nameYourPrice.value) } companion object { const val EXTRA_GITHUB = "extra_github" private const val EXTRA_PRICE = "extra_price" private const val EXTRA_NAME_YOUR_PRICE = "extra_name_your_price" } }
gpl-3.0
17432edd1e867fc73457ef90585f91a1
33.060606
99
0.640712
5.102157
false
false
false
false
nemerosa/ontrack
ontrack-extension-github/src/main/java/net/nemerosa/ontrack/extension/github/ingestion/extensions/validation/GitHubIngestionValidateDataByRunIdInput.kt
1
1140
package net.nemerosa.ontrack.extension.github.ingestion.extensions.validation import net.nemerosa.ontrack.model.annotations.APIDescription import net.nemerosa.ontrack.model.annotations.APIName /** * Input for the data validation for a build identified by GHA workflow run ID */ @APIName("GitHubIngestionValidateDataByRunIdInput") @APIDescription("Input for the data validation for a build identified by GHA workflow run ID") class GitHubIngestionValidateDataByRunIdInput( owner: String, repository: String, // ref: String, validation: String, validationData: GitHubIngestionValidationDataInput, validationStatus: String?, @APIDescription("ID of the GHA workflow run") val runId: Long, ) : AbstractGitHubIngestionValidateDataInput( owner, repository, // ref, validation, validationData, validationStatus, ) { override fun toPayload() = GitHubIngestionValidateDataPayload( owner = owner, repository = repository, validation = validation, validationData = validationData, validationStatus = validationStatus, runId = runId, ) }
mit
3c6554c9974b652f2bd210372693b194
30.694444
94
0.735965
4.578313
false
false
false
false
maxirosson/jdroid-googleplay-publisher
jdroid-gradle-googleplay-publisher-plugin/src/main/java/com/jdroid/android/googleplay/publisher/task/BaseTask.kt
1
2349
package com.jdroid.android.googleplay.publisher.task import com.jdroid.android.googleplay.publisher.App import com.jdroid.android.googleplay.publisher.AppContext import com.jdroid.android.googleplay.publisher.TrackType import com.jdroid.android.googleplay.publisher.commons.AbstractTask abstract class BaseTask : AbstractTask() { override fun onExecute() { val extension = getExtension() val appContext = AppContext() appContext.applicationId = extension.applicationId appContext.privateKeyJsonFilePath = extension.privateKeyJsonFilePath appContext.connectTimeout = extension.connectTimeout appContext.readTimeout = extension.readTimeout appContext.locales = extension.locales.orEmpty().split(",") appContext.releaseName = extension.releaseName appContext.isDraft = extension.draft appContext.isDryRun = extension.dryRun appContext.metadataPath = extension.metadataPath appContext.deobfuscationFilePath = extension.deobfuscationFilePath appContext.isDeobfuscationFileUploadEnabled = extension.isDeobfuscationFileUploadEnabled appContext.isReleaseNotesRequired = extension.releaseNotesRequired appContext.isVideoRequired = extension.videoRequired appContext.isPromoGraphicRequired = extension.promoGraphicRequired appContext.isPhoneScreenshotsRequired = extension.phoneScreenshotsRequired appContext.isTvBannerRequired = extension.tvBannerRequired appContext.isSevenInchScreenshotsRequired = extension.sevenInchScreenshotsRequired appContext.isTenInchScreenshotsRequired = extension.tenInchScreenshotsRequired appContext.isTvScreenshotsRequired = extension.tvScreenshotsRequired appContext.isWearScreenshotsRequired = extension.wearScreenshotsRequired appContext.apkPath = extension.apkPath appContext.apkDir = extension.apkDir appContext.bundlePath = extension.bundlePath appContext.bundleDir = extension.bundleDir appContext.trackType = TrackType.findByKey(extension.track!!) appContext.userPercentage = extension.userPercentage appContext.setFailOnApkUpgradeVersionConflict(extension.failOnApkUpgradeVersionConflict) onExecute(App(appContext)) } protected abstract fun onExecute(app: App) }
apache-2.0
db552f092d8b89eaedaef335750e15d4
52.386364
96
0.780758
5.350797
false
false
false
false
soywiz/korge
korge/src/commonMain/kotlin/com/soywiz/korge/particle/ParticleEmitter.kt
1
2654
package com.soywiz.korge.particle import com.soywiz.kds.* import com.soywiz.klock.* import com.soywiz.korag.* import com.soywiz.korim.bitmap.* import com.soywiz.korim.color.* import com.soywiz.korma.geom.* //e: java.lang.UnsupportedOperationException: Class literal annotation arguments are not yet supported: Factory //@AsyncFactoryClass(ParticleEmitter.Factory::class) class ParticleEmitter() { enum class Type(val index: Int) { GRAVITY(0), RADIAL(1) } var textureName: String? = null var texture: BmpSlice? = null var sourcePosition = Point() var sourcePositionVariance = Point() var speed = 100.0 var speedVariance = 30.0 var lifeSpan = 2.0 var lifespanVariance = 1.9 var angle: Angle = 270.0.degrees var angleVariance: Angle = 2.0.degrees var gravity = Point() var radialAcceleration = 0.0 var tangentialAcceleration = 0.0 var radialAccelVariance = 0.0 var tangentialAccelVariance = 0.0 var startColor = RGBAf(1f, 1f, 1f, 1f) var startColorVariance = RGBAf(0f, 0f, 0f, 0f) var endColor = RGBAf(1f, 1f, 1f, 1f) var endColorVariance = RGBAf(0f, 0f, 0f, 0f) var maxParticles = 500 var startSize = 70.0 var startSizeVariance = 50.0 var endSize = 10.0 var endSizeVariance = 5.0 var duration = -1.0 var emitterType = Type.GRAVITY var maxRadius = 0.0 var maxRadiusVariance = 0.0 var minRadius = 0.0 var minRadiusVariance = 0.0 var rotatePerSecond = 0.0.degrees var rotatePerSecondVariance = 0.0.degrees var blendFuncSource = AG.BlendFactor.ONE var blendFuncDestination = AG.BlendFactor.ONE var rotationStart = 0.0.degrees var rotationStartVariance = 0.0.degrees var rotationEnd = 0.0.degrees var rotationEndVariance = 0.0.degrees fun create(x: Double = 0.0, y: Double = 0.0, time: TimeSpan = TimeSpan.NIL): ParticleEmitterView = ParticleEmitterView(this, IPoint(x, y)).apply { this.timeUntilStop = time } companion object { val blendFactorMap = mapOf( 0 to AG.BlendFactor.ZERO, 1 to AG.BlendFactor.ONE, 0x300 to AG.BlendFactor.SOURCE_COLOR, 0x301 to AG.BlendFactor.ONE_MINUS_SOURCE_COLOR, 0x302 to AG.BlendFactor.SOURCE_ALPHA, 0x303 to AG.BlendFactor.ONE_MINUS_SOURCE_ALPHA, 0x304 to AG.BlendFactor.DESTINATION_ALPHA, 0x305 to AG.BlendFactor.ONE_MINUS_DESTINATION_ALPHA, 0x306 to AG.BlendFactor.DESTINATION_COLOR, 0x307 to AG.BlendFactor.ONE_MINUS_DESTINATION_COLOR, ) val blendFactorMapReversed = blendFactorMap.flip() val typeMap = Type.values().associateBy { it.index } val typeMapReversed = typeMap.flip() } }
apache-2.0
ec1c492e67011e2d0a8d30c800479be9
32.594937
111
0.703466
3.256442
false
false
false
false
nhaarman/AsyncAwait-Android
asyncawait-android/src/main/kotlin/com/nhaarman/async/AsyncController.kt
1
10566
package com.nhaarman.async import android.os.Looper import io.reactivex.disposables.Disposable import retrofit2.Call import retrofit2.Response import java.util.concurrent.Executors import java.util.concurrent.TimeUnit import kotlin.reflect.KProperty import io.reactivex.Single as Single2 import rx.Single as Single1 import rx.Subscription as Subscription1 /** * Run asynchronous computations based on [c] coroutine parameter. * * Execution starts immediately within the 'async' call and it runs until * the first suspension point is reached (an 'await' call). * The remaining part of the coroutine will be executed as the awaited code * is completed. * There is no thread switching after 'await' calls. * * @param c a coroutine representing asynchronous computations * @param T the return type of the coroutine. * * @return Task object representing result of computations */ fun <T> async(coroutine c: AsyncController<T>.() -> Continuation<Unit>): Task<T> { val controller = AsyncController<T>() controller.c().resume(Unit) return controller.task } /** * Run asynchronous computations based on [c] coroutine parameter. * * Execution starts immediately within the 'async' call and it runs until * the first suspension point is reached (an 'await' call). * The remaining part of the coroutine will be executed as the awaited code * is completed. * There is no thread switching after 'await' calls. * * @param c a coroutine representing asynchronous computations * * @return Task object representing result of computations */ @JvmName("asyncWithoutParameter") fun async(coroutine c: AsyncController<Unit>.() -> Continuation<Unit>): Task<Unit> { val controller = AsyncController<Unit>() controller.c().resume(Unit) return controller.task } /** * Run asynchronous computations based on [c] coroutine parameter. * * Execution starts immediately within the 'async' call and it runs until * the first suspension point is reached (an 'await' call). * The remaining part of the coroutine will be executed *on the main thread* * as the awaited code is completed. * * @param c a coroutine representing asynchronous computations * @param T the return type of the coroutine. * * @return Task object representing result of computations */ fun <T> asyncUI(coroutine c: AsyncController<T>.() -> Continuation<Unit>): Task<T> { val controller = AsyncController<T>(returnToMainThread = true) controller.c().resume(Unit) return controller.task } /** * Run asynchronous computations based on [c] coroutine parameter. * * Execution starts immediately within the 'async' call and it runs until * the first suspension point is reached (an 'await' call). * The remaining part of the coroutine will be executed *on the main thread* * as the awaited code is completed. * * @param c a coroutine representing asynchronous computations * * @return Task object representing result of computations */ @JvmName("asyncUIWithoutParameter") fun asyncUI(coroutine c: AsyncController<Unit>.() -> Continuation<Unit>): Task<Unit> { val controller = AsyncController<Unit>(returnToMainThread = true) controller.c().resume(Unit) return controller.task } /** * Returns a [Task] that completes after a specified time interval. * * @param time the delay to wait before completing the returned task. * @param unit the [TimeUnit] in which [time] is defined. * * @return a cancelable [Task]. */ fun delay(time: Long, unit: TimeUnit): Task<Unit> { return Task<Unit>().apply { val task = this startedWith(executorService.submit { Thread.sleep(unit.toMillis(time)) task.complete(Unit) }) } } class AsyncController<T>(private val returnToMainThread: Boolean = false) { internal val task = Task<T>() private fun isCanceled() = task.isCanceled() /** * Suspends the coroutine call until [task] completes. * * @return the result of [task]. */ suspend fun <R> await(task: Task<R>, machine: Continuation<R>) { if (isCanceled()) return this.task.awaitingOn(task) task.whenComplete( { result -> this.task.awaitDone() if (!isCanceled()) resume(machine, result) }, { throwable -> this.task.awaitDone() if (!isCanceled()) resumeWithException(machine, throwable) } ) } /** * Suspends the coroutine call until callee task completes. * * @return the result of the callee. */ suspend operator fun <R> Task<R>.getValue( thisRef: Any?, property: KProperty<*>, machine: Continuation<R> ) { await(this, machine) } /** * For usage with Retrofit 2. * Enqueues [call] to be ran asynchronously and suspends the coroutine until [call] completes. * * @return the result of [call]. */ suspend fun <R> await(call: Call<R>, machine: Continuation<Response<R>>) { if (isCanceled()) return task.awaitingOn(CancelableCall(call)) call.enqueue( { response -> task.awaitDone() if (!isCanceled()) resume(machine, response) }, { throwable -> task.awaitDone() if (!isCanceled()) resumeWithException(machine, throwable) } ) } /** * For usage with Retrofit 2 * Enqueues the callee Call to be ran asynchronously and suspends the coroutine until the callee completes. * * @return the result of the callee. */ suspend operator fun <R> Call<R>.getValue( thisRef: Any?, property: KProperty<*>, machine: Continuation<Response<R>> ) { await(this, machine) } /** * For usage with RxJava 1.x * Subscribes to the [single] and suspends the coroutine until [single] completes. * * @return the completed result of [single]. */ suspend fun <R> await(single: Single1<R>, machine: Continuation<R>) { if (isCanceled()) return var subscription: Subscription1? = null task.awaitingOn(object : Cancelable { override fun cancel() { subscription?.unsubscribe() } override fun isCanceled(): Boolean { return subscription?.isUnsubscribed ?: false } }) subscription = single.subscribe( { result -> task.awaitDone() if (!isCanceled()) resume(machine, result) }, { throwable -> task.awaitDone() if (!isCanceled()) resumeWithException(machine, throwable) } ) } /** * For usage with RxJava 1.x * Subscribes to the callee [Single][rx.Single] and suspends the coroutine until the callee completes. * * @return the completed result of the callee [Single][rx.Single]. */ suspend operator fun <R> Single1<R>.getValue( thisRef: Any?, property: KProperty<*>, machine: Continuation<R> ) { await(this, machine) } /** * For usage with RxJava 2.x * Subscribes to the [single] and suspends the coroutine until [single] completes. * * @return the completed result of [single]. */ suspend fun <R> await(single: Single2<R>, machine: Continuation<R>) { if (isCanceled()) return var disposable: Disposable? = null task.awaitingOn(object : Cancelable { override fun cancel() { disposable?.dispose() } override fun isCanceled(): Boolean { return disposable?.isDisposed ?: false } }) disposable = single.subscribe( { result -> task.awaitDone() if (!isCanceled()) resume(machine, result) }, { throwable -> task.awaitDone() if (!isCanceled()) resumeWithException(machine, throwable) } ) } /** * For usage with RxJava 2.x * Subscribes to the callee [Single][io.reactivex.Single] and suspends the coroutine until the callee completes. * * @return the completed result of the callee [Single][io.reactivex.Single]. */ suspend operator fun <R> Single2<R>.getValue( thisRef: Any?, property: KProperty<*>, machine: Continuation<R> ) { await(this, machine) } /** * Runs [f] asynchronously and suspends the coroutine call until [f] completes. * * @return the result of [f]. */ suspend fun <R> await(f: () -> R, machine: Continuation<R>) { if (isCanceled()) return task.startedWith(executorService.submit { try { val data = f() if (!isCanceled()) resume(machine, data) } catch(e: Throwable) { if (!isCanceled()) resumeWithException(machine, e) } }) } /** * Runs the callee function asynchronously and suspends the coroutine call until the function completes. * * @return the result of the callee function. */ suspend operator fun <R> (() -> R).getValue( thisRef: Any?, property: KProperty<*>, machine: Continuation<R> ) { await(this, machine) } private fun <R> resume(machine: Continuation<R>, result: R) { runOnUiIfNecessary { machine.resume(result) } } private fun <R> resumeWithException(machine: Continuation<R>, throwable: Throwable) { runOnUiIfNecessary { machine.resumeWithException(throwable) } } private fun runOnUiIfNecessary(action: () -> Unit) { if (returnToMainThread && Looper.myLooper() != Looper.getMainLooper()) { runOnUi(action) } else { action() } } @Suppress("unused", "unused_parameter") operator fun handleResult(value: T, c: Continuation<Nothing>) { task.complete(value) } @Suppress("unused", "unused_parameter") operator fun handleException(t: Throwable, c: Continuation<Nothing>) { if (isCanceled() && t is InterruptedException) return if (!task.handleError(t)) runOnUi { throw t } } } private val executorService by lazy { Executors.newCachedThreadPool() }
apache-2.0
b57e52e08c2c6fb8d1c7f1c9b0dc10a0
30.446429
116
0.61272
4.591917
false
false
false
false
xbh0902/cryptlib
CryptLibrary/src/main/kotlin/me/xbh/lib/core/java/CryptServiceJavaImpl.kt
1
1773
package me.xbh.lib.core.java import android.content.Context import me.xbh.lib.core.CryptService import me.xbh.lib.core.ICrypt import me.xbh.lib.core.cxx.Md5 import me.xbh.lib.core.java.utils.Md5Util import java.util.HashMap /** * <p> * 描述:使用`CryptServiceImpl`可以对数据加密,提供安全保障。其中包含MD5、AES、和RSA公钥加密解密 * </p> * 创建日期:2017年11月22日. * @author [email protected] * @version 1.0 */ internal class CryptServiceJavaImpl: CryptService { private val objs = HashMap<String, ICrypt>() init { objs.put(CryptService.AES, AesJavaImpl()) objs.put(CryptService.RSA, RsaJavaImpl()) } /** * 获取RSA公钥 * @param buildType 构建环境 * dev:1、qa:2、pro:3 */ override fun getRsaPubKey(buildType: Int): String = getElement(CryptService.RSA).getKey(buildType) /** * 获取一个16位的随机密钥 */ override fun getAesKey(): String = getElement(CryptService.AES).getKey(null) /** * md5加密 */ override fun md5(plain: String): String = Md5Util.getMD5(plain) /** * 获取本地密钥 */ override fun getAesLocalKey(context: Context) = getElement(CryptService.AES).getKey(context) /** * 加密 */ override fun encrypt(plain: String, key: String, type: String): String { val crypt = getElement(type) return crypt.encrypt(plain, key) } /** * 解密 */ override fun decrypt(cipher: String, key: String, type: String): String { val crypt = getElement(type) return crypt.decrypt(cipher, key) } private fun getElement(type: String): ICrypt { return objs[type] as ICrypt } }
mit
b773386888a12dae8a5fff9de4269c02
22.594203
102
0.633067
3.221782
false
false
false
false
vanita5/twittnuker
twittnuker/src/main/kotlin/de/vanita5/twittnuker/util/TransitionUtils.kt
1
2758
/* * 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.util import android.graphics.Bitmap import android.graphics.Canvas import android.graphics.Matrix import android.graphics.RectF import android.view.View /** * Static utility methods for Transitions. */ object TransitionUtils { private const val MAX_IMAGE_SIZE = 1024 * 1024 /** * Creates a Bitmap of the given view, using the Matrix matrix to transform to the local * coordinates. `matrix` will be modified during the bitmap creation. * * If the bitmap is large, it will be scaled uniformly down to at most 1MB size. * * @param view The view to create a bitmap for. * * @param matrix The matrix converting the view local coordinates to the coordinates that * the bitmap will be displayed in. `matrix` will be modified before * returning. * * @param bounds The bounds of the bitmap in the destination coordinate system (where the * view should be presented. Typically, this is matrix.mapRect(viewBounds); * * @return A bitmap of the given view or null if bounds has no width or height. */ fun createViewBitmap(view: View, matrix: Matrix, bounds: RectF): Bitmap? { if (bounds.isEmpty) return null var bitmapWidth = Math.round(bounds.width()) var bitmapHeight = Math.round(bounds.height()) val scale = Math.min(1f, MAX_IMAGE_SIZE.toFloat() / (bitmapWidth * bitmapHeight)) bitmapWidth *= scale.toInt() bitmapHeight *= scale.toInt() matrix.postTranslate(-bounds.left, -bounds.top) matrix.postScale(scale, scale) val bitmap = Bitmap.createBitmap(bitmapWidth, bitmapHeight, Bitmap.Config.ARGB_8888) val canvas = Canvas(bitmap!!) canvas.concat(matrix) view.draw(canvas) return bitmap } }
gpl-3.0
47802e3a9af4847576503b23200cfb1a
38.414286
93
0.686004
4.178788
false
false
false
false
AndroidX/androidx
glance/glance-appwidget/src/androidMain/kotlin/androidx/glance/appwidget/template/GlanceAppWidgetTemplates.kt
3
10978
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.glance.appwidget.template import androidx.compose.runtime.Composable import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.DpSize import androidx.compose.ui.unit.TextUnit import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.glance.Button import androidx.glance.GlanceModifier import androidx.glance.GlanceTheme import androidx.glance.Image import androidx.glance.LocalSize import androidx.glance.action.clickable import androidx.glance.layout.Alignment import androidx.glance.layout.Column import androidx.glance.layout.ContentScale import androidx.glance.layout.Row import androidx.glance.layout.Spacer import androidx.glance.layout.fillMaxWidth import androidx.glance.layout.height import androidx.glance.layout.size import androidx.glance.layout.width import androidx.glance.template.ActionBlock import androidx.glance.template.HeaderBlock import androidx.glance.template.ImageBlock import androidx.glance.template.ImageSize import androidx.glance.template.TemplateButton import androidx.glance.template.TemplateImageButton import androidx.glance.template.TemplateImageWithDescription import androidx.glance.template.TemplateText import androidx.glance.template.TemplateTextButton import androidx.glance.template.TextBlock import androidx.glance.template.TextType import androidx.glance.text.Text import androidx.glance.text.TextStyle /** * Default header template layout implementation for AppWidgets, usually displayed at the top of the * glanceable in default layout implementations. * * @param headerIcon glanceable main logo icon * @param header main header text */ @Composable internal fun AppWidgetTemplateHeader( headerIcon: TemplateImageWithDescription? = null, header: TemplateText? = null, ) { if (headerIcon == null && header == null) return Row( modifier = GlanceModifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically ) { headerIcon?.let { Image( provider = it.image, contentDescription = it.description, modifier = GlanceModifier.height(24.dp).width(24.dp) ) } header?.let { if (headerIcon != null) { Spacer(modifier = GlanceModifier.width(8.dp)) } val size = textSize(TextType.Title, DisplaySize.fromDpSize(LocalSize.current)) Text( modifier = GlanceModifier.defaultWeight(), text = header.text, style = TextStyle( fontSize = size, color = GlanceTheme.colors.onSurface ), maxLines = 1 ) } } } /** * Default header template layout implementation for AppWidgets, usually displayed at the top of the * glanceable in default layout implementations by [HeaderBlock]. * * @param headerBlock The glanceable header block to display */ @Composable internal fun AppWidgetTemplateHeader(headerBlock: HeaderBlock) { AppWidgetTemplateHeader( headerBlock.icon, headerBlock.text, ) } /** * Default text section layout for AppWidgets. Displays an ordered list of text fields, styled * according to the [TextType] of each field. * * @param textList the ordered list of text fields to display in the block */ @Composable internal fun AppWidgetTextSection(textList: List<TemplateText>) { if (textList.isEmpty()) return Column { textList.forEachIndexed { index, item -> val size = textSize(item.type, DisplaySize.fromDpSize(LocalSize.current)) Text( item.text, style = TextStyle(fontSize = size, color = GlanceTheme.colors.onSurface), maxLines = maxLines(item.type) ) if (index < textList.size - 1) { Spacer(modifier = GlanceModifier.height(8.dp)) } } } } /** * Displays a [TemplateButton] for AppWidget layouts. * * @param button text or image button * @param glanceModifier Glance modifier for further text or image button customization */ @Composable internal fun AppWidgetTemplateButton( button: TemplateButton, glanceModifier: GlanceModifier = GlanceModifier ) { when (button) { is TemplateImageButton -> { // TODO: Specify sizing for image button val image = button.image Image( provider = image.image, contentDescription = image.description, modifier = glanceModifier.clickable(button.action) ) } is TemplateTextButton -> { Button( text = button.text, onClick = button.action, style = TextStyle(color = GlanceTheme.colors.onPrimary), modifier = glanceModifier ) } } } /** * Displays an [ImageBlock] as a single image for AppWidget layout template. * * @param imageBlock The [ImageBlock] data containing the main image for display * @param modifier Glance modifier for further image button customization */ @Composable internal fun SingleImageBlockTemplate( imageBlock: ImageBlock, modifier: GlanceModifier = GlanceModifier ) { if (imageBlock.images.isNotEmpty()) { val mainImage = imageBlock.images[0] val imageSize: Dp = when (imageBlock.size) { ImageSize.Small -> 64.dp ImageSize.Medium -> 96.dp ImageSize.Large -> 128.dp ImageSize.Undefined -> 96.dp else -> 96.dp } Image( provider = mainImage.image, contentDescription = mainImage.description, modifier = if (ImageSize.Undefined == imageBlock.size) modifier else modifier.size( imageSize ), contentScale = ContentScale.Crop ) } } /** * Displays a [TextBlock] with top three types of text lines for AppWidget layout template. * * @param textBlock The [TextBlock] data containing top three types of text lines. */ @Composable internal fun TextBlockTemplate(textBlock: TextBlock) { AppWidgetTextSection( listOfNotNull( textBlock.text1, textBlock.text2, textBlock.text3, ) ) } /** * Displays a [HeaderBlock] with header information. * * @param headerBlock The [HeaderBlock] data containing the header information. */ @Composable internal fun HeaderBlockTemplate(headerBlock: HeaderBlock?) { headerBlock?.let { AppWidgetTemplateHeader(it) } } /** * Displays an [ActionBlock] as a sequence of action buttons for AppWidget layout template. * * @param actionBlock The [ActionBlock] data containing a list of buttons for display */ @Composable internal fun ActionBlockTemplate(actionBlock: ActionBlock?) { if (actionBlock?.actionButtons?.isNotEmpty() == true) { Row { actionBlock.actionButtons.forEach { button -> AppWidgetTemplateButton(button) Spacer(modifier = GlanceModifier.width(4.dp)) } } } } /** * Displays an entity of a block of texts from a [TextBlock] and an image from an [ImageBlock] * ordered by priority of the blocks with the default to the [TextBlock] being ahead of the * [ImageBlock] if they have the same priority. * * @param textBlock The [TextBlock] for an entity. * @param imageBlock The [ImageBlock] for an entity. * @param modifier The modifier for the textBlock in relation to the imageBlock. */ @Composable internal fun TextAndImageBlockTemplate( textBlock: TextBlock, imageBlock: ImageBlock? = null, modifier: GlanceModifier = GlanceModifier ) { if (imageBlock == null || imageBlock.images.isEmpty()) { TextBlockTemplate(textBlock) } else { // Show first block by lower numbered priority if (textBlock.priority <= imageBlock.priority) { Column( modifier = modifier, verticalAlignment = Alignment.Vertical.CenterVertically ) { TextBlockTemplate(textBlock) } Spacer(modifier = GlanceModifier.width(16.dp)) SingleImageBlockTemplate(imageBlock) } else { SingleImageBlockTemplate(imageBlock) Spacer(modifier = GlanceModifier.width(16.dp)) Column( modifier = modifier, verticalAlignment = Alignment.Vertical.CenterVertically ) { TextBlockTemplate(textBlock) } } } } private enum class DisplaySize { Small, Medium, Large; companion object { fun fromDpSize(dpSize: DpSize): DisplaySize = if (dpSize.width < 180.dp && dpSize.height < 120.dp) { Small } else if (dpSize.width < 280.dp && dpSize.height < 180.dp) { Medium } else { Large } } } private fun textSize(textClass: TextType, displaySize: DisplaySize): TextUnit = when (textClass) { // TODO: Does display scale? TextType.Display -> 45.sp TextType.Title -> { when (displaySize) { DisplaySize.Small -> 14.sp DisplaySize.Medium -> 16.sp DisplaySize.Large -> 22.sp } } TextType.Headline -> { when (displaySize) { DisplaySize.Small -> 12.sp DisplaySize.Medium -> 14.sp DisplaySize.Large -> 18.sp } } TextType.Body -> { when (displaySize) { DisplaySize.Small -> 12.sp DisplaySize.Medium -> 14.sp DisplaySize.Large -> 14.sp } } TextType.Label -> { when (displaySize) { DisplaySize.Small -> 11.sp DisplaySize.Medium -> 12.sp DisplaySize.Large -> 14.sp } } else -> 12.sp } private fun maxLines(textClass: TextType): Int = when (textClass) { TextType.Display -> 1 TextType.Title -> 3 TextType.Body -> 3 TextType.Label -> 1 TextType.Headline -> 1 else -> 1 }
apache-2.0
fbe67661ce3405654c23e6d0c9ebb53b
30.912791
100
0.635362
4.626212
false
false
false
false
codeka/wwmmo
planet-render/src/main/kotlin/au/com/codeka/warworlds/planetrender/PlanetRenderer.kt
1
2312
package au.com.codeka.warworlds.planetrender import au.com.codeka.warworlds.common.Colour import au.com.codeka.warworlds.common.Colour.Companion.blend import au.com.codeka.warworlds.common.Image import au.com.codeka.warworlds.planetrender.Template.PlanetTemplate import au.com.codeka.warworlds.planetrender.Template.PlanetsTemplate import java.awt.image.BufferedImage import java.util.* /** * This is actually a very simple ray-tracing engine. The simplicity comes from the fact that * we assume there's only one object in the scene (the planet) and one light source (the sun). */ class PlanetRenderer { private val singlePlanetGenerators = ArrayList<SinglePlanetGenerator>() constructor(tmpl: PlanetTemplate, rand: Random) { singlePlanetGenerators.add(SinglePlanetGenerator(tmpl, rand)) } constructor(tmpl: PlanetsTemplate, rand: Random) { for (planetTmpl in tmpl.getParameters(PlanetTemplate::class.java)) { singlePlanetGenerators.add(SinglePlanetGenerator(planetTmpl, rand)) } } /** * Renders a planet into the given [Image]. */ fun render(img: Image) { var i = 0 for (planetGenerator in singlePlanetGenerators) { for (y in 0 until img.height) { for (x in 0 until img.width) { val nx = x.toDouble() / img.width.toDouble() - 0.5 val ny = y.toDouble() / img.height.toDouble() - 0.5 val c = planetGenerator.getPixelColour(nx, ny) if (i == 0) { img.setPixelColour(x, y, c) } else { img.blendPixelColour(x, y, c) } } } i++ } } /** * Renders a planet into the given [BufferedImage]. */ fun render(img: BufferedImage) { var i = 0 for (planetGenerator in singlePlanetGenerators) { for (y in 0 until img.height) { for (x in 0 until img.width) { val nx = x.toDouble() / img.width.toDouble() - 0.5 val ny = y.toDouble() / img.height.toDouble() - 0.5 val c = planetGenerator.getPixelColour(nx, ny) if (i == 0) { img.setRGB(x, y, c.toArgb()) } else { var imgColour = Colour(img.getRGB(x, y)) imgColour = blend(imgColour, c) img.setRGB(x, y, imgColour.toArgb()) } } } i++ } } }
mit
6a361f4fdd3c28866695f6be6652134c
30.671233
94
0.62846
3.675676
false
false
false
false
mvarnagiris/expensius
app/src/main/kotlin/com/mvcoding/expensius/feature/premium/PremiumActivity.kt
1
4046
/* * Copyright (C) 2016 Mantas Varnagiris. * * 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. */ package com.mvcoding.expensius.feature.premium import android.content.Context import android.content.Intent import android.os.Bundle import android.support.design.widget.Snackbar import android.support.v7.widget.LinearLayoutManager import android.view.View import android.view.View.GONE import android.view.View.VISIBLE import android.view.ViewGroup import com.jakewharton.rxbinding.support.v4.widget.refreshes import com.mvcoding.expensius.R import com.mvcoding.expensius.extension.inflate import com.mvcoding.expensius.extension.snackbar import com.mvcoding.expensius.feature.* import kotlinx.android.synthetic.main.activity_premium.* import kotlinx.android.synthetic.main.item_view_billing_product.view.* import rx.Observable import rx.subjects.PublishSubject class PremiumActivity : BaseActivity(), PremiumPresenter.View { companion object { fun start(context: Context) = ActivityStarter(context, PremiumActivity::class).start() } private val REQUEST_BILLING = 1 private val presenter by lazy { providePremiumPresenter() } private val billingFlow by lazy { provideBillingFlow() } private val adapter by lazy { Adapter() } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_premium) recyclerView.setHasFixedSize(true) recyclerView.layoutManager = LinearLayoutManager(this) recyclerView.adapter = adapter presenter.attach(this) } override fun onDestroy() { super.onDestroy() presenter.detach(this) } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) billingFlow.onActivityResult(requestCode, resultCode, data) } override fun showFreeUser() = subscriptionTextView.setText(R.string.long_user_is_using_free_version) override fun showPremiumUser() = subscriptionTextView.setText(R.string.long_user_is_using_premium_version) override fun refreshes() = swipeRefreshLayout.refreshes() override fun billingProductSelects(): Observable<BillingProduct> = adapter.itemPositionClicks().map { adapter.getItem(it) } override fun showBillingProducts(billingProducts: List<BillingProduct>) = adapter.setItems(billingProducts) override fun displayBuyProcess(productId: String) = billingFlow.startPurchase(this, REQUEST_BILLING, productId) override fun showLoading(): Unit = with(swipeRefreshLayout) { isRefreshing = true } override fun hideLoading(): Unit = with(swipeRefreshLayout) { isRefreshing = false } override fun showEmptyView(): Unit = with(emptyTextView) { visibility = VISIBLE } override fun hideEmptyView(): Unit = with(emptyTextView) { visibility = GONE } override fun showError(error: Error) { snackbar(R.string.error_refreshing_purchases, Snackbar.LENGTH_LONG).show() } private class Adapter : BaseClickableAdapter<BillingProduct, ClickableViewHolder>() { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int, clickSubject: PublishSubject<Pair<View, Int>>) = ClickableViewHolder(parent.inflate(R.layout.item_view_billing_product), clickSubject) override fun onBindViewHolder(holder: ClickableViewHolder, position: Int) { holder.itemView.titleTextView.text = getItem(position).title holder.itemView.priceTextView.text = getItem(position).price } } }
gpl-3.0
83278a685a2a2b92a5ed6d2305388d04
42.98913
127
0.753831
4.597727
false
false
false
false
Dr-Horv/Advent-of-Code-2017
src/main/kotlin/solutions/day23/Day23.kt
1
2558
package solutions.day23 import solutions.Solver import utils.* class Day23 : Solver { override fun solve(input: List<String>, partTwo: Boolean): String { if (partTwo) { return doPartTwo() } val registers = mutableMapOf<String, Long>().withDefault { 0 } val instructions = input var index = 0L var iteration = 0 var mulUsed = 0 loop@ while (index < instructions.size) { iteration++ val instruction = instructions[index.toInt()].splitAtWhitespace() when (instruction[0]) { "set" -> set(registers, instruction[1], instruction[2]) "sub" -> sub(registers, instruction[1], instruction[2]) "mul" -> { mul(registers, instruction[1], instruction[2]) mulUsed++ } "jnz" -> { if (getValue(registers, instruction[1]) != 0L) { index += getValue(registers, instruction[2]) continue@loop } } } index++ } return mulUsed.toString() } private fun doPartTwo(): String { var a = 1 var b = 0 var c = 0 var d = 0 var e = 0 var f = 0 var g = 0 var h = 0 b = 65 // set b 65 c = b // set c b if(a != 0) { b = b * 100 // mul b 100 b = b + 100_000 // sub b -100_000 c = b // set c b c = c + 17_000 // sub c -17_000 } loop3@ while (true) { f = 1 // set f 1 d = 2 // set d 2 loop2@ while (true) { loop1@ while (true) { if(b % d == 0) { f = 0 } e = b g = e - b // sub g b if (g == 0) { // jnz g -8 break@loop1 } } d++ // sub d -1 g = d - b // sub g b if (g == 0) { // jnz g -13 break@loop2 } } if (f == 0) { // jnz f 2 h++ // sub h -1 } g = b - c // sub g c if (g == 0) { // jnz g 2, jnz 1 3 break@loop3 } b = b + 17 // sub - 17 // jnz 1 -23 } return h.toString() } }
mit
260a392c7cc2bca18db8f02180fddc08
25.645833
77
0.361611
4.306397
false
false
false
false
HabitRPG/habitrpg-android
Habitica/src/main/java/com/habitrpg/android/habitica/models/TutorialStep.kt
1
1070
package com.habitrpg.android.habitica.models import io.realm.RealmModel import io.realm.RealmObject import io.realm.annotations.RealmClass import java.util.Date @RealmClass(embedded = true) open class TutorialStep : RealmObject(), BaseMainObject { var key: String? = null var tutorialGroup: String? = null set(group) { field = group this.key = group + "_" + this.identifier } var identifier: String? = null set(identifier) { field = identifier this.key = this.tutorialGroup + "_" + identifier } var wasCompleted: Boolean = false var displayedOn: Date? = null fun shouldDisplay(): Boolean = !this.wasCompleted && (this.displayedOn == null || Date().time - (displayedOn?.time ?: 0) > 86400000) override val realmClass: Class<out RealmModel> get() = TutorialStep::class.java override val primaryIdentifier: String? get() = key override val primaryIdentifierName: String get() = "key" }
gpl-3.0
a4fbf2bb214333c90cf441205af5c0ee
29.470588
109
0.619626
4.367347
false
false
false
false
charleskorn/batect
app/src/main/kotlin/batect/docker/pull/DockerRegistryDomainResolver.kt
1
1287
/* Copyright 2017-2020 Charles Korn. 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 batect.docker.pull import batect.docker.defaultRegistryName // The logic for this is based on https://github.com/docker/distribution/blob/master/reference/normalize.go. class DockerRegistryDomainResolver { fun resolveDomainForImage(imageName: String): String { val possibleRegistryName = imageName.substringBefore("/", defaultRegistryName) if (possibleRegistryName == "index.docker.io") { return defaultRegistryName } if (possibleRegistryName.contains('.') || possibleRegistryName.contains(':') || possibleRegistryName == "localhost") { return possibleRegistryName } return defaultRegistryName } }
apache-2.0
ef7833867f6795f829f13598bd08e08d
34.75
126
0.724165
4.912214
false
false
false
false
kiruto/debug-bottle
components/src/main/kotlin/com/exyui/android/debugbottle/components/SearchableListViewHelper.kt
1
1175
package com.exyui.android.debugbottle.components import java.util.regex.Pattern /** * Created by yuriel on 8/17/16. */ internal object SearchableListViewHelper { fun getPattern(str: String): Pattern { var patternStr = ".*" for (c in str) { patternStr += "($c).*" } return Pattern.compile(patternStr, Pattern.CASE_INSENSITIVE) } interface HighlightListener<T> { val collections: Collection<T> fun getString(t: T): String fun update(map: Map<T, List<String>>, str: String) fun highlight(p: Pattern, str: String = ""): Map<T, List<String>> { val result = mutableMapOf<T, List<String>>() for (t in collections) { val matcher = p.matcher(getString(t)) if (!matcher.matches()) continue //val index = collections.indexOf(t) val l = mutableListOf<String>() for (i in 0..matcher.groupCount() - 1) { l.add(matcher.group(i)) } result.put(t, l) } update(result, str) return result } } }
apache-2.0
d1b703e8b738415420e6bb6be7ee94a0
27.682927
75
0.531064
4.272727
false
false
false
false
kotlinx/kotlinx.html
src/jvmTest/kotlin/html5-tags.kt
1
1831
package kotlinx.html.tests import kotlinx.html.* import kotlinx.html.dom.* import kotlin.test.* import org.junit.Test as test class Html5TagsTest { @Test fun able_to_create_main_tag() { val tree = createHTMLDocument().html { body { main(classes = "main-test") { id = "test-node" +"content" } } } print(tree.serialize(true).trim().replace("\r\n", "\n")) assertEquals("<!DOCTYPE html>\n<html><body><main class=\"main-test\" id=\"test-node\">content</main></body></html>", tree.serialize(false)) assertEquals(""" <!DOCTYPE html> <html> <body> <main class="main-test" id="test-node">content</main> </body> </html>""".trimIndent(), tree.serialize(true).trim().replace("\r\n", "\n")) } @test fun `able to create complex tree and render it with pretty print`() { val tree = createHTMLDocument().html { body { h1 { +"header" } div { +"content" span { +"yo" } } } } assertEquals("<!DOCTYPE html>\n<html><body><h1>header</h1><div>content<span>yo</span></div></body></html>", tree.serialize(false)) assertEquals(""" <!DOCTYPE html> <html> <body> <h1>header</h1> <div> content<span>yo</span> </div> </body> </html>""".trimIndent(), tree.serialize(true).trim().replace("\r\n", "\n")) } }
apache-2.0
2b4673cc277e229b8c27becb74190248
29.533333
147
0.425997
4.554726
false
true
false
false
dropbox/Store
store/src/main/java/com/dropbox/android/external/store4/impl/SourceOfTruthWithBarrier.kt
1
8590
/* * Copyright 2019 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.dropbox.android.external.store4.impl import com.dropbox.android.external.store4.ResponseOrigin import com.dropbox.android.external.store4.SourceOfTruth import com.dropbox.android.external.store4.StoreResponse import com.dropbox.android.external.store4.impl.operators.mapIndexed import kotlinx.coroutines.CancellationException import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.catch import kotlinx.coroutines.flow.emitAll import kotlinx.coroutines.flow.flatMapLatest import kotlinx.coroutines.flow.flow import kotlinx.coroutines.flow.flowOf import kotlinx.coroutines.flow.onStart import java.util.concurrent.atomic.AtomicLong /** * Wraps a [SourceOfTruth] and blocks reads while a write is in progress. * * Used in the [com.dropbox.android.external.store4.impl.RealStore] implementation to avoid * dispatching values to downstream while a write is in progress. */ internal class SourceOfTruthWithBarrier<Key, Input, Output>( private val delegate: SourceOfTruth<Key, Input, Output> ) { /** * Each key has a barrier so that we can block reads while writing. */ private val barriers = RefCountedResource<Key, MutableStateFlow<BarrierMsg>>( create = { MutableStateFlow(BarrierMsg.Open.INITIAL) } ) /** * Each message gets dispatched with a version. This ensures we won't accidentally turn on the * reader flow for a new reader that happens to have arrived while a write is in progress since * that write should be considered as a disk read for that flow, not fetcher. */ private val versionCounter = AtomicLong(0) fun reader(key: Key, lock: CompletableDeferred<Unit>): Flow<StoreResponse<Output?>> { return flow { val barrier = barriers.acquire(key) val readerVersion: Long = versionCounter.incrementAndGet() try { lock.await() emitAll( barrier .flatMapLatest { val messageArrivedAfterMe = readerVersion < it.version val writeError = if (messageArrivedAfterMe && it is BarrierMsg.Open) { it.writeError } else { null } val readFlow: Flow<StoreResponse<Output?>> = when (it) { is BarrierMsg.Open -> delegate.reader(key).mapIndexed { index, output -> if (index == 0 && messageArrivedAfterMe) { val firstMsgOrigin = if (writeError == null) { // restarted barrier without an error means write succeeded ResponseOrigin.Fetcher } else { // when a write fails, we still get a new reader because // we've disabled the previous reader before starting the // write operation. But since write has failed, we should // use the SourceOfTruth as the origin ResponseOrigin.SourceOfTruth } StoreResponse.Data( origin = firstMsgOrigin, value = output ) } else { StoreResponse.Data( origin = ResponseOrigin.SourceOfTruth, value = output ) as StoreResponse<Output?> // necessary cast for catch block } }.catch { throwable -> this.emit( StoreResponse.Error.Exception( error = SourceOfTruth.ReadException( key = key, cause = throwable ), origin = ResponseOrigin.SourceOfTruth ) ) } is BarrierMsg.Blocked -> { flowOf() } } readFlow .onStart { // if we have a pending error, make sure to dispatch it first. if (writeError != null) { emit( StoreResponse.Error.Exception( origin = ResponseOrigin.SourceOfTruth, error = writeError ) ) } } } ) } finally { // we are using a finally here instead of onCompletion as there might be a // possibility where flow gets cancelled right before `emitAll`. barriers.release(key, barrier) } } } suspend fun write(key: Key, value: Input) { val barrier = barriers.acquire(key) try { barrier.emit(BarrierMsg.Blocked(versionCounter.incrementAndGet())) val writeError = try { delegate.write(key, value) null } catch (throwable: Throwable) { if (throwable !is CancellationException) { throwable } else { null } } barrier.emit( BarrierMsg.Open( version = versionCounter.incrementAndGet(), writeError = writeError?.let { SourceOfTruth.WriteException( key = key, value = value, cause = writeError ) } ) ) if (writeError is CancellationException) { // only throw if it failed because of cancelation. // otherwise, we take care of letting downstream know that there was a write error throw writeError } } finally { barriers.release(key, barrier) } } suspend fun delete(key: Key) { delegate.delete(key) } suspend fun deleteAll() { delegate.deleteAll() } private sealed class BarrierMsg( val version: Long ) { class Blocked(version: Long) : BarrierMsg(version) class Open(version: Long, val writeError: Throwable? = null) : BarrierMsg(version) { companion object { val INITIAL = Open(INITIAL_VERSION) } } } // visible for testing internal suspend fun barrierCount() = barriers.size() companion object { private const val INITIAL_VERSION = -1L } }
apache-2.0
b3610112ce1193b8d2d4ae72d4c52588
42.826531
107
0.471711
6.270073
false
false
false
false
noemus/kotlin-eclipse
kotlin-eclipse-ui/src/org/jetbrains/kotlin/ui/editors/selection/handlers/KotlinStringTemplateSelectionHandler.kt
1
1529
package org.jetbrains.kotlin.ui.editors.selection.handlers import org.jetbrains.kotlin.psi.KtStringTemplateExpression import com.intellij.psi.PsiElement import com.intellij.openapi.util.TextRange public class KotlinStringTemplateSelectionHandler: KotlinDefaultSelectionHandler() { override fun canSelect(enclosingElement: PsiElement) = enclosingElement is KtStringTemplateExpression override fun selectEnclosing(enclosingElement: PsiElement, selectedRange: TextRange): TextRange { val literalRange = super.selectEnclosing(enclosingElement, selectedRange) val resultRange = TextRange(literalRange.getStartOffset()+1, literalRange.getEndOffset()-1) if (!resultRange.contains(selectedRange) || resultRange.equals(selectedRange)) { return literalRange } //drop quotes return TextRange(literalRange.getStartOffset()+1, literalRange.getEndOffset()-1) } override fun selectNext(enclosingElement: PsiElement, selectionCandidate: PsiElement, selectedRange: TextRange): TextRange { if (selectionCandidate.getNextSibling() == null) {// is quote sign return enclosingElement.getTextRange() } return selectionWithElementAppendedToEnd(selectedRange, selectionCandidate) } override fun selectPrevious(enclosingElement: PsiElement, selectionCandidate:PsiElement, selectedRange: TextRange): TextRange { if (selectionCandidate.getPrevSibling() == null) {// is quote sign return enclosingElement.getTextRange() } return selectionWithElementAppendedToBeginning(selectedRange, selectionCandidate) } }
apache-2.0
ed1f1ce80fc97d1587d97bcd861003c5
44
128
0.814912
4.793103
false
false
false
false
vitorsalgado/android-boilerplate
api/src/main/kotlin/br/com/vitorsalgado/example/api/ApiResponse.kt
1
916
package br.com.vitorsalgado.example.api import retrofit2.Response import java.io.IOException class ApiResponse<T> { private val statusCode: Int val body: T? private val errorMessage: String? val isSuccessful: Boolean get() = statusCode in 200..399 constructor(error: Throwable) { statusCode = 500 body = null errorMessage = error.message } internal constructor(response: Response<T>) { statusCode = response.code() if (response.isSuccessful) { body = response.body() errorMessage = null } else { var message: String? = null if (response.errorBody() != null) { try { message = response.errorBody()!!.string() } catch (ignored: IOException) { } } if (message == null || message.isEmpty()) { message = response.message() } errorMessage = message body = null } } }
apache-2.0
f163e51232716debf03a809b4b52f155
18.913043
51
0.611354
4.361905
false
false
false
false
krupalshah/Locate
app/src/main/java/com/experiments/locate/helper/storage/PreferenceHelper.kt
1
2493
/* * Copyright (c) 2016 Krupal Shah * * 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.experiments.locate.helper.storage import android.content.Context import android.content.SharedPreferences /** * Created by Krupal Shah on 17-Dec-16. * * helper for shared prefs */ object PreferenceHelper { private const val DEFAULT_PREFS = "locate_prefs" fun defaultPrefs(context: Context): SharedPreferences = getPreferences(context = context, name = DEFAULT_PREFS) fun getPreferences(context: Context, name: String): SharedPreferences = context.applicationContext.getSharedPreferences(name, Context.MODE_PRIVATE) inline fun SharedPreferences.edit(operation: (SharedPreferences.Editor) -> Unit) { val editor = this.edit() operation(editor) editor.apply() } /** * puts a key value pair in sharedprefs if doesn't exists, otherwise updates value on given key */ operator fun SharedPreferences.set(key: String, value: Any) { when (value) { is String -> edit(operation = { editor -> editor.putString(key, value) }) is Int -> edit(operation = { editor -> editor.putInt(key, value) }) is Boolean -> edit(operation = { editor -> editor.putBoolean(key, value) }) is Float -> edit(operation = { editor -> editor.putFloat(key, value) }) is Long -> edit(operation = { editor -> editor.putLong(key, value) }) } } /** * get get value on given key. *[T] is type of class for needed value */ operator inline fun <reified T> SharedPreferences.get(key: String): T? { when (T::class) { String::class -> getString(key, null) Int::class -> getInt(key, -1) Boolean::class -> getBoolean(key, false) Float::class -> getFloat(key, -1f) Long::class -> getLong(key, -1) } return null } }
apache-2.0
bf86e3c459e0f04baa3dd0e208edf450
34.126761
99
0.637786
4.204047
false
false
false
false
handstandsam/ShoppingApp
app/src/main/java/com/handstandsam/shoppingapp/di/SessionGraph.kt
1
1816
package com.handstandsam.shoppingapp.di import android.content.Context import com.handstandsam.shoppingapp.cart.ActorStateFlowShoppingCartDao import com.handstandsam.shoppingapp.cart.ShoppingCart import com.handstandsam.shoppingapp.cart.ShoppingCartDao import com.handstandsam.shoppingapp.preferences.UserPreferences import com.handstandsam.shoppingapp.repository.SessionManager interface SessionGraph { val sessionManager: SessionManager val shoppingCart: ShoppingCart val userPreferences: UserPreferences } class SessionGraphImpl( appContext: Context ) : SessionGraph { private enum class DatabaseType { IN_MEMORY, ROOM, SQLDELIGHT } private val dbType = DatabaseType.IN_MEMORY private val shoppingCartDao: ShoppingCartDao = when (dbType) { DatabaseType.IN_MEMORY -> { ActorStateFlowShoppingCartDao() } DatabaseType.ROOM -> { error("Add the dependency for shopping-room") // RoomShoppingCartDao( // Room.databaseBuilder( // appContext, // RoomItemInCartDatabase::class.java, // "cart_room.db" // ).build() // ) } DatabaseType.SQLDELIGHT -> { error("Add the dependency for shopping-cartsqldelight") // SqlDelightShoppingCartDao( // AndroidSqliteDriver( // schema = Database.Schema, // context = appContext, // name = "cart_sqldelight.db" // ) // ) } } override val shoppingCart: ShoppingCart = ShoppingCart(shoppingCartDao) override val userPreferences = UserPreferences(appContext) override val sessionManager = SessionManager(shoppingCart, userPreferences) }
apache-2.0
d6bf5c5d39f4bec8b110df106d065ff5
32.036364
79
0.65033
5.058496
false
false
false
false
Tvede-dk/CommonsenseAndroidKotlin
widgets/src/main/kotlin/com/commonsense/android/kotlin/views/widgets/ViewAttribute.kt
1
4126
@file:Suppress("unused", "NOTHING_TO_INLINE", "MemberVisibilityCanBePrivate") package com.commonsense.android.kotlin.views.widgets import android.content.* import android.content.res.* import android.graphics.* import android.support.annotation.* import android.util.* import com.commonsense.android.kotlin.base.* import com.commonsense.android.kotlin.base.extensions.* import com.commonsense.android.kotlin.system.extensions.* import com.commonsense.android.kotlin.system.logging.* import com.commonsense.android.kotlin.views.datastructures.* import java.lang.ref.* /** * Created by Kasper Tvede on 13-06-2017. */ interface ViewAttribute { /** * if any custom attributes, return the name of the styles. */ @StyleableRes fun getStyleResource(): IntArray? /** * if any custom attributes, parse them */ fun parseTypedArray(data: TypedArray) { val context = getContext() attributes.forEach { it.use { parse(data, context) } } } /** * callback for when to update the ui (from state). */ fun updateView() fun afterSetupView() fun getContext(): Context fun post(action: Runnable): Boolean fun post(action: EmptyFunction) { post(Runnable(action)) } fun invalidate() @VisibleForTesting(otherwise = VisibleForTesting.PROTECTED) val attributes: MutableList<WeakReference<ViewVariable<*>>> } fun ViewAttribute.colorVariable(@ColorInt defaultValue: Int, @StyleableRes styleIndex: Int): ColorValueViewVariable = ColorValueViewVariable(defaultValue, styleIndex, attributes, this::updateView) fun ViewAttribute.colorVariable(@StyleableRes styleIndex: Int): ColorValueViewVariable = colorVariable(Color.BLACK, styleIndex) fun ViewAttribute.intVariable(defaultValue: Int, @StyleableRes styleIndex: Int): IntViewVariable = IntViewVariable(defaultValue, styleIndex, attributes, this::updateView) fun ViewAttribute.intVariable(@StyleableRes styleIndex: Int): IntViewVariable = intVariable(0, styleIndex) fun ViewAttribute.textVariable(@StyleableRes styleIndex: Int): TextViewVariable = TextViewVariable(styleIndex, attributes, this::updateView) fun ViewAttribute.booleanVariable(defaultValue: Boolean, @StyleableRes styleIndex: Int): BooleanViewVariable = BooleanViewVariable(defaultValue, styleIndex, attributes, this::updateView) fun ViewAttribute.booleanVariable(@StyleableRes styleIndex: Int): BooleanViewVariable = booleanVariable(false, styleIndex) fun ViewAttribute.drawableVariable(@StyleableRes styleIndex: Int): DrawableViewVariable = DrawableViewVariable(styleIndex, attributes, this::updateView) fun ViewAttribute.dimensionVariable(@StyleableRes styleIndex: Int): DimensionViewVariable = dimensionVariable(0f, styleIndex) fun ViewAttribute.dimensionVariable(@Dimension defaultValue: Float, @StyleableRes styleIndex: Int) : DimensionViewVariable = DimensionViewVariable(defaultValue, styleIndex, attributes, this::updateView) fun ViewAttribute.prepareAttributes(attrs: AttributeSet? = null, defStyleAttr: Int? = null) { val style = getStyleResource() if (style != null && attrs != null) { val typedArray = getContext().getTypedArrayFor(attrs, style, defStyleAttr ?: 0) tryAndLog(this::class) { parseTypedArray(typedArray) } typedArray.recycle() afterSetupView() updateView() } else { afterSetupView() } } interface LateAttributes : ViewAttribute { var partialTypedArray: TypedArray? fun setupTypedArray(attrs: AttributeSet?, defStyleAttr: Int = 0) { val style = getStyleResource() if (style != null && attrs != null) partialTypedArray = getContext().getTypedArrayFor(attrs, style, defStyleAttr) } fun afterFinishInflate() { partialTypedArray?.let { tryAndLog(this::class) { parseTypedArray(it) } it.recycle() } partialTypedArray = null afterSetupView() updateView() } }
mit
8c407d3ef7d02bc9590f4597b181fc34
30.738462
117
0.7111
4.579356
false
false
false
false
pbauerochse/youtrack-worklog-viewer
application/src/main/java/de/pbauerochse/worklogviewer/fx/components/statistics/panels/TimePerUserAndProjectGraphStatistics.kt
1
2901
package de.pbauerochse.worklogviewer.fx.components.statistics.panels import de.pbauerochse.worklogviewer.fx.components.statistics.data.TaskCountByProjectAndUserStatisticData import de.pbauerochse.worklogviewer.util.FormattingUtil.formatMinutes import de.pbauerochse.worklogviewer.util.FormattingUtil.getFormatted import javafx.scene.chart.CategoryAxis import javafx.scene.chart.NumberAxis import javafx.scene.chart.StackedBarChart import javafx.scene.control.Tooltip import javafx.scene.layout.Priority import javafx.scene.layout.VBox import org.slf4j.LoggerFactory /** * Displays the time spent by a user as a bar graph * Each bar is divided into sections fpr the different * projects, the user worked on */ class TimePerUserAndProjectGraphStatistics( private val statisticsData: TaskCountByProjectAndUserStatisticData, employeeAxis: NumberAxis = NumberAxis() ) : StackedBarChart<Number, String>(employeeAxis, CategoryAxis()) { private var alreadyRendered = false init { title = getFormatted("view.statistics.byemployeeandproject") prefHeight = (HEIGHT_PER_Y_AXIS_ELEMENT * statisticsData.numberOfUsers + HEIGHT_PER_X_AXIS_ELEMENT * statisticsData.projectStatistic.size + ADDITIONAL_HEIGHT).toDouble() styleClass.add("statistic-item") employeeAxis.apply { label = getFormatted("view.statistics.timespentinhours") tickLabelRotation = 90.0 } VBox.setVgrow(this, Priority.ALWAYS) renderStatisticsIfNecessary() visibleProperty().addListener { _, _, _ -> renderStatisticsIfNecessary() } } private fun renderStatisticsIfNecessary() { if (isVisible && !alreadyRendered) { LOGGER.debug("Rendering Data") renderStatistics() alreadyRendered = true } } private fun renderStatistics() { statisticsData.projectStatistic.forEach { projectStatistic -> val series = Series<Number, String>() series.name = projectStatistic.projectName projectStatistic.userStatistics.forEach { userSummary -> val timeSpentInHours = userSummary.timeSpentInMinutes.toDouble() / 60.0 val formattedTime = formatMinutes(userSummary.timeSpentInMinutes) val data = Data<Number, String>(timeSpentInHours, userSummary.user.label) series.data.add(data) data.nodeProperty().addListener { _, _, newNode -> Tooltip.install(newNode, Tooltip("${series.name} - $formattedTime")) } } data.add(series) } } companion object { private const val HEIGHT_PER_Y_AXIS_ELEMENT = 40 private const val HEIGHT_PER_X_AXIS_ELEMENT = 35 private const val ADDITIONAL_HEIGHT = 150 private val LOGGER = LoggerFactory.getLogger(TimePerUserAndProjectGraphStatistics::class.java) } }
mit
4176f4fd5b2678fbd4b2fa618d641a4e
38.216216
177
0.704929
4.6416
false
false
false
false
jonashao/next-kotlin
app/src/main/java/com/junnanhao/next/MediaNotificationManager.kt
1
17916
/* * Copyright (C) 2014 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.junnanhao.next import android.app.Notification import android.app.NotificationChannel import android.app.NotificationManager import android.app.PendingIntent import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.content.IntentFilter import android.graphics.Bitmap import android.graphics.Canvas import android.graphics.Color import android.graphics.drawable.BitmapDrawable import android.graphics.drawable.Drawable import android.os.Build import android.os.RemoteException import android.support.annotation.RequiresApi import android.support.v4.app.NotificationCompat import android.support.v4.app.NotificationManagerCompat import android.support.v4.content.ContextCompat import android.support.v4.graphics.drawable.DrawableCompat import android.support.v4.media.MediaDescriptionCompat import android.support.v4.media.MediaMetadataCompat import android.support.v4.media.session.MediaControllerCompat import android.support.v4.media.session.MediaSessionCompat import android.support.v4.media.session.PlaybackStateCompat import com.facebook.common.executors.UiThreadImmediateExecutorService import com.facebook.common.references.CloseableReference import com.facebook.datasource.DataSource import com.facebook.drawee.backends.pipeline.Fresco import com.facebook.imagepipeline.datasource.BaseBitmapDataSubscriber import com.facebook.imagepipeline.image.CloseableImage import com.facebook.imagepipeline.request.ImageRequest import com.github.ajalt.timberkt.wtf import com.junnanhao.next.ui.MainActivity import com.junnanhao.next.utils.ResourceHelper /** * Keeps track of a notification and updates it automatically for a given * MediaSession. Maintaining a visible notification (usually) guarantees that the music service * won't be killed during playback. */ class MediaNotificationManager @Throws(RemoteException::class) constructor(private val mService: MusicService) : BroadcastReceiver() { private var mSessionToken: MediaSessionCompat.Token? = null private var mController: MediaControllerCompat? = null private var mTransportControls: MediaControllerCompat.TransportControls? = null private var mPlaybackState: PlaybackStateCompat? = null private var mMetadata: MediaMetadataCompat? = null private val mNotificationManager: NotificationManagerCompat private val mPauseIntent: PendingIntent private val mPlayIntent: PendingIntent private val mPreviousIntent: PendingIntent private val mNextIntent: PendingIntent private val mStopCastIntent: PendingIntent private val mNotificationColor: Int private var mStarted = false init { updateSessionToken() mNotificationColor = ResourceHelper.getThemeColor(mService, R.color.next_green, Color.GREEN) mNotificationManager = NotificationManagerCompat.from(mService) val pkg = mService.packageName mPauseIntent = PendingIntent.getBroadcast(mService, REQUEST_CODE, Intent(ACTION_PAUSE).setPackage(pkg), PendingIntent.FLAG_CANCEL_CURRENT) mPlayIntent = PendingIntent.getBroadcast(mService, REQUEST_CODE, Intent(ACTION_PLAY).setPackage(pkg), PendingIntent.FLAG_CANCEL_CURRENT) mPreviousIntent = PendingIntent.getBroadcast(mService, REQUEST_CODE, Intent(ACTION_PREV).setPackage(pkg), PendingIntent.FLAG_CANCEL_CURRENT) mNextIntent = PendingIntent.getBroadcast(mService, REQUEST_CODE, Intent(ACTION_NEXT).setPackage(pkg), PendingIntent.FLAG_CANCEL_CURRENT) mStopCastIntent = PendingIntent.getBroadcast(mService, REQUEST_CODE, Intent(ACTION_STOP_CASTING).setPackage(pkg), PendingIntent.FLAG_CANCEL_CURRENT) // Cancel all notifications to handle the case where the Service was killed and // restarted by the system. mNotificationManager.cancelAll() } @RequiresApi(Build.VERSION_CODES.O) private fun createChannels() { // create player channel val playerChannel = NotificationChannel(PLAYER_CHANNEL_ID, mService.resources.getString(R .string.notification_channel_player), NotificationManagerCompat.IMPORTANCE_HIGH) // Sets whether notifications posted to this channel should display notification lights playerChannel.enableLights(false) // Sets whether notification posted to this channel should vibrate. playerChannel.enableVibration(true) // Sets the notification light color for notifications posted to this channel playerChannel.lightColor = Color.GREEN // Sets whether notifications posted to this channel appear on the lock screen or not playerChannel.lockscreenVisibility = Notification.VISIBILITY_PUBLIC getManager()?.createNotificationChannel(playerChannel) } private var mManager: NotificationManager? = null private fun getManager(): NotificationManager? { if (mManager == null) { mManager = mService.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager } return mManager } /** * Posts the notification and starts tracking the session to keep it * updated. The notification will automatically be removed if the session is * destroyed before [.stopNotification] is called. */ fun startNotification() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { createChannels() } if (!mStarted) { mMetadata = mController?.metadata mPlaybackState = mController?.playbackState // The notification must be updated after setting started to true val notification = createNotification() if (notification != null) { mController!!.registerCallback(mCb) val filter = IntentFilter() filter.addAction(ACTION_NEXT) filter.addAction(ACTION_PAUSE) filter.addAction(ACTION_PLAY) filter.addAction(ACTION_PREV) filter.addAction(ACTION_STOP_CASTING) mService.registerReceiver(this, filter) mService.startForeground(NOTIFICATION_ID, notification) mStarted = true } } } /** * Removes the notification and stops tracking the session. If the session * was destroyed this has no effect. */ fun stopNotification() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { getManager()?.deleteNotificationChannel(PLAYER_CHANNEL_ID) } if (mStarted) { mStarted = false mController!!.unregisterCallback(mCb) try { mNotificationManager.cancel(NOTIFICATION_ID) mService.unregisterReceiver(this) } catch (ex: IllegalArgumentException) { // ignore if the receiver is not registered. } mService.stopForeground(true) } } override fun onReceive(context: Context, intent: Intent) { val action = intent.action wtf { "Received intent with action $action" } when (action) { ACTION_PAUSE -> mTransportControls!!.pause() ACTION_PLAY -> mTransportControls!!.play() ACTION_NEXT -> mTransportControls!!.skipToNext() ACTION_PREV -> mTransportControls!!.skipToPrevious() ACTION_STOP_CASTING -> { val i = Intent(context, MusicService::class.java) i.action = MusicService.ACTION_CMD i.putExtra(MusicService.CMD_NAME, MusicService.CMD_STOP_CASTING) mService.startService(i) } else -> wtf { "Unknown intent ignored. Action= $action" } } } /** * Update the state based on a change on the session token. Called either when * we are running for the first time or when the media session owner has destroyed the session * (see [android.media.session.MediaController.Callback.onSessionDestroyed]) */ @Throws(RemoteException::class) private fun updateSessionToken() { val freshToken = mService.sessionToken if (mSessionToken == null && freshToken != null || mSessionToken != null && mSessionToken != freshToken) { if (mController != null) { mController!!.unregisterCallback(mCb) } mSessionToken = freshToken if (mSessionToken != null) { mController = MediaControllerCompat(mService, mSessionToken!!) mTransportControls = mController!!.transportControls if (mStarted) { mController!!.registerCallback(mCb) } } } } private fun createContentIntent(description: MediaDescriptionCompat?): PendingIntent { val openUI = Intent(mService, MainActivity::class.java) openUI.flags = Intent.FLAG_ACTIVITY_SINGLE_TOP openUI.putExtra(MainActivity.EXTRA_START_FULLSCREEN, true) if (description != null) { openUI.putExtra(MainActivity.EXTRA_CURRENT_MEDIA_DESCRIPTION, description) } return PendingIntent.getActivity(mService, REQUEST_CODE, openUI, PendingIntent.FLAG_CANCEL_CURRENT) } private val mCb = object : MediaControllerCompat.Callback() { override fun onPlaybackStateChanged(state: PlaybackStateCompat) { mPlaybackState = state wtf { "Received new playback state $state" } if (state.state == PlaybackStateCompat.STATE_STOPPED || state.state == PlaybackStateCompat.STATE_NONE) { stopNotification() } else { val notification = createNotification() if (notification != null) { mNotificationManager.notify(NOTIFICATION_ID, notification) } } } override fun onMetadataChanged(metadata: MediaMetadataCompat?) { mMetadata = metadata wtf { "Received new metadata $metadata" } val notification = createNotification() if (notification != null) { mNotificationManager.notify(NOTIFICATION_ID, notification) } } override fun onSessionDestroyed() { super.onSessionDestroyed() wtf { "Session was destroyed, resetting to the new session token" } try { updateSessionToken() } catch (e: RemoteException) { wtf { "could not connect media controller $e" } } } } private fun createNotification(): Notification? { if (mMetadata == null || mPlaybackState == null) { return null } val notificationBuilder = NotificationCompat.Builder(mService, PLAYER_CHANNEL_ID) var playPauseButtonPosition = 0 // If skip to previous action is enabled if (mPlaybackState!!.actions and PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS != 0L) { notificationBuilder.addAction(R.drawable.ic_skip_previous_black_24dp, mService.getString(R.string.label_previous), mPreviousIntent) // If there is a "skip to previous" button, the play/pause button will // be the second one. We need to keep track of it, because the MediaStyle notification // requires to specify the index of the buttons (actions) that should be visible // when in compact view. playPauseButtonPosition = 1 } addPlayPauseAction(notificationBuilder) // If skip to next action is enabled if (mPlaybackState!!.actions and PlaybackStateCompat.ACTION_SKIP_TO_NEXT != 0L) { notificationBuilder.addAction(R.drawable.ic_skip_next_black_24dp, mService.getString(R.string.label_next), mNextIntent) } val description = mMetadata!!.description notificationBuilder .setStyle(android.support.v4.media.app.NotificationCompat.MediaStyle() .setShowActionsInCompactView(playPauseButtonPosition) // show only play/pause in compact view .setMediaSession(mSessionToken)) .setColor(mNotificationColor) .setSmallIcon(R.drawable.ic_next_sm) .setVisibility(NotificationCompat.VISIBILITY_PUBLIC) .setUsesChronometer(true) .setContentIntent(createContentIntent(description)) .setContentTitle(description.title) .setContentText(description.subtitle) // set default large icon val coverArt: Drawable = ContextCompat.getDrawable(mService, R.drawable.ic_music) DrawableCompat.setTint(coverArt, ContextCompat.getColor(mService, R.color.black_overlay)) notificationBuilder.setLargeIcon(coverArt.toBitmap()) // try to fetch large icon if (description.iconUri != null) { val imageRequest = ImageRequest.fromUri(description.iconUri) val imagePipeline = Fresco.getImagePipeline() val dataSource = imagePipeline.fetchDecodedImage(imageRequest, null) dataSource.subscribe(object : BaseBitmapDataSubscriber() { override fun onFailureImpl(dataSource: DataSource<CloseableReference<CloseableImage>>?) { } override fun onNewResultImpl(bitmap: Bitmap?) { notificationBuilder.setLargeIcon(bitmap) mNotificationManager.notify(NOTIFICATION_ID, notificationBuilder.build()) } }, UiThreadImmediateExecutorService.getInstance()) } if (mController != null && mController!!.extras != null) { val castName = mController!!.extras.getString(MusicService.EXTRA_CONNECTED_CAST) if (castName != null) { val castInfo = mService.resources .getString(R.string.casting_to_device, castName) notificationBuilder.setSubText(castInfo) notificationBuilder.addAction(R.drawable.ic_close_black_24dp, mService.getString(R.string.stop_casting), mStopCastIntent) } } setNotificationPlaybackState(notificationBuilder) return notificationBuilder.build() } private fun Drawable.toBitmap(): Bitmap { if (this is BitmapDrawable) { return bitmap } val width = if (intrinsicWidth > 0) intrinsicWidth else 1 val height = if (intrinsicHeight > 0) intrinsicHeight else 1 val bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888) val canvas = Canvas(bitmap) setBounds(0, 0, canvas.width, canvas.height) draw(canvas) return bitmap } private fun addPlayPauseAction(builder: NotificationCompat.Builder) { val label: String val icon: Int val intent: PendingIntent if (mPlaybackState!!.state == PlaybackStateCompat.STATE_PLAYING) { label = mService.getString(R.string.label_pause) icon = R.drawable.ic_pause_black_24dp intent = mPauseIntent } else { label = mService.getString(R.string.label_play) icon = R.drawable.ic_play_arrow_black_24dp intent = mPlayIntent } builder.addAction(android.support.v4.app.NotificationCompat.Action(icon, label, intent)) } private fun setNotificationPlaybackState(builder: NotificationCompat.Builder) { if (mPlaybackState == null || !mStarted) { mService.stopForeground(true) return } if (mPlaybackState!!.state == PlaybackStateCompat.STATE_PLAYING && mPlaybackState!!.position >= 0) { wtf { "updateNotificationPlaybackState. updating playback position to " + "${(System.currentTimeMillis() - mPlaybackState!!.position) / 1000} seconds" } builder .setWhen(System.currentTimeMillis() - mPlaybackState!!.position) .setShowWhen(true) .setUsesChronometer(true) } else { wtf { "updateNotificationPlaybackState. hiding playback position" } builder .setWhen(0) .setShowWhen(false) .setUsesChronometer(false) } // Make sure that the notification can be dismissed by the user when we are not playing: builder.setOngoing(mPlaybackState!!.state == PlaybackStateCompat.STATE_PLAYING) } companion object { private val NOTIFICATION_ID = 412 private val REQUEST_CODE = 100 val ACTION_PAUSE = "com.junnanhao.next.pause" val ACTION_PLAY = "com.junnanhao.next.play" val ACTION_PREV = "com.junnanhao.next.prev" val ACTION_NEXT = "com.junnanhao.next.next" val ACTION_STOP_CASTING = "com.junnanhao.next.stop_cast" val PLAYER_CHANNEL_ID = "com.junnanhao.next.player_channel" } }
apache-2.0
85ef1cbb7548fb31518bdde5f6290d7b
40.568445
118
0.658015
5.146797
false
false
false
false
TCA-Team/TumCampusApp
app/src/main/java/de/tum/in/tumcampusapp/api/tumonline/TUMOnlineClient.kt
1
5905
package de.tum.`in`.tumcampusapp.api.tumonline import android.content.Context import com.tickaroo.tikxml.TikXml import com.tickaroo.tikxml.retrofit.TikXmlConverterFactory import de.tum.`in`.tumcampusapp.api.app.ApiHelper import de.tum.`in`.tumcampusapp.api.tumonline.interceptors.AddTokenInterceptor import de.tum.`in`.tumcampusapp.api.tumonline.interceptors.CacheResponseInterceptor import de.tum.`in`.tumcampusapp.api.tumonline.interceptors.CheckErrorInterceptor import de.tum.`in`.tumcampusapp.api.tumonline.interceptors.CheckTokenInterceptor import de.tum.`in`.tumcampusapp.api.tumonline.model.AccessToken import de.tum.`in`.tumcampusapp.api.tumonline.model.TokenConfirmation import de.tum.`in`.tumcampusapp.component.tumui.calendar.model.CalendarItem import de.tum.`in`.tumcampusapp.component.tumui.calendar.model.CreateEventResponse import de.tum.`in`.tumcampusapp.component.tumui.calendar.model.DeleteEventResponse import de.tum.`in`.tumcampusapp.component.tumui.calendar.model.EventsResponse import de.tum.`in`.tumcampusapp.component.tumui.grades.model.ExamList import de.tum.`in`.tumcampusapp.component.tumui.lectures.model.LectureAppointmentsResponse import de.tum.`in`.tumcampusapp.component.tumui.lectures.model.LectureDetailsResponse import de.tum.`in`.tumcampusapp.component.tumui.lectures.model.LecturesResponse import de.tum.`in`.tumcampusapp.component.tumui.person.model.Employee import de.tum.`in`.tumcampusapp.component.tumui.person.model.IdentitySet import de.tum.`in`.tumcampusapp.component.tumui.person.model.PersonList import de.tum.`in`.tumcampusapp.component.tumui.tutionfees.model.TuitionList import de.tum.`in`.tumcampusapp.utils.CacheManager import de.tum.`in`.tumcampusapp.utils.Const import de.tum.`in`.tumcampusapp.utils.DateTimeUtils import io.reactivex.Single import retrofit2.Call import retrofit2.Retrofit import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory class TUMOnlineClient(private val apiService: TUMOnlineAPIService) { fun getCalendar(cacheControl: CacheControl): Call<EventsResponse> { return apiService.getCalendar( Const.CALENDAR_MONTHS_BEFORE, Const.CALENDAR_MONTHS_AFTER, cacheControl.header) } fun createEvent(calendarItem: CalendarItem, eventId: String?): Call<CreateEventResponse> { val start = DateTimeUtils.getDateTimeString(calendarItem.eventStart) val end = DateTimeUtils.getDateTimeString(calendarItem.eventEnd) return apiService.createCalendarEvent( calendarItem.title, calendarItem.description, start, end, eventId) } fun deleteEvent(eventId: String): Call<DeleteEventResponse> { return apiService.deleteCalendarEvent(eventId) } fun getTuitionFeesStatus(cacheControl: CacheControl): Call<TuitionList> { return apiService.getTuitionFeesStatus(cacheControl.header) } fun getPersonalLectures(cacheControl: CacheControl): Call<LecturesResponse> { return apiService.getPersonalLectures(cacheControl.header) } fun getLectureDetails(id: String, cacheControl: CacheControl): Call<LectureDetailsResponse> { return apiService.getLectureDetails(id, cacheControl.header) } fun getLectureAppointments(id: String, cacheControl: CacheControl): Call<LectureAppointmentsResponse> { return apiService.getLectureAppointments(id, cacheControl.header) } fun searchLectures(query: String): Call<LecturesResponse> { return apiService.searchLectures(query) } fun getPersonDetails(id: String, cacheControl: CacheControl): Call<Employee> { return apiService.getPersonDetails(id, cacheControl.header) } fun searchPerson(query: String): Call<PersonList> { return apiService.searchPerson(query) } fun getGrades(cacheControl: CacheControl): Call<ExamList> { return apiService.getGrades(cacheControl.header) } fun requestToken(username: String, tokenName: String): Single<AccessToken> { return apiService.requestToken(username, tokenName) } fun getIdentity(): Single<IdentitySet> = apiService.getIdentity() fun uploadSecret(token: String, secret: String): Call<TokenConfirmation> { return apiService.uploadSecret(token, secret) } companion object { private const val BASE_URL = "https://campus.tum.de/tumonline/" // For testing // private const val BASE_URL = "https://campusquality.tum.de/QSYSTEM_TUM/" private var client: TUMOnlineClient? = null @JvmStatic @Synchronized fun getInstance(context: Context): TUMOnlineClient { if (client == null) { client = buildAPIClient(context) } return client!! } private fun buildAPIClient(context: Context): TUMOnlineClient { val cacheManager = CacheManager(context) val client = ApiHelper.getOkHttpClient(context) .newBuilder() .cache(cacheManager.cache) .addInterceptor(AddTokenInterceptor(context)) .addInterceptor(CheckTokenInterceptor(context)) .addNetworkInterceptor(CacheResponseInterceptor()) .addNetworkInterceptor(CheckErrorInterceptor(context)) .build() val tikXml = TikXml.Builder() .exceptionOnUnreadXml(false) .build() val xmlConverterFactory = TikXmlConverterFactory.create(tikXml) val apiService = Retrofit.Builder() .baseUrl(BASE_URL) .client(client) .addConverterFactory(xmlConverterFactory) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .build() .create(TUMOnlineAPIService::class.java) return TUMOnlineClient(apiService) } } }
gpl-3.0
38a6cdda2641cf60ace7e754b3ebaa8c
41.797101
107
0.7221
4.664297
false
false
false
false
PassionateWsj/YH-Android
app/src/main/java/com/intfocus/template/subject/one/module/singlevalue/SingleValueImpl.kt
1
2235
package com.intfocus.template.subject.templateone.singlevalue import com.alibaba.fastjson.JSON import com.intfocus.template.subject.one.ModeImpl import com.intfocus.template.subject.one.entity.SingleValue import rx.Observable import rx.Observer import rx.Subscription import rx.android.schedulers.AndroidSchedulers import rx.schedulers.Schedulers /** * **************************************************** * @author jameswong * created on: 17/10/20 下午3:35 * e-mail: [email protected] * name: * desc: * **************************************************** */ class SingleValueImpl : SingleValueModel { companion object { private var INSTANCE: SingleValueImpl? = null private var observable: Subscription? = null /** * Returns the single instance of this class, creating it if necessary. */ @JvmStatic fun getInstance(): SingleValueImpl { return INSTANCE ?: SingleValueImpl() .apply { INSTANCE = this } } /** * Used to force [getInstance] to create a new instance * next time it's called. */ @JvmStatic fun destroyInstance() { unSubscribe() INSTANCE = null } /** * 取消订阅 */ private fun unSubscribe() { observable?.unsubscribe() ?: return } } override fun getData(rootId: Int, index: Int, callback: SingleValueModel.LoadDataCallback) { observable = Observable.just(ModeImpl.getInstance().queryModuleConfig(index, rootId)) .subscribeOn(Schedulers.io()) .map { JSON.parseObject<SingleValue>(it, SingleValue::class.java) } .observeOn(AndroidSchedulers.mainThread()) .subscribe(object : Observer<SingleValue> { override fun onNext(t: SingleValue?) { t?.let { callback.onDataLoaded(t) } } override fun onError(e: Throwable?) { callback.onDataNotAvailable(e) } override fun onCompleted() { } }) } }
gpl-3.0
f6068a24f73bc248e2f5f817daa08d85
29.040541
96
0.548358
5.267773
false
false
false
false
westnordost/StreetComplete
app/src/main/java/de/westnordost/streetcomplete/data/osm/elementgeometry/ElementGeometryCreator.kt
1
10002
package de.westnordost.streetcomplete.data.osm.elementgeometry import de.westnordost.osmapi.map.MapData import de.westnordost.osmapi.map.data.* import de.westnordost.streetcomplete.ktx.isArea import de.westnordost.streetcomplete.util.centerPointOfPolygon import de.westnordost.streetcomplete.util.centerPointOfPolyline import de.westnordost.streetcomplete.util.isRingDefinedClockwise import javax.inject.Inject import kotlin.collections.ArrayList /** Creates an ElementGeometry from an element and a collection of positions. */ class ElementGeometryCreator @Inject constructor() { /** Create an ElementGeometry from any element, using the given MapData to find the positions * of the nodes. * * @param element the element to create the geometry for * @param mapData the MapData that contains the elements with the necessary * @param allowIncomplete whether incomplete relations should return an incomplete * ElementGeometry (otherwise: null) * * @return an ElementGeometry or null if any necessary element to create the geometry is not * in the given MapData */ fun create(element: Element, mapData: MapData, allowIncomplete: Boolean = false): ElementGeometry? { when(element) { is Node -> { return create(element) } is Way -> { val positions = mapData.getNodePositions(element) ?: return null return create(element, positions) } is Relation -> { val positionsByWayId = mapData.getWaysNodePositions(element, allowIncomplete) ?: return null return create(element, positionsByWayId) } else -> return null } } /** Create an ElementPointGeometry for a node. */ fun create(node: Node) = ElementPointGeometry(node.position) /** * Create an ElementGeometry for a way * * @param way the way to create the geometry for * @param wayGeometry the geometry of the way: A list of positions of its nodes. * * @return an ElementPolygonsGeometry if the way is an area or an ElementPolylinesGeometry * if the way is a linear feature */ fun create(way: Way, wayGeometry: List<LatLon>): ElementGeometry? { val polyline = ArrayList(wayGeometry) polyline.eliminateDuplicates() if (wayGeometry.size < 2) return null return if (way.isArea()) { /* ElementGeometry considers polygons that are defined clockwise holes, so ensure that it is defined CCW here. */ if (polyline.isRingDefinedClockwise()) polyline.reverse() ElementPolygonsGeometry(arrayListOf(polyline), polyline.centerPointOfPolygon()) } else { ElementPolylinesGeometry(arrayListOf(polyline), polyline.centerPointOfPolyline()) } } /** * Create an ElementGeometry for a relation * * @param relation the relation to create the geometry for * @param wayGeometries the geometries of the ways that are members of the relation. It is a * map of way ids to a list of positions. * * @return an ElementPolygonsGeometry if the relation describes an area or an * ElementPolylinesGeometry if it describes is a linear feature */ fun create(relation: Relation, wayGeometries: Map<Long, List<LatLon>>): ElementGeometry? { return if (relation.isArea()) { createMultipolygonGeometry(relation, wayGeometries) } else { createPolylinesGeometry(relation, wayGeometries) } } private fun createMultipolygonGeometry( relation: Relation, wayGeometries: Map<Long, List<LatLon>> ): ElementPolygonsGeometry? { val outer = createNormalizedRingGeometry(relation, "outer", false, wayGeometries) val inner = createNormalizedRingGeometry(relation, "inner", true, wayGeometries) if (outer.isEmpty()) return null val rings = ArrayList<ArrayList<LatLon>>() rings.addAll(outer) rings.addAll(inner) /* only use first ring that is not a hole if there are multiple this is the same behavior as Leaflet or Tangram */ return ElementPolygonsGeometry(rings, outer.first().centerPointOfPolygon()) } private fun createPolylinesGeometry( relation: Relation, wayGeometries: Map<Long, List<LatLon>> ): ElementPolylinesGeometry? { val waysNodePositions = getRelationMemberWaysNodePositions(relation, wayGeometries) val joined = waysNodePositions.joined() val polylines = joined.ways polylines.addAll(joined.rings) if (polylines.isEmpty()) return null /* if there are more than one polylines, these polylines are not connected to each other, so there is no way to find a reasonable "center point". In most cases however, there is only one polyline, so let's just take the first one... This is the same behavior as Leaflet or Tangram */ return ElementPolylinesGeometry(polylines, polylines.first().centerPointOfPolyline()) } private fun createNormalizedRingGeometry( relation: Relation, role: String, clockwise: Boolean, wayGeometries: Map<Long, List<LatLon>> ): ArrayList<ArrayList<LatLon>> { val waysNodePositions = getRelationMemberWaysNodePositions(relation, role, wayGeometries) val ringGeometry = waysNodePositions.joined().rings ringGeometry.setOrientation(clockwise) return ringGeometry } private fun getRelationMemberWaysNodePositions( relation: Relation, wayGeometries: Map<Long, List<LatLon>> ): List<List<LatLon>> { return relation.members .filter { it.type == Element.Type.WAY } .mapNotNull { getValidNodePositions(wayGeometries[it.ref]) } } private fun getRelationMemberWaysNodePositions( relation: Relation, withRole: String, wayGeometries: Map<Long, List<LatLon>> ): List<List<LatLon>> { return relation.members .filter { it.type == Element.Type.WAY && it.role == withRole } .mapNotNull { getValidNodePositions(wayGeometries[it.ref]) } } private fun getValidNodePositions(wayGeometry: List<LatLon>?): List<LatLon>? { if (wayGeometry == null) return null val nodePositions = ArrayList(wayGeometry) nodePositions.eliminateDuplicates() return if (nodePositions.size >= 2) nodePositions else null } } /** Ensures that all given rings are defined in clockwise/counter-clockwise direction */ private fun List<MutableList<LatLon>>.setOrientation(clockwise: Boolean) { for (ring in this) { if (ring.isRingDefinedClockwise() != clockwise) { ring.reverse() } } } private fun List<LatLon>.isRing() = first() == last() private class ConnectedWays(val rings: ArrayList<ArrayList<LatLon>>, val ways: ArrayList<ArrayList<LatLon>>) /** Returns a list of polylines joined together at their endpoints into rings and ways */ private fun List<List<LatLon>>.joined(): ConnectedWays { val nodeWayMap = NodeWayMap(this) val rings: ArrayList<ArrayList<LatLon>> = ArrayList() val ways: ArrayList<ArrayList<LatLon>> = ArrayList() var currentWay: ArrayList<LatLon> = ArrayList() while (nodeWayMap.hasNextNode()) { val node: LatLon = if (currentWay.isEmpty()) nodeWayMap.getNextNode() else currentWay.last() val waysAtNode = nodeWayMap.getWaysAtNode(node) if (waysAtNode == null) { ways.add(currentWay) currentWay = ArrayList() } else { val way = waysAtNode.first() currentWay.join(way) nodeWayMap.removeWay(way) // finish ring and start new one if (currentWay.isRing()) { rings.add(currentWay) currentWay = ArrayList() } } } if (currentWay.isNotEmpty()) { ways.add(currentWay) } return ConnectedWays(rings, ways) } /** Join the given adjacent polyline into this polyline */ private fun MutableList<LatLon>.join(way: List<LatLon>) { if (isEmpty()) { addAll(way) } else { when { last() == way.last() -> addAll(way.asReversed().subList(1, way.size)) last() == way.first() -> addAll(way.subList(1, way.size)) first() == way.last() -> addAll(0, way.subList(0, way.size - 1)) first() == way.first() -> addAll(0, way.asReversed().subList(0, way.size - 1)) else -> throw IllegalArgumentException("The ways are not adjacent") } } } private fun MutableList<LatLon>.eliminateDuplicates() { val it = iterator() var prev: LatLon? = null while (it.hasNext()) { val line = it.next() if (prev == null || line.latitude != prev.latitude || line.longitude != prev.longitude) { prev = line } else { it.remove() } } } private fun MapData.getNodePositions(way: Way): List<LatLon>? { return way.nodeIds.map { nodeId -> val node = getNode(nodeId) ?: return null node.position } } private fun MapData.getWaysNodePositions(relation: Relation, allowIncomplete: Boolean = false): Map<Long, List<LatLon>>? { val wayMembers = relation.members.filter { it.type == Element.Type.WAY } val result = mutableMapOf<Long, List<LatLon>>() for (wayMember in wayMembers) { val way = getWay(wayMember.ref) if (way != null) { val wayPositions = getNodePositions(way) if (wayPositions != null) { result[way.id] = wayPositions } else { if (!allowIncomplete) return null } } else { if (!allowIncomplete) return null } } return result }
gpl-3.0
9a8c8a394e896d84491d43850e8712db
37.32567
122
0.643971
4.481183
false
false
false
false
elect86/jAssimp
src/main/kotlin/assimp/format/fbx/fbxMeshGeometry.kt
2
20212
/* Open Asset Import Library (assimp) ---------------------------------------------------------------------- Copyright (c) 2006-2017, assimp team All rights reserved. Redistribution and use of this software in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * 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. * Neither the name of the assimp team, nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission of the assimp team. 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 OWNER 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 assimp.format.fbx import assimp.* import kotlin.reflect.KMutableProperty0 /** @file FBXImporter.h * @brief Declaration of the FBX main importer class */ /** * DOM base class for all kinds of FBX geometry */ open class Geometry(id: Long, element: Element, name: String, doc: Document) : Object(id, element, name) { /** Get the Skin attached to this geometry or NULL */ var skin: Skin? = null init { val conns = doc.getConnectionsByDestinationSequenced(id, "Deformer") for (con in conns) { val sk = processSimpleConnection<Skin>(con, false, "Skin -> Geometry", element) if (sk != null) { skin = sk break } } } } /** * DOM class for FBX geometry of type "Mesh" */ class MeshGeometry(id: Long, element: Element, name: String, doc: Document) : Geometry(id, element, name, doc) { // cached data arrays /** Per-face-vertex material assignments */ val materials = ArrayList<Int>() val vertices = ArrayList<AiVector3D>() val faces = ArrayList<Int>() val facesVertexStartIndices = ArrayList<Int>() val tangents = ArrayList<AiVector3D>() val binormals = ArrayList<AiVector3D>() val normals = ArrayList<AiVector3D>() val uvNames = Array(AI_MAX_NUMBER_OF_TEXTURECOORDS) { "" } val uvs = Array(AI_MAX_NUMBER_OF_TEXTURECOORDS) { ArrayList<AiVector2D>() } val colors = Array(AI_MAX_NUMBER_OF_COLOR_SETS) { ArrayList<AiColor4D>() } var mappingCounts = intArrayOf() var mappingOffsets = intArrayOf() var mappings = intArrayOf() init { val sc = element.compound ?: domError("failed to read Geometry object (class: Mesh), no data scope found") // must have Mesh elements: val vertices = getRequiredElement(sc, "Vertices", element) val polygonVertexIndex = getRequiredElement(sc, "PolygonVertexIndex", element) // optional Mesh elements: val layer = sc.getCollection("Layer") val tempVerts = ArrayList<AiVector3D>() vertices.parseVec3DataArray(tempVerts) if (tempVerts.isEmpty()) logger.warn { "encountered mesh with no vertices" } else { val tempFaces = ArrayList<Int>() polygonVertexIndex.parseIntsDataArray(tempFaces) if (tempFaces.isEmpty()) logger.warn { "encountered mesh with no faces" } else { this.vertices.ensureCapacity(tempFaces.size) faces.ensureCapacity(tempFaces.size / 3) mappingOffsets = IntArray(tempVerts.size) mappingCounts = IntArray(tempVerts.size) mappings = IntArray(tempFaces.size) val vertexCount = tempVerts.size // generate output vertices, computing an adjacency table to preserve the mapping from fbx indices to *this* indexing. var count = 0 for (index in tempFaces) { val absi = if (index < 0) -index - 1 else index if (absi >= vertexCount) domError("polygon vertex index out of range", polygonVertexIndex) this.vertices += tempVerts[absi] ++count ++mappingCounts[absi] if (index < 0) { faces += count count = 0 } } var cursor = 0 for (i in tempVerts.indices) { mappingOffsets[i] = cursor cursor += mappingCounts[i] mappingCounts[i] = 0 } cursor = 0 for (index in tempFaces) { val absi = if (index < 0) -index - 1 else index mappings[mappingOffsets[absi] + mappingCounts[absi]++] = cursor++ } // if settings.readAllLayers is true: // * read all layers, try to load as many vertex channels as possible // if settings.readAllLayers is false: // * read only the layer with index 0, but warn about any further layers layer.forEach { val tokens = it.tokens val index = tokens[0].parseAsInt if (doc.settings.readAllLayers || index == 0) readLayer(it.scope) // layer else logger.warn { "ignoring additional geometry layers" } } } } } /** Get a UV coordinate slot, returns an empty array if * the requested slot does not exist. */ fun getTextureCoords(index: Int) = if (index >= AI_MAX_NUMBER_OF_TEXTURECOORDS) arrayListOf() else uvs[index] /** Get a UV coordinate slot, returns an empty array if the requested slot does not exist. */ fun getTextureCoordChannelName(index: Int) = if (index >= AI_MAX_NUMBER_OF_TEXTURECOORDS) "" else uvNames[index] /** Get a vertex color coordinate slot, returns an empty array if the requested slot does not exist. */ fun getVertexColors(index: Int) = if (index >= AI_MAX_NUMBER_OF_COLOR_SETS) arrayListOf() else colors[index] /** Convert from a fbx file vertex index (for example from a #Cluster weight) or NULL if the vertex index is not valid. */ fun toOutputVertexIndex(inIndex: Int, count: KMutableProperty0<Int>): Int? { if (inIndex >= mappingCounts.size) return null assert(mappingCounts.size == mappingOffsets.size) count.set(mappingCounts[inIndex]) assert(mappingOffsets[inIndex] + count() <= mappings.size) return mappingOffsets[inIndex] } /** Determine the face to which a particular output vertex index belongs. This mapping is always unique. */ fun faceForVertexIndex(inIndex: Int): Int { assert(inIndex < vertices.size) // in the current conversion pattern this will only be needed if weights are present, so no need to always pre-compute this table if (facesVertexStartIndices.isEmpty()) { for (i in 0..faces.size) facesVertexStartIndices += 0 facesVertexStartIndices[1] = faces.sum() facesVertexStartIndices.removeAt(facesVertexStartIndices.lastIndex) } assert(facesVertexStartIndices.size == faces.size) return facesVertexStartIndices.indexOfFirst { it > inIndex } // TODO last item excluded? } fun readLayer(layer: Scope) { val layerElement = layer.getCollection("LayerElement") for (eit in layerElement) readLayerElement(eit.scope) } fun readLayerElement(layerElement: Scope) { val type = getRequiredElement(layerElement, "Type") val typedIndex = getRequiredElement(layerElement, "TypedIndex") val type_ = type[0].parseAsString val typedIndex_ = typedIndex[0].parseAsInt val top = element.scope val candidates = top.getCollection(type_) for (it in candidates) { val index = it[0].parseAsInt if (index == typedIndex_) { readVertexData(type_, typedIndex_, it.scope) return } } logger.error("failed to resolve vertex layer element: $type, index: $typedIndex") } fun readVertexData(type: String, index: Int, source: Scope) { val mappingInformationType = getRequiredElement(source, "MappingInformationType")[0].parseAsString val referenceInformationType = getRequiredElement(source, "ReferenceInformationType")[0].parseAsString when (type) { "LayerElementUV" -> { if (index >= AI_MAX_NUMBER_OF_TEXTURECOORDS) { logger.error { "ignoring UV layer, maximum number of UV channels exceeded: $index (limit is $AI_MAX_NUMBER_OF_TEXTURECOORDS)" } return } source["Name"]?.let { uvNames[index] = it[0].parseAsString } readVertexDataUV(uvs[index], source, mappingInformationType, referenceInformationType) } "LayerElementMaterial" -> { if (materials.isNotEmpty()) { logger.error("ignoring additional material layer") return } val tempMaterials = ArrayList<Int>() readVertexDataMaterials(tempMaterials, source, mappingInformationType, referenceInformationType) /* sometimes, there will be only negative entries. Drop the material layer in such a case (I guess it means a default material should be used). This is what the converter would do anyway, and it avoids losing the material if there are more material layers coming of which at least one contains actual data (did observe that with one test file). */ if (tempMaterials.all { it < 0 }) { logger.warn("ignoring dummy material layer (all entries -1)") return } materials.clear() materials += tempMaterials } "LayerElementNormal" -> { if (normals.isNotEmpty()) { logger.error("ignoring additional normal layer") return } readVertexDataNormals(normals, source, mappingInformationType, referenceInformationType) } "LayerElementTangent" -> { if (tangents.isNotEmpty()) { logger.error("ignoring additional tangent layer") return } readVertexDataTangents(tangents, source, mappingInformationType, referenceInformationType) } "LayerElementBinormal" -> { if (binormals.isNotEmpty()) { logger.error("ignoring additional binormal layer") return } readVertexDataBinormals(binormals, source, mappingInformationType, referenceInformationType) } "LayerElementColor" -> { if (index >= AI_MAX_NUMBER_OF_COLOR_SETS) { logger.error("ignoring vertex color layer, maximum number of color sets exceeded: $index (limit is $AI_MAX_NUMBER_OF_COLOR_SETS)") return } readVertexDataColors(colors[index], source, mappingInformationType, referenceInformationType) } } } fun readVertexDataUV(uvOut: ArrayList<AiVector2D>, source: Scope, mappingInformationType: String, referenceInformationType: String) = resolveVertexDataArray(uvOut, source, mappingInformationType, referenceInformationType, "UV", "UVIndex", vertices.size, mappingCounts, mappingOffsets, mappings) fun readVertexDataNormals(normalsOut: ArrayList<AiVector3D>, source: Scope, mappingInformationType: String, referenceInformationType: String) = resolveVertexDataArray(normalsOut, source, mappingInformationType, referenceInformationType, "Normals", "NormalsIndex", vertices.size, mappingCounts, mappingOffsets, mappings) fun readVertexDataColors(colorsOut: ArrayList<AiColor4D>, source: Scope, mappingInformationType: String, referenceInformationType: String) = resolveVertexDataArray(colorsOut, source, mappingInformationType, referenceInformationType, "Colors", "ColorIndex", vertices.size, mappingCounts, mappingOffsets, mappings) fun readVertexDataTangents(tangentsOut: ArrayList<AiVector3D>, source: Scope, mappingInformationType: String, referenceInformationType: String) { val any = source.elements["Tangents"]!!.isNotEmpty() resolveVertexDataArray(tangentsOut, source, mappingInformationType, referenceInformationType, if (any) "Tangents" else "Tangent", if (any) "TangentsIndex" else "TangentIndex", vertices.size, mappingCounts, mappingOffsets, mappings) } fun readVertexDataBinormals(binormalsOut: ArrayList<AiVector3D>, source: Scope, mappingInformationType: String, referenceInformationType: String) { val any = source.elements["Binormals"]!!.isNotEmpty() resolveVertexDataArray(binormalsOut, source, mappingInformationType, referenceInformationType, if (any) "Binormals" else "Binormal", if (any) "BinormalsIndex" else "BinormalIndex", vertices.size, mappingCounts, mappingOffsets, mappings) } fun readVertexDataMaterials(materialsOut: ArrayList<Int>, source: Scope, mappingInformationType: String, referenceInformationType: String) { val faceCount = faces.size assert(faceCount != 0) /* materials are handled separately. First of all, they are assigned per-face and not per polyvert. Secondly, ReferenceInformationType=IndexToDirect has a slightly different meaning for materials. */ getRequiredElement(source, "Materials").parseIntsDataArray(materialsOut) if (mappingInformationType == "AllSame") { // easy - same material for all faces if (materialsOut.isEmpty()) { logger.error("expected material index, ignoring") return } else if (materialsOut.size > 1) { logger.warn("expected only a single material index, ignoring all except the first one") materialsOut.clear() } for (i in vertices.indices) materials += materialsOut[0] } else if (mappingInformationType == "ByPolygon" && referenceInformationType == "IndexToDirect") { if (materials.size < faceCount) while (materials.size < faceCount) materials += 0 else while (materials.size > faceCount) materials.dropLast(materials.size - faceCount) if (materialsOut.size != faceCount) { logger.error("length of input data unexpected for ByPolygon mapping: ${materialsOut.size}, expected $faceCount") return } } else logger.error("ignoring material assignments, access type not implemented: $mappingInformationType, $referenceInformationType") } /** Lengthy utility function to read and resolve a FBX vertex data array - that is, the output is in polygon vertex * order. This logic is used for reading normals, UVs, colors, tangents .. */ inline fun <reified T : Any> resolveVertexDataArray(dataOut: ArrayList<T>, source: Scope, mappingInformationType: String, referenceInformationType: String, dataElementName: String, indexDataElementName: String, vertexCount: Int, mappingCounts: IntArray, mappingOffsets: IntArray, mappings: IntArray) { /* handle permutations of Mapping and Reference type - it would be nice to deal with this more elegantly and with less redundancy, but right now it seems unavoidable. */ if (mappingInformationType == "ByVertice" && referenceInformationType == "Direct") { if (!source.hasElement(indexDataElementName)) return val tempData = ArrayList<T>() getRequiredElement(source, dataElementName).parseVectorDataArray(tempData) val tempData2 = Array<T?>(tempData.size, { null }) for (i in 0 until tempData.size) { val iStart = mappingOffsets[i] val iEnd = iStart + mappingCounts[i] for (j in iStart until iEnd) tempData2[mappings[j]] = tempData[i] } dataOut.addAll(tempData2.filterNotNull()) } else if (mappingInformationType == "ByVertice" && referenceInformationType == "IndexToDirect") { val tempData = ArrayList<T>() getRequiredElement(source, dataElementName).parseVectorDataArray(tempData) val tempData2 = Array<T?>(tempData.size, { null }) val uvIndices = ArrayList<Int>() if (!source.hasElement(indexDataElementName)) return getRequiredElement(source, indexDataElementName).parseIntsDataArray(uvIndices) for (i in 0 until uvIndices.size) { val iStart = mappingOffsets[i] val iEnd = iStart + mappingCounts[i] for (j in iStart until iEnd) { if (uvIndices[i] >= tempData.size) domError("index out of range", getRequiredElement(source, indexDataElementName)) tempData2[mappings[j]] = tempData[uvIndices[i]] } } dataOut.addAll(tempData2.filterNotNull()) } else if (mappingInformationType == "ByPolygonVertex" && referenceInformationType == "Direct") { val tempData = ArrayList<T>() getRequiredElement(source, dataElementName).parseVectorDataArray(tempData) if (tempData.size != vertexCount) { logger.error { "length of input data unexpected for ByPolygon mapping: ${tempData.size}, expected $vertexCount" } return } dataOut.addAll(tempData) } else if (mappingInformationType == "ByPolygonVertex" && referenceInformationType == "IndexToDirect") { val tempData = ArrayList<T>() getRequiredElement(source, dataElementName).parseVectorDataArray(tempData) val uvIndices = ArrayList<Int>() getRequiredElement(source, indexDataElementName).parseIntsDataArray(uvIndices) if (uvIndices.size != vertexCount) { logger.error("length of input data unexpected for ByPolygonVertex mapping") return } val tempData2 = Array<T?>(vertexCount) { null } var next = 0 for (i in uvIndices) { if (i >= tempData.size) domError("index out of range", getRequiredElement(source, indexDataElementName)) tempData2[next++] = tempData[i] } dataOut.addAll(tempData2.filterNotNull()) } else logger.error("ignoring vertex data channel, access type not implemented: $mappingInformationType, $referenceInformationType") } }
mit
28420fd22853c191d56f7804810dd3dc
44.62754
151
0.619929
4.886847
false
false
false
false
westnordost/StreetComplete
app/src/main/java/de/westnordost/streetcomplete/quests/opening_hours/AddOpeningHoursForm.kt
1
8183
package de.westnordost.streetcomplete.quests.opening_hours import android.os.Bundle import androidx.appcompat.app.AlertDialog import androidx.recyclerview.widget.LinearLayoutManager import androidx.appcompat.widget.PopupMenu import android.view.LayoutInflater import android.view.View import android.widget.EditText import java.util.ArrayList import javax.inject.Inject import de.westnordost.streetcomplete.Injector import de.westnordost.streetcomplete.R import de.westnordost.streetcomplete.quests.AbstractQuestFormAnswerFragment import de.westnordost.streetcomplete.util.AdapterDataChangedWatcher import de.westnordost.streetcomplete.util.Serializer import android.view.Menu.NONE import androidx.core.view.isGone import androidx.recyclerview.widget.RecyclerView import de.westnordost.streetcomplete.quests.OtherAnswer import de.westnordost.streetcomplete.ktx.toObject import de.westnordost.streetcomplete.quests.opening_hours.adapter.* import de.westnordost.streetcomplete.quests.opening_hours.parser.toOpeningHoursRows import de.westnordost.streetcomplete.quests.opening_hours.parser.toOpeningHoursRules import kotlinx.android.synthetic.main.quest_opening_hours.* class AddOpeningHoursForm : AbstractQuestFormAnswerFragment<OpeningHoursAnswer>() { override val contentLayoutResId = R.layout.quest_opening_hours override val otherAnswers = listOf( OtherAnswer(R.string.quest_openingHours_no_sign) { confirmNoSign() }, OtherAnswer(R.string.quest_openingHours_answer_no_regular_opening_hours) { showInputCommentDialog() }, OtherAnswer(R.string.quest_openingHours_answer_247) { showConfirm24_7Dialog() }, OtherAnswer(R.string.quest_openingHours_answer_seasonal_opening_hours) { setAsResurvey(false) openingHoursAdapter.changeToMonthsMode() } ) private lateinit var openingHoursAdapter: RegularOpeningHoursAdapter private var isDisplayingPreviousOpeningHours: Boolean = false @Inject internal lateinit var serializer: Serializer init { Injector.applicationComponent.inject(this) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) openingHoursAdapter = RegularOpeningHoursAdapter(requireContext(), countryInfo) openingHoursAdapter.registerAdapterDataObserver(AdapterDataChangedWatcher { checkIsFormComplete() }) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) if (savedInstanceState != null) { onLoadInstanceState(savedInstanceState) } else { initStateFromTags() } openingHoursList.layoutManager = LinearLayoutManager(activity, RecyclerView.VERTICAL, false) openingHoursList.adapter = openingHoursAdapter openingHoursList.isNestedScrollingEnabled = false checkIsFormComplete() addTimesButton.setOnClickListener { onClickAddButton(it) } } private fun onClickAddButton(v: View) { val rows = openingHoursAdapter.rows val addMonthAvailable = rows.any { it is OpeningMonthsRow } val addTimeAvailable = rows.isNotEmpty() && rows.last() is OpeningWeekdaysRow val addOffDayAvailable = rows.isNotEmpty() && rows.last() is OpeningWeekdaysRow if (addMonthAvailable || addTimeAvailable || addOffDayAvailable) { val popup = PopupMenu(requireContext(), v) if (addTimeAvailable) popup.menu.add(NONE, 0, NONE, R.string.quest_openingHours_add_hours) popup.menu.add(NONE, 1, NONE, R.string.quest_openingHours_add_weekdays) if (addOffDayAvailable) popup.menu.add(NONE, 2, NONE, R.string.quest_openingHours_add_off_days) if (addMonthAvailable) popup.menu.add(NONE, 3, NONE, R.string.quest_openingHours_add_months) popup.setOnMenuItemClickListener { item -> when(item.itemId) { 0 -> openingHoursAdapter.addNewHours() 1 -> openingHoursAdapter.addNewWeekdays() 2 -> openingHoursAdapter.addNewOffDays() 3 -> openingHoursAdapter.addNewMonths() } true } popup.show() } else { openingHoursAdapter.addNewWeekdays() } } private fun initStateFromTags() { val oh = osmElement!!.tags!!["opening_hours"] val rows = oh?.toOpeningHoursRules()?.toOpeningHoursRows() if (rows != null) { openingHoursAdapter.rows = rows.toMutableList() setAsResurvey(true) } else { setAsResurvey(false) } } private fun onLoadInstanceState(savedInstanceState: Bundle) { openingHoursAdapter.rows = serializer.toObject<ArrayList<OpeningHoursRow>>(savedInstanceState.getByteArray(OPENING_HOURS_DATA)!!).toMutableList() isDisplayingPreviousOpeningHours = savedInstanceState.getBoolean(IS_DISPLAYING_PREVIOUS_HOURS) } override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) outState.putByteArray(OPENING_HOURS_DATA, serializer.toBytes(ArrayList(openingHoursAdapter.rows))) outState.putBoolean(IS_DISPLAYING_PREVIOUS_HOURS, isDisplayingPreviousOpeningHours) } override fun onClickOk() { applyAnswer(RegularOpeningHours(openingHoursAdapter.createOpeningHours())) } private fun showInputCommentDialog() { val view = LayoutInflater.from(activity).inflate(R.layout.quest_opening_hours_comment, null) val commentInput = view.findViewById<EditText>(R.id.commentInput) AlertDialog.Builder(requireContext()) .setTitle(R.string.quest_openingHours_comment_title) .setView(view) .setPositiveButton(android.R.string.ok) { _, _ -> val txt = commentInput.text.toString().replace("\"","").trim() if (txt.isEmpty()) { AlertDialog.Builder(requireContext()) .setMessage(R.string.quest_openingHours_emptyAnswer) .setPositiveButton(android.R.string.ok, null) .show() } else { applyAnswer(DescribeOpeningHours(txt)) } } .setNegativeButton(android.R.string.cancel, null) .show() } private fun setAsResurvey(resurvey: Boolean) { openingHoursAdapter.isEnabled = !resurvey isDisplayingPreviousOpeningHours = resurvey addTimesButton.isGone = resurvey if (resurvey) { setButtonsView(R.layout.quest_buttonpanel_yes_no) requireView().findViewById<View>(R.id.noButton).setOnClickListener { setAsResurvey(false) } requireView().findViewById<View>(R.id.yesButton).setOnClickListener { applyAnswer(RegularOpeningHours( osmElement!!.tags!!["opening_hours"]!!.toOpeningHoursRules()!! )) } } else { removeButtonsView() } } private fun showConfirm24_7Dialog() { AlertDialog.Builder(requireContext()) .setMessage(R.string.quest_openingHours_24_7_confirmation) .setPositiveButton(android.R.string.yes) { _, _ -> applyAnswer(AlwaysOpen) } .setNegativeButton(android.R.string.no, null) .show() } private fun confirmNoSign() { AlertDialog.Builder(requireContext()) .setTitle(R.string.quest_generic_confirmation_title) .setPositiveButton(R.string.quest_generic_confirmation_yes) { _, _ -> applyAnswer(NoOpeningHoursSign) } .setNegativeButton(R.string.quest_generic_confirmation_no, null) .show() } override fun isFormComplete() = openingHoursAdapter.rows.isNotEmpty() && !isDisplayingPreviousOpeningHours companion object { private const val OPENING_HOURS_DATA = "oh_data" private const val IS_DISPLAYING_PREVIOUS_HOURS = "oh_is_displaying_previous_hours" } }
gpl-3.0
a2bd11e296ec8906b73fac825c5e73d4
40.120603
153
0.679702
4.768648
false
false
false
false
InsertKoinIO/koin
android/koin-android/src/main/java/org/koin/androidx/viewmodel/ViewModelOwner.kt
1
1083
package org.koin.androidx.viewmodel import androidx.lifecycle.ViewModelStoreOwner import androidx.savedstate.SavedStateRegistryOwner @Deprecated("Replaced by ViewModelStoreOwner") typealias ViewModelStoreOwnerProducer = () -> ViewModelStoreOwner @Deprecated("Replaced by ViewModelStoreOwner") typealias ViewModelOwnerDefinition = () -> ViewModelOwner @Deprecated("Replaced by ViewModelStoreOwner") class ViewModelOwner( val storeOwner: ViewModelStoreOwner, val stateRegistry: SavedStateRegistryOwner? = null, ) { companion object { @Deprecated("Replaced by ViewModelStoreOwner") fun from(storeOwner: ViewModelStoreOwner, stateRegistry: SavedStateRegistryOwner? = null) = ViewModelOwner(storeOwner, stateRegistry) @Deprecated("Replaced by ViewModelStoreOwner") fun from(storeOwner: ViewModelStoreOwner) = ViewModelOwner(storeOwner) @Deprecated("Replaced by ViewModelStoreOwner") fun fromAny(owner: Any) = ViewModelOwner((owner as ViewModelStoreOwner), owner as? SavedStateRegistryOwner) } }
apache-2.0
41d419eb9987766dd83ab8eb5d75a7e1
36.37931
99
0.762696
5.611399
false
false
false
false
StepicOrg/stepic-android
app/src/main/java/org/stepik/android/presentation/comment/ComposeCommentPresenter.kt
2
4091
package org.stepik.android.presentation.comment import io.reactivex.Scheduler import io.reactivex.Single import io.reactivex.rxkotlin.plusAssign import io.reactivex.rxkotlin.subscribeBy import org.stepic.droid.analytic.Analytic import org.stepic.droid.di.qualifiers.BackgroundScheduler import org.stepic.droid.di.qualifiers.MainScheduler import org.stepik.android.domain.comment.interactor.ComposeCommentInteractor import org.stepik.android.domain.comment.model.CommentsData import org.stepik.android.domain.submission.interactor.LastSubmissionInteractor import org.stepik.android.model.Submission import org.stepik.android.model.comments.Comment import org.stepik.android.model.comments.DiscussionThread import org.stepik.android.presentation.base.PresenterBase import javax.inject.Inject class ComposeCommentPresenter @Inject constructor( private val analytic: Analytic, private val composeCommentInteractor: ComposeCommentInteractor, private val lastSubmissionInteractor: LastSubmissionInteractor, @BackgroundScheduler private val backgroundScheduler: Scheduler, @MainScheduler private val mainScheduler: Scheduler ) : PresenterBase<ComposeCommentView>() { private var state: ComposeCommentView.State = ComposeCommentView.State.Idle set(value) { field = value view?.setState(value) } override fun attachView(view: ComposeCommentView) { super.attachView(view) view.setState(state) } fun onData(discussionThread: DiscussionThread, target: Long, parent: Long?, submission: Submission?, forceUpdate: Boolean = false) { if (state != ComposeCommentView.State.Idle && !(state == ComposeCommentView.State.NetworkError && forceUpdate)) { return } if (discussionThread.thread == DiscussionThread.THREAD_SOLUTIONS && parent == null && submission == null ) { state = ComposeCommentView.State.Loading compositeDisposable += lastSubmissionInteractor .getLastSubmission(target) .observeOn(mainScheduler) .subscribeOn(backgroundScheduler) .subscribeBy( onSuccess = { state = ComposeCommentView.State.Create(it) }, onComplete = { state = ComposeCommentView.State.NetworkError }, onError = { state = ComposeCommentView.State.NetworkError } ) } else { state = ComposeCommentView.State.Create(submission) } } fun onSubmissionSelected(submission: Submission) { if (state is ComposeCommentView.State.Create) { state = ComposeCommentView.State.Create(submission) } } fun createComment(comment: Comment) { val oldState = (state as? ComposeCommentView.State.Create) ?: return replaceComment( oldState, composeCommentInteractor .createComment(comment.copy(submission = oldState.submission?.id)) .doOnSuccess { analytic.reportEvent(Analytic.Comments.COMMENTS_SENT_SUCCESSFULLY) }, isCommentCreated = true ) } fun updateComment(comment: Comment) { val oldState = (state as? ComposeCommentView.State.Create) ?: return replaceComment(oldState, composeCommentInteractor.saveComment(comment), isCommentCreated = false) } private fun replaceComment(oldState: ComposeCommentView.State.Create, commentSource: Single<CommentsData>, isCommentCreated: Boolean) { state = ComposeCommentView.State.Loading compositeDisposable += commentSource .doOnSubscribe { analytic.reportEvent(Analytic.Comments.CLICK_SEND_COMMENTS) } .observeOn(mainScheduler) .subscribeOn(backgroundScheduler) .subscribeBy( onSuccess = { state = ComposeCommentView.State.Complete(it, isCommentCreated) }, onError = { state = oldState; view?.showNetworkError() } ) } }
apache-2.0
131b90fd71b83bdc2d832241b6106eb5
37.971429
139
0.683696
5.063119
false
false
false
false
andrewoma/kwery
mapper/src/test/kotlin/com/github/andrewoma/kwery/mappertest/example/test/LanguageDaoTest.kt
1
2058
/* * Copyright (c) 2015 Andrew O'Malley * * 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.github.andrewoma.kwery.mappertest.example.test import com.github.andrewoma.kwery.mappertest.example.Language import com.github.andrewoma.kwery.mappertest.example.LanguageDao import java.time.LocalDateTime import kotlin.properties.Delegates class LanguageDaoTest : AbstractFilmDaoTest<Language, Int, LanguageDao>() { override var dao: LanguageDao by Delegates.notNull() override fun afterSessionSetup() { dao = LanguageDao(session) super.afterSessionSetup() } override val data = listOf( Language(-1, "German", LocalDateTime.now()), Language(-1, "Dutch", LocalDateTime.now()), Language(-1, "Japanese", LocalDateTime.now()), Language(-1, "Chinese", LocalDateTime.now()) ) override fun mutateContents(t: Language) = t.copy(name = "Russian") override fun contentsEqual(t1: Language, t2: Language) = t1.name == t2.name }
mit
4ef48769680bd01801b54cd7814c33ff
41.020408
80
0.729349
4.435345
false
true
false
false
GKZX-HN/MyGithub
app/src/main/java/com/gkzxhn/mygithub/ui/fragment/SecondFragment.kt
1
4089
package com.gkzxhn.mygithub.ui.fragment import android.content.Intent import android.content.res.Resources import android.os.Bundle import android.support.v4.app.Fragment import android.support.v4.app.FragmentPagerAdapter import android.support.v4.view.ViewPager import android.support.v7.widget.Toolbar import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.gkzxhn.balabala.base.BaseFragment import com.gkzxhn.balabala.mvp.contract.BaseView import com.gkzxhn.mygithub.R import kotlinx.android.synthetic.main.fragment_second.* /** * Created by Xuezhi on 2017/12/12. */ class SecondFragment : BaseFragment(), BaseView { private lateinit var mFragments: ArrayList<Fragment> private lateinit var theme: Resources.Theme override fun launchActivity(intent: Intent) { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun showLoading() { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun hideLoading() { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun showMessage() { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun killMyself() { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun initContentView() { initFragments() setOnClickListener() } override fun initView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View { return inflater!!.inflate(R.layout.fragment_second, container, false) } private fun initFragments() { mFragments = arrayListOf() val eventFragment = EventFragment() val activityFragment = ActivityFragment() //val eventFragment2 = EventFragment() mFragments.add(eventFragment) mFragments.add(activityFragment) vp_second.adapter = object : FragmentPagerAdapter(childFragmentManager) { override fun getItem(position: Int): Fragment = mFragments[position] override fun getCount(): Int = 2 } vp_second.offscreenPageLimit = 1 vp_second.addOnPageChangeListener(object : ViewPager.OnPageChangeListener { override fun onPageScrollStateChanged(state: Int) { } override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) { } override fun onPageSelected(position: Int) { when (position) { 0 -> { LeftButtonShow() } 1 -> { RightButtonShow() } } } }) } override fun getStatusBar(): View? { return status_view_notifications } override fun getToolbar(): Toolbar? { return toolbar_notifications } fun LeftButtonShow() { tv_left_button.setBackgroundResource(R.drawable.notification_left_selected) tv_left_button.setTextColor(android.graphics.Color.BLACK) tv_right_button.setBackgroundResource(R.drawable.notification_right_unselect) tv_right_button.setTextColor(android.graphics.Color.WHITE) } fun RightButtonShow() { tv_left_button.setBackgroundResource(R.drawable.notification_left_unselect) tv_left_button.setTextColor(android.graphics.Color.WHITE) tv_right_button.setBackgroundResource(R.drawable.notification_right_selected) tv_right_button.setTextColor(android.graphics.Color.BLACK) } fun setOnClickListener() { tv_left_button.setOnClickListener { vp_second.arrowScroll(View.FOCUS_LEFT) } tv_right_button.setOnClickListener { vp_second.arrowScroll(View.FOCUS_RIGHT) } } }
gpl-3.0
70d976d965faa3cf6a83ca2c8e6c9a97
32.243902
112
0.666178
4.788056
false
false
false
false
xurxodev/Movies-Kotlin-Kata
app/src/main/kotlin/com/xurxodev/movieskotlinkata/presentation/view/MovieListActivity.kt
1
2313
package com.xurxodev.movieskotlinkata.presentation.view import android.os.Bundle import android.support.v7.app.AppCompatActivity import android.view.View import com.xurxodev.moviesandroidkotlin.R import com.xurxodev.movieskotlinkata.App import com.xurxodev.movieskotlinkata.di.module.ActivityModule import com.xurxodev.movieskotlinkata.domain.entity.Movie import com.xurxodev.movieskotlinkata.presentation.adapter.MovieAdapter import com.xurxodev.movieskotlinkata.presentation.presenter.MoviesListPresenter import kotlinx.android.synthetic.main.activity_movies.* import javax.inject.Inject class MovieListActivity : AppCompatActivity(), MoviesListPresenter.View { @Inject lateinit var presenter: MoviesListPresenter lateinit var movieAdapter: MovieAdapter override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_movies) (application as App).appComponent.activityComponent() .activityModule(ActivityModule(this)).build().inject(this) initializeRecyclerView() initializeRefreshButton() initializePresenter() } private fun initializeRecyclerView() { this.movieAdapter = MovieAdapter() { item -> presenter.onMovieClicked(item) } recycler.adapter = movieAdapter } private fun initializeRefreshButton() { refresh_button.setOnClickListener { presenter.onRefreshAction() } } private fun initializePresenter() { presenter.attachView(this) } override fun onDestroy() { presenter.detachView() super.onDestroy() } override fun showMovies(movies: List<Movie>) { movieAdapter.setMovies(movies) } override fun clearMovies() { movieAdapter.clearMovies() } override fun showLoading() { pb_loading.visibility = View.VISIBLE movies_title_text_view.text =getString(R.string.loading_movies_text); } override fun hideLoading() { pb_loading.visibility = View.GONE } override fun showTotalMovies(count: Int) { movies_title_text_view.text = getString(R.string.movies_count_text,count) } override fun showConnectionError() { this.toast(R.string.connection_error_text) } }
apache-2.0
e2d8c01e7f7f6109c2b93a626c7a1a0a
28.666667
82
0.717683
4.769072
false
false
false
false
Maccimo/intellij-community
jvm/jvm-analysis-kotlin-tests/testSrc/com/intellij/codeInspection/tests/kotlin/test/junit/KotlinJUnitMalformedDeclarationInspectionTest.kt
1
44113
package com.intellij.codeInspection.tests.kotlin.test.junit import com.intellij.codeInspection.tests.ULanguage import com.intellij.codeInspection.tests.test.junit.JUnitMalformedDeclarationInspectionTestBase import com.intellij.openapi.module.Module import com.intellij.openapi.roots.ContentEntry import com.intellij.openapi.roots.ModifiableRootModel import com.intellij.testFramework.LightProjectDescriptor import com.intellij.testFramework.PsiTestUtil import com.intellij.util.PathUtil import java.io.File class KotlinJUnitMalformedDeclarationInspectionTest : JUnitMalformedDeclarationInspectionTestBase() { override fun getProjectDescriptor(): LightProjectDescriptor = object : JUnitProjectDescriptor(sdkLevel) { override fun configureModule(module: Module, model: ModifiableRootModel, contentEntry: ContentEntry) { super.configureModule(module, model, contentEntry) val jar = File(PathUtil.getJarPathForClass(JvmStatic::class.java)) PsiTestUtil.addLibrary(model, "kotlin-stdlib", jar.parent, jar.name) } } /* Malformed extensions */ fun `test malformed extension no highlighting`() { myFixture.testHighlighting(ULanguage.KOTLIN, """ class A { @org.junit.jupiter.api.extension.RegisterExtension val myRule5 = Rule5() class Rule5 : org.junit.jupiter.api.extension.Extension { } } """.trimIndent()) } fun `test malformed extension highlighting`() { myFixture.testHighlighting(ULanguage.KOTLIN, """ class A { @org.junit.jupiter.api.extension.RegisterExtension val <warning descr="'A.Rule5' should implement 'org.junit.jupiter.api.extension.Extension'">myRule5</warning> = Rule5() class Rule5 { } } """.trimIndent()) } /* Malformed nested class */ fun `test malformed nested no highlighting`() { myFixture.testHighlighting(ULanguage.KOTLIN, """ class A { @org.junit.jupiter.api.Nested inner class B { } } """.trimIndent()) } fun `test malformed nested class highlighting`() { myFixture.testHighlighting(ULanguage.KOTLIN, """ class A { @org.junit.jupiter.api.Nested class <warning descr="Only non-static nested classes can serve as '@Nested' test classes.">B</warning> { } } """.trimIndent()) } /* Malformed parameterized */ fun `test malformed parameterized no highlighting`() { myFixture.testHighlighting(ULanguage.KOTLIN, """ enum class TestEnum { FIRST, SECOND, THIRD } class ValueSourcesTest { @org.junit.jupiter.params.ParameterizedTest @org.junit.jupiter.params.provider.ValueSource(ints = [1]) fun testWithIntValues(i: Int) { } @org.junit.jupiter.params.ParameterizedTest @org.junit.jupiter.params.provider.ValueSource(longs = [1L]) fun testWithIntValues(i: Long) { } @org.junit.jupiter.params.ParameterizedTest @org.junit.jupiter.params.provider.ValueSource(doubles = [0.5]) fun testWithDoubleValues(d: Double) { } @org.junit.jupiter.params.ParameterizedTest @org.junit.jupiter.params.provider.ValueSource(strings = [""]) fun testWithStringValues(s: String) { } @org.junit.jupiter.params.ParameterizedTest @org.junit.jupiter.params.provider.ValueSource(strings = ["foo"]) fun implicitParameter(argument: String, testReporter: org.junit.jupiter.api.TestInfo) { } @org.junit.jupiter.api.extension.ExtendWith(org.junit.jupiter.api.extension.TestExecutionExceptionHandler::class) annotation class RunnerExtension { } @RunnerExtension abstract class AbstractValueSource { } class ValueSourcesWithCustomProvider : AbstractValueSource() { @org.junit.jupiter.params.ParameterizedTest @org.junit.jupiter.params.provider.ValueSource(ints = [1]) fun testWithIntValues(i: Int, fromExtension: String) { } } @org.junit.jupiter.params.ParameterizedTest @org.junit.jupiter.params.provider.ValueSource(strings = ["FIRST"]) fun implicitConversionEnum(e: TestEnum) { } @org.junit.jupiter.params.ParameterizedTest @org.junit.jupiter.params.provider.ValueSource(strings = ["1"]) fun implicitConversionString(i: Int) { } @org.junit.jupiter.params.ParameterizedTest @org.junit.jupiter.params.provider.ValueSource(strings = ["title"]) fun implicitConversionClass(book: Book) { } class Book(val title: String) { } } class MethodSource { @org.junit.jupiter.params.ParameterizedTest @org.junit.jupiter.params.provider.MethodSource("stream") fun simpleStream(x: Int, y: Int) { System.out.println("${'$'}x, ${'$'}y") } @org.junit.jupiter.params.ParameterizedTest @org.junit.jupiter.params.provider.MethodSource("iterable") fun simpleIterable(x: Int, y: Int) { System.out.println("${'$'}x, ${'$'}y") } @org.junit.jupiter.params.ParameterizedTest @org.junit.jupiter.params.provider.MethodSource(value = ["stream", "iterator", "iterable"]) fun parametersArray(x: Int, y: Int) { System.out.println("${'$'}x, ${'$'}y") } @org.junit.jupiter.params.ParameterizedTest @org.junit.jupiter.params.provider.MethodSource(value = ["stream", "iterator"]) fun implicitValueArray(x: Int, y: Int) { System.out.println("${'$'}x, ${'$'}y") } @org.junit.jupiter.params.ParameterizedTest @org.junit.jupiter.params.provider.MethodSource(value = ["argumentsArrayProvider"]) fun argumentsArray(x: Int, s: String) { System.out.println("${'$'}x, ${'$'}s") } @org.junit.jupiter.params.ParameterizedTest @org.junit.jupiter.params.provider.MethodSource(value = ["anyArrayProvider"]) fun anyArray(x: Int, s: String) { System.out.println("${'$'}x, ${'$'}s") } @org.junit.jupiter.params.ParameterizedTest @org.junit.jupiter.params.provider.MethodSource(value = ["any2DArrayProvider"]) fun any2DArray(x: Int, s: String) { System.out.println("${'$'}x, ${'$'}s") } @org.junit.jupiter.params.ParameterizedTest @org.junit.jupiter.params.provider.MethodSource("intStreamProvider") fun intStream(x: Int) { System.out.println(x) } @org.junit.jupiter.params.ParameterizedTest @org.junit.jupiter.params.provider.MethodSource("intStreamProvider") fun injectTestReporter(x: Int, testReporter: org.junit.jupiter.api.TestReporter) { System.out.println("${'$'}x, ${'$'}testReporter") } companion object { @JvmStatic fun stream(): java.util.stream.Stream<org.junit.jupiter.params.provider.Arguments>? { return null } @JvmStatic fun iterable(): Iterable<org.junit.jupiter.params.provider.Arguments>? { return null } @JvmStatic fun argumentsArrayProvider(): Array<org.junit.jupiter.params.provider.Arguments> { return arrayOf(org.junit.jupiter.params.provider.Arguments.of(1, "one")) } @JvmStatic fun anyArrayProvider(): Array<Any> { return arrayOf(org.junit.jupiter.params.provider.Arguments.of(1, "one")) } @JvmStatic fun any2DArrayProvider(): Array<Array<Any>> { return arrayOf(arrayOf(1, "s")) } @JvmStatic fun intStreamProvider(): java.util.stream.IntStream? { return null } } } @org.junit.jupiter.api.TestInstance(org.junit.jupiter.api.TestInstance.Lifecycle.PER_CLASS) class TestWithMethodSource { @org.junit.jupiter.params.ParameterizedTest @org.junit.jupiter.params.provider.MethodSource("getParameters") public fun shouldExecuteWithParameterizedMethodSource(arguments: String) { } public fun getParameters(): java.util.stream.Stream<String> { return java.util.Arrays.asList( "Another execution", "Last execution").stream() } } class EnumSource { @org.junit.jupiter.params.ParameterizedTest @org.junit.jupiter.params.provider.EnumSource(names = ["FIRST"]) fun runTest(value: TestEnum) { } @org.junit.jupiter.params.ParameterizedTest @org.junit.jupiter.params.provider.EnumSource( value = TestEnum::class, names = ["regexp-value"], mode = org.junit.jupiter.params.provider.EnumSource.Mode.MATCH_ALL ) fun disable() { } @org.junit.jupiter.params.ParameterizedTest @org.junit.jupiter.params.provider.EnumSource(value = TestEnum::class, names = ["SECOND", "FIRST"/*, "commented"*/]) fun array() { } @org.junit.jupiter.params.ParameterizedTest @org.junit.jupiter.params.provider.EnumSource(TestEnum::class) fun testWithEnumSourceCorrect(value: TestEnum) { } } class CsvSource { @org.junit.jupiter.params.ParameterizedTest @org.junit.jupiter.params.provider.CsvSource(value = ["src, 1"]) fun testWithCsvSource(first: String, second: Int) { } } class NullSource { @org.junit.jupiter.params.ParameterizedTest @org.junit.jupiter.params.provider.NullSource fun testWithNullSrc(o: Any) { } } class EmptySource { @org.junit.jupiter.params.ParameterizedTest @org.junit.jupiter.params.provider.EmptySource fun testFooSet(input: Set<String>) {} @org.junit.jupiter.params.ParameterizedTest @org.junit.jupiter.params.provider.EmptySource fun testFooList(input: List<String>) {} @org.junit.jupiter.params.ParameterizedTest @org.junit.jupiter.params.provider.EmptySource fun testFooMap(input: Map<String, String>) {} } """.trimIndent() ) } fun `test malformed parameterized value source wrong type`() { myFixture.testHighlighting(ULanguage.KOTLIN, """ class ValueSourcesTest { @org.junit.jupiter.params.ParameterizedTest @org.junit.jupiter.params.provider.ValueSource(booleans = [ <warning descr="No implicit conversion found to convert 'boolean' to 'int'">false</warning> ]) fun testWithBooleanSource(argument: Int) { } } """.trimIndent()) } fun `test malformed parameterized enum source wrong type`() { myFixture.testHighlighting(ULanguage.KOTLIN, """ enum class TestEnum { FIRST, SECOND, THIRD } class ValueSourcesTest { @org.junit.jupiter.params.ParameterizedTest @org.junit.jupiter.params.provider.EnumSource(<warning descr="No implicit conversion found to convert 'TestEnum' to 'int'">TestEnum::class</warning>) fun testWithEnumSource(i: Int) { } } """.trimIndent()) } fun `test malformed parameterized multiple types`() { myFixture.testHighlighting(ULanguage.KOTLIN, """ class ValueSourcesTest { @org.junit.jupiter.params.ParameterizedTest @org.junit.jupiter.params.provider.<warning descr="Exactly one type of input must be provided">ValueSource</warning>( ints = [1], strings = ["str"] ) fun testWithMultipleValues(i: Int) { } } """.trimIndent()) } fun `test malformed parameterized no value defined`() { myFixture.testHighlighting(ULanguage.KOTLIN, """ class ValueSourcesTest { @org.junit.jupiter.params.ParameterizedTest @org.junit.jupiter.params.provider.<warning descr="No value source is defined">ValueSource</warning>() fun testWithNoValues(i: Int) { } } """.trimIndent()) } fun `test malformed parameterized no argument defined`() { myFixture.testHighlighting(ULanguage.KOTLIN, """ class ValueSourcesTest { @org.junit.jupiter.params.ParameterizedTest <warning descr="'@NullSource' cannot provide an argument to method because method doesn't have parameters">@org.junit.jupiter.params.provider.NullSource</warning> fun testWithNullSrcNoParam() {} } """.trimIndent()) } fun `test malformed parameterized value source multiple parameters`() { myFixture.testHighlighting(ULanguage.KOTLIN, """ class ValueSourcesTest { @org.junit.jupiter.params.ParameterizedTest @org.junit.jupiter.params.provider.ValueSource(strings = ["foo"]) fun <warning descr="Multiple parameters are not supported by this source">testWithMultipleParams</warning>(argument: String, i: Int) { } } """.trimIndent()) } fun `test malformed parameterized and test annotation defined`() { myFixture.testHighlighting(ULanguage.KOTLIN, """ class ValueSourcesTest { @org.junit.jupiter.params.ParameterizedTest @org.junit.jupiter.params.provider.ValueSource(ints = [1]) @org.junit.jupiter.api.Test fun <warning descr="Suspicious combination of '@Test' and '@ParameterizedTest'">testWithTestAnnotation</warning>(i: Int) { } } """.trimIndent()) } fun `test malformed parameterized and value source defined`() { myFixture.testHighlighting(ULanguage.KOTLIN, """ class ValueSourcesTest { @org.junit.jupiter.params.provider.ValueSource(ints = [1]) @org.junit.jupiter.api.Test fun <warning descr="Suspicious combination of '@ValueSource' and '@Test'">testWithTestAnnotationNoParameterized</warning>(i: Int) { } } """.trimIndent()) } fun `test malformed parameterized no argument source provided`() { myFixture.testHighlighting(ULanguage.KOTLIN, """ class ValueSourcesTest { @org.junit.jupiter.params.ParameterizedTest @org.junit.jupiter.params.provider.ArgumentsSources() fun <warning descr="No sources are provided, the suite would be empty">emptyArgs</warning>(param: String) { } } """.trimIndent()) } fun `test malformed parameterized method source should be static`() { myFixture.testHighlighting(ULanguage.KOTLIN, """ class ValueSourcesTest { @org.junit.jupiter.params.ParameterizedTest @org.junit.jupiter.params.provider.MethodSource("<warning descr="Method source 'a' must be static">a</warning>") fun foo(param: String) { } fun a(): Array<String> { return arrayOf("a", "b") } } """.trimIndent()) } fun `test malformed parameterized method source should have no parameters`() { myFixture.testHighlighting(ULanguage.KOTLIN, """ class ValueSourcesTest { @org.junit.jupiter.params.ParameterizedTest @org.junit.jupiter.params.provider.MethodSource("<warning descr="Method source 'a' should have no parameters">a</warning>") fun foo(param: String) { } companion object { @JvmStatic fun a(i: Int): Array<String> { return arrayOf("a", i.toString()) } } } """.trimIndent()) } fun `test malformed parameterized method source wrong return type`() { myFixture.testHighlighting(ULanguage.KOTLIN, """ class ValueSourcesTest { @org.junit.jupiter.params.ParameterizedTest @org.junit.jupiter.params.provider.MethodSource( "<warning descr="Method source 'a' must have one of the following return types: 'Stream<?>', 'Iterator<?>', 'Iterable<?>' or 'Object[]'">a</warning>" ) fun foo(param: String) { } companion object { @JvmStatic fun a(): Any { return arrayOf("a", "b") } } } """.trimIndent()) } fun `test malformed parameterized method source not found`() { myFixture.testHighlighting(ULanguage.KOTLIN, """ class ValueSourcesTest { @org.junit.jupiter.params.ParameterizedTest @org.junit.jupiter.params.provider.MethodSource("<warning descr="Cannot resolve target method source: 'a'">a</warning>") fun foo(param: String) { } } """.trimIndent()) } fun `test malformed parameterized enum source unresolvable entry`() { myFixture.testHighlighting(ULanguage.KOTLIN, """ class EnumSourceTest { private enum class Foo { AAA, AAX, BBB } @org.junit.jupiter.params.ParameterizedTest @org.junit.jupiter.params.provider.EnumSource( value = Foo::class, names = ["<warning descr="Can't resolve 'enum' constant reference.">invalid-value</warning>"], mode = org.junit.jupiter.params.provider.EnumSource.Mode.INCLUDE ) fun invalid() { } @org.junit.jupiter.params.ParameterizedTest @org.junit.jupiter.params.provider.EnumSource( value = Foo::class, names = ["<warning descr="Can't resolve 'enum' constant reference.">invalid-value</warning>"] ) fun invalidDefault() { } } """.trimIndent()) } fun `test malformed parameterized add test instance quick fix`() { myFixture.testQuickFix(ULanguage.KOTLIN, """ import org.junit.jupiter.params.ParameterizedTest import org.junit.jupiter.params.provider.Arguments import org.junit.jupiter.params.provider.MethodSource import java.util.stream.Stream; class Test { private fun parameters(): Stream<Arguments>? { return null; } @MethodSource("param<caret>eters") @ParameterizedTest fun foo(param: String) { } } """.trimIndent(), """ import org.junit.jupiter.api.TestInstance import org.junit.jupiter.params.ParameterizedTest import org.junit.jupiter.params.provider.Arguments import org.junit.jupiter.params.provider.MethodSource import java.util.stream.Stream; @TestInstance(TestInstance.Lifecycle.PER_CLASS) class Test { private fun parameters(): Stream<Arguments>? { return null; } @MethodSource("param<caret>eters") @ParameterizedTest fun foo(param: String) { } } """.trimIndent(), "Annotate as @TestInstance") } fun `test malformed parameterized introduce method source quick fix`() { myFixture.testQuickFix(ULanguage.KOTLIN, """ import org.junit.jupiter.params.ParameterizedTest import org.junit.jupiter.params.provider.MethodSource class Test { @MethodSource("para<caret>meters") @ParameterizedTest fun foo(param: String) { } } """.trimIndent(), """ import org.junit.jupiter.params.ParameterizedTest import org.junit.jupiter.params.provider.Arguments import org.junit.jupiter.params.provider.MethodSource import java.util.stream.Stream class Test { @MethodSource("parameters") @ParameterizedTest fun foo(param: String) { } companion object { @JvmStatic fun parameters(): Stream<Arguments> { TODO("Not yet implemented") } } } """.trimIndent(), "Add method 'parameters' to 'Test'") } fun `test malformed parameterized create csv source quick fix`() { val file = myFixture.addFileToProject("CsvFile.kt", """ class CsvFile { @org.junit.jupiter.params.ParameterizedTest @org.junit.jupiter.params.provider.CsvFileSource(resources = "two-<caret>column.txt") fun testWithCsvFileSource(first: String, second: Int) { } } """.trimIndent()) myFixture.configureFromExistingVirtualFile(file.virtualFile) val intention = myFixture.findSingleIntention("Create File two-column.txt") assertNotNull(intention) myFixture.launchAction(intention) assertNotNull(myFixture.findFileInTempDir("two-column.txt")) } /* Malformed repeated test*/ fun `test malformed repeated test no highlighting`() { myFixture.testHighlighting(ULanguage.KOTLIN, """ object WithRepeated { @org.junit.jupiter.api.RepeatedTest(1) fun repeatedTestNoParams() { } @org.junit.jupiter.api.RepeatedTest(1) fun repeatedTestWithRepetitionInfo(repetitionInfo: org.junit.jupiter.api.RepetitionInfo) { } @org.junit.jupiter.api.BeforeEach fun config(repetitionInfo: org.junit.jupiter.api.RepetitionInfo) { } } class WithRepeatedAndCustomNames { @org.junit.jupiter.api.RepeatedTest(value = 1, name = "{displayName} {currentRepetition}/{totalRepetitions}") fun repeatedTestWithCustomName() { } } class WithRepeatedAndTestInfo { @org.junit.jupiter.api.BeforeEach fun beforeEach(testInfo: org.junit.jupiter.api.TestInfo, repetitionInfo: org.junit.jupiter.api.RepetitionInfo) {} @org.junit.jupiter.api.RepeatedTest(1) fun repeatedTestWithTestInfo(testInfo: org.junit.jupiter.api.TestInfo) { } @org.junit.jupiter.api.AfterEach fun afterEach(testInfo: org.junit.jupiter.api.TestInfo, repetitionInfo: org.junit.jupiter.api.RepetitionInfo) {} } class WithRepeatedAndTestReporter { @org.junit.jupiter.api.BeforeEach fun beforeEach(testReporter: org.junit.jupiter.api.TestReporter, repetitionInfo: org.junit.jupiter.api.RepetitionInfo) {} @org.junit.jupiter.api.RepeatedTest(1) fun repeatedTestWithTestInfo(testReporter: org.junit.jupiter.api.TestReporter) { } @org.junit.jupiter.api.AfterEach fun afterEach(testReporter: org.junit.jupiter.api.TestReporter, repetitionInfo: org.junit.jupiter.api.RepetitionInfo) {} } """.trimIndent()) } fun `test malformed repeated test combination of @Test and @RepeatedTest`() { myFixture.testHighlighting(ULanguage.KOTLIN, """ class WithRepeatedAndTests { @org.junit.jupiter.api.Test @org.junit.jupiter.api.RepeatedTest(1) fun <warning descr="Suspicious combination of '@Test' and '@RepeatedTest'">repeatedTestAndTest</warning>() { } } """.trimIndent()) } fun `test malformed repeated test with injected RepeatedInfo for @Test method`() { myFixture.testHighlighting(ULanguage.KOTLIN, """ class WithRepeatedInfoAndTest { @org.junit.jupiter.api.BeforeEach fun beforeEach(repetitionInfo: org.junit.jupiter.api.RepetitionInfo) { } @org.junit.jupiter.api.Test fun <warning descr="Method 'nonRepeated' annotated with '@Test' should not declare parameter 'repetitionInfo'">nonRepeated</warning>(repetitionInfo: org.junit.jupiter.api.RepetitionInfo) { } } """.trimIndent() ) } fun `test malformed repeated test with injected RepetitionInfo for @BeforeAll method`() { myFixture.testHighlighting(ULanguage.KOTLIN, """ class WithBeforeEach { companion object { @JvmStatic @org.junit.jupiter.api.BeforeAll fun <warning descr="Method 'beforeAllWithRepetitionInfo' annotated with '@BeforeAll' should not declare parameter 'repetitionInfo'">beforeAllWithRepetitionInfo</warning>(repetitionInfo: org.junit.jupiter.api.RepetitionInfo) { } } } """.trimIndent()) } fun `test malformed repeated test with non-positive repetitions`() { myFixture.testHighlighting(ULanguage.KOTLIN, """ class WithRepeated { @org.junit.jupiter.api.RepeatedTest(<warning descr="The number of repetitions must be greater than zero">-1</warning>) fun repeatedTestNegative() { } @org.junit.jupiter.api.RepeatedTest(<warning descr="The number of repetitions must be greater than zero">0</warning>) fun repeatedTestBoundaryZero() { } } """.trimIndent()) } /* Malformed before after */ fun `test malformed before highlighting`() { myFixture.testHighlighting(ULanguage.KOTLIN, """ class MainTest { @org.junit.Before fun <warning descr="Method 'before' annotated with '@Before' should be of type 'void' and not declare parameter 'i'">before</warning>(i: Int): String { return "${'$'}i" } } """.trimIndent()) } fun `test malformed before each highlighting`() { myFixture.testHighlighting(ULanguage.KOTLIN, """ class MainTest { @org.junit.jupiter.api.BeforeEach fun <warning descr="Method 'beforeEach' annotated with '@BeforeEach' should be of type 'void' and not declare parameter 'i'">beforeEach</warning>(i: Int): String { return "" } } """.trimIndent()) } fun `test malformed before each remove private quickfix`() { myFixture.testQuickFix(ULanguage.KOTLIN, """ class MainTest { @org.junit.jupiter.api.BeforeEach private fun bef<caret>oreEach() { } } """.trimIndent(), """ import org.junit.jupiter.api.BeforeEach class MainTest { @BeforeEach fun bef<caret>oreEach(): Unit { } } """.trimIndent(), "Fix 'beforeEach' method signature") } fun `test malformed before class no highlighting`() { myFixture.testHighlighting(ULanguage.KOTLIN, """ class BeforeClassStatic { companion object { @JvmStatic @org.junit.BeforeClass fun beforeClass() { } } } @org.junit.jupiter.api.TestInstance(org.junit.jupiter.api.TestInstance.Lifecycle.PER_CLASS) class BeforeAllTestInstancePerClass { @org.junit.jupiter.api.BeforeAll fun beforeAll() { } } class BeforeAllStatic { companion object { @JvmStatic @org.junit.jupiter.api.BeforeAll fun beforeAll() { } } } class TestParameterResolver : org.junit.jupiter.api.extension.ParameterResolver { override fun supportsParameter( parameterContext: org.junit.jupiter.api.extension.ParameterContext, extensionContext: org.junit.jupiter.api.extension.ExtensionContext ): Boolean = true override fun resolveParameter( parameterContext: org.junit.jupiter.api.extension.ParameterContext, extensionContext: org.junit.jupiter.api.extension.ExtensionContext ): Any = "" } @org.junit.jupiter.api.extension.ExtendWith(TestParameterResolver::class) class ParameterResolver { companion object { @JvmStatic @org.junit.jupiter.api.BeforeAll fun beforeAll(foo: String) { println(foo) } } } @org.junit.jupiter.api.extension.ExtendWith(value = [TestParameterResolver::class]) class ParameterResolverArray { companion object { @JvmStatic @org.junit.jupiter.api.BeforeAll fun beforeAll(foo: String) { println(foo) } } } @org.junit.jupiter.api.extension.ExtendWith(TestParameterResolver::class) annotation class CustomTestAnnotation @CustomTestAnnotation class MetaParameterResolver { companion object { @JvmStatic @org.junit.jupiter.api.BeforeAll fun beforeAll(foo: String) { println(foo) } } } """.trimIndent()) } fun `test malformed before class method that is non-static`() { myFixture.testHighlighting(ULanguage.KOTLIN, """ class MainTest { @org.junit.BeforeClass fun <warning descr="Method 'beforeClass' annotated with '@BeforeClass' should be static">beforeClass</warning>() { } } """.trimIndent()) } fun `test malformed before class method that is not private`() { myFixture.testHighlighting(ULanguage.KOTLIN, """ class MainTest { companion object { @JvmStatic @org.junit.BeforeClass private fun <warning descr="Method 'beforeClass' annotated with '@BeforeClass' should be public">beforeClass</warning>() { } } } """.trimIndent()) } fun `test malformed before class method that has parameters`() { myFixture.testHighlighting(ULanguage.KOTLIN, """ class MainTest { companion object { @JvmStatic @org.junit.BeforeClass fun <warning descr="Method 'beforeClass' annotated with '@BeforeClass' should not declare parameter 'i'">beforeClass</warning>(i: Int) { System.out.println(i) } } } """.trimIndent()) } fun `test malformed before class method with a non void return type`() { myFixture.testHighlighting(ULanguage.KOTLIN, """ class MainTest { companion object { @JvmStatic @org.junit.BeforeClass fun <warning descr="Method 'beforeClass' annotated with '@BeforeClass' should be of type 'void'">beforeClass</warning>(): String { return "" } } } """.trimIndent()) } fun `test malformed before all method that is non-static`() { myFixture.testHighlighting(ULanguage.KOTLIN, """ class MainTest { @org.junit.jupiter.api.BeforeAll fun <warning descr="Method 'beforeAll' annotated with '@BeforeAll' should be static">beforeAll</warning>() { } } """.trimIndent()) } fun `test malformed before all method that is not private`() { myFixture.testHighlighting(ULanguage.KOTLIN, """ class MainTest { companion object { @JvmStatic @org.junit.jupiter.api.BeforeAll private fun <warning descr="Method 'beforeAll' annotated with '@BeforeAll' should be public">beforeAll</warning>() { } } } """.trimIndent()) } fun `test malformed before all method that has parameters`() { myFixture.testHighlighting(ULanguage.KOTLIN, """ class MainTest { companion object { @JvmStatic @org.junit.jupiter.api.BeforeAll fun <warning descr="Method 'beforeAll' annotated with '@BeforeAll' should not declare parameter 'i'">beforeAll</warning>(i: Int) { System.out.println(i) } } } """.trimIndent()) } fun `test malformed before all method with a non void return type`() { myFixture.testHighlighting(ULanguage.KOTLIN, """ class MainTest { companion object { @JvmStatic @org.junit.jupiter.api.BeforeAll fun <warning descr="Method 'beforeAll' annotated with '@BeforeAll' should be of type 'void'">beforeAll</warning>(): String { return "" } } } """.trimIndent()) } fun `test malformed before all quickfix`() { myFixture.testQuickFix(ULanguage.KOTLIN, """ import org.junit.jupiter.api.BeforeAll class MainTest { @BeforeAll fun before<caret>All(i: Int): String { return "" } } """.trimIndent(), """ import org.junit.jupiter.api.BeforeAll class MainTest { companion object { @JvmStatic @BeforeAll fun beforeAll(): Unit { return "" } } } """.trimIndent(), "Fix 'beforeAll' method signature") } /* Malformed datapoint(s) */ fun `test malformed datapoint no highlighting`() { myFixture.testHighlighting(ULanguage.KOTLIN, """ class Test { companion object { @JvmField @org.junit.experimental.theories.DataPoint val f1: Any? = null } } """.trimIndent()) } fun `test malformed datapoint non-static highlighting`() { myFixture.testHighlighting(ULanguage.KOTLIN, """ class Test { @JvmField @org.junit.experimental.theories.DataPoint val <warning descr="Field 'f1' annotated with '@DataPoint' should be static">f1</warning>: Any? = null } """.trimIndent()) } fun `test malformed datapoint non-public highlighting`() { myFixture.testHighlighting(ULanguage.KOTLIN, """ class Test { companion object { @JvmStatic @org.junit.experimental.theories.DataPoint private val <warning descr="Field 'f1' annotated with '@DataPoint' should be public">f1</warning>: Any? = null } } """.trimIndent()) } fun `test malformed datapoint field highlighting`() { myFixture.testHighlighting(ULanguage.KOTLIN, """ class Test { @org.junit.experimental.theories.DataPoint private val <warning descr="Field 'f1' annotated with '@DataPoint' should be static and public">f1</warning>: Any? = null } """.trimIndent()) } fun `test malformed datapoint method highlighting`() { myFixture.testHighlighting(ULanguage.KOTLIN, """ class Test { @org.junit.experimental.theories.DataPoint private fun <warning descr="Method 'f1' annotated with '@DataPoint' should be static and public">f1</warning>(): Any? = null } """.trimIndent()) } fun `test malformed datapoints method highlighting`() { myFixture.testHighlighting(ULanguage.KOTLIN, """ class Test { @org.junit.experimental.theories.DataPoints private fun <warning descr="Method 'f1' annotated with '@DataPoints' should be static and public">f1</warning>(): Any? = null } """.trimIndent()) } fun `test malformed datapoint make field public quickfix`() { myFixture.testQuickFix(ULanguage.KOTLIN, """ class Test { companion object { @org.junit.experimental.theories.DataPoint val f<caret>1: Any? = null } } """.trimIndent(), """ class Test { companion object { @kotlin.jvm.JvmField @org.junit.experimental.theories.DataPoint val f1: Any? = null } } """.trimIndent(), "Fix 'f1' field signature") } fun `test malformed datapoint make field public and static quickfix`() { myFixture.testQuickFix(ULanguage.KOTLIN, """ class Test { @org.junit.experimental.theories.DataPoint val f<caret>1: Any? = null } """.trimIndent(), """ class Test { companion object { @kotlin.jvm.JvmField @org.junit.experimental.theories.DataPoint val f1: Any? = null } } """.trimIndent(), "Fix 'f1' field signature") } fun `test malformed datapoint make method public and static quickfix`() { myFixture.testQuickFix(ULanguage.KOTLIN, """ class Test { @org.junit.experimental.theories.DataPoint private fun f<caret>1(): Any? = null } """.trimIndent(), """ class Test { companion object { @JvmStatic @org.junit.experimental.theories.DataPoint fun f1(): Any? = null } } """.trimIndent(), "Fix 'f1' method signature") } /* Malformed setup/teardown */ fun `test malformed setup no highlighting`() { myFixture.testHighlighting(ULanguage.KOTLIN, """ class C : junit.framework.TestCase() { override fun setUp() { } } """.trimIndent()) } fun `test malformed setup highlighting`() { myFixture.testHighlighting(ULanguage.KOTLIN, """ class C : junit.framework.TestCase() { private fun <warning descr="Method 'setUp' should be a non-private, non-static, have no parameters and be of type void">setUp</warning>(i: Int) { System.out.println(i) } } """.trimIndent()) } fun `test malformed setup quickfix`() { myFixture.testQuickFix(ULanguage.KOTLIN, """ class C : junit.framework.TestCase() { private fun set<caret>Up(i: Int) { } } """.trimIndent(), """ class C : junit.framework.TestCase() { fun setUp(): Unit { } } """.trimIndent(), "Fix 'setUp' method signature") } /* Malformed rule */ fun `test malformed rule field non-public highlighting`() { myFixture.testHighlighting(ULanguage.KOTLIN, """ class SomeTestRule : org.junit.rules.TestRule { override fun apply(base: org.junit.runners.model.Statement, description: org.junit.runner.Description): org.junit.runners.model.Statement = base } class PrivateRule { @org.junit.Rule var <warning descr="Field 'x' annotated with '@Rule' should be public">x</warning> = SomeTestRule() } """.trimIndent()) } fun `test malformed rule object inherited rule highlighting`() { myFixture.testHighlighting(ULanguage.KOTLIN, """ class SomeTestRule : org.junit.rules.TestRule { override fun apply(base: org.junit.runners.model.Statement, description: org.junit.runner.Description): org.junit.runners.model.Statement = base } object OtherRule : org.junit.rules.TestRule { override fun apply(base: org.junit.runners.model.Statement, description: org.junit.runner.Description): org.junit.runners.model.Statement = base } object ObjRule { @org.junit.Rule private var <warning descr="Field 'x' annotated with '@Rule' should be non-static and public">x</warning> = SomeTestRule() } class ClazzRule { @org.junit.Rule fun x() = OtherRule @org.junit.Rule fun <warning descr="Method 'y' annotated with '@Rule' should be of type 'org.junit.rules.TestRule'">y</warning>() = 0 @org.junit.Rule public fun z() = object : org.junit.rules.TestRule { override fun apply(base: org.junit.runners.model.Statement, description: org.junit.runner.Description): org.junit.runners.model.Statement = base } @org.junit.Rule public fun <warning descr="Method 'a' annotated with '@Rule' should be of type 'org.junit.rules.TestRule'">a</warning>() = object { } } """.trimIndent()) } fun `test malformed rule method static highlighting`() { myFixture.testHighlighting(ULanguage.KOTLIN, """ class SomeTestRule : org.junit.rules.TestRule { override fun apply(base: org.junit.runners.model.Statement, description: org.junit.runner.Description): org.junit.runners.model.Statement = base } class PrivateRule { @org.junit.Rule private fun <warning descr="Method 'x' annotated with '@Rule' should be public">x</warning>() = SomeTestRule() } """.trimIndent()) } fun `test malformed rule method non TestRule type highlighting`() { myFixture.testHighlighting(ULanguage.KOTLIN, """ class PrivateRule { @org.junit.Rule fun <warning descr="Method 'x' annotated with '@Rule' should be of type 'org.junit.rules.TestRule'">x</warning>() = 0 } """.trimIndent()) } fun `test malformed class rule field highlighting`() { myFixture.testHighlighting(ULanguage.KOTLIN, """ class SomeTestRule : org.junit.rules.TestRule { override fun apply(base: org.junit.runners.model.Statement, description: org.junit.runner.Description): org.junit.runners.model.Statement = base } object PrivateClassRule { @org.junit.ClassRule private var <warning descr="Field 'x' annotated with '@ClassRule' should be public">x</warning> = SomeTestRule() @org.junit.ClassRule private var <warning descr="Field 'y' annotated with '@ClassRule' should be public and be of type 'org.junit.rules.TestRule'">y</warning> = 0 } """.trimIndent()) } fun `test malformed rule make field public quickfix`() { myFixture.testQuickFix(ULanguage.KOTLIN, """ class PrivateRule { @org.junit.Rule var x<caret> = 0 } """.trimIndent(), """ class PrivateRule { @kotlin.jvm.JvmField @org.junit.Rule var x = 0 } """.trimIndent(), "Fix 'x' field signature") } fun `test malformed class rule make field public quickfix`() { myFixture.testQuickFix(ULanguage.KOTLIN, """ class SomeTestRule : org.junit.rules.TestRule { override fun apply(base: org.junit.runners.model.Statement, description: org.junit.runner.Description): org.junit.runners.model.Statement = base } object PrivateClassRule { @org.junit.ClassRule private var x<caret> = SomeTestRule() } """.trimIndent(), """ class SomeTestRule : org.junit.rules.TestRule { override fun apply(base: org.junit.runners.model.Statement, description: org.junit.runner.Description): org.junit.runners.model.Statement = base } object PrivateClassRule { @kotlin.jvm.JvmField @org.junit.ClassRule var x = SomeTestRule() } """.trimIndent(), "Fix 'x' field signature") } /* Malformed test */ fun `test malformed test for JUnit 3 highlighting`() { myFixture.testHighlighting(ULanguage.KOTLIN, """ public class JUnit3TestMethodIsPublicVoidNoArg : junit.framework.TestCase() { fun testOne() { } public fun <warning descr="Method 'testTwo' should be a public, non-static, have no parameters and be of type void">testTwo</warning>(): Int { return 2 } public fun <warning descr="Method 'testFour' should be a public, non-static, have no parameters and be of type void">testFour</warning>(i: Int) { println(i) } public fun testFive() { } private fun testSix(i: Int) { println(i) } //ignore when method doesn't look like test anymore companion object { @JvmStatic public fun <warning descr="Method 'testThree' should be a public, non-static, have no parameters and be of type void">testThree</warning>() { } } } """.trimIndent()) } fun `test malformed test for JUnit 4 highlighting`() { myFixture.addClass(""" package mockit; public @interface Mocked { } """.trimIndent()) myFixture.testHighlighting(ULanguage.KOTLIN, """ public class JUnit4TestMethodIsPublicVoidNoArg { @org.junit.Test fun testOne() { } @org.junit.Test public fun <warning descr="Method 'testTwo' annotated with '@Test' should be of type 'void'">testTwo</warning>(): Int { return 2 } @org.junit.Test public fun <warning descr="Method 'testFour' annotated with '@Test' should not declare parameter 'i'">testFour</warning>(i: Int) { } @org.junit.Test public fun testFive() { } @org.junit.Test public fun testMock(@mockit.Mocked s: String) { } companion object { @JvmStatic @org.junit.Test public fun <warning descr="Method 'testThree' annotated with '@Test' should be non-static">testThree</warning>() { } } } """.trimIndent()) } fun `test malformed test for JUnit 4 runWith highlighting`() { myFixture.testHighlighting(ULanguage.KOTLIN, """ @org.junit.runner.RunWith(org.junit.runner.Runner::class) class JUnit4RunWith { @org.junit.Test public fun <warning descr="Method 'testMe' annotated with '@Test' should be of type 'void' and not declare parameter 'i'">testMe</warning>(i: Int): Int { return -1 } } """.trimIndent()) } /* Malformed suite */ fun `test malformed suite no highlighting`() { myFixture.testHighlighting(ULanguage.KOTLIN, """ class Junit3Suite : junit.framework.TestCase() { companion object { @JvmStatic fun suite() = junit.framework.TestSuite() } } """.trimIndent()) } fun `test malformed suite highlighting`() { myFixture.testHighlighting(ULanguage.KOTLIN, """ class Junit3Suite : junit.framework.TestCase() { fun <warning descr="Method 'suite' should be a non-private, static and have no parameters">suite</warning>() = junit.framework.TestSuite() } """.trimIndent()) } fun `test malformed suite quickfix`() { myFixture.testQuickFix(ULanguage.KOTLIN, """ class Junit3Suite : junit.framework.TestCase() { fun sui<caret>te() = junit.framework.TestSuite() } """.trimIndent(), """ class Junit3Suite : junit.framework.TestCase() { companion object { @JvmStatic fun suite() = junit.framework.TestSuite() } } """.trimIndent(), "Fix 'suite' method signature") } }
apache-2.0
bf6a800f121f6807dca2d52e9ac80bb8
39.508724
237
0.641466
4.600855
false
true
false
false
Maccimo/intellij-community
platform/workspaceModel/storage/testEntities/gen/com/intellij/workspaceModel/storage/entities/test/api/OoParentWithPidEntityImpl.kt
3
10727
package com.intellij.workspaceModel.storage.entities.test.api import com.intellij.workspaceModel.storage.* import com.intellij.workspaceModel.storage.EntityInformation import com.intellij.workspaceModel.storage.EntitySource import com.intellij.workspaceModel.storage.EntityStorage import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion import com.intellij.workspaceModel.storage.ModifiableWorkspaceEntity import com.intellij.workspaceModel.storage.MutableEntityStorage import com.intellij.workspaceModel.storage.PersistentEntityId import com.intellij.workspaceModel.storage.WorkspaceEntity import com.intellij.workspaceModel.storage.impl.ConnectionId import com.intellij.workspaceModel.storage.impl.EntityLink import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData import com.intellij.workspaceModel.storage.impl.extractOneToOneChild import com.intellij.workspaceModel.storage.impl.updateOneToOneChildOfParent import org.jetbrains.deft.ObjBuilder import org.jetbrains.deft.Type import org.jetbrains.deft.annotations.Child @GeneratedCodeApiVersion(1) @GeneratedCodeImplVersion(1) open class OoParentWithPidEntityImpl: OoParentWithPidEntity, WorkspaceEntityBase() { companion object { internal val CHILDONE_CONNECTION_ID: ConnectionId = ConnectionId.create(OoParentWithPidEntity::class.java, OoChildForParentWithPidEntity::class.java, ConnectionId.ConnectionType.ONE_TO_ONE, false) internal val CHILDTHREE_CONNECTION_ID: ConnectionId = ConnectionId.create(OoParentWithPidEntity::class.java, OoChildAlsoWithPidEntity::class.java, ConnectionId.ConnectionType.ONE_TO_ONE, false) val connections = listOf<ConnectionId>( CHILDONE_CONNECTION_ID, CHILDTHREE_CONNECTION_ID, ) } @JvmField var _parentProperty: String? = null override val parentProperty: String get() = _parentProperty!! override val childOne: OoChildForParentWithPidEntity? get() = snapshot.extractOneToOneChild(CHILDONE_CONNECTION_ID, this) override val childThree: OoChildAlsoWithPidEntity? get() = snapshot.extractOneToOneChild(CHILDTHREE_CONNECTION_ID, this) override fun connectionIdList(): List<ConnectionId> { return connections } class Builder(val result: OoParentWithPidEntityData?): ModifiableWorkspaceEntityBase<OoParentWithPidEntity>(), OoParentWithPidEntity.Builder { constructor(): this(OoParentWithPidEntityData()) override fun applyToBuilder(builder: MutableEntityStorage) { if (this.diff != null) { if (existsInBuilder(builder)) { this.diff = builder return } else { error("Entity OoParentWithPidEntity is already created in a different builder") } } this.diff = builder this.snapshot = builder addToBuilder() this.id = getEntityData().createEntityId() // Process linked entities that are connected without a builder processLinkedEntities(builder) checkInitialization() // TODO uncomment and check failed tests } fun checkInitialization() { val _diff = diff if (!getEntityData().isParentPropertyInitialized()) { error("Field OoParentWithPidEntity#parentProperty should be initialized") } if (!getEntityData().isEntitySourceInitialized()) { error("Field OoParentWithPidEntity#entitySource should be initialized") } } override fun connectionIdList(): List<ConnectionId> { return connections } override var parentProperty: String get() = getEntityData().parentProperty set(value) { checkModificationAllowed() getEntityData().parentProperty = value changedProperty.add("parentProperty") } override var entitySource: EntitySource get() = getEntityData().entitySource set(value) { checkModificationAllowed() getEntityData().entitySource = value changedProperty.add("entitySource") } override var childOne: OoChildForParentWithPidEntity? get() { val _diff = diff return if (_diff != null) { _diff.extractOneToOneChild(CHILDONE_CONNECTION_ID, this) ?: this.entityLinks[EntityLink(true, CHILDONE_CONNECTION_ID)] as? OoChildForParentWithPidEntity } else { this.entityLinks[EntityLink(true, CHILDONE_CONNECTION_ID)] as? OoChildForParentWithPidEntity } } set(value) { checkModificationAllowed() val _diff = diff if (_diff != null && value is ModifiableWorkspaceEntityBase<*> && value.diff == null) { if (value is ModifiableWorkspaceEntityBase<*>) { value.entityLinks[EntityLink(false, CHILDONE_CONNECTION_ID)] = this } // else you're attaching a new entity to an existing entity that is not modifiable _diff.addEntity(value) } if (_diff != null && (value !is ModifiableWorkspaceEntityBase<*> || value.diff != null)) { _diff.updateOneToOneChildOfParent(CHILDONE_CONNECTION_ID, this, value) } else { if (value is ModifiableWorkspaceEntityBase<*>) { value.entityLinks[EntityLink(false, CHILDONE_CONNECTION_ID)] = this } // else you're attaching a new entity to an existing entity that is not modifiable this.entityLinks[EntityLink(true, CHILDONE_CONNECTION_ID)] = value } changedProperty.add("childOne") } override var childThree: OoChildAlsoWithPidEntity? get() { val _diff = diff return if (_diff != null) { _diff.extractOneToOneChild(CHILDTHREE_CONNECTION_ID, this) ?: this.entityLinks[EntityLink(true, CHILDTHREE_CONNECTION_ID)] as? OoChildAlsoWithPidEntity } else { this.entityLinks[EntityLink(true, CHILDTHREE_CONNECTION_ID)] as? OoChildAlsoWithPidEntity } } set(value) { checkModificationAllowed() val _diff = diff if (_diff != null && value is ModifiableWorkspaceEntityBase<*> && value.diff == null) { if (value is ModifiableWorkspaceEntityBase<*>) { value.entityLinks[EntityLink(false, CHILDTHREE_CONNECTION_ID)] = this } // else you're attaching a new entity to an existing entity that is not modifiable _diff.addEntity(value) } if (_diff != null && (value !is ModifiableWorkspaceEntityBase<*> || value.diff != null)) { _diff.updateOneToOneChildOfParent(CHILDTHREE_CONNECTION_ID, this, value) } else { if (value is ModifiableWorkspaceEntityBase<*>) { value.entityLinks[EntityLink(false, CHILDTHREE_CONNECTION_ID)] = this } // else you're attaching a new entity to an existing entity that is not modifiable this.entityLinks[EntityLink(true, CHILDTHREE_CONNECTION_ID)] = value } changedProperty.add("childThree") } override fun getEntityData(): OoParentWithPidEntityData = result ?: super.getEntityData() as OoParentWithPidEntityData override fun getEntityClass(): Class<OoParentWithPidEntity> = OoParentWithPidEntity::class.java } } class OoParentWithPidEntityData : WorkspaceEntityData.WithCalculablePersistentId<OoParentWithPidEntity>() { lateinit var parentProperty: String fun isParentPropertyInitialized(): Boolean = ::parentProperty.isInitialized override fun wrapAsModifiable(diff: MutableEntityStorage): ModifiableWorkspaceEntity<OoParentWithPidEntity> { val modifiable = OoParentWithPidEntityImpl.Builder(null) modifiable.allowModifications { modifiable.diff = diff modifiable.snapshot = diff modifiable.id = createEntityId() modifiable.entitySource = this.entitySource } modifiable.changedProperty.clear() return modifiable } override fun createEntity(snapshot: EntityStorage): OoParentWithPidEntity { val entity = OoParentWithPidEntityImpl() entity._parentProperty = parentProperty entity.entitySource = entitySource entity.snapshot = snapshot entity.id = createEntityId() return entity } override fun persistentId(): PersistentEntityId<*> { return OoParentEntityId(parentProperty) } override fun getEntityInterface(): Class<out WorkspaceEntity> { return OoParentWithPidEntity::class.java } override fun serialize(ser: EntityInformation.Serializer) { } override fun deserialize(de: EntityInformation.Deserializer) { } override fun equals(other: Any?): Boolean { if (other == null) return false if (this::class != other::class) return false other as OoParentWithPidEntityData if (this.parentProperty != other.parentProperty) return false if (this.entitySource != other.entitySource) return false return true } override fun equalsIgnoringEntitySource(other: Any?): Boolean { if (other == null) return false if (this::class != other::class) return false other as OoParentWithPidEntityData if (this.parentProperty != other.parentProperty) return false return true } override fun hashCode(): Int { var result = entitySource.hashCode() result = 31 * result + parentProperty.hashCode() return result } }
apache-2.0
6180a9abc3a339a27e5b5df11c954c3e
42.609756
204
0.629626
6.019641
false
false
false
false
Maccimo/intellij-community
plugins/kotlin/completion/src/org/jetbrains/kotlin/idea/completion/VariableOrParameterNameWithTypeCompletion.kt
3
13288
// 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.completion import com.intellij.codeInsight.completion.* import com.intellij.codeInsight.completion.impl.CamelHumpMatcher import com.intellij.codeInsight.lookup.* import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.util.Key import com.intellij.psi.PsiClass import com.intellij.psi.PsiElement import com.intellij.psi.codeStyle.NameUtil import org.jetbrains.kotlin.descriptors.ClassifierDescriptor import org.jetbrains.kotlin.descriptors.DeclarationDescriptor import org.jetbrains.kotlin.idea.base.fe10.codeInsight.newDeclaration.Fe10KotlinNameSuggester import org.jetbrains.kotlin.idea.completion.handlers.isCharAt import org.jetbrains.kotlin.idea.completion.handlers.skipSpaces import org.jetbrains.kotlin.idea.core.KotlinIndicesHelper import org.jetbrains.kotlin.idea.core.moveCaret import org.jetbrains.kotlin.idea.formatter.kotlinCustomSettings import org.jetbrains.kotlin.idea.resolve.ResolutionFacade import org.jetbrains.kotlin.idea.util.IdeDescriptorRenderers import org.jetbrains.kotlin.idea.util.getResolutionScope import org.jetbrains.kotlin.psi.KtDeclaration import org.jetbrains.kotlin.psi.KtExpression import org.jetbrains.kotlin.psi.KtParameter import org.jetbrains.kotlin.psi.psiUtil.forEachDescendantOfType import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.scopes.DescriptorKindFilter import org.jetbrains.kotlin.resolve.scopes.utils.collectDescriptorsFiltered import org.jetbrains.kotlin.types.KotlinType import org.jetbrains.kotlin.types.isError import java.util.* class VariableOrParameterNameWithTypeCompletion( private val collector: LookupElementsCollector, private val lookupElementFactory: BasicLookupElementFactory, private val prefixMatcher: PrefixMatcher, private val resolutionFacade: ResolutionFacade, private val withType: Boolean ) { private val userPrefixes: List<String> private val classNamePrefixMatchers: List<PrefixMatcher> init { val prefix = prefixMatcher.prefix val prefixWords = NameUtil.splitNameIntoWords(prefix) // prefixes to use to generate parameter names from class names val nameSuggestionPrefixes = if (prefix.isEmpty() || prefix[0].isUpperCase()) emptyList() else prefixWords.indices.map { index -> if (index == 0) prefix else prefixWords.drop(index).joinToString("") } userPrefixes = nameSuggestionPrefixes.indices.map { prefixWords.take(it).joinToString("") } classNamePrefixMatchers = nameSuggestionPrefixes.map { CamelHumpMatcher(it.capitalize(Locale.US), false) } } private val suggestionsByTypesAdded = HashSet<Type>() private val lookupNamesAdded = HashSet<String>() fun addFromImportedClasses(position: PsiElement, bindingContext: BindingContext, visibilityFilter: (DeclarationDescriptor) -> Boolean) { for ((classNameMatcher, userPrefix) in classNamePrefixMatchers.zip(userPrefixes)) { val resolutionScope = position.getResolutionScope(bindingContext, resolutionFacade) val classifiers = resolutionScope.collectDescriptorsFiltered(DescriptorKindFilter.NON_SINGLETON_CLASSIFIERS, classNameMatcher.asNameFilter()) for (classifier in classifiers) { if (visibilityFilter(classifier)) { addSuggestionsForClassifier(classifier, userPrefix, notImported = false) } } collector.flushToResultSet() } } fun addFromAllClasses(parameters: CompletionParameters, indicesHelper: KotlinIndicesHelper) { for ((classNameMatcher, userPrefix) in classNamePrefixMatchers.zip(userPrefixes)) { AllClassesCompletion( parameters, indicesHelper, classNameMatcher, resolutionFacade, { !it.isSingleton }, includeTypeAliases = true, includeJavaClassesNotToBeUsed = false ).collect( { addSuggestionsForClassifier(it, userPrefix, notImported = true) }, { addSuggestionsForJavaClass(it, userPrefix, notImported = true) } ) collector.flushToResultSet() } } fun addFromParametersInFile( position: PsiElement, resolutionFacade: ResolutionFacade, visibilityFilter: (DeclarationDescriptor) -> Boolean ) { val lookupElementToCount = LinkedHashMap<LookupElement, Pair<Int, String>>() position.containingFile.forEachDescendantOfType<KtParameter>( canGoInside = { it !is KtExpression || it is KtDeclaration } // we analyze parameters inside bodies to not resolve too much ) { parameter -> ProgressManager.checkCanceled() val name = parameter.name if (name != null && prefixMatcher.isStartMatch(name)) { val descriptor = resolutionFacade.analyze(parameter)[BindingContext.VALUE_PARAMETER, parameter] if (descriptor != null) { val parameterType = descriptor.type if (parameterType.isVisible(visibilityFilter)) { val lookupElement = MyLookupElement.create(name, ArbitraryType(parameterType), withType, lookupElementFactory)!! val (count, s) = lookupElementToCount[lookupElement] ?: Pair(0, name) lookupElementToCount[lookupElement] = Pair(count + 1, s) } } } } for ((lookupElement, countAndName) in lookupElementToCount) { val (count, name) = countAndName lookupElement.putUserData(PRIORITY_KEY, -count) if (withType || !lookupNamesAdded.contains(name)) collector.addElement(lookupElement) lookupNamesAdded.add(name) } } private fun addSuggestionsForClassifier(classifier: DeclarationDescriptor, userPrefix: String, notImported: Boolean) { addSuggestions(classifier.name.asString(), userPrefix, DescriptorType(classifier as ClassifierDescriptor), notImported) } private fun addSuggestionsForJavaClass(psiClass: PsiClass, userPrefix: String, notImported: Boolean) { addSuggestions(psiClass.name!!, userPrefix, JavaClassType(psiClass), notImported) } private fun addSuggestions(className: String, userPrefix: String, type: Type, notImported: Boolean) { ProgressManager.checkCanceled() if (suggestionsByTypesAdded.contains(type)) return // don't add suggestions for the same with longer user prefix val nameSuggestions = Fe10KotlinNameSuggester.getCamelNames(className, { true }, userPrefix.isEmpty()) for (name in nameSuggestions) { val parameterName = userPrefix + name if (prefixMatcher.isStartMatch(parameterName)) { val lookupElement = MyLookupElement.create(parameterName, type, withType, lookupElementFactory) if (lookupElement != null) { lookupElement.putUserData(PRIORITY_KEY, userPrefix.length) // suggestions with longer user prefix get lower priority if (withType || !lookupNamesAdded.contains(parameterName)) collector.addElement(lookupElement, notImported) suggestionsByTypesAdded.add(type) lookupNamesAdded.add(parameterName) } } } } private fun KotlinType.isVisible(visibilityFilter: (DeclarationDescriptor) -> Boolean): Boolean { if (isError) return false val classifier = constructor.declarationDescriptor ?: return false return visibilityFilter(classifier) && arguments.all { it.isStarProjection || it.type.isVisible(visibilityFilter) } } private abstract class Type(private val idString: String) { abstract fun createTypeLookupElement(lookupElementFactory: BasicLookupElementFactory): LookupElement? override fun equals(other: Any?) = other is Type && other.idString == idString override fun hashCode() = idString.hashCode() } private class DescriptorType(private val classifier: ClassifierDescriptor) : Type(IdeDescriptorRenderers.SOURCE_CODE.renderClassifierName(classifier)) { override fun createTypeLookupElement(lookupElementFactory: BasicLookupElementFactory) = lookupElementFactory.createLookupElement(classifier, qualifyNestedClasses = true) } private class JavaClassType(private val psiClass: PsiClass) : Type(psiClass.qualifiedName!!) { override fun createTypeLookupElement(lookupElementFactory: BasicLookupElementFactory) = lookupElementFactory.createLookupElementForJavaClass(psiClass, qualifyNestedClasses = true) } private class ArbitraryType(private val type: KotlinType) : Type(IdeDescriptorRenderers.SOURCE_CODE.renderType(type)) { override fun createTypeLookupElement(lookupElementFactory: BasicLookupElementFactory) = lookupElementFactory.createLookupElementForType(type) } private class MyLookupElement private constructor( private val parameterName: String, private val type: Type, typeLookupElement: LookupElement, private val shouldInsertType: Boolean ) : LookupElementDecorator<LookupElement>(typeLookupElement) { companion object { fun create(parameterName: String, type: Type, shouldInsertType: Boolean, factory: BasicLookupElementFactory): LookupElement? { val typeLookupElement = type.createTypeLookupElement(factory) ?: return null val lookupElement = MyLookupElement(parameterName, type, typeLookupElement, shouldInsertType) if (!shouldInsertType) { lookupElement.putUserData(KotlinCompletionCharFilter.SUPPRESS_ITEM_SELECTION_BY_CHARS_ON_TYPING, Unit) } lookupElement.putUserData(KotlinCompletionCharFilter.HIDE_LOOKUP_ON_COLON, Unit) return lookupElement.suppressAutoInsertion() } } private val lookupString = parameterName + if (shouldInsertType) ": " + delegate.lookupString else "" override fun getLookupString() = lookupString override fun getAllLookupStrings() = setOf(lookupString) override fun renderElement(presentation: LookupElementPresentation) { super.renderElement(presentation) if (shouldInsertType) { presentation.itemText = parameterName + ": " + presentation.itemText } else { presentation.prependTailText(": " + presentation.itemText, true) presentation.itemText = parameterName } } override fun getDelegateInsertHandler(): InsertHandler<LookupElement> = InsertHandler { context, element -> if (context.completionChar == Lookup.REPLACE_SELECT_CHAR) { val replacementOffset = context.offsetMap.tryGetOffset(REPLACEMENT_OFFSET) if (replacementOffset != null) { val tailOffset = context.tailOffset context.document.deleteString(tailOffset, replacementOffset) val chars = context.document.charsSequence var offset = chars.skipSpaces(tailOffset) if (chars.isCharAt(offset, ',')) { offset++ offset = chars.skipSpaces(offset) context.editor.moveCaret(offset) } } } val settings = context.file.kotlinCustomSettings val spaceBefore = if (settings.SPACE_BEFORE_TYPE_COLON) " " else "" val spaceAfter = if (settings.SPACE_AFTER_TYPE_COLON) " " else "" val startOffset = context.startOffset if (shouldInsertType) { val text = "$parameterName$spaceBefore:$spaceAfter" context.document.insertString(startOffset, text) // update start offset so that it does not include the text we inserted context.offsetMap.addOffset(CompletionInitializationContext.START_OFFSET, startOffset + text.length) element.handleInsert(context) } else { context.document.replaceString(startOffset, context.tailOffset, parameterName) context.commitDocument() } } override fun equals(other: Any?) = other is MyLookupElement && parameterName == other.parameterName && type == other.type && shouldInsertType == other.shouldInsertType override fun hashCode() = parameterName.hashCode() } companion object { private val PRIORITY_KEY = Key<Int>("ParameterNameAndTypeCompletion.PRIORITY_KEY") val REPLACEMENT_OFFSET = OffsetKey.create("ParameterNameAndTypeCompletion.REPLACEMENT_OFFSET") } object Weigher : LookupElementWeigher("kotlin.parameterNameAndTypePriority") { override fun weigh(element: LookupElement, context: WeighingContext): Int = element.getUserData(PRIORITY_KEY) ?: 0 } }
apache-2.0
51752fe286096f643e203e92fb856fc7
48.76779
158
0.693257
5.436989
false
false
false
false
fcostaa/kotlin-rxjava-android
library/cache/src/main/kotlin/com/github/felipehjcosta/marvelapp/cache/data/CharacterEntity.kt
1
388
package com.github.felipehjcosta.marvelapp.cache.data import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.PrimaryKey @Entity(tableName = "character") data class CharacterEntity( @PrimaryKey() var id: Long = 0L, var name: String = "", var description: String = "", @ColumnInfo(name = "resource_uri") var resourceURI: String = "" )
mit
2888b5103d41eaefee267c18950779db
20.555556
53
0.706186
3.959184
false
false
false
false
AcornUI/Acorn
acornui-core/src/main/kotlin/com/acornui/Application.kt
1
2124
/* * Copyright 2020 Poly Forest, 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. */ @file:Suppress("MemberVisibilityCanBePrivate", "unused", "CssUnusedSymbol") package com.acornui import com.acornui.component.Stage import com.acornui.component.stage import com.acornui.di.* import com.acornui.dom.element import kotlinx.browser.document import kotlinx.dom.clear import org.w3c.dom.HTMLElement import org.w3c.dom.ParentNode /** * Creates an Acorn application. * * @param rootId The root element id whose elements will be replaced with the new application's stage. */ fun app( rootId: String, appConfig: AppConfig = AppConfig(), dependencies: DependencyMap = emptyDependencies, init: Stage.() -> Unit ) { val rootElement = element<HTMLElement>(rootId) rootElement.clear() app(appConfig, rootElement, dependencies, init) } /** * Creates an Acorn application, appending the new application's stage to the given [parentNode]. * * @param appConfig * @param parentNode The parent node on which to append the stage. May be null. * @param init The initialization block with the [Stage] as the receiver. */ fun app( appConfig: AppConfig = AppConfig(), parentNode: ParentNode? = document.body, dependencies: DependencyMap = emptyDependencies, init: Stage.() -> Unit ) { appContext(appConfig, dependencies).apply { parentNode?.append(stage.dom) stage.init() } } private fun appContext(appConfig: AppConfig, dependencies: DependencyMap) : Context = ContextImpl(owner = mainContext, dependencies = dependencyMapOf(AppConfig to appConfig) + dependencies, marker = ContextMarker.APPLICATION)
apache-2.0
b7458bd5d737cb4bc5ad9f4eb6475700
31.692308
225
0.75565
3.970093
false
true
false
false
google/identity-credential
appholder/src/main/java/com/android/mdl/app/wallet/SelectDocumentFragment.kt
1
6992
package com.android.mdl.app.wallet import android.Manifest import android.content.pm.PackageManager import android.os.Bundle import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Toast import androidx.activity.OnBackPressedCallback import androidx.activity.result.contract.ActivityResultContracts import androidx.core.content.ContextCompat import androidx.fragment.app.Fragment import androidx.fragment.app.activityViewModels import androidx.navigation.fragment.findNavController import com.android.mdl.app.R import com.android.mdl.app.adapter.DocumentAdapter import com.android.mdl.app.databinding.FragmentSelectDocumentBinding import com.android.mdl.app.document.Document import com.android.mdl.app.document.DocumentManager import com.android.mdl.app.util.TransferStatus import com.android.mdl.app.viewmodel.ShareDocumentViewModel import com.google.android.material.tabs.TabLayoutMediator class SelectDocumentFragment : Fragment() { companion object { private const val LOG_TAG = "SelectDocumentFragment" } private var _binding: FragmentSelectDocumentBinding? = null private val binding get() = _binding!! private val viewModel: ShareDocumentViewModel by activityViewModels() private val timeInterval = 2000 // # milliseconds passed between two back presses private var mBackPressed: Long = 0 private val appPermissions: Array<String> = if (android.os.Build.VERSION.SDK_INT >= 31) { arrayOf( Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.BLUETOOTH_ADVERTISE, Manifest.permission.BLUETOOTH_SCAN, Manifest.permission.BLUETOOTH_CONNECT, ) } else { arrayOf( Manifest.permission.ACCESS_FINE_LOCATION, ) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) // Ask to press twice before leave the app requireActivity().onBackPressedDispatcher.addCallback( this, object : OnBackPressedCallback(true) { override fun handleOnBackPressed() { if (mBackPressed + timeInterval > System.currentTimeMillis()) { requireActivity().finish() return } else { Toast.makeText( requireContext(), R.string.toast_press_back_twice, Toast.LENGTH_SHORT ).show() } mBackPressed = System.currentTimeMillis() } }) } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { _binding = FragmentSelectDocumentBinding.inflate(inflater) val adapter = DocumentAdapter() binding.vpDocuments.adapter = adapter binding.fragment = this setupDocumentsPager(binding) val documentManager = DocumentManager.getInstance(requireContext()) setupScreen(binding, adapter, documentManager.getDocuments().toMutableList()) val permissionsNeeded = appPermissions.filter { permission -> ContextCompat.checkSelfPermission( requireContext(), permission ) != PackageManager.PERMISSION_GRANTED } if (permissionsNeeded.isNotEmpty()) { permissionsLauncher.launch( permissionsNeeded.toTypedArray() ) } return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { viewModel.getTransferStatus().observe(viewLifecycleOwner) { when (it) { TransferStatus.CONNECTED -> { openTransferScreen() } TransferStatus.ERROR -> { binding.tvNfcLabel.text = "Error on presentation!" } //Shall we update the top label of the screen for each state? else -> {} } } } override fun onDestroyView() { super.onDestroyView() _binding = null } private fun setupDocumentsPager(binding: FragmentSelectDocumentBinding) { TabLayoutMediator(binding.tlPageIndicator, binding.vpDocuments) { _, _ -> }.attach() binding.vpDocuments.offscreenPageLimit = 1 binding.vpDocuments.setPageTransformer(DocumentPageTransformer(requireContext())) val itemDecoration = DocumentPagerItemDecoration( requireContext(), R.dimen.viewpager_current_item_horizontal_margin ) binding.vpDocuments.addItemDecoration(itemDecoration) } private fun setupScreen( binding: FragmentSelectDocumentBinding, adapter: DocumentAdapter, documentsList: MutableList<Document> ) { if (documentsList.isEmpty()) { showEmptyView(binding) } else { adapter.submitList(documentsList) showDocumentsPager(binding) } } private fun openTransferScreen() { val destination = SelectDocumentFragmentDirections.toTransferDocument() findNavController().navigate(destination) } private fun showEmptyView(binding: FragmentSelectDocumentBinding) { binding.vpDocuments.visibility = View.GONE binding.cvEmptyView.visibility = View.VISIBLE binding.btShowQr.visibility = View.GONE binding.btAddDocument.setOnClickListener { openAddDocument() } } private fun showDocumentsPager(binding: FragmentSelectDocumentBinding) { binding.vpDocuments.visibility = View.VISIBLE binding.cvEmptyView.visibility = View.GONE binding.btShowQr.visibility = View.VISIBLE binding.btShowQr.setOnClickListener { displayQRCode() } } private fun displayQRCode() { val destination = SelectDocumentFragmentDirections.toShowQR() findNavController().navigate(destination) } private fun openAddDocument() { val destination = SelectDocumentFragmentDirections.toAddSelfSigned() findNavController().navigate(destination) } private val permissionsLauncher = registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { permissions -> permissions.entries.forEach { Log.d(LOG_TAG, "permissionsLauncher ${it.key} = ${it.value}") if (!it.value) { Toast.makeText( activity, "The ${it.key} permission is required for BLE", Toast.LENGTH_LONG ).show() return@registerForActivityResult } } } }
apache-2.0
610ea325a1e3e9877a67ed9dbe8b3b0d
35.421875
104
0.6373
5.496855
false
false
false
false
mdaniel/intellij-community
platform/execution-impl/src/com/intellij/execution/runToolbar/RunToolbarMainSlotActive.kt
1
5976
// 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.execution.runToolbar import com.intellij.execution.runToolbar.RunToolbarProcessStartedAction.Companion.PROP_ACTIVE_ENVIRONMENT import com.intellij.execution.runToolbar.components.MouseListenerHelper import com.intellij.execution.runToolbar.components.TrimmedMiddleLabel import com.intellij.icons.AllIcons import com.intellij.idea.ActionsBundle import com.intellij.openapi.actionSystem.ActionToolbar import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.Presentation import com.intellij.openapi.actionSystem.impl.segmentedActionBar.SegmentedCustomAction import com.intellij.openapi.actionSystem.impl.segmentedActionBar.SegmentedCustomPanel import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.util.Key import com.intellij.util.ui.JBDimension import com.intellij.util.ui.UIUtil import net.miginfocom.swing.MigLayout import java.awt.Color import java.awt.Dimension import java.awt.Font import java.beans.PropertyChangeEvent import javax.swing.Icon import javax.swing.JLabel import javax.swing.JPanel import javax.swing.UIManager internal class RunToolbarMainSlotActive : SegmentedCustomAction(), RTBarAction { companion object { private val LOG = Logger.getInstance(RunToolbarMainSlotActive::class.java) val ARROW_DATA = Key<Icon?>("ARROW_DATA") } override fun actionPerformed(e: AnActionEvent) { } override fun checkMainSlotVisibility(state: RunToolbarMainSlotState): Boolean { return state == RunToolbarMainSlotState.PROCESS } override fun update(e: AnActionEvent) { RunToolbarProcessStartedAction.updatePresentation(e) val presentation = e.presentation if (!RunToolbarProcess.isExperimentalUpdatingEnabled) { e.mainState()?.let { presentation.isEnabledAndVisible = presentation.isEnabledAndVisible && checkMainSlotVisibility(it) } } presentation.description = e.runToolbarData()?.let { RunToolbarData.prepareDescription(presentation.text, ActionsBundle.message("action.RunToolbarShowHidePopupAction.click.to.show.popup.text")) } presentation.putClientProperty(ARROW_DATA, e.arrowIcon()) traceLog(LOG, e) } override fun createCustomComponent(presentation: Presentation, place: String): SegmentedCustomPanel { return RunToolbarMainSlotActive(presentation) } private class RunToolbarMainSlotActive(presentation: Presentation) : SegmentedCustomPanel(presentation), PopupControllerComponent { private val arrow = JLabel() private val dragArea = RunWidgetResizePane() private val setting = object : TrimmedMiddleLabel() { override fun getFont(): Font { return UIUtil.getToolbarFont() } override fun getForeground(): Color { return UIUtil.getLabelForeground() } } private val process = object : JLabel() { override fun getFont(): Font { return UIUtil.getToolbarFont() } override fun getForeground(): Color { return UIUtil.getLabelInfoForeground() } } init { layout = MigLayout("ins 0 0 0 3, fill, ay center, gap 0") val pane = JPanel().apply { layout = MigLayout("ins 0, fill, novisualpadding, ay center, gap 0", "[pref!][min!]3[shp 1, push]3[]push") add(JPanel().apply { isOpaque = false add(arrow) val d = preferredSize d.width = FixWidthSegmentedActionToolbarComponent.ARROW_WIDTH preferredSize = d }) add(JPanel().apply { preferredSize = JBDimension(1, 12) minimumSize = JBDimension(1, 12) background = UIManager.getColor("Separator.separatorColor") }) add(setting, "wmin 10") add(process, "wmin 0") isOpaque = false } add(dragArea, "pos 0 0") add(pane, "growx") MouseListenerHelper.addListener(pane, { doClick() }, { doShiftClick() }, { doRightClick() }) } fun doRightClick() { RunToolbarRunConfigurationsAction.doRightClick(ActionToolbar.getDataContextFor(this)) } private fun doClick() { val list = mutableListOf<PopupControllerComponentListener>() list.addAll(listeners) list.forEach { it.actionPerformedHandler() } } private fun doShiftClick() { ActionToolbar.getDataContextFor(this).editConfiguration() } private val listeners = mutableListOf<PopupControllerComponentListener>() override fun addListener(listener: PopupControllerComponentListener) { listeners.add(listener) } override fun removeListener(listener: PopupControllerComponentListener) { listeners.remove(listener) } override fun updateIconImmediately(isOpened: Boolean) { arrow.icon = if (isOpened) AllIcons.Toolbar.Collapse else AllIcons.Toolbar.Expand } override fun presentationChanged(event: PropertyChangeEvent) { updateArrow() updateEnvironment() setting.icon = presentation.icon setting.text = presentation.text toolTipText = presentation.description } private fun updateEnvironment() { presentation.getClientProperty(PROP_ACTIVE_ENVIRONMENT)?.let { env -> env.getRunToolbarProcess()?.let { background = it.pillColor process.text = if (env.isProcessTerminating()) ActionsBundle.message("action.RunToolbarRemoveSlotAction.terminating") else it.name } } ?: kotlin.run { isOpaque = false } } private fun updateArrow() { arrow.icon = presentation.getClientProperty(ARROW_DATA) } override fun getPreferredSize(): Dimension { val d = super.getPreferredSize() d.width = FixWidthSegmentedActionToolbarComponent.CONFIG_WITH_ARROW_WIDTH return d } } }
apache-2.0
adce3017304addb0cc926cb14040d6f5
32.768362
140
0.709505
4.886345
false
false
false
false
ksmirenko/telegram-proger-bot
src/main/java/stackOverflow/StackOverflow.kt
1
6011
package stackOverflow import com.google.appengine.api.urlfetch.HTTPMethod import com.google.appengine.api.urlfetch.HTTPRequest import com.google.appengine.api.urlfetch.URLFetchServiceFactory import org.json.simple.JSONArray import org.json.simple.JSONObject import org.json.simple.parser.JSONParser import progerbot.HttpRequests import java.io.ByteArrayInputStream import java.io.IOException import java.net.URL import java.net.URLEncoder import java.util.* public object StackOverflow { public val clientID: String public val clientSecret: String public val key: String public val redirectURI: String //'State' url parameter is a chatID private val authUrlWithoutState: String //stores pairs chatID/accessToken private val authTokens = Hashtable<String, String>() private val CHARSET = "UTF-8" init { try { // loading authorization data from locally stored file val prop = Properties() val inputStream = progerbot.MainServlet::class.java. classLoader.getResourceAsStream("auth.properties") prop.load(inputStream) clientID = prop.getProperty("json.stackOverflowClientID") clientSecret = prop.getProperty("json.stackOverflowClientSecret") key = prop.getProperty("json.stackOverflowKey") redirectURI = prop.getProperty("json.stackOverflowRedirectURI") authUrlWithoutState = "https://stackexchange.com/oauth?client_id=$clientID&" + "redirect_uri=$redirectURI&scope=read_inbox" } catch (e: IOException) { progerbot.Logger.println("Cannot load auth.properties") clientID = "" clientSecret = "" key = "" redirectURI = "" authUrlWithoutState = "" } } //returns url user should follow to get authorized public fun getAuthUrl(chatId: String): String = "$authUrlWithoutState&state=$chatId" //try to authorize to StackOverflow by providing code gotten when user was redirected //from StackOverflow to our server public fun tryConfirmCode(chatId: String, code: String): Boolean { val url = "https://stackexchange.com/oauth/access_token" val stackOverflowPost = HTTPRequest(URL(url), HTTPMethod.POST) stackOverflowPost.payload = ("client_id=$clientID&client_secret=$clientSecret&" + "code=$code&redirect_uri=$redirectURI").toByteArray(CHARSET) val stackOverflowResponse = URLFetchServiceFactory.getURLFetchService().fetch(stackOverflowPost) val success = (stackOverflowResponse.responseCode == 200) if (success) { var postResponseProp = Properties() postResponseProp.load(ByteArrayInputStream(stackOverflowResponse.content)) authTokens.put(chatId, postResponseProp.getProperty("access_token")) } else { progerbot.Logger.println("[StackOverflowError] Could not confirm code for chat $chatId") } return success } //just removes user`s authorization token if it`s stored public fun logOut(chatId: String): Boolean { val containsKey = authTokens.containsKey(chatId) if (containsKey) authTokens.remove(chatId) return containsKey } //returns result of search on StackOverflow where parameter 'title' is a searching question public fun search(textToSearch: String): String { val url = "https://api.stackexchange.com/2.2/search/advanced?order=desc&sort=activity&" + "q=${URLEncoder.encode(textToSearch, CHARSET)}&site=stackoverflow.com&key=$key" val res = HttpRequests.simpleRequest(url, HTTPMethod.GET, "") if (res.responseCode != 200) return "Cannot perform search" val jsonObj = JSONParser().parse(res.content.toString(CHARSET)) as JSONObject var jsonArr = JSONParser().parse((jsonObj).get("items").toString()) as JSONArray if (jsonArr.isEmpty()) return "No matches" var searchRes = StringBuilder() for (i in 0..Math.min(jsonArr.size - 1, 5)) searchRes.append((jsonArr[i] as JSONObject).get("title").toString() + "\n" + (jsonArr[i] as JSONObject).get("link").toString() + "\n\n") return searchRes.toString() } public fun getUnreadInboxItems(chatId: String): String { if (!authTokens.containsKey(chatId)) return "Yor are not authorized!" val authToken = authTokens.get(chatId) val url = "https://api.stackexchange.com/2.2/inbox/unread?access_token=$authToken&key=$key&filter=withbody" val res = HttpRequests.simpleRequest(url, HTTPMethod.GET, "") if (res.responseCode != 200) return "Cannot get notifications" val jsonObj = JSONParser().parse(res.content.toString(CHARSET)) as JSONObject var jsonArr = JSONParser().parse((jsonObj).get("items").toString()) as JSONArray //contains pairs of inner item types and item types to be shown to user val itemTypes = mapOf<String, String>(Pair("comment", "comment"), Pair("new_answer", "answer"), Pair("comment", "comment"), Pair("meta_question", "meta question"), Pair("chat_message", "chat message"), Pair("careers_invitations", "careers invitation"), Pair("careers_message", "careers message"), Pair("post_notice", "post notice")) var searchRes = StringBuilder() jsonArr.forEach { val message = it as JSONObject if (message.get("is_unread").toString() == "true") searchRes.append("Unread ${itemTypes.get(message.get("item_type"))}:\n" + message.get("body").toString() + "\n" + message.get("link").toString() + "\n\n") } val unreadMessages = searchRes.toString() if (unreadMessages.isEmpty()) return "No unread notifications" return unreadMessages } }
apache-2.0
2788c1ed4e7430acefa76ac60ecf6da8
47.088
115
0.655132
4.452593
false
false
false
false
WhisperSystems/Signal-Android
app/src/main/java/org/thoughtcrime/securesms/util/MessageRecordUtil.kt
1
3506
@file:JvmName("MessageRecordUtil") package org.thoughtcrime.securesms.util import android.content.Context import org.thoughtcrime.securesms.R import org.thoughtcrime.securesms.database.model.MediaMmsMessageRecord import org.thoughtcrime.securesms.database.model.MessageRecord import org.thoughtcrime.securesms.database.model.MmsMessageRecord import org.thoughtcrime.securesms.stickers.StickerUrl const val MAX_BODY_DISPLAY_LENGTH = 1000 fun MessageRecord.isMediaMessage(): Boolean { return isMms && !isMmsNotification && (this as MediaMmsMessageRecord).containsMediaSlide() && slideDeck.stickerSlide == null } fun MessageRecord.hasSticker(): Boolean = isMms && (this as MmsMessageRecord).slideDeck.stickerSlide != null fun MessageRecord.hasSharedContact(): Boolean = isMms && (this as MmsMessageRecord).sharedContacts.isNotEmpty() fun MessageRecord.hasLocation(): Boolean = isMms && ((this as MmsMessageRecord).slideDeck.slides).any { slide -> slide.hasLocation() } fun MessageRecord.hasAudio(): Boolean = isMms && (this as MmsMessageRecord).slideDeck.audioSlide != null fun MessageRecord.isCaptionlessMms(context: Context): Boolean = getDisplayBody(context).isEmpty() && isMms && (this as MmsMessageRecord).slideDeck.textSlide == null fun MessageRecord.hasThumbnail(): Boolean = isMms && (this as MmsMessageRecord).slideDeck.thumbnailSlide != null fun MessageRecord.isBorderless(context: Context): Boolean { return isCaptionlessMms(context) && hasThumbnail() && (this as MmsMessageRecord).slideDeck.thumbnailSlide?.isBorderless == true } fun MessageRecord.hasNoBubble(context: Context): Boolean = hasSticker() || isBorderless(context) fun MessageRecord.hasOnlyThumbnail(context: Context): Boolean { return hasThumbnail() && !hasAudio() && !hasDocument() && !hasSharedContact() && !hasSticker() && !isBorderless(context) && !isViewOnceMessage() } fun MessageRecord.hasDocument(): Boolean = isMms && (this as MmsMessageRecord).slideDeck.documentSlide != null fun MessageRecord.isViewOnceMessage(): Boolean = isMms && (this as MmsMessageRecord).isViewOnce fun MessageRecord.hasExtraText(): Boolean { val hasTextSlide = isMms && (this as MmsMessageRecord).slideDeck.textSlide != null val hasOverflowText: Boolean = body.length > MAX_BODY_DISPLAY_LENGTH return hasTextSlide || hasOverflowText } fun MessageRecord.hasQuote(): Boolean = isMms && (this as MmsMessageRecord).quote != null fun MessageRecord.hasLinkPreview(): Boolean = isMms && (this as MmsMessageRecord).linkPreviews.isNotEmpty() fun MessageRecord.hasBigImageLinkPreview(context: Context): Boolean { if (!hasLinkPreview()) { return false } val linkPreview = (this as MmsMessageRecord).linkPreviews[0] if (linkPreview.thumbnail.isPresent && !Util.isEmpty(linkPreview.description)) { return true } val minWidth = context.resources.getDimensionPixelSize(R.dimen.media_bubble_min_width_solo) return linkPreview.thumbnail.isPresent && linkPreview.thumbnail.get().width >= minWidth && !StickerUrl.isValidShareLink(linkPreview.url) } fun MessageRecord.isTextOnly(context: Context): Boolean { return !isMms || ( !isViewOnceMessage() && !hasLinkPreview() && !hasQuote() && !hasExtraText() && !hasDocument() && !hasThumbnail() && !hasAudio() && !hasLocation() && !hasSharedContact() && !hasSticker() && !isCaptionlessMms(context) ) }
gpl-3.0
e113d8b1521401446eaf61e8e2831500
31.462963
138
0.733314
4.154028
false
false
false
false
GunoH/intellij-community
plugins/devkit/intellij.devkit.i18n/src/DevKitPropertiesQuotesValidationInspection.kt
7
3699
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.idea.devkit.i18n import com.intellij.codeInspection.ProblemsHolder import com.intellij.lang.properties.PropertiesInspectionBase import com.intellij.lang.properties.parsing.PropertiesTokenTypes import com.intellij.lang.properties.psi.Property import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiElement import com.intellij.psi.PsiElementVisitor import org.jetbrains.annotations.NonNls import org.jetbrains.idea.devkit.inspections.DevKitInspectionBase import java.text.ChoiceFormat class DevKitPropertiesQuotesValidationInspection : PropertiesInspectionBase() { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor { if (!DevKitInspectionBase.isAllowed(holder.file)) { return PsiElementVisitor.EMPTY_VISITOR } return object : PsiElementVisitor() { override fun visitElement(element: PsiElement) { if (element !is Property) return val value = element.value ?: return val quotedParam = checkQuotedParam(value) ?: return val paramString = "{$quotedParam}" val idx = value.indexOf(paramString) + element.getNode().findChildByType(PropertiesTokenTypes.VALUE_CHARACTERS)!!.startOffsetInParent holder.registerProblem(element, TextRange(idx, idx + paramString.length), DevKitI18nBundle.message("inspection.message.wrong.quotes.around.parameter.reference", paramString)) } } } fun checkQuotedParam(pattern: String): Int? { var raw = true var inQuote = false var i = 0 var paramSB : StringBuilder? = null var level = 0 while (i < pattern.length) { val ch = pattern[i] if (raw) { if (ch == '\'') { if (i + 1 < pattern.length && pattern[i + 1] == '\'') { i++ } else { if (!inQuote) { paramSB = StringBuilder() } else { val quotedStr = paramSB.toString() if (quotedStr.startsWith('{') && quotedStr.endsWith('}')) { try { return Integer.parseInt(quotedStr.trimStart { it == '{'}.trimEnd { it == '}'}) } catch (ignored: NumberFormatException) { } } paramSB = null } inQuote = !inQuote } } else if (ch == '{' && !inQuote) { raw = false } else if (inQuote) { paramSB!!.append(ch) } } else { paramSB?.append(ch) if (inQuote) { if (ch == '\'') { inQuote = false } } else when (ch) { '{' -> level++ ',' -> { @NonNls val prefix = "choice," if (pattern.substring(i + 1).trim().startsWith(prefix)) { i += prefix.length + 1 paramSB = StringBuilder() } } '}' -> { if (level -- == 0) { try { val choiceFormat = ChoiceFormat(paramSB.toString().trimEnd { it == '}' }) for (format in choiceFormat.formats) { return checkQuotedParam(format as String) ?: continue } } catch (ignore: IllegalArgumentException) { //illegal choice format, do nothing for now } paramSB = null raw = true } } '\'' -> inQuote = true } } ++i } return null } }
apache-2.0
c2bf3f40a89ee8b770b3594535e87c39
32.636364
142
0.554204
4.712102
false
false
false
false
GunoH/intellij-community
plugins/kotlin/j2k/post-processing/src/org/jetbrains/kotlin/idea/j2k/post/processing/J2kPostProcessor.kt
2
14090
// 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.j2k.post.processing import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.progress.ProcessCanceledException import com.intellij.openapi.progress.ProgressManager import com.intellij.psi.impl.source.PostprocessReformattingAspect import org.jetbrains.kotlin.diagnostics.Errors import org.jetbrains.kotlin.idea.caches.resolve.resolveImportReference import org.jetbrains.kotlin.idea.codeInsight.intentions.shared.RemoveUnnecessaryParenthesesIntention import org.jetbrains.kotlin.idea.codeinsight.utils.NegatedBinaryExpressionSimplificationUtils.canBeSimplifiedWithoutChangingSemantics import org.jetbrains.kotlin.idea.codeinsight.utils.commitAndUnblockDocument import org.jetbrains.kotlin.idea.codeinsights.impl.base.KotlinInspectionFacade import org.jetbrains.kotlin.idea.inspections.* import org.jetbrains.kotlin.idea.inspections.branchedTransformations.IfThenToElvisInspection import org.jetbrains.kotlin.idea.inspections.branchedTransformations.IfThenToSafeAccessInspection import org.jetbrains.kotlin.idea.inspections.conventionNameCalls.ReplaceGetOrSetInspection import org.jetbrains.kotlin.idea.intentions.* import org.jetbrains.kotlin.idea.intentions.branchedTransformations.intentions.FoldIfToReturnAsymmetricallyIntention import org.jetbrains.kotlin.idea.intentions.branchedTransformations.intentions.FoldIfToReturnIntention import org.jetbrains.kotlin.idea.intentions.branchedTransformations.isTrivialStatementBody import org.jetbrains.kotlin.idea.j2k.post.processing.processings.* import org.jetbrains.kotlin.idea.quickfix.* import org.jetbrains.kotlin.idea.util.ImportInsertHelper import org.jetbrains.kotlin.j2k.ConverterContext import org.jetbrains.kotlin.j2k.JKPostProcessingTarget import org.jetbrains.kotlin.j2k.PostProcessor import org.jetbrains.kotlin.j2k.files import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.lexer.KtTokens.CONST_KEYWORD import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.nj2k.NewJ2kConverterContext import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.parents class NewJ2kPostProcessor : PostProcessor { companion object { private val LOG = Logger.getInstance("@org.jetbrains.kotlin.idea.j2k.post.processings.NewJ2kPostProcessor") } override fun insertImport(file: KtFile, fqName: FqName) { runUndoTransparentActionInEdt(inWriteAction = true) { val descriptors = file.resolveImportReference(fqName) descriptors.firstOrNull()?.let { ImportInsertHelper.getInstance(file.project).importDescriptor(file, it) } } } override val phasesCount = processings.size override fun doAdditionalProcessing( target: JKPostProcessingTarget, converterContext: ConverterContext?, onPhaseChanged: ((Int, String) -> Unit)? ) { if (converterContext !is NewJ2kConverterContext) error("Invalid converter context for new J2K") for ((i, group) in processings.withIndex()) { ProgressManager.checkCanceled() onPhaseChanged?.invoke(i, group.description) for (processing in group.processings) { ProgressManager.checkCanceled() try { processing.runProcessingConsideringOptions(target, converterContext) target.files().forEach(::commitFile) } catch (e: ProcessCanceledException) { throw e } catch (t: Throwable) { target.files().forEach(::commitFile) LOG.error(t) } } } } private fun GeneralPostProcessing.runProcessingConsideringOptions( target: JKPostProcessingTarget, converterContext: NewJ2kConverterContext ) { if (options.disablePostprocessingFormatting) { PostprocessReformattingAspect.getInstance(converterContext.project).disablePostprocessFormattingInside { runProcessing(target, converterContext) } } else { runProcessing(target, converterContext) } } private fun commitFile(file: KtFile) { runUndoTransparentActionInEdt(inWriteAction = true) { file.commitAndUnblockDocument() } } } private val errorsFixingDiagnosticBasedPostProcessingGroup = DiagnosticBasedPostProcessingGroup( diagnosticBasedProcessing(Errors.REDUNDANT_OPEN_IN_INTERFACE) { element: KtModifierListOwner, _ -> element.removeModifier(KtTokens.OPEN_KEYWORD) }, diagnosticBasedProcessing(Errors.PLATFORM_CLASS_MAPPED_TO_KOTLIN) { element: KtDotQualifiedExpression, _ -> val parent = element.parent as? KtImportDirective ?: return@diagnosticBasedProcessing parent.delete() }, diagnosticBasedProcessing( UnsafeCallExclExclFixFactory, Errors.UNSAFE_CALL, Errors.UNSAFE_INFIX_CALL, Errors.UNSAFE_OPERATOR_CALL ), diagnosticBasedProcessing( MissingIteratorExclExclFixFactory, Errors.ITERATOR_ON_NULLABLE ), diagnosticBasedProcessing( SmartCastImpossibleExclExclFixFactory, Errors.SMARTCAST_IMPOSSIBLE ), diagnosticBasedProcessing( ReplacePrimitiveCastWithNumberConversionFix, Errors.CAST_NEVER_SUCCEEDS ), diagnosticBasedProcessing( ChangeCallableReturnTypeFix.ReturnTypeMismatchOnOverrideFactory, Errors.RETURN_TYPE_MISMATCH_ON_OVERRIDE ), diagnosticBasedProcessing( RemoveModifierFixBase.createRemoveProjectionFactory(true), Errors.REDUNDANT_PROJECTION ), diagnosticBasedProcessing( AddModifierFixFE10.createFactory(KtTokens.OVERRIDE_KEYWORD), Errors.VIRTUAL_MEMBER_HIDDEN ), diagnosticBasedProcessing( RemoveModifierFixBase.createRemoveModifierFromListOwnerPsiBasedFactory(KtTokens.OPEN_KEYWORD), Errors.NON_FINAL_MEMBER_IN_FINAL_CLASS, Errors.NON_FINAL_MEMBER_IN_OBJECT ), diagnosticBasedProcessing( MakeVisibleFactory, Errors.INVISIBLE_MEMBER ), diagnosticBasedProcessing( RemoveModifierFixBase.removeNonRedundantModifier, Errors.WRONG_MODIFIER_TARGET ), diagnosticBasedProcessing( ChangeVisibilityOnExposureFactory, Errors.EXPOSED_FUNCTION_RETURN_TYPE, Errors.EXPOSED_PARAMETER_TYPE, Errors.EXPOSED_PROPERTY_TYPE, Errors.EXPOSED_PROPERTY_TYPE_IN_CONSTRUCTOR.errorFactory, Errors.EXPOSED_PROPERTY_TYPE_IN_CONSTRUCTOR.warningFactory, Errors.EXPOSED_RECEIVER_TYPE, Errors.EXPOSED_SUPER_CLASS, Errors.EXPOSED_SUPER_INTERFACE ), fixValToVarDiagnosticBasedProcessing, fixTypeMismatchDiagnosticBasedProcessing ) private val addOrRemoveModifiersProcessingGroup = InspectionLikeProcessingGroup( runSingleTime = true, processings = listOf( RemoveRedundantVisibilityModifierProcessing(), RemoveRedundantModalityModifierProcessing(), inspectionBasedProcessing(AddOperatorModifierInspection(), writeActionNeeded = false), ) ) private val removeRedundantElementsProcessingGroup = InspectionLikeProcessingGroup( runSingleTime = true, processings = listOf( RemoveExplicitTypeArgumentsProcessing(), RemoveJavaStreamsCollectCallTypeArgumentsProcessing(), ExplicitThisInspectionBasedProcessing(), RemoveOpenModifierOnTopLevelDeclarationsProcessing(), inspectionBasedProcessing(KotlinInspectionFacade.instance.removeEmptyClassBody) ) ) private val inspectionLikePostProcessingGroup = InspectionLikeProcessingGroup( RemoveRedundantConstructorKeywordProcessing(), RemoveExplicitOpenInInterfaceProcessing(), RemoveRedundantOverrideVisibilityProcessing(), MoveLambdaOutsideParenthesesProcessing(), intentionBasedProcessing(ConvertToStringTemplateIntention(), writeActionNeeded = false) { ConvertToStringTemplateIntention.shouldSuggestToConvert(it) }, intentionBasedProcessing(UsePropertyAccessSyntaxIntention(), writeActionNeeded = false), UninitializedVariableReferenceFromInitializerToThisReferenceProcessing(), UnresolvedVariableReferenceFromInitializerToThisReferenceProcessing(), RemoveRedundantSamAdaptersProcessing(), RemoveRedundantCastToNullableProcessing(), inspectionBasedProcessing(ReplacePutWithAssignmentInspection()), ReplaceGetterBodyWithSingleReturnStatementWithExpressionBody(), inspectionBasedProcessing(UnnecessaryVariableInspection(), writeActionNeeded = false), RedundantExplicitTypeInspectionBasedProcessing(), JavaObjectEqualsToEqOperatorProcessing(), RemoveExplicitPropertyTypeProcessing(), RemoveRedundantNullabilityProcessing(), CanBeValInspectionBasedProcessing(), inspectionBasedProcessing(FoldInitializerAndIfToElvisInspection(), writeActionNeeded = false), inspectionBasedProcessing(JavaMapForEachInspection()), intentionBasedProcessing(FoldIfToReturnIntention()) { it.then.isTrivialStatementBody() && it.`else`.isTrivialStatementBody() }, intentionBasedProcessing(FoldIfToReturnAsymmetricallyIntention()) { it.then.isTrivialStatementBody() && (KtPsiUtil.skipTrailingWhitespacesAndComments( it ) as KtReturnExpression).returnedExpression.isTrivialStatementBody() }, inspectionBasedProcessing(IfThenToSafeAccessInspection(inlineWithPrompt = false), writeActionNeeded = false), inspectionBasedProcessing(IfThenToElvisInspection(highlightStatement = true, inlineWithPrompt = false), writeActionNeeded = false), inspectionBasedProcessing(KotlinInspectionFacade.instance.simplifyNegatedBinaryExpression) { it.canBeSimplifiedWithoutChangingSemantics() }, inspectionBasedProcessing(ReplaceGetOrSetInspection()), intentionBasedProcessing(ObjectLiteralToLambdaIntention(), writeActionNeeded = true), intentionBasedProcessing(RemoveUnnecessaryParenthesesIntention()), intentionBasedProcessing(DestructureIntention(), writeActionNeeded = false), inspectionBasedProcessing(SimplifyAssertNotNullInspection()), intentionBasedProcessing(RemoveRedundantCallsOfConversionMethodsIntention()), LiftReturnInspectionBasedProcessing(), LiftAssignmentInspectionBasedProcessing(), intentionBasedProcessing(RemoveEmptyPrimaryConstructorIntention()), MayBeConstantInspectionBasedProcessing(), RemoveForExpressionLoopParameterTypeProcessing(), intentionBasedProcessing(ReplaceMapGetOrDefaultIntention()), inspectionBasedProcessing(ReplaceGuardClauseWithFunctionCallInspection()), inspectionBasedProcessing(KotlinInspectionFacade.instance.sortModifiers), intentionBasedProcessing(ConvertToRawStringTemplateIntention(), additionalChecker = ::shouldConvertToRawString), intentionBasedProcessing(IndentRawStringIntention()) ) private val cleaningUpDiagnosticBasedPostProcessingGroup = DiagnosticBasedPostProcessingGroup( removeUselessCastDiagnosticBasedProcessing, removeUnnecessaryNotNullAssertionDiagnosticBasedProcessing, fixValToVarDiagnosticBasedProcessing ) private val processings: List<NamedPostProcessingGroup> = listOf( NamedPostProcessingGroup( KotlinNJ2KServicesBundle.message("processing.step.inferring.types"), listOf( InspectionLikeProcessingGroup( processings = listOf( VarToValProcessing(), CanBeValInspectionBasedProcessing() ), runSingleTime = true ), NullabilityInferenceProcessing(), MutabilityInferenceProcessing(), ClearUnknownLabelsProcessing() ) ), NamedPostProcessingGroup( KotlinNJ2KServicesBundle.message("processing.step.cleaning.up.code"), listOf( InspectionLikeProcessingGroup(VarToValProcessing()), ConvertGettersAndSettersToPropertyProcessing(), InspectionLikeProcessingGroup(MoveGetterAndSetterAnnotationsToPropertyProcessing()), InspectionLikeProcessingGroup( RemoveExplicitGetterInspectionBasedProcessing(), RemoveExplicitSetterInspectionBasedProcessing() ), MergePropertyWithConstructorParameterProcessing(), errorsFixingDiagnosticBasedPostProcessingGroup, addOrRemoveModifiersProcessingGroup, inspectionLikePostProcessingGroup, removeRedundantElementsProcessingGroup, cleaningUpDiagnosticBasedPostProcessingGroup ) ), NamedPostProcessingGroup( KotlinNJ2KServicesBundle.message("processing.step.optimizing.imports.and.formatting.code"), listOf( ShortenReferenceProcessing(), OptimizeImportsProcessing(), FormatCodeProcessing() ) ) ) private fun shouldConvertToRawString(element: KtBinaryExpression): Boolean { fun KtStringTemplateEntry.isNewline(): Boolean = this is KtEscapeStringTemplateEntry && unescapedValue == "\n" val middleNewlinesExist = ConvertToStringTemplateIntention.buildReplacement(element) .entries .dropLastWhile { it.isNewline() } .any { it.isNewline() } return middleNewlinesExist && element.parents.none { (it as? KtProperty)?.hasModifier(CONST_KEYWORD) == true } }
apache-2.0
c97bbce9ce38bcc6c0fe709b72bc785d
44.899023
139
0.728673
5.998297
false
false
false
false
GunoH/intellij-community
plugins/kotlin/base/fe10/highlighting/src/org/jetbrains/kotlin/idea/highlighter/CompilerWarningIntentionAction.kt
2
1613
// 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.highlighter import com.intellij.codeInsight.intention.AbstractEmptyIntentionAction import com.intellij.codeInsight.intention.LowPriorityAction import com.intellij.codeInspection.util.IntentionFamilyName import com.intellij.icons.AllIcons import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.openapi.util.Iconable import com.intellij.psi.PsiFile import com.intellij.ui.ExperimentalUI import org.jetbrains.kotlin.idea.base.fe10.highlighting.KotlinBaseFe10HighlightingBundle import javax.swing.Icon class CompilerWarningIntentionAction(private val name: @IntentionFamilyName String): AbstractEmptyIntentionAction(), LowPriorityAction, Iconable { override fun getText(): String = KotlinBaseFe10HighlightingBundle.message("kotlin.compiler.warning.0.options", name) override fun getFamilyName(): String = name override fun isAvailable(project: Project, editor: Editor?, file: PsiFile?): Boolean = true override fun equals(other: Any?): Boolean { if (this === other) return true if (other == null || javaClass != other.javaClass) return false val that = other as CompilerWarningIntentionAction return name == that.name } override fun hashCode(): Int = name.hashCode() override fun getIcon(@Iconable.IconFlags flags: Int): Icon? = if (ExperimentalUI.isNewUI()) null else AllIcons.Actions.RealIntentionBulb }
apache-2.0
db2fe089ff30415023e6efe91eb3fdcd
47.878788
158
0.785493
4.595442
false
false
false
false
AsamK/TextSecure
app/src/main/java/org/thoughtcrime/securesms/stories/landing/StoriesLandingFragment.kt
1
12661
package org.thoughtcrime.securesms.stories.landing import android.Manifest import android.content.Intent import android.graphics.Color import android.net.Uri import android.os.Bundle import android.transition.TransitionInflater import android.view.Menu import android.view.MenuInflater import android.view.MenuItem import android.view.View import android.widget.Toast import androidx.activity.OnBackPressedCallback import androidx.core.app.ActivityOptionsCompat import androidx.core.app.SharedElementCallback import androidx.core.view.ViewCompat import androidx.fragment.app.viewModels import androidx.recyclerview.widget.LinearLayoutManager import com.google.android.material.dialog.MaterialAlertDialogBuilder import com.google.android.material.floatingactionbutton.FloatingActionButton import com.google.android.material.snackbar.BaseTransientBottomBar import com.google.android.material.snackbar.Snackbar import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers import io.reactivex.rxjava3.core.Single import io.reactivex.rxjava3.kotlin.subscribeBy import org.thoughtcrime.securesms.R import org.thoughtcrime.securesms.components.settings.DSLConfiguration import org.thoughtcrime.securesms.components.settings.DSLSettingsAdapter import org.thoughtcrime.securesms.components.settings.DSLSettingsFragment import org.thoughtcrime.securesms.components.settings.DSLSettingsText import org.thoughtcrime.securesms.components.settings.configure import org.thoughtcrime.securesms.conversation.ConversationIntents import org.thoughtcrime.securesms.conversation.mutiselect.forward.MultiselectForwardFragment import org.thoughtcrime.securesms.conversation.mutiselect.forward.MultiselectForwardFragmentArgs import org.thoughtcrime.securesms.conversation.ui.error.SafetyNumberChangeDialog import org.thoughtcrime.securesms.database.model.MediaMmsMessageRecord import org.thoughtcrime.securesms.database.model.MmsMessageRecord import org.thoughtcrime.securesms.mediasend.v2.MediaSelectionActivity import org.thoughtcrime.securesms.permissions.Permissions import org.thoughtcrime.securesms.stories.StoryTextPostModel import org.thoughtcrime.securesms.stories.StoryViewerArgs import org.thoughtcrime.securesms.stories.dialogs.StoryContextMenu import org.thoughtcrime.securesms.stories.dialogs.StoryDialogs import org.thoughtcrime.securesms.stories.my.MyStoriesActivity import org.thoughtcrime.securesms.stories.settings.StorySettingsActivity import org.thoughtcrime.securesms.stories.tabs.ConversationListTab import org.thoughtcrime.securesms.stories.tabs.ConversationListTabsViewModel import org.thoughtcrime.securesms.stories.viewer.StoryViewerActivity import org.thoughtcrime.securesms.util.LifecycleDisposable import org.thoughtcrime.securesms.util.visible import java.util.concurrent.TimeUnit /** * The "landing page" for Stories. */ class StoriesLandingFragment : DSLSettingsFragment(layoutId = R.layout.stories_landing_fragment) { companion object { private const val LIST_SMOOTH_SCROLL_TO_TOP_THRESHOLD = 25 } private lateinit var emptyNotice: View private lateinit var cameraFab: FloatingActionButton private val lifecycleDisposable = LifecycleDisposable() private val viewModel: StoriesLandingViewModel by viewModels( factoryProducer = { StoriesLandingViewModel.Factory(StoriesLandingRepository(requireContext())) } ) private val tabsViewModel: ConversationListTabsViewModel by viewModels(ownerProducer = { requireActivity() }) private lateinit var adapter: DSLSettingsAdapter override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setHasOptionsMenu(true) } override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { menu.clear() inflater.inflate(R.menu.story_landing_menu, menu) } override fun onResume() { super.onResume() viewModel.isTransitioningToAnotherScreen = false } override fun bindAdapter(adapter: DSLSettingsAdapter) { this.adapter = adapter StoriesLandingItem.register(adapter) MyStoriesItem.register(adapter) ExpandHeader.register(adapter) lifecycleDisposable.bindTo(viewLifecycleOwner) emptyNotice = requireView().findViewById(R.id.empty_notice) cameraFab = requireView().findViewById(R.id.camera_fab) sharedElementEnterTransition = TransitionInflater.from(requireContext()).inflateTransition(R.transition.change_transform_fabs) setEnterSharedElementCallback(object : SharedElementCallback() { override fun onSharedElementStart(sharedElementNames: MutableList<String>?, sharedElements: MutableList<View>?, sharedElementSnapshots: MutableList<View>?) { if (sharedElementNames?.contains("camera_fab") == true) { cameraFab.setImageResource(R.drawable.ic_compose_24) lifecycleDisposable += Single.timer(200, TimeUnit.MILLISECONDS) .observeOn(AndroidSchedulers.mainThread()) .subscribeBy { cameraFab.setImageResource(R.drawable.ic_camera_outline_24) } } } }) cameraFab.setOnClickListener { Permissions.with(this) .request(Manifest.permission.CAMERA) .ifNecessary() .withRationaleDialog(getString(R.string.ConversationActivity_to_capture_photos_and_video_allow_signal_access_to_the_camera), R.drawable.ic_camera_24) .withPermanentDenialDialog(getString(R.string.ConversationActivity_signal_needs_the_camera_permission_to_take_photos_or_video)) .onAllGranted { startActivityIfAble(MediaSelectionActivity.camera(requireContext(), isStory = true)) } .onAnyDenied { Toast.makeText(requireContext(), R.string.ConversationActivity_signal_needs_camera_permissions_to_take_photos_or_video, Toast.LENGTH_LONG).show() } .execute() } viewModel.state.observe(viewLifecycleOwner) { if (it.loadingState == StoriesLandingState.LoadingState.LOADED) { adapter.submitList(getConfiguration(it).toMappingModelList()) emptyNotice.visible = it.hasNoStories } } requireActivity().onBackPressedDispatcher.addCallback( viewLifecycleOwner, object : OnBackPressedCallback(true) { override fun handleOnBackPressed() { tabsViewModel.onChatsSelected() } } ) lifecycleDisposable += tabsViewModel.tabClickEvents .filter { it == ConversationListTab.STORIES } .subscribeBy(onNext = { val layoutManager = recyclerView?.layoutManager as? LinearLayoutManager ?: return@subscribeBy if (layoutManager.findFirstVisibleItemPosition() <= LIST_SMOOTH_SCROLL_TO_TOP_THRESHOLD) { recyclerView?.smoothScrollToPosition(0) } else { recyclerView?.scrollToPosition(0) } }) } private fun getConfiguration(state: StoriesLandingState): DSLConfiguration { return configure { val (stories, hidden) = state.storiesLandingItems.map { createStoryLandingItem(it) }.partition { !it.data.isHidden } if (state.displayMyStoryItem) { customPref( MyStoriesItem.Model( onClick = { startActivityIfAble(Intent(requireContext(), MyStoriesActivity::class.java)) }, onClickThumbnail = { cameraFab.performClick() } ) ) } stories.forEach { item -> customPref(item) } if (hidden.isNotEmpty()) { customPref( ExpandHeader.Model( title = DSLSettingsText.from(R.string.StoriesLandingFragment__hidden_stories), isExpanded = state.isHiddenContentVisible, onClick = { viewModel.setHiddenContentVisible(it) } ) ) } if (state.isHiddenContentVisible) { hidden.forEach { item -> customPref(item) } } } } private fun createStoryLandingItem(data: StoriesLandingItemData): StoriesLandingItem.Model { return StoriesLandingItem.Model( data = data, onRowClick = { model, preview -> if (model.data.storyRecipient.isMyStory) { startActivityIfAble(Intent(requireContext(), MyStoriesActivity::class.java)) } else if (model.data.primaryStory.messageRecord.isOutgoing && model.data.primaryStory.messageRecord.isFailed) { if (model.data.primaryStory.messageRecord.isIdentityMismatchFailure) { SafetyNumberChangeDialog.show(requireContext(), childFragmentManager, model.data.primaryStory.messageRecord) } else { StoryDialogs.resendStory(requireContext()) { lifecycleDisposable += viewModel.resend(model.data.primaryStory.messageRecord).subscribe() } } } else { val options = ActivityOptionsCompat.makeSceneTransitionAnimation(requireActivity(), preview, ViewCompat.getTransitionName(preview) ?: "") val record = model.data.primaryStory.messageRecord as MmsMessageRecord val blur = record.slideDeck.thumbnailSlide?.placeholderBlur val (text: StoryTextPostModel?, image: Uri?) = if (record.storyType.isTextStory) { StoryTextPostModel.parseFrom(record) to null } else { null to record.slideDeck.thumbnailSlide?.uri } startActivityIfAble( StoryViewerActivity.createIntent( context = requireContext(), storyViewerArgs = StoryViewerArgs( recipientId = model.data.storyRecipient.id, storyId = -1L, isInHiddenStoryMode = model.data.isHidden, storyThumbTextModel = text, storyThumbUri = image, storyThumbBlur = blur, recipientIds = viewModel.getRecipientIds(model.data.isHidden) ) ), options.toBundle() ) } }, onForwardStory = { MultiselectForwardFragmentArgs.create(requireContext(), it.data.primaryStory.multiselectCollection.toSet()) { args -> MultiselectForwardFragment.showBottomSheet(childFragmentManager, args) } }, onGoToChat = { startActivityIfAble(ConversationIntents.createBuilder(requireContext(), it.data.storyRecipient.id, -1L).build()) }, onHideStory = { if (!it.data.isHidden) { handleHideStory(it) } else { lifecycleDisposable += viewModel.setHideStory(it.data.storyRecipient, !it.data.isHidden).subscribe() } }, onShareStory = { StoryContextMenu.share(this@StoriesLandingFragment, it.data.primaryStory.messageRecord as MediaMmsMessageRecord) }, onSave = { StoryContextMenu.save(requireContext(), it.data.primaryStory.messageRecord) }, onDeleteStory = { handleDeleteStory(it) } ) } private fun handleDeleteStory(model: StoriesLandingItem.Model) { lifecycleDisposable += StoryContextMenu.delete(requireContext(), setOf(model.data.primaryStory.messageRecord)).subscribe() } private fun handleHideStory(model: StoriesLandingItem.Model) { MaterialAlertDialogBuilder(requireContext(), R.style.Signal_ThemeOverlay_Dialog_Rounded) .setTitle(R.string.StoriesLandingFragment__hide_story) .setMessage(getString(R.string.StoriesLandingFragment__new_story_updates, model.data.storyRecipient.getShortDisplayName(requireContext()))) .setPositiveButton(R.string.StoriesLandingFragment__hide) { _, _ -> viewModel.setHideStory(model.data.storyRecipient, true).subscribe { Snackbar.make(cameraFab, R.string.StoriesLandingFragment__story_hidden, Snackbar.LENGTH_SHORT) .setTextColor(Color.WHITE) .setAnchorView(cameraFab) .setAnimationMode(BaseTransientBottomBar.ANIMATION_MODE_FADE) .show() } } .setNegativeButton(android.R.string.cancel) { _, _ -> } .show() } override fun onOptionsItemSelected(item: MenuItem): Boolean { return if (item.itemId == R.id.action_settings) { startActivityIfAble(StorySettingsActivity.getIntent(requireContext())) true } else { false } } override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) { Permissions.onRequestPermissionsResult(this, requestCode, permissions, grantResults) } private fun startActivityIfAble(intent: Intent, options: Bundle? = null) { if (viewModel.isTransitioningToAnotherScreen) { return } viewModel.isTransitioningToAnotherScreen = true startActivity(intent, options) } }
gpl-3.0
46a7a812b8f3c263661c7d83d4cabc73
39.450479
170
0.724982
4.875241
false
false
false
false
daviddenton/k2
src/main/kotlin/io/github/daviddenton/k2/formats/Argo.kt
1
1845
package io.github.daviddenton.k2.formats import argo.format.CompactJsonFormatter import argo.format.PrettyJsonFormatter import argo.jdom.JdomParser import argo.jdom.JsonNode import argo.jdom.JsonNodeFactories import argo.jdom.JsonNodeFactories.booleanNode import argo.jdom.JsonRootNode import java.math.BigDecimal import java.math.BigInteger import io.github.daviddenton.k2.formats.Json as AbsJson object Argo : JsonLibrary <JsonRootNode, JsonNode>(Json) { object Json : AbsJson<JsonRootNode, JsonNode> { private val pretty = PrettyJsonFormatter() private val compact = CompactJsonFormatter() override fun parse(s: String): JsonRootNode = JdomParser().parse(s) override fun pretty(node: JsonRootNode): String = pretty.format(node) override fun compact(node: JsonRootNode): String = compact.format(node) override fun obj(fields: Iterable<Pair<String, JsonNode>>): JsonRootNode = JsonNodeFactories.`object`(fields.map { field(it.first, it.second) }) override fun array(elements: Iterable<JsonNode>): JsonRootNode = JsonNodeFactories.array(elements) override fun string(value: String) = JsonNodeFactories.string(value) override fun number(value: Int) = JsonNodeFactories.number(value.toLong()) override fun number(value: Double) = JsonNodeFactories.number(BigDecimal(value)) override fun number(value: BigDecimal) = JsonNodeFactories.number(value) override fun number(value: Long) = JsonNodeFactories.number(value) override fun number(value: BigInteger) = JsonNodeFactories.number(value) override fun boolean(value: Boolean) = booleanNode(value) override fun nullNode() = JsonNodeFactories.nullNode() private fun field(name: String, value: JsonNode) = JsonNodeFactories.field(name, value) } }
apache-2.0
2f0da77b8b526cf318e49969bfb94cf0
35.9
152
0.742005
4.212329
false
false
false
false
dahlstrom-g/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/collections/AbstractCallChainChecker.kt
2
4859
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.inspections.collections import org.jetbrains.annotations.NonNls import org.jetbrains.kotlin.config.ApiVersion import org.jetbrains.kotlin.idea.base.projectStructure.languageVersionSettings import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.inspections.AbstractKotlinInspection import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.psi.KtCallExpression import org.jetbrains.kotlin.psi.KtExpression import org.jetbrains.kotlin.psi.KtQualifiedExpression import org.jetbrains.kotlin.psi.KtReturnExpression import org.jetbrains.kotlin.psi.psiUtil.anyDescendantOfType import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall import org.jetbrains.kotlin.resolve.calls.model.DefaultValueArgument import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall abstract class AbstractCallChainChecker : AbstractKotlinInspection() { protected fun findQualifiedConversion( expression: KtQualifiedExpression, conversionGroups: Map<ConversionId, List<Conversion>>, additionalCallCheck: (Conversion, ResolvedCall<*>, ResolvedCall<*>, BindingContext) -> Boolean ): Conversion? { val firstExpression = expression.receiverExpression val firstCallExpression = getCallExpression(firstExpression) ?: return null val firstCalleeExpression = firstCallExpression.calleeExpression ?: return null val secondCallExpression = expression.selectorExpression as? KtCallExpression ?: return null val secondCalleeExpression = secondCallExpression.calleeExpression ?: return null val apiVersion by lazy { expression.languageVersionSettings.apiVersion } val actualConversions = conversionGroups[ConversionId(firstCalleeExpression, secondCalleeExpression)]?.filter { it.replaceableApiVersion == null || apiVersion >= it.replaceableApiVersion }?.sortedByDescending { it.removeNotNullAssertion } ?: return null val context = expression.analyze() val firstResolvedCall = firstExpression.getResolvedCall(context) ?: return null val secondResolvedCall = expression.getResolvedCall(context) ?: return null val conversion = actualConversions.firstOrNull { firstResolvedCall.isCalling(FqName(it.firstFqName)) && additionalCallCheck(it, firstResolvedCall, secondResolvedCall, context) } ?: return null // Do not apply for lambdas with return inside val lambdaArgument = firstCallExpression.lambdaArguments.firstOrNull() if (lambdaArgument?.anyDescendantOfType<KtReturnExpression>() == true) return null if (!secondResolvedCall.isCalling(FqName(conversion.secondFqName))) return null if (secondResolvedCall.valueArguments.any { (parameter, resolvedArgument) -> parameter.type.isFunctionOfAnyKind() && resolvedArgument !is DefaultValueArgument } ) return null return conversion } protected fun List<Conversion>.group(): Map<ConversionId, List<Conversion>> = groupBy { conversion -> conversion.id } data class ConversionId(val firstFqName: String, val secondFqName: String) { constructor(first: KtExpression, second: KtExpression) : this(first.text, second.text) } data class Conversion( @NonNls val firstFqName: String, @NonNls val secondFqName: String, @NonNls val replacement: String, @NonNls val additionalArgument: String? = null, val addNotNullAssertion: Boolean = false, val enableSuspendFunctionCall: Boolean = true, val removeNotNullAssertion: Boolean = false, val replaceableApiVersion: ApiVersion? = null, ) { private fun String.convertToShort() = takeLastWhile { it != '.' } val id: ConversionId get() = ConversionId(firstName, secondName) val firstName = firstFqName.convertToShort() val secondName = secondFqName.convertToShort() fun withArgument(argument: String) = Conversion(firstFqName, secondFqName, replacement, argument) } companion object { fun KtQualifiedExpression.firstCalleeExpression(): KtExpression? { val firstExpression = receiverExpression val firstCallExpression = getCallExpression(firstExpression) ?: return null return firstCallExpression.calleeExpression } fun getCallExpression(firstExpression: KtExpression) = (firstExpression as? KtQualifiedExpression)?.selectorExpression as? KtCallExpression ?: firstExpression as? KtCallExpression } }
apache-2.0
20a7ed43b61c9f38ee7bf030551bdc9c
47.6
158
0.739247
5.515323
false
false
false
false
QuarkWorks/RealmTypeSafeQuery-Android
query/src/main/kotlin/com/quarkworks/android/realmtypesafequery/RealmQueryExtensions.kt
1
5460
@file:Suppress("unused") package com.quarkworks.android.realmtypesafequery import com.quarkworks.android.realmtypesafequery.fields.* import io.realm.* /* Null */ fun <T : RealmModel> RealmQuery<T>.isNull(field: RealmNullableField<T>) : RealmQuery<T> { field.isNull(this) return this } fun <T : RealmModel> RealmQuery<T>.isNotNull(field: RealmNullableField<T>) : RealmQuery<T> { field.isNotNull(this) return this } /* EqualTo */ fun <T : RealmModel, V> RealmQuery<T>.equalTo(field: RealmEquatableField<T, V>, value: V?) : RealmQuery<T> { field.equalTo(this, value) return this } fun <T : RealmModel, V> RealmQuery<T>.notEqualTo(field: RealmEquatableField<T, V>, value: V?) : RealmQuery<T> { field.notEqualTo(this, value) return this } fun <T : RealmModel, V> RealmQuery<T>.`in`(field: RealmInableField<T, V>, value: Array<V>) : RealmQuery<T> { field.`in`(this, value) return this } fun <T : RealmModel, V> RealmQuery<T>.`in`(field: RealmInableField<T, V>, value: List<V>) : RealmQuery<T> { field.`in`(this, value) return this } /* String */ fun <T : RealmModel> RealmQuery<T>.equalTo(field: RealmStringField<T>, value: String?, casing: Case) : RealmQuery<T> { field.equalTo(this, value, casing) return this } fun <T : RealmModel> RealmQuery<T>.notEqualTo(field: RealmStringField<T>, value: String?, casing: Case) : RealmQuery<T> { field.notEqualTo(this, value, casing) return this } fun <T : RealmModel> RealmQuery<T>.beginsWith(field: RealmStringField<T>, value: String?, casing: Case = Case.SENSITIVE) : RealmQuery<T> { field.beginsWith(this, value, casing) return this } fun <T : RealmModel> RealmQuery<T>.endsWith(field: RealmStringField<T>, value: String?, casing: Case = Case.SENSITIVE) : RealmQuery<T> { field.endsWith(this, value, casing) return this } fun <T : RealmModel> RealmQuery<T>.contains(field: RealmStringField<T>, value: String?, casing: Case = Case.SENSITIVE) : RealmQuery<T> { field.contains(this, value, casing) return this } fun <T : RealmModel> RealmQuery<T>.contains(field: RealmStringField<T>, value: String?, delimiter: String, casing: Case = Case.SENSITIVE) : RealmQuery<T> { field.contains(this, value, delimiter, casing) return this } fun <T : RealmModel> RealmQuery<T>.like(field: RealmStringField<T>, value: String?, casing: Case = Case.SENSITIVE) : RealmQuery<T> { field.like(this, value, casing) return this } /* Comparison */ fun <T : RealmModel, V> RealmQuery<T>.greaterThan(field: RealmComparableField<T, V>, value: V?) : RealmQuery<T> { field.greaterThan(this, value) return this } fun <T : RealmModel, V> RealmQuery<T>.greaterThanOrEqualTo(field: RealmComparableField<T, V>, value: V?) : RealmQuery<T> { field.greaterThanOrEqualTo(this, value) return this } fun <T : RealmModel, V> RealmQuery<T>.lessThan(field: RealmComparableField<T, V>, value: V?) : RealmQuery<T> { field.lessThan(this, value) return this } fun <T : RealmModel, V> RealmQuery<T>.lessThanOrEqualTo(field: RealmComparableField<T, V>, value: V?) : RealmQuery<T> { field.lessThanOrEqualTo(this, value) return this } fun <T : RealmModel, V> RealmQuery<T>.between(field: RealmComparableField<T, V>, start: V?, end: V?) : RealmQuery<T> { field.between(this, start, end) return this } /* Group */ fun <T : RealmModel> RealmQuery<T>.group(body: (RealmQuery<T>) -> Void) : RealmQuery<T> { beginGroup() body(this) endGroup() return this } /* Or */ fun <T : RealmModel> RealmQuery<T>.or(body: (RealmQuery<T>) -> Void) : RealmQuery<T> = or().group(body) /* Not */ fun <T : RealmModel> RealmQuery<T>.not(body: (RealmQuery<T>) -> Void) : RealmQuery<T> = not().group(body) /* Empty */ fun <T : RealmModel> RealmQuery<T>.isEmpty(field: RealmEmptyableField<T>) : RealmQuery<T> { field.isEmpty(this) return this } fun <T : RealmModel> RealmQuery<T>.isNotEmpty(field: RealmEmptyableField<T>) : RealmQuery<T> { field.isNotEmpty(this) return this } /* Distinct */ fun <T : RealmModel> RealmQuery<T>.distinct(field: RealmDistinctableField<T>) : RealmQuery<T> = field.distinct(this) fun <T : RealmModel> RealmQuery<T>.distinct(firstField: RealmDistinctableField<T>, vararg remainingFields: RealmDistinctableField<T>) : RealmQuery<T> = firstField.distinct(this, *remainingFields) /* Aggregate */ fun <T : RealmModel, V> RealmQuery<T>.sum(field: RealmAggregatableField<T, V>) : V = field.sum(this) fun <T : RealmModel> RealmQuery<T>.average(field: RealmAggregatableField<T, *>) : Double = field.average(this) /* Min Max */ fun <T : RealmModel, V> RealmQuery<T>.min(field: RealmMinMaxField<T, V>) : V? = field.min(this) fun <T : RealmModel, V> RealmQuery<T>.max(field: RealmMinMaxField<T, V>) : V? = field.max(this) /* Sorting */ fun <T : RealmModel> RealmQuery<T>.sort(field: RealmSortableField<T>, sortOrder: Sort = Sort.ASCENDING) : RealmQuery<T> = field.sort(this, sortOrder) fun <T : RealmModel> RealmQuery<T>.sort(field1: RealmSortableField<T>, sortOrder1: Sort, field2: RealmSortableField<T>, sortOrder2: Sort) : RealmQuery<T> = field1.sort(this, sortOrder1, field2, sortOrder2) fun <T : RealmModel> RealmQuery<T>.sort(fields: Array<RealmSortableField<T>>, sortOrders: Array<Sort>) : RealmQuery<T> = RealmSortableField.sort(this, fields, sortOrders);
mit
7f56a380b192d7271b04e8fba652c50d
27.736842
155
0.682601
3.261649
false
false
false
false
chrhsmt/Sishen
app/src/main/java/com/chrhsmt/sisheng/debug/AnalyzedRecordedData.kt
1
1111
package com.chrhsmt.sisheng.debug import android.content.Context import com.chrhsmt.sisheng.ReibunInfo import com.chrhsmt.sisheng.Settings import com.chrhsmt.sisheng.point.Point import java.io.File data class AnalyzedRecordedData(var file: File, var csvLine: String?) { companion object { private val TAG = "AnalyzedRecordedData" private var selected : AnalyzedRecordedData? = null fun getSelected(): AnalyzedRecordedData? { return selected } fun setSelected(instance: AnalyzedRecordedData) { selected = instance } } var id: Int? = null var point: Point? = null var sex: String? = null fun init(): AnalyzedRecordedData { val line = this.csvLine?.split(",") this.id = line?.get(1)?.trim()?.toInt() this.sex = line?.get(2)?.trim() this.point = Point(line?.get(3)?.trim()?.toInt()?: 0, 0.0, 0.0, 0, null) return this } override fun toString(): String { return String.format("%s - %s - %s", this.file.name, this.point?.score, this.point?.success()) } }
mit
57c15ba5820232a94df4970207a33848
28.263158
102
0.627363
3.884615
false
false
false
false
dahlstrom-g/intellij-community
plugins/kotlin/idea/tests/testData/intentions/branched/unfolding/assignmentToIf/nestedIfs.kt
9
450
// AFTER-WARNING: Parameter 'a' is never used fun <T> doSomething(a: T) {} fun test(n: Int): String { var res: String <caret>res = if (n == 1) { if (3 > 2) { doSomething("***") "one" } else { doSomething("***") "???" } } else if (n == 2) { doSomething("***") "two" } else { doSomething("***") "too many" } return res }
apache-2.0
0f14e4e082a2367e141b4abd52148d91
17.75
45
0.393333
3.87931
false
false
false
false
elpassion/el-space-android
el-space-app/src/main/java/pl/elpassion/elspace/hub/report/list/ReportListActivity.kt
1
7553
package pl.elpassion.elspace.hub.report.list import android.app.Activity import android.content.Context import android.content.Intent import android.os.Bundle import android.support.design.widget.Snackbar import android.support.design.widget.Snackbar.Callback.DISMISS_EVENT_ACTION import android.support.v7.app.AppCompatActivity import android.view.Menu import android.view.MenuItem import android.view.View import com.crashlytics.android.Crashlytics import com.elpassion.android.commons.recycler.adapters.basicAdapterWithConstructors import com.elpassion.android.commons.recycler.basic.ViewHolderBinder import com.jakewharton.rxbinding2.support.design.widget.dismisses import com.jakewharton.rxbinding2.support.v4.widget.refreshes import com.jakewharton.rxbinding2.view.clicks import io.reactivex.Observable import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.schedulers.Schedulers import io.reactivex.subjects.PublishSubject import kotlinx.android.synthetic.main.report_list_activity.* import pl.elpassion.elspace.R import pl.elpassion.elspace.common.SchedulersSupplier import pl.elpassion.elspace.common.extensions.* import pl.elpassion.elspace.common.hideLoader import pl.elpassion.elspace.common.showLoader import pl.elpassion.elspace.hub.report.PaidVacationHourlyReport import pl.elpassion.elspace.hub.report.RegularHourlyReport import pl.elpassion.elspace.hub.report.Report import pl.elpassion.elspace.hub.report.add.ReportAddActivity import pl.elpassion.elspace.hub.report.edit.ReportEditActivity import pl.elpassion.elspace.hub.report.list.adapter.Empty import pl.elpassion.elspace.hub.report.list.adapter.Separator import pl.elpassion.elspace.hub.report.list.adapter.holders.* import pl.elpassion.elspace.hub.report.list.service.DayFilterImpl import pl.elpassion.elspace.hub.report.list.service.ReportDayServiceImpl class ReportListActivity : AppCompatActivity(), ReportList.View, ReportList.Actions { private val controller by lazy { ReportListController( reportDayService = ReportDayServiceImpl(ReportList.ServiceProvider.get()), dayFilter = DayFilterImpl(), actions = this, view = this, schedulers = SchedulersSupplier(Schedulers.io(), AndroidSchedulers.mainThread())) } private var adapterItems = mutableListOf<AdapterItem>() private val toolbarClicks by lazy { toolbar.menuClicks() } private val reportScreenResult: PublishSubject<Unit> = PublishSubject.create() private val errorSnackBar by lazy { Snackbar.make(reportListCoordinator, R.string.internet_connection_error, Snackbar.LENGTH_INDEFINITE) .setAction(R.string.refresh_action, {}) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.report_list_activity) setSupportActionBar(toolbar) showBackArrowOnActionBar() reportsContainer.layoutManager = ReportsLinearLayoutManager(this) reportsContainer.adapter = basicAdapterWithConstructors(adapterItems, this::createHoldersForItem) controller.onCreate() } private fun createHoldersForItem(itemPosition: Int): Pair<Int, (itemView: View) -> ViewHolderBinder<AdapterItem>> { val item = adapterItems[itemPosition] return when (item) { is DayWithHourlyReports -> DayItemViewHolder.create(controller::onDayClick) is DayWithDailyReport -> DayWithDailyReportsItemViewHolder.create(controller::onReportClick) is DayWithoutReports -> createDayWithoutReportsHolder(item) is RegularHourlyReport -> RegularReportItemViewHolder.create(controller::onReportClick) is PaidVacationHourlyReport -> PaidVacationReportItemViewHolder.create(controller::onReportClick) is Separator -> SeparatorItemViewHolder.create() is Empty -> EmptyItemViewHolder.create() else -> throw IllegalArgumentException() } } private fun createDayWithoutReportsHolder(day: DayWithoutReports) = when { day.isWeekend -> WeekendDayItemViewHolder.create(controller::onDayClick) else -> DayNotFilledInItemViewHolder.create(controller::onDayClick) } override fun onCreateOptionsMenu(menu: Menu?): Boolean { menuInflater.inflate(R.menu.report_list_menu, menu) return true } override fun onOptionsItemSelected(item: MenuItem) = handleClickOnBackArrowItem(item) override fun onDestroy() { super.onDestroy() controller.onDestroy() } override fun refreshingEvents() = reportSwipeToRefresh.refreshes() override fun reportAdd(): Observable<Unit> = fabAddReport.clicks() override fun snackBarRetry(): Observable<Unit> = errorSnackBar.dismisses() .filter { it == DISMISS_EVENT_ACTION } .map { Unit } override fun monthChangeToNext(): Observable<Unit> = toolbarClicks.onMenuItemClicks(R.id.action_next_month) override fun monthChangeToPrev(): Observable<Unit> = toolbarClicks.onMenuItemClicks(R.id.action_prev_month) override fun scrollToCurrent(): Observable<Unit> = toolbarClicks.onMenuItemClicks(R.id.action_today) override fun resultRefresh(): Observable<Unit> = reportScreenResult override fun reportsFilter(): Observable<Boolean> = toolbarClicks.onMenuItemAction(R.id.action_filter) .doOnNext { it.isChecked = !it.isChecked val icon = when (it.isChecked) { true -> R.drawable.filter_on else -> R.drawable.filter_off } it.setIcon(icon) } .map { it.isChecked } .startWith(false) override fun scrollToPosition(position: Int) { appBarLayout.setExpanded(false, true) reportsContainer.smoothScrollToPosition(position) } override fun showMonthName(monthName: String) { supportActionBar?.title = monthName } override fun openAddReportScreen(date: String) { ReportAddActivity.startForResult(this, date, REPORT_SCREEN_CHANGES_REQUEST_CODE) } override fun openEditReportScreen(report: Report) { ReportEditActivity.startForResult(this, REPORT_SCREEN_CHANGES_REQUEST_CODE, report) } override fun hideLoader() { reportSwipeToRefresh.isRefreshing = false hideLoader(reportListCoordinator) } override fun showLoader() { showLoader(reportListCoordinator) } override fun isDuringPullToRefresh() = reportSwipeToRefresh.isRefreshing override fun showError(ex: Throwable) { Crashlytics.logException(ex) errorSnackBar.show() } override fun showDays(items: List<AdapterItem>) { adapterItems.clear() adapterItems.addAll(items) reportsContainer.adapter.notifyDataSetChanged() controller.updateLastPassedDayPosition(adapterItems.indexOfLast { it is Day && it.hasPassed }) } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { if (requestCode == REPORT_SCREEN_CHANGES_REQUEST_CODE && resultCode == Activity.RESULT_OK) { reportScreenResult.onNext(Unit) } super.onActivityResult(requestCode, resultCode, data) } companion object { private val REPORT_SCREEN_CHANGES_REQUEST_CODE = 100 fun start(context: Context) { context.startActivity(Intent(context, ReportListActivity::class.java)) } } }
gpl-3.0
dfdebdde9ac9be76871b509746ff58c5
40.734807
119
0.729379
4.653728
false
false
false
false
tateisu/SubwayTooter
app/src/main/java/jp/juggler/subwaytooter/columnviewholder/ColumnViewHolderActions.kt
1
10460
package jp.juggler.subwaytooter.columnviewholder import android.view.View import android.widget.CompoundButton import jp.juggler.subwaytooter.ActColumnCustomize import jp.juggler.subwaytooter.ActLanguageFilter import jp.juggler.subwaytooter.App1 import jp.juggler.subwaytooter.R import jp.juggler.subwaytooter.action.accountResendConfirmMail import jp.juggler.subwaytooter.action.listCreate import jp.juggler.subwaytooter.action.notificationDeleteAll import jp.juggler.subwaytooter.actmain.closeColumn import jp.juggler.subwaytooter.actmain.closeColumnAll import jp.juggler.subwaytooter.api.entity.TootAnnouncement import jp.juggler.subwaytooter.column.* import jp.juggler.util.hideKeyboard import jp.juggler.util.isCheckedNoAnime import jp.juggler.util.showToast import jp.juggler.util.withCaption import java.util.regex.Pattern fun ColumnViewHolder.onListListUpdated() { etListName.setText("") } fun ColumnViewHolder.checkRegexFilterError(src: String): String? { try { if (src.isEmpty()) { return null } val m = Pattern.compile(src).matcher("") if (m.find()) { // 空文字列にマッチする正規表現はエラー扱いにする // そうしないとCWの警告テキストにマッチしてしまう return activity.getString(R.string.regex_filter_matches_empty_string) } return null } catch (ex: Throwable) { val message = ex.message return if (message != null && message.isNotEmpty()) { message } else { ex.withCaption(activity.resources, R.string.regex_error) } } } fun ColumnViewHolder.isRegexValid(): Boolean { val s = etRegexFilter.text.toString() val error = checkRegexFilterError(s) tvRegexFilterError.text = error ?: "" return error == null } fun ColumnViewHolder.onCheckedChangedImpl(view: CompoundButton?, isChecked: Boolean) { view ?: return val column = this.column if (bindingBusy || column == null || statusAdapter == null) return // カラムを追加/削除したときに ColumnからColumnViewHolderへの参照が外れることがある // リロードやリフレッシュ操作で直るようにする column.addColumnViewHolder(this) when (view) { cbDontCloseColumn -> { column.dontClose = isChecked showColumnCloseButton() activity.appState.saveColumnList() } cbShowMediaDescription -> { column.showMediaDescription = isChecked activity.appState.saveColumnList() column.startLoading() } cbWithAttachment -> { column.withAttachment = isChecked activity.appState.saveColumnList() column.startLoading() } cbRemoteOnly -> { column.remoteOnly = isChecked activity.appState.saveColumnList() column.startLoading() } cbWithHighlight -> { column.withHighlight = isChecked activity.appState.saveColumnList() column.startLoading() } cbDontShowBoost -> { column.dontShowBoost = isChecked activity.appState.saveColumnList() column.startLoading() } cbDontShowReply -> { column.dontShowReply = isChecked activity.appState.saveColumnList() column.startLoading() } cbDontShowReaction -> { column.dontShowReaction = isChecked activity.appState.saveColumnList() column.startLoading() } cbDontShowVote -> { column.dontShowVote = isChecked activity.appState.saveColumnList() column.startLoading() } cbDontShowNormalToot -> { column.dontShowNormalToot = isChecked activity.appState.saveColumnList() column.startLoading() } cbDontShowNonPublicToot -> { column.dontShowNonPublicToot = isChecked activity.appState.saveColumnList() column.startLoading() } cbDontShowFavourite -> { column.dontShowFavourite = isChecked activity.appState.saveColumnList() column.startLoading() } cbDontShowFollow -> { column.dontShowFollow = isChecked activity.appState.saveColumnList() column.startLoading() } cbInstanceLocal -> { column.instanceLocal = isChecked activity.appState.saveColumnList() column.startLoading() } cbDontStreaming -> { column.dontStreaming = isChecked activity.appState.saveColumnList() activity.appState.streamManager.updateStreamingColumns() } cbDontAutoRefresh -> { column.dontAutoRefresh = isChecked activity.appState.saveColumnList() } cbHideMediaDefault -> { column.hideMediaDefault = isChecked activity.appState.saveColumnList() column.fireShowContent(reason = "HideMediaDefault in ColumnSetting", reset = true) } cbSystemNotificationNotRelated -> { column.systemNotificationNotRelated = isChecked activity.appState.saveColumnList() } cbEnableSpeech -> { column.enableSpeech = isChecked activity.appState.saveColumnList() } cbOldApi -> { column.useOldApi = isChecked activity.appState.saveColumnList() column.startLoading() } } } fun ColumnViewHolder.onClickImpl(v: View?) { v ?: return val column = this.column val statusAdapter = this.statusAdapter if (bindingBusy || column == null || statusAdapter == null) return // カラムを追加/削除したときに ColumnからColumnViewHolderへの参照が外れることがある // リロードやリフレッシュ操作で直るようにする column.addColumnViewHolder(this) when (v) { btnColumnClose -> activity.closeColumn(column) btnColumnReload -> { App1.custom_emoji_cache.clearErrorCache() if (column.isSearchColumn) { etSearch.hideKeyboard() etSearch.setText(column.searchQuery) cbResolve.isCheckedNoAnime = column.searchResolve } else if (column.type == ColumnType.REACTIONS) { updateReactionQueryView() } refreshLayout.isRefreshing = false column.startLoading() } btnSearch -> { if (column.isSearchColumn) { etSearch.hideKeyboard() column.searchQuery = etSearch.text.toString().trim { it <= ' ' } column.searchResolve = cbResolve.isChecked } activity.appState.saveColumnList() column.startLoading() } btnSearchClear -> { column.searchQuery = "" column.searchResolve = cbResolve.isChecked etSearch.setText("") flEmoji.removeAllViews() activity.appState.saveColumnList() column.startLoading() } llColumnHeader -> scrollToTop2() btnColumnSetting -> { if (showColumnSetting(!isColumnSettingShown)) { hideAnnouncements() } } btnDeleteNotification -> activity.notificationDeleteAll(column.accessInfo) btnColor -> activity.appState.columnIndex(column)?.let { colIdx -> activity.arColumnColor.launch( ActColumnCustomize.createIntent(activity, colIdx) ) } btnLanguageFilter -> activity.appState.columnIndex(column)?.let { colIdx -> activity.arLanguageFilter.launch( ActLanguageFilter.createIntent(activity, colIdx) ) } btnListAdd -> { val tv = etListName.text.toString().trim { it <= ' ' } if (tv.isEmpty()) { activity.showToast(true, R.string.list_name_empty) return } activity.listCreate(column.accessInfo, tv, null) } llRefreshError -> { column.mRefreshLoadingErrorPopupState = 1 - column.mRefreshLoadingErrorPopupState showRefreshError() } btnQuickFilterAll -> clickQuickFilter(Column.QUICK_FILTER_ALL) btnQuickFilterMention -> clickQuickFilter(Column.QUICK_FILTER_MENTION) btnQuickFilterFavourite -> clickQuickFilter(Column.QUICK_FILTER_FAVOURITE) btnQuickFilterBoost -> clickQuickFilter(Column.QUICK_FILTER_BOOST) btnQuickFilterFollow -> clickQuickFilter(Column.QUICK_FILTER_FOLLOW) btnQuickFilterPost -> clickQuickFilter(Column.QUICK_FILTER_POST) btnQuickFilterReaction -> clickQuickFilter(Column.QUICK_FILTER_REACTION) btnQuickFilterVote -> clickQuickFilter(Column.QUICK_FILTER_VOTE) btnAnnouncements -> toggleAnnouncements() btnAnnouncementsPrev -> { column.announcementId = TootAnnouncement.move(column.announcements, column.announcementId, -1) activity.appState.saveColumnList() showAnnouncements() } btnAnnouncementsNext -> { column.announcementId = TootAnnouncement.move(column.announcements, column.announcementId, +1) activity.appState.saveColumnList() showAnnouncements() } btnConfirmMail -> { activity.accountResendConfirmMail(column.accessInfo) } btnEmojiAdd -> { addEmojiQuery() } } } fun ColumnViewHolder.onLongClickImpl(v: View?): Boolean = when (v) { btnColumnClose -> activity.appState.columnIndex(column)?.let { activity.closeColumnAll(it) true } ?: false else -> false }
apache-2.0
8f1e9ecc164925d4caff575ee300deaa
29.993711
94
0.593474
5.169715
false
false
false
false
orauyeu/SimYukkuri
subprojects/simyukkuri/src/main/kotlin/simyukkuri/gameobject/yukkuri/statistic/statistics/MovementImpl.kt
1
3534
package simyukkuri.gameobject.yukkuri.statistic.statistics import simyukkuri.GameScene import simyukkuri.Time import simyukkuri.gameobject.yukkuri.event.action.actions.Sleep import simyukkuri.gameobject.yukkuri.statistic.YukkuriStats import simyukkuri.geometry.HasPosition3 import simyukkuri.geometry.Position3 /** [Movement]の標準的ゆっくりへの実装 */ class MovementImpl(x: Double, y: Double, z: Double) : Movement { companion object { /** 重力による1秒あたりの加速 */ private const val gravAccel = 5.0 /** 現在のフィールド */ lateinit var gameScene: GameScene } lateinit var self: YukkuriStats override var position: Position3 get() = Position3(x, y, z) set(value) { x = value.x y = value.y z = value.z } // TODO: マップからはみ出ないようにする. override var x = x override var y = y override var z = z override val radius: Double get() = 128.0 override var height = 128.0 /** x方向の速さ */ var vx = 0.0 /** y方向の速さ */ var vy = 0.0 /** z方向の速さ */ var vz = 0.0 // TODO: ベルトコンベアに対応して床の速度を表す変数を作る /** 掴まれているか */ var isGrabbed = false /** 移動の目的地 */ var destination: HasPosition3? = null // プレイヤーが配置した壁の処理を一旦消したのでまた加える. // TODO: 移動後の座標を反映する. /** 慣性による移動や衝突ダメージの処理を行う. */ protected fun move() { // 衝突によるダメージ var collisionDamage = 0.0 if (isGrabbed) { return } var x = position.x + vx if (x < 0.0) { collisionDamage += Math.abs(vx) x = 0.0 vx = -vx } else if (x > gameScene.maxX) { collisionDamage += Math.abs(vx) x = gameScene.maxX vx = -vx } var z = position.z + vz if (z < 0.0) { collisionDamage += Math.abs(vz) z = 0.0 vz = -vz } else if (z > gameScene.maxZ) { collisionDamage += Math.abs(vz) z = gameScene.maxZ vz = -vz } var y = position.y + vy if (y > 0.0) { vy -= gravAccel * Time.UNIT } else { collisionDamage += Math.abs(vy) // 摩擦で停止 // TODO: 摩擦による減速に置き換える z = 0.0 vz = 0.0 vy = 0.0 vx = 0.0 } // 1.5は適当 if (collisionDamage >= self.jumpHeight * 1.5) { self.damageParam += (collisionDamage - self.jumpHeight * 1.5).toFloat() self.says(self.msgList.screams) // プレイヤーしかこのタイプのダメージを与えられないことが前提 self.getAngry() // TODO: 多分これではちゃんと動作していない. if (self.action == Sleep(self)) self.action.interrupt() if (self.isDead) { self.says(self.msgList.killedInstantly) self.isCrushed = true } } } override fun update() { move() } }
apache-2.0
1437e7264d07a08aaa0a8be3d9ff157d
23.781513
83
0.497392
3.291845
false
false
false
false
triarius/GenPass
app/src/main/kotlin/com/example/android/genpass/preference/SeekBarPreference.kt
1
5325
package com.example.android.genpass.preference import android.content.Context import android.content.res.TypedArray import android.os.Parcel import android.os.Parcelable import android.preference.DialogPreference import android.preference.Preference import android.util.AttributeSet import android.view.Gravity import android.view.View import android.widget.LinearLayout import android.widget.SeekBar import android.widget.TextView import com.example.android.genpass.R /** * Created by narthana on 28/12/16. */ class SeekBarPreference (context: Context, attrs: AttributeSet): DialogPreference(context, attrs), SeekBar.OnSeekBarChangeListener { private val seekBar: SeekBar = SeekBar(context, null).also { it.setOnSeekBarChangeListener(this) } private val valueText: TextView = TextView(context, null).apply { gravity = Gravity.CENTER_HORIZONTAL textSize = TEXT_SIZE } private var value: Int = DEFAULT_VALUE // don't get int here, update in onBind, allows cancel private var max = DEFAULT_MAX // if the min/maxPrefKey attributes are set, derive the min/maxVal from the prefs dynamically // otherwise use 0 and the android:max attribute value private var minKey: String? = null private var maxKey: String? = null private val minVal: Int get() = keyToPref(minKey, 0) private val maxVal: Int get() = keyToPref(maxKey, max) init { context.theme.obtainStyledAttributes(attrs, R.styleable.SeekBarPreference, 0, 0).use { if (hasValue(R.styleable.SeekBarPreference_minPrefKey)) minKey = getString(R.styleable.SeekBarPreference_minPrefKey) if (hasValue(R.styleable.SeekBarPreference_maxPrefKey)) maxKey = getString(R.styleable.SeekBarPreference_maxPrefKey) if (hasValue(R.styleable.SeekBarPreference_android_max)) max = getInt(R.styleable.SeekBarPreference_android_max, DEFAULT_MAX) } } private fun keyToPref(key: String?, defaultValue: Int) = key?.run { sharedPreferences.getInt(this, defaultValue) } ?: defaultValue override fun onCreateDialogView(): View { seekBar.max = maxVal - minVal value = getPersistedInt(DEFAULT_VALUE) // remove seekbar from previous parent (if any) seekBar.removeFromParent() valueText.removeFromParent() return LinearLayout(context).apply { orientation = LinearLayout.VERTICAL val pad = LAYOUT_PADDING.dpToPx(context) setPadding(pad, pad, pad, pad) val lp = LinearLayout.LayoutParams( LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT ) addView(valueText, lp) addView(seekBar, lp) } } override fun onBindDialogView(view: View) { super.onBindDialogView(view) value = getPersistedInt(DEFAULT_VALUE) seekBar.progress = value - minVal valueText.text = value.toString() } override fun onSetInitialValue(restorePersistedValue: Boolean, defaultValue: Any?) { if (restorePersistedValue) value = getPersistedInt(DEFAULT_VALUE) else { value = defaultValue as Int persistInt(value) } } override fun onGetDefaultValue(a: TypedArray, index: Int) = a.getInt(index, DEFAULT_VALUE) override fun onDialogClosed(positiveResult: Boolean) { if (positiveResult) persistInt(value) } // handle saved states override fun onSaveInstanceState(): Parcelable { val superState = super.onSaveInstanceState() return SavedState(superState).also { value = this.value } } override fun onRestoreInstanceState(state: Parcelable?) { // check whether state is one that we have already saved if (state == null || state.javaClass != SavedState::class.java) { super.onRestoreInstanceState(state) return } // Cast state to custom BaseSavedState val castState = state as SavedState // restore widget state value = castState.value seekBar.progress = value - minVal super.onRestoreInstanceState(castState.superState) } private class SavedState: Preference.BaseSavedState { // Member that holds the setting's value var value: Int = 0 constructor(superState: Parcelable) : super(superState) constructor(source: Parcel) : super(source) { value = source.readInt() } override fun writeToParcel(dest: Parcel, flags: Int) { dest.writeInt(value) super.writeToParcel(dest, flags) } companion object @JvmField val CREATOR = creator(::SavedState) } // seekbar listener override fun onProgressChanged(seekBar: SeekBar, progress: Int, fromUser: Boolean) { value = minVal + progress valueText.text = value.toString() } override fun onStartTrackingTouch(seekBar: SeekBar) {} override fun onStopTrackingTouch(seekBar: SeekBar) {} companion object { private const val DEFAULT_VALUE = 0 private const val DEFAULT_MAX = 100 private const val LAYOUT_PADDING = 3.0f private const val TEXT_SIZE = 20.0f } }
gpl-3.0
a12bf8e05d28f3438675cabbdecde362
33.810458
98
0.669296
4.788669
false
false
false
false
google/intellij-community
plugins/git4idea/src/git4idea/rebase/interactive/dialog/GitInteractiveRebaseDialog.kt
5
7525
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package git4idea.rebase.interactive.dialog import com.intellij.openapi.actionSystem.* import com.intellij.openapi.actionSystem.ex.CustomComponentAction import com.intellij.openapi.application.ModalityState import com.intellij.openapi.project.DumbAware import com.intellij.openapi.project.Project import com.intellij.openapi.ui.DialogWrapper import com.intellij.openapi.ui.Messages import com.intellij.openapi.vcs.VcsException import com.intellij.openapi.vcs.changes.Change import com.intellij.openapi.vcs.changes.committed.CommittedChangesTreeBrowser import com.intellij.openapi.vfs.VirtualFile import com.intellij.ui.AnActionButton import com.intellij.ui.OnePixelSplitter import com.intellij.ui.PopupHandler import com.intellij.ui.ToolbarDecorator import com.intellij.ui.components.labels.LinkLabel import com.intellij.ui.components.labels.LinkListener import com.intellij.util.concurrency.annotations.RequiresBackgroundThread import com.intellij.util.ui.JBDimension import com.intellij.util.ui.JBUI import com.intellij.util.ui.components.BorderLayoutPanel import com.intellij.vcs.log.VcsCommitMetadata import com.intellij.vcs.log.ui.details.FullCommitDetailsListPanel import git4idea.history.GitCommitRequirements import git4idea.history.GitLogUtil import git4idea.i18n.GitBundle import git4idea.rebase.GitRebaseEntryWithDetails import git4idea.rebase.interactive.GitRebaseTodoModel import org.jetbrains.annotations.ApiStatus import java.awt.BorderLayout import java.awt.Dimension import javax.swing.JComponent import javax.swing.JSeparator import javax.swing.SwingConstants @ApiStatus.Internal const val GIT_INTERACTIVE_REBASE_DIALOG_DIMENSION_KEY = "Git.Interactive.Rebase.Dialog" internal class GitInteractiveRebaseDialog<T : GitRebaseEntryWithDetails>( private val project: Project, root: VirtualFile, entries: List<T> ) : DialogWrapper(project, true) { companion object { private const val DETAILS_PROPORTION = "Git.Interactive.Rebase.Details.Proportion" internal const val PLACE = "Git.Interactive.Rebase.Dialog" private const val DIALOG_HEIGHT = 550 private const val DIALOG_WIDTH = 1000 } private val commitsTableModel = GitRebaseCommitsTableModel(entries) private val resetEntriesLabel = LinkLabel<Any?>(GitBundle.message("rebase.interactive.dialog.reset.link.text"), null).apply { isVisible = false setListener( LinkListener { _, _ -> commitsTable.removeEditor() commitsTableModel.resetEntries() isVisible = false }, null ) } private val commitsTable = object : GitRebaseCommitsTableView(project, commitsTableModel, disposable) { override fun onEditorCreate() { isOKActionEnabled = false } override fun onEditorRemove() { isOKActionEnabled = true } } private val modalityState = window?.let { ModalityState.stateForComponent(it) } ?: ModalityState.current() private val fullCommitDetailsListPanel = object : FullCommitDetailsListPanel(project, disposable, modalityState) { @RequiresBackgroundThread @Throws(VcsException::class) override fun loadChanges(commits: List<VcsCommitMetadata>): List<Change> { val changes = mutableListOf<Change>() GitLogUtil.readFullDetailsForHashes(project, root, commits.map { it.id.asString() }, GitCommitRequirements.DEFAULT) { gitCommit -> changes.addAll(gitCommit.changes) } return CommittedChangesTreeBrowser.zipChanges(changes) } } private val iconActions = listOf( PickAction(commitsTable), EditAction(commitsTable) ) private val rewordAction = RewordAction(commitsTable) private val fixupAction = FixupAction(commitsTable) private val squashAction = SquashAction(commitsTable) private val dropAction = DropAction(commitsTable) private val contextMenuOnlyActions = listOf<AnAction>(ShowGitRebaseCommandsDialog(project, commitsTable)) private var modified = false init { commitsTable.selectionModel.addListSelectionListener { _ -> fullCommitDetailsListPanel.commitsSelected(commitsTable.selectedRows.map { commitsTableModel.getEntry(it).commitDetails }) } commitsTableModel.addTableModelListener { resetEntriesLabel.isVisible = true } commitsTableModel.addTableModelListener { modified = true } PopupHandler.installRowSelectionTablePopup( commitsTable, DefaultActionGroup().apply { addAll(iconActions) add(rewordAction) add(squashAction) add(fixupAction) add(dropAction) addSeparator() addAll(contextMenuOnlyActions) }, PLACE ) title = GitBundle.message("rebase.interactive.dialog.title") setOKButtonText(GitBundle.message("rebase.interactive.dialog.start.rebase")) init() } override fun getDimensionServiceKey() = GIT_INTERACTIVE_REBASE_DIALOG_DIMENSION_KEY override fun createCenterPanel() = BorderLayoutPanel().apply { val decorator = ToolbarDecorator.createDecorator(commitsTable) .setToolbarPosition(ActionToolbarPosition.TOP) .setPanelBorder(JBUI.Borders.empty()) .setScrollPaneBorder(JBUI.Borders.empty()) .disableAddAction() .disableRemoveAction() .addExtraActions(*iconActions.toTypedArray()) .addExtraAction(AnActionButtonSeparator()) .addExtraAction(rewordAction) .addExtraAction(AnActionOptionButton(squashAction, listOf(fixupAction))) .addExtraAction(dropAction) val tablePanel = decorator.createPanel() val resetEntriesLabelPanel = BorderLayoutPanel().addToCenter(resetEntriesLabel).apply { border = JBUI.Borders.empty(0, 5, 0, 10) } decorator.actionsPanel.apply { add(BorderLayout.EAST, resetEntriesLabelPanel) } val detailsSplitter = OnePixelSplitter(DETAILS_PROPORTION, 0.5f).apply { firstComponent = tablePanel secondComponent = fullCommitDetailsListPanel } addToCenter(detailsSplitter) preferredSize = JBDimension(DIALOG_WIDTH, DIALOG_HEIGHT) } override fun getStyle() = DialogStyle.COMPACT fun getModel(): GitRebaseTodoModel<T> = commitsTableModel.rebaseTodoModel override fun getPreferredFocusedComponent(): JComponent = commitsTable override fun doCancelAction() { if (modified) { val result = Messages.showDialog( rootPane, GitBundle.message("rebase.interactive.dialog.discard.modifications.message"), GitBundle.message("rebase.interactive.dialog.discard.modifications.cancel"), arrayOf( GitBundle.message("rebase.interactive.dialog.discard.modifications.discard"), GitBundle.message("rebase.interactive.dialog.discard.modifications.continue") ), 0, Messages.getQuestionIcon() ) if (result != Messages.YES) { return } } super.doCancelAction() } override fun getHelpId(): String { return "reference.VersionControl.Git.RebaseCommits" } private class AnActionButtonSeparator : AnActionButton(), CustomComponentAction, DumbAware { companion object { private val SEPARATOR_HEIGHT = JBUI.scale(20) } override fun actionPerformed(e: AnActionEvent) { throw UnsupportedOperationException() } override fun createCustomComponent(presentation: Presentation, place: String) = JSeparator(SwingConstants.VERTICAL).apply { preferredSize = Dimension(preferredSize.width, SEPARATOR_HEIGHT) } } }
apache-2.0
e726f52566b3818033609924d08e911d
36.819095
136
0.758538
4.703125
false
false
false
false
JetBrains/intellij-community
plugins/kotlin/base/scripting/gen/org/jetbrains/kotlin/idea/core/script/ucache/KotlinScriptLibraryEntityImpl.kt
1
10382
// 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.core.script.ucache import com.intellij.workspaceModel.storage.EntityInformation import com.intellij.workspaceModel.storage.EntitySource import com.intellij.workspaceModel.storage.EntityStorage import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion import com.intellij.workspaceModel.storage.MutableEntityStorage import com.intellij.workspaceModel.storage.SymbolicEntityId import com.intellij.workspaceModel.storage.WorkspaceEntity import com.intellij.workspaceModel.storage.WorkspaceEntityWithSymbolicId import com.intellij.workspaceModel.storage.bridgeEntities.LibraryRoot import com.intellij.workspaceModel.storage.impl.ConnectionId import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase import com.intellij.workspaceModel.storage.impl.UsedClassesCollector import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData import com.intellij.workspaceModel.storage.impl.containers.MutableWorkspaceList import com.intellij.workspaceModel.storage.impl.containers.toMutableWorkspaceList import com.intellij.workspaceModel.storage.url.VirtualFileUrl import java.io.Serializable import org.jetbrains.deft.ObjBuilder import org.jetbrains.deft.Type @GeneratedCodeApiVersion(1) @GeneratedCodeImplVersion(1) open class KotlinScriptLibraryEntityImpl(val dataSource: KotlinScriptLibraryEntityData) : KotlinScriptLibraryEntity, WorkspaceEntityBase() { companion object { val connections = listOf<ConnectionId>( ) } override val name: String get() = dataSource.name override val roots: List<KotlinScriptLibraryRoot> get() = dataSource.roots override val entitySource: EntitySource get() = dataSource.entitySource override fun connectionIdList(): List<ConnectionId> { return connections } class Builder(result: KotlinScriptLibraryEntityData?) : ModifiableWorkspaceEntityBase<KotlinScriptLibraryEntity, KotlinScriptLibraryEntityData>(result), KotlinScriptLibraryEntity.Builder { constructor() : this(KotlinScriptLibraryEntityData()) override fun applyToBuilder(builder: MutableEntityStorage) { if (this.diff != null) { if (existsInBuilder(builder)) { this.diff = builder return } else { error("Entity KotlinScriptLibraryEntity is already created in a different builder") } } this.diff = builder this.snapshot = builder addToBuilder() this.id = getEntityData().createEntityId() // DON'T_REMOVE_AT_CODE_GENERATION: start (see IDEA-305887) indexLibraryRoots(roots) // DON'T_REMOVE_AT_CODE_GENERATION: end // After adding entity data to the builder, we need to unbind it and move the control over entity data to builder // Builder may switch to snapshot at any moment and lock entity data to modification this.currentEntityData = null // Process linked entities that are connected without a builder processLinkedEntities(builder) checkInitialization() // TODO uncomment and check failed tests } fun checkInitialization() { val _diff = diff if (!getEntityData().isEntitySourceInitialized()) { error("Field WorkspaceEntity#entitySource should be initialized") } if (!getEntityData().isNameInitialized()) { error("Field KotlinScriptLibraryEntity#name should be initialized") } if (!getEntityData().isRootsInitialized()) { error("Field KotlinScriptLibraryEntity#roots should be initialized") } } override fun connectionIdList(): List<ConnectionId> { return connections } override fun afterModification() { val collection_roots = getEntityData().roots if (collection_roots is MutableWorkspaceList<*>) { collection_roots.cleanModificationUpdateAction() } } // Relabeling code, move information from dataSource to this builder override fun relabel(dataSource: WorkspaceEntity, parents: Set<WorkspaceEntity>?) { dataSource as KotlinScriptLibraryEntity if (this.entitySource != dataSource.entitySource) this.entitySource = dataSource.entitySource if (this.name != dataSource.name) this.name = dataSource.name if (this.roots != dataSource.roots) this.roots = dataSource.roots.toMutableList() if (parents != null) { } } // DON'T_REMOVE_AT_CODE_GENERATION: start (see IDEA-305887) private fun indexLibraryRoots(libraryRoots: List<KotlinScriptLibraryRoot>) { val jarDirectories = mutableSetOf<VirtualFileUrl>() val libraryRootList = libraryRoots.map { it.url }.toHashSet() index(this, "roots", libraryRootList) indexJarDirectories(this, jarDirectories) } // DON'T_REMOVE_AT_CODE_GENERATION: end override var entitySource: EntitySource get() = getEntityData().entitySource set(value) { checkModificationAllowed() getEntityData(true).entitySource = value changedProperty.add("entitySource") } override var name: String get() = getEntityData().name set(value) { checkModificationAllowed() getEntityData(true).name = value changedProperty.add("name") } private val rootsUpdater: (value: List<KotlinScriptLibraryRoot>) -> Unit = { value -> changedProperty.add("roots") } override var roots: MutableList<KotlinScriptLibraryRoot> get() { val collection_roots = getEntityData().roots if (collection_roots !is MutableWorkspaceList) return collection_roots if (diff == null || modifiable.get()) { collection_roots.setModificationUpdateAction(rootsUpdater) } else { collection_roots.cleanModificationUpdateAction() } return collection_roots } set(value) { checkModificationAllowed() getEntityData(true).roots = value rootsUpdater.invoke(value) } override fun getEntityClass(): Class<KotlinScriptLibraryEntity> = KotlinScriptLibraryEntity::class.java } } class KotlinScriptLibraryEntityData : WorkspaceEntityData.WithCalculableSymbolicId<KotlinScriptLibraryEntity>() { lateinit var name: String lateinit var roots: MutableList<KotlinScriptLibraryRoot> fun isNameInitialized(): Boolean = ::name.isInitialized fun isRootsInitialized(): Boolean = ::roots.isInitialized override fun wrapAsModifiable(diff: MutableEntityStorage): WorkspaceEntity.Builder<KotlinScriptLibraryEntity> { val modifiable = KotlinScriptLibraryEntityImpl.Builder(null) modifiable.diff = diff modifiable.snapshot = diff modifiable.id = createEntityId() return modifiable } override fun createEntity(snapshot: EntityStorage): KotlinScriptLibraryEntity { return getCached(snapshot) { val entity = KotlinScriptLibraryEntityImpl(this) entity.snapshot = snapshot entity.id = createEntityId() entity } } override fun clone(): KotlinScriptLibraryEntityData { val clonedEntity = super.clone() clonedEntity as KotlinScriptLibraryEntityData clonedEntity.roots = clonedEntity.roots.toMutableWorkspaceList() return clonedEntity } override fun symbolicId(): SymbolicEntityId<*> { return KotlinScriptLibraryId(name) } override fun getEntityInterface(): Class<out WorkspaceEntity> { return KotlinScriptLibraryEntity::class.java } override fun serialize(ser: EntityInformation.Serializer) { } override fun deserialize(de: EntityInformation.Deserializer) { } override fun createDetachedEntity(parents: List<WorkspaceEntity>): WorkspaceEntity { return KotlinScriptLibraryEntity(name, roots, entitySource) { } } override fun getRequiredParents(): List<Class<out WorkspaceEntity>> { val res = mutableListOf<Class<out WorkspaceEntity>>() return res } override fun equals(other: Any?): Boolean { if (other == null) return false if (this.javaClass != other.javaClass) return false other as KotlinScriptLibraryEntityData if (this.entitySource != other.entitySource) return false if (this.name != other.name) return false if (this.roots != other.roots) return false return true } override fun equalsIgnoringEntitySource(other: Any?): Boolean { if (other == null) return false if (this.javaClass != other.javaClass) return false other as KotlinScriptLibraryEntityData if (this.name != other.name) return false if (this.roots != other.roots) return false return true } override fun hashCode(): Int { var result = entitySource.hashCode() result = 31 * result + name.hashCode() result = 31 * result + roots.hashCode() return result } override fun hashCodeIgnoringEntitySource(): Int { var result = javaClass.hashCode() result = 31 * result + name.hashCode() result = 31 * result + roots.hashCode() return result } override fun collectClassUsagesData(collector: UsedClassesCollector) { collector.add(KotlinScriptLibraryRootTypeId::class.java) collector.add(KotlinScriptLibraryRoot::class.java) this.roots?.let { collector.add(it::class.java) } collector.sameForAllEntities = false } }
apache-2.0
3416800434dedae6b30573f3f90d4b78
37.738806
140
0.668176
5.698134
false
false
false
false
allotria/intellij-community
platform/configuration-store-impl/src/schemeManager/SchemeManagerBase.kt
1
1830
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.configurationStore.schemeManager import com.intellij.openapi.options.SchemeManager import com.intellij.openapi.options.SchemeProcessor abstract class SchemeManagerBase<T : Any, in MUTABLE_SCHEME : T>(internal val processor: SchemeProcessor<T, MUTABLE_SCHEME>) : SchemeManager<T>() { /** * Schemes can be lazy loaded, so, client should be able to set current scheme by name, not only by instance. */ @Volatile internal var currentPendingSchemeName: String? = null override var activeScheme: T? = null internal set override var currentSchemeName: String? get() = activeScheme?.let { processor.getSchemeKey(it) } ?: currentPendingSchemeName set(schemeName) = setCurrentSchemeName(schemeName, true) internal fun processPendingCurrentSchemeName(newScheme: T): Boolean { if (processor.getSchemeKey(newScheme) == currentPendingSchemeName) { setCurrent(newScheme, false) return true } return false } override fun setCurrent(scheme: T?, notify: Boolean, processChangeSynchronously: Boolean) { currentPendingSchemeName = null val oldCurrent = activeScheme activeScheme = scheme if (notify && oldCurrent !== scheme) { processor.onCurrentSchemeSwitched(oldCurrent, scheme, processChangeSynchronously) } } override fun setCurrentSchemeName(schemeName: String?, notify: Boolean) { currentPendingSchemeName = schemeName val scheme = schemeName?.let { findSchemeByName(it) } // don't set current scheme if no scheme by name - pending resolution (see currentSchemeName field comment) if (scheme != null || schemeName == null) { setCurrent(scheme, notify) } } }
apache-2.0
f8f50906fccebd76e8beb18601eb061f
37.145833
147
0.738251
4.586466
false
false
false
false
Skatteetaten/boober
src/main/kotlin/no/skatteetaten/aurora/boober/service/exceptions.kt
1
4609
package no.skatteetaten.aurora.boober.service import no.skatteetaten.aurora.boober.model.ApplicationError import no.skatteetaten.aurora.boober.model.AuroraConfigException import no.skatteetaten.aurora.boober.model.AuroraContextCommand import no.skatteetaten.aurora.boober.model.AuroraDeployCommand import no.skatteetaten.aurora.boober.model.AuroraDeploymentContext import no.skatteetaten.aurora.boober.model.ConfigFieldErrorDetail import no.skatteetaten.aurora.boober.model.ErrorDetail import no.skatteetaten.aurora.boober.model.ErrorType.SKIPPED import no.skatteetaten.aurora.boober.model.InvalidDeploymentContext abstract class ServiceException(message: String?, cause: Throwable?) : RuntimeException(message, cause) { constructor(message: String) : this(message, null) } class OpenShiftException(messages: String?, cause: Throwable? = null) : ServiceException(messages, cause) class AuroraDeploymentSpecValidationException(message: String, cause: Throwable? = null) : ServiceException(message, cause) class UnauthorizedAccessException(message: String) : ServiceException(message) class ExceptionList(val exceptions: List<Exception>) : RuntimeException() sealed class ContextErrors(open val command: AuroraContextCommand, open val errors: List<Throwable>) data class ContextResourceValidationErrors( override val command: AuroraContextCommand, override val errors: List<Throwable>, val context: AuroraDeploymentContext ) : ContextErrors(command, errors) data class ContextCreationErrors( override val command: AuroraContextCommand, override val errors: List<Throwable> ) : ContextErrors(command, errors) class MultiApplicationValidationException( val errors: List<ContextErrors> = listOf(), val errorMessage: String = "An error occurred for one or more applications" ) : ServiceException(errorMessage) { fun toValidationErrors(): List<ApplicationError> { return this.errors.flatMap { it.asApplicationErrors() } } } class MultiApplicationValidationResultException( val valid: List<AuroraDeploymentContext> = listOf(), val invalid: List<InvalidDeploymentContext> = listOf(), val errorMessage: String = "An error occurred for one or more applications" ) : ServiceException(errorMessage) { fun toValidationErrors(): List<ApplicationError> = listOf( invalid.map { it.errors.asApplicationErrors() }.flatten(), valid.map { it.asSkippedApplicationError() } ).flatten() } class MultiApplicationDeployValidationResultException( val valid: List<AuroraDeployCommand> = listOf(), val invalid: List<ContextErrors> = listOf(), val errorMessage: String = "An error occurred for one or more applications" ) : ServiceException(errorMessage) { fun toValidationErrors(): List<ApplicationError> = listOf( invalid.map { it.asApplicationErrors() }.flatten(), valid.map { it.context.asSkippedApplicationError() } ).flatten() } fun ContextErrors.asApplicationErrors(): List<ApplicationError> = errors.map { t -> ApplicationError( this.command.applicationDeploymentRef.application, this.command.applicationDeploymentRef.environment, when (t) { is AuroraConfigException -> t.errors is IllegalArgumentException -> listOf(ConfigFieldErrorDetail.illegal(t.message ?: "")) else -> listOf(ErrorDetail(message = t.message ?: "")) } ) } fun AuroraDeploymentContext.asSkippedApplicationError(): ApplicationError = ApplicationError( this.cmd.applicationDeploymentRef.application, this.cmd.applicationDeploymentRef.environment, listOf( ErrorDetail( type = SKIPPED, message = "Deploy skipped due to validation errors in multi application deployment commands" ) ) ) open class ProvisioningException(message: String, cause: Throwable? = null) : ServiceException(message, cause) class AuroraConfigServiceException(message: String, cause: Throwable? = null) : ServiceException(message, cause) class AuroraVaultServiceException(message: String, cause: Throwable? = null) : ServiceException(message, cause) class GitReferenceException(message: String, cause: Throwable? = null) : ServiceException(message, cause) class DeployLogServiceException(message: String, cause: Throwable? = null) : ServiceException(message, cause) class NotificationServiceException(message: String, cause: Throwable? = null) : ServiceException(message, cause) class UrlValidationException(message: String) : ServiceException(message)
apache-2.0
a2f31052bc44af957a0c78076fc9a9bd
40.151786
112
0.756129
4.58607
false
false
false
false
bitsydarel/DBWeather
app/src/main/java/com/dbeginc/dbweather/notifications/NotificationActivity.kt
1
2453
/* * Copyright (C) 2017 Darel Bitsy * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License */ package com.dbeginc.dbweather.notifications import android.databinding.DataBindingUtil import android.os.Bundle import android.support.v7.app.AppCompatActivity import android.view.Menu import android.view.MenuItem import com.dbeginc.dbweather.R import com.dbeginc.dbweather.databinding.ActivityNotificationBinding import com.dbeginc.dbweather.utils.utility.NOTIFICATION_KEY import com.dbeginc.dbweather.utils.utility.goToMainScreen /** * Created by Darel Bitsy on 01/02/17. * * Notification activity that show * User about notification */ class NotificationActivity : AppCompatActivity() { private lateinit var binding: ActivityNotificationBinding override fun onCreate(savedState: Bundle?) { super.onCreate(savedState) binding = DataBindingUtil.setContentView( this, R.layout.activity_notification ) binding.notification = if (savedState == null) intent.getParcelableExtra(NOTIFICATION_KEY) else savedState.getParcelable(NOTIFICATION_KEY) } override fun onSaveInstanceState(outState: Bundle?) { super.onSaveInstanceState(outState) outState?.putParcelable(NOTIFICATION_KEY, binding.notification) } override fun onCreateOptionsMenu(menu: Menu?): Boolean { menuInflater.inflate(R.menu.activity_notification, menu) return true } override fun onPrepareOptionsMenu(menu: Menu?): Boolean { menu?.findItem(R.id.temperature)?.title = binding.notification?.temperature ?: "" return true } override fun onOptionsItemSelected(item: MenuItem?): Boolean { when (item?.itemId) { R.id.openFullWeather -> goToMainScreen(currentScreen = this) R.id.closeWindow -> supportFinishAfterTransition() } return super.onOptionsItemSelected(item) } }
gpl-3.0
57a8993d32025e8d0e6d3d0be4dfc3dc
33.069444
98
0.722788
4.663498
false
false
false
false
leafclick/intellij-community
plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/converters/MavenArtifactCoordinatesHelper.kt
1
2926
/* * Copyright 2000-2009 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.idea.maven.dom.converters import com.intellij.psi.xml.XmlTag import com.intellij.util.xml.ConvertContext import com.intellij.util.xml.DomManager import org.jetbrains.idea.maven.dom.model.MavenDomArtifactCoordinates import org.jetbrains.idea.maven.dom.model.MavenDomProjectModel import org.jetbrains.idea.maven.dom.model.MavenDomShortArtifactCoordinates import org.jetbrains.idea.maven.model.MavenId object MavenArtifactCoordinatesHelper { @JvmStatic fun getId(context: ConvertContext): MavenId { return getMavenId(getCoordinates(context), context) } @JvmStatic fun getCoordinates(context: ConvertContext): MavenDomShortArtifactCoordinates? { return context.invocationElement.parent as MavenDomShortArtifactCoordinates } @JvmStatic fun getMavenId(coords: MavenDomShortArtifactCoordinates?, context: ConvertContext): MavenId { if (coords is MavenDomArtifactCoordinates) { val version = MavenDependencyCompletionUtil.removeDummy(coords.version.stringValue) if (!version.isEmpty()) { return withVersion(coords, version) } } val domModel = DomManager.getDomManager(context.project).getFileElement(context.file, MavenDomProjectModel::class.java) ?: return withVersion(coords, "") val groupId = MavenDependencyCompletionUtil.removeDummy(coords?.groupId?.stringValue) val artifactId = MavenDependencyCompletionUtil.removeDummy(coords?.artifactId?.stringValue) if (artifactId.isNotEmpty() && groupId.isNotEmpty() && (coords!=null && !MavenDependencyCompletionUtil.isInsideManagedDependency(coords))) { val managed = MavenDependencyCompletionUtil.findManagedDependency(domModel.rootElement, context.project, groupId, artifactId) return withVersion(coords, managed?.version?.stringValue ?: "") } else { return MavenId(groupId, artifactId, "") } } @JvmStatic fun withVersion(coords: MavenDomShortArtifactCoordinates?, version: String): MavenId { if (coords == null) { return MavenId("", "", "") } return MavenId(MavenDependencyCompletionUtil.removeDummy(coords.groupId.stringValue), MavenDependencyCompletionUtil.removeDummy(coords.artifactId.stringValue), version) } }
apache-2.0
646c652cf5061f235f563ae2f14a9165
42.044118
144
0.74026
4.726979
false
false
false
false
mtransitapps/mtransit-for-android
src/main/java/org/mtransit/android/ui/pref/main/MainPreferencesViewModel.kt
1
4711
package org.mtransit.android.ui.pref.main import androidx.lifecycle.LiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.distinctUntilChanged import dagger.hilt.android.lifecycle.HiltViewModel import org.mtransit.android.ad.IAdManager import org.mtransit.android.billing.IBillingManager import org.mtransit.android.common.repository.DefaultPreferenceRepository import org.mtransit.android.common.repository.LocalPreferenceRepository import org.mtransit.android.commons.MTLog import org.mtransit.android.commons.pref.liveData import javax.inject.Inject @HiltViewModel class MainPreferencesViewModel @Inject constructor( private val billingManager: IBillingManager, private val adManager: IAdManager, lclPrefRepository: LocalPreferenceRepository, defaultPrefRepository: DefaultPreferenceRepository, ) : ViewModel(), MTLog.Loggable { companion object { private val LOG_TAG = MainPreferencesViewModel::class.java.simpleName internal const val DEVICE_SETTINGS_GROUP_PREF = "pDeviceSettings" internal const val DEVICE_SETTINGS_LANGUAGE_PREF = "pDeviceSettingsLanguage" internal const val DEVICE_SETTINGS_DATE_AND_TIME_PREF = "pDeviceSettingsDateAndTime" internal const val DEVICE_SETTINGS_LOCATION_PREF = "pDeviceSettingsLocation" internal const val DEVICE_SETTINGS_POWER_MANAGEMENT_PREF = "pDeviceSettingsPowerManagement" internal const val FEEDBACK_EMAIL_PREF = "pFeedbackEmail" internal const val FEEDBACK_STORE_PREF = "pFeedbackStore" internal const val SUPPORT_SUBSCRIPTIONS_PREF = "pSupportSubs" internal const val ABOUT_PRIVACY_POLICY_PREF = "pAboutPrivacyPolicy" internal const val ABOUT_TERMS_OF_USE_PREF = "pAboutTermsOfUse" internal const val ABOUT_APP_VERSION_PREF = "pAboutAppVersion" internal const val THIRD_PARTY_GOOGLE_PRIVACY_POLICY_PREF = "p3rdPartyGooglePrivacyPolicy" internal const val THIRD_PARTY_YOUTUBE_TERMS_OF_SERVICE_PREF = "p3rdPartyYouTubeTermsOfService" internal const val SOCIAL_FACEBOOK_PREF = "pSocialFacebook" internal const val SOCIAL_TWITTER_PREF = "pSocialTwitter" internal const val DEV_MODE_GROUP_PREF = "pDevMode" internal const val DEV_MODE_MODULE_PREF = "pDevModeModule" internal const val DEV_MODE_REWARDED_RESET_PREF = "pDevModeRewardedReset" internal const val DEV_MODE_AD_INSPECTOR_PREF = "pDevModeAdInspector" internal const val DEV_MODE_AD_MEDIATION_TEST_PREF = "pDevModeAdMediationTest" internal const val TWITTER_PAGE_URL = "https://twitter.com/montransit" internal const val FACEBOOK_PAGE_URL = "https://facebook.com/MonTransit" internal const val PRIVACY_POLICY_PAGE_URL = "https://github.com/mtransitapps/mtransit-for-android/wiki/PrivacyPolicy" internal const val PRIVACY_POLICY_FR_PAGE_URL = "https://github.com/mtransitapps/mtransit-for-android/wiki/PrivacyPolicyFr" internal const val TERMS_OF_USE_PAGE_URL = "https://github.com/mtransitapps/mtransit-for-android/wiki/TermsOfUse" internal const val TERMS_OF_USE_FR_PAGE_URL = "https://github.com/mtransitapps/mtransit-for-android/wiki/TermsOfUseFr" internal const val GOOGLE_PRIVACY_POLICY_PAGE_URL = "https://policies.google.com/privacy" internal const val YOUTUBE_TERMS_OF_SERVICE_PAGE_URL = "https://www.youtube.com/t/terms" } override fun getLogTag(): String = LOG_TAG val currentSubscription: String? = billingManager.getCurrentSubscription() val hasSubscription: Boolean? = billingManager.isHasSubscription() val theme: LiveData<String> = defaultPrefRepository.pref.liveData( DefaultPreferenceRepository.PREFS_THEME, DefaultPreferenceRepository.PREFS_THEME_DEFAULT ).distinctUntilChanged() val units: LiveData<String> = defaultPrefRepository.pref.liveData( DefaultPreferenceRepository.PREFS_UNITS, DefaultPreferenceRepository.PREFS_UNITS_DEFAULT ).distinctUntilChanged() val useInternalWebBrowser: LiveData<Boolean> = defaultPrefRepository.pref.liveData( DefaultPreferenceRepository.PREFS_USE_INTERNAL_WEB_BROWSER, DefaultPreferenceRepository.PREFS_USE_INTERNAL_WEB_BROWSER_DEFAULT ).distinctUntilChanged() val devModeEnabled: LiveData<Boolean> = lclPrefRepository.pref.liveData( LocalPreferenceRepository.PREFS_LCL_DEV_MODE_ENABLED, LocalPreferenceRepository.PREFS_LCL_DEV_MODE_ENABLED_DEFAULT ).distinctUntilChanged() fun resetRewardedAd() { adManager.resetRewarded() } fun openAdInspector() { adManager.openAdInspector() } fun refreshData() { billingManager.refreshPurchases() } }
apache-2.0
1fa7123b73bd0a2435af6971120e32d9
47.57732
134
0.762046
4.278837
false
false
false
false
leafclick/intellij-community
plugins/settings-repository/src/git/GitRepositoryManager.kt
1
10007
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.settingsRepository.git import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.diagnostic.runAndLogException import com.intellij.openapi.progress.EmptyProgressIndicator import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.util.ShutDownTracker import com.intellij.openapi.util.text.StringUtil import com.intellij.util.SmartList import com.intellij.util.io.* import org.eclipse.jgit.api.AddCommand import org.eclipse.jgit.api.errors.NoHeadException import org.eclipse.jgit.api.errors.UnmergedPathsException import org.eclipse.jgit.errors.TransportException import org.eclipse.jgit.ignore.IgnoreNode import org.eclipse.jgit.lib.Constants import org.eclipse.jgit.lib.Repository import org.eclipse.jgit.lib.RepositoryState import org.eclipse.jgit.storage.file.FileRepositoryBuilder import org.eclipse.jgit.transport.* import org.jetbrains.settingsRepository.* import org.jetbrains.settingsRepository.RepositoryManager.Updater import java.io.IOException import java.nio.file.FileAlreadyExistsException import java.nio.file.Path import kotlin.concurrent.write class GitRepositoryManager(private val credentialsStore: Lazy<IcsCredentialsStore>, dir: Path) : BaseRepositoryManager(dir), GitRepositoryClient { override val repository: Repository get() { var r = _repository if (r == null) { r = buildRepository(workTree = dir) _repository = r if (ApplicationManager.getApplication()?.isUnitTestMode != true) { ShutDownTracker.getInstance().registerShutdownTask { _repository?.close() } } } return r } // we must recreate repository if dir changed because repository stores old state and cannot be reinitialized (so, old instance cannot be reused and we must instantiate new one) private var _repository: Repository? = null override val credentialsProvider: CredentialsProvider by lazy { JGitCredentialsProvider(credentialsStore, repository) } private var ignoreRules: IgnoreNode? = null override fun createRepositoryIfNeeded(): Boolean { ignoreRules = null if (isRepositoryExists()) { return false } repository.create() repository.disableAutoCrLf() return true } override fun deleteRepository() { ignoreRules = null super.deleteRepository() val r = _repository if (r != null) { _repository = null r.close() } } override fun getUpstream() = repository.upstream override fun setUpstream(url: String?, branch: String?) { repository.setUpstream(url, branch ?: Constants.MASTER) } override fun isRepositoryExists(): Boolean { val repo = _repository if (repo == null) { return dir.exists() && FileRepositoryBuilder().setWorkTree(dir.toFile()).setUseSystemConfig(false).setup().objectDirectory.exists() } else { return repo.objectDatabase.exists() } } override fun hasUpstream() = getUpstream() != null override fun addToIndex(file: Path, path: String, content: ByteArray, size: Int) { repository.edit(AddLoadedFile(path, content, size, file.lastModified().toMillis())) } override fun deleteFromIndex(path: String, isFile: Boolean) { repository.deletePath(path, isFile, false) } override suspend fun commit(indicator: ProgressIndicator?, syncType: SyncType?, fixStateIfCannotCommit: Boolean): Boolean { lock.write { try { // will be reset if OVERWRITE_LOCAL, so, we should not fix state in this case return commitIfCan(indicator, if (!fixStateIfCannotCommit || syncType == SyncType.OVERWRITE_LOCAL) repository.repositoryState else repository.fixAndGetState()) } catch (e: UnmergedPathsException) { if (syncType == SyncType.OVERWRITE_LOCAL) { LOG.warn("Unmerged detected, ignored because sync type is OVERWRITE_LOCAL", e) return false } else { indicator?.checkCanceled() LOG.warn("Unmerged detected, will be attempted to resolve", e) resolveUnmergedConflicts(repository) indicator?.checkCanceled() return commitIfCan(indicator, repository.fixAndGetState()) } } catch (e: NoHeadException) { LOG.warn("Cannot commit - no HEAD", e) return false } } } private fun commitIfCan(indicator: ProgressIndicator?, state: RepositoryState): Boolean { if (state.canCommit()) { return commit(repository, indicator) } else { LOG.warn("Cannot commit, repository in state ${state.description}") return false } } override fun getAheadCommitsCount() = repository.getAheadCommitsCount() override fun push(indicator: ProgressIndicator?) { LOG.debug("Push") val refSpecs = SmartList(RemoteConfig(repository.config, Constants.DEFAULT_REMOTE_NAME).pushRefSpecs) if (refSpecs.isEmpty()) { val head = repository.findRef(Constants.HEAD) if (head != null && head.isSymbolic) { refSpecs.add(RefSpec(head.leaf.name)) } } val monitor = indicator.asProgressMonitor() for (transport in Transport.openAll(repository, Constants.DEFAULT_REMOTE_NAME, Transport.Operation.PUSH)) { for (attempt in 0..1) { transport.credentialsProvider = credentialsProvider try { val result = transport.push(monitor, transport.findRemoteRefUpdatesFor(refSpecs)) if (LOG.isDebugEnabled) { printMessages(result) for (refUpdate in result.remoteUpdates) { LOG.debug(refUpdate.toString()) } } break } catch (e: TransportException) { if (e.status == TransportException.Status.NOT_PERMITTED) { if (attempt == 0) { credentialsProvider.reset(transport.uri) } else { throw AuthenticationException(e) } } else if (e.status == TransportException.Status.BAD_GATEWAY) { continue } else { wrapIfNeedAndReThrow(e) } } finally { transport.close() } } } } override fun fetch(indicator: ProgressIndicator?): Updater { val pullTask = Pull(this, indicator ?: EmptyProgressIndicator()) val refToMerge = pullTask.fetch() return object : Updater { override var definitelySkipPush = false // KT-8632 override suspend fun merge(): UpdateResult? = lock.write { val committed = commit(pullTask.indicator) if (refToMerge == null) { definitelySkipPush = !committed && getAheadCommitsCount() == 0 return null } return pullTask.pull(prefetchedRefToMerge = refToMerge) } } } override suspend fun pull(indicator: ProgressIndicator?) = Pull(this, indicator).pull() override suspend fun resetToTheirs(indicator: ProgressIndicator) = Reset(this, indicator).reset(true) override suspend fun resetToMy(indicator: ProgressIndicator, localRepositoryInitializer: (() -> Unit)?) = Reset(this, indicator).reset(false, localRepositoryInitializer) override fun canCommit() = repository.repositoryState.canCommit() fun renameDirectory(pairs: Map<String, String?>, commitMessage: String): Boolean { var addCommand: AddCommand? = null val toDelete = SmartList<DeleteDirectory>() for ((oldPath, newPath) in pairs) { val old = dir.resolve(oldPath) if (!old.exists()) { continue } LOG.info("Rename $oldPath to $newPath") old.directoryStreamIfExists { val new = if (newPath == null) dir else dir.resolve(newPath) for (file in it) { LOG.runAndLogException { if (file.isHidden()) { file.delete() } else { try { file.move(new.resolve(file.fileName)) } catch (ignored: FileAlreadyExistsException) { return@runAndLogException } if (addCommand == null) { addCommand = AddCommand(repository) } addCommand!!.addFilepattern(if (newPath == null) file.fileName.toString() else "$newPath/${file.fileName}") } } } toDelete.add(DeleteDirectory(oldPath)) } LOG.runAndLogException { old.delete() } } if (toDelete.isEmpty() && addCommand == null) { return false } repository.edit(toDelete) addCommand?.call() repository.commit(IdeaCommitMessageFormatter().appendCommitOwnerInfo().append(commitMessage).toString()) return true } private fun getIgnoreRules(): IgnoreNode? { var node = ignoreRules if (node == null) { val file = dir.resolve(Constants.DOT_GIT_IGNORE) if (file.exists()) { node = IgnoreNode() file.inputStream().use { node.parse(it) } ignoreRules = node } } return node } override fun isPathIgnored(path: String): Boolean { // add first slash as WorkingTreeIterator does "The ignore code wants path to start with a '/' if possible." return getIgnoreRules()?.isIgnored("/$path", false) == IgnoreNode.MatchResult.IGNORED } } fun printMessages(fetchResult: OperationResult) { if (LOG.isDebugEnabled) { val messages = fetchResult.messages if (!StringUtil.isEmptyOrSpaces(messages)) { LOG.debug(messages) } } } class GitRepositoryService : RepositoryService { override fun isValidRepository(file: Path): Boolean { if (file.resolve(Constants.DOT_GIT).exists()) { return true } // existing bare repository try { buildRepository(gitDir = file, mustExists = true) } catch (e: IOException) { return false } return true } }
apache-2.0
079144118c9137c06f321a4d5ec88a02
31.283871
179
0.662936
4.586159
false
false
false
false
zdary/intellij-community
plugins/github/src/org/jetbrains/plugins/github/pullrequest/comment/action/GHPRDiffReviewResolvedThreadsToggleAction.kt
8
1271
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.github.pullrequest.comment.action import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.ToggleAction import org.jetbrains.plugins.github.i18n.GithubBundle import org.jetbrains.plugins.github.pullrequest.comment.GHPRDiffReviewSupport class GHPRDiffReviewResolvedThreadsToggleAction : ToggleAction({ GithubBundle.message("pull.request.review.show.resolved.threads") }, { GithubBundle.message("pull.request.review.show.resolved.threads.description") }, null) { override fun update(e: AnActionEvent) { super.update(e) val reviewSupport = e.getData(GHPRDiffReviewSupport.DATA_KEY) e.presentation.isVisible = reviewSupport != null e.presentation.isEnabled = reviewSupport != null && reviewSupport.showReviewThreads } override fun isSelected(e: AnActionEvent): Boolean = e.getData(GHPRDiffReviewSupport.DATA_KEY)?.showResolvedReviewThreads ?: false override fun setSelected(e: AnActionEvent, state: Boolean) { e.getData(GHPRDiffReviewSupport.DATA_KEY)?.showResolvedReviewThreads = state } }
apache-2.0
3d473a118ad5300aec1dcbd21c429b64
46.111111
140
0.775767
4.413194
false
false
false
false
AndroidX/androidx
wear/compose/compose-material/src/commonMain/kotlin/androidx/wear/compose/material/Vignette.kt
3
3995
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.wear.compose.material import androidx.compose.foundation.Image import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.layout.ContentScale /** * Possible combinations for vignette state. */ @kotlin.jvm.JvmInline public value class VignettePosition constructor(private val key: Int) { internal fun drawTop(): Boolean { return when (key) { 1 -> false else -> { true } } } internal fun drawBottom(): Boolean { return when (key) { 0 -> false else -> { true } } } companion object { /** * Only the top part of the vignette is displayed. */ val Top = VignettePosition(0) /** * Only the bottom part of the vignette is displayed. */ val Bottom = VignettePosition(1) /** * Both the top and bottom of the vignette is displayed. */ val TopAndBottom = VignettePosition(2) } override fun toString(): String { return when (this) { Top -> "VignetteValue.Top" Bottom -> "VignetteValue.Bottom" else -> "VignetteValue.Both" } } } /** * Vignette is whole screen decoration used to blur the top and bottom of the edges of a wearable * screen when scrolling content is displayed. The vignette is split between a top and bottom image * which can be displayed independently depending on the use case. * * The vignette is designed to be used as an overlay, typically in the [Scaffold]. * * Simple example of a Vignette with a [ScalingLazyColumn] as the main application content where * the top/bottom vignette images can be turned on/off can be found at * * @sample androidx.wear.compose.material.samples.SimpleScaffoldWithScrollIndicator * * @param vignettePosition whether to draw top and/or bottom images for this [Vignette] * @param modifier optional Modifier for the root of the [Vignette] */ @Composable public fun Vignette( vignettePosition: VignettePosition, modifier: Modifier = Modifier, ) { Box(modifier = modifier.fillMaxSize()) { if (vignettePosition.drawTop()) { Image( painter = imageResource( if (isRoundDevice()) ImageResources.CircularVignetteTop else ImageResources.RectangularVignetteTop ), contentScale = ContentScale.FillWidth, contentDescription = null, modifier = Modifier.align(Alignment.TopCenter).fillMaxWidth(), ) } if (vignettePosition.drawBottom()) { Image( painter = imageResource( if (isRoundDevice()) ImageResources.CircularVignetteBottom else ImageResources.RectangularVignetteBottom ), contentScale = ContentScale.FillWidth, contentDescription = null, modifier = Modifier.align(Alignment.BottomCenter).fillMaxWidth(), ) } } }
apache-2.0
6d0157b848a092cb4c2648b00fed1e96
32.016529
99
0.6403
4.576174
false
false
false
false
LouisCAD/Splitties
modules/checkedlazy/src/androidMain/kotlin/splitties/checkedlazy/CheckedLazy.kt
1
2650
/* * Copyright 2019 Louis Cognault Ayeva Derman. Use of this source code is governed by the Apache 2.0 license. */ @file:Suppress("NOTHING_TO_INLINE") package splitties.checkedlazy /** * Returns a lazy that throws an [IllegalStateException] if its value is accessed outside of main thread. */ fun <T> mainThreadLazy( initializer: () -> T ): Lazy<T> = CheckedAccessLazyImpl(initializer, mainThreadChecker) /** * Creates a new instance of the [Lazy] that uses the specified initialization * function [initializer] and calls [readChecker] on each access. * * If you want to check access to always happen on a specific thread, you can pass the result of * a call to the [accessOn] helper function. There's also the [noAccessOn] helper function that does * the contrary. * * Let's say you want to throw an [IllegalStateException] for a custom condition, it's [readChecker] * responsibility to do it. [check] or [require] from stdlib may help you implement this kind * of check. * * This lazy is as safe as the [readChecker] is: an empty one will be like calling [kotlin.lazy] with * [kotlin.LazyThreadSafetyMode.NONE], which is potentially unsafe. * * @param readChecker This method may check any condition external to this [Lazy]. */ fun <T> checkedLazy(readChecker: () -> Unit, initializer: () -> T): Lazy<T> { return CheckedAccessLazyImpl(initializer, readChecker) } /** * This is a modified version of [kotlin.UnsafeLazyImpl] which calls [readCheck] on each access. * If you also supplied [firstAccessCheck] (using secondary constructor), it will be called on the * first access, then [readCheck] will be called for subsequent accesses. */ internal class CheckedAccessLazyImpl<out T>( initializer: () -> T, private val readCheck: (() -> Unit)? = null, private var firstAccessCheck: (() -> Unit)? = null ) : Lazy<T> { private var initializer: (() -> T)? = initializer private var _value: Any? = uninitializedValue override val value: T get() { if (_value === uninitializedValue) { firstAccessCheck?.invoke() ?: readCheck?.invoke() _value = initializer!!() firstAccessCheck = null initializer = null } else readCheck?.invoke() @Suppress("UNCHECKED_CAST") return _value as T } override fun isInitialized(): Boolean = _value !== uninitializedValue override fun toString(): String = if (isInitialized()) value.toString() else NOT_INITIALIZED } internal val uninitializedValue = Any() internal const val NOT_INITIALIZED = "Lazy value not initialized yet."
apache-2.0
08cf0a7467270225e70ec43d2bb5e700
37.970588
109
0.686792
4.219745
false
false
false
false
kickstarter/android-oss
app/src/main/java/com/kickstarter/ui/views/RecyclerViewScrollListener.kt
1
1126
package com.kickstarter.ui.views import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView abstract class RecyclerViewScrollListener : RecyclerView.OnScrollListener() { private var firstVisibleItem = 0 private var visibleItemCount = 0 @Volatile private var mEnabled = true private var mPreLoadCount = 0 override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) { super.onScrolled(recyclerView, dx, dy) if (mEnabled) { val manager = recyclerView.layoutManager require(manager is LinearLayoutManager) { "Expected recyclerview to have linear layout manager" } visibleItemCount = manager.childCount firstVisibleItem = manager.findFirstCompletelyVisibleItemPosition() onItemIsFirstVisibleItem(firstVisibleItem) } } /** * Called when end of scroll is reached. * * @param recyclerView - related recycler view. */ abstract fun onItemIsFirstVisibleItem(index: Int) fun disableScrollListener() { mEnabled = false } }
apache-2.0
1c9cc9ddbdac67a2dc82ef046e3fe67c
33.121212
109
0.70071
5.439614
false
false
false
false
kickstarter/android-oss
app/src/main/java/com/kickstarter/libs/loadmore/ApolloPaginate.kt
1
9533
package com.kickstarter.libs.loadmore import android.util.Pair import com.kickstarter.libs.rx.transformers.Transformers import com.kickstarter.models.ApolloEnvelope import rx.Observable import rx.functions.Func1 import rx.functions.Func2 import rx.subjects.PublishSubject import java.net.MalformedURLException import java.util.ArrayList class ApolloPaginate<Data, Envelope : ApolloEnvelope, Params>( val nextPage: Observable<Void>, val startOverWith: Observable<Params>, val envelopeToListOfData: Func1<Envelope, List<Data>>, val loadWithParams: Func1<Pair<Params, String?>, Observable<Envelope>>, val pageTransformation: Func1<List<Data>, List<Data>>, val clearWhenStartingOver: Boolean = true, val concater: Func2<List<Data>?, List<Data>?, List<Data>?>, val distinctUntilChanged: Boolean, val isReversed: Boolean ) { private val _morePath = PublishSubject.create<String?>() private val _isFetching = PublishSubject.create<Boolean>() private var isFetching: Observable<Boolean?> = this._isFetching private var loadingPage: Observable<Int?>? = null private var paginatedData: Observable<List<Data>>? = null init { paginatedData = startOverWith.switchMap { firstPageParams: Params -> this.dataWithPagination( firstPageParams ) } loadingPage = startOverWith.switchMap<Int> { nextPage.scan(1, { accum: Int, _ -> accum + 1 }) } } class Builder<Data, Envelope : ApolloEnvelope, Params> { private var nextPage: Observable<Void>? = null private var startOverWith: Observable<Params>? = null private var envelopeToListOfData: Func1<Envelope, List<Data>>? = null private var loadWithParams: Func1<Pair<Params, String?>, Observable<Envelope>>? = null private var pageTransformation: Func1<List<Data>, List<Data>> = Func1<List<Data>, List<Data>> { x: List<Data> -> x } private var clearWhenStartingOver = false private var concater: Func2<List<Data>?, List<Data>?, List<Data>?> = Func2 { xs: List<Data>?, ys: List<Data>? -> mutableListOf<Data>().apply { if (isReversed) { ys?.toMutableList()?.let { this.addAll(it) } xs?.toMutableList()?.let { this.addAll(it) } } else { xs?.toMutableList()?.let { this.addAll(it) } ys?.toMutableList()?.let { this.addAll(it) } } }.toList() } private var distinctUntilChanged = false private var isReversed = false /** * [Required] An observable that emits whenever a new page of data should be loaded. */ fun nextPage(nextPage: Observable<Void>): Builder<Data, Envelope, Params> { this.nextPage = nextPage return this } /** * [Optional] An observable that emits when a fresh first page should be loaded. */ fun startOverWith(startOverWith: Observable<Params>): Builder<Data, Envelope, Params> { this.startOverWith = startOverWith return this } /** * [Required] A function that takes an `Envelope` instance and returns the list of data embedded in it. */ fun envelopeToListOfData(envelopeToListOfData: Func1<Envelope, List<Data>>): Builder<Data, Envelope, Params> { this.envelopeToListOfData = envelopeToListOfData return this } /** * [Required] A function that takes a `Params` and performs the associated network request * and returns an `Observable<Envelope>` </Envelope> */ fun loadWithParams(loadWithParams: Func1<Pair<Params, String?>, Observable<Envelope>>): Builder<Data, Envelope, Params> { this.loadWithParams = loadWithParams return this } /** * [Optional] Function to transform every page of data that is loaded. */ fun pageTransformation(pageTransformation: Func1<List<Data>, List<Data>>): Builder<Data, Envelope, Params> { this.pageTransformation = pageTransformation return this } /** * [Optional] Determines if the list of loaded data is cleared when starting over from the first page. */ fun clearWhenStartingOver(clearWhenStartingOver: Boolean): Builder<Data, Envelope, Params> { this.clearWhenStartingOver = clearWhenStartingOver return this } /** * [Optional] Determines how two lists are concatenated together while paginating. A regular `ListUtils::concat` is probably * sufficient, but sometimes you may want `ListUtils::concatDistinct` */ fun concater(concater: Func2<List<Data>?, List<Data>?, List<Data>?>): Builder<Data, Envelope, Params> { this.concater = concater return this } /** * [Optional] Determines if the list of loaded data is should be distinct until changed. */ fun distinctUntilChanged(distinctUntilChanged: Boolean): Builder<Data, Envelope, Params> { this.distinctUntilChanged = distinctUntilChanged return this } /** * [Optional] Determines if the list of loaded data is should be distinct until changed. */ fun isReversed(isReversed: Boolean): Builder<Data, Envelope, Params> { this.isReversed = isReversed return this } @Throws(RuntimeException::class) fun build(): ApolloPaginate<Data, Envelope, Params> { // Early error when required field is not set if (nextPage == null) { throw RuntimeException("`nextPage` is required") } if (envelopeToListOfData == null) { throw RuntimeException("`envelopeToListOfData` is required") } if (loadWithParams == null) { throw RuntimeException("`loadWithParams` is required") } // Default params for optional fields if (startOverWith == null) { startOverWith = Observable.just(null) } return ApolloPaginate( requireNotNull(nextPage), requireNotNull(startOverWith), requireNotNull(envelopeToListOfData), requireNotNull(loadWithParams), pageTransformation, clearWhenStartingOver, concater, distinctUntilChanged, isReversed ) } } companion object { @JvmStatic fun <Data, Envelope : ApolloEnvelope, FirstPageParams> builder(): Builder<Data, Envelope, FirstPageParams> = Builder() } /** * Returns an observable that emits the accumulated list of paginated data each time a new page is loaded. */ private fun dataWithPagination(firstPageParams: Params): Observable<List<Data>?>? { val data = paramsAndMoreUrlWithPagination(firstPageParams)?.concatMap { fetchData(it) }?.takeUntil { obj -> obj?.isEmpty() } val paginatedData = if (clearWhenStartingOver) data?.scan(ArrayList(), concater) else data?.scan(concater) return if (distinctUntilChanged) paginatedData?.distinctUntilChanged() else paginatedData } /** * Returns an observable that emits the params for the next page of data *or* the more URL for the next page. */ private fun paramsAndMoreUrlWithPagination(firstPageParams: Params): Observable<Pair<Params, String?>>? { return _morePath .map { path: String? -> Pair<Params, String?>( firstPageParams, path ) } .compose(Transformers.takeWhen(nextPage)) .startWith(Pair(firstPageParams, null)) } private fun fetchData(paginatingData: Pair<Params, String?>): Observable<List<Data>?> { return loadWithParams.call(paginatingData) .retry(2) .compose(Transformers.neverError()) .doOnNext { envelope: Envelope -> keepMorePath(envelope) } .map(envelopeToListOfData) .map(this.pageTransformation) .takeUntil { data: List<Data> -> data.isEmpty() } .doOnSubscribe { _isFetching.onNext(true) } .doAfterTerminate { _isFetching.onNext(false) } } private fun keepMorePath(envelope: Envelope) { try { _morePath.onNext( if (isReversed) envelope.pageInfoEnvelope()?.startCursor else envelope.pageInfoEnvelope()?.endCursor ) } catch (ignored: MalformedURLException) { ignored.printStackTrace() } } // Outputs fun paginatedData(): Observable<List<Data>>? { return paginatedData } fun isFetching(): Observable<Boolean?> { return isFetching } fun loadingPage(): Observable<Int?>? { return loadingPage } }
apache-2.0
c3aba2fb7adc3613fbc1ec445cbfa599
35.80695
132
0.587958
4.983272
false
false
false
false
siosio/intellij-community
plugins/kotlin/jps/jps-plugin/src/org/jetbrains/kotlin/jps/incremental/CacheAttributesManager.kt
1
1812
// 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.jps.incremental /** * Manages cache attributes values. * * Attribute values can be loaded by calling [loadActual]. * Based on loaded actual and fixed [expected] values [CacheAttributesDiff] can be constructed which can calculate [CacheStatus]. * Build system may perform required actions based on that (i.e. rebuild something, clearing caches, etc...). * * [CacheAttributesDiff] can be used to cache current attribute values and then can be used as facade for cache version operations. */ interface CacheAttributesManager<Attrs : Any> { /** * Cache attribute values expected by the current version of build system and compiler. * `null` means that cache is not required (incremental compilation is disabled). */ val expected: Attrs? /** * Load actual cache attribute values. * `null` means that cache is not yet created. * * This is internal operation that should be implemented by particular implementation of CacheAttributesManager. * Consider using `loadDiff().actual` for getting actual values. */ fun loadActual(): Attrs? /** * Write [values] as cache attributes for next build execution. */ fun writeVersion(values: Attrs? = expected) /** * Check if cache with [actual] attributes values can be used when [expected] attributes are required. */ fun isCompatible(actual: Attrs, expected: Attrs): Boolean = actual == expected } fun <Attrs : Any> CacheAttributesManager<Attrs>.loadDiff( actual: Attrs? = this.loadActual(), expected: Attrs? = this.expected ) = CacheAttributesDiff(this, actual, expected)
apache-2.0
f17c943f76c1652ccd751c555e4b0a42
40.204545
158
0.716336
4.474074
false
false
false
false
alt236/Bluetooth-LE-Library---Android
sample_app/src/main/java/uk/co/alt236/btlescan/ui/details/recyclerview/holder/AdRecordHolder.kt
1
838
package uk.co.alt236.btlescan.ui.details.recyclerview.holder import android.view.View import android.widget.TextView import uk.co.alt236.btlescan.R import uk.co.alt236.btlescan.ui.common.recyclerview.BaseViewHolder import uk.co.alt236.btlescan.ui.details.recyclerview.model.AdRecordItem class AdRecordHolder(itemView: View) : BaseViewHolder<AdRecordItem>(itemView) { val stringTextView: TextView = itemView.findViewById<View>(R.id.data_as_string) as TextView val lengthTextView: TextView = itemView.findViewById<View>(R.id.length) as TextView val arrayTextView: TextView = itemView.findViewById<View>(R.id.data_as_array) as TextView val charactersTextView: TextView = itemView.findViewById<View>(R.id.data_as_characters) as TextView val titleTextView: TextView = itemView.findViewById<View>(R.id.title) as TextView }
apache-2.0
12c59b377a5cd99ba3bc92a17107efd9
54.933333
103
0.801909
3.757848
false
false
false
false
siosio/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/UsePropertyAccessSyntaxIntention.kt
1
15130
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.intentions import com.intellij.codeInspection.CleanupLocalInspectionTool import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.openapi.ui.LabeledComponent import com.intellij.openapi.util.Key import com.intellij.profile.codeInspection.InspectionProjectProfileManager import com.intellij.psi.PsiElement import org.jdom.Element import org.jetbrains.kotlin.descriptors.CallableDescriptor import org.jetbrains.kotlin.descriptors.FunctionDescriptor import org.jetbrains.kotlin.diagnostics.Severity import org.jetbrains.kotlin.idea.FrontendInternals import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.analysis.analyzeInContext import org.jetbrains.kotlin.idea.caches.resolve.getResolutionFacade import org.jetbrains.kotlin.idea.configuration.ui.NotPropertyListPanel import org.jetbrains.kotlin.idea.core.NotPropertiesService import org.jetbrains.kotlin.idea.core.copied import org.jetbrains.kotlin.idea.core.replaced import org.jetbrains.kotlin.idea.inspections.IntentionBasedInspection import org.jetbrains.kotlin.idea.resolve.ResolutionFacade import org.jetbrains.kotlin.idea.resolve.frontendService import org.jetbrains.kotlin.idea.resolve.getDataFlowValueFactory import org.jetbrains.kotlin.idea.resolve.getLanguageVersionSettings import org.jetbrains.kotlin.idea.util.application.runWriteAction import org.jetbrains.kotlin.idea.util.getResolutionScope import org.jetbrains.kotlin.idea.util.shouldNotConvertToProperty import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.name.FqNameUnsafe import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.getQualifiedExpressionForSelector import org.jetbrains.kotlin.psi.psiUtil.getQualifiedExpressionForSelectorOrThis import org.jetbrains.kotlin.renderer.render import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.DelegatingBindingTrace import org.jetbrains.kotlin.resolve.bindingContextUtil.getDataFlowInfoBefore import org.jetbrains.kotlin.resolve.bindingContextUtil.isUsedAsExpression import org.jetbrains.kotlin.resolve.calls.CallResolver import org.jetbrains.kotlin.resolve.calls.callUtil.getResolvedCall import org.jetbrains.kotlin.resolve.calls.context.BasicCallResolutionContext import org.jetbrains.kotlin.resolve.calls.context.CheckArgumentTypesMode import org.jetbrains.kotlin.resolve.calls.context.ContextDependency import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall import org.jetbrains.kotlin.resolve.calls.model.isReallySuccess import org.jetbrains.kotlin.resolve.calls.smartcasts.DataFlowInfo import org.jetbrains.kotlin.resolve.calls.util.DelegatingCall import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.resolve.scopes.LexicalScope import org.jetbrains.kotlin.resolve.scopes.SyntheticScopes import org.jetbrains.kotlin.synthetic.SyntheticJavaPropertyDescriptor import org.jetbrains.kotlin.synthetic.canBePropertyAccessor import org.jetbrains.kotlin.types.KotlinType import org.jetbrains.kotlin.types.TypeUtils import org.jetbrains.kotlin.types.typeUtil.isUnit import org.jetbrains.kotlin.utils.KotlinExceptionWithAttachments import javax.swing.JComponent @Suppress("DEPRECATION") class UsePropertyAccessSyntaxInspection : IntentionBasedInspection<KtCallExpression>(UsePropertyAccessSyntaxIntention::class), CleanupLocalInspectionTool { val fqNameList = NotPropertiesServiceImpl.default.map(::FqNameUnsafe).toMutableList() @Suppress("CAN_BE_PRIVATE") var fqNameStrings = NotPropertiesServiceImpl.default.toMutableList() override fun readSettings(node: Element) { super.readSettings(node) fqNameList.clear() fqNameStrings.mapTo(fqNameList, ::FqNameUnsafe) } override fun writeSettings(node: Element) { fqNameStrings.clear() fqNameList.mapTo(fqNameStrings) { it.asString() } super.writeSettings(node) } override fun createOptionsPanel(): JComponent? { val list = NotPropertyListPanel(fqNameList) return LabeledComponent.create(list, KotlinBundle.message("excluded.methods")) } override fun inspectionTarget(element: KtCallExpression): PsiElement? { return element.calleeExpression } override fun inspectionProblemText(element: KtCallExpression): String? { val accessor = when (element.valueArguments.size) { 0 -> "getter" 1 -> "setter" else -> null } return KotlinBundle.message("use.of.0.method.instead.of.property.access.syntax", accessor.toString()) } } class NotPropertiesServiceImpl(private val project: Project) : NotPropertiesService { override fun getNotProperties(element: PsiElement): Set<FqNameUnsafe> { val profile = InspectionProjectProfileManager.getInstance(project).currentProfile val tool = profile.getUnwrappedTool(USE_PROPERTY_ACCESS_INSPECTION, element) return (tool?.fqNameList ?: default.map(::FqNameUnsafe)).toSet() } companion object { private val atomicMethods = listOf( "getAndIncrement", "getAndDecrement", "getAcquire", "getOpaque", "getPlain" ) private val atomicClasses = listOf("AtomicInteger", "AtomicLong") val default: List<String> = listOf( "java.net.Socket.getInputStream", "java.net.Socket.getOutputStream", "java.net.URLConnection.getInputStream", "java.net.URLConnection.getOutputStream" ) + atomicClasses.flatMap { klass -> atomicMethods.map { method -> "java.util.concurrent.atomic.$klass.$method" } } val USE_PROPERTY_ACCESS_INSPECTION: Key<UsePropertyAccessSyntaxInspection> = Key.create("UsePropertyAccessSyntax") } } class UsePropertyAccessSyntaxIntention : SelfTargetingOffsetIndependentIntention<KtCallExpression>( KtCallExpression::class.java, KotlinBundle.lazyMessage("use.property.access.syntax") ) { override fun isApplicableTo(element: KtCallExpression): Boolean = detectPropertyNameToUse(element) != null override fun applyTo(element: KtCallExpression, editor: Editor?) { val propertyName = detectPropertyNameToUse(element) ?: return runWriteAction { applyTo(element, propertyName, reformat = true) } } fun applyTo(element: KtCallExpression, propertyName: Name, reformat: Boolean): KtExpression = when (element.valueArguments.size) { 0 -> replaceWithPropertyGet(element, propertyName) 1 -> replaceWithPropertySet(element, propertyName, reformat) else -> error("More than one argument in call to accessor") } fun detectPropertyNameToUse(callExpression: KtCallExpression): Name? { if (callExpression.getQualifiedExpressionForSelector() ?.receiverExpression is KtSuperExpression ) return null // cannot call extensions on "super" val callee = callExpression.calleeExpression as? KtNameReferenceExpression ?: return null if (!canBePropertyAccessor(callee.getReferencedName())) return null val resolutionFacade = callExpression.getResolutionFacade() val bindingContext = resolutionFacade.analyze(callExpression, BodyResolveMode.PARTIAL_FOR_COMPLETION) val resolvedCall = callExpression.getResolvedCall(bindingContext) ?: return null if (!resolvedCall.isReallySuccess()) return null val function = resolvedCall.resultingDescriptor as? FunctionDescriptor ?: return null val notProperties = (inspection as? UsePropertyAccessSyntaxInspection)?.fqNameList?.toSet() ?: NotPropertiesService.getNotProperties(callExpression) if (function.shouldNotConvertToProperty(notProperties)) return null val resolutionScope = callExpression.getResolutionScope(bindingContext, resolutionFacade) @OptIn(FrontendInternals::class) val property = findSyntheticProperty(function, resolutionFacade.getFrontendService(SyntheticScopes::class.java)) ?: return null if (KtTokens.KEYWORDS.types.any { it.toString() == property.name.asString() }) return null val dataFlowInfo = bindingContext.getDataFlowInfoBefore(callee) val qualifiedExpression = callExpression.getQualifiedExpressionForSelectorOrThis() val expectedType = bindingContext[BindingContext.EXPECTED_EXPRESSION_TYPE, qualifiedExpression] ?: TypeUtils.NO_EXPECTED_TYPE if (!checkWillResolveToProperty( resolvedCall, property, bindingContext, resolutionScope, dataFlowInfo, expectedType, resolutionFacade ) ) return null val isSetUsage = callExpression.valueArguments.size == 1 val valueArgumentExpression = callExpression.valueArguments.firstOrNull()?.getArgumentExpression()?.takeUnless { it is KtLambdaExpression || it is KtNamedFunction || it is KtCallableReferenceExpression } if (isSetUsage && valueArgumentExpression == null) { return null } if (isSetUsage && qualifiedExpression.isUsedAsExpression(bindingContext)) { // call to the setter used as expression can be converted in the only case when it's used as body expression for some declaration and its type is Unit val parent = qualifiedExpression.parent if (parent !is KtDeclarationWithBody || qualifiedExpression != parent.bodyExpression) return null if (function.returnType?.isUnit() != true) return null } if (isSetUsage && property.type != function.valueParameters.single().type) { val qualifiedExpressionCopy = qualifiedExpression.copied() val callExpressionCopy = ((qualifiedExpressionCopy as? KtQualifiedExpression)?.selectorExpression ?: qualifiedExpressionCopy) as KtCallExpression val newExpression = applyTo(callExpressionCopy, property.name, reformat = false) val bindingTrace = DelegatingBindingTrace(bindingContext, "Temporary trace") val newBindingContext = newExpression.analyzeInContext( resolutionScope, contextExpression = callExpression, trace = bindingTrace, dataFlowInfo = dataFlowInfo, expectedType = expectedType, isStatement = true ) if (newBindingContext.diagnostics.any { it.severity == Severity.ERROR }) return null } return property.name } private fun checkWillResolveToProperty( resolvedCall: ResolvedCall<out CallableDescriptor>, property: SyntheticJavaPropertyDescriptor, bindingContext: BindingContext, resolutionScope: LexicalScope, dataFlowInfo: DataFlowInfo, expectedType: KotlinType, facade: ResolutionFacade ): Boolean { val project = resolvedCall.call.callElement.project val newCall = object : DelegatingCall(resolvedCall.call) { private val newCallee = KtPsiFactory(project).createExpressionByPattern("$0", property.name, reformat = false) override fun getCalleeExpression() = newCallee override fun getValueArgumentList(): KtValueArgumentList? = null override fun getValueArguments(): List<ValueArgument> = emptyList() override fun getFunctionLiteralArguments(): List<LambdaArgument> = emptyList() } val bindingTrace = DelegatingBindingTrace(bindingContext, "Temporary trace") val context = BasicCallResolutionContext.create( bindingTrace, resolutionScope, newCall, expectedType, dataFlowInfo, ContextDependency.INDEPENDENT, CheckArgumentTypesMode.CHECK_VALUE_ARGUMENTS, false, facade.getLanguageVersionSettings(), facade.getDataFlowValueFactory() ) @OptIn(FrontendInternals::class) val callResolver = facade.frontendService<CallResolver>() val result = callResolver.resolveSimpleProperty(context) return result.isSuccess && result.resultingDescriptor.original == property } private fun findSyntheticProperty(function: FunctionDescriptor, syntheticScopes: SyntheticScopes): SyntheticJavaPropertyDescriptor? { SyntheticJavaPropertyDescriptor.findByGetterOrSetter(function, syntheticScopes)?.let { return it } for (overridden in function.overriddenDescriptors) { findSyntheticProperty(overridden, syntheticScopes)?.let { return it } } return null } private fun replaceWithPropertyGet(callExpression: KtCallExpression, propertyName: Name): KtExpression { val newExpression = KtPsiFactory(callExpression).createExpression(propertyName.render()) return callExpression.replaced(newExpression) } private fun replaceWithPropertySet(callExpression: KtCallExpression, propertyName: Name, reformat: Boolean): KtExpression { val call = callExpression.getQualifiedExpressionForSelector() ?: callExpression val callParent = call.parent var callToConvert = callExpression if (callParent is KtDeclarationWithBody && call == callParent.bodyExpression) { ConvertToBlockBodyIntention.convert(callParent, true) val firstStatement = callParent.bodyBlockExpression?.statements?.first() callToConvert = (firstStatement as? KtQualifiedExpression)?.selectorExpression as? KtCallExpression ?: firstStatement as? KtCallExpression ?: throw KotlinExceptionWithAttachments("Unexpected contents of function after conversion: ${callParent::class.java}") .withAttachment("callParent", callParent.text) } val qualifiedExpression = callToConvert.getQualifiedExpressionForSelector() val argument = callToConvert.valueArguments.single() if (qualifiedExpression != null) { val pattern = when (qualifiedExpression) { is KtDotQualifiedExpression -> "$0.$1=$2" is KtSafeQualifiedExpression -> "$0?.$1=$2" else -> error(qualifiedExpression) //TODO: make it sealed? } val newExpression = KtPsiFactory(callToConvert).createExpressionByPattern( pattern, qualifiedExpression.receiverExpression, propertyName, argument.getArgumentExpression()!!, reformat = reformat ) return qualifiedExpression.replaced(newExpression) } else { val newExpression = KtPsiFactory(callToConvert).createExpressionByPattern("$0=$1", propertyName, argument.getArgumentExpression()!!) return callToConvert.replaced(newExpression) } } }
apache-2.0
8db40c5827a11b586703889a5face6c0
47.338658
162
0.731328
5.599556
false
false
false
false
siosio/intellij-community
platform/execution-impl/src/com/intellij/execution/runToolbar/RunToolbarExtraSlotsAction.kt
1
8063
// 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.execution.runToolbar import com.intellij.icons.AllIcons import com.intellij.openapi.actionSystem.* import com.intellij.openapi.actionSystem.ex.CustomComponentAction import com.intellij.openapi.actionSystem.impl.ActionButton import com.intellij.openapi.project.DumbAware import com.intellij.openapi.ui.popup.JBPopup import com.intellij.openapi.util.Disposer import com.intellij.ui.awt.RelativePoint import com.intellij.ui.popup.AbstractPopup import com.intellij.ui.popup.ComponentPopupBuilderImpl import com.intellij.util.ui.JBUI import com.intellij.util.ui.PositionTracker import com.intellij.util.ui.UIUtil import java.awt.AWTEvent import java.awt.Dialog import java.awt.Point import java.awt.Toolkit import java.awt.event.* import java.util.function.Supplier import javax.swing.JComponent import javax.swing.event.AncestorEvent import javax.swing.event.AncestorListener class RunToolbarExtraSlotsAction : AnAction(), CustomComponentAction, DumbAware { override fun actionPerformed(e: AnActionEvent) { } override fun update(e: AnActionEvent) { e.project?.let { val slotManager = RunToolbarSlotManager.getInstance(it) val isOpened = e.dataContext.getData(RunToolbarMainWidgetComponent.RUN_TOOLBAR_MAIN_WIDGET_COMPONENT_KEY)?.isOpened ?: false e.presentation.icon = when { isOpened -> AllIcons.Toolbar.Collapse slotManager.slotsCount() == 0 -> AllIcons.Toolbar.AddSlot else -> AllIcons.Toolbar.Expand } } } override fun createCustomComponent(presentation: Presentation, place: String, dataContext: DataContext): JComponent { return object : ActionButton(this, presentation, place, ActionToolbar.DEFAULT_MINIMUM_BUTTON_SIZE) { private var popup: JBPopup? = null private var pane: RunToolbarExtraSlotPane? = null init { dataContext.getData(CommonDataKeys.PROJECT)?.let { pane = RunToolbarExtraSlotPane(it) { cancel() } } } private val t: Int = JBUI.scale(4) fun updateIconImmediately(manager: RunToolbarSlotManager, mainWidget: RunToolbarMainWidgetComponent) { myIcon = when { mainWidget.isOpened -> AllIcons.Toolbar.Collapse manager.slotsCount() == 0 -> AllIcons.Toolbar.AddSlot else -> AllIcons.Toolbar.Expand } } private var canClose = false private var pressedOnMainWidget = false private var pressedOnButton = false override fun addNotify() { super.addNotify() mousePosition?.let { val bounds = this.bounds bounds.location = Point(0, 0) if (bounds.contains(it)) { myRollover = true repaint() } } } private fun cancel() { pressedOnMainWidget = false pressedOnButton = false canClose = true popup?.cancel() } override fun actionPerformed(event: AnActionEvent) { event.project?.let { project -> val manager = RunToolbarSlotManager.getInstance(project) event.dataContext.getData(RunToolbarMainWidgetComponent.RUN_TOOLBAR_MAIN_WIDGET_COMPONENT_KEY)?.let { mainWidgetComponent -> if (mainWidgetComponent.isOpened) { cancel() return } mainWidgetComponent.isOpened = true val slotPane = (if(pane?.project == project) pane else null) ?: RunToolbarExtraSlotPane(project) { cancel() } pane = slotPane if (manager.slotsCount() == 0) { manager.addNewSlot() } val tracker = object : PositionTracker<AbstractPopup>(this) { override fun recalculateLocation(b: AbstractPopup): RelativePoint { val location = bounds.location location.y += height + t return RelativePoint(component, location) } } val button = this val builder = object : ComponentPopupBuilderImpl(slotPane.getView(), mainWidgetComponent) { override fun createPopup(): JBPopup { return createPopup(Supplier<AbstractPopup?> { object : AbstractPopup() { override fun cancel(e: InputEvent?) { e?.let { if (it is MouseEvent) { val bounds = button.bounds bounds.location = Point(0, 0) if (bounds.contains(RelativePoint(it).getPoint(button))) { pressedOnButton = true } else { val mainBounds = mainWidgetComponent.bounds mainBounds.location = Point(0, 0) pressedOnMainWidget = mainBounds.contains(RelativePoint(it).getPoint(mainWidgetComponent)) } } } super.cancel(e) } } }) } } val popup = builder .setCancelOnClickOutside(true) .setCancelCallback { (canClose || popup?.isFocused == false) && (!pressedOnMainWidget && !pressedOnButton) } .setMayBeParent(true) .setShowBorder(true) .createPopup() val recalculateLocation = if (popup is AbstractPopup) tracker.recalculateLocation(popup) else RelativePoint(this, this.bounds.location) popup.show(recalculateLocation) val ancestorListener = object : AncestorListener { override fun ancestorAdded(event: AncestorEvent?) { } override fun ancestorRemoved(event: AncestorEvent?) { cancel() } override fun ancestorMoved(event: AncestorEvent?) { } } mainWidgetComponent.addAncestorListener(ancestorListener) val adapterListener = object : ComponentAdapter() { override fun componentMoved(e: ComponentEvent?) { updateLocation() } override fun componentResized(e: ComponentEvent?) { updateLocation() } private fun updateLocation() { if (popup is AbstractPopup) { popup.setLocation(tracker.recalculateLocation(popup)) } } } val awtEventListener = AWTEventListener { if (it.id == MouseEvent.MOUSE_RELEASED) { pressedOnMainWidget = false } else if (it is WindowEvent) { if(it.window is Dialog) { cancel() } } } Toolkit.getDefaultToolkit().addAWTEventListener( awtEventListener, AWTEvent.MOUSE_EVENT_MASK or AWTEvent.WINDOW_EVENT_MASK) UIUtil.getRootPane(this)?.layeredPane?.let { it.addComponentListener(adapterListener) Disposer.register(popup) { it.removeComponentListener(adapterListener) } } Disposer.register(popup) { pressedOnMainWidget = false pressedOnButton = false mainWidgetComponent.isOpened = false updateIconImmediately(manager, mainWidgetComponent) mainWidgetComponent.removeAncestorListener(ancestorListener) Toolkit.getDefaultToolkit().removeAWTEventListener(awtEventListener) canClose = false this.popup = null } updateIconImmediately(manager, mainWidgetComponent) this.popup = popup } } } } } }
apache-2.0
0701d6222ff20e1a95f8525a15480cb5
34.368421
140
0.588863
5.386106
false
false
false
false
siosio/intellij-community
plugins/gradle/java/testSources/importing/GradleAttachSourcesProviderIntegrationTest.kt
2
2766
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.gradle.importing import com.intellij.openapi.application.runReadAction import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskId import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskNotificationListenerAdapter import com.intellij.openapi.externalSystem.service.notification.ExternalSystemProgressNotificationManager import com.intellij.openapi.roots.LibraryOrderEntry import com.intellij.openapi.roots.OrderRootType import com.intellij.psi.JavaPsiFacade import com.intellij.psi.search.GlobalSearchScope import org.assertj.core.api.Assertions.assertThat import org.jetbrains.plugins.gradle.util.GradleAttachSourcesProvider import org.junit.Test class GradleAttachSourcesProviderIntegrationTest : GradleImportingTestCase() { @Test fun `test download sources dynamic task`() { importProject(createBuildScriptBuilder() .withJavaPlugin() .withIdeaPlugin() .withJUnit4() .addPrefix("idea.module.downloadSources = false") .generate()) assertModules("project", "project.main", "project.test") val junitLib: LibraryOrderEntry = getModuleLibDeps("project.test", "Gradle: junit:junit:4.12").single() assertThat(junitLib.getRootFiles(OrderRootType.CLASSES)) .hasSize(1) .allSatisfy { assertEquals("junit-4.12.jar", it.name) } val psiFile = runReadAction { JavaPsiFacade.getInstance(myProject).findClass("junit.framework.Test", GlobalSearchScope.allScope(myProject))!!.containingFile } val output = mutableListOf<String>() val listener = object : ExternalSystemTaskNotificationListenerAdapter() { override fun onTaskOutput(id: ExternalSystemTaskId, text: String, stdOut: Boolean) { output += text } } try { ExternalSystemProgressNotificationManager.getInstance().addNotificationListener(listener) val callback = GradleAttachSourcesProvider().getActions(mutableListOf(junitLib), psiFile) .single() .perform(mutableListOf(junitLib)) .apply { waitFor(5000) } assertNull(callback.error) } finally { ExternalSystemProgressNotificationManager.getInstance().removeNotificationListener(listener) } assertThat(output) .filteredOn{ it.startsWith("Sources were downloaded to") } .hasSize(1) .allSatisfy { assertThat(it).endsWith("junit-4.12-sources.jar") } assertThat(junitLib.getRootFiles(OrderRootType.SOURCES)) .hasSize(1) .allSatisfy { assertEquals("junit-4.12-sources.jar", it.name) } } }
apache-2.0
3da38bc8bc65ac63febfa0f183183be6
42.234375
140
0.736443
4.852632
false
true
false
false
JetBrains/kotlin-native
backend.native/tests/codegen/mpp/mpp_default_args.kt
4
1661
/* * Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license * that can be found in the LICENSE file. */ package codegen.mpp.mpp_default_args import kotlin.test.* @Test fun runTest() { box() } fun box() { assertEquals(test1(), 42) assertEquals(test2(17), 34) assertEquals(test3(), -1) Test4().test() Test5().Inner().test() 42.test6() assertEquals(inlineFunction("OK"), "OK,0,null") } expect fun test1(x: Int = 42): Int actual fun test1(x: Int) = x expect fun test2(x: Int, y: Int = x): Int actual fun test2(x: Int, y: Int) = x + y expect fun test3(x: Int = 42, y: Int = x + 1): Int actual fun test3(x: Int, y: Int) = x - y expect class Test4 { fun test(arg: Any = this) } actual class Test4 { actual fun test(arg: Any) { assertEquals(arg, this) } } expect class Test5 { inner class Inner { constructor(arg: Any = this@Test5) fun test(arg1: Any = this@Test5, arg2: Any = this@Inner) } } actual class Test5 { actual inner class Inner { actual constructor(arg: Any) { assertEquals(arg, this@Test5) } actual fun test(arg1: Any, arg2: Any) { assertEquals(arg1, this@Test5) assertEquals(arg2, this@Inner) } } } expect fun Int.test6(arg: Int = this) actual fun Int.test6(arg: Int) { assertEquals(arg, this) } // Default parameter in inline function. expect inline fun inlineFunction(a: String, b: Int = 0, c: () -> Double? = { null }): String actual inline fun inlineFunction(a: String, b: Int, c: () -> Double?): String = a + "," + b + "," + c()
apache-2.0
4f10a8fe26ea675589d0f427832b236c
21.146667
103
0.605057
3.151803
false
true
false
false
K0zka/kerub
src/main/kotlin/com/github/kerubistan/kerub/model/dynamic/HostDynamic.kt
2
1660
package com.github.kerubistan.kerub.model.dynamic import com.fasterxml.jackson.annotation.JsonIgnore import com.fasterxml.jackson.annotation.JsonProperty import com.fasterxml.jackson.annotation.JsonTypeName import com.github.kerubistan.kerub.model.Host import com.github.kerubistan.kerub.model.annotations.Dynamic import com.github.kerubistan.kerub.model.history.IgnoreDiff import com.github.kerubistan.kerub.utils.validateSize import io.github.kerubistan.kroki.time.now import org.hibernate.search.annotations.DocumentId import org.hibernate.search.annotations.Field import java.math.BigInteger import java.util.UUID /** * Dynamic general information about the status of a host. */ @JsonTypeName("host-dyn") @Dynamic(Host::class) data class HostDynamic( @DocumentId @JsonProperty("id") override val id: UUID, @IgnoreDiff override val lastUpdated: Long = now(), @Field val status: HostStatus = HostStatus.Up, val userCpu: Byte? = null, val systemCpu: Byte? = null, val idleCpu: Byte? = null, val memFree: BigInteger? = null, val memUsed: BigInteger? = null, val memSwapped: BigInteger? = null, val ksmEnabled: Boolean = false, val cpuStats: List<CpuStat> = listOf(), val storageStatus: List<StorageDeviceDynamic> = listOf(), val storageDeviceHealth: Map<String, Boolean> = mapOf(), val cpuTemperature: List<Int> = listOf() ) : DynamicEntity { override fun updatedNow() = this.copy(lastUpdated = now()) init { memFree?.validateSize("memFree") memSwapped?.validateSize("memSwapped") memUsed?.validateSize("memUsed") } @get:JsonIgnore val storageStatusById by lazy { storageStatus.associateBy { it.id } } }
apache-2.0
ad2b10ea68e14bca1cf6372aaedbaecb
30.320755
60
0.763253
3.577586
false
false
false
false
NineWorlds/serenity-android
serenity-app/src/test/kotlin/us/nineworlds/serenity/jobs/MovieSecondaryCategoryJobTest.kt
2
1912
package us.nineworlds.serenity.jobs import com.nhaarman.mockitokotlin2.any import com.nhaarman.mockitokotlin2.verify import org.apache.commons.lang3.RandomStringUtils import org.greenrobot.eventbus.EventBus import org.junit.Before import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith import org.mockito.Mock import org.mockito.junit.MockitoJUnit import org.mockito.quality.Strictness.STRICT_STUBS import org.robolectric.RobolectricTestRunner import us.nineworlds.serenity.TestingModule import us.nineworlds.serenity.common.rest.SerenityClient import us.nineworlds.serenity.events.MovieSecondaryCategoryEvent import us.nineworlds.serenity.test.InjectingTest import us.nineworlds.serenity.testrunner.PlainAndroidRunner import javax.inject.Inject @RunWith(PlainAndroidRunner::class) class MovieSecondaryCategoryJobTest : InjectingTest() { @Rule @JvmField public val rule = MockitoJUnit.rule().strictness(STRICT_STUBS) @Inject lateinit var mockClient: SerenityClient @Mock lateinit var mockEventBus: EventBus lateinit var job: MovieSecondaryCategoryJob private val expectedVideoId: String = RandomStringUtils.randomAlphanumeric(5) private val secondaryCategory: String = RandomStringUtils.randomAlphabetic(10) @Before override fun setUp() { super.setUp() job = MovieSecondaryCategoryJob(expectedVideoId, secondaryCategory) job.eventBus = mockEventBus } @Test fun onRunFetchesCategoriesForTheSpecifiedId() { job.onRun() verify(mockClient).retrieveItemByIdCategory(expectedVideoId, secondaryCategory) } @Test fun onRunFetchesCategoriesAndPostsMainCategoryEvent() { job.onRun() verify(mockClient).retrieveItemByIdCategory(expectedVideoId, secondaryCategory) verify(mockEventBus).post(any<MovieSecondaryCategoryEvent>()) } override fun installTestModules() { scope.installTestModules(TestingModule()) } }
mit
22d7b269b31c00883d3b447e72e024b3
27.969697
83
0.811192
4.248889
false
true
false
false
androidx/androidx
room/room-compiler/src/main/kotlin/androidx/room/solver/TypeAdapterStore.kt
3
39729
/* * Copyright (C) 2016 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.room.solver import androidx.annotation.VisibleForTesting import androidx.room.compiler.processing.XType import androidx.room.compiler.processing.isArray import androidx.room.compiler.processing.isEnum import androidx.room.ext.CollectionTypeNames.ARRAY_MAP import androidx.room.ext.CollectionTypeNames.INT_SPARSE_ARRAY import androidx.room.ext.CollectionTypeNames.LONG_SPARSE_ARRAY import androidx.room.ext.CommonTypeNames import androidx.room.ext.GuavaTypeNames import androidx.room.ext.isByteBuffer import androidx.room.ext.isEntityElement import androidx.room.ext.isNotByte import androidx.room.ext.isNotKotlinUnit import androidx.room.ext.isNotVoid import androidx.room.ext.isNotVoidObject import androidx.room.ext.isUUID import androidx.room.parser.ParsedQuery import androidx.room.parser.SQLTypeAffinity import androidx.room.preconditions.checkTypeOrNull import androidx.room.processor.Context import androidx.room.processor.EntityProcessor import androidx.room.processor.FieldProcessor import androidx.room.processor.PojoProcessor import androidx.room.processor.ProcessorErrors import androidx.room.processor.ProcessorErrors.DO_NOT_USE_GENERIC_IMMUTABLE_MULTIMAP import androidx.room.solver.binderprovider.CoroutineFlowResultBinderProvider import androidx.room.solver.binderprovider.CursorQueryResultBinderProvider import androidx.room.solver.binderprovider.DataSourceFactoryQueryResultBinderProvider import androidx.room.solver.binderprovider.DataSourceQueryResultBinderProvider import androidx.room.solver.binderprovider.GuavaListenableFutureQueryResultBinderProvider import androidx.room.solver.binderprovider.InstantQueryResultBinderProvider import androidx.room.solver.binderprovider.ListenableFuturePagingSourceQueryResultBinderProvider import androidx.room.solver.binderprovider.LiveDataQueryResultBinderProvider import androidx.room.solver.binderprovider.PagingSourceQueryResultBinderProvider import androidx.room.solver.binderprovider.RxCallableQueryResultBinderProvider import androidx.room.solver.binderprovider.RxJava2PagingSourceQueryResultBinderProvider import androidx.room.solver.binderprovider.RxJava3PagingSourceQueryResultBinderProvider import androidx.room.solver.binderprovider.RxQueryResultBinderProvider import androidx.room.solver.prepared.binder.PreparedQueryResultBinder import androidx.room.solver.prepared.binderprovider.GuavaListenableFuturePreparedQueryResultBinderProvider import androidx.room.solver.prepared.binderprovider.InstantPreparedQueryResultBinderProvider import androidx.room.solver.prepared.binderprovider.PreparedQueryResultBinderProvider import androidx.room.solver.prepared.binderprovider.RxPreparedQueryResultBinderProvider import androidx.room.solver.prepared.result.PreparedQueryResultAdapter import androidx.room.solver.query.parameter.ArrayQueryParameterAdapter import androidx.room.solver.query.parameter.BasicQueryParameterAdapter import androidx.room.solver.query.parameter.CollectionQueryParameterAdapter import androidx.room.solver.query.parameter.QueryParameterAdapter import androidx.room.solver.query.result.ArrayQueryResultAdapter import androidx.room.solver.query.result.EntityRowAdapter import androidx.room.solver.query.result.GuavaImmutableMultimapQueryResultAdapter import androidx.room.solver.query.result.GuavaOptionalQueryResultAdapter import androidx.room.solver.query.result.ImmutableListQueryResultAdapter import androidx.room.solver.query.result.ImmutableMapQueryResultAdapter import androidx.room.solver.query.result.ListQueryResultAdapter import androidx.room.solver.query.result.MapQueryResultAdapter import androidx.room.solver.query.result.MultimapQueryResultAdapter import androidx.room.solver.query.result.MultimapQueryResultAdapter.Companion.validateMapTypeArgs import androidx.room.solver.query.result.MultimapQueryResultAdapter.MapType.Companion.isSparseArray import androidx.room.solver.query.result.OptionalQueryResultAdapter import androidx.room.solver.query.result.PojoRowAdapter import androidx.room.solver.query.result.QueryResultAdapter import androidx.room.solver.query.result.QueryResultBinder import androidx.room.solver.query.result.RowAdapter import androidx.room.solver.query.result.SingleColumnRowAdapter import androidx.room.solver.query.result.SingleItemQueryResultAdapter import androidx.room.solver.query.result.SingleNamedColumnRowAdapter import androidx.room.solver.shortcut.binder.DeleteOrUpdateMethodBinder import androidx.room.solver.shortcut.binder.InsertOrUpsertMethodBinder import androidx.room.solver.shortcut.binderprovider.DeleteOrUpdateMethodBinderProvider import androidx.room.solver.shortcut.binderprovider.GuavaListenableFutureDeleteOrUpdateMethodBinderProvider import androidx.room.solver.shortcut.binderprovider.GuavaListenableFutureInsertMethodBinderProvider import androidx.room.solver.shortcut.binderprovider.GuavaListenableFutureUpsertMethodBinderProvider import androidx.room.solver.shortcut.binderprovider.InsertOrUpsertMethodBinderProvider import androidx.room.solver.shortcut.binderprovider.InstantDeleteOrUpdateMethodBinderProvider import androidx.room.solver.shortcut.binderprovider.InstantInsertMethodBinderProvider import androidx.room.solver.shortcut.binderprovider.InstantUpsertMethodBinderProvider import androidx.room.solver.shortcut.binderprovider.RxCallableDeleteOrUpdateMethodBinderProvider import androidx.room.solver.shortcut.binderprovider.RxCallableInsertMethodBinderProvider import androidx.room.solver.shortcut.binderprovider.RxCallableUpsertMethodBinderProvider import androidx.room.solver.shortcut.result.DeleteOrUpdateMethodAdapter import androidx.room.solver.shortcut.result.InsertOrUpsertMethodAdapter import androidx.room.solver.types.BoxedBooleanToBoxedIntConverter import androidx.room.solver.types.BoxedPrimitiveColumnTypeAdapter import androidx.room.solver.types.ByteArrayColumnTypeAdapter import androidx.room.solver.types.ByteBufferColumnTypeAdapter import androidx.room.solver.types.ColumnTypeAdapter import androidx.room.solver.types.CompositeAdapter import androidx.room.solver.types.CursorValueReader import androidx.room.solver.types.EnumColumnTypeAdapter import androidx.room.solver.types.PrimitiveBooleanToIntConverter import androidx.room.solver.types.PrimitiveColumnTypeAdapter import androidx.room.solver.types.StatementValueBinder import androidx.room.solver.types.StringColumnTypeAdapter import androidx.room.solver.types.TypeConverter import androidx.room.solver.types.UuidColumnTypeAdapter import androidx.room.vo.BuiltInConverterFlags import androidx.room.vo.MapInfo import androidx.room.vo.ShortcutQueryParameter import androidx.room.vo.isEnabled import com.google.common.collect.ImmutableList import com.google.common.collect.ImmutableListMultimap import com.google.common.collect.ImmutableMap import com.google.common.collect.ImmutableMultimap import com.google.common.collect.ImmutableSetMultimap import com.squareup.javapoet.TypeName @Suppress("PLATFORM_CLASS_MAPPED_TO_KOTLIN") /** * Holds all type adapters and can create on demand composite type adapters to convert a type into a * database column. */ class TypeAdapterStore private constructor( val context: Context, /** * first type adapter has the highest priority */ private val columnTypeAdapters: List<ColumnTypeAdapter>, @get:VisibleForTesting internal val typeConverterStore: TypeConverterStore, private val builtInConverterFlags: BuiltInConverterFlags ) { companion object { fun copy(context: Context, store: TypeAdapterStore): TypeAdapterStore { return TypeAdapterStore( context = context, columnTypeAdapters = store.columnTypeAdapters, typeConverterStore = store.typeConverterStore, builtInConverterFlags = store.builtInConverterFlags ) } fun create( context: Context, builtInConverterFlags: BuiltInConverterFlags, vararg extras: Any ): TypeAdapterStore { val adapters = arrayListOf<ColumnTypeAdapter>() val converters = arrayListOf<TypeConverter>() fun addAny(extra: Any?) { when (extra) { is TypeConverter -> converters.add(extra) is ColumnTypeAdapter -> adapters.add(extra) is List<*> -> extra.forEach(::addAny) else -> throw IllegalArgumentException("unknown extra $extra") } } extras.forEach(::addAny) fun addTypeConverter(converter: TypeConverter) { converters.add(converter) } fun addColumnAdapter(adapter: ColumnTypeAdapter) { adapters.add(adapter) } val primitives = PrimitiveColumnTypeAdapter .createPrimitiveAdapters(context.processingEnv) primitives.forEach(::addColumnAdapter) BoxedPrimitiveColumnTypeAdapter .createBoxedPrimitiveAdapters(primitives) .forEach(::addColumnAdapter) StringColumnTypeAdapter.create(context.processingEnv).forEach(::addColumnAdapter) ByteArrayColumnTypeAdapter.create(context.processingEnv).forEach(::addColumnAdapter) PrimitiveBooleanToIntConverter.create(context.processingEnv).forEach(::addTypeConverter) // null aware converter is able to automatically null wrap converters so we don't // need this as long as we are running in KSP BoxedBooleanToBoxedIntConverter.create(context.processingEnv) .forEach(::addTypeConverter) return TypeAdapterStore( context = context, columnTypeAdapters = adapters, typeConverterStore = TypeConverterStore.create( context = context, typeConverters = converters, knownColumnTypes = adapters.map { it.out } ), builtInConverterFlags = builtInConverterFlags ) } } val queryResultBinderProviders: List<QueryResultBinderProvider> = mutableListOf<QueryResultBinderProvider>().apply { add(CursorQueryResultBinderProvider(context)) add(LiveDataQueryResultBinderProvider(context)) add(GuavaListenableFutureQueryResultBinderProvider(context)) addAll(RxQueryResultBinderProvider.getAll(context)) addAll(RxCallableQueryResultBinderProvider.getAll(context)) add(DataSourceQueryResultBinderProvider(context)) add(DataSourceFactoryQueryResultBinderProvider(context)) add(RxJava2PagingSourceQueryResultBinderProvider(context)) add(RxJava3PagingSourceQueryResultBinderProvider(context)) add(ListenableFuturePagingSourceQueryResultBinderProvider(context)) add(PagingSourceQueryResultBinderProvider(context)) add(CoroutineFlowResultBinderProvider(context)) add(InstantQueryResultBinderProvider(context)) } val preparedQueryResultBinderProviders: List<PreparedQueryResultBinderProvider> = mutableListOf<PreparedQueryResultBinderProvider>().apply { addAll(RxPreparedQueryResultBinderProvider.getAll(context)) add(GuavaListenableFuturePreparedQueryResultBinderProvider(context)) add(InstantPreparedQueryResultBinderProvider(context)) } val insertBinderProviders: List<InsertOrUpsertMethodBinderProvider> = mutableListOf<InsertOrUpsertMethodBinderProvider>().apply { addAll(RxCallableInsertMethodBinderProvider.getAll(context)) add(GuavaListenableFutureInsertMethodBinderProvider(context)) add(InstantInsertMethodBinderProvider(context)) } val deleteOrUpdateBinderProvider: List<DeleteOrUpdateMethodBinderProvider> = mutableListOf<DeleteOrUpdateMethodBinderProvider>().apply { addAll(RxCallableDeleteOrUpdateMethodBinderProvider.getAll(context)) add(GuavaListenableFutureDeleteOrUpdateMethodBinderProvider(context)) add(InstantDeleteOrUpdateMethodBinderProvider(context)) } val upsertBinderProviders: List<InsertOrUpsertMethodBinderProvider> = mutableListOf<InsertOrUpsertMethodBinderProvider>().apply { addAll(RxCallableUpsertMethodBinderProvider.getAll(context)) add(GuavaListenableFutureUpsertMethodBinderProvider(context)) add(InstantUpsertMethodBinderProvider(context)) } /** * Searches 1 way to bind a value into a statement. */ fun findStatementValueBinder( input: XType, affinity: SQLTypeAffinity? ): StatementValueBinder? { if (input.isError()) { return null } val adapter = findDirectAdapterFor(input, affinity) if (adapter != null) { return adapter } fun findTypeConverterAdapter(): ColumnTypeAdapter? { val targetTypes = affinity?.getTypeMirrors(context.processingEnv) val binder = typeConverterStore.findConverterIntoStatement( input = input, columnTypes = targetTypes ) ?: return null // columnAdapter should not be null but we are receiving errors on crash in `first()` so // this safeguard allows us to dispatch the real problem to the user (e.g. why we couldn't // find the right adapter) val columnAdapter = getAllColumnAdapters(binder.to).firstOrNull() ?: return null return CompositeAdapter(input, columnAdapter, binder, null) } val adapterByTypeConverter = findTypeConverterAdapter() if (adapterByTypeConverter != null) { return adapterByTypeConverter } val defaultAdapter = createDefaultTypeAdapter(input) if (defaultAdapter != null) { return defaultAdapter } return null } /** * Searches 1 way to read it from cursor */ fun findCursorValueReader(output: XType, affinity: SQLTypeAffinity?): CursorValueReader? { if (output.isError()) { return null } val adapter = findColumnTypeAdapter(output, affinity, skipDefaultConverter = true) if (adapter != null) { // two way is better return adapter } fun findTypeConverterAdapter(): ColumnTypeAdapter? { val targetTypes = affinity?.getTypeMirrors(context.processingEnv) val converter = typeConverterStore.findConverterFromCursor( columnTypes = targetTypes, output = output ) ?: return null return CompositeAdapter( output, getAllColumnAdapters(converter.from).first(), null, converter ) } // we could not find a two way version, search for anything val typeConverterAdapter = findTypeConverterAdapter() if (typeConverterAdapter != null) { return typeConverterAdapter } val defaultAdapter = createDefaultTypeAdapter(output) if (defaultAdapter != null) { return defaultAdapter } return null } /** * Finds a two way converter, if you need 1 way, use findStatementValueBinder or * findCursorValueReader. */ fun findColumnTypeAdapter( out: XType, affinity: SQLTypeAffinity?, skipDefaultConverter: Boolean ): ColumnTypeAdapter? { if (out.isError()) { return null } val adapter = findDirectAdapterFor(out, affinity) if (adapter != null) { return adapter } fun findTypeConverterAdapter(): ColumnTypeAdapter? { val targetTypes = affinity?.getTypeMirrors(context.processingEnv) val intoStatement = typeConverterStore.findConverterIntoStatement( input = out, columnTypes = targetTypes ) ?: return null // ok found a converter, try the reverse now val fromCursor = typeConverterStore.reverse(intoStatement) ?: typeConverterStore.findTypeConverter(intoStatement.to, out) ?: return null return CompositeAdapter( out, getAllColumnAdapters(intoStatement.to).first(), intoStatement, fromCursor ) } val adapterByTypeConverter = findTypeConverterAdapter() if (adapterByTypeConverter != null) { return adapterByTypeConverter } if (!skipDefaultConverter) { val defaultAdapter = createDefaultTypeAdapter(out) if (defaultAdapter != null) { return defaultAdapter } } return null } private fun createDefaultTypeAdapter(type: XType): ColumnTypeAdapter? { val typeElement = type.typeElement return when { builtInConverterFlags.enums.isEnabled() && typeElement?.isEnum() == true -> EnumColumnTypeAdapter(typeElement, type) builtInConverterFlags.uuid.isEnabled() && type.isUUID() -> UuidColumnTypeAdapter(type) builtInConverterFlags.byteBuffer.isEnabled() && type.isByteBuffer() -> ByteBufferColumnTypeAdapter(type) else -> null } } private fun findDirectAdapterFor( out: XType, affinity: SQLTypeAffinity? ): ColumnTypeAdapter? { return getAllColumnAdapters(out).firstOrNull { affinity == null || it.typeAffinity == affinity } } fun findDeleteOrUpdateMethodBinder(typeMirror: XType): DeleteOrUpdateMethodBinder { return deleteOrUpdateBinderProvider.first { it.matches(typeMirror) }.provide(typeMirror) } fun findInsertMethodBinder( typeMirror: XType, params: List<ShortcutQueryParameter> ): InsertOrUpsertMethodBinder { return insertBinderProviders.first { it.matches(typeMirror) }.provide(typeMirror, params) } fun findUpsertMethodBinder( typeMirror: XType, params: List<ShortcutQueryParameter> ): InsertOrUpsertMethodBinder { return upsertBinderProviders.first { it.matches(typeMirror) }.provide(typeMirror, params) } fun findQueryResultBinder( typeMirror: XType, query: ParsedQuery, extrasCreator: TypeAdapterExtras.() -> Unit = { } ): QueryResultBinder { return findQueryResultBinder(typeMirror, query, TypeAdapterExtras().apply(extrasCreator)) } fun findQueryResultBinder( typeMirror: XType, query: ParsedQuery, extras: TypeAdapterExtras ): QueryResultBinder { return queryResultBinderProviders.first { it.matches(typeMirror) }.provide(typeMirror, query, extras) } fun findPreparedQueryResultBinder( typeMirror: XType, query: ParsedQuery ): PreparedQueryResultBinder { return preparedQueryResultBinderProviders.first { it.matches(typeMirror) }.provide(typeMirror, query) } fun findPreparedQueryResultAdapter(typeMirror: XType, query: ParsedQuery) = PreparedQueryResultAdapter.create(typeMirror, query.type) fun findDeleteOrUpdateAdapter(typeMirror: XType): DeleteOrUpdateMethodAdapter? { return DeleteOrUpdateMethodAdapter.create(typeMirror) } fun findInsertAdapter( typeMirror: XType, params: List<ShortcutQueryParameter> ): InsertOrUpsertMethodAdapter? { return InsertOrUpsertMethodAdapter.createInsert(context, typeMirror, params) } fun findUpsertAdapter( typeMirror: XType, params: List<ShortcutQueryParameter> ): InsertOrUpsertMethodAdapter? { return InsertOrUpsertMethodAdapter.createUpsert(context, typeMirror, params) } fun findQueryResultAdapter( typeMirror: XType, query: ParsedQuery, extrasCreator: TypeAdapterExtras.() -> Unit = { } ): QueryResultAdapter? { return findQueryResultAdapter(typeMirror, query, TypeAdapterExtras().apply(extrasCreator)) } fun findQueryResultAdapter( typeMirror: XType, query: ParsedQuery, extras: TypeAdapterExtras ): QueryResultAdapter? { if (typeMirror.isError()) { return null } // TODO: (b/192068912) Refactor the following since this if-else cascade has gotten large if (typeMirror.isArray() && typeMirror.componentType.isNotByte()) { val rowAdapter = findRowAdapter(typeMirror.componentType, query) ?: return null return ArrayQueryResultAdapter(typeMirror, rowAdapter) } else if (typeMirror.typeArguments.isEmpty()) { val rowAdapter = findRowAdapter(typeMirror, query) ?: return null return SingleItemQueryResultAdapter(rowAdapter) } else if (typeMirror.rawType.asTypeName() == GuavaTypeNames.OPTIONAL) { // Handle Guava Optional by unpacking its generic type argument and adapting that. // The Optional adapter will reappend the Optional type. val typeArg = typeMirror.typeArguments.first() // use nullable when finding row adapter as non-null adapters might return // default values val rowAdapter = findRowAdapter(typeArg.makeNullable(), query) ?: return null return GuavaOptionalQueryResultAdapter( typeArg = typeArg, resultAdapter = SingleItemQueryResultAdapter(rowAdapter) ) } else if (typeMirror.rawType.asTypeName() == CommonTypeNames.OPTIONAL) { // Handle java.util.Optional similarly. val typeArg = typeMirror.typeArguments.first() // use nullable when finding row adapter as non-null adapters might return // default values val rowAdapter = findRowAdapter(typeArg.makeNullable(), query) ?: return null return OptionalQueryResultAdapter( typeArg = typeArg, resultAdapter = SingleItemQueryResultAdapter(rowAdapter) ) } else if (typeMirror.isTypeOf(ImmutableList::class)) { val typeArg = typeMirror.typeArguments.first().extendsBoundOrSelf() val rowAdapter = findRowAdapter(typeArg, query) ?: return null return ImmutableListQueryResultAdapter( typeArg = typeArg, rowAdapter = rowAdapter ) } else if (typeMirror.isTypeOf(java.util.List::class)) { val typeArg = typeMirror.typeArguments.first().extendsBoundOrSelf() val rowAdapter = findRowAdapter(typeArg, query) ?: return null return ListQueryResultAdapter( typeArg = typeArg, rowAdapter = rowAdapter ) } else if (typeMirror.isTypeOf(ImmutableMap::class)) { val keyTypeArg = typeMirror.typeArguments[0].extendsBoundOrSelf() val valueTypeArg = typeMirror.typeArguments[1].extendsBoundOrSelf() // Create a type mirror for a regular Map in order to use MapQueryResultAdapter. This // avoids code duplication as Immutable Map can be initialized by creating an immutable // copy of a regular map. val mapType = context.processingEnv.getDeclaredType( context.processingEnv.requireTypeElement(Map::class), keyTypeArg, valueTypeArg ) val resultAdapter = findQueryResultAdapter(mapType, query, extras) ?: return null return ImmutableMapQueryResultAdapter( context = context, parsedQuery = query, keyTypeArg = keyTypeArg, valueTypeArg = valueTypeArg, resultAdapter = resultAdapter ) } else if (typeMirror.isTypeOf(ImmutableSetMultimap::class) || typeMirror.isTypeOf(ImmutableListMultimap::class) || typeMirror.isTypeOf(ImmutableMultimap::class) ) { val keyTypeArg = typeMirror.typeArguments[0].extendsBoundOrSelf() val valueTypeArg = typeMirror.typeArguments[1].extendsBoundOrSelf() if (valueTypeArg.typeElement == null) { context.logger.e( "Guava multimap 'value' type argument does not represent a class. " + "Found $valueTypeArg." ) return null } val immutableClassName = if (typeMirror.isTypeOf(ImmutableListMultimap::class)) { GuavaTypeNames.IMMUTABLE_LIST_MULTIMAP } else if (typeMirror.isTypeOf(ImmutableSetMultimap::class)) { GuavaTypeNames.IMMUTABLE_SET_MULTIMAP } else { // Return type is base class ImmutableMultimap which is not recommended. context.logger.e(DO_NOT_USE_GENERIC_IMMUTABLE_MULTIMAP) return null } // Get @MapInfo info if any (this might be null) val mapInfo = extras.getData(MapInfo::class) val keyRowAdapter = findRowAdapter( typeMirror = keyTypeArg, query = query, columnName = mapInfo?.keyColumnName ) ?: return null val valueRowAdapter = findRowAdapter( typeMirror = valueTypeArg, query = query, columnName = mapInfo?.valueColumnName ) ?: return null validateMapTypeArgs( context = context, keyTypeArg = keyTypeArg, valueTypeArg = valueTypeArg, keyReader = findCursorValueReader(keyTypeArg, null), valueReader = findCursorValueReader(valueTypeArg, null), mapInfo = mapInfo ) return GuavaImmutableMultimapQueryResultAdapter( context = context, parsedQuery = query, keyTypeArg = keyTypeArg, valueTypeArg = valueTypeArg, keyRowAdapter = checkTypeOrNull(keyRowAdapter) ?: return null, valueRowAdapter = checkTypeOrNull(valueRowAdapter) ?: return null, immutableClassName = immutableClassName ) } else if (typeMirror.isTypeOf(java.util.Map::class) || typeMirror.rawType.asTypeName().equalsIgnoreNullability(ARRAY_MAP) || typeMirror.rawType.asTypeName().equalsIgnoreNullability(LONG_SPARSE_ARRAY) || typeMirror.rawType.asTypeName().equalsIgnoreNullability(INT_SPARSE_ARRAY) ) { val mapType = when (typeMirror.rawType.asTypeName()) { LONG_SPARSE_ARRAY -> MultimapQueryResultAdapter.MapType.LONG_SPARSE INT_SPARSE_ARRAY -> MultimapQueryResultAdapter.MapType.INT_SPARSE ARRAY_MAP -> MultimapQueryResultAdapter.MapType.ARRAY_MAP else -> MultimapQueryResultAdapter.MapType.DEFAULT } val keyTypeArg = when (mapType) { MultimapQueryResultAdapter.MapType.LONG_SPARSE -> context.processingEnv.requireType(TypeName.LONG) MultimapQueryResultAdapter.MapType.INT_SPARSE -> context.processingEnv.requireType(TypeName.INT) else -> typeMirror.typeArguments[0].extendsBoundOrSelf() } val mapValueTypeArg = if (mapType.isSparseArray()) { typeMirror.typeArguments[0].extendsBoundOrSelf() } else { typeMirror.typeArguments[1].extendsBoundOrSelf() } if (mapValueTypeArg.typeElement == null) { context.logger.e( "Multimap 'value' collection type argument does not represent a class. " + "Found $mapValueTypeArg." ) return null } // TODO: Handle nested collection values in the map // Get @MapInfo info if any (this might be null) val mapInfo = extras.getData(MapInfo::class) val collectionTypeRaw = context.COMMON_TYPES.READONLY_COLLECTION.rawType if (collectionTypeRaw.isAssignableFrom(mapValueTypeArg.rawType)) { // The Map's value type argument is assignable to a Collection, we need to make // sure it is either a list or a set. val listTypeRaw = context.COMMON_TYPES.LIST.rawType val setTypeRaw = context.COMMON_TYPES.SET.rawType val collectionValueType = when { mapValueTypeArg.rawType.isAssignableFrom(listTypeRaw) -> MultimapQueryResultAdapter.CollectionValueType.LIST mapValueTypeArg.rawType.isAssignableFrom(setTypeRaw) -> MultimapQueryResultAdapter.CollectionValueType.SET else -> { context.logger.e( ProcessorErrors.valueCollectionMustBeListOrSet( mapValueTypeArg.asTypeName().toString(context.codeLanguage) ) ) return null } } val valueTypeArg = mapValueTypeArg.typeArguments.single().extendsBoundOrSelf() val keyRowAdapter = findRowAdapter( typeMirror = keyTypeArg, query = query, columnName = mapInfo?.keyColumnName ) ?: return null val valueRowAdapter = findRowAdapter( typeMirror = valueTypeArg, query = query, columnName = mapInfo?.valueColumnName ) ?: return null validateMapTypeArgs( context = context, keyTypeArg = keyTypeArg, valueTypeArg = valueTypeArg, keyReader = findCursorValueReader(keyTypeArg, null), valueReader = findCursorValueReader(valueTypeArg, null), mapInfo = mapInfo ) return MapQueryResultAdapter( context = context, parsedQuery = query, keyTypeArg = keyTypeArg, valueTypeArg = valueTypeArg, keyRowAdapter = checkTypeOrNull(keyRowAdapter) ?: return null, valueRowAdapter = checkTypeOrNull(valueRowAdapter) ?: return null, valueCollectionType = collectionValueType, mapType = mapType ) } else { val keyRowAdapter = findRowAdapter( typeMirror = keyTypeArg, query = query, columnName = mapInfo?.keyColumnName ) ?: return null val valueRowAdapter = findRowAdapter( typeMirror = mapValueTypeArg, query = query, columnName = mapInfo?.valueColumnName ) ?: return null validateMapTypeArgs( context = context, keyTypeArg = keyTypeArg, valueTypeArg = mapValueTypeArg, keyReader = findCursorValueReader(keyTypeArg, null), valueReader = findCursorValueReader(mapValueTypeArg, null), mapInfo = mapInfo ) return MapQueryResultAdapter( context = context, parsedQuery = query, keyTypeArg = keyTypeArg, valueTypeArg = mapValueTypeArg, keyRowAdapter = checkTypeOrNull(keyRowAdapter) ?: return null, valueRowAdapter = checkTypeOrNull(valueRowAdapter) ?: return null, valueCollectionType = null, mapType = mapType ) } } return null } /** * Find a converter from cursor to the given type mirror. * If there is information about the query result, we try to use it to accept *any* POJO. */ fun findRowAdapter( typeMirror: XType, query: ParsedQuery, columnName: String? = null ): RowAdapter? { if (typeMirror.isError()) { return null } val typeElement = typeMirror.typeElement if (typeElement != null && !typeMirror.asTypeName().isPrimitive) { if (typeMirror.typeArguments.isNotEmpty()) { // TODO one day support this return null } val resultInfo = query.resultInfo val (rowAdapter, rowAdapterLogs) = if (resultInfo != null && query.errors.isEmpty() && resultInfo.error == null ) { // if result info is not null, first try a pojo row adapter context.collectLogs { subContext -> val pojo = PojoProcessor.createFor( context = subContext, element = typeElement, bindingScope = FieldProcessor.BindingScope.READ_FROM_CURSOR, parent = null ).process() PojoRowAdapter( context = subContext, info = resultInfo, query = query, pojo = pojo, out = typeMirror ) } } else { Pair(null, null) } if (rowAdapter == null && query.resultInfo == null) { // we don't know what query returns. Check for entity. if (typeElement.isEntityElement()) { return EntityRowAdapter( EntityProcessor( context = context, element = typeElement ).process() ) } } if (rowAdapter != null && rowAdapterLogs?.hasErrors() != true) { rowAdapterLogs?.writeTo(context) return rowAdapter } if (columnName != null) { val singleNamedColumn = findCursorValueReader( typeMirror, query.resultInfo?.columns?.find { it.name == columnName }?.type ) if (singleNamedColumn != null) { return SingleNamedColumnRowAdapter(singleNamedColumn, columnName) } } if ((resultInfo?.columns?.size ?: 1) == 1) { val singleColumn = findCursorValueReader( typeMirror, resultInfo?.columns?.get(0)?.type ) if (singleColumn != null) { return SingleColumnRowAdapter(singleColumn) } } // if we tried, return its errors if (rowAdapter != null) { rowAdapterLogs?.writeTo(context) return rowAdapter } // use pojo adapter as a last resort. // this happens when @RawQuery or @SkipVerification is used. if (query.resultInfo == null && typeMirror.isNotVoid() && typeMirror.isNotVoidObject() && typeMirror.isNotKotlinUnit() ) { val pojo = PojoProcessor.createFor( context = context, element = typeElement, bindingScope = FieldProcessor.BindingScope.READ_FROM_CURSOR, parent = null ).process() return PojoRowAdapter( context = context, info = null, query = query, pojo = pojo, out = typeMirror ) } return null } else { if (columnName != null) { val singleNamedColumn = findCursorValueReader( typeMirror, query.resultInfo?.columns?.find { it.name == columnName }?.type ) if (singleNamedColumn != null) { return SingleNamedColumnRowAdapter(singleNamedColumn, columnName) } } val singleColumn = findCursorValueReader(typeMirror, null) ?: return null return SingleColumnRowAdapter(singleColumn) } } fun findQueryParameterAdapter( typeMirror: XType, isMultipleParameter: Boolean ): QueryParameterAdapter? { if (context.COMMON_TYPES.READONLY_COLLECTION.rawType.isAssignableFrom(typeMirror)) { val typeArg = typeMirror.typeArguments.first().extendsBoundOrSelf() // An adapter for the collection type arg wrapped in the built-in collection adapter. val wrappedCollectionAdapter = findStatementValueBinder(typeArg, null)?.let { CollectionQueryParameterAdapter(it, typeMirror.nullability) } // An adapter for the collection itself, likely a user provided type converter for the // collection. val directCollectionAdapter = findStatementValueBinder(typeMirror, null)?.let { BasicQueryParameterAdapter(it) } // Prioritize built-in collection adapters when finding an adapter for a multi-value // binding param since it is likely wrong to use a collection to single value converter // for an expression that takes in multiple values. return if (isMultipleParameter) { wrappedCollectionAdapter ?: directCollectionAdapter } else { directCollectionAdapter ?: wrappedCollectionAdapter } } else if (typeMirror.isArray() && typeMirror.componentType.isNotByte()) { val component = typeMirror.componentType val binder = findStatementValueBinder(component, null) ?: return null return ArrayQueryParameterAdapter(binder, typeMirror.nullability) } else { val binder = findStatementValueBinder(typeMirror, null) ?: return null return BasicQueryParameterAdapter(binder) } } private fun getAllColumnAdapters(input: XType): List<ColumnTypeAdapter> { return columnTypeAdapters.filter { input.isSameType(it.out) } } }
apache-2.0
5dc17e6bbef48745d275ad7820b4a1d5
43.689539
107
0.645221
5.601946
false
false
false
false
brave-warrior/TravisClient_Android
app-v3/src/main/java/com/khmelenko/lab/varis/auth/AuthViewModel.kt
2
7149
package com.khmelenko.lab.varis.auth import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import android.text.TextUtils import com.khmelenko.lab.varis.network.request.AccessTokenRequest import com.khmelenko.lab.varis.network.request.AuthorizationRequest import com.khmelenko.lab.varis.network.response.AccessToken import com.khmelenko.lab.varis.network.response.Authorization import com.khmelenko.lab.varis.network.retrofit.github.GitHubRestClient import com.khmelenko.lab.varis.network.retrofit.github.TWO_FACTOR_HEADER import com.khmelenko.lab.varis.network.retrofit.travis.TravisRestClient import com.khmelenko.lab.varis.storage.AppSettings import com.khmelenko.lab.varis.util.EncryptionUtils import com.khmelenko.lab.varis.util.StringUtils import io.reactivex.Single import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.disposables.CompositeDisposable import io.reactivex.schedulers.Schedulers import retrofit2.HttpException import java.net.HttpURLConnection import java.util.Arrays /** * Authentication ViewModel * * @author Dmytro Khmelenko ([email protected]) */ class AuthViewModel( private val travisRestClient: TravisRestClient, private val gitHubRestClient: GitHubRestClient, private val appSettings: AppSettings) : ViewModel() { private val subscriptions = CompositeDisposable() private lateinit var basicAuth: String private lateinit var authorization: Authorization private var securityCode: String? = null private var securityCodeInput: Boolean = false private val authState = MutableLiveData<AuthState>() val serverUrl: String get() = appSettings.serverUrl val isCodeInput: Boolean get() = securityCodeInput fun state(): LiveData<AuthState> = authState override fun onCleared() { subscriptions.clear() } /** * Updates server endpoint * * @param newServer New server endpoint */ fun updateServer(newServer: String) { appSettings.putServerUrl(newServer) travisRestClient.updateTravisEndpoint(newServer) } /** * Executes login action * * @param userName Username * @param password Password */ fun login(userName: String, password: String) { basicAuth = EncryptionUtils.generateBasicAuthorization(userName, password) doLogin(getAuthorizationJob(false)) } /** * Executes two-factor auth call * * @param securityCode Security code */ fun twoFactorAuth(securityCode: String) { this.securityCode = securityCode doLogin(getAuthorizationJob(true)) } private fun getAuthorizationJob(twoFactorAuth: Boolean): Single<Authorization> { return if (twoFactorAuth) { gitHubRestClient.apiService.createNewAuthorization(basicAuth, securityCode!!, prepareAuthorizationRequest()) } else { gitHubRestClient.apiService.createNewAuthorization(basicAuth, prepareAuthorizationRequest()) } } private fun doLogin(authorizationJob: Single<Authorization>) { postState(AuthState.Loading) val subscription = authorizationJob .flatMap { doAuthorization(it) } .doOnSuccess { saveAccessToken(it) } .doAfterSuccess { cleanUpAfterAuthorization() } .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe { authorization, throwable -> if (throwable == null) { postState(AuthState.Success) } else { if (throwable is HttpException && isTwoFactorAuthRequired(throwable)) { securityCodeInput = true postState(AuthState.ShowTwoFactorAuth) } else { postState(AuthState.AuthError(throwable.message)) } } } subscriptions.add(subscription) } fun oauthLogin(token: String) { postState(AuthState.Loading) val subscription = gitHubRestClient.apiService.createOAuthAuthentication(token) .flatMap { doAuthorization(token) } .doOnSuccess { saveAccessToken(it) } .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe { authorization, throwable -> if (throwable == null) { postState(AuthState.Success) } else { postState(AuthState.AuthError(throwable.message)) } } subscriptions.add(subscription) } private fun cleanUpAfterAuthorization() { // start deletion authorization on Github, because we don't need it anymore val cleanUpJob = if (!TextUtils.isEmpty(securityCode)) { gitHubRestClient.apiService.deleteAuthorization(basicAuth, securityCode!!, authorization.id.toString()) } else { gitHubRestClient.apiService.deleteAuthorization(basicAuth, authorization.id.toString()) } val task = cleanUpJob .onErrorReturn { Any() } .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe() subscriptions.add(task) } private fun saveAccessToken(accessToken: AccessToken) { // save access token to settings val token = accessToken.accessToken appSettings.putAccessToken(token) } private fun doAuthorization(token: String): Single<AccessToken> { val request = AccessTokenRequest() request.gitHubToken = token return travisRestClient.apiService.auth(request) } private fun doAuthorization(authorization: Authorization): Single<AccessToken> { this.authorization = authorization return doAuthorization(authorization.token) } private fun isTwoFactorAuthRequired(exception: HttpException): Boolean { val response = exception.response() var twoFactorAuthRequired = false for (header in response.headers().names()) { if (TWO_FACTOR_HEADER == header) { twoFactorAuthRequired = true break } } return response.code() == HttpURLConnection.HTTP_UNAUTHORIZED && twoFactorAuthRequired } /** * Prepares authorization request * * @return Authorization request */ private fun prepareAuthorizationRequest(): AuthorizationRequest { val scopes = Arrays.asList("read:org", "user:email", "repo_deployment", "repo:status", "write:repo_hook", "repo") val note = String.format("varis_client_%1\$s", StringUtils.getRandomString()) return AuthorizationRequest(scopes, note, null, null, null, null) } private fun postState(newState: AuthState) { authState.value = newState } }
apache-2.0
d72945e0798d36678bf179b63a6ac367
34.567164
120
0.654497
5.195494
false
false
false
false
androidx/androidx
room/room-compiler-processing/src/test/java/androidx/room/compiler/processing/XTypeParameterElementTest.kt
3
16893
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.room.compiler.processing import androidx.room.compiler.processing.util.Source import androidx.room.compiler.processing.util.runProcessorTest import com.google.common.truth.Truth.assertThat import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.JUnit4 @RunWith(JUnit4::class) class XTypeParameterElementTest { @Test fun classTypeParameters() { val src = Source.kotlin( "Foo.kt", """ class Foo<T1, T2> """.trimIndent() ) runProcessorTest(sources = listOf(src)) { invocation -> val foo = invocation.processingEnv.requireTypeElement("Foo") assertThat(foo.typeParameters).hasSize(2) val t1 = foo.typeParameters[0] val t2 = foo.typeParameters[1] assertThat(t1.name).isEqualTo("T1") assertThat(t1.typeVariableName.name).isEqualTo("T1") assertThat(t1.typeVariableName.bounds).isEmpty() assertThat(t2.name).isEqualTo("T2") assertThat(t2.typeVariableName.name).isEqualTo("T2") assertThat(t2.typeVariableName.bounds).isEmpty() // Note: Javac and KSP have different default types when no bounds are provided. val expectedBoundType = if (invocation.isKsp) { invocation.processingEnv.requireType("kotlin.Any").makeNullable() } else { invocation.processingEnv.requireType("java.lang.Object") } assertThat(t1.bounds).hasSize(1) val t1Bound = t1.bounds[0] assertThat(t1Bound.asTypeName().java.toString()).isEqualTo("java.lang.Object") if (invocation.isKsp) { assertThat(t1Bound.asTypeName().kotlin.toString()).isEqualTo("kotlin.Any?") } assertThat(t1Bound.isSameType(expectedBoundType)).isTrue() assertThat(t2.bounds).hasSize(1) val t2Bound = t2.bounds[0] assertThat(t2Bound.asTypeName().java.toString()).isEqualTo("java.lang.Object") if (invocation.isKsp) { assertThat(t2Bound.asTypeName().kotlin.toString()).isEqualTo("kotlin.Any?") } assertThat(t2Bound.isSameType(expectedBoundType)).isTrue() } } @Test fun classTypeParametersWithBounds() { val src = Source.kotlin( "Foo.kt", """ class Foo<T1 : Bar, T2 : Baz?> open class Bar open class Baz """.trimIndent() ) runProcessorTest(sources = listOf(src)) { invocation -> val foo = invocation.processingEnv.requireTypeElement("Foo") assertThat(foo.typeParameters).hasSize(2) val t1 = foo.typeParameters[0] val t2 = foo.typeParameters[1] assertThat(t1.name).isEqualTo("T1") assertThat(t1.typeVariableName.name).isEqualTo("T1") assertThat(t1.typeVariableName.bounds.map { it.toString() }).containsExactly("Bar") assertThat(t2.name).isEqualTo("T2") assertThat(t2.typeVariableName.name).isEqualTo("T2") assertThat(t2.typeVariableName.bounds.map { it.toString() }).containsExactly("Baz") assertThat(t1.bounds).hasSize(1) val t1Bound = t1.bounds[0] assertThat(t1Bound.asTypeName().java.toString()).isEqualTo("Bar") if (invocation.isKsp) { assertThat(t1Bound.asTypeName().kotlin.toString()).isEqualTo("Bar") } val bar = invocation.processingEnv.requireType("Bar") assertThat(t1Bound.isSameType(bar)).isTrue() assertThat(t2.bounds).hasSize(1) val t2Bound = t2.bounds[0] assertThat(t2Bound.asTypeName().java.toString()).isEqualTo("Baz") if (invocation.isKsp) { assertThat(t2Bound.asTypeName().kotlin.toString()).isEqualTo("Baz?") } val nullableBar = invocation.processingEnv.requireType("Baz").makeNullable() assertThat(t2Bound.isSameType(nullableBar)).isTrue() } } @Test fun classTypeParametersWithInOut() { val src = Source.kotlin( "Foo.kt", """ class Foo<in T1 : Bar?, out T2 : Baz> open class Bar open class Baz """.trimIndent() ) runProcessorTest(sources = listOf(src)) { invocation -> val foo = invocation.processingEnv.requireTypeElement("Foo") assertThat(foo.typeParameters).hasSize(2) val t1 = foo.typeParameters[0] val t2 = foo.typeParameters[1] assertThat(t1.name).isEqualTo("T1") assertThat(t1.typeVariableName.name).isEqualTo("T1") assertThat(t1.typeVariableName.bounds.map { it.toString() }).containsExactly("Bar") assertThat(t2.name).isEqualTo("T2") assertThat(t2.typeVariableName.name).isEqualTo("T2") assertThat(t2.typeVariableName.bounds.map { it.toString() }).containsExactly("Baz") assertThat(t1.bounds).hasSize(1) val t1Bound = t1.bounds[0] assertThat(t1Bound.asTypeName().java.toString()).isEqualTo("Bar") if (invocation.isKsp) { assertThat(t1Bound.asTypeName().kotlin.toString()).isEqualTo("Bar?") } val nullableBar = invocation.processingEnv.requireType("Bar").makeNullable() assertThat(t1Bound.isSameType(nullableBar)).isTrue() assertThat(t2.bounds).hasSize(1) val t2Bound = t2.bounds[0] assertThat(t2Bound.asTypeName().java.toString()).isEqualTo("Baz") if (invocation.isKsp) { assertThat(t2Bound.asTypeName().kotlin.toString()).isEqualTo("Baz") } val baz = invocation.processingEnv.requireType("Baz") assertThat(t2Bound.isSameType(baz)).isTrue() } } @Test fun javaClassTypeParametersWithExtends() { val src = Source.java( "Foo", """ class Foo<T extends Bar & Baz> {} class Bar {} interface Baz {} """.trimIndent() ) runProcessorTest(sources = listOf(src)) { invocation -> val foo = invocation.processingEnv.requireTypeElement("Foo") assertThat(foo.typeParameters).hasSize(1) val t = foo.typeParameters[0] assertThat(t.name).isEqualTo("T") assertThat(t.typeVariableName.name).isEqualTo("T") assertThat(t.typeVariableName.bounds.map { it.toString() }) .containsExactly("Bar", "Baz") assertThat(t.bounds).hasSize(2) val bound0 = t.bounds[0] assertThat(bound0.asTypeName().java.toString()).isEqualTo("Bar") if (invocation.isKsp) { assertThat(bound0.asTypeName().kotlin.toString()).isEqualTo("Bar") } val bar = invocation.processingEnv.requireType("Bar") assertThat(bound0.isSameType(bar)).isTrue() assertThat(bound0.nullability).isEqualTo(XNullability.UNKNOWN) val bound1 = t.bounds[1] assertThat(bound1.asTypeName().java.toString()).isEqualTo("Baz") if (invocation.isKsp) { assertThat(bound1.asTypeName().kotlin.toString()).isEqualTo("Baz") } val baz = invocation.processingEnv.requireType("Baz") assertThat(bound1.isSameType(baz)).isTrue() assertThat(bound1.nullability).isEqualTo(XNullability.UNKNOWN) } } @Test fun methodTypeParameters() { val src = Source.kotlin( "Foo.kt", """ class Foo { fun <T1, T2> someMethod(t1: T1, t2: T2) {} } """.trimIndent() ) runProcessorTest(sources = listOf(src)) { invocation -> val foo = invocation.processingEnv.requireTypeElement("Foo") val methods = foo.getDeclaredMethods() assertThat(methods).hasSize(1) val method = methods[0] assertThat(method.jvmName).isEqualTo("someMethod") assertThat(method.typeParameters).hasSize(2) val t1 = method.typeParameters[0] val t2 = method.typeParameters[1] assertThat(t1.name).isEqualTo("T1") assertThat(t1.typeVariableName.name).isEqualTo("T1") assertThat(t1.typeVariableName.bounds).isEmpty() assertThat(t2.name).isEqualTo("T2") assertThat(t2.typeVariableName.name).isEqualTo("T2") assertThat(t2.typeVariableName.bounds).isEmpty() // Note: Javac and KSP have different default types when no bounds are provided. val expectedBoundType = if (invocation.isKsp) { invocation.processingEnv.requireType("kotlin.Any").makeNullable() } else { invocation.processingEnv.requireType("java.lang.Object") } assertThat(t1.bounds).hasSize(1) val t1Bound = t1.bounds[0] assertThat(t1Bound.asTypeName().java.toString()).isEqualTo("java.lang.Object") if (invocation.isKsp) { assertThat(t1Bound.asTypeName().kotlin.toString()).isEqualTo("kotlin.Any?") } assertThat(t1Bound.isSameType(expectedBoundType)).isTrue() assertThat(t2.bounds).hasSize(1) val t2Bound = t2.bounds[0] assertThat(t2Bound.asTypeName().java.toString()).isEqualTo("java.lang.Object") if (invocation.isKsp) { assertThat(t2Bound.asTypeName().kotlin.toString()).isEqualTo("kotlin.Any?") } assertThat(t2Bound.isSameType(expectedBoundType)).isTrue() } } @Test fun methodTypeParametersWithBounds() { val src = Source.kotlin( "Foo.kt", """ class Foo { fun <T1 : Bar, T2 : Baz?> someMethod(t1: T1, t2: T2) {} } open class Bar open class Baz """.trimIndent() ) runProcessorTest(sources = listOf(src)) { invocation -> val foo = invocation.processingEnv.requireTypeElement("Foo") val methods = foo.getDeclaredMethods() assertThat(methods).hasSize(1) val method = methods[0] assertThat(method.jvmName).isEqualTo("someMethod") assertThat(method.typeParameters).hasSize(2) val t1 = method.typeParameters[0] val t2 = method.typeParameters[1] assertThat(t1.name).isEqualTo("T1") assertThat(t1.typeVariableName.name).isEqualTo("T1") assertThat(t1.typeVariableName.bounds.map { it.toString() }).containsExactly("Bar") assertThat(t2.name).isEqualTo("T2") assertThat(t2.typeVariableName.name).isEqualTo("T2") assertThat(t2.typeVariableName.bounds.map { it.toString() }).containsExactly("Baz") assertThat(t1.bounds).hasSize(1) val t1Bound = t1.bounds[0] assertThat(t1Bound.asTypeName().java.toString()).isEqualTo("Bar") if (invocation.isKsp) { assertThat(t1Bound.asTypeName().kotlin.toString()).isEqualTo("Bar") } val bar = invocation.processingEnv.requireType("Bar") assertThat(t1Bound.isSameType(bar)).isTrue() assertThat(t2.bounds).hasSize(1) val t2Bound = t2.bounds[0] assertThat(t2Bound.asTypeName().java.toString()).isEqualTo("Baz") if (invocation.isKsp) { assertThat(t2Bound.asTypeName().kotlin.toString()).isEqualTo("Baz?") } val nullableBar = invocation.processingEnv.requireType("Baz").makeNullable() assertThat(t2Bound.isSameType(nullableBar)).isTrue() } } @Test fun javaMethodTypeParametersWithExtends() { val src = Source.java( "Foo", """ class Foo { <T extends Bar & Baz> void someMethod(T t) {} } class Bar {} interface Baz {} """.trimIndent() ) runProcessorTest(sources = listOf(src)) { invocation -> val foo = invocation.processingEnv.requireTypeElement("Foo") val methods = foo.getDeclaredMethods() assertThat(methods).hasSize(1) val method = methods[0] assertThat(method.jvmName).isEqualTo("someMethod") assertThat(method.typeParameters).hasSize(1) val t = method.typeParameters[0] assertThat(t.name).isEqualTo("T") assertThat(t.typeVariableName.name).isEqualTo("T") assertThat(t.typeVariableName.bounds.map { it.toString() }) .containsExactly("Bar", "Baz") assertThat(t.bounds).hasSize(2) val bound0 = t.bounds[0] assertThat(bound0.asTypeName().java.toString()).isEqualTo("Bar") if (invocation.isKsp) { assertThat(bound0.asTypeName().kotlin.toString()).isEqualTo("Bar") } val bar = invocation.processingEnv.requireType("Bar") assertThat(bound0.isSameType(bar)).isTrue() assertThat(bound0.nullability).isEqualTo(XNullability.UNKNOWN) val bound1 = t.bounds[1] assertThat(bound1.asTypeName().java.toString()).isEqualTo("Baz") if (invocation.isKsp) { assertThat(bound1.asTypeName().kotlin.toString()).isEqualTo("Baz") } val baz = invocation.processingEnv.requireType("Baz") assertThat(bound1.isSameType(baz)).isTrue() assertThat(bound1.nullability).isEqualTo(XNullability.UNKNOWN) } } // Note: constructor type parameters are only allowed in Java sources. @Test fun javaConstructorTypeParametersWithExtends() { val src = Source.java( "Foo", """ class Foo { <T extends Bar & Baz> Foo(T t) {} } class Bar {} interface Baz {} """.trimIndent() ) runProcessorTest(sources = listOf(src)) { invocation -> val foo = invocation.processingEnv.requireTypeElement("Foo") val constructors = foo.getConstructors() assertThat(constructors).hasSize(1) val constructor = constructors[0] assertThat(constructor.typeParameters).hasSize(1) val t = constructor.typeParameters[0] assertThat(t.name).isEqualTo("T") assertThat(t.typeVariableName.name).isEqualTo("T") assertThat(t.typeVariableName.bounds.map { it.toString() }) .containsExactly("Bar", "Baz") assertThat(t.bounds).hasSize(2) val bound0 = t.bounds[0] assertThat(bound0.asTypeName().java.toString()).isEqualTo("Bar") if (invocation.isKsp) { assertThat(bound0.asTypeName().kotlin.toString()).isEqualTo("Bar") } val bar = invocation.processingEnv.requireType("Bar") assertThat(bound0.isSameType(bar)).isTrue() assertThat(bound0.nullability).isEqualTo(XNullability.UNKNOWN) val bound1 = t.bounds[1] assertThat(bound1.asTypeName().java.toString()).isEqualTo("Baz") if (invocation.isKsp) { assertThat(bound1.asTypeName().kotlin.toString()).isEqualTo("Baz") } val baz = invocation.processingEnv.requireType("Baz") assertThat(bound1.isSameType(baz)).isTrue() assertThat(bound1.nullability).isEqualTo(XNullability.UNKNOWN) assertThat(constructor.parameters).hasSize(1) val parameter = constructor.parameters[0] assertThat(parameter.name).isEqualTo("t") assertThat(parameter.type.asTypeName().java.toString()).isEqualTo("T") if (invocation.isKsp) { assertThat(parameter.type.asTypeName().kotlin.toString()).isEqualTo("T") } } } }
apache-2.0
4147619045aab665d61823add559f7a1
40.404412
95
0.589771
4.599238
false
false
false
false
holisticon/ranked
backend/command/src/main/kotlin/elo/EloMatchSaga.kt
1
3806
@file:Suppress("UNUSED", "PackageDirectoryMismatch") package de.holisticon.ranked.command.elo import de.holisticon.ranked.command.api.ParticipateInMatch import de.holisticon.ranked.command.api.UpdatePlayerRanking import de.holisticon.ranked.model.Team import de.holisticon.ranked.model.UserName import de.holisticon.ranked.model.event.MatchCreated import de.holisticon.ranked.model.event.PlayerParticipatedInMatch import de.holisticon.ranked.model.event.TeamWonMatch import de.holisticon.ranked.service.elo.EloCalculationService import mu.KLogging import org.axonframework.commandhandling.gateway.CommandGateway import org.axonframework.eventhandling.saga.SagaEventHandler import org.axonframework.eventhandling.saga.SagaLifecycle.end import org.axonframework.eventhandling.saga.StartSaga import org.axonframework.spring.stereotype.Saga import org.springframework.beans.factory.annotation.Autowired @Saga class EloMatchSaga { companion object : KLogging() { const val UNSET_ELO = -1 } @Autowired @Transient lateinit var commandGateway: CommandGateway @Autowired @Transient lateinit var eloCalculationService: EloCalculationService private val rankings: MutableMap<UserName, Int> = mutableMapOf() private lateinit var winner: Team private lateinit var looser: Team private lateinit var matchId: String @StartSaga @SagaEventHandler(associationProperty = "matchId") fun on(e: MatchCreated) { this.matchId = e.matchId logger.trace("Elo saga started for match $matchId.") // send commands to players arrayOf(e.teamBlue.player1, e.teamBlue.player2, e.teamRed.player1, e.teamRed.player2) .forEach { // initialize elo rankings[it] = UNSET_ELO // send participation request commandGateway.send<Any>(ParticipateInMatch(userName = it, matchId = matchId)) } } @SagaEventHandler(associationProperty = "matchId") fun on(e: PlayerParticipatedInMatch) { if (rankings.contains(e.player) && e.matchId == matchId) { logger.trace("Player ${e.player} participated in a match ${e.matchId} and had elo ranking ${e.eloRanking}.") rankings[e.player] = e.eloRanking calculateElo() } else { logger.error("Something bad happened on receipt of $e. The player is unknown and unexpected for elo saga $matchId.") } } @SagaEventHandler(associationProperty = "matchId") fun on(e: TeamWonMatch) { this.winner = e.team this.looser = e.looser calculateElo() } fun calculateElo() { // make sure elo is provided and winner and looser are determined if (validateElo()) { logger.trace("Elo saga calculated new rankings for the match $matchId.") val teamResultElo = eloCalculationService.calculateTeamElo( Pair(rankings[winner.player1]!!, rankings[winner.player2]!!), // winner Pair(rankings[looser.player1]!!, rankings[looser.player2]!!) // looser ) commandGateway.send<Any>(UpdatePlayerRanking(userName = winner.player1, matchId = matchId, eloRanking = teamResultElo.first.first)) commandGateway.send<Any>(UpdatePlayerRanking(userName = winner.player2, matchId = matchId, eloRanking = teamResultElo.first.second)) commandGateway.send<Any>(UpdatePlayerRanking(userName = looser.player1, matchId = matchId, eloRanking = teamResultElo.second.first)) commandGateway.send<Any>(UpdatePlayerRanking(userName = looser.player2, matchId = matchId, eloRanking = teamResultElo.second.second)) // end saga end() } } fun validateElo(): Boolean { return ::winner.isInitialized && ::looser.isInitialized && arrayOf(winner.player1, winner.player2, looser.player1, looser.player2).all { player -> rankings.containsKey(player) && rankings[player] != UNSET_ELO } } }
bsd-3-clause
a13bf4ef55f505eb3c8bb76e7daf2416
33.917431
139
0.737257
4.053248
false
false
false
false
GunoH/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/ConvertRangeCheckToTwoComparisonsIntention.kt
2
2543
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.intentions import com.intellij.openapi.editor.Editor import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingOffsetIndependentIntention import org.jetbrains.kotlin.idea.util.RangeKtExpressionType.* import org.jetbrains.kotlin.idea.util.getRangeBinaryExpressionType import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.resolve.calls.util.getType import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode class ConvertRangeCheckToTwoComparisonsIntention : SelfTargetingOffsetIndependentIntention<KtBinaryExpression>( KtBinaryExpression::class.java, KotlinBundle.lazyMessage("convert.to.comparisons") ) { private fun KtExpression?.isSimple() = this is KtConstantExpression || this is KtNameReferenceExpression override fun applyTo(element: KtBinaryExpression, editor: Editor?) { element.replace(convertToComparison(element)?.value ?: return) } override fun isApplicableTo(element: KtBinaryExpression) = convertToComparison(element) != null private fun convertToComparison(element: KtBinaryExpression): Lazy<KtExpression>? { if (element.operationToken != KtTokens.IN_KEYWORD) return null // ignore for-loop. for(x in 1..2) should not be convert to for(1<=x && x<=2) if (element.parent is KtForExpression) return null val rangeExpression = element.right ?: return null val arg = element.left ?: return null val (left, right) = rangeExpression.getArguments() ?: return null val context = lazy { rangeExpression.analyze(BodyResolveMode.PARTIAL) } if (!arg.isSimple() || left?.isSimple() != true || right?.isSimple() != true || setOf(arg.getType(context.value), left.getType(context.value), right.getType(context.value)).size != 1) return null val pattern = when (rangeExpression.getRangeBinaryExpressionType(context)) { RANGE_TO -> "$0 <= $1 && $1 <= $2" UNTIL, RANGE_UNTIL -> "$0 <= $1 && $1 < $2" DOWN_TO -> "$0 >= $1 && $1 >= $2" null -> return null } return lazy { KtPsiFactory(element).createExpressionByPattern(pattern, left, arg, right, reformat = false) } } }
apache-2.0
3cd341f06a24a0468b91de8ed0d8c677
50.918367
158
0.723948
4.477113
false
false
false
false
GunoH/intellij-community
platform/platform-api/src/com/intellij/util/animation/components/BezierPainter.kt
8
5157
// 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.util.animation.components import com.intellij.ui.JBColor import com.intellij.util.animation.Easing import java.awt.* import java.awt.event.MouseAdapter import java.awt.event.MouseEvent import java.awt.geom.CubicCurve2D import java.awt.geom.Point2D import javax.swing.JComponent import kotlin.properties.Delegates import kotlin.reflect.KProperty open class BezierPainter(x1: Double, y1: Double, x2: Double, y2: Double) : JComponent() { private val controlSize = 10 private val gridColor = JBColor(Color(0xF0F0F0), Color(0x313335)) var firstControlPoint: Point2D by Delegates.observable(Point2D.Double(x1, y1), this::fireEvents) var secondControlPoint: Point2D by Delegates.observable(Point2D.Double(x2, y2), this::fireEvents) private fun fireEvents(prop: KProperty<*>, oldValue: Any?, newValue: Any?) { if (oldValue != newValue) { firePropertyChange(prop.name, oldValue, newValue) repaint() } } init { val value = object : MouseAdapter() { var i = 0 override fun mouseDragged(e: MouseEvent) { val point = e.point when (i) { 1 -> firstControlPoint = fromScreenXY(point) 2 -> secondControlPoint = fromScreenXY(point) } repaint() } override fun mouseMoved(e: MouseEvent) = with (e.point ) { i = when { this intersects firstControlPoint -> 1 this intersects secondControlPoint -> 2 else -> 0 } if (i != 0) { cursor = Cursor.getPredefinedCursor(Cursor.HAND_CURSOR) } else { cursor = Cursor.getDefaultCursor() } } private infix fun Point.intersects(point: Point2D) : Boolean { val xy = toScreenXY(point) return xy.x - controlSize / 2 <= x && x <= xy.x + controlSize / 2 && xy.y - controlSize / 2 <= y && y <= xy.y + controlSize / 2 } } addMouseMotionListener(value) addMouseListener(value) minimumSize = Dimension(300, 300) } fun getEasing() : Easing = Easing.bezier(firstControlPoint.x, firstControlPoint.y, secondControlPoint.x, secondControlPoint.y) private fun toScreenXY(point: Point2D) : Point = visibleRect.let { b -> val insets = insets val width = b.width - (insets.left + insets.right) val height = b.height - (insets.top + insets.bottom) return Point((point.x * width + insets.left + b.x).toInt(), height - (point.y * height).toInt() + insets.top + b.y) } private fun fromScreenXY(point: Point) : Point2D.Double = visibleRect.let { b -> val insets = insets val left = insets.left + b.x val top = insets.top + b.y val width = b.width - (insets.left + insets.right) val height = b.height - (insets.top + insets.bottom) val x = (minOf(maxOf(-left, point.x - left), b.width - left).toDouble()) / width val y = (minOf(maxOf(-top, point.y - top), b.height - top).toDouble()) / height return Point2D.Double(x, 1.0 - y) } override fun paintComponent(g: Graphics) { val bounds = visibleRect val insets = insets val x = bounds.x + insets.left val y = bounds.y + insets.top val width = bounds.width - (insets.left + insets.right) val height = bounds.height - (insets.top + insets.bottom) val g2d = g.create() as Graphics2D g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON) g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_SPEED) g2d.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE) g2d.color = JBColor.background() g2d.fillRect(0, 0, bounds.width, bounds.height) g2d.color = gridColor for (i in 0..4) { g2d.drawLine(x + width * i / 4, y, x + width * i / 4, y + height) g2d.drawLine(x,y + height * i / 4, x + width, y + height * i / 4) } val (x0, y0) = toScreenXY(Point2D.Double(0.0, 0.0)) val (x1, y1) = toScreenXY(firstControlPoint) val (x2, y2) = toScreenXY(secondControlPoint) val (x3, y3) = toScreenXY(Point2D.Double(1.0, 1.0)) val bez = CubicCurve2D.Double(x0, y0, x1, y1, x2, y2, x3, y3) g2d.color = JBColor.foreground() g2d.stroke = BasicStroke(2f) g2d.draw(bez) g2d.stroke = BasicStroke(1f) g2d.color = when { isEnabled -> Color(151, 118, 169) JBColor.isBright() -> JBColor.LIGHT_GRAY else -> JBColor.GRAY } g2d.fillOval(x1.toInt() - controlSize / 2, y1.toInt() - controlSize / 2, controlSize, controlSize) g2d.drawLine(x0.toInt(), y0.toInt(), x1.toInt(), y1.toInt()) g2d.color = when { isEnabled -> Color(208, 167, 8) JBColor.isBright() -> JBColor.LIGHT_GRAY else -> JBColor.GRAY } g2d.fillOval(x2.toInt() - controlSize / 2, y2.toInt() - controlSize / 2, controlSize, controlSize) g2d.drawLine(x2.toInt(), y2.toInt(), x3.toInt(), y3.toInt()) g2d.dispose() } private operator fun Point2D.component1() = x private operator fun Point2D.component2() = y }
apache-2.0
b7458d6121e88a6553ced061c2f2d183
36.376812
140
0.652511
3.394997
false
false
false
false
JetBrains/kotlin-native
backend.native/tests/codegen/cycles/cycle.kt
4
400
/* * Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license * that can be found in the LICENSE file. */ package codegen.cycles.cycle import kotlin.test.* fun cycle(cnt: Int): Int { var sum = 1 while (sum == cnt) { sum = sum + 1 } return sum } @Test fun runTest() { if (cycle(1) != 2) throw Error() if (cycle(0) != 1) throw Error() }
apache-2.0
54935c6ba510143f2cf2c2363a97ea73
18.047619
101
0.63
3.076923
false
true
false
false
Cognifide/gradle-aem-plugin
src/main/kotlin/com/cognifide/gradle/aem/common/instance/service/osgi/ComponentState.kt
1
2159
package com.cognifide.gradle.aem.common.instance.service.osgi import com.cognifide.gradle.aem.common.instance.Instance import com.cognifide.gradle.common.utils.Patterns import com.fasterxml.jackson.annotation.JsonIgnore import com.fasterxml.jackson.annotation.JsonIgnoreProperties import com.fasterxml.jackson.annotation.JsonProperty import org.apache.commons.lang3.builder.EqualsBuilder import org.apache.commons.lang3.builder.HashCodeBuilder @JsonIgnoreProperties(ignoreUnknown = true) class ComponentState private constructor() { @JsonIgnore lateinit var instance: Instance @JsonProperty("data") lateinit var components: List<Component> @JsonProperty("status") var total: Int = 0 @get:JsonIgnore val unknown: Boolean get() = components.isEmpty() fun check(pids: Collection<String>, predicate: (Component) -> Boolean): Boolean { return !unknown && find(pids, listOf()).all(predicate) } fun check(pids: Collection<String>, ignoredPids: Collection<String>, predicate: (Component) -> Boolean): Boolean { return !unknown && find(pids, ignoredPids).all(predicate) } fun find(pids: Collection<String>): List<Component> = find(pids, listOf()) fun find(pids: Collection<String>, ignoredPids: Collection<String>): List<Component> = components.filter { Patterns.wildcard(it.uid, pids) && !Patterns.wildcard(it.uid, ignoredPids) } override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as ComponentState return EqualsBuilder() .append(components, other.components) .append(total, other.total) .isEquals } override fun hashCode(): Int = HashCodeBuilder() .append(components) .append(total) .toHashCode() override fun toString(): String = "ComponentState(instance='${instance.name}', total='$total')" companion object { fun unknown(): ComponentState = ComponentState().apply { components = listOf() total = 0 } } }
apache-2.0
4c0edc0c684869d5ce957ef57b0e4f00
32.215385
118
0.678555
4.397149
false
false
false
false
blan4/MangaReader
app/src/main/java/org/seniorsigan/mangareader/ui/ChaptersActivity.kt
1
991
package org.seniorsigan.mangareader.ui import android.os.Bundle import android.support.v7.app.AppCompatActivity import org.seniorsigan.mangareader.INTENT_MANGA import org.seniorsigan.mangareader.R import org.seniorsigan.mangareader.models.MangaItem import org.seniorsigan.mangareader.ui.fragments.ChapterListFragment class ChaptersActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_chapters) val manga = intent.getSerializableExtra(INTENT_MANGA) as MangaItem? if (savedInstanceState == null) { val chapterListFragment = ChapterListFragment() chapterListFragment.arguments = intent.extras chapterListFragment.arguments.putSerializable(ChapterListFragment.mangaItemArgument, manga) supportFragmentManager.beginTransaction().add(R.id.fragments_container, chapterListFragment).commit() } } }
mit
461e3b1cb92fe726420b767868f0fae8
40.291667
113
0.765893
5.082051
false
false
false
false
tooploox/android-versioning-plugin
src/main/kotlin/versioning/model/RevisionVersionInfo.kt
1
873
package versioning.model import versioning.Constants data class RevisionVersionInfo( val lastVersion: Version, val commitsSinceLastTag: Int, // 0 if we're on tag, -1 if there's no previous tag val currentRevisionSha: String? ) { companion object { @JvmStatic fun fromGitDescribe(description: String?): RevisionVersionInfo { if (description == null) { return RevisionVersionInfo(Version.getDefault(), -1, null) } val parts = description.replace(Constants.TAG_PREFIX, "").split("-") return RevisionVersionInfo( Version.fromString(parts[0]), parts.getOrNull(1)?.toInt() ?: 0, parts.getOrNull(2)?.substring(1) ) } } fun hasVersionTag(): Boolean = commitsSinceLastTag == 0 }
apache-2.0
26d1c773f0359f9be4c14b535dd16f68
28.1
89
0.584192
4.877095
false
false
false
false