repo_name
stringlengths 7
81
| path
stringlengths 6
242
| copies
stringclasses 55
values | size
stringlengths 2
6
| content
stringlengths 55
737k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 5.44
99.8
| line_max
int64 15
979
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.93
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
vanita5/twittnuker | twittnuker/src/main/kotlin/de/vanita5/twittnuker/fragment/filter/FiltersFragment.kt | 1 | 2014 | /*
* Twittnuker - Twitter client for Android
*
* Copyright (C) 2013-2017 vanita5 <[email protected]>
*
* This program incorporates a modified version of Twidere.
* Copyright (C) 2012-2017 Mariotaku Lee <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.vanita5.twittnuker.fragment.filter
import android.os.Bundle
import de.vanita5.twittnuker.R
import de.vanita5.twittnuker.adapter.SupportTabsAdapter
import de.vanita5.twittnuker.fragment.AbsToolbarTabPagesFragment
class FiltersFragment : AbsToolbarTabPagesFragment() {
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
setHasOptionsMenu(true)
}
override fun addTabs(adapter: SupportTabsAdapter) {
adapter.add(cls = FilteredUsersFragment::class.java, name = getString(R.string.filter_type_users), tag = "users")
adapter.add(cls = FilteredKeywordsFragment::class.java, name = getString(R.string.filter_type_keywords), tag = "keywords")
adapter.add(cls = FilteredSourcesFragment::class.java, name = getString(R.string.filter_type_sources), tag = "sources")
adapter.add(cls = FilteredLinksFragment::class.java, name = getString(R.string.filter_type_links), tag = "links")
adapter.add(cls = FilterSettingsFragment::class.java, name = getString(R.string.action_settings), tag = "settings")
}
} | gpl-3.0 | 052f13f98e2033e984de7f67db5e2c1b | 42.804348 | 130 | 0.74429 | 4.052314 | false | false | false | false |
AndroidX/androidx | compose/material/material/samples/src/main/java/androidx/compose/material/samples/BottomNavigationSamples.kt | 3 | 2290 | /*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.material.samples
import androidx.annotation.Sampled
import androidx.compose.material.BottomNavigation
import androidx.compose.material.BottomNavigationItem
import androidx.compose.material.Icon
import androidx.compose.material.Text
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Favorite
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
@Sampled
@Composable
fun BottomNavigationSample() {
var selectedItem by remember { mutableStateOf(0) }
val items = listOf("Songs", "Artists", "Playlists")
BottomNavigation {
items.forEachIndexed { index, item ->
BottomNavigationItem(
icon = { Icon(Icons.Filled.Favorite, contentDescription = null) },
label = { Text(item) },
selected = selectedItem == index,
onClick = { selectedItem = index }
)
}
}
}
@Composable
fun BottomNavigationWithOnlySelectedLabelsSample() {
var selectedItem by remember { mutableStateOf(0) }
val items = listOf("Songs", "Artists", "Playlists")
BottomNavigation {
items.forEachIndexed { index, item ->
BottomNavigationItem(
icon = { Icon(Icons.Filled.Favorite, contentDescription = null) },
label = { Text(item) },
selected = selectedItem == index,
onClick = { selectedItem = index },
alwaysShowLabel = false
)
}
}
}
| apache-2.0 | 324f13a11af9c39156df479a6d4d5a9d | 33.69697 | 82 | 0.689083 | 4.790795 | false | false | false | false |
Nunnery/MythicDrops | src/main/kotlin/com/tealcube/minecraft/bukkit/mythicdrops/enchantments/MythicCustomEnchantmentRegistry.kt | 1 | 3554 | /*
* This file is part of MythicDrops, licensed under the MIT License.
*
* Copyright (C) 2020 Richard Harrah
*
* 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.tealcube.minecraft.bukkit.mythicdrops.enchantments
import com.tealcube.minecraft.bukkit.mythicdrops.api.enchantments.CustomEnchantmentRegistry
import org.bukkit.Material
import org.bukkit.NamespacedKey
import org.bukkit.enchantments.Enchantment
import org.bukkit.enchantments.EnchantmentTarget
import org.bukkit.plugin.Plugin
class MythicCustomEnchantmentRegistry(plugin: Plugin) : CustomEnchantmentRegistry {
private val customEnchantmentMap: Map<String, Enchantment>
init {
// have to do this because they removed the ALL EnchantmentTarget in 1.16
val glowEnchantments = EnchantmentTarget.values().mapNotNull {
if (it.name == "ALL") return@mapNotNull null // ensure this works on < 1.16
val enchantmentName = "${CustomEnchantmentRegistry.GLOW}-${it.name}"
val namespacedKey = NamespacedKey(plugin, enchantmentName)
val glowEnchantment = GlowEnchantment(namespacedKey, it)
enchantmentName to glowEnchantment
}
customEnchantmentMap = glowEnchantments.toMap()
}
override fun getCustomEnchantmentByKey(key: String, material: Material): Enchantment? {
val enchantmentTargets = EnchantmentTarget.values().filter { it.includes(material) }
val potentialEnchantmentKeys = enchantmentTargets.map { "$key-${it.name}" }
// Find the first enchantment key that matches and return that
for (enchantmentKey in potentialEnchantmentKeys) {
val enchantment = customEnchantmentMap[enchantmentKey]
if (enchantment != null) {
return enchantment
}
}
// otherwise null
return null
}
override fun registerEnchantments() {
customEnchantmentMap.values.forEach { registerEnchantment(it) }
}
private fun registerEnchantment(enchantment: Enchantment) {
if (Enchantment.getByKey(enchantment.key) != null) {
return
}
try {
val f = Enchantment::class.java.getDeclaredField("acceptingNew")
f.isAccessible = true
f[null] = true
} catch (ignored: Exception) {
}
try {
Enchantment.registerEnchantment(enchantment)
} catch (ignored: IllegalStateException) {
} catch (ignored: IllegalArgumentException) {
}
}
}
| mit | 12179e5f71dbfd3f1e30654ccb0b335b | 42.876543 | 105 | 0.705684 | 4.881868 | false | false | false | false |
hannesa2/owncloud-android | owncloudApp/src/main/java/com/owncloud/android/ui/activity/FileDisplayActivity.kt | 1 | 70189 | /**
* ownCloud Android client application
*
* @author Bartek Przybylski
* @author David A. Velasco
* @author David González Verdugo
* @author Christian Schabesberger
* @author Shashvat Kedia
* @author Abel García de Prada
* Copyright (C) 2011 Bartek Przybylski
* Copyright (C) 2020 ownCloud GmbH.
*
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2,
* as published by the Free Software Foundation.
*
*
* 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:></http:>//www.gnu.org/licenses/>.
*/
package com.owncloud.android.ui.activity
import android.accounts.Account
import android.accounts.AuthenticatorException
import android.app.Activity
import android.content.BroadcastReceiver
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.content.ServiceConnection
import android.content.res.Resources.NotFoundException
import android.net.Uri
import android.os.Bundle
import android.os.IBinder
import android.view.Menu
import android.view.MenuItem
import android.view.View
import androidx.core.view.isVisible
import androidx.fragment.app.Fragment
import androidx.localbroadcastmanager.content.LocalBroadcastManager
import com.owncloud.android.AppRater
import com.owncloud.android.BuildConfig
import com.owncloud.android.MainApp
import com.owncloud.android.R
import com.owncloud.android.databinding.ActivityMainBinding
import com.owncloud.android.datamodel.FileDataStorageManager
import com.owncloud.android.datamodel.OCFile
import com.owncloud.android.extensions.checkPasscodeEnforced
import com.owncloud.android.extensions.manageOptionLockSelected
import com.owncloud.android.extensions.showMessageInSnackbar
import com.owncloud.android.files.services.FileDownloader
import com.owncloud.android.files.services.FileDownloader.FileDownloaderBinder
import com.owncloud.android.files.services.FileUploader
import com.owncloud.android.files.services.FileUploader.FileUploaderBinder
import com.owncloud.android.files.services.TransferRequester
import com.owncloud.android.interfaces.ISecurityEnforced
import com.owncloud.android.interfaces.LockType
import com.owncloud.android.lib.common.authentication.OwnCloudBearerCredentials
import com.owncloud.android.lib.common.operations.RemoteOperation
import com.owncloud.android.lib.common.operations.RemoteOperationResult
import com.owncloud.android.lib.common.operations.RemoteOperationResult.ResultCode
import com.owncloud.android.lib.resources.status.OwnCloudVersion
import com.owncloud.android.operations.CopyFileOperation
import com.owncloud.android.operations.CreateFolderOperation
import com.owncloud.android.operations.MoveFileOperation
import com.owncloud.android.operations.RefreshFolderOperation
import com.owncloud.android.operations.RemoveFileOperation
import com.owncloud.android.operations.RenameFileOperation
import com.owncloud.android.operations.SynchronizeFileOperation
import com.owncloud.android.operations.UploadFileOperation
import com.owncloud.android.presentation.ui.security.bayPassUnlockOnce
import com.owncloud.android.syncadapter.FileSyncAdapter
import com.owncloud.android.ui.errorhandling.ErrorMessageAdapter
import com.owncloud.android.ui.fragment.FileDetailFragment
import com.owncloud.android.ui.fragment.FileFragment
import com.owncloud.android.ui.fragment.OCFileListFragment
import com.owncloud.android.ui.fragment.TaskRetainerFragment
import com.owncloud.android.ui.helpers.FilesUploadHelper
import com.owncloud.android.ui.helpers.UriUploader
import com.owncloud.android.ui.preview.PreviewAudioFragment
import com.owncloud.android.ui.preview.PreviewImageActivity
import com.owncloud.android.ui.preview.PreviewImageFragment
import com.owncloud.android.ui.preview.PreviewTextFragment
import com.owncloud.android.ui.preview.PreviewVideoActivity
import com.owncloud.android.ui.preview.PreviewVideoFragment
import com.owncloud.android.utils.Extras
import com.owncloud.android.utils.PreferenceUtils
import info.hannes.cvscanner.CVScanner
import info.hannes.github.AppUpdateHelper
import info.hannes.liveedgedetection.ScanConstants
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
import timber.log.Timber
import java.io.File
import kotlin.coroutines.CoroutineContext
/**
* Displays, what files the user has available in his ownCloud. This is the main view.
*/
class FileDisplayActivity : FileActivity(), FileFragment.ContainerActivity, OnEnforceableRefreshListener,
CoroutineScope, ISecurityEnforced {
private val job = Job()
override val coroutineContext: CoroutineContext
get() = job + Dispatchers.Main
private var syncBroadcastReceiver: SyncBroadcastReceiver? = null
private var uploadBroadcastReceiver: UploadBroadcastReceiver? = null
private var downloadBroadcastReceiver: DownloadBroadcastReceiver? = null
private var lastSslUntrustedServerResult: RemoteOperationResult<*>? = null
private var leftFragmentContainer: View? = null
private var rightFragmentContainer: View? = null
private var selectAllMenuItem: MenuItem? = null
private var mainMenu: Menu? = null
private var fileWaitingToPreview: OCFile? = null
private var syncInProgress = false
private var fileListOption = FileListOption.ALL_FILES
private var waitingToSend: OCFile? = null
private var waitingToOpen: OCFile? = null
private var localBroadcastManager: LocalBroadcastManager? = null
var filesUploadHelper: FilesUploadHelper? = null
internal set
private val listOfFilesFragment: OCFileListFragment?
get() = supportFragmentManager.findFragmentByTag(TAG_LIST_OF_FILES) as OCFileListFragment?
private val secondFragment: FileFragment?
get() = supportFragmentManager.findFragmentByTag(TAG_SECOND_FRAGMENT) as FileFragment?
private val isFabOpen: Boolean
get() = listOfFilesFragment?.fabMain?.isExpanded ?: false
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
Timber.v("onCreate() start")
super.onCreate(savedInstanceState) // this calls onAccountChanged() when ownCloud Account is valid
checkPasscodeEnforced(this)
localBroadcastManager = LocalBroadcastManager.getInstance(this)
/// Load of saved instance state
if (savedInstanceState != null) {
Timber.d(savedInstanceState.toString())
fileWaitingToPreview = savedInstanceState.getParcelable(KEY_WAITING_TO_PREVIEW)
syncInProgress = savedInstanceState.getBoolean(KEY_SYNC_IN_PROGRESS)
waitingToSend = savedInstanceState.getParcelable(KEY_WAITING_TO_SEND)
filesUploadHelper = savedInstanceState.getParcelable(KEY_UPLOAD_HELPER)
fileListOption =
savedInstanceState.getParcelable(KEY_FILE_LIST_OPTION) as? FileListOption ?: FileListOption.ALL_FILES
if (account != null) {
filesUploadHelper?.init(this, account.name)
}
} else {
fileWaitingToPreview = null
syncInProgress = false
waitingToSend = null
fileListOption =
intent.getParcelableExtra(EXTRA_FILE_LIST_OPTION) as? FileListOption ?: FileListOption.ALL_FILES
filesUploadHelper = FilesUploadHelper(
this,
if (account == null) "" else account.name
)
}
/// USER INTERFACE
// Inflate and set the layout view
binding = ActivityMainBinding.inflate(layoutInflater)
val view = binding.root
setContentView(view)
// setup toolbar
setupRootToolbar(
isSearchEnabled = true,
title = getString(R.string.default_display_name_for_root_folder),
)
// setup drawer
setupDrawer()
setupNavigationBottomBar(getMenuItemForFileListOption(fileListOption))
leftFragmentContainer = findViewById(R.id.left_fragment_container)
rightFragmentContainer = findViewById(R.id.right_fragment_container)
// Init Fragment without UI to retain AsyncTask across configuration changes
val fm = supportFragmentManager
var taskRetainerFragment =
fm.findFragmentByTag(TaskRetainerFragment.FTAG_TASK_RETAINER_FRAGMENT) as TaskRetainerFragment?
if (taskRetainerFragment == null) {
taskRetainerFragment = TaskRetainerFragment()
fm.beginTransaction()
.add(taskRetainerFragment, TaskRetainerFragment.FTAG_TASK_RETAINER_FRAGMENT).commit()
} // else, Fragment already created and retained across configuration change
Timber.v("onCreate() end")
if (resources.getBoolean(R.bool.enable_rate_me_feature) && !BuildConfig.DEBUG) {
AppRater.appLaunched(this, packageName)
}
AppUpdateHelper.checkForNewVersion(
this,
BuildConfig.GIT_REPOSITORY,
BuildConfig.VERSION_NAME
)
}
override fun onPostCreate(savedInstanceState: Bundle?) {
super.onPostCreate(savedInstanceState)
if (savedInstanceState == null) {
createMinFragments()
}
setBackgroundText()
}
/**
* Called when the ownCloud [Account] associated to the Activity was just updated.
*/
override fun onAccountSet(stateWasRecovered: Boolean) {
super.onAccountSet(stateWasRecovered)
if (account != null) {
/// Check whether the 'main' OCFile handled by the Activity is contained in the
// current Account
var file: OCFile? = file
// get parent from path
val parentPath: String
if (file != null) {
if (file.isDown && file.lastSyncDateForProperties == 0L) {
// upload in progress - right now, files are not inserted in the local
// cache until the upload is successful get parent from path
parentPath = file.remotePath.substring(
0,
file.remotePath.lastIndexOf(file.fileName)
)
if (storageManager.getFileByPath(parentPath) == null) {
file = null // not able to know the directory where the file is uploading
}
} else {
file = storageManager.getFileByPath(file.remotePath)
// currentDir = null if not in the current Account
}
}
if (file == null) {
// fall back to root folder
file = storageManager.getFileByPath(OCFile.ROOT_PATH) // never returns null
}
setFile(file)
if (mAccountWasSet) {
setAccountInDrawer(account)
}
if (!stateWasRecovered) {
Timber.d("Initializing Fragments in onAccountChanged..")
initFragmentsWithFile()
file?.isFolder?.let { isFolder ->
if (isFolder) {
startSyncFolderOperation(file, false)
}
}
} else {
file?.isFolder?.let { isFolder ->
updateFragmentsVisibility(!isFolder)
updateToolbar(if (isFolder) null else file)
}
}
}
}
private fun createMinFragments() {
val listOfFiles = OCFileListFragment.newInstance(false, fileListOption, false, false, true)
listOfFiles.setSearchListener(findViewById(R.id.root_toolbar_search_view))
val transaction = supportFragmentManager.beginTransaction()
transaction.add(R.id.left_fragment_container, listOfFiles, TAG_LIST_OF_FILES)
transaction.commit()
}
private fun initFragmentsWithFile() {
if (account != null && file != null) {
/// First fragment
listOfFilesFragment?.listDirectory(currentDir)
?: Timber.e("Still have a chance to lose the initialization of list fragment >(")
/// Second fragment
val file = file
val secondFragment = chooseInitialSecondFragment(file)
secondFragment?.let {
setSecondFragment(it)
updateFragmentsVisibility(true)
updateToolbar(file)
} ?: cleanSecondFragment()
} else {
Timber.e("initFragmentsWithFile() called with invalid nulls! account is $account, file is $file")
}
}
/**
* Choose the second fragment that is going to be shown
*
* @param file used to decide which fragment should be chosen
* @return a new second fragment instance if it has not been chosen before, or the fragment
* previously chosen otherwise
*/
private fun chooseInitialSecondFragment(file: OCFile?): Fragment? {
var secondFragment = supportFragmentManager.findFragmentByTag(TAG_SECOND_FRAGMENT)
if (secondFragment == null) { // If second fragment has not been chosen yet, choose it
if (file != null && !file.isFolder) {
if ((PreviewAudioFragment.canBePreviewed(file) || PreviewVideoFragment.canBePreviewed(file)) && file.lastSyncDateForProperties > 0 // temporal fix
) {
val startPlaybackPosition = intent.getIntExtra(PreviewVideoActivity.EXTRA_START_POSITION, 0)
val autoplay = intent.getBooleanExtra(PreviewVideoActivity.EXTRA_AUTOPLAY, true)
if (PreviewAudioFragment.canBePreviewed(file)) {
secondFragment = PreviewAudioFragment.newInstance(
file,
account,
startPlaybackPosition,
autoplay
)
} else {
secondFragment = PreviewVideoFragment.newInstance(
file,
account,
startPlaybackPosition,
autoplay
)
}
} else if (PreviewTextFragment.canBePreviewed(file)) {
secondFragment = PreviewTextFragment.newInstance(
file,
account
)
} else {
secondFragment = FileDetailFragment.newInstance(file, account)
}
}
}
return secondFragment
}
/**
* Replaces the second fragment managed by the activity with the received as
* a parameter.
*
*
* Assumes never will be more than two fragments managed at the same time.
*
* @param fragment New second Fragment to set.
*/
private fun setSecondFragment(fragment: Fragment) {
val transaction = supportFragmentManager.beginTransaction()
transaction.replace(R.id.right_fragment_container, fragment, TAG_SECOND_FRAGMENT)
transaction.commit()
}
fun showBottomNavBar(show: Boolean) {
binding.navCoordinatorLayout.bottomNavView.isVisible = show
}
private fun updateFragmentsVisibility(existsSecondFragment: Boolean) {
if (existsSecondFragment) {
if (leftFragmentContainer?.visibility != View.GONE) {
leftFragmentContainer?.visibility = View.GONE
}
if (rightFragmentContainer?.visibility != View.VISIBLE) {
rightFragmentContainer?.visibility = View.VISIBLE
}
showBottomNavBar(show = false)
} else {
if (leftFragmentContainer?.visibility != View.VISIBLE) {
leftFragmentContainer?.visibility = View.VISIBLE
showBottomNavBar(show = true)
}
if (rightFragmentContainer?.visibility != View.GONE) {
rightFragmentContainer?.visibility = View.GONE
}
}
}
private fun cleanSecondFragment() {
val second = secondFragment
if (second != null) {
val tr = supportFragmentManager.beginTransaction()
tr.remove(second)
tr.commit()
}
updateFragmentsVisibility(false)
updateToolbar(null)
}
fun refreshListOfFilesFragment(reloadData: Boolean) {
val fileListFragment = listOfFilesFragment
fileListFragment?.listDirectory(reloadData)
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
val inflater = menuInflater
// Allow or disallow touches with other visible windows
val actionBarView = findViewById<View>(R.id.action_bar)
if (actionBarView != null) {
actionBarView.filterTouchesWhenObscured =
PreferenceUtils.shouldDisallowTouchesWithOtherVisibleWindows(applicationContext)
}
inflater.inflate(R.menu.main_menu, menu)
selectAllMenuItem = menu.findItem(R.id.action_select_all)
if (secondFragment == null) {
selectAllMenuItem?.isVisible = true
} else {
val shareFileMenuItem = menu.findItem(R.id.action_share_current_folder)
menu.removeItem(shareFileMenuItem.itemId)
}
mainMenu = menu
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.action_select_all -> {
listOfFilesFragment?.selectAll()
}
android.R.id.home -> {
val second = secondFragment
val currentDir = currentDir
val inRootFolder = currentDir != null && currentDir.parentId == 0L
val fileFragmentVisible = second != null && second.file != null
if (!inRootFolder || fileFragmentVisible) {
onBackPressed()
} else if (isDrawerOpen()) {
closeDrawer()
} else {
openDrawer()
}
}
}
return super.onOptionsItemSelected(item)
}
/**
* Called, when the user selected something for uploading
*/
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
bayPassUnlockOnce()
// Handle calls form internal activities.
if (requestCode == REQUEST_CODE__SELECT_CONTENT_FROM_APPS && (resultCode == Activity.RESULT_OK || resultCode == RESULT_OK_AND_MOVE)) {
requestUploadOfContentFromApps(data, resultCode)
} else if (requestCode == REQUEST_CODE__UPLOAD_FROM_CAMERA) {
if (resultCode == Activity.RESULT_OK || resultCode == RESULT_OK_AND_MOVE) {
filesUploadHelper?.onActivityResult(object : FilesUploadHelper.OnCheckAvailableSpaceListener {
override fun onCheckAvailableSpaceStart() {
}
override fun onCheckAvailableSpaceFinished(
hasEnoughSpace: Boolean,
capturedFilePaths: Array<String>
) {
if (hasEnoughSpace) {
requestUploadOfFilesFromFileSystem(capturedFilePaths, FileUploader.LOCAL_BEHAVIOUR_MOVE)
}
}
})
} else if (requestCode == Activity.RESULT_CANCELED) {
filesUploadHelper?.deleteImageFile()
}
// requestUploadOfFilesFromFileSystem(data,resultCode);
} else if (requestCode == REQUEST_CODE__UPLOAD_SCANNED_DOCUMENT) {
if (resultCode == RESULT_OK) {
val scannedDocumentPath = data?.getStringExtra(CVScanner.RESULT_IMAGE_PATH)
filesUploadHelper!!.onActivityResult(
scannedDocumentPath,
object : FilesUploadHelper.OnCheckAvailableSpaceListener {
override fun onCheckAvailableSpaceStart() = Unit
override fun onCheckAvailableSpaceFinished(
hasEnoughSpace: Boolean,
capturedFilePaths: Array<String>
) {
if (hasEnoughSpace) {
requestUploadOfFilesFromFileSystem(capturedFilePaths, FileUploader.LOCAL_BEHAVIOUR_MOVE)
}
}
})
}
} else if (requestCode == REQUEST_CODE__UPLOAD_LIVEDGE_DOCUMENT) {
if (resultCode == RESULT_OK) {
data?.extras?.let { bundle ->
val scannedDocumentPath = bundle.getString(ScanConstants.SCANNED_RESULT)
filesUploadHelper!!.onActivityResult(scannedDocumentPath,
object : FilesUploadHelper.OnCheckAvailableSpaceListener {
override fun onCheckAvailableSpaceStart() = Unit
override fun onCheckAvailableSpaceFinished(
hasEnoughSpace: Boolean,
capturedFilePaths: Array<String>
) {
if (hasEnoughSpace) {
requestUploadOfFilesFromFileSystem(
capturedFilePaths,
FileUploader.LOCAL_BEHAVIOUR_MOVE
)
}
}
})
}
}
} else if (requestCode == REQUEST_CODE__MOVE_FILES && resultCode == Activity.RESULT_OK) {
handler.postDelayed(
{ requestMoveOperation(data!!) },
DELAY_TO_REQUEST_OPERATIONS_LATER
)
} else if (requestCode == REQUEST_CODE__COPY_FILES && resultCode == Activity.RESULT_OK) {
handler.postDelayed(
{ requestCopyOperation(data!!) },
DELAY_TO_REQUEST_OPERATIONS_LATER
)
} else {
super.onActivityResult(requestCode, resultCode, data)
}
}
private fun requestUploadOfFilesFromFileSystem(filePaths: Array<String>?, behaviour: Int) {
if (filePaths != null) {
val remotePaths = arrayOfNulls<String>(filePaths.size)
val remotePathBase = currentDir?.remotePath
for (j in remotePaths.indices) {
remotePaths[j] = remotePathBase + File(filePaths[j]).name
}
val requester = TransferRequester()
requester.uploadNewFiles(
this,
account,
filePaths,
remotePaths, null, // MIME type will be detected from file name
behaviour,
false, // do not create parent folder if not existent
UploadFileOperation.CREATED_BY_USER
)
} else {
Timber.d("User clicked on 'Update' with no selection")
showMessageInSnackbar(R.id.list_layout, getString(R.string.filedisplay_no_file_selected))
}
}
private fun requestUploadOfContentFromApps(contentIntent: Intent?, resultCode: Int) {
val streamsToUpload = ArrayList<Uri>()
if (contentIntent!!.clipData != null && contentIntent.clipData!!.itemCount > 0) {
for (i in 0 until contentIntent.clipData!!.itemCount) {
streamsToUpload.add(contentIntent.clipData!!.getItemAt(i).uri)
}
} else {
streamsToUpload.add(contentIntent.data!!)
}
val behaviour = if (resultCode == RESULT_OK_AND_MOVE)
FileUploader.LOCAL_BEHAVIOUR_MOVE
else
FileUploader.LOCAL_BEHAVIOUR_COPY
val currentDir = currentDir
val remotePath = if (currentDir != null) currentDir.remotePath else OCFile.ROOT_PATH
val uploader = UriUploader(
this,
streamsToUpload,
remotePath,
account,
behaviour,
false, null// Not needed copy temp task listener
)// Not show waiting dialog while file is being copied from private storage
uploader.uploadUris()
}
/**
* Request the operation for moving the file/folder from one path to another
*
* @param data Intent received
*/
private fun requestMoveOperation(data: Intent) {
val folderToMoveAt = data.getParcelableExtra<OCFile>(FolderPickerActivity.EXTRA_FOLDER)
val files = data.getParcelableArrayListExtra<OCFile>(FolderPickerActivity.EXTRA_FILES)
fileOperationsHelper.moveFiles(files, folderToMoveAt)
}
/**
* Request the operation for copying the file/folder from one path to another
*
* @param data Intent received
*/
private fun requestCopyOperation(data: Intent) {
val folderToMoveAt = data.getParcelableExtra<OCFile>(FolderPickerActivity.EXTRA_FOLDER)
val files = data.getParcelableArrayListExtra<OCFile>(FolderPickerActivity.EXTRA_FILES)
fileOperationsHelper.copyFiles(files, folderToMoveAt)
}
override fun onBackPressed() {
val isFabOpen = isFabOpen
/*
* BackPressed priority/hierarchy:
* 1. close drawer if opened
* 2. close FAB if open (only if drawer isn't open)
* 3. navigate up (only if drawer and FAB aren't open)
*/
if (isDrawerOpen() && isFabOpen) {
// close drawer first
super.onBackPressed()
} else if (isDrawerOpen() && !isFabOpen) {
// close drawer
super.onBackPressed()
} else if (!isDrawerOpen() && isFabOpen) {
// close fab
listOfFilesFragment?.fabMain?.collapse()
} else {
// all closed
val listOfFiles = listOfFilesFragment
if (secondFragment == null) {
val currentDir = currentDir
if (currentDir == null || currentDir.parentId == FileDataStorageManager.ROOT_PARENT_ID.toLong()) {
finish()
return
}
listOfFiles?.onBrowseUp()
}
if (listOfFiles != null) { // should never be null, indeed
file = listOfFiles.currentFile
listOfFiles.listDirectory(false)
}
cleanSecondFragment()
}
}
override fun onSaveInstanceState(outState: Bundle) {
// responsibility of restore is preferred in onCreate() before than in
// onRestoreInstanceState when there are Fragments involved
Timber.v("onSaveInstanceState() start")
super.onSaveInstanceState(outState)
outState.putParcelable(KEY_WAITING_TO_PREVIEW, fileWaitingToPreview)
outState.putBoolean(KEY_SYNC_IN_PROGRESS, syncInProgress)
outState.putParcelable(KEY_FILE_LIST_OPTION, fileListOption)
//outState.putBoolean(KEY_REFRESH_SHARES_IN_PROGRESS,
// mRefreshSharesInProgress);
outState.putParcelable(KEY_WAITING_TO_SEND, waitingToSend)
outState.putParcelable(KEY_UPLOAD_HELPER, filesUploadHelper)
Timber.v("onSaveInstanceState() end")
}
override fun onResume() {
Timber.v("onResume() start")
super.onResume()
setCheckedItemAtBottomBar(getMenuItemForFileListOption(fileListOption))
// refresh list of files
refreshListOfFilesFragment(true)
// Listen for sync messages
val syncIntentFilter = IntentFilter(FileSyncAdapter.EVENT_FULL_SYNC_START)
syncIntentFilter.addAction(FileSyncAdapter.EVENT_FULL_SYNC_END)
syncIntentFilter.addAction(FileSyncAdapter.EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED)
syncIntentFilter.addAction(RefreshFolderOperation.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED)
syncIntentFilter.addAction(RefreshFolderOperation.EVENT_SINGLE_FOLDER_SHARES_SYNCED)
syncBroadcastReceiver = SyncBroadcastReceiver()
localBroadcastManager!!.registerReceiver(syncBroadcastReceiver!!, syncIntentFilter)
// Listen for upload messages
val uploadIntentFilter = IntentFilter(FileUploader.getUploadFinishMessage())
uploadIntentFilter.addAction(FileUploader.getUploadStartMessage())
uploadBroadcastReceiver = UploadBroadcastReceiver()
localBroadcastManager!!.registerReceiver(uploadBroadcastReceiver!!, uploadIntentFilter)
// Listen for download messages
val downloadIntentFilter = IntentFilter(
FileDownloader.getDownloadAddedMessage()
)
downloadIntentFilter.addAction(FileDownloader.getDownloadFinishMessage())
downloadBroadcastReceiver = DownloadBroadcastReceiver()
localBroadcastManager!!.registerReceiver(downloadBroadcastReceiver!!, downloadIntentFilter)
Timber.v("onResume() end")
}
override fun onPause() {
Timber.v("onPause() start")
if (syncBroadcastReceiver != null) {
localBroadcastManager!!.unregisterReceiver(syncBroadcastReceiver!!)
syncBroadcastReceiver = null
}
if (uploadBroadcastReceiver != null) {
localBroadcastManager!!.unregisterReceiver(uploadBroadcastReceiver!!)
uploadBroadcastReceiver = null
}
if (downloadBroadcastReceiver != null) {
localBroadcastManager!!.unregisterReceiver(downloadBroadcastReceiver!!)
downloadBroadcastReceiver = null
}
super.onPause()
Timber.v("onPause() end")
}
private inner class SyncBroadcastReceiver : BroadcastReceiver() {
/**
* [BroadcastReceiver] to enable syncing feedback in UI
*/
override fun onReceive(context: Context, intent: Intent) {
val event = intent.action
Timber.d("Received broadcast $event")
val accountName = intent.getStringExtra(FileSyncAdapter.EXTRA_ACCOUNT_NAME)
val synchFolderRemotePath = intent.getStringExtra(FileSyncAdapter.EXTRA_FOLDER_PATH)
val serverVersion = intent.getParcelableExtra<OwnCloudVersion>(FileSyncAdapter.EXTRA_SERVER_VERSION)
if (serverVersion != null && !serverVersion.isServerVersionSupported) {
Timber.d("Server version not supported")
showRequestAccountChangeNotice(getString(R.string.server_not_supported), true)
}
val synchResult = intent.getSerializableExtra(FileSyncAdapter.EXTRA_RESULT) as? RemoteOperationResult<*>
val sameAccount = account != null && accountName == account.name && storageManager != null
if (sameAccount) {
if (FileSyncAdapter.EVENT_FULL_SYNC_START == event) {
syncInProgress = true
} else {
var currentFile: OCFile? = if (file == null)
null
else
storageManager.getFileByPath(file.remotePath)
val currentDir = if (currentDir == null)
null
else
storageManager.getFileByPath(currentDir!!.remotePath)
if (currentDir == null) {
// current folder was removed from the server
showMessageInSnackbar(
R.id.list_layout,
String.format(
getString(R.string.sync_current_folder_was_removed),
synchFolderRemotePath
)
)
browseToRoot()
} else {
if (currentFile == null && !file.isFolder) {
// currently selected file was removed in the server, and now we
// know it
cleanSecondFragment()
currentFile = currentDir
}
if (synchFolderRemotePath != null && currentDir.remotePath == synchFolderRemotePath) {
val fileListFragment = listOfFilesFragment
fileListFragment?.listDirectory(true)
}
file = currentFile
}
syncInProgress =
FileSyncAdapter.EVENT_FULL_SYNC_END != event &&
RefreshFolderOperation.EVENT_SINGLE_FOLDER_SHARES_SYNCED != event
if (RefreshFolderOperation.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED == event) {
if (!synchResult?.isSuccess!!) {
/// TODO refactor and make common
if (ResultCode.UNAUTHORIZED == synchResult.code ||
synchResult.isException && synchResult.exception is AuthenticatorException
) {
launch(Dispatchers.IO) {
val credentials =
com.owncloud.android.lib.common.accounts.AccountUtils.getCredentialsForAccount(
MainApp.appContext,
account
)
launch(Dispatchers.Main) {
if (credentials is OwnCloudBearerCredentials) { // OAuth
showRequestRegainAccess()
} else {
showRequestAccountChangeNotice(
getString(R.string.auth_failure_snackbar),
false
)
}
}
}
} else if (ResultCode.SSL_RECOVERABLE_PEER_UNVERIFIED == synchResult.code) {
showUntrustedCertDialog(synchResult)
}
}
if (synchFolderRemotePath == OCFile.ROOT_PATH) {
setAccountInDrawer(account)
}
}
}
val fileListFragment = listOfFilesFragment
fileListFragment?.setProgressBarAsIndeterminate(syncInProgress)
Timber.d("Setting progress visibility to $syncInProgress")
setBackgroundText()
}
if (synchResult?.code == ResultCode.SSL_RECOVERABLE_PEER_UNVERIFIED) {
lastSslUntrustedServerResult = synchResult
} else if (synchResult?.code == ResultCode.SPECIFIC_SERVICE_UNAVAILABLE) {
if (synchResult.httpCode == 503) {
if (synchResult.httpPhrase == "Error: Call to a member function getUID() on null") {
showRequestAccountChangeNotice(getString(R.string.auth_failure_snackbar), false)
} else {
showMessageInSnackbar(R.id.list_layout, synchResult.httpPhrase)
}
} else {
showRequestAccountChangeNotice(getString(R.string.auth_failure_snackbar), false)
}
}
}
}
/**
* Show a text message on screen view for notifying user if content is
* loading or folder is empty
*/
fun setBackgroundText() {
val ocFileListFragment = listOfFilesFragment
if (ocFileListFragment != null) {
if (selectAllMenuItem != null) {
selectAllMenuItem!!.isVisible = true
if (ocFileListFragment.noOfItems == 0) {
selectAllMenuItem!!.isVisible = false
}
}
var message = R.string.file_list_loading
if (!syncInProgress) {
// In case file list is empty
message =
when (fileListOption) {
FileListOption.AV_OFFLINE -> R.string.file_list_empty_available_offline
FileListOption.SHARED_BY_LINK -> R.string.file_list_empty_shared_by_links
else -> R.string.file_list_empty
}
ocFileListFragment.progressBar.visibility = View.GONE
ocFileListFragment.shadowView.visibility = View.VISIBLE
}
ocFileListFragment.setMessageForEmptyList(getString(message))
} else {
Timber.e("OCFileListFragment is null")
}
}
/**
* Once the file upload has finished -> update view
*/
private inner class UploadBroadcastReceiver : BroadcastReceiver() {
/**
* Once the file upload has finished -> update view
*
* @author David A. Velasco
* [BroadcastReceiver] to enable upload feedback in UI
*/
override fun onReceive(context: Context, intent: Intent) {
val uploadedRemotePath = intent.getStringExtra(Extras.EXTRA_REMOTE_PATH)
val accountName = intent.getStringExtra(Extras.EXTRA_ACCOUNT_NAME)
val sameAccount = account != null && accountName == account.name
val currentDir = currentDir
val isDescendant = currentDir != null &&
uploadedRemotePath != null &&
uploadedRemotePath.startsWith(currentDir.remotePath)
val renamedInUpload = file.remotePath == intent.getStringExtra(Extras.EXTRA_OLD_REMOTE_PATH)
val sameFile = renamedInUpload || file.remotePath == uploadedRemotePath
val success = intent.getBooleanExtra(Extras.EXTRA_UPLOAD_RESULT, false)
if (sameAccount && isDescendant) {
val linkedToRemotePath = intent.getStringExtra(Extras.EXTRA_LINKED_TO_PATH)
if (linkedToRemotePath == null || isAscendant(linkedToRemotePath)) {
refreshListOfFilesFragment(true)
}
}
if (sameAccount && sameFile) {
if (success && uploadedRemotePath != null) {
file = storageManager.getFileByPath(uploadedRemotePath)
}
refreshSecondFragment(
intent.action,
success
)
if (renamedInUpload) {
val newName = File(uploadedRemotePath).name
showMessageInSnackbar(
R.id.list_layout,
String.format(getString(R.string.filedetails_renamed_in_upload_msg), newName)
)
updateToolbar(file)
}
}
}
private fun refreshSecondFragment(uploadEvent: String?, success: Boolean) {
val secondFragment = secondFragment
if (secondFragment != null) {
if (!success && !file.fileExists()) {
cleanSecondFragment()
} else {
val file = file
var fragmentReplaced = false
if (success && secondFragment is FileDetailFragment) {
// start preview if previewable
fragmentReplaced = true
when {
PreviewImageFragment.canBePreviewed(file) -> startImagePreview(file)
PreviewAudioFragment.canBePreviewed(file) -> startAudioPreview(file, 0)
PreviewVideoFragment.canBePreviewed(file) -> startVideoPreview(file, 0)
PreviewTextFragment.canBePreviewed(file) -> startTextPreview(file)
else -> fragmentReplaced = false
}
}
if (!fragmentReplaced) {
secondFragment.onSyncEvent(uploadEvent, success, file)
}
}
}
}
// TODO refactor this receiver, and maybe DownloadBroadcastReceiver; this method is duplicated :S
private fun isAscendant(linkedToRemotePath: String): Boolean {
val currentDir = currentDir
return currentDir != null && currentDir.remotePath.startsWith(linkedToRemotePath)
}
}
/**
* Class waiting for broadcast events from the [FileDownloader] service.
*
*
* Updates the UI when a download is started or finished, provided that it is relevant for the
* current folder.
*/
private inner class DownloadBroadcastReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
val sameAccount = isSameAccount(intent)
val downloadedRemotePath = intent.getStringExtra(Extras.EXTRA_REMOTE_PATH)
val isDescendant = isDescendant(downloadedRemotePath)
if (sameAccount && isDescendant) {
val linkedToRemotePath = intent.getStringExtra(Extras.EXTRA_LINKED_TO_PATH)
if (linkedToRemotePath == null || isAscendant(linkedToRemotePath)) {
refreshListOfFilesFragment(true)
}
refreshSecondFragment(
intent.action,
downloadedRemotePath,
intent.getBooleanExtra(Extras.EXTRA_DOWNLOAD_RESULT, false)
)
invalidateOptionsMenu()
}
waitingToSend = waitingToSend?.let { file ->
storageManager.getFileByPath(file.remotePath)
}
if (waitingToSend?.isDown == true) {
sendDownloadedFile()
}
waitingToOpen = waitingToOpen?.let { file ->
storageManager.getFileByPath(file.remotePath)
}
if (waitingToOpen?.isDown == true) {
openDownloadedFile()
}
}
private fun isDescendant(downloadedRemotePath: String?): Boolean {
val currentDir = currentDir
return currentDir != null &&
downloadedRemotePath != null &&
downloadedRemotePath.startsWith(currentDir.remotePath)
}
private fun isAscendant(linkedToRemotePath: String): Boolean {
val currentDir = currentDir
return currentDir != null && currentDir.remotePath.startsWith(linkedToRemotePath)
}
private fun isSameAccount(intent: Intent): Boolean {
val accountName = intent.getStringExtra(Extras.EXTRA_ACCOUNT_NAME)
return accountName != null && account != null &&
accountName == account.name
}
private fun refreshSecondFragment(
downloadEvent: String?, downloadedRemotePath: String?,
success: Boolean
) {
val secondFragment = secondFragment
if (secondFragment != null) {
var fragmentReplaced = false
if (secondFragment is FileDetailFragment) {
/// user was watching download progress
val detailsFragment = secondFragment as FileDetailFragment?
val fileInFragment = detailsFragment?.file
if (fileInFragment != null && downloadedRemotePath != fileInFragment.remotePath) {
// the user browsed to other file ; forget the automatic preview
fileWaitingToPreview = null
} else if (downloadEvent == FileDownloader.getDownloadFinishMessage()) {
// replace the right panel if waiting for preview
val waitedPreview = fileWaitingToPreview?.remotePath == downloadedRemotePath
if (waitedPreview) {
if (success) {
// update the file from database, to get the local storage path
fileWaitingToPreview = storageManager.getFileById(fileWaitingToPreview!!.fileId)
when {
PreviewAudioFragment.canBePreviewed(fileWaitingToPreview) -> {
fragmentReplaced = true
startAudioPreview(fileWaitingToPreview!!, 0)
}
PreviewVideoFragment.canBePreviewed(fileWaitingToPreview) -> {
fragmentReplaced = true
startVideoPreview(fileWaitingToPreview!!, 0)
}
PreviewTextFragment.canBePreviewed(fileWaitingToPreview) -> {
fragmentReplaced = true
startTextPreview(fileWaitingToPreview)
}
else -> fileOperationsHelper.openFile(fileWaitingToPreview)
}
}
fileWaitingToPreview = null
}
}
}
if (!fragmentReplaced && downloadedRemotePath == secondFragment.file.remotePath) {
secondFragment.onSyncEvent(downloadEvent, success, null)
}
}
}
}
fun browseToRoot() {
val listOfFiles = listOfFilesFragment
if (listOfFiles != null) { // should never be null, indeed
val root = storageManager.getFileByPath(OCFile.ROOT_PATH)
listOfFiles.listDirectory(root)
file = listOfFiles.currentFile
startSyncFolderOperation(root, false)
}
cleanSecondFragment()
}
/**
* {@inheritDoc}
* Updates action bar and second fragment, if in dual pane mode.
*/
override fun onBrowsedDownTo(directory: OCFile) {
file = directory
cleanSecondFragment()
// Sync Folder
startSyncFolderOperation(directory, false)
}
/**
* Shows the information of the [OCFile] received as a
* parameter in the second fragment.
*
* @param file [OCFile] whose details will be shown
*/
override fun showDetails(file: OCFile) {
val detailFragment = FileDetailFragment.newInstance(file, account)
setSecondFragment(detailFragment)
updateFragmentsVisibility(true)
updateToolbar(file)
setFile(file)
}
private fun updateToolbar(chosenFileFromParam: OCFile?) {
val chosenFile = chosenFileFromParam ?: file // If no file is passed, current file decides
if (chosenFile == null || chosenFile.remotePath == OCFile.ROOT_PATH) {
val title =
when (fileListOption) {
FileListOption.AV_OFFLINE -> getString(R.string.drawer_item_only_available_offline)
FileListOption.SHARED_BY_LINK -> getString(R.string.drawer_item_shared_by_link_files)
FileListOption.ALL_FILES -> getString(R.string.default_display_name_for_root_folder)
}
setupRootToolbar(title, isSearchEnabled = true)
listOfFilesFragment?.setSearchListener(findViewById(R.id.root_toolbar_search_view))
} else {
updateStandardToolbar(title = chosenFile.fileName, displayHomeAsUpEnabled = true, homeButtonEnabled = true)
}
}
override fun newTransferenceServiceConnection(): ServiceConnection? {
return ListServiceConnection()
}
/**
* Defines callbacks for service binding, passed to bindService()
*/
private inner class ListServiceConnection : ServiceConnection {
override fun onServiceConnected(component: ComponentName, service: IBinder) {
if (component == ComponentName(this@FileDisplayActivity, FileDownloader::class.java)) {
Timber.d("Download service connected")
mDownloaderBinder = service as FileDownloaderBinder
if (fileWaitingToPreview != null) {
if (storageManager != null) {
// update the file
fileWaitingToPreview = storageManager.getFileById(fileWaitingToPreview!!.fileId)
if (!fileWaitingToPreview!!.isDown) {
// If the file to preview isn't downloaded yet, check if it is being
// downloaded in this moment or not
requestForDownload()
}
}
}
if (file != null && mDownloaderBinder.isDownloading(account, file)) {
// If the file is being downloaded, assure that the fragment to show is details
// fragment, not the streaming video fragment which has been previously
// set in chooseInitialSecondFragment method
val secondFragment = secondFragment
if (secondFragment != null && secondFragment is PreviewVideoFragment) {
cleanSecondFragment()
showDetails(file)
}
}
} else if (component == ComponentName(
this@FileDisplayActivity,
FileUploader::class.java
)
) {
Timber.d("Upload service connected")
mUploaderBinder = service as FileUploaderBinder
} else {
return
}
val listOfFiles = listOfFilesFragment
listOfFiles?.listDirectory(false)
val secondFragment = secondFragment
secondFragment?.onTransferServiceConnected()
}
override fun onServiceDisconnected(component: ComponentName) {
if (component == ComponentName(
this@FileDisplayActivity,
FileDownloader::class.java
)
) {
Timber.d("Download service disconnected")
mDownloaderBinder = null
} else if (component == ComponentName(
this@FileDisplayActivity,
FileUploader::class.java
)
) {
Timber.d("Upload service disconnected")
mUploaderBinder = null
}
}
}
/**
* Updates the view associated to the activity after the finish of some operation over files
* in the current account.
*
* @param operation Removal operation performed.
* @param result Result of the removal.
*/
override fun onRemoteOperationFinish(operation: RemoteOperation<*>, result: RemoteOperationResult<*>) {
super.onRemoteOperationFinish(operation, result)
when (operation) {
is RemoveFileOperation -> onRemoveFileOperationFinish(operation, result)
is RenameFileOperation -> onRenameFileOperationFinish(operation, result)
is SynchronizeFileOperation -> onSynchronizeFileOperationFinish(operation, result)
is CreateFolderOperation -> onCreateFolderOperationFinish(operation, result)
is MoveFileOperation -> onMoveFileOperationFinish(operation, result)
is CopyFileOperation -> onCopyFileOperationFinish(operation, result)
}
}
/**
* Updates the view associated to the activity after the finish of an operation trying to
* remove a file.
*
* @param operation Removal operation performed.
* @param result Result of the removal.
*/
private fun onRemoveFileOperationFinish(
operation: RemoveFileOperation,
result: RemoteOperationResult<*>
) {
if (listOfFilesFragment!!.isSingleItemChecked || result.isException || !result.isSuccess) {
if (result.code != ResultCode.FORBIDDEN || result.code == ResultCode.FORBIDDEN && operation.isLastFileToRemove) {
showMessageInSnackbar(
R.id.list_layout,
ErrorMessageAdapter.getResultMessage(result, operation, resources)
)
}
}
if (result.isSuccess) {
val removedFile = operation.file
val second = secondFragment
if (second != null && removedFile == second.file) {
if (second is PreviewAudioFragment) {
second.stopPreview()
} else if (second is PreviewVideoFragment) {
second.releasePlayer()
}
file = storageManager.getFileById(removedFile.parentId)
cleanSecondFragment()
}
if (storageManager.getFileById(removedFile.parentId) == currentDir) {
refreshListOfFilesFragment(true)
}
invalidateOptionsMenu()
} else {
if (result.isSslRecoverableException) {
lastSslUntrustedServerResult = result
showUntrustedCertDialog(lastSslUntrustedServerResult)
}
}
}
/**
* Updates the view associated to the activity after the finish of an operation trying to move a
* file.
*
* @param operation Move operation performed.
* @param result Result of the move operation.
*/
private fun onMoveFileOperationFinish(
operation: MoveFileOperation,
result: RemoteOperationResult<*>
) {
if (result.isSuccess) {
refreshListOfFilesFragment(true)
} else {
try {
showMessageInSnackbar(
R.id.list_layout,
ErrorMessageAdapter.getResultMessage(result, operation, resources)
)
} catch (e: NotFoundException) {
Timber.e(e, "Error while trying to show fail message")
}
}
}
/**
* Updates the view associated to the activity after the finish of an operation trying to copy a
* file.
*
* @param operation Copy operation performed.
* @param result Result of the copy operation.
*/
private fun onCopyFileOperationFinish(operation: CopyFileOperation, result: RemoteOperationResult<*>) {
if (result.isSuccess) {
refreshListOfFilesFragment(true)
} else {
try {
showMessageInSnackbar(
R.id.list_layout,
ErrorMessageAdapter.getResultMessage(result, operation, resources)
)
} catch (e: NotFoundException) {
Timber.e(e, "Error while trying to show fail message")
}
}
}
/**
* Updates the view associated to the activity after the finish of an operation trying to rename
* a file.
*
* @param operation Renaming operation performed.
* @param result Result of the renaming.
*/
private fun onRenameFileOperationFinish(
operation: RenameFileOperation,
result: RemoteOperationResult<*>
) {
var renamedFile: OCFile? = operation.file
if (result.isSuccess) {
val details = secondFragment
if (details != null && renamedFile == details.file) {
renamedFile = storageManager.getFileById(renamedFile!!.fileId)
file = renamedFile
details.onFileMetadataChanged(renamedFile)
updateToolbar(renamedFile)
}
if (storageManager.getFileById(renamedFile!!.parentId) == currentDir) {
refreshListOfFilesFragment(true)
}
} else {
showMessageInSnackbar(
R.id.list_layout,
ErrorMessageAdapter.getResultMessage(result, operation, resources)
)
if (result.isSslRecoverableException) {
lastSslUntrustedServerResult = result
showUntrustedCertDialog(lastSslUntrustedServerResult)
}
}
}
private fun onSynchronizeFileOperationFinish(
operation: SynchronizeFileOperation,
result: RemoteOperationResult<*>
) {
if (result.isSuccess) {
if (operation.transferWasRequested()) {
// this block is probably useless duy
val syncedFile = operation.localFile
refreshListOfFilesFragment(false)
val secondFragment = secondFragment
if (secondFragment != null && syncedFile == secondFragment.file) {
secondFragment.onSyncEvent(FileDownloader.getDownloadAddedMessage(), false, null)
invalidateOptionsMenu()
}
} else if (secondFragment == null) {
showMessageInSnackbar(
R.id.list_layout,
ErrorMessageAdapter.getResultMessage(result, operation, resources)
)
}
}
/// no matter if sync was right or not - if there was no transfer and the file is down, OPEN it
val waitedForPreview = fileWaitingToPreview?.let { it == operation.localFile && it.isDown } ?: false
if (!operation.transferWasRequested() and waitedForPreview) {
fileOperationsHelper.openFile(fileWaitingToPreview)
fileWaitingToPreview = null
}
}
/**
* Updates the view associated to the activity after the finish of an operation trying create a
* new folder
*
* @param operation Creation operation performed.
* @param result Result of the creation.
*/
private fun onCreateFolderOperationFinish(
operation: CreateFolderOperation,
result: RemoteOperationResult<*>
) {
if (result.isSuccess) {
refreshListOfFilesFragment(true)
} else {
try {
showMessageInSnackbar(
R.id.list_layout,
ErrorMessageAdapter.getResultMessage(result, operation, resources)
)
} catch (e: NotFoundException) {
Timber.e(e, "Error while trying to show fail message")
}
}
}
private fun requestForDownload() {
val account = account
//if (!fileWaitingToPreview.isDownloading()) {
// If the file is not being downloaded, start the download
if (!mDownloaderBinder.isDownloading(account, fileWaitingToPreview)) {
val i = Intent(this, FileDownloader::class.java)
i.putExtra(FileDownloader.KEY_ACCOUNT, account)
i.putExtra(FileDownloader.KEY_FILE, fileWaitingToPreview)
startService(i)
}
}
override fun onSavedCertificate() {
startSyncFolderOperation(currentDir, false)
}
/**
* Starts an operation to refresh the requested folder.
*
*
* The operation is run in a new background thread created on the fly.
*
*
* The refresh updates is a "light sync": properties of regular files in folder are updated (including
* associated shares), but not their contents. Only the contents of files marked to be kept-in-sync are
* synchronized too.
*
* @param folder Folder to refresh.
* @param ignoreETag If 'true', the data from the server will be fetched and synced even if the eTag
* didn't change.
*/
fun startSyncFolderOperation(folder: OCFile?, ignoreETag: Boolean) {
// the execution is slightly delayed to allow the activity get the window focus if it's being started
// or if the method is called from a dialog that is being dismissed
handler.postDelayed(
{
if (hasWindowFocus()) {
syncInProgress = true
// perform folder synchronization
val synchFolderOp = RefreshFolderOperation(
folder,
ignoreETag,
account,
applicationContext
)
synchFolderOp.execute(
storageManager,
MainApp.appContext, null, null
)// unneeded, handling via SyncBroadcastReceiver
val fileListFragment = listOfFilesFragment
fileListFragment?.setProgressBarAsIndeterminate(true)
setBackgroundText()
} // else: NOTHING ; lets' not refresh when the user rotates the device but there is
// another window floating over
},
DELAY_TO_REQUEST_OPERATIONS_LATER + 350
)
}
private fun requestForDownload(file: OCFile?) {
val account = account
if (!mDownloaderBinder.isDownloading(account, fileWaitingToPreview)) {
val i = Intent(this, FileDownloader::class.java)
i.putExtra(FileDownloader.KEY_ACCOUNT, account)
i.putExtra(FileDownloader.KEY_FILE, file)
startService(i)
}
}
private fun sendDownloadedFile() {
fileOperationsHelper.sendDownloadedFile(waitingToSend)
waitingToSend = null
}
private fun openDownloadedFile() {
fileOperationsHelper.openFile(waitingToOpen)
waitingToOpen = null
}
/**
* Requests the download of the received [OCFile] , updates the UI
* to monitor the download progress and prepares the activity to send the file
* when the download finishes.
*
* @param file [OCFile] to download and preview.
*/
fun startDownloadForSending(file: OCFile) {
waitingToSend = file
requestForDownload(waitingToSend)
val hasSecondFragment = secondFragment != null
updateFragmentsVisibility(hasSecondFragment)
}
/**
* Requests the download of the received [OCFile] , updates the UI
* to monitor the download progress and prepares the activity to open the file
* when the download finishes.
*
* @param file [OCFile] to download and preview.
*/
fun startDownloadForOpening(file: OCFile) {
waitingToOpen = file
requestForDownload(waitingToOpen)
val hasSecondFragment = secondFragment != null
updateFragmentsVisibility(hasSecondFragment)
}
/**
* Opens the image gallery showing the image [OCFile] received as parameter.
*
* @param file Image [OCFile] to show.
*/
fun startImagePreview(file: OCFile) {
val showDetailsIntent = Intent(this, PreviewImageActivity::class.java)
showDetailsIntent.putExtra(EXTRA_FILE, file)
showDetailsIntent.putExtra(EXTRA_ACCOUNT, account)
startActivity(showDetailsIntent)
}
/**
* Stars the preview of an already down audio [OCFile].
*
* @param file Media [OCFile] to preview.
* @param startPlaybackPosition Media position where the playback will be started,
* in milliseconds.
*/
fun startAudioPreview(file: OCFile, startPlaybackPosition: Int) {
val mediaFragment = PreviewAudioFragment.newInstance(
file,
account,
startPlaybackPosition,
true
)
setSecondFragment(mediaFragment)
updateFragmentsVisibility(true)
updateToolbar(file)
setFile(file)
}
/**
* Stars the preview of an already down video [OCFile].
*
* @param file Media [OCFile] to preview.
* @param startPlaybackPosition Media position where the playback will be started,
* in milliseconds.
*/
fun startVideoPreview(file: OCFile, startPlaybackPosition: Int) {
val mediaFragment = PreviewVideoFragment.newInstance(
file,
account,
startPlaybackPosition,
true
)
setSecondFragment(mediaFragment)
updateFragmentsVisibility(true)
updateToolbar(file)
setFile(file)
}
/**
* Stars the preview of a text file [OCFile].
*
* @param file Text [OCFile] to preview.
*/
fun startTextPreview(file: OCFile?) {
val textPreviewFragment = PreviewTextFragment.newInstance(
file,
account
)
setSecondFragment(textPreviewFragment)
updateFragmentsVisibility(true)
updateToolbar(file)
setFile(file)
}
/**
* Requests the synchronization of the received [OCFile],
* updates the UI to monitor the progress and prepares the activity
* to preview or open the file when the download finishes.
*
* @param file [OCFile] to sync and open.
*/
fun startSyncThenOpen(file: OCFile) {
val detailFragment = FileDetailFragment.newInstance(file, account)
setSecondFragment(detailFragment)
fileWaitingToPreview = file
fileOperationsHelper.syncFile(file)
updateFragmentsVisibility(true)
updateToolbar(file)
setFile(file)
}
/**
* Request stopping the upload/download operation in progress over the given [OCFile] file.
*
* @param file [OCFile] file which operation are wanted to be cancel
*/
fun cancelTransference(file: OCFile) {
fileOperationsHelper.cancelTransference(file)
fileWaitingToPreview?.let {
if (it.remotePath == file.remotePath) {
fileWaitingToPreview = null
}
}
waitingToSend?.let {
if (it.remotePath == file.remotePath) {
waitingToSend = null
}
}
refreshListOfFilesFragment(false)
val secondFragment = secondFragment
if (secondFragment != null && file == secondFragment.file) {
if (!file.fileExists()) {
cleanSecondFragment()
} else {
secondFragment.onSyncEvent(FileDownloader.getDownloadFinishMessage(), false, null)
}
}
invalidateOptionsMenu()
}
/**
* Request stopping all upload/download operations in progress over the given [OCFile] files.
*
* @param files list of [OCFile] files which operations are wanted to be cancel
*/
fun cancelTransference(files: List<OCFile>) {
for (file in files) {
cancelTransference(file)
}
}
override fun onRefresh(ignoreETag: Boolean) {
refreshList(ignoreETag)
}
override fun onRefresh() {
refreshList(true)
}
private fun refreshList(ignoreETag: Boolean) {
listOfFilesFragment?.let {
it.currentFile?.let { folder ->
startSyncFolderOperation(folder, ignoreETag)
}
}
}
private fun navigateTo(newFileListOption: FileListOption) {
if (fileListOption != newFileListOption) {
if (listOfFilesFragment != null) {
fileListOption = newFileListOption
file = storageManager.getFileByPath(OCFile.ROOT_PATH)
listOfFilesFragment?.updateFileListOption(newFileListOption)
updateToolbar(null)
} else {
super.navigateToOption(FileListOption.ALL_FILES)
}
} else {
browseToRoot()
}
}
override fun navigateToOption(fileListOption: FileListOption) {
navigateTo(fileListOption)
}
private fun getMenuItemForFileListOption(fileListOption: FileListOption?): Int = when (fileListOption) {
FileListOption.SHARED_BY_LINK -> R.id.nav_shared_by_link_files
FileListOption.AV_OFFLINE -> R.id.nav_available_offline_files
else -> R.id.nav_all_files
}
override fun optionLockSelected(type: LockType) {
manageOptionLockSelected(type)
}
companion object {
private const val TAG_LIST_OF_FILES = "LIST_OF_FILES"
private const val TAG_SECOND_FRAGMENT = "SECOND_FRAGMENT"
private const val KEY_WAITING_TO_PREVIEW = "WAITING_TO_PREVIEW"
private const val KEY_SYNC_IN_PROGRESS = "SYNC_IN_PROGRESS"
private const val KEY_WAITING_TO_SEND = "WAITING_TO_SEND"
private const val KEY_UPLOAD_HELPER = "FILE_UPLOAD_HELPER"
private const val KEY_FILE_LIST_OPTION = "FILE_LIST_OPTION"
const val ACTION_DETAILS = "com.owncloud.android.ui.activity.action.DETAILS"
const val REQUEST_CODE__SELECT_CONTENT_FROM_APPS = REQUEST_CODE__LAST_SHARED + 1
const val REQUEST_CODE__MOVE_FILES = REQUEST_CODE__LAST_SHARED + 2
const val REQUEST_CODE__COPY_FILES = REQUEST_CODE__LAST_SHARED + 3
const val REQUEST_CODE__UPLOAD_FROM_CAMERA = REQUEST_CODE__LAST_SHARED + 4
const val REQUEST_CODE__UPLOAD_SCANNED_DOCUMENT = REQUEST_CODE__LAST_SHARED + 5
const val REQUEST_CODE__UPLOAD_LIVEDGE_DOCUMENT = REQUEST_CODE__LAST_SHARED + 6
const val RESULT_OK_AND_MOVE = Activity.RESULT_FIRST_USER
}
}
| gpl-2.0 | 78f2db7d93420b2c18d6f27c471fa28c | 39.03822 | 163 | 0.594469 | 5.448455 | false | false | false | false |
AndroidX/androidx | health/connect/connect-client/src/main/java/androidx/health/connect/client/request/ReadRecordsRequest.kt | 3 | 3672 | /*
* Copyright (C) 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.health.connect.client.request
import androidx.health.connect.client.records.Record
import androidx.health.connect.client.records.metadata.DataOrigin
import androidx.health.connect.client.time.TimeRangeFilter
import kotlin.reflect.KClass
/**
* Request object to read [Record]s in Android Health Platform determined by time range and other
* filters.
*
* Returned collection will contain a
* [androidx.health.data.client.response.ReadRecordsResponse.pageToken] if number of records exceeds
* [pageSize]. Use this if you expect an unbound number of records within specified time ranges.
* Stops at any time once desired amount of records are processed.
*
* @param T type of [Record], such as `Steps`.
* @param recordType Which type of [Record] to read, such as `Steps::class`.
* @param timeRangeFilter The [TimeRangeFilter] to read from.
* @param dataOriginFilter List of [DataOrigin] to read from, or empty for no filter.
* @param ascendingOrder Whether the [Record] should be returned in ascending or descending order by
* time. Default is true for ascending.
* @param pageSize Maximum number of [Record] within one page. If there's more data remaining (and
* the next page should be read), the response will contain a [pageToken] to be used in the
* subsequent read request. Must be positive, default to 1000.
* @param pageToken Continuation token to access the next page, returned in the response to the
* previous page read request, or `null` for the initial request for the first page.
*
* @see androidx.health.connect.client.response.ReadRecordsResponse
* @see androidx.health.connect.client.HealthConnectClient.readRecords
*/
public class ReadRecordsRequest<T : Record>(
internal val recordType: KClass<T>,
internal val timeRangeFilter: TimeRangeFilter,
internal val dataOriginFilter: Set<DataOrigin> = emptySet(),
internal val ascendingOrder: Boolean = true,
internal val pageSize: Int = 1000,
internal val pageToken: String? = null,
) {
init {
require(pageSize > 0) { "pageSize must be positive." }
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as ReadRecordsRequest<*>
if (recordType != other.recordType) return false
if (timeRangeFilter != other.timeRangeFilter) return false
if (dataOriginFilter != other.dataOriginFilter) return false
if (ascendingOrder != other.ascendingOrder) return false
if (pageSize != other.pageSize) return false
if (pageToken != other.pageToken) return false
return true
}
override fun hashCode(): Int {
var result = recordType.hashCode()
result = 31 * result + timeRangeFilter.hashCode()
result = 31 * result + dataOriginFilter.hashCode()
result = 31 * result + ascendingOrder.hashCode()
result = 31 * result + pageSize
result = 31 * result + (pageToken?.hashCode() ?: 0)
return result
}
}
| apache-2.0 | f36f8dcd527af9730ab9335d228cb1fd | 42.714286 | 100 | 0.721133 | 4.424096 | false | false | false | false |
TeamWizardry/LibrarianLib | modules/core/src/main/kotlin/com/teamwizardry/librarianlib/math/Vec3i.kt | 1 | 1252 | package com.teamwizardry.librarianlib.math
import com.teamwizardry.librarianlib.core.util.ivec
import net.minecraft.util.math.Vec3i
@JvmSynthetic
public operator fun Vec3i.plus(other: Vec3i): Vec3i = ivec(this.x + other.x, this.y + other.y, this.z + other.z)
@JvmSynthetic
public operator fun Vec3i.minus(other: Vec3i): Vec3i = ivec(this.x - other.x, this.y - other.y, this.z - other.z)
@JvmSynthetic
public operator fun Vec3i.times(other: Vec3i): Vec3i = ivec(this.x * other.x, this.y * other.y, this.z * other.z)
@JvmSynthetic
public operator fun Vec3i.div(other: Vec3i): Vec3i = ivec(this.x / other.x, this.y / other.y, this.z / other.z)
@JvmSynthetic
public operator fun Vec3i.div(other: Int): Vec3i = ivec(this.x / other, this.y / other, this.z / other)
@JvmSynthetic
public operator fun Vec3i.times(other: Int): Vec3i = ivec(this.x * other, this.y * other, this.z * other)
@JvmSynthetic
public operator fun Vec3i.unaryMinus(): Vec3i = this * -1
@JvmSynthetic
public infix fun Vec3i.cross(other: Vec3i): Vec3i = this.crossProduct(other)
@JvmSynthetic
public operator fun Vec3i.component1(): Int = this.x
@JvmSynthetic
public operator fun Vec3i.component2(): Int = this.y
@JvmSynthetic
public operator fun Vec3i.component3(): Int = this.z
| lgpl-3.0 | 13f386624f9801c020bf53e1251a2eb7 | 35.823529 | 113 | 0.740415 | 2.878161 | false | false | false | false |
pdvrieze/darwin-android-auth | src/main/java/uk/ac/bournemouth/darwin/auth/AccountDetailFragment.kt | 1 | 5194 | package uk.ac.bournemouth.darwin.auth
import android.accounts.Account
import android.arch.lifecycle.LiveData
import android.arch.lifecycle.Observer
import android.arch.lifecycle.ViewModelProviders
import android.databinding.DataBindingUtil
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v7.recyclerview.extensions.ListAdapter
import android.support.v7.util.DiffUtil
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import nl.adaptivity.android.coroutines.CompatCoroutineFragment
import org.xmlpull.v1.XmlPullParserFactory
import uk.ac.bournemouth.darwin.auth.databinding.AccountDetailBinding
import uk.ac.bournemouth.darwin.auth.databinding.KeyListContentBinding
import java.net.HttpURLConnection
import java.net.URI
/**
* A fragment representing a single Account detail screen.
* This fragment is either contained in a [AccountListActivity]
* in two-pane mode (on tablets) or a [AccountDetailActivity]
* on handsets.
*/
class AccountDetailFragment : CompatCoroutineFragment() {
/**
* The dummy content this fragment is presenting.
*/
private var account: Account? = null
private lateinit var binding: AccountDetailBinding
private lateinit var accountInfo: LiveData<AccountInfo>
private val keyAdapter = KeyAdapter()
@Suppress("ClassName")
object KEYINFO_DIFF_CALLBACK: DiffUtil.ItemCallback<KeyInfo>() {
override fun areItemsTheSame(oldItem: KeyInfo, newItem: KeyInfo): Boolean {
return oldItem.keyId == newItem.keyId
}
override fun areContentsTheSame(oldItem: KeyInfo, newItem: KeyInfo): Boolean {
return oldItem == newItem
}
}
class KeyAdapter(data: List<KeyInfo> = emptyList()): ListAdapter<KeyInfo, KeyViewHolder>(KEYINFO_DIFF_CALLBACK) {
init {
setHasStableIds(true)
if (data.isNotEmpty()) submitList(data)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): KeyViewHolder {
return KeyViewHolder(DataBindingUtil.inflate(LayoutInflater.from(parent.context), R.layout.key_list_content, parent, false))
}
override fun onBindViewHolder(holder: KeyViewHolder, position: Int) {
holder.binding.keyInfo = getItem(position)
}
override fun getItemId(position: Int): Long {
return getItem(position).keyId.toLong()
}
}
class KeyViewHolder(val binding: KeyListContentBinding): RecyclerView.ViewHolder(binding.root)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
arguments?.let {
if (it.containsKey(ARG_ACCOUNT)) {
account = it.getParcelable(ARG_ACCOUNT)
}
}
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
binding = DataBindingUtil.inflate(inflater, R.layout.account_detail, container, false)
binding.keyList.adapter=keyAdapter
val viewModel = ViewModelProviders.of(this).get(AccountsViewModel::class.java)
// Show the dummy content as text in a TextView.
account?.let { account ->
binding.accountDetail.text = container!!.resources.getString(R.string.lbl_account_name, account.name)
accountInfo = viewModel.getAccountInfo(account).invoke(this)
accountInfo.observe(this, Observer<AccountInfo> { info ->
binding.info = info
keyAdapter.submitList(info?.keys?: emptyList())
} )
}
viewModel.loading.observe(this) { binding.loading = it?: false }
binding.refreshLayout.setOnRefreshListener {
val a = account
if (a!=null) {
viewModel.getAccountInfo(a, true).invoke(this)
}
}
return binding.root
}
companion object {
/**
* The fragment argument representing the item ID that this fragment
* represents.
*/
const val ARG_ACCOUNT = "account"
}
}
private fun getInfoUrl(authBaseUrl: String?): URI {
return URI.create("${if (authBaseUrl.isNullOrEmpty()) DarwinAuthenticator.DEFAULT_AUTH_BASE_URL else authBaseUrl}myaccount")
}
internal fun getAccountInfoHelper(authBaseUrl: String?, token: String?): AccountInfo? {
val conn = getInfoUrl(authBaseUrl).toURL().openConnection() as HttpURLConnection
try {
conn.addRequestProperty("DWNID", token)
conn.addRequestProperty("Accept-Content", "text/xml")
val response = conn.responseCode
if (response < 400) {
conn.inputStream.use {
val reader = XmlPullParserFactory.newInstance().newPullParser()
.apply { setInput(it, conn.getHeaderField("Content-Encoding") ?: "UTF8") }
reader.nextTag()
return AccountInfo.from(reader, authBaseUrl)
}
} else {
return null
}
} finally {
conn.disconnect()
}
} | lgpl-2.1 | 8712501f38922ec02e07ebcb5623b24d | 33.177632 | 136 | 0.671352 | 4.773897 | false | false | false | false |
chiragbharadwaj/crypto | src/set1/hex/Hex.kt | 2 | 7930 | package set1.hex
/* Set 1, Challenge 1. Convert strings represented in hex to their equivalent representations in base-64. */
object Hex {
/* <Char[]>.regroup(n) reverses the receiver object in groups/chunks of size [n]. That is, the entire receiver
* object is reversed while keeping chunks of size n intact (counting from the back). For example, if n = 3, then
* ['d','e','a','d','b','e','e'].regroup(3) would return ['e','d','b','e','d','e','a'].
* Requires: [n] >= 1.
* */
private fun CharArray.regroup(n: Int): CharArray {
if (n < 1) throw IllegalArgumentException("$n is not greater than or equal to 1!")
// No need to do extra work if it's already that small.
if (this.size < n) return this
// Pre-processing information.
val rev = this.reversedArray()
val final = rev.size - (rev.size % n) - 1
val chs = CharArray(rev.size)
var base = 0 // Marker for which "group of n" we're on.
var count = 0 // How far away from the base marker we are, up to n away.
for (i in 0..final) {
// Small optimization hack to get everything done in a single loop.
if (i < rev.size - final - 1) {
chs[final + i + 1] = this[i]
}
// Reset the counter.
if (count == n) {
count = 0
base = i // Move the marker up.
}
// Don't question these indices. They work! Source: lots of testing.
chs[i] = rev[base + n - count - 1]
count++
}
return chs
}
/* <Char>.toDecimal() converts the receiver object to the equivalent integer.
* Requires: The receiver object must be input as a single base-16 number, i.e. it is either [0-9] or [a-f].
*/
private fun Char.toDecimal(): Int =
when (this) {
in '0'..'9' -> this - '0'
in 'a'..'f' -> this - 'a' + 10
else -> throw IllegalArgumentException("$this is not a valid hex character!")
}
/* <Char[]>.toDecimal() converts the receiver object into the equivalent integer via base arithmetic on each hex input
* character from right-to-left.
* Requires: The receiver object consists of only hexadecimal characters, i.e. only [0-9] and [a-f] as constituents.
*/
private fun CharArray.toDecimal(): Int =
this.fold(0) { acc, c -> 16 * acc + c.toDecimal() }
/* <Char>.toDec() converts the receiver object to the equivalent integer.
* Requires: The receiver object must be input as a single base-64 number, i.e. it is either [0-9],[a-z],[A-Z], or [+,/].
*/
private fun Char.toDec(): Int =
when (this) {
in 'A'..'Z' -> this - 'A'
in 'a'..'z' -> this - 'a' + 26
in '0'..'9' -> this - '0' + 52
'+' -> 62
'/' -> 63
'=' -> 0 // Special character used for padding in base-64, apparently.
else -> throw IllegalArgumentException("$this is not a valid base-64 character!")
}
/* <Char[]>.toDec() converts the receiver object into the equivalent integer via base arithmetic on each base-64 input
* character from right-to-left.
* Requires: The receiver object consists of only base-64 characters, i.e. only [0-9],[a-z],[A-Z], and [+,/] as constituents.
*/
private fun CharArray.toDec(): Int =
this.fold(0) { acc, c -> 64 * acc + c.toDec() }
/* <Char[]>.chunkToSixtyFour() converts the receiver object from its hexadecimal representation to a base-64
* representation by converting the three hexadecimal characters into two base-64 characters.
* Requires: The receiver object consists of at most three hexadecimal characters, i.e. between 000 and fff.
*/
private fun chunkToSixtyFour(chars: CharArray): CharArray {
/* intToChar(num) converts [num] to its base-64 character representation.
* Requires: 0 <= [num] <= 63.
*/
fun intToChar(num: Int): Char {
val mod = num % 26
return when (num / 26) {
0 -> 'A' + mod
1 -> 'a' + mod
2 -> when (mod) {
10 -> '+'
11 -> '/'
else -> mod.toString()[0] // Another hack based on the representation.
}
else -> throw IllegalStateException("$num is greater than 63 in base-64!") // Even 63/26 = 2.
}.toChar()
}
val dec = chars.toDecimal()
val msb = dec / 64
val lsb = dec - (64 * msb)
return intArrayOf(msb,lsb)
.map(::intToChar)
.toCharArray()
}
/* <Char[]>.chunkToHex() converts the receiver object from its base-64 representation to a hexadecimal representation
* by converting the two base-64 characters into three hexadecimal characters.
* Requires: The receiver object consists of at most two base-64 characters, i.e. between 00 and //.
*/
private fun chunkToHex(chars: CharArray): CharArray {
/* toHex(num) converts [num] to its hex character representation.
* Requires: 0 <= [num] <= 15.
*/
fun toHex(num: Int): Char =
when (num) {
in 0..9 -> '0' + num
in 10..15 -> 'a' + num - 10
else -> throw IllegalArgumentException("$num is not an integer between 0 and 15.")
}
val dec = chars.toDec()
val msb = dec / 256
val sb = (dec - (256 * msb)) / 16
val lsb = dec - (256 * msb) - (16 * sb)
return intArrayOf(msb,sb,lsb)
.map(::toHex)
.toCharArray()
}
/* <Char[]>.toSixtyFour() converts the receiver object from its hexadecimal representation to a base-64 representation
* by converting each chunk of three hexadecimal characters into two base-64 characters.
* Requires: The receiver object consists of only hexadecimal characters, i.e. only [0-9] and [a-f] as constituents.
*/
private fun CharArray.toSixtyFour(): CharArray {
val numGroups = this.size / 3
val chs = CharArray(2 * numGroups)
for (i in 0 until numGroups) {
val sub = this.slice(3 * i until 3 * i + 3).toCharArray()
val convertedChs = chunkToSixtyFour(sub)
chs[2*i] = convertedChs[0]
chs[2*i+1] = convertedChs[1]
}
val last = this.slice(3 * numGroups until this.size).toCharArray()
val convertedChs = chunkToSixtyFour(last)
return chs + if (this.size % 3 != 0) convertedChs else CharArray(0)
}
/* <Char[]>.toHex() converts the receiver object from its base-64 representation to a hexadecimal representation by
* converting each chunk of two base-64 characters into three hexadecimal characters.
* Requires: The receiver object consists of only base-64 characters, i.e. only [0-9],[a-z],[A-Z], and [+,/] as constituents.
*/
private fun CharArray.toHex(): CharArray {
val numGroups = this.size / 2
val chs = CharArray(3 * numGroups)
for (i in 0 until numGroups) {
val sub = this.slice(2 * i until 2 * i + 2).toCharArray()
val convertedChs = chunkToHex(sub)
chs[3*i] = convertedChs[0]
chs[3*i+1] = convertedChs[1]
chs[3*i+2] = convertedChs[2]
}
val last = this.slice(2 * numGroups until this.size).toCharArray()
val convertedChs = chunkToHex(last)
return chs + if (this.size % 2 != 0) convertedChs else CharArray(0) // Parallel behavior to above.
}
/* convert(hex) returns the string [hex] in a base-64 representation of itself.
* Requires: [hex] consists of only hexadecimal characters, i.e. only [0-9] and [a-f] as constituents.
*/
fun convert(hex: String): String {
return hex
.toCharArray()
.regroup(3)
.toSixtyFour()
.regroup(2)
.joinToString("")
}
/* unconvert(base) returns the string [base] in a hexadecimal representation of itself.
* Requires: [base] consists of only base-64 characters, i.e. only [0-9],[a-z],[A-Z], and [+,/] as constituents.
*/
fun unconvert(base: String): String {
return base
.toCharArray()
.regroup(2)
.toHex()
.regroup(3)
.joinToString("") // Exactly the opposite process as convert(hex).
}
} | gpl-2.0 | e2785a1b8007cc3ba6210802bcc3bc44 | 40.307292 | 127 | 0.611349 | 3.652695 | false | false | false | false |
ealva-com/ealvalog | ealvalog/src/main/java/com/ealva/ealvalog/NullMarker.kt | 1 | 1519 | /*
* Copyright 2017 Eric A. Snell
*
* This file is part of eAlvaLog.
*
* 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.ealva.ealvalog
import java.io.ObjectStreamException
import java.util.Formatter
/**
* A no-op implementation of the [Marker] interface
*
* Created by Eric A. Snell on 2/28/17.
*/
@Suppress("unused")
object NullMarker : Marker {
private const val serialVersionUID = -6861067652369180156L
override val name = "NullMarker"
override fun add(marker: Marker) = false
override fun remove(marker: Marker) = false
override fun isOrContains(marker: Marker) = false
override fun isOrContains(markerName: String) = false
override fun iterator(): Iterator<Marker> = emptyList<Marker>().iterator()
override fun toStringBuilder(builder: StringBuilder, includeContained: Boolean) = builder
override fun formatTo(formatter: Formatter, flags: Int, width: Int, precision: Int) {}
@Throws(ObjectStreamException::class)
private fun readResolve(): Any = NullMarker
}
| apache-2.0 | 5b84381390f695263cd25ce0ea5c093a | 35.166667 | 91 | 0.744569 | 3.935233 | false | false | false | false |
DemonWav/autosync | src/main/kotlin/com/demonwav/autosync/AutoSyncConfigurable.kt | 1 | 5896 | package com.demonwav.autosync
import com.intellij.openapi.fileChooser.FileChooser
import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory
import com.intellij.openapi.options.Configurable
import com.intellij.openapi.options.ConfigurationException
import com.intellij.openapi.project.Project
import com.intellij.openapi.wm.WindowManager
import com.intellij.ui.TableUtil
import com.intellij.ui.ToolbarDecorator
import com.intellij.ui.components.JBLabel
import com.intellij.ui.table.JBTable
import com.intellij.util.ArrayUtil
import com.intellij.util.ui.UIUtil
import org.jetbrains.annotations.Nls
import java.awt.BorderLayout
import java.awt.Dimension
import javax.swing.JCheckBox
import javax.swing.JComponent
import javax.swing.JPanel
import javax.swing.JSpinner
import javax.swing.JTable
import javax.swing.ListSelectionModel
import javax.swing.SpinnerNumberModel
class AutoSyncConfigurable(private val project: Project) : Configurable {
private lateinit var panel: JPanel
private lateinit var enableCheckBox: JCheckBox
private lateinit var timeSpinner: JSpinner
private lateinit var excludeDirsPanel: JPanel
private var table: JTable? = null
@Nls
override fun getDisplayName() = "Auto Sync Settings"
override fun getHelpTopic() = null
override fun createComponent(): JComponent? {
timeSpinner.model = model
createExcludePanel(excludeDirsPanel)
return panel
}
override fun isModified(): Boolean {
val settings = AutoSyncSettings.getInstance(project)
return settings.isEnabled != enableCheckBox.isSelected || settings.timeBetweenSyncs != (timeSpinner.value as Number).toLong() ||
includedDirsIsModified()
}
private fun includedDirsIsModified(): Boolean {
val settings = AutoSyncSettings.getInstance(project)
val tableModel = table!!.model as TableModel
if (settings.excludedUrls.size != tableModel.rowCount) {
return true
}
val count = tableModel.rowCount
return (0 until count).any { settings.excludedUrls[it] != tableModel.getValueAt(it).url }
}
@Throws(ConfigurationException::class)
override fun apply() {
val settings = AutoSyncSettings.getInstance(project)
settings.modified = true
settings.isEnabled = enableCheckBox.isSelected
settings.timeBetweenSyncs = (timeSpinner.value as Number).toLong()
WindowManager.getInstance().getFrame(project)?.let { frame ->
frame.removeWindowFocusListener(AutoSyncFocusListener) // for good measure
if (settings.isEnabled) {
frame.addWindowFocusListener(AutoSyncFocusListener)
}
}
saveData()
}
override fun reset() {
val settings = AutoSyncSettings.getInstance(project)
enableCheckBox.isSelected = settings.isEnabled
timeSpinner.value = settings.timeBetweenSyncs
val array = ArrayUtil.newIntArray(table!!.rowCount)
for (i in 0 until table!!.rowCount) {
array[i] = i
}
TableUtil.selectRows(table!!, array)
TableUtil.removeSelectedItems(table!!)
val tableModel = table!!.model as TableModel
val excludedUrls = AutoSyncSettings.getInstance(project).excludedUrls
for (url in excludedUrls) {
tableModel.addTableItem(TableItem(url))
}
}
private fun createExcludePanel(panel: JPanel) {
val model = createModel()
table = JBTable(model)
table?.apply {
intercellSpacing = Dimension(0, 0)
setDefaultRenderer(TableItem::class.java, Renderer())
setShowGrid(false)
dragEnabled = false
showHorizontalLines = false
showVerticalLines = false
selectionModel.selectionMode = ListSelectionModel.MULTIPLE_INTERVAL_SELECTION
}
val tablePanel = ToolbarDecorator.createDecorator(table!!).setAddAction {
val descriptor = FileChooserDescriptorFactory.createAllButJarContentsDescriptor()
descriptor.title = "Choose directories and files to include"
val files = FileChooser.chooseFiles(descriptor, table, project, null)
val tableModel = table!!.model as TableModel
var changes = false
for (file in files) {
if (file != null) {
tableModel.addTableItem(TableItem(file))
changes = true
}
}
if (changes) {
TableUtil.selectRows(table!!, intArrayOf(model.rowCount - 1))
}
}.setRemoveAction {
TableUtil.removeSelectedItems(table!!)
}.createPanel()
val mainPanel = JPanel(BorderLayout())
mainPanel.add(tablePanel, BorderLayout.CENTER)
mainPanel.add(JBLabel("Manage directories and files to include in the sync process.", UIUtil.ComponentStyle.SMALL,
UIUtil.FontColor.BRIGHTER), BorderLayout.NORTH)
panel.add(mainPanel, BorderLayout.CENTER)
}
private fun createModel() : TableModel {
val tableModel = TableModel()
val excludedUrls = AutoSyncSettings.getInstance(project).excludedUrls
for (url in excludedUrls) {
tableModel.addTableItem(TableItem(url))
}
return tableModel
}
private fun saveData() {
TableUtil.stopEditing(table!!)
val count = table!!.rowCount
val urls = ArrayUtil.newStringArray(count)
for (row in 0 until count) {
val item = (table!!.model as TableModel).getValueAt(row)
urls[row] = item.url
}
AutoSyncSettings.getInstance(project).excludedUrls = mutableListOf(*urls)
}
companion object {
private val model = SpinnerNumberModel(15, 0, 60, 1)
}
}
| mit | 5b63f085c16deffd0b48f5d1338eb1e9 | 34.305389 | 136 | 0.669776 | 5.082759 | false | false | false | false |
Tvede-dk/CommonsenseAndroidKotlin | widgets/src/test/kotlin/com/commonsense/android/kotlin/views/input/selection/SingleSelectionHandlerTest.kt | 1 | 6444 | package com.commonsense.android.kotlin.views.input.selection
import com.commonsense.android.kotlin.test.*
import org.junit.*
/**
* Created by kasper on 25/08/2017.
*/
class SingleSelectionHandlerTest {
@Test
fun testSelectionStrategy() {
val selectionHandler = SingleSelectionHandler<String> {}
val toggle1 = MockedToggleableViewNoCallback("1234")
selectionHandler.addView(toggle1)
toggle1.checked.assert(false, "should not be marked by default")
selectionHandler.setSelectedValue("1234")
toggle1.checked.assert(true, "should be marked when asked to")
val toggle2 = MockedToggleableViewNoCallback("123")
selectionHandler.addView(toggle2)
toggle1.checked.assert(true)
toggle2.checked.assert(false, "should not be marked by default")
selectionHandler.setSelectedValue("123")
toggle1.checked.assert(false)
toggle2.checked.assert(true)
val toggle3 = MockedToggleableViewNoCallback("abc")
selectionHandler.addView(toggle3)
toggle1.checked.assert(false)
toggle2.checked.assert(true)
toggle3.checked.assert(false)
selectionHandler.setSelectedValue("1234")
toggle1.checked.assert(true)
toggle2.checked.assert(false)
toggle3.checked.assert(false)
selectionHandler.setSelectedValue("abc")
toggle1.checked.assert(false)
toggle2.checked.assert(false)
toggle3.checked.assert(true)
}
@Test
fun testCallbackFeature() {
val selectionHandler = SingleSelectionHandler<String> {}
val toggle1 = MockedToggleableViewWithCallback("1234")
selectionHandler.addView(toggle1)
toggle1.checked.assert(false, "should not be marked by default")
selectionHandler.setSelectedValue("1234")
toggle1.checked.assert(true, "should be marked when asked to")
val toggle2 = MockedToggleableViewWithCallback("123")
selectionHandler.addView(toggle2)
toggle1.checked.assert(true)
toggle2.checked.assert(false, "should not be marked by default")
toggle2.checked = true
toggle1.checked.assert(false)
toggle2.checked.assert(true)
toggle2.deselect()
toggle1.checked.assert(false)
toggle2.checked.assert(true)
toggle1.checked = true
toggle1.checked.assert(true)
toggle2.checked.assert(false)
toggle1.deselect()
toggle1.checked.assert(true)
toggle2.checked.assert(false)
toggle2.deselect()
toggle1.checked.assert(true)
toggle2.checked.assert(false)
val toggle3 = MockedToggleableViewWithCallback("qwerty")
selectionHandler += toggle3
toggle1.checked.assert(true)
toggle2.checked.assert(false)
toggle3.checked.assert(false)
toggle3.checked = true
toggle1.checked.assert(false)
toggle2.checked.assert(false)
toggle3.checked.assert(true)
toggle3.select()
toggle1.checked.assert(false)
toggle2.checked.assert(false)
toggle3.checked.assert(true)
toggle2.select()
toggle1.checked.assert(false)
toggle2.checked.assert(true)
toggle3.checked.assert(false)
}
@Test
fun testCallback() {
var ourValue: String? = null
val selectionHandler = SingleSelectionHandler<String> {
ourValue = it
}
val toggle1 = MockedToggleableViewWithCallback("1234")
selectionHandler.addView(toggle1)
toggle1.checked.assert(false)
toggle1.checked = true
"1234".assert(ourValue ?: "")
ourValue = null
(ourValue == null).assert(true)
val toggle2 = MockedToggleableViewWithCallback("qwe")
selectionHandler.addView(toggle2)
(ourValue == null).assert(true)
toggle2.checked = true
"qwe".assert(ourValue!!)
}
@Test
fun testDeselection() {
var ourValue: String? = null
val selectionHandler = SingleSelectionHandler<String> {
ourValue = it
}
val toggle1 = MockedToggleableViewWithCallback("1234")
selectionHandler += toggle1
toggle1.checked = true
"1234".assertNotNullAndEquals(ourValue)
toggle1.checked = false
"1234".assertNotNullAndEquals(ourValue)
//before setup should still resepct it.
selectionHandler.allowDeselection { ourValue = "<null>" }
toggle1.checked = false
"<null>".assertNotNullAndEquals(ourValue)
toggle1.checked = true
"1234".assertNotNullAndEquals(ourValue)
toggle1.checked = false
"<null>".assertNotNullAndEquals(ourValue)
val toggle2 = MockedToggleableViewWithCallback("4321")
selectionHandler += toggle2
toggle2.checked = true
toggle1.checked.assert(false)
"4321".assertNotNullAndEquals(ourValue)
toggle2.checked = false
"<null>".assertNotNullAndEquals(ourValue)
toggle1.checked.assert(false)
toggle2.checked.assert(false)
}
@Ignore
@Test
fun getSelection() {
}
@Ignore
@Test
fun setSelection() {
}
@Ignore
@Test
fun allowDeselection() {
}
@Ignore
@Test
fun setSelectedValue() {
}
@Ignore
@Test
fun handleSelectionChanged() {
}
@Ignore
@Test
fun isSelected() {
}
@Ignore
@Test
fun removeSelected() {
}
}
private class MockedToggleableViewNoCallback(myStr: String) : ToggleableView<String> {
override fun clearOnSelectionChanged() {
}
override var checked: Boolean = false
override val value = myStr
override fun setOnSelectionChanged(callback: SelectionToggleCallback<String>) {
}
}
private class MockedToggleableViewWithCallback(myStr: String) : ToggleableView<String> {
override fun clearOnSelectionChanged() {
}
private var _checked: Boolean = false
override val value = myStr
private var selectionCallback: SelectionToggleCallback<String>? = null
override var checked: Boolean
get() = _checked
set(value) {
_checked = value
selectionCallback?.invoke(this, value)
}
override fun setOnSelectionChanged(callback: SelectionToggleCallback<String>) {
this.selectionCallback = callback
}
} | mit | be11e9514e2a97ed4047187bdba1360e | 25.854167 | 88 | 0.650993 | 4.374745 | false | true | false | false |
arkon/LISTEN.moe-Unofficial-Android-App | app/src/main/java/me/echeung/moemoekyun/viewmodel/BaseViewModel.kt | 1 | 2491 | package me.echeung.moemoekyun.viewmodel
import android.graphics.Bitmap
import android.os.SystemClock
import android.view.View
import android.widget.Chronometer
import android.widget.ImageView
import android.widget.TextView
import androidx.annotation.ColorInt
import androidx.databinding.BaseObservable
import androidx.databinding.Bindable
import androidx.databinding.BindingAdapter
import me.echeung.moemoekyun.BR
import me.echeung.moemoekyun.util.ext.loadImage
import me.echeung.moemoekyun.util.ext.toggleVisibility
import me.echeung.moemoekyun.util.ext.transitionBackgroundColor
abstract class BaseViewModel : BaseObservable() {
// Network connection
// ========================================================================
@get:Bindable
var isConnected: Boolean = false
set(isConnected) {
field = isConnected
notifyPropertyChanged(BR.connected)
}
// Auth status
// ========================================================================
@get:Bindable
var isAuthed: Boolean = false
set(isAuthed) {
field = isAuthed
notifyPropertyChanged(BR.authed)
}
companion object {
@JvmStatic
@BindingAdapter("android:alpha")
fun setAlpha(v: View, visible: Boolean) {
v.alpha = (if (visible) 1 else 0).toFloat()
}
@JvmStatic
@BindingAdapter("android:selected")
fun setSelected(v: TextView, selected: Boolean) {
v.isSelected = selected
}
@JvmStatic
@BindingAdapter("android:visibility")
fun setVisibility(v: View, visible: Boolean) {
v.toggleVisibility(visible)
}
@JvmStatic
@BindingAdapter("android:imageBitmap")
fun loadImage(v: ImageView, bitmap: Bitmap?) {
v.loadImage(bitmap)
}
@JvmStatic
@BindingAdapter("android:imageUrl")
fun loadImage(v: ImageView, url: String?) {
v.loadImage(url)
}
@JvmStatic
@BindingAdapter("android:transitionBackgroundColor")
fun transitionBackgroundColor(v: View, @ColorInt toColor: Int) {
v.transitionBackgroundColor(toColor)
}
@JvmStatic
@BindingAdapter("android:chronometerProgress")
fun setChronometerProgress(v: Chronometer, progress: Long) {
v.base = SystemClock.elapsedRealtime() - progress
v.start()
}
}
}
| mit | 1b0a355381b9e453189fbabf8678f6a0 | 28.654762 | 79 | 0.610197 | 5.09407 | false | false | false | false |
raxden/square | square/src/main/java/com/raxdenstudios/square/interceptor/ActivityInterceptor.kt | 2 | 2292 | package com.raxdenstudios.square.interceptor
import android.app.Activity
import android.app.Application
import android.os.Bundle
import android.support.v4.app.FragmentActivity
import android.support.v4.app.FragmentManager
abstract class ActivityInterceptor<TInterceptor : Interceptor, TCallback : HasInterceptor>(
val mCallback: TCallback
) : Application.ActivityLifecycleCallbacks, Interceptor {
private var mSavedInstanceState: Bundle? = null
override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle?) {}
open fun onActivityRestoreInstanceState(activity: Activity, savedInstanceState: Bundle) {
mSavedInstanceState = savedInstanceState
}
// =============================================================================================
override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {
mCallback.onInterceptorCreated(this as TInterceptor)
savedInstanceState?.also { onActivityRestoreInstanceState(activity, savedInstanceState) }
}
// =============================================================================================
override fun onActivityStarted(activity: Activity) {
onActivityStarted(activity, mSavedInstanceState)
}
protected open fun onActivityStarted(activity: Activity, savedInstanceState: Bundle?) {}
// =============================================================================================
override fun onActivityResumed(activity: Activity) {}
// =============================================================================================
override fun onActivityPaused(activity: Activity) {}
// =============================================================================================
override fun onActivityStopped(activity: Activity) {}
// =============================================================================================
override fun onActivityDestroyed(activity: Activity) {
mSavedInstanceState = null
}
// =============================================================================================
protected fun getFragmentManager(activity: Activity) : FragmentManager? = (activity as? FragmentActivity)?.supportFragmentManager
} | apache-2.0 | 79e7390515c2484e36ff3866affc010f | 39.22807 | 133 | 0.534031 | 7.322684 | false | false | false | false |
felipebz/sonar-plsql | zpa-core/src/test/kotlin/org/sonar/plugins/plsqlopen/api/statements/UpdateStatementTest.kt | 1 | 2347 | /**
* Z PL/SQL Analyzer
* Copyright (C) 2015-2022 Felipe Zorzo
* mailto:felipe AT felipezorzo DOT com DOT br
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.plugins.plsqlopen.api.statements
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import org.sonar.plugins.plsqlopen.api.PlSqlGrammar
import org.sonar.plugins.plsqlopen.api.RuleTest
import com.felipebz.flr.tests.Assertions.assertThat
class UpdateStatementTest : RuleTest() {
@BeforeEach
fun init() {
setRootRule(PlSqlGrammar.UPDATE_STATEMENT)
}
@Test
fun matchesSimpleUpdate() {
assertThat(p).matches("update tab set x = 1;")
}
@Test
fun matchesUpdateWithWhere() {
assertThat(p).matches("update tab set x = 1 where y = 1;")
}
@Test
fun matchesUpdateWithWhereCurrentOf() {
assertThat(p).matches("update tab set x = 1 where current of cur;")
}
@Test
fun matchesUpdateMultipleColumns() {
assertThat(p).matches("update tab set x = 1, y = 1;")
}
@Test
fun matchesUpdateWithAlias() {
assertThat(p).matches("update tab t set t.x = 1;")
}
@Test
fun matchesUpdateWithSchema() {
assertThat(p).matches("update sch.tab set sch.tab.x = 1;")
}
@Test
fun matchesLabeledUpdate() {
assertThat(p).matches("<<foo>> update tab set x = 1;")
}
@Test
fun matchesUpdateWithReturningInto() {
assertThat(p).matches("update tab set x = 1 returning x into y;")
}
@Test
fun matchesUpdateDefaultValue() {
assertThat(p).matches("update tab set x = default;")
}
}
| lgpl-3.0 | 5ef5f8a4a5b3e9dacf7c6ec84154b685 | 28.3375 | 75 | 0.680017 | 4.067591 | false | true | false | false |
maddog05/MaddogUtilities | maddogutilities/src/main/java/com/maddog05/maddogutilities/extension/StringExtensions.kt | 1 | 784 | package com.maddog05.maddogutilities.extension
import android.util.Patterns
import android.webkit.URLUtil
fun String.isEmailValid(): Boolean {
val email = this.trim()
if (email.isEmpty()) return false
return email.isNotEmpty() && Patterns.EMAIL_ADDRESS.matcher(email).matches()
}
fun String.isHttpUrlValid(): Boolean {
val url = this.trim()
if (url.isEmpty())
return false
return url.isNotEmpty() && URLUtil.isValidUrl(url)
}
fun String.capitalize(): String {
val text = this
val array = text.toCharArray()
array[0] = Character.toUpperCase(array[0])
for (i in 1 until array.size) {
if (Character.isWhitespace(array[i - 1])) {
array[i] = Character.toUpperCase(array[i])
}
}
return String(array)
} | mit | 20a6d0bf329deaa5083092415a4dbb1d | 25.166667 | 80 | 0.66199 | 3.78744 | false | false | false | false |
GabrielCastro/open_otp | app/src/main/kotlin/ca/gabrielcastro/openotp/ui/scan/BarcodeScanActivity.kt | 1 | 1992 | package ca.gabrielcastro.openotp.ui.scan
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import ca.gabrielcastro.openotp.app.App
import ca.gabrielcastro.openotp.model.Totp
import ca.gabrielcastro.openotp.model.totpFrom
import ca.gabrielcastro.openotp.ui.base.BaseActivity
import com.google.zxing.integration.android.IntentIntegrator
import timber.log.Timber
import javax.inject.Inject
class BarcodeScanActivity : BaseActivity() {
companion object {
const val RESULT_INVALID_CODE = Activity.RESULT_FIRST_USER + 1
fun intent(context: Context): Intent {
return Intent(context, BarcodeScanActivity::class.java)
}
}
@Inject
lateinit var presenter: ScanContract.Presenter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setResult(RESULT_CANCELED)
App.component(this).scanComponent.inject(this)
val integrator = IntentIntegrator(this)
integrator.setPrompt("Scan the verification code")
integrator.initiateScan()
}
private fun totpForData(requestCode: Int, resultCode: Int, data: Intent?): Totp? {
if (data == null) {
return null
}
val result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data) ?: return null
val contents = result.contents ?: return null
return totpFrom(contents)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
val totp = totpForData(requestCode, resultCode, data)
if (totp != null) {
Timber.e("Found totp: $totp")
presenter.addTotp(totp)
setResult(RESULT_OK)
} else {
Timber.e("Invalid totp")
presenter.invalidScan()
setResult(RESULT_INVALID_CODE)
}
finish()
}
}
| mit | bb7117c84a3b410c7d59baf8776ed791 | 32.762712 | 103 | 0.681225 | 4.466368 | false | false | false | false |
Exaltead/SceneClassifier | DataExtraction/src/main/kotlin/features/Feature.kt | 1 | 555 | package features
data class Feature(val location: String, val type: String, val features: FloatArray) {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as Feature
if (location != other.location) return false
if (type != other.type) return false
return true
}
override fun hashCode(): Int {
var result = location.hashCode()
result = 31 * result + type.hashCode()
return result
}
}
| gpl-3.0 | 7b8efce04fdd9f77abeb95c726c294f1 | 25.428571 | 86 | 0.612613 | 4.625 | false | false | false | false |
Asqatasun/Asqatasun | runner/asqatasun-runner/src/main/kotlin/org/asqatasun/runner/AsqatasunCli.kt | 1 | 14447 | /*
* Asqatasun - Automated webpage assessment
* Copyright (C) 2008-2020 Asqatasun.org
*
* This file is part of Asqatasun.
*
* Asqatasun 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/>.
*
* Contact us by mail: asqatasun AT asqatasun DOT org
*/
package org.asqatasun.runner
import org.apache.commons.cli.*
import org.apache.commons.io.FileUtils
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.config.AutowireCapableBeanFactory
import org.springframework.context.ApplicationContext
import org.springframework.context.annotation.AnnotationConfigApplicationContext
import java.io.FileNotFoundException
import java.io.PrintStream
import java.net.MalformedURLException
import java.net.URL
/**
* This class launches Asqatasun with urls passed as arguments by the user.
*
* @author jkowalczyk
*/
class AsqatasunCli {
companion object {
val logger: Logger = LoggerFactory.getLogger(AsqatasunCli::class.java)
private var referential = Referential.RGAA_3_0
private var level = Level.SILVER
private var auditType = AuditType.PAGE_AUDIT
private const val DEFAULT_XMS_VALUE = 64
private val OPTIONS = createOptions()
@JvmStatic
fun main(args: Array<String>) {
val clp: CommandLineParser = DefaultParser()
try {
val cl = clp.parse(OPTIONS, args)
if (cl.hasOption("h")) {
printUsage()
return
}
if (cl.hasOption("f")) {
val ffPath = cl.getOptionValue("f")
if (isValidPath(ffPath, "f", false)) {
System.setProperty("webdriver.firefox.bin", ffPath)
} else {
printUsage()
return
}
}
if (cl.hasOption("d")) {
val display = cl.getOptionValue("d")
if (isValidDisplay(display, "d")) {
System.setProperty("display", ":$display")
} else {
printUsage()
return
}
}
if (cl.hasOption("r")) {
val ref = cl.getOptionValue("r")
if (Referential.fromCode(ref) == null) {
println("\nThe referential \"$ref\" doesn't exist.\n")
printUsage()
return
}
this.referential = Referential.fromCode(ref)!!
}
if (cl.hasOption("l")) {
val level = cl.getOptionValue("l")
if (Level.fromCode(level) == null) {
println("\nThe level \"" + level + "\" doesn't exist.\n");
printUsage()
return
}
this.level = Level.fromCode(level)!!
}
if (cl.hasOption("t")) {
val auditType = cl.getOptionValue("t")
if (AuditType.fromCode(auditType) == null) {
println("\nThe audit type \"$auditType\" doesn't exist.\n")
printUsage()
return
}
this.auditType = AuditType.fromCode(auditType)!!
}
if (cl.hasOption("o")) {
val outputDir = cl.getOptionValue("o")
if (isValidPath(outputDir, "o", true)) {
try {
System.setOut(PrintStream(outputDir))
} catch (ex: FileNotFoundException) {
printUsage()
return
}
} else {
printUsage()
return
}
}
if (cl.hasOption("x")) {
val xmxValue = cl.getOptionValue("x")
if (!isValidXmxValue(xmxValue)) {
printUsage()
return
}
}
when (auditType) {
AuditType.PAGE_AUDIT -> {
if (!isValidPageUrl(cl)) {
printUsage()
return
}
initSpringContextAndGetRunner()
.runAuditOnline(cl.args, referential.code, level.code)
}
AuditType.SCENARIO_AUDIT -> {
if (!isValidScenarioPath(cl)) {
printUsage()
return
}
initSpringContextAndGetRunner().runAuditScenario(cl.args.first(), referential.code, level.code)
}
AuditType.UPLOAD_AUDIT -> {
if (!isValidFilePath(cl)) {
printUsage()
return
}
initSpringContextAndGetRunner().runAuditUpload(cl.args, referential.code, level.code)
}
AuditType.SITE_AUDIT -> {
println("Functionality is not working on cli interface")
printUsage()
}
}
} catch (ex: ParseException) {
logger.error("Cannot parse scenario or file", ex)
}
}
/**
*
* @return an instance of AsqatasunRunner
*/
private fun initSpringContextAndGetRunner(): AsqatasunRunner {
val context: ApplicationContext = AnnotationConfigApplicationContext("org.asqatasun")
val asqatasunRunner = AsqatasunRunner()
//the magic: auto-wire the instance with all its dependencies:
context.autowireCapableBeanFactory.autowireBeanProperties(asqatasunRunner,
AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, true)
return asqatasunRunner
}
/**
* Create the asqatasun command line interface options
* @return the options to launch asqatasun cli
*/
private fun createOptions() =
Options()
.addOption(Option.builder("h")
.longOpt("help")
.desc("Show this message.")
.hasArg(false)
.required(false)
.build())
.addOption(Option.builder("o")
.longOpt("output")
.desc("Path to the output result file.")
.hasArg(true)
.required(false)
.build())
.addOption(Option.builder("f")
.longOpt("firefox-bin")
.desc("Path to the firefox bin.")
.hasArg(true)
.required(false)
.build())
.addOption(Option.builder("d")
.longOpt("display")
.desc("Value of the display")
.hasArg(true)
.required(false)
.build())
.addOption(Option.builder("r")
.longOpt("referential")
.desc("""Referential :
- "Aw22" for Accessiweb 2.2
- "Rgaa30" for Rgaa 3.0 (default)
- "Rgaa40" for Rgaa 4.0
- "Seo" for SEO 1.0""")
.hasArg(true)
.required(false)
.build())
.addOption(Option.builder("l")
.longOpt("level")
.desc("""Level :
- "Or" for Gold level or AAA level,
- "Ar" for Silver level or AA level (default),
- "Bz" for Bronze level or A level""")
.hasArg(true)
.required(false)
.build())
.addOption(Option.builder("t")
.longOpt("audit-type")
.desc("""Audit type :
- "Page" for page audit (default)
- "File" for file audit
- "Scenario" for scenario audit
- "Site" for site audit""")
.hasArg(true)
.required(false)
.build())
.addOption(Option.builder("x")
.longOpt("xmx-value")
.desc("""Xmx value set to the process (without 'M' at the end):
- default is 256
- must be superior to 64 (Xms value)""")
.hasArg(true)
.required(false)
.build())
/**
* Print usage
*/
private fun printUsage() =
HelpFormatter().printHelp(
"./bin/asqatasun.sh [OPTIONS]... [URL OR FILE OR SCENARIO]...\n",
OPTIONS)
/**
*
* @param path
* @param option
* @param testWritable
* @return whether the given path is valid for the given argument
*/
private fun isValidPath(path: String, option: String, testWritable: Boolean): Boolean {
val file = FileUtils.getFile(path)
if (file.exists() && file.canExecute() && file.canRead()) {
if (!testWritable) {
return true
} else if (file.canWrite()) {
return true
}
}
println("\n$path is an invalid path for $option option.\n")
return false
}
/**
*
* @param display
* @param option
* @return whether the given display is valid
*/
private fun isValidDisplay(display: String, option: String): Boolean {
return try {
Integer.valueOf(display)
true
} catch (nme: NumberFormatException) {
println("\n$display is invalid for $option option.\n")
false
}
}
/**
*
* @param xmxStr
* @return whether the given level is valid
*/
private fun isValidXmxValue(xmxStr: String): Boolean {
println(xmxStr)
try {
val xmxValue = Integer.valueOf(xmxStr)
if (xmxValue <= DEFAULT_XMS_VALUE) {
println("\nThe value of the Xmx value \"$xmxStr\" must be superior to $DEFAULT_XMS_VALUE.\n")
return false
}
} catch (nfe: NumberFormatException) {
println("\nThe format of the Xmx value \"$xmxStr\" is incorrect.\n")
return false
}
return true
}
/**
*
* @param auditType
* @return whether the given level is valid
*/
private fun isValidAuditType(auditType: String) = (AuditType.fromCode(auditType) != null)
/**
*
* @param cl
* @return whether the given level is valid
*/
private fun isValidPageUrl(cl: CommandLine): Boolean {
if (cl.argList.isEmpty()) {
println("\nPlease specify at least one URL\n")
return false
}
for (arg in cl.args) {
try {
URL(arg)
} catch (ex: MalformedURLException) {
println("\nThe URL $arg is malformed\n")
return false
}
}
return true
}
private fun isValidSiteUrl(cl: CommandLine): Boolean {
if (cl.argList.isEmpty()) {
println("\nPlease specify at least one URL\n")
return false
}
if (cl.argList.size > 1) {
println("\nOnly one URL is expected\n")
return false
}
try {
URL(cl.args[0])
} catch (ex: MalformedURLException) {
println("\nThe URL " + cl.args[0] + " is malformed\n")
return false
}
return true
}
private fun isValidFilePath(cl: CommandLine): Boolean {
if (cl.argList.isEmpty()) {
println("\nPlease specify at least one file\n")
return false
}
for (arg in cl.args) {
val file = FileUtils.getFile(arg)
if (!file.canRead()) {
println("\nThe file " + file.absolutePath + " is unreadable.\n")
return false
}
}
return true
}
private fun isValidScenarioPath(cl: CommandLine): Boolean {
if (cl.argList.isEmpty()) {
println("\nPlease specify at least one scenario\n")
return false
}
if (cl.argList.size > 1) {
println("\nOnly one scenario is expected\n")
return false
}
val scenario = FileUtils.getFile(cl.args[0])
if (!scenario.canRead()) {
println("\nThe scenario file is unreadable.\n")
return false
}
return true
}
}
}
| agpl-3.0 | cb730aa9494dfe97dee981756eed8009 | 36.427461 | 119 | 0.45615 | 5.268782 | false | false | false | false |
jriley/HackerNews | mobile/src/main/kotlin/dev/jriley/hackernews/Constants.kt | 1 | 175 | package dev.jriley.hackernews
object Constants {
val ID = "id"
val TYPE = "type"
val BOOKMARKED = "bookmarked"
val DELETED = "deleted"
val TAG = "HN3W5"
} | mpl-2.0 | efb33c56136e39bf56ab35fea1220608 | 18.555556 | 33 | 0.628571 | 3.301887 | false | false | false | false |
square/wire | wire-library/wire-runtime/src/nativeMain/kotlin/com/squareup/wire/ProtoAdapter.kt | 1 | 8184 | /*
* Copyright 2015 Square Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.squareup.wire
import okio.BufferedSink
import okio.BufferedSource
import okio.ByteString
import kotlin.reflect.KClass
actual abstract class ProtoAdapter<E> actual constructor(
internal actual val fieldEncoding: FieldEncoding,
actual val type: KClass<*>?,
actual val typeUrl: String?,
actual val syntax: Syntax,
actual val identity: E?,
actual val sourceFile: String?,
) {
internal actual val packedAdapter: ProtoAdapter<List<E>>? = when {
this is PackedProtoAdapter<*> || this is RepeatedProtoAdapter<*> -> null
fieldEncoding == FieldEncoding.LENGTH_DELIMITED -> null
else -> commonCreatePacked()
}
internal actual val repeatedAdapter: ProtoAdapter<List<E>>? = when {
this is RepeatedProtoAdapter<*> || this is PackedProtoAdapter<*> -> null
else -> commonCreateRepeated()
}
/** Returns the redacted form of `value`. */
actual abstract fun redact(value: E): E
/**
* The size of the non-null data `value`. This does not include the size required for a
* length-delimited prefix (should the type require one).
*/
actual abstract fun encodedSize(value: E): Int
/**
* The size of `tag` and `value` in the wire format. This size includes the tag, type,
* length-delimited prefix (should the type require one), and value. Returns 0 if `value` is
* null.
*/
actual open fun encodedSizeWithTag(tag: Int, value: E?): Int {
return commonEncodedSizeWithTag(tag, value)
}
/** Write non-null `value` to `writer`. */
actual abstract fun encode(writer: ProtoWriter, value: E)
/** Write non-null `value` to `writer`. */
actual open fun encode(writer: ReverseProtoWriter, value: E) {
delegateEncode(writer, value)
}
/** Write `tag` and `value` to `writer`. If value is null this does nothing. */
actual open fun encodeWithTag(writer: ProtoWriter, tag: Int, value: E?) {
commonEncodeWithTag(writer, tag, value)
}
/** Write `tag` and `value` to `writer`. If value is null this does nothing. */
actual open fun encodeWithTag(writer: ReverseProtoWriter, tag: Int, value: E?) {
commonEncodeWithTag(writer, tag, value)
}
/** Encode `value` and write it to `stream`. */
actual fun encode(sink: BufferedSink, value: E) {
commonEncode(sink, value)
}
/** Encode `value` as a `byte[]`. */
actual fun encode(value: E): ByteArray {
return commonEncode(value)
}
/** Encode `value` as a [ByteString]. */
actual fun encodeByteString(value: E): ByteString {
return commonEncodeByteString(value)
}
/** Read a non-null value from `reader`. */
actual abstract fun decode(reader: ProtoReader): E
/** Read an encoded message from `bytes`. */
actual fun decode(bytes: ByteArray): E {
return commonDecode(bytes)
}
/** Read an encoded message from `bytes`. */
actual fun decode(bytes: ByteString): E {
return commonDecode(bytes)
}
/** Read an encoded message from `source`. */
actual fun decode(source: BufferedSource): E {
return commonDecode(source)
}
/** Returns a human-readable version of the given `value`. */
actual open fun toString(value: E): String {
return commonToString(value)
}
internal actual fun withLabel(label: WireField.Label): ProtoAdapter<*> {
return commonWithLabel(label)
}
/** Returns an adapter for `E` but as a packed, repeated value. */
actual fun asPacked(): ProtoAdapter<List<E>> {
require(fieldEncoding != FieldEncoding.LENGTH_DELIMITED) {
"Unable to pack a length-delimited type."
}
return packedAdapter ?: throw UnsupportedOperationException(
"Can't create a packed adapter from a packed or repeated adapter."
)
}
/**
* Returns an adapter for `E` but as a repeated value.
*
* Note: Repeated items are not required to be encoded sequentially. Thus, when decoding using
* the returned adapter, only single-element lists will be returned and it is the caller's
* responsibility to merge them into the final list.
*/
actual fun asRepeated(): ProtoAdapter<List<E>> {
return repeatedAdapter ?: throw UnsupportedOperationException(
"Can't create a repeated adapter from a repeated or packed adapter."
)
}
actual class EnumConstantNotFoundException actual constructor(
actual val value: Int,
type: KClass<*>?
) : IllegalArgumentException("Unknown enum tag $value for ${type?.simpleName}")
actual companion object {
/**
* Creates a new proto adapter for a map using `keyAdapter` and `valueAdapter`.
*
* Note: Map entries are not required to be encoded sequentially. Thus, when decoding using
* the returned adapter, only single-element maps will be returned and it is the caller's
* responsibility to merge them into the final map.
*/
actual fun <K, V> newMapAdapter(
keyAdapter: ProtoAdapter<K>,
valueAdapter: ProtoAdapter<V>
): ProtoAdapter<Map<K, V>> {
return commonNewMapAdapter(keyAdapter, valueAdapter)
}
actual val BOOL: ProtoAdapter<Boolean> = commonBool()
actual val INT32: ProtoAdapter<Int> = commonInt32()
actual val UINT32: ProtoAdapter<Int> = commonUint32()
actual val SINT32: ProtoAdapter<Int> = commonSint32()
actual val FIXED32: ProtoAdapter<Int> = commonFixed32()
actual val SFIXED32: ProtoAdapter<Int> = commonSfixed32()
actual val INT64: ProtoAdapter<Long> = commonInt64()
/**
* Like INT64, but negative longs are interpreted as large positive values, and encoded that way
* in JSON.
*/
actual val UINT64: ProtoAdapter<Long> = commonUint64()
actual val SINT64: ProtoAdapter<Long> = commonSint64()
actual val FIXED64: ProtoAdapter<Long> = commonFixed64()
actual val SFIXED64: ProtoAdapter<Long> = commonSfixed64()
actual val FLOAT: ProtoAdapter<Float> = commonFloat()
actual val DOUBLE: ProtoAdapter<Double> = commonDouble()
actual val BYTES: ProtoAdapter<ByteString> = commonBytes()
actual val STRING: ProtoAdapter<String> = commonString()
actual val DURATION: ProtoAdapter<Duration> = commonDuration()
actual val INSTANT: ProtoAdapter<Instant> = commonInstant()
actual val EMPTY: ProtoAdapter<Unit> = commonEmpty()
actual val STRUCT_MAP: ProtoAdapter<Map<String, *>?> = commonStructMap()
actual val STRUCT_LIST: ProtoAdapter<List<*>?> = commonStructList()
actual val STRUCT_NULL: ProtoAdapter<Nothing?> = commonStructNull()
actual val STRUCT_VALUE: ProtoAdapter<Any?> = commonStructValue()
actual val DOUBLE_VALUE: ProtoAdapter<Double?> = commonWrapper(DOUBLE, "type.googleapis.com/google.protobuf.DoubleValue")
actual val FLOAT_VALUE: ProtoAdapter<Float?> = commonWrapper(FLOAT, "type.googleapis.com/google.protobuf.FloatValue")
actual val INT64_VALUE: ProtoAdapter<Long?> = commonWrapper(INT64, "type.googleapis.com/google.protobuf.Int64Value")
actual val UINT64_VALUE: ProtoAdapter<Long?> = commonWrapper(UINT64, "type.googleapis.com/google.protobuf.UInt64Value")
actual val INT32_VALUE: ProtoAdapter<Int?> = commonWrapper(INT32, "type.googleapis.com/google.protobuf.Int32Value")
actual val UINT32_VALUE: ProtoAdapter<Int?> = commonWrapper(UINT32, "type.googleapis.com/google.protobuf.UInt32Value")
actual val BOOL_VALUE: ProtoAdapter<Boolean?> = commonWrapper(BOOL, "type.googleapis.com/google.protobuf.BoolValue")
actual val STRING_VALUE: ProtoAdapter<String?> = commonWrapper(STRING, "type.googleapis.com/google.protobuf.StringValue")
actual val BYTES_VALUE: ProtoAdapter<ByteString?> = commonWrapper(BYTES, "type.googleapis.com/google.protobuf.BytesValue")
}
}
| apache-2.0 | d8768d7b4ad3bebd18c35108ec83faab | 40.333333 | 126 | 0.711999 | 4.186189 | false | false | false | false |
jainsahab/AndroidSnooper | TestApp/src/main/java/com/github/jainsahab/MainActivity.kt | 1 | 3817 | package com.github.jainsahab
import android.os.Bundle
import android.util.Log
import android.view.Menu
import android.view.MenuItem
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import com.prateekj.snooper.AndroidSnooper
import com.prateekj.snooper.okhttp.SnooperInterceptor
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.content_main.*
import okhttp3.Call
import okhttp3.Callback
import okhttp3.Interceptor
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody.Companion.toRequestBody
import okhttp3.Response
import okhttp3.ResponseBody.Companion.toResponseBody
import org.json.JSONObject
import java.io.IOException
import java.util.Date
class MainActivity : AppCompatActivity() {
private val requestBody: JSONObject
get() {
val postdata = JSONObject()
postdata.put("name", "test" + Date().time)
postdata.put("job", "Investment manager")
postdata.put("age", "23")
return postdata
}
private val okHttpClient: OkHttpClient
get() {
val builder = OkHttpClient.Builder()
builder.networkInterceptors().add(SnooperInterceptor())
builder.networkInterceptors().add(object : Interceptor {
@Throws(IOException::class)
override fun intercept(chain: Interceptor.Chain): Response {
val response = chain.proceed(chain.request())
return response.newBuilder()
.removeHeader("Content-type")
.addHeader("Content-type", "application/json; charset=utf-8")
.body(
response.body!!.string()
.toResponseBody(response.body!!.contentType())
)
.build()
}
})
return builder.build()
}
override fun onCreate(savedInstanceState: Bundle?) {
AndroidSnooper.init(application)
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
setSupportActionBar(toolbar)
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.menu_main, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
val id = item.itemId
return if (id == R.id.action_settings) {
true
} else super.onOptionsItemSelected(item)
}
fun fetchPosts(view: View) {
val request = Request.Builder()
.addHeader("Accept-Encoding", "identity")
.addHeader("Content-type", "application/json; charset=utf-8")
.url("https://reqres.in/api/users?page=1&per_page=12")
.build()
executeRequest(request)
}
fun fetchPostsFail(view: View) {
val request = Request.Builder()
.addHeader("Accept-Encoding", "identity")
.addHeader("Content-type", "application/json; charset=utf-8")
.url("https://reqres.in/apii/use?page=1&per_page=12")
.build()
executeRequest(request)
}
fun createPost(view: View) {
val request = Request.Builder()
.addHeader("Accept-Encoding", "identity")
.addHeader("Content-type", "application/json; charset=utf-8")
.url("https://reqres.in/api/users")
.post(requestBody.toString().toRequestBody("application/json".toMediaTypeOrNull()))
.build()
executeRequest(request)
}
private fun executeRequest(request: Request) {
okHttpClient.newCall(request).enqueue(object : Callback {
override fun onFailure(call: Call, e: IOException) {
Log.e("MAIN", "failure $e", e)
}
@Throws(IOException::class)
override fun onResponse(call: Call, response: Response) {
if (response.isSuccessful) {
val text = response.body!!.string()
runOnUiThread {
result.text = text
}
}
}
})
}
}
| apache-2.0 | f1679055f46332fcc600895566e0825a | 29.536 | 89 | 0.676971 | 4.208379 | false | false | false | false |
JStege1206/AdventOfCode | aoc-2018/src/main/kotlin/nl/jstege/adventofcode/aoc2018/days/Day03.kt | 1 | 2685 | package nl.jstege.adventofcode.aoc2018.days
import nl.jstege.adventofcode.aoccommon.days.Day
import nl.jstege.adventofcode.aoccommon.utils.extensions.extractValues
import nl.jstege.adventofcode.aoccommon.utils.extensions.transformTo
class Day03 : Day(title = "No Matter How You Slice It") {
private companion object Configuration {
private const val GRID_WIDTH = 1000
private const val GRID_HEIGHT = 1000
private const val INPUT_PATTERN_STRING = """#(\d+)\s@\s(\d+),(\d+):\s(\d+)x(\d+)"""
private val INPUT_REGEX = INPUT_PATTERN_STRING.toRegex()
private const val ID_INDEX = 1
private const val X_INDEX = 2
private const val Y_INDEX = 3
private const val WIDTH_INDEX = 4
private const val HEIGHT_INDEX = 5
private val PARAM_INDICES = intArrayOf(
ID_INDEX,
X_INDEX,
Y_INDEX,
WIDTH_INDEX,
HEIGHT_INDEX
)
}
override fun first(input: Sequence<String>): Any =
input
.parse()
.transformTo(Grid(GRID_WIDTH, GRID_HEIGHT), Grid::set)
.count { it > 1 }
override fun second(input: Sequence<String>): Any =
Grid(GRID_WIDTH, GRID_HEIGHT).let { grid ->
input
.parse()
.onEach(grid::set)
.toList() //Make sure all claims have been processed.
.first { claim -> grid[claim].all { it == 1 } }
.id
}
private fun Sequence<String>.parse(): Sequence<Claim> = this
.map { it.extractValues(INPUT_REGEX, *PARAM_INDICES) }
.map { it.map(String::toInt) }
.map { (id, x, y, w, h) -> Claim(id, x, y, x + w, y + h) }
private data class Claim(
val id: Int,
val startX: Int,
val startY: Int,
val endX: Int,
val endY: Int
)
private class Grid(val width: Int = GRID_WIDTH, height: Int = GRID_HEIGHT) : Iterable<Int> {
private val grid = IntArray(width * height)
fun set(claim: Claim) =
claim.let { (_, startX, startY, endX, endY) ->
for (y in startY until endY) {
for (x in startX until endX) {
grid[y * width + x]++
}
}
}
operator fun get(claim: Claim): List<Int> =
claim.let { (_, startX, startY, endX, endY) ->
(startY until endY).flatMap { y ->
grid.copyOfRange(y * width + startX, y * width + endX).toList()
}
}
override fun iterator(): Iterator<Int> = grid.iterator()
}
}
| mit | 2954fceb60500ba7512a40d71f432f9f | 32.5625 | 96 | 0.533706 | 4.130769 | false | false | false | false |
JetBrains/ideavim | src/main/java/com/maddyhome/idea/vim/helper/DocumentManager.kt | 1 | 1343 | /*
* Copyright 2003-2022 The IdeaVim authors
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE.txt file or at
* https://opensource.org/licenses/MIT.
*/
package com.maddyhome.idea.vim.helper
import com.intellij.openapi.editor.Document
import com.intellij.openapi.editor.event.DocumentListener
import com.intellij.openapi.util.Key
import com.maddyhome.idea.vim.EventFacade
import com.maddyhome.idea.vim.group.MarkGroup
import com.maddyhome.idea.vim.group.SearchGroup
object DocumentManager {
private val docListeners = mutableSetOf<DocumentListener>()
private val LISTENER_MARKER = Key<String>("VimlistenerMarker")
init {
docListeners += MarkGroup.MarkUpdater.INSTANCE
docListeners += SearchGroup.DocumentSearchListener.INSTANCE
}
fun addListeners(doc: Document) {
val marker = doc.getUserData(LISTENER_MARKER)
if (marker != null) return
doc.putUserData(LISTENER_MARKER, "foo")
for (docListener in docListeners) {
EventFacade.getInstance().addDocumentListener(doc, docListener)
}
}
fun removeListeners(doc: Document) {
doc.getUserData(LISTENER_MARKER) ?: return
doc.putUserData(LISTENER_MARKER, null)
for (docListener in docListeners) {
EventFacade.getInstance().removeDocumentListener(doc, docListener)
}
}
}
| mit | 7c059aa5ce4072e6de1328210a0f2a49 | 28.844444 | 72 | 0.752048 | 4.094512 | false | false | false | false |
JetBrains/ideavim | src/main/java/com/maddyhome/idea/vim/group/IjVimStorageService.kt | 1 | 2349 | /*
* Copyright 2003-2022 The IdeaVim authors
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE.txt file or at
* https://opensource.org/licenses/MIT.
*/
package com.maddyhome.idea.vim.group
import com.intellij.openapi.util.Key
import com.maddyhome.idea.vim.api.VimEditor
import com.maddyhome.idea.vim.api.VimStorageServiceBase
import com.maddyhome.idea.vim.ex.ExException
import com.maddyhome.idea.vim.helper.EditorHelper
import com.maddyhome.idea.vim.newapi.ij
class IjVimStorageService : VimStorageServiceBase() {
val bufferToKey = mutableMapOf<String, MutableMap<String, Any?>>()
override fun <T> getDataFromEditor(editor: VimEditor, key: com.maddyhome.idea.vim.api.Key<T>): T? {
return editor.ij.getUserData(getOrCreateIjKey(key))
}
override fun <T> putDataToEditor(editor: VimEditor, key: com.maddyhome.idea.vim.api.Key<T>, data: T) {
editor.ij.putUserData(getOrCreateIjKey(key), data)
}
@Suppress("UNCHECKED_CAST")
override fun <T> getDataFromBuffer(editor: VimEditor, key: com.maddyhome.idea.vim.api.Key<T>): T? {
val buffer = EditorHelper.getVirtualFile(editor.ij)?.path ?: "empty path"
return bufferToKey[buffer]?.get(key.name) as T?
}
override fun <T> putDataToBuffer(editor: VimEditor, key: com.maddyhome.idea.vim.api.Key<T>, data: T) {
val buffer = EditorHelper.getVirtualFile(editor.ij)?.path ?: "empty path"
var bufferStorage = bufferToKey[buffer]
if (bufferStorage == null) {
bufferStorage = mutableMapOf()
bufferToKey[buffer] = bufferStorage
}
bufferStorage[key.name] = data
}
override fun <T> getDataFromTab(editor: VimEditor, key: com.maddyhome.idea.vim.api.Key<T>): T? {
throw ExException("Tab scope is not yet supported by IdeaVim :(")
}
override fun <T> putDataToTab(editor: VimEditor, key: com.maddyhome.idea.vim.api.Key<T>, data: T) {
throw ExException("Tab scope is not yet supported by IdeaVim :(")
}
private val ijKeys = mutableMapOf<String, Key<out Any?>>()
@Suppress("UNCHECKED_CAST")
private fun <T> getOrCreateIjKey(key: com.maddyhome.idea.vim.api.Key<T>): Key<T> {
val storedIjKey = ijKeys[key.name]
if (storedIjKey != null) {
return storedIjKey as Key<T>
}
val newKey = Key<T>(key.name)
ijKeys[key.name] = newKey
return newKey
}
}
| mit | e4d11fe8411c5d2488101a1dc9842566 | 35.703125 | 104 | 0.714347 | 3.527027 | false | false | false | false |
Andreyv1989/KotlinLessons | src/iv_properties/_32_Properties_.kt | 1 | 537 | package iv_properties
import util.TODO
import util.doc32
class PropertyExample() {
var counter = 0
var propertyWithCounter: Int? = null
set(v: Int?) {
field = v
counter++
}
}
fun todoTask32(): Nothing = TODO(
"""
Task 32.
Add a custom setter to PropertyExample.propertyWithCounter so that
the 'counter' property is incremented every time 'propertyWithCounter' is assigned to.
""",
documentation = doc32(),
references = { PropertyExample() }
)
| mit | 3e00989ef4812d64d30a83581767a631 | 19.653846 | 94 | 0.614525 | 4.365854 | false | false | false | false |
ingokegel/intellij-community | plugins/kotlin/idea/tests/testData/refactoring/move/kotlin/moveTopLevelDeclarations/misc/protectedMembersExternalRefs/before/foo/test.kt | 13 | 532 | package foo
open class <caret>Older {
protected object ProtectedObject { val inProtectedObject = 0 }
protected class ProtectedClass { val inProtectedClass = 0 }
protected fun protectedFun() = 0
protected var protectedVar = 0
}
class Younger : Older() {
protected val v1: ProtectedObject = ProtectedObject
val v2 = ProtectedObject.inProtectedObject
protected val v3: ProtectedClass = ProtectedClass()
val v4 = ProtectedClass().inProtectedClass
val v5 = protectedFun()
val v6 = protectedVar
} | apache-2.0 | 6d14a9bc22a837b77a5bad317bdfeaa0 | 30.352941 | 66 | 0.727444 | 4.360656 | false | false | false | false |
mdaniel/intellij-community | plugins/kotlin/base/facet/src/org/jetbrains/kotlin/idea/facet/KotlinVersionInfoProvider.kt | 1 | 3975 | // 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.facet
import com.intellij.openapi.extensions.ExtensionPointName
import com.intellij.openapi.module.Module
import com.intellij.openapi.roots.ModuleRootModel
import org.jetbrains.kotlin.config.KotlinFacetSettingsProvider
import org.jetbrains.kotlin.config.LanguageVersion
import org.jetbrains.kotlin.idea.compiler.configuration.IdeKotlinVersion
import org.jetbrains.kotlin.idea.compiler.configuration.KotlinPluginLayout
import org.jetbrains.kotlin.platform.IdePlatformKind
import org.jetbrains.kotlin.platform.idePlatformKind
import org.jetbrains.kotlin.platform.jvm.JvmPlatforms
interface KotlinVersionInfoProvider {
companion object {
val EP_NAME: ExtensionPointName<KotlinVersionInfoProvider> = ExtensionPointName("org.jetbrains.kotlin.versionInfoProvider")
}
fun getCompilerVersion(module: Module): IdeKotlinVersion?
fun getLibraryVersions(
module: Module,
platformKind: IdePlatformKind,
rootModel: ModuleRootModel?
): Collection<IdeKotlinVersion>
}
fun getRuntimeLibraryVersions(
module: Module,
rootModel: ModuleRootModel?,
platformKind: IdePlatformKind
): Collection<IdeKotlinVersion> {
return KotlinVersionInfoProvider.EP_NAME.extensionList.asSequence()
.map { it.getLibraryVersions(module, platformKind, rootModel) }
.firstOrNull { it.isNotEmpty() } ?: emptyList()
}
fun getLibraryLanguageLevel(
module: Module,
rootModel: ModuleRootModel?,
platformKind: IdePlatformKind?,
coerceRuntimeLibraryVersionToReleased: Boolean = true
): LanguageVersion = getLibraryVersion(module, rootModel, platformKind, coerceRuntimeLibraryVersionToReleased).languageVersion
fun getLibraryVersion(
module: Module,
rootModel: ModuleRootModel?,
platformKind: IdePlatformKind?,
coerceRuntimeLibraryVersionToReleased: Boolean = true
): IdeKotlinVersion {
val minVersion = getRuntimeLibraryVersions(module, rootModel, platformKind ?: JvmPlatforms.defaultJvmPlatform.idePlatformKind)
.addReleaseVersionIfNecessary(coerceRuntimeLibraryVersionToReleased)
.minOrNull()
return getDefaultVersion(module, minVersion, coerceRuntimeLibraryVersionToReleased)
}
fun getDefaultVersion(
module: Module,
explicitVersion: IdeKotlinVersion? = null,
coerceRuntimeLibraryVersionToReleased: Boolean = true
): IdeKotlinVersion {
if (explicitVersion != null) {
return explicitVersion
}
val libVersion = KotlinVersionInfoProvider.EP_NAME.extensions
.mapNotNull { it.getCompilerVersion(module) }
.addReleaseVersionIfNecessary(coerceRuntimeLibraryVersionToReleased)
.minOrNull()
return libVersion ?: KotlinPluginLayout.standaloneCompilerVersion
}
fun getDefaultLanguageLevel(
module: Module,
explicitVersion: IdeKotlinVersion? = null,
coerceRuntimeLibraryVersionToReleased: Boolean = true
): LanguageVersion = getDefaultVersion(module, explicitVersion, coerceRuntimeLibraryVersionToReleased).languageVersion
private fun Iterable<IdeKotlinVersion>.addReleaseVersionIfNecessary(shouldAdd: Boolean): Iterable<IdeKotlinVersion> =
if (shouldAdd) this + KotlinPluginLayout.standaloneCompilerVersion else this
fun getRuntimeLibraryVersion(module: Module): IdeKotlinVersion? {
val settingsProvider = KotlinFacetSettingsProvider.getInstance(module.project) ?: return null
val targetPlatform = settingsProvider.getInitializedSettings(module).targetPlatform
val versions = getRuntimeLibraryVersions(module, null, (targetPlatform ?: JvmPlatforms.defaultJvmPlatform).idePlatformKind)
return versions.toSet().singleOrNull()
}
fun getRuntimeLibraryVersionOrDefault(module: Module): IdeKotlinVersion {
return getRuntimeLibraryVersion(module) ?: KotlinPluginLayout.standaloneCompilerVersion
} | apache-2.0 | f09d99eb4ead3cbd7f1417fac2e60c54 | 41.752688 | 158 | 0.797987 | 5.430328 | false | false | false | false |
cqjjjzr/BiliLiveLib | BiliLiveOnlineKeeper/src/main/kotlin/charlie/bilionlinekeeper/OnlineExp.kt | 1 | 1662 | package charlie.bilionlinekeeper
import charlie.bililivelib.exceptions.BiliLiveException
import charlie.bililivelib.user.HeartbeatProtocol
import charlie.bililivelib.user.Session
import charlie.bilionlinekeeper.util.I18n
import charlie.bilionlinekeeper.util.LogUtil
import org.apache.logging.log4j.Level
import org.apache.logging.log4j.LogManager
import java.util.*
class OnlineExp(session: Session) {
private fun logSingleException(ex: BiliLiveException) {
LogUtil.logException(
logger,
Level.WARN,
I18n.getString("onlineExp.exception")!!,
ex)
}
private val PERIOD_MILLIS = (5 * 1000L)
private val protocol = HeartbeatProtocol(session)
private val timer = Timer("OnlineExp", false)
private val logger = LogManager.getLogger("onlineExp")
private var task: TimerTask? = null
private var started: Boolean = false
fun start() {
started = true
task = OnlineExpTask().apply {
timer.schedule(this, 0L, PERIOD_MILLIS)
}
logStart()
}
private fun logStart() {
logger.info(I18n.getString("onlineExp.start"))
}
fun stop() {
(task ?: return).cancel()
started = false
logStop()
}
private fun logStop() {
logger.info(I18n.getString("onlineExp.stop"))
}
fun isStarted(): Boolean = started
private inner class OnlineExpTask : TimerTask() {
override fun run() {
try {
protocol.heartbeat()
} catch (ex: BiliLiveException) {
logSingleException(ex)
}
}
}
} | apache-2.0 | 25621f694c3b71e34de969956ed47f9a | 25.822581 | 59 | 0.625752 | 4.093596 | false | false | false | false |
hsson/card-balance-app | app/src/main/java/se/creotec/chscardbalance2/controller/SplashActivity.kt | 1 | 4725 | // Copyright (c) 2017 Alexander Håkansson
//
// This software is released under the MIT License.
// https://opensource.org/licenses/MIT
package se.creotec.chscardbalance2.controller
import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import se.creotec.chscardbalance2.BuildConfig
import se.creotec.chscardbalance2.Constants
import se.creotec.chscardbalance2.GlobalState
import se.creotec.chscardbalance2.model.CardData
import se.creotec.chscardbalance2.service.BalanceService
class SplashActivity : AppCompatActivity() {
private enum class RunState {
NORMAL,
FIRST,
UPGRADED
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
when (runState) {
SplashActivity.RunState.NORMAL -> {
// Do nothing special
completeUpgrade()
startMain()
}
SplashActivity.RunState.FIRST -> {
// Check for any legacy data from version 2.x.x
val legacyNumber = getLegacyNumber()
if (legacyNumber != null && legacyNumber != "") {
convertLegacyNumber(legacyNumber)
// Introduce old user to new interface
val intent = Intent(this, AppUpgradedFromLegacyActivity::class.java)
startActivity(intent)
finish()
} else {
val firstRunIntent = Intent(this, AppFirstRunActivity::class.java)
startActivity(firstRunIntent)
finish()
}
}
SplashActivity.RunState.UPGRADED -> {
val savedVersionCode = getSavedVersionCode()
if (savedVersionCode <= 44) {
// Upgraded to using the userInfo cookie in balance
Intent(this, AppUserInfoUpgrade::class.java).also {
startActivity(it)
finish()
}
} else {
completeUpgrade()
startMain()
}
}
}
}
private fun startMain() {
val intent = Intent(this, MainActivity::class.java)
startActivity(intent)
finish()
}
// Get eventual legacy number from saved preferences
private fun getLegacyNumber(): String? {
val preferences = getSharedPreferences(Constants.PREFS_FILE_NAME_LEGACY, Context.MODE_PRIVATE)
return preferences.getString(Constants.PREFS_CARD_NUMBER_LEGACY_KEY, null)
}
// Convert an old legacy number to new model
private fun convertLegacyNumber(number: String) {
val global = application as GlobalState
val cardData = CardData()
cardData.cardNumber = number
global.model.cardData = cardData
global.saveCardData()
// Delete legacy number
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
this.deleteSharedPreferences(Constants.PREFS_FILE_NAME_LEGACY)
} else {
val editor = getSharedPreferences(Constants.PREFS_FILE_NAME_LEGACY, Context.MODE_PRIVATE).edit()
editor.putString(Constants.PREFS_CARD_NUMBER_LEGACY_KEY, null)
editor.apply()
}
// Attempt to update card info from backend
val updateBalanceIntent = Intent(this, BalanceService::class.java)
updateBalanceIntent.action = Constants.ACTION_UPDATE_CARD
this.startService(updateBalanceIntent)
}
private fun getSavedVersionCode(): Int {
val preferences = getSharedPreferences(Constants.PREFS_FILE_NAME, Context.MODE_PRIVATE)
return preferences.getInt(Constants.PREFS_VERSION_CODE_KEY, Constants.PREFS_VERSION_CODE_NONEXISTING)
}
// Determines if the application was started normally, was just upgraded, or if it's the
// first time the app is ran.
private val runState: RunState
get() {
val currentVersionCode = BuildConfig.VERSION_CODE
val savedVersionCode = getSavedVersionCode()
return when {
savedVersionCode == Constants.PREFS_VERSION_CODE_NONEXISTING -> RunState.FIRST
currentVersionCode > savedVersionCode -> RunState.UPGRADED
else -> RunState.NORMAL
}
}
private fun completeUpgrade() {
val preferences = getSharedPreferences(Constants.PREFS_FILE_NAME, Context.MODE_PRIVATE)
preferences.edit().putInt(Constants.PREFS_VERSION_CODE_KEY, BuildConfig.VERSION_CODE).apply()
}
}
| mit | 2505e1d82335d0c9bd05b1c3899bc3fc | 36.792 | 109 | 0.622354 | 5.06867 | false | false | false | false |
WhisperSystems/Signal-Android | app/src/main/java/org/thoughtcrime/securesms/keyboard/emoji/search/EmojiSearchRepository.kt | 1 | 2010 | package org.thoughtcrime.securesms.keyboard.emoji.search
import android.content.Context
import android.net.Uri
import org.signal.core.util.concurrent.SignalExecutors
import org.thoughtcrime.securesms.components.emoji.Emoji
import org.thoughtcrime.securesms.components.emoji.EmojiPageModel
import org.thoughtcrime.securesms.components.emoji.RecentEmojiPageModel
import org.thoughtcrime.securesms.database.DatabaseFactory
import org.thoughtcrime.securesms.database.EmojiSearchDatabase
import org.thoughtcrime.securesms.emoji.EmojiSource
import org.thoughtcrime.securesms.util.TextSecurePreferences
import java.util.function.Consumer
private const val MINIMUM_QUERY_THRESHOLD = 1
private const val EMOJI_SEARCH_LIMIT = 20
class EmojiSearchRepository(private val context: Context) {
private val emojiSearchDatabase: EmojiSearchDatabase = DatabaseFactory.getEmojiSearchDatabase(context)
fun submitQuery(query: String, includeRecents: Boolean, limit: Int = EMOJI_SEARCH_LIMIT, consumer: Consumer<EmojiPageModel>) {
if (query.length < MINIMUM_QUERY_THRESHOLD && includeRecents) {
consumer.accept(RecentEmojiPageModel(context, TextSecurePreferences.RECENT_STORAGE_KEY))
} else {
SignalExecutors.SERIAL.execute {
val emoji: List<String> = emojiSearchDatabase.query(query, limit)
val displayEmoji: List<Emoji> = emoji
.mapNotNull { canonical -> EmojiSource.latest.canonicalToVariations[canonical] }
.map { Emoji(it) }
consumer.accept(EmojiSearchResultsPageModel(emoji, displayEmoji))
}
}
}
private class EmojiSearchResultsPageModel(
private val emoji: List<String>,
private val displayEmoji: List<Emoji>
) : EmojiPageModel {
override fun getKey(): String = ""
override fun getIconAttr(): Int = -1
override fun getEmoji(): List<String> = emoji
override fun getDisplayEmoji(): List<Emoji> = displayEmoji
override fun getSpriteUri(): Uri? = null
override fun isDynamic(): Boolean = false
}
}
| gpl-3.0 | 1f1cfad65b2134f1d47250821396d1de | 36.222222 | 128 | 0.768657 | 4.506726 | false | false | false | false |
siarhei-luskanau/android-iot-doorbell | ui/ui_permissions/src/main/kotlin/siarhei/luskanau/iot/doorbell/ui/permissions/PermissionsFragment.kt | 1 | 2987 | package siarhei.luskanau.iot.doorbell.ui.permissions
import android.content.pm.PackageManager
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.annotation.VisibleForTesting
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.ComposeView
import androidx.compose.ui.tooling.preview.Preview
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import com.google.android.material.composethemeadapter.MdcTheme
import siarhei.luskanau.iot.doorbell.common.AppConstants.PERMISSIONS
class PermissionsFragment(
presenterProvider: (fragment: Fragment) -> PermissionsPresenter
) : Fragment() {
private val presenter: PermissionsPresenter by lazy { presenterProvider(this) }
private var activityResultLauncher: ActivityResultLauncher<Array<String>>? = null
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
) =
ComposeView(inflater.context).apply {
setContent {
MdcTheme {
PermissionsPreview()
}
}
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
activityResultLauncher = registerForActivityResult(
ActivityResultContracts.RequestMultiplePermissions()
) { result: Map<String, Boolean> ->
val allGranted = result.values.reduce { acc, b -> acc && b }
if (allGranted) {
presenter.onPermissionsGranted()
} else {
presenter.onPermissionsNotGranted()
}
}
if (hasPermissions().not()) {
activityResultLauncher?.launch(PERMISSIONS)
} else {
// If permissions have already been granted, proceed
presenter.onPermissionsGranted()
}
}
private fun hasPermissions(): Boolean {
for (permission in PERMISSIONS) {
if (ContextCompat.checkSelfPermission(
requireContext(),
permission
) != PackageManager.PERMISSION_GRANTED
) {
return false
}
}
return true
}
}
@Preview
@Composable
@Suppress("FunctionNaming")
@VisibleForTesting
fun PermissionsPreview() =
Text(
modifier = Modifier
.fillMaxWidth()
.fillMaxHeight(),
text = "permissions",
style = MaterialTheme.typography.h6
)
| mit | 9cb77b61c2566f80f479831850e4a6a5 | 31.467391 | 85 | 0.676264 | 5.45073 | false | false | false | false |
iPoli/iPoli-android | app/src/main/java/io/ipoli/android/player/profile/ProfilePostListViewController.kt | 1 | 8973 | package io.ipoli.android.player.profile
import android.animation.Animator
import android.animation.AnimatorInflater
import android.os.Bundle
import android.support.v7.widget.GridLayoutManager
import android.support.v7.widget.LinearLayoutManager
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.animation.OvershootInterpolator
import com.google.firebase.auth.FirebaseAuth
import io.ipoli.android.R
import io.ipoli.android.common.redux.android.BaseViewController
import io.ipoli.android.common.view.*
import io.ipoli.android.friends.feed.*
import io.ipoli.android.friends.feed.data.AndroidReactionType
import io.ipoli.android.friends.feed.data.Post
import io.ipoli.android.player.profile.ProfileViewState.StateType.*
import kotlinx.android.synthetic.main.controller_profile_post_list.view.*
import kotlinx.android.synthetic.main.item_popup_reaction.view.*
import kotlinx.android.synthetic.main.view_empty_list.view.*
import kotlinx.android.synthetic.main.view_loader.view.*
import kotlinx.android.synthetic.main.view_require_login.view.*
/**
* Created by Polina Zhelyazkova <[email protected]>
* on 7/23/18.
*/
class ProfilePostListViewController(args: Bundle? = null) :
BaseViewController<ProfileAction, ProfileViewState>(args), ReactionPopupHandler {
private var friendId: String? = null
override var stateKey = ""
constructor(reducerKey: String, friendId: String?) : this() {
this.stateKey = reducerKey
this.friendId = friendId
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup,
savedViewState: Bundle?
): View {
val view = inflater.inflate(R.layout.controller_profile_post_list, container, false)
if (friendId == null) {
view.shareItem.onDebounceClick {
navigateFromRoot().toPostItemPicker()
}
} else {
view.shareItem.gone()
}
view.reactionPopup.layoutManager = GridLayoutManager(view.context, 3)
view.reactionPopup.adapter = ReactionPopupAdapter(this)
(view.reactionPopup.adapter as ReactionPopupAdapter).updateAll(
AndroidReactionType.values().map { rt ->
val title = stringRes(rt.title)
ReactionPopupViewModel(
title,
rt.animation,
title,
Post.ReactionType.valueOf(rt.name)
) {
if (FirebaseAuth.getInstance().currentUser == null) {
showShortToast(R.string.error_need_registration)
} else {
dispatch(ProfileAction.ReactToPost(it, friendId))
}
}
}
)
view.feedList.setOnTouchListener { _, _ ->
if (isPopupShown()) {
hideReactionPopup()
true
} else {
false
}
}
view.feedList.layoutManager = LinearLayoutManager(view.context)
view.feedList.adapter = PostAdapter(this, activity!!)
view.emptyAnimation.setAnimation("empty_posts.json")
return view
}
override fun onCreateLoadAction() =
ProfileAction.LoadPosts(playerId = friendId)
override fun colorStatusBars() {
}
override fun onDetach(view: View) {
dispatch(ProfileAction.UnloadPosts)
super.onDetach(view)
}
override fun handleBack() =
if (view != null && view!!.reactionPopup.visible) {
hideReactionPopup()
true
} else false
override fun render(state: ProfileViewState, view: View) {
when (state.type) {
SHOW_REQUIRE_LOGIN -> {
view.loader.gone()
view.emptyContainer.gone()
view.feedList.gone()
view.reactionPopup.gone()
view.shareItem.gone()
view.loginMessageContainer.visible()
view.loginMessage.setText(R.string.posts_sign_in)
view.loginButton.onDebounceClick {
navigateFromRoot().toAuth(isSigningUp = true)
}
}
NO_INTERNET_CONNECTION -> {
view.loader.gone()
view.emptyContainer.visible()
view.emptyAnimation.pauseAnimation()
view.emptyAnimation.gone()
view.feedList.gone()
view.reactionPopup.gone()
view.shareItem.gone()
view.loginMessageContainer.gone()
view.emptyTitle.text = stringRes(R.string.error_no_internet_title)
view.emptyText.text = stringRes(R.string.posts_no_internet_text)
}
POSTS_CHANGED -> {
if (state.posts!!.isNotEmpty()) {
renderPosts(state, view)
} else {
renderEmptyPosts(view)
}
}
else -> {
}
}
}
private fun renderEmptyPosts(view: View) {
view.loader.gone()
view.emptyContainer.visible()
view.feedList.gone()
view.reactionPopup.gone()
showShareItemIfNotFriend(view)
view.emptyAnimation.playAnimation()
view.emptyAnimation.visible()
view.emptyTitle.text = stringRes(R.string.feed_empty_title)
view.emptyText.text = stringRes(R.string.feed_empty_text)
}
private fun renderPosts(
state: ProfileViewState,
view: View
) {
view.loader.gone()
view.emptyContainer.gone()
view.reactionPopup.gone()
view.loginMessageContainer.gone()
view.feedList.visible()
showShareItemIfNotFriend(view)
val postVMs = state.posts!!.map { p ->
toPostViewModel(context = activity!!, post = p,
reactListener = { postId, _ ->
dispatch(ProfileAction.ShowReactionPopupForPost(postId))
},
reactListListener = {
if (FirebaseAuth.getInstance().currentUser == null) {
showShortToast(R.string.error_need_registration)
} else {
navigate().toReactionHistory(it)
}
},
commentsListener = {
if (FirebaseAuth.getInstance().currentUser == null) {
showShortToast(R.string.error_need_registration)
} else {
navigateFromRoot().toPost(it)
}
},
shareListener = { m ->
navigate().toSharePost(m)
},
postClickListener = {
if (FirebaseAuth.getInstance().currentUser == null) {
showShortToast(R.string.error_need_registration)
} else {
navigateFromRoot().toPost(it)
}
}
)
}
(view.feedList.adapter as PostAdapter).updateAll(postVMs)
}
private fun showShareItemIfNotFriend(view: View) {
if (friendId == null) {
view.shareItem.visible()
}
}
override fun isPopupShown() = view?.let { it.reactionPopup.alpha > 0 } ?: false
override fun containerCoordinates() =
view?.let {
val parentLoc = IntArray(2)
view!!.container.getLocationInWindow(parentLoc)
parentLoc
} ?: intArrayOf(0, 0)
override fun hideReactionPopup() {
view?.reactionPopup?.children?.forEach {
it.reactionAnimation.cancelAnimation()
}
view?.let {
playAnimation(
createPopupAnimator(
it.reactionPopup, true
),
onEnd = { it.reactionPopup.gone() }
)
}
}
override fun showReactionPopup(x: Int, y: Float) {
view?.let {
val reactionPopup = it.reactionPopup
reactionPopup.x = x.toFloat()
reactionPopup.y = y
playAnimation(
createPopupAnimator(reactionPopup),
onStart = { reactionPopup.visible() },
onEnd = {
it.reactionPopup.children.forEach { v ->
v.reactionAnimation.playAnimation()
}
})
}
}
private fun createPopupAnimator(view: View, reverse: Boolean = false): Animator {
val anim = if (reverse) R.animator.popout else R.animator.popup
val animator = AnimatorInflater.loadAnimator(view.context, anim)
animator.setTarget(view)
animator.interpolator = OvershootInterpolator()
animator.duration = shortAnimTime
return animator
}
} | gpl-3.0 | 30baf15f86190c5dafb1b996fcfc5f66 | 32.237037 | 92 | 0.566923 | 4.86078 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/uast/uast-kotlin-base/src/org/jetbrains/uast/kotlin/expressions/KotlinLocalFunctionULambdaExpression.kt | 3 | 1482 | // 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.uast.kotlin
import com.intellij.psi.PsiType
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.kotlin.psi.KtFunction
import org.jetbrains.uast.*
import org.jetbrains.uast.kotlin.psi.UastKotlinPsiParameter
@ApiStatus.Internal
class KotlinLocalFunctionULambdaExpression(
override val sourcePsi: KtFunction,
givenParent: UElement?
) : KotlinAbstractUExpression(givenParent), ULambdaExpression {
override val functionalInterfaceType: PsiType? = null
override val body by lz {
sourcePsi.bodyExpression?.let { wrapExpressionBody(this, it) } ?: UastEmptyExpression(this)
}
override val valueParameters by lz {
sourcePsi.valueParameters.mapIndexed { i, p ->
KotlinUParameter(UastKotlinPsiParameter.create(p, sourcePsi, this, i), p, this)
}
}
override fun asRenderString(): String {
val renderedValueParameters = valueParameters.joinToString(
prefix = "(",
postfix = ")",
transform = KotlinUParameter::asRenderString
)
val expressions = (body as? UBlockExpression)?.expressions?.joinToString("\n") {
it.asRenderString().withMargin
} ?: body.asRenderString()
return "fun $renderedValueParameters {\n${expressions.withMargin}\n}"
}
}
| apache-2.0 | d3630f73a61d1861201d1f89fd0d698e | 38 | 158 | 0.709177 | 5.006757 | false | false | false | false |
codebutler/farebot | farebot-app/src/main/java/com/codebutler/farebot/app/feature/keys/KeysScreen.kt | 1 | 4284 | /*
* KeysScreen.kt
*
* This file is part of FareBot.
* Learn more at: https://codebutler.github.io/farebot/
*
* Copyright (C) 2017 Eric Butler <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.codebutler.farebot.app.feature.keys
import android.content.Context
import android.view.Menu
import com.codebutler.farebot.R
import com.codebutler.farebot.app.core.activity.ActivityOperations
import com.codebutler.farebot.app.core.inject.ScreenScope
import com.codebutler.farebot.app.core.ui.ActionBarOptions
import com.codebutler.farebot.app.core.ui.FareBotScreen
import com.codebutler.farebot.app.core.util.ErrorUtils
import com.codebutler.farebot.app.feature.keys.add.AddKeyScreen
import com.codebutler.farebot.app.feature.main.MainActivity
import com.codebutler.farebot.persist.CardKeysPersister
import com.codebutler.farebot.persist.db.model.SavedKey
import com.uber.autodispose.kotlin.autoDisposable
import dagger.Component
import io.reactivex.Single
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import javax.inject.Inject
class KeysScreen : FareBotScreen<KeysScreen.KeysComponent, KeysScreenView>(), KeysScreenView.Listener {
@Inject lateinit var activityOperations: ActivityOperations
@Inject lateinit var keysPersister: CardKeysPersister
override fun getTitle(context: Context): String = context.getString(R.string.keys)
override fun getActionBarOptions(): ActionBarOptions = ActionBarOptions(
backgroundColorRes = R.color.accent,
textColorRes = R.color.white
)
override fun onCreateView(context: Context): KeysScreenView = KeysScreenView(context, activityOperations, this)
override fun onShow(context: Context) {
super.onShow(context)
activityOperations.menuItemClick
.autoDisposable(this)
.subscribe({ menuItem ->
when (menuItem.itemId) {
R.id.add -> navigator.goTo(AddKeyScreen())
}
})
loadKeys()
}
override fun onUpdateMenu(menu: Menu?) {
activity.menuInflater.inflate(R.menu.screen_keys, menu)
}
override fun onDeleteSelectedItems(items: List<KeyViewModel>) {
for ((savedKey) in items) {
keysPersister.delete(savedKey)
}
loadKeys()
}
override fun createComponent(parentComponent: MainActivity.MainActivityComponent): KeysScreen.KeysComponent =
DaggerKeysScreen_KeysComponent.builder()
.mainActivityComponent(parentComponent)
.build()
override fun inject(component: KeysScreen.KeysComponent) {
component.inject(this)
}
private fun loadKeys() {
observeKeys()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.autoDisposable(this)
.subscribe(
{ keys -> view.setViewModels(keys) },
{ e -> ErrorUtils.showErrorToast(activity, e) }
)
}
private fun observeKeys(): Single<List<KeyViewModel>> {
return Single.create<List<SavedKey>> { e ->
try {
e.onSuccess(keysPersister.savedKeys)
} catch (error: Throwable) {
e.onError(error)
}
}.map { savedKeys ->
savedKeys.map { savedKey -> KeyViewModel(savedKey) }
}
}
@ScreenScope
@Component(dependencies = arrayOf(MainActivity.MainActivityComponent::class))
interface KeysComponent {
fun inject(screen: KeysScreen)
}
}
| gpl-3.0 | 35e20fe5232d313c4ad65dd57db503fb | 34.404959 | 115 | 0.683473 | 4.509474 | false | false | false | false |
roylanceMichael/yaclib | core/src/main/java/org/roylance/yaclib/core/enums/CommonStringsHelper.kt | 1 | 1267 | package org.roylance.yaclib.core.enums
object CommonStringsHelper {
const val DebianBuild = "build/debian/"
const val DebianBuildBuild = "build/debian/build/"
const val BuildInstallPath = "build/install/"
const val SBinPath = "${DebianBuildBuild}usr/sbin/"
const val DebianEtcPath = "${DebianBuildBuild}etc/init.d"
const val CustomScript = "custom.sh"
const val CreateAndInstallPackageName = "create_install_package.sh"
private const val RunName = "run"
private const val StopName = "stop"
fun buildDebianEtcPath(projectName: String): String {
return "$DebianEtcPath/$projectName"
}
fun buildProjectRunScriptLocation(projectName: String): String {
return buildInstallPath(projectName, "${projectName}_$RunName.sh")
}
fun buildSystemRunScriptLocation(projectName: String): String {
return "$SBinPath${projectName}_$RunName"
}
fun buildProjectStopScriptLocation(projectName: String): String {
return buildInstallPath(projectName, "${projectName}_$StopName.sh")
}
fun buildSystemStopScriptLocation(projectName: String): String {
return "$SBinPath${projectName}_$StopName"
}
fun buildInstallPath(projectName: String, fileName: String): String {
return "$BuildInstallPath$projectName/$fileName"
}
} | mit | e5e852d24808db6d6ee4af27689a6af5 | 32.368421 | 71 | 0.748224 | 4.047923 | false | false | false | false |
airbnb/lottie-android | lottie-compose/src/main/java/com/airbnb/lottie/compose/LottieAnimation.kt | 1 | 10681 | package com.airbnb.lottie.compose
import android.graphics.Matrix
import android.graphics.Typeface
import androidx.annotation.FloatRange
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.size
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.drawscope.drawIntoCanvas
import androidx.compose.ui.graphics.nativeCanvas
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.layout.ScaleFactor
import androidx.compose.ui.unit.IntSize
import androidx.compose.ui.unit.dp
import com.airbnb.lottie.FontAssetDelegate
import com.airbnb.lottie.LottieComposition
import com.airbnb.lottie.LottieDrawable
import com.airbnb.lottie.RenderMode
import com.airbnb.lottie.utils.Utils
import kotlin.math.roundToInt
/**
* This is the base LottieAnimation composable. It takes a composition and renders it at a specific progress.
*
* The overloaded version of [LottieAnimation] that handles playback and is sufficient for most use cases.
*
* @param composition The composition that will be rendered. To generate a [LottieComposition], you can use
* [rememberLottieComposition].
* @param progress A provider for the progress (between 0 and 1) that should be rendered. If you want to render a
* specific frame, you can use [LottieComposition.getFrameForProgress]. In most cases, you will want
* to use one of the overloaded LottieAnimation composables that drives the animation for you.
* The overloads that have isPlaying as a parameter instead of progress will drive the
* animation automatically. You may want to use this version if you want to drive the animation
* from your own Animatable or via events such as download progress or a gesture.
* @param outlineMasksAndMattes Enable this to debug slow animations by outlining masks and mattes.
* The performance overhead of the masks and mattes will be proportional to the
* surface area of all of the masks/mattes combined.
* DO NOT leave this enabled in production.
* @param applyOpacityToLayers Sets whether to apply opacity to the each layer instead of shape.
* Opacity is normally applied directly to a shape. In cases where translucent
* shapes overlap, applying opacity to a layer will be more accurate at the
* expense of performance.
* Note: This process is very expensive. The performance impact will be reduced
* when hardware acceleration is enabled.
* @param enableMergePaths Enables experimental merge paths support. Most animations with merge paths will
* want this on but merge path support is more limited than some other rendering
* features so it defaults to off. The only way to know if your animation will work
* well with merge paths or not is to try it. If your animation has merge paths and
* doesn't render correctly, please file an issue.
* @param renderMode Allows you to specify whether you want Lottie to use hardware or software rendering.
* Defaults to AUTOMATIC. Refer to [LottieAnimationView.setRenderMode] for more info.
* @param maintainOriginalImageBounds When true, dynamically set bitmaps will be drawn with the exact bounds of the original animation,
* regardless of the bitmap size.
* When false, dynamically set bitmaps will be drawn at the top left of the original image but with its own bounds.
* Defaults to false.
* @param dynamicProperties Allows you to change the properties of an animation dynamically. To use them, use
* [rememberLottieDynamicProperties]. Refer to its docs for more info.
* @param alignment Define where the animation should be placed within this composable if it has a different
* size than this composable.
* @param contentScale Define how the animation should be scaled if it has a different size than this Composable.
* @param clipToCompositionBounds Determines whether or not Lottie will clip the animation to the original animation composition bounds.
* @param fontMap A map of keys to Typefaces. The key can be: "fName", "fFamily", or "fFamily-fStyle" as specified in your Lottie file.
*/
@Composable
fun LottieAnimation(
composition: LottieComposition?,
progress: () -> Float,
modifier: Modifier = Modifier,
outlineMasksAndMattes: Boolean = false,
applyOpacityToLayers: Boolean = false,
enableMergePaths: Boolean = false,
renderMode: RenderMode = RenderMode.AUTOMATIC,
maintainOriginalImageBounds: Boolean = false,
dynamicProperties: LottieDynamicProperties? = null,
alignment: Alignment = Alignment.Center,
contentScale: ContentScale = ContentScale.Fit,
clipToCompositionBounds: Boolean = true,
fontMap: Map<String, Typeface>? = null,
) {
val drawable = remember { LottieDrawable() }
val matrix = remember { Matrix() }
var setDynamicProperties: LottieDynamicProperties? by remember { mutableStateOf(null) }
if (composition == null || composition.duration == 0f) return Box(modifier)
val dpScale = Utils.dpScale()
Canvas(
modifier = modifier
.size((composition.bounds.width() / dpScale).dp, (composition.bounds.height() / dpScale).dp)
) {
drawIntoCanvas { canvas ->
val compositionSize = Size(composition.bounds.width().toFloat(), composition.bounds.height().toFloat())
val intSize = IntSize(size.width.roundToInt(), size.height.roundToInt())
val scale = contentScale.computeScaleFactor(compositionSize, size)
val translation = alignment.align(compositionSize * scale, intSize, layoutDirection)
matrix.reset()
matrix.preTranslate(translation.x.toFloat(), translation.y.toFloat())
matrix.preScale(scale.scaleX, scale.scaleY)
drawable.enableMergePathsForKitKatAndAbove(enableMergePaths)
drawable.renderMode = renderMode
drawable.composition = composition
drawable.setFontMap(fontMap)
if (dynamicProperties !== setDynamicProperties) {
setDynamicProperties?.removeFrom(drawable)
dynamicProperties?.addTo(drawable)
setDynamicProperties = dynamicProperties
}
drawable.setOutlineMasksAndMattes(outlineMasksAndMattes)
drawable.isApplyingOpacityToLayersEnabled = applyOpacityToLayers
drawable.maintainOriginalImageBounds = maintainOriginalImageBounds
drawable.clipToCompositionBounds = clipToCompositionBounds
drawable.progress = progress()
drawable.setBounds(0, 0, composition.bounds.width(), composition.bounds.height())
drawable.draw(canvas.nativeCanvas, matrix)
}
}
}
/**
* This is like [LottieAnimation] except that it takes a raw progress parameter instead of taking a progress provider.
*
* @see LottieAnimation
*/
@Composable
@Deprecated("Pass progress as a lambda instead of a float. This overload will be removed in the next release.")
fun LottieAnimation(
composition: LottieComposition?,
@FloatRange(from = 0.0, to = 1.0) progress: Float,
modifier: Modifier = Modifier,
outlineMasksAndMattes: Boolean = false,
applyOpacityToLayers: Boolean = false,
enableMergePaths: Boolean = false,
renderMode: RenderMode = RenderMode.AUTOMATIC,
maintainOriginalImageBounds: Boolean = false,
dynamicProperties: LottieDynamicProperties? = null,
alignment: Alignment = Alignment.Center,
contentScale: ContentScale = ContentScale.Fit,
clipToCompositionBounds: Boolean = true,
) {
LottieAnimation(
composition,
{ progress },
modifier,
outlineMasksAndMattes,
applyOpacityToLayers,
enableMergePaths,
renderMode,
maintainOriginalImageBounds,
dynamicProperties,
alignment,
contentScale,
clipToCompositionBounds,
)
}
/**
* This is like [LottieAnimation] except that it handles driving the animation via [animateLottieCompositionAsState]
* instead of taking a progress provider.
*
* @see LottieAnimation
* @see animateLottieCompositionAsState
*/
@Composable
fun LottieAnimation(
composition: LottieComposition?,
modifier: Modifier = Modifier,
isPlaying: Boolean = true,
restartOnPlay: Boolean = true,
clipSpec: LottieClipSpec? = null,
speed: Float = 1f,
iterations: Int = 1,
outlineMasksAndMattes: Boolean = false,
applyOpacityToLayers: Boolean = false,
enableMergePaths: Boolean = false,
renderMode: RenderMode = RenderMode.AUTOMATIC,
reverseOnRepeat: Boolean = false,
maintainOriginalImageBounds: Boolean = false,
dynamicProperties: LottieDynamicProperties? = null,
alignment: Alignment = Alignment.Center,
contentScale: ContentScale = ContentScale.Fit,
clipToCompositionBounds: Boolean = true,
fontMap: Map<String, Typeface>? = null,
) {
val progress by animateLottieCompositionAsState(
composition,
isPlaying,
restartOnPlay,
reverseOnRepeat,
clipSpec,
speed,
iterations,
)
LottieAnimation(
composition = composition,
progress = { progress },
modifier = modifier,
outlineMasksAndMattes = outlineMasksAndMattes,
applyOpacityToLayers = applyOpacityToLayers,
enableMergePaths = enableMergePaths,
renderMode = renderMode,
maintainOriginalImageBounds = maintainOriginalImageBounds,
dynamicProperties = dynamicProperties,
alignment = alignment,
contentScale = contentScale,
clipToCompositionBounds = clipToCompositionBounds,
fontMap = fontMap,
)
}
private operator fun Size.times(scale: ScaleFactor): IntSize {
return IntSize((width * scale.scaleX).toInt(), (height * scale.scaleY).toInt())
}
| apache-2.0 | 931725da50568993405a2fcbbb2590f3 | 47.112613 | 150 | 0.697219 | 5.042965 | false | false | false | false |
denofevil/import-cost | src/main/kotlin/com/github/denofevil/importCost/ImportCostCodeVisionProvider.kt | 1 | 4539 | package com.github.denofevil.importCost
import com.intellij.codeInsight.codeVision.CodeVisionEntry
import com.intellij.codeInsight.codeVision.CodeVisionRelativeOrdering
import com.intellij.codeInsight.codeVision.ui.model.ClickableRichTextCodeVisionEntry
import com.intellij.codeInsight.codeVision.ui.model.ClickableTextCodeVisionEntry
import com.intellij.codeInsight.codeVision.ui.model.richText.RichText
import com.intellij.codeInsight.hints.codeVision.CodeVisionProviderBase
import com.intellij.lang.ecmascript6.psi.ES6ImportCall
import com.intellij.lang.ecmascript6.psi.ES6ImportDeclaration
import com.intellij.lang.html.HtmlCompatibleFile
import com.intellij.lang.javascript.psi.JSCallExpression
import com.intellij.lang.javascript.psi.JSFile
import com.intellij.lang.javascript.psi.JSVarStatement
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.options.ShowSettingsUtil
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiDocumentManager
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.ui.SimpleTextAttributes
import java.awt.event.MouseEvent
class ImportCostCodeVisionProvider : CodeVisionProviderBase() {
override val id: String get() = "Import Cost"
override val name: String get() = "Import Cost"
override val groupId: String get() = "Import Cost"
override val relativeOrderings: List<CodeVisionRelativeOrdering> get() = emptyList()
override fun acceptsElement(element: PsiElement): Boolean {
return element is ES6ImportDeclaration ||
isRequireCall(element) ||
isRequireVarStatement(element) ||
element is ES6ImportCall
}
private fun isRequireCall(element: PsiElement?) = element is JSCallExpression && element.isRequireCall
private fun isRequireVarStatement(element: PsiElement): Boolean {
return element is JSVarStatement &&
element.variables.size == 1 && isRequireCall(element.variables[0].initializer)
}
override fun acceptsFile(file: PsiFile): Boolean {
val project = file.project
val settings = project.getService(ImportCostSettings::class.java)
if (!settings.isCodeVision()) return false
@Suppress("UnstableApiUsage") //we update plugins for every version, so it isn't big deal
return file is JSFile || file is HtmlCompatibleFile
}
override fun getHint(element: PsiElement, file: PsiFile): String? {
val project = element.project
val vFile = file.virtualFile ?: return null
val service = project.getService(ImportCostLanguageService::class.java)
val document = PsiDocumentManager.getInstance(project).getDocument(file) ?: return null
val lineNumber = document.getLineNumber(element.textRange.endOffset)
val importSize = service.getImportSize(vFile, lineNumber)
if (importSize.size <= 0) return null
val info = calculateSizeInfo(project, importSize.size)
return info.name + "#" + convertToText(project, importSize)
}
override fun computeForEditor(editor: Editor, file: PsiFile): List<Pair<TextRange, CodeVisionEntry>> {
val fromParent = super.computeForEditor(editor, file)
if (fromParent.isEmpty()) return fromParent
return fromParent.map {
val range = it.first
val entry = it.second
if (entry is ClickableTextCodeVisionEntry) {
val text = entry.text
val parts = text.split("#")
if (parts.size != 2) return@map it
val realText = parts[1]
val info = ImportCostSizeKind.valueOf(parts[0])
val richText = RichText()
val textAttributes = getHandlerAttributes(info, false)
richText.append(realText, SimpleTextAttributes.fromTextAttributes(textAttributes))
val newEntry = ClickableRichTextCodeVisionEntry(
entry.providerId,
richText,
entry.onClick,
entry.icon,
entry.longPresentation,
entry.tooltip,
entry.extraActions
)
return@map range to newEntry
}
return@map it
}
}
override fun handleClick(editor: Editor, element: PsiElement, event: MouseEvent?) {
ShowSettingsUtil.getInstance().showSettingsDialog(element.project, ImportCostConfigurable::class.java)
}
} | apache-2.0 | 0e0baa704cb30af65c697f1dd3141ddc | 43.07767 | 110 | 0.695748 | 4.833866 | false | false | false | false |
code-disaster/lwjgl3 | modules/lwjgl/openvr/src/templates/kotlin/openvr/templates/VRScreenshots.kt | 4 | 5332 | /*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
*/
package openvr.templates
import org.lwjgl.generator.*
import openvr.*
val VRScreenshots = "VRScreenshots".nativeClass(
Module.OPENVR,
prefixMethod = "VRScreenshots_",
binding = OPENVR_FNTABLE_BINDING
) {
documentation = "Allows the application to generate screenshots."
EVRScreenshotError(
"RequestScreenshot",
"""
Request a screenshot of the requested type.
A request of the #EVRScreenshotType_VRScreenshotType_Stereo type will always work. Other types will depend on the underlying application support.
The first file name is for the preview image and should be a regular screenshot (ideally from the left eye). The second is the VR screenshot in the
correct format. They should be in the same aspect ratio.
Note that the VR dashboard will call this function when the user presses the screenshot binding (currently System Button + Trigger). If Steam is
running, the destination file names will be in %TEMP% and will be copied into Steam's screenshot library for the running application once
#SubmitScreenshot() is called. If Steam is not running, the paths will be in the user's documents folder under Documents\SteamVR\Screenshots. Other VR
applications can call this to initate a screenshot outside of user control. The destination file names do not need an extension, will be replaced with
the correct one for the format which is currently .png.
""",
Check(1)..ScreenshotHandle_t.p("pOutScreenshotHandle", ""),
EVRScreenshotType("type", "", "EVRScreenshotType_\\w+"),
charASCII.const.p("pchPreviewFilename", ""),
charASCII.const.p("pchVRFilename", "")
)
EVRScreenshotError(
"HookScreenshot",
"""
Called by the running VR application to indicate that it wishes to be in charge of screenshots. If the application does not call this, the Compositor
will only support #EVRScreenshotType_VRScreenshotType_Stereo screenshots that will be captured without notification to the running app.
Once hooked your application will receive a #EVREventType_VREvent_RequestScreenshot event when the user presses the buttons to take a screenshot.
""",
EVRScreenshotType.const.p("pSupportedTypes", ""),
AutoSize("pSupportedTypes")..int("numTypes", "")
)
EVRScreenshotType(
"GetScreenshotPropertyType",
"When your application receives a #EVREventType_VREvent_RequestScreenshot event, call these functions to get the details of the screenshot request.",
ScreenshotHandle_t("screenshotHandle", ""),
Check(1)..EVRScreenshotError.p("pError", "")
)
uint32_t(
"GetScreenshotPropertyFilename",
"Get the filename for the preview or vr image (see {@code EScreenshotPropertyFilenames}).",
ScreenshotHandle_t("screenshotHandle", ""),
EVRScreenshotPropertyFilenames("filenameType", "", "EVRScreenshotPropertyFilenames_\\w+"),
Return(RESULT, includesNT = true)..nullable..charASCII.p("pchFilename", ""),
AutoSize("pchFilename")..uint32_t("cchFilename", ""),
Check(1)..EVRScreenshotError.p("pError", ""),
returnDoc = "the size of the string"
)
EVRScreenshotError(
"UpdateScreenshotProgress",
"""
Call this if the application is taking the screen shot will take more than a few ms processing. This will result in an overlay being presented that
shows a completion bar.
""",
ScreenshotHandle_t("screenshotHandle", ""),
float("flProgress", "")
)
EVRScreenshotError(
"TakeStereoScreenshot",
"""
Tells the compositor to take an internal screenshot of type #EVRScreenshotType_VRScreenshotType_Stereo. It will take the current submitted scene
textures of the running application and write them into the preview image and a side-by-side file for the VR image.
This is similiar to request screenshot, but doesn't ever talk to the application, just takes the shot and submits.
""",
Check(1)..ScreenshotHandle_t.p("pOutScreenshotHandle", ""),
charASCII.const.p("pchPreviewFilename", ""),
charASCII.const.p("pchVRFilename", "")
)
EVRScreenshotError(
"SubmitScreenshot",
"""
Submit the completed screenshot.
If Steam is running this will call into the Steam client and upload the screenshot to the screenshots section of the library for the running
application. If Steam is not running, this function will display a notification to the user that the screenshot was taken. The paths should be full
paths with extensions.
File paths should be absolute including extensions.
{@code screenshotHandle} can be #k_unScreenshotHandleInvalid if this was a new shot taking by the app to be saved and not initiated by a user
(achievement earned or something).
""",
ScreenshotHandle_t("screenshotHandle", ""),
EVRScreenshotType("type", "", "EVRScreenshotType_\\w+"),
charASCII.const.p("pchSourcePreviewFilename", ""),
charASCII.const.p("pchSourceVRFilename", "")
)
} | bsd-3-clause | 1b6fd0c2bd4264daca75d854be94d97b | 43.815126 | 158 | 0.69111 | 4.714412 | false | false | false | false |
MichaelRocks/grip | library/src/main/java/io/michaelrocks/grip/commons/LazyList.kt | 1 | 3017 | /*
* Copyright 2021 Michael Rozumyanskiy
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.michaelrocks.grip.commons
import java.util.ArrayList
import java.util.Collections
internal class LazyList<T>(val factory: () -> MutableList<T> = { ArrayList<T>() }) : MutableList<T> {
private var delegate: MutableList<T> = emptyMutableList()
override val size: Int
get() = delegate.size
override fun contains(element: T): Boolean =
delegate.contains(element)
override fun containsAll(elements: Collection<T>): Boolean =
delegate.containsAll(elements)
override fun get(index: Int): T =
delegate[index]
override fun indexOf(element: T): Int =
delegate.indexOf(element)
override fun isEmpty(): Boolean =
delegate.isEmpty()
override fun iterator(): MutableIterator<T> =
delegate.iterator()
override fun lastIndexOf(element: T): Int =
delegate.lastIndexOf(element)
override fun add(element: T): Boolean =
mutate().add(element)
override fun add(index: Int, element: T) =
mutate().add(index, element)
override fun addAll(elements: Collection<T>): Boolean =
mutate().addAll(elements)
override fun addAll(index: Int, elements: Collection<T>): Boolean =
mutate().addAll(index, elements)
override fun clear() =
delegate.clear()
override fun listIterator(): MutableListIterator<T> =
delegate.listIterator()
override fun listIterator(index: Int): MutableListIterator<T> =
delegate.listIterator(index)
override fun remove(element: T): Boolean =
delegate.remove(element)
override fun removeAll(elements: Collection<T>): Boolean =
delegate.removeAll(elements)
override fun removeAt(index: Int): T =
delegate.removeAt(index)
override fun retainAll(elements: Collection<T>): Boolean =
delegate.retainAll(elements)
override fun set(index: Int, element: T): T =
delegate.set(index, element)
override fun subList(fromIndex: Int, toIndex: Int): MutableList<T> =
delegate.subList(fromIndex, toIndex)
fun immutableCopy(): List<T> =
if (isEmpty()) listOf()
else toMutableList().immutable()
fun detachImmutableCopy(): List<T> =
delegate.immutable().apply {
delegate = emptyMutableList()
}
@Suppress("UNCHECKED_CAST")
private fun emptyMutableList() =
Collections.EMPTY_LIST as MutableList<T>
private fun mutate(): MutableList<T> {
if (delegate === Collections.EMPTY_LIST) {
delegate = factory()
}
return delegate
}
}
| apache-2.0 | 7bf73781a3603657218390bfe421bde6 | 27.196262 | 101 | 0.705668 | 4.243319 | false | false | false | false |
DemonWav/MinecraftDev | src/test/kotlin/com/demonwav/mcdev/platform/mixin/AccessorMixinTest.kt | 1 | 4833 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2018 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.platform.mixin
import com.demonwav.mcdev.platform.mixin.util.isAccessorMixin
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiJavaFile
import org.intellij.lang.annotations.Language
class AccessorMixinTest : BaseMixinTest() {
override fun setUp() {
super.setUp()
buildProject {
src {
java("test/BaseMixin.java", """
package test;
public class BaseMixin {}
""")
java("test/BaseMixinInterface.java", """
package test;
public interface BaseMixinInterface {}
""")
}
}
}
private fun doTest(className: String, @Language("JAVA") code: String, test: (psiClass: PsiClass) -> Unit) {
var psiClass: PsiClass? = null
buildProject {
src {
psiClass = java("test/$className.java", code).toPsiFile<PsiJavaFile>().classes[0]
}
}
test(psiClass!!)
}
fun `test accessor mixin`() = doTest("AccessorMixin", """
package test;
import org.spongepowered.asm.mixin.gen.Accessor;
import org.spongepowered.asm.mixin.gen.Invoker;
import org.spongepowered.asm.mixin.Mixin;
@Mixin(BaseMixin.class)
public interface AccessorMixin {
@Accessor String getString();
@Accessor int getInt();
@Invoker void invoke();
@Invoker double doThing();
}
""") { psiClass ->
assertTrue(psiClass.isAccessorMixin)
}
fun `test missing accessor annotation`() = doTest("MissingAnnotationAccessorMixin", """
package test;
import org.spongepowered.asm.mixin.gen.Accessor;
import org.spongepowered.asm.mixin.gen.Invoker;
import org.spongepowered.asm.mixin.Mixin;
@Mixin(BaseMixin.class)
public interface MissingAnnotationAccessorMixin {
@Accessor String getString();
@Accessor int getInt();
@Invoker void invoke();
double doThing();
}
""") { psiClass ->
assertFalse(psiClass.isAccessorMixin)
}
fun `test accessor target interface`() = doTest("TargetInterface", """
package test;
import org.spongepowered.asm.mixin.gen.Accessor;
import org.spongepowered.asm.mixin.gen.Invoker;
import org.spongepowered.asm.mixin.Mixin;
@Mixin(BaseMixinInterface.class)
public interface TargetInterface {
@Accessor String getString();
@Accessor int getInt();
@Invoker void invoke();
@Invoker double doThing();
}
""") { psiClass ->
assertFalse(psiClass.isAccessorMixin)
}
fun `test only accessors`() = doTest("AccessorMixin", """
package test;
import org.spongepowered.asm.mixin.gen.Accessor;
import org.spongepowered.asm.mixin.Mixin;
@Mixin(BaseMixin.class)
public interface AccessorMixin {
@Accessor String getString();
@Accessor int getInt();
}
""") { psiClass ->
assertTrue(psiClass.isAccessorMixin)
}
fun `test only invokers`() = doTest("AccessorMixin", """
package test;
import org.spongepowered.asm.mixin.gen.Invoker;
import org.spongepowered.asm.mixin.Mixin;
@Mixin(BaseMixin.class)
public interface AccessorMixin {
@Invoker void invoke();
@Invoker double doThing();
}
""") { psiClass ->
assertTrue(psiClass.isAccessorMixin)
}
fun `test non-interface accessor mixin`() = doTest("NonInterfaceAccessorMixin", """
package test;
import org.spongepowered.asm.mixin.gen.Accessor;
import org.spongepowered.asm.mixin.gen.Invoker;
import org.spongepowered.asm.mixin.Mixin;
@Mixin(BaseMixin.class)
public class NonInterfaceAccessorMixin {
@Accessor String getString();
@Invoker void invoke();
}
""") { psiClass ->
assertFalse(psiClass.isAccessorMixin)
}
fun `test non-interface target interface`() = doTest("NonInterfaceTargetInterface", """
package test;
import org.spongepowered.asm.mixin.gen.Accessor;
import org.spongepowered.asm.mixin.gen.Invoker;
import org.spongepowered.asm.mixin.Mixin;
@Mixin(BaseMixinInterface.class)
public class NonInterfaceAccessorMixin {
@Accessor String getString();
@Invoker void invoke();
}
""") { psiClass ->
assertFalse(psiClass.isAccessorMixin)
}
}
| mit | 79e09f397f33a948b1e499a2af123abb | 28.469512 | 111 | 0.596938 | 4.987616 | false | true | false | false |
neva-dev/javarel-framework | foundation/src/main/kotlin/com/neva/javarel/foundation/impl/adapting/GenericAdaptingManager.kt | 1 | 2081 | package com.neva.javarel.foundation.impl.adapting
import com.google.common.collect.Maps
import com.google.common.collect.Sets
import com.neva.javarel.foundation.api.adapting.Adapter
import com.neva.javarel.foundation.api.adapting.AdaptingException
import com.neva.javarel.foundation.api.adapting.AdaptingManager
import org.apache.felix.scr.annotations.*
import kotlin.reflect.KClass
@Component(immediate = true)
@Service
class GenericAdaptingManager : AdaptingManager {
@Reference(
referenceInterface = Adapter::class,
cardinality = ReferenceCardinality.MANDATORY_MULTIPLE,
policy = ReferencePolicy.DYNAMIC,
policyOption = ReferencePolicyOption.GREEDY
)
override val adapters = Maps.newConcurrentMap<KClass<Any>, MutableSet<Adapter<Any, Any>>>()
@Suppress("UNCHECKED_CAST")
override fun <T : Any> adapt(adaptable: Any, clazz: KClass<T>): T {
val sourceType = adaptable.javaClass.kotlin
val targetType = clazz as KClass<Any>
val adapter = findAdapter(sourceType, targetType)
if (adapter == null) {
throw AdaptingException("Adapting type: '${sourceType.qualifiedName}' into '${targetType.qualifiedName}' is not possible.")
}
return adapter.adapt(adaptable) as T
}
private fun findAdapter(sourceType: KClass<Any>?, targetType: KClass<Any>): Adapter<Any, Any>? {
var fallback: Adapter<Any, Any>? = null
if (adapters.containsKey(targetType)) {
for (adapter in adapters.get(targetType)!!) {
if (adapter.sourceTypes.contains(sourceType)) {
return adapter
} else {
fallback = adapter
}
}
}
return fallback
}
private fun bindAdapters(adapter: Adapter<Any, Any>) {
adapters.getOrPut(adapter.targetType, { Sets.newConcurrentHashSet() }).add(adapter)
}
private fun unbindAdapters(adapter: Adapter<Any, Any>) {
adapters.get(adapter.targetType)!!.remove(adapter)
}
}
| apache-2.0 | 4ec2313f49e39b4faba47901043f334b | 33.683333 | 135 | 0.662662 | 4.353556 | false | false | false | false |
tomsteele/burpbuddy | src/main/kotlin/burp/ProxyListener.kt | 1 | 5035 | package burp
import com.github.kittinunf.fuel.Fuel
import com.github.kittinunf.fuel.core.FuelManager
import com.github.kittinunf.fuel.core.requests.write
import com.github.kittinunf.fuel.core.requests.writeln
import com.github.salomonbrys.kotson.fromJson
import com.google.gson.Gson
import com.sun.org.apache.xpath.internal.operations.Bool
import javax.swing.JToggleButton
import javax.swing.JTextField
class ProxyListener(private val requestHookField: JTextField, private val responseHookField: JTextField,
private val requestHookButton: JToggleButton, private val responseHookButton: JToggleButton,
private val callbacks: IBurpExtenderCallbacks): IProxyListener {
override fun processProxyMessage(messageIsRequest: Boolean, message: IInterceptedProxyMessage) {
val requestHookURL = requestHookField.text
val responseHookURL = responseHookField.text
val httpRequestResponse = message.messageInfo
val messageReference = message.messageReference
val gson = Gson()
FuelManager.instance.baseHeaders = mapOf("Content-Type" to "application/json")
val b2b = BurpToBuddy(callbacks)
if (!requestHookButton.isSelected && messageIsRequest && requestHookURL != "") {
val jsonHttpRequestResponse = b2b.httpRequestResponseToJsonObject(httpRequestResponse)
jsonHttpRequestResponse.addProperty("tool", "proxy")
jsonHttpRequestResponse.addProperty("reference_id", messageReference)
jsonHttpRequestResponse.remove("response")
val (_, response, _) = Fuel.post(requestHookURL).
body(jsonHttpRequestResponse.toString()).response()
if (response.statusCode != 200) {
return
}
val modifiedHttpRequest = gson.fromJson<HttpRequestResponse>(String(response.data))
val originalHttpRequest = gson.fromJson<HttpRequestResponse>(jsonHttpRequestResponse.toString())
callbacks.stdout.write(modifiedHttpRequest.request.method)
if (requestHasChangesThatAreNotToRaw(originalHttpRequest, modifiedHttpRequest)) {
// Build the new "headers" to fit into burp's spec.
val methodPathVersion = "${modifiedHttpRequest.request.method} ${modifiedHttpRequest.request.path} ${modifiedHttpRequest.request.http_version}"
val headers = mutableListOf(methodPathVersion)
headers.addAll(modifiedHttpRequest.request.headers.map({
"${it.key}: ${it.value}"
}))
httpRequestResponse.request = callbacks.helpers.buildHttpMessage(headers,
callbacks.helpers.base64Decode(modifiedHttpRequest.request.body))
} else if (originalHttpRequest.request.raw != modifiedHttpRequest.request.raw) {
httpRequestResponse.request = callbacks.helpers.base64Decode(modifiedHttpRequest.request.raw)
}
if (modifiedHttpRequest.comment != "") {
httpRequestResponse.comment = modifiedHttpRequest.comment
}
if (modifiedHttpRequest.highlight != "") {
httpRequestResponse.highlight = modifiedHttpRequest.highlight
}
} else if (!responseHookButton.isSelected && responseHookURL != "") {
val jsonHttpRequestResponse = b2b.httpRequestResponseToJsonObject(httpRequestResponse)
jsonHttpRequestResponse.addProperty("reference_id", messageReference)
jsonHttpRequestResponse.addProperty("tool", "proxy")
jsonHttpRequestResponse.remove("request")
val (_, response, _) = Fuel.post(responseHookURL).body(jsonHttpRequestResponse.toString()).responseString()
if (response.statusCode != 200) {
return
}
val modifiedHttpResponse = gson.fromJson<HttpRequestResponse>(String(response.data))
val originalHttpResponse = gson.fromJson<HttpRequestResponse>(jsonHttpRequestResponse.toString())
if (originalHttpResponse.response != null && modifiedHttpResponse.response != null
&& originalHttpResponse.response.raw != modifiedHttpResponse.response.raw) {
httpRequestResponse.response = callbacks.helpers.base64Decode(modifiedHttpResponse.response.raw)
}
if (modifiedHttpResponse.comment != "" ) {
httpRequestResponse.comment = modifiedHttpResponse.comment
}
if (modifiedHttpResponse.highlight != "") {
httpRequestResponse.highlight = modifiedHttpResponse.highlight
}
}
}
private fun requestHasChangesThatAreNotToRaw(x: HttpRequestResponse, y: HttpRequestResponse): Boolean {
return (x.request.method != y.request.method ||
x.request.path != y.request.path ||
x.request.body != y.request.body ||
x.request.http_version != y.request.http_version)
}
} | mit | c2781c97bd5548dd352b21a64a0eee4f | 52.574468 | 159 | 0.674876 | 5.201446 | false | false | false | false |
dhis2/dhis2-android-sdk | core/src/main/java/org/hisp/dhis/android/core/sms/data/localdbrepository/internal/OngoingSubmissionsStore.kt | 1 | 6252 | /*
* Copyright (c) 2004-2022, University of Oslo
* All rights reserved.
*
* Redistribution and use 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 HISP project nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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 org.hisp.dhis.android.core.sms.data.localdbrepository.internal
import android.util.Log
import android.util.Pair
import dagger.Reusable
import io.reactivex.Completable
import io.reactivex.Single
import javax.inject.Inject
import org.hisp.dhis.android.core.arch.db.querybuilders.internal.WhereClauseBuilder
import org.hisp.dhis.android.core.arch.db.stores.internal.ObjectWithoutUidStore
import org.hisp.dhis.android.core.sms.domain.repository.internal.LocalDbRepository.TooManySubmissionsException
import org.hisp.dhis.android.core.sms.domain.repository.internal.SubmissionType
@Reusable
internal class OngoingSubmissionsStore @Inject constructor(
private val smsOngoingSubmissionStore: ObjectWithoutUidStore<SMSOngoingSubmission>,
private val smsConfigStore: SMSConfigStore
) {
private var ongoingSubmissions: Map<Int, SubmissionType>? = null
private var lastGeneratedSubmissionId: Int? = null
fun getOngoingSubmissions(): Single<Map<Int, SubmissionType>> {
return Single.fromCallable {
if (ongoingSubmissions == null) {
updateOngoingSubmissions()
}
ongoingSubmissions!!
}.onErrorReturn { throwable ->
Log.e(TAG, throwable.message, throwable)
emptyMap()
}
}
@SuppressWarnings("MagicNumber")
fun addOngoingSubmission(id: Int?, type: SubmissionType?): Completable {
if (id == null || id < 0 || id > 255) {
return Completable.error(IllegalArgumentException("Wrong submission id"))
}
return if (type == null) {
Completable.error(IllegalArgumentException("Wrong submission type"))
} else getOngoingSubmissions().flatMapCompletable { submissions: Map<Int, SubmissionType> ->
if (submissions.containsKey(id)) {
Completable.error(IllegalArgumentException("Submission id already exists"))
} else {
Completable.fromCallable {
val ongoingSubmission = SMSOngoingSubmission.builder().submissionId(id).type(type).build()
smsOngoingSubmissionStore.insert(ongoingSubmission)
updateOngoingSubmissions()
}
}
}
}
fun removeOngoingSubmission(id: Int?): Completable {
return if (id == null) {
Completable.error(IllegalArgumentException("Wrong submission id"))
} else {
Completable.fromCallable {
val whereClause = WhereClauseBuilder()
.appendKeyStringValue(SMSOngoingSubmissionTableInfo.Columns.SUBMISSION_ID, id)
.build()
smsOngoingSubmissionStore.deleteWhereIfExists(whereClause)
updateOngoingSubmissions()
}
}
}
private fun updateOngoingSubmissions() {
val submissionList = smsOngoingSubmissionStore.selectAll()
this.ongoingSubmissions = submissionList.associate { it.submissionId() to it.type() }
lastGeneratedSubmissionId?.let { saveLastGeneratedSubmissionId(it) }
}
private fun getLastGeneratedSubmissionId(): Single<Int> {
return if (lastGeneratedSubmissionId != null) {
Single.just(lastGeneratedSubmissionId)
} else Single.fromCallable {
smsConfigStore.get(SMSConfigKey.LAST_SUBMISSION_ID)?.toInt() ?: 0
}
.doOnSuccess { lastGeneratedSubmissionId = it }
}
private fun saveLastGeneratedSubmissionId(id: Int) {
smsConfigStore.set(SMSConfigKey.LAST_SUBMISSION_ID, id.toString())
}
@SuppressWarnings("MagicNumber")
fun generateNextSubmissionId(): Single<Int> {
return Single.zip<Map<Int, SubmissionType>, Int, Pair<Map<Int, SubmissionType>, Int>>(
getOngoingSubmissions(),
getLastGeneratedSubmissionId()
) { a: Map<Int, SubmissionType>?, b: Int? -> Pair.create(a, b) }
.flatMap { ids: Pair<Map<Int, SubmissionType>, Int> ->
val ongoingIds: Collection<Int> = ids.first.keys
val lastId = ids.second
var i = lastId
do {
i++
if (i >= 255) {
i = 0
}
if (!ongoingIds.contains(i)) {
lastGeneratedSubmissionId = i
return@flatMap Single.just(i)
}
} while (i != lastId)
Single.error(TooManySubmissionsException())
}
}
companion object {
private val TAG = OngoingSubmissionsStore::class.java.simpleName
}
}
| bsd-3-clause | cc210c5318be5dadade6dcd8a5648d05 | 43.028169 | 110 | 0.663948 | 4.880562 | false | false | false | false |
dahlstrom-g/intellij-community | plugins/ide-features-trainer/src/training/statistic/FeatureUsageStatisticConsts.kt | 6 | 2310 | // 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 training.statistic
object FeatureUsageStatisticConsts {
const val LESSON_ID = "lesson_id"
const val LANGUAGE = "language"
const val DURATION = "duration"
const val START = "start"
const val PASSED = "passed"
const val STOPPED = "stopped"
const val START_MODULE_ACTION = "start_module_action"
const val MODULE_NAME = "module_name"
const val PROGRESS = "progress"
const val COMPLETED_COUNT = "completed_count"
const val COURSE_SIZE = "course_size"
const val EXPAND_WELCOME_PANEL = "expand_welcome_screen"
const val SHORTCUT_CLICKED = "shortcut_clicked"
const val RESTORE = "restore"
const val LEARN_PROJECT_OPENED_FIRST_TIME = "learn_project_opened_first_time"
const val NON_LEARNING_PROJECT_OPENED = "non_learning_project_opened"
const val LEARN_PROJECT_OPENING_WAY = "learn_opening_way"
const val ACTION_ID = "action_id"
const val TASK_ID = "task_id"
const val KEYMAP_SCHEME = "keymap_scheme"
const val REASON = "reason"
const val NEW_LESSONS_NOTIFICATION_SHOWN = "new_lessons_notification_shown"
const val SHOW_NEW_LESSONS = "show_new_lessons"
const val NEED_SHOW_NEW_LESSONS_NOTIFICATIONS = "need_show_new_lessons_notifications"
const val NEW_LESSONS_COUNT = "new_lessons_count"
const val LAST_BUILD_LEARNING_OPENED = "last_build_learning_opened"
const val SHOULD_SHOW_NEW_LESSONS = "show_it"
const val TIP_FILENAME = "filename"
const val LESSON_LINK_CLICKED_FROM_TIP = "lesson_link_clicked_from_tip"
const val LESSON_STARTING_WAY = "starting_way"
const val HELP_LINK_CLICKED = "help_link_clicked"
const val ONBOARDING_FEEDBACK_NOTIFICATION_SHOWN = "onboarding_feedback_notification_shown"
const val ONBOARDING_FEEDBACK_DIALOG_RESULT = "onboarding_feedback_dialog_result"
const val FEEDBACK_ENTRY_PLACE = "feedback_entry_place"
const val FEEDBACK_HAS_BEEN_SENT = "feedback_has_been_sent"
const val FEEDBACK_OPENED_VIA_NOTIFICATION = "feedback_opened_via_notification"
const val FEEDBACK_LIKENESS_ANSWER = "feedback_likeness_answer"
const val FEEDBACK_EXPERIENCED_USER = "feedback_experienced_user"
const val PROBLEM = "problem"
const val INTERNAL_PROBLEM = "internal_problem"
}
| apache-2.0 | fe3783b45d91008df8ca7806a5f082f4 | 50.333333 | 140 | 0.752381 | 3.526718 | false | false | false | false |
ThePreviousOne/tachiyomi | app/src/main/java/eu/kanade/tachiyomi/data/source/online/russian/Mangachan.kt | 1 | 3991 | package eu.kanade.tachiyomi.data.source.online.russian
import android.content.Context
import eu.kanade.tachiyomi.data.database.models.Chapter
import eu.kanade.tachiyomi.data.database.models.Manga
import eu.kanade.tachiyomi.data.source.Language
import eu.kanade.tachiyomi.data.source.RU
import eu.kanade.tachiyomi.data.source.model.Page
import eu.kanade.tachiyomi.data.source.online.ParsedOnlineSource
import okhttp3.Response
import org.jsoup.nodes.Document
import org.jsoup.nodes.Element
import java.text.SimpleDateFormat
import java.util.*
class Mangachan(override val id: Int) : ParsedOnlineSource() {
override val name = "Mangachan"
override val baseUrl = "http://mangachan.me"
override val lang: Language get() = RU
override val supportsLatest = true
override fun popularMangaInitialUrl() = "$baseUrl/mostfavorites"
override fun latestUpdatesInitialUrl() = "$baseUrl/manga/new"
override fun searchMangaInitialUrl(query: String, filters: List<Filter>) = "$baseUrl/?do=search&subaction=search&story=$query"
override fun popularMangaSelector() = "div.content_row"
override fun latestUpdatesSelector() = "div.content_row"
override fun popularMangaFromElement(element: Element, manga: Manga) {
element.select("h2 > a").first().let {
manga.setUrlWithoutDomain(it.attr("href"))
manga.title = it.text()
}
}
override fun latestUpdatesFromElement(element: Element, manga: Manga) {
popularMangaFromElement(element, manga)
}
override fun popularMangaNextPageSelector() = "a:contains(Вперед)"
override fun latestUpdatesNextPageSelector() = "a:contains(Вперед)"
override fun searchMangaSelector() = popularMangaSelector()
override fun searchMangaFromElement(element: Element, manga: Manga) {
popularMangaFromElement(element, manga)
}
override fun searchMangaNextPageSelector() = popularMangaNextPageSelector()
override fun mangaDetailsParse(document: Document, manga: Manga) {
val infoElement = document.select("table.mangatitle").first()
val descElement = document.select("div#description").first()
val imgElement = document.select("img#cover").first()
manga.author = infoElement.select("tr:eq(2) > td:eq(1)").text()
manga.genre = infoElement.select("tr:eq(5) > td:eq(1)").text()
manga.status = parseStatus(infoElement.select("tr:eq(4) > td:eq(1)").text())
manga.description = descElement.textNodes().first().text()
manga.thumbnail_url = baseUrl + imgElement.attr("src")
}
private fun parseStatus(element: String): Int {
when {
element.contains("перевод завершен") -> return Manga.COMPLETED
element.contains("перевод продолжается") -> return Manga.ONGOING
else -> return Manga.UNKNOWN
}
}
override fun chapterListSelector() = "table.table_cha tr:gt(1)"
override fun chapterFromElement(element: Element, chapter: Chapter) {
val urlElement = element.select("a").first()
chapter.setUrlWithoutDomain(urlElement.attr("href"))
chapter.name = urlElement.text()
chapter.date_upload = element.select("div.date").first()?.text()?.let {
SimpleDateFormat("yyyy-MM-dd", Locale.US).parse(it).time
} ?: 0
}
override fun pageListParse(response: Response, pages: MutableList<Page>) {
val html = response.body().string()
val beginIndex = html.indexOf("fullimg\":[") + 10
val endIndex = html.indexOf(",]", beginIndex)
val trimmedHtml = html.substring(beginIndex, endIndex).replace("\"", "")
val pageUrls = trimmedHtml.split(',')
for ((i, url) in pageUrls.withIndex()) {
pages.add(Page(i, "", url))
}
}
override fun pageListParse(document: Document, pages: MutableList<Page>) { }
override fun imageUrlParse(document: Document) = ""
} | apache-2.0 | 1298e063d462e27324254d8b84b11209 | 35.878505 | 130 | 0.685171 | 4.325658 | false | false | false | false |
JuliaSoboleva/SmartReceiptsLibrary | app/src/main/java/co/smartreceipts/android/columns/ordering/AbstractColumnsOrderer.kt | 2 | 5609 | package co.smartreceipts.android.columns.ordering
import co.smartreceipts.android.model.Column
import co.smartreceipts.android.model.Receipt
import co.smartreceipts.android.model.factory.ColumnBuilderFactory
import co.smartreceipts.android.model.impl.columns.receipts.ReceiptColumnDefinitions
import co.smartreceipts.android.persistence.database.controllers.impl.ColumnTableController
import co.smartreceipts.android.persistence.database.operations.DatabaseOperationMetadata
import co.smartreceipts.android.persistence.database.operations.OperationFamilyType
import co.smartreceipts.analytics.log.Logger
import io.reactivex.Completable
import io.reactivex.Observable
import io.reactivex.Scheduler
/**
* Manages our ordering of our PDF & CSV columns, helping us to ensure that we can keep things in
* a consistent order. This class also provides utility methods to allow us to insert a new column
* at a specific position
*/
abstract class AbstractColumnsOrderer(private val columnTableController: ColumnTableController,
private val receiptColumnDefinitions: ReceiptColumnDefinitions,
private val scheduler: Scheduler) {
/**
* Inserts a given column definition, [definitionToInsert], after another column ([after]), which
* may be in our current list. If [after] is not in our list, we will add [definitionToInsert] to
* the end of the list. In the event that the list contains multiple instances of [after], we
* insert [definitionToInsert] after the first instance
*
* @param definitionToInsert the definition to add to our list
* @param after the item to add [definitionToInsert] after
*
* @return a [Completable], which will emit onComplete or onError based on the result of this operation
*/
fun insertColumnAfter(definitionToInsert: ReceiptColumnDefinitions.ActualDefinition, after: ReceiptColumnDefinitions.ActualDefinition) : Completable {
return columnTableController.get()
.subscribeOn(scheduler)
.map { columns ->
// First, loop through each item to see if we can find the 'after' index
var customOrderId = columns.size.toLong()
for (index in 0 until columns.size) {
if (columns[index].type == after.columnType) {
customOrderId = (index + 1).toLong()
}
}
// Use this to build the column that we need to insert
val columnToInsert = receiptColumnDefinitions.getColumnFromDefinition(
definition = definitionToInsert,
customOrderId = customOrderId
)
// To be safe here, we will update all of our column indices to the appropriate position
val columnsToUpdate = mutableListOf<Pair<Column<Receipt>, Column<Receipt>>>()
for (index in 0 until columns.size) {
val oldColumn = columns[index]
val newCustomOrderId = if (index >= customOrderId) index + 1 else index
val newColumn = ColumnBuilderFactory(receiptColumnDefinitions, oldColumn)
.setCustomOrderId(newCustomOrderId.toLong())
.build()
columnsToUpdate.add(Pair(oldColumn, newColumn))
}
return@map ColumnTableActionsData(columnToInsert, columnsToUpdate)
}
.flatMap { columnTableActionsData ->
// First, we perform our series of updates
Observable.fromIterable(columnTableActionsData.columnsToUpdate)
.flatMap { pair ->
columnTableController.update(pair.first, pair.second, DatabaseOperationMetadata(OperationFamilyType.Silent))
.flatMap { resultOptional ->
if (resultOptional.isPresent) {
Observable.just(resultOptional.get())
} else {
Observable.error<Column<Receipt>>(Exception("Failed to update the column custom_order_id"))
}
}
}
.toList() // Use this to collect / wait for all update results
.flatMap { _ ->
columnTableController.insert(columnTableActionsData.columnToInsert, DatabaseOperationMetadata())
.firstOrError()
}
}
.doOnError {
Logger.warn(this, "Failed to insert {} after {}", definitionToInsert, after)
}
.doOnSuccess {
Logger.info(this, "Successfully inserted {} after {}", definitionToInsert, after)
}
.ignoreElement()
}
/**
* A private inner class, which we use to store the required metadata that we need to insert and
* update metadata for our columns
*/
private data class ColumnTableActionsData(
val columnToInsert: Column<Receipt>,
val columnsToUpdate: List<Pair<Column<Receipt>, Column<Receipt>>>)
} | agpl-3.0 | f4dba47d59bd72dfb4fa30bbdcbe6959 | 54 | 154 | 0.583705 | 5.929175 | false | false | false | false |
zbeboy/ISY | src/main/java/top/zbeboy/isy/web/bean/graduate/design/replan/DefenseGroupBean.kt | 1 | 441 | package top.zbeboy.isy.web.bean.graduate.design.replan
import top.zbeboy.isy.domain.tables.pojos.DefenseGroup
/**
* Created by zbeboy 2018-02-06 .
**/
class DefenseGroupBean : DefenseGroup() {
var buildingId: Int? = null
var buildingName: String? = null
var buildingCode: String? = null
var staffName: String? = null
var studentName: String? = null
// 压缩组员信息
var memberName: List<String>? = null
} | mit | 0c23771977788902395c40392a66de59 | 25.875 | 54 | 0.694639 | 3.404762 | false | false | false | false |
DemonWav/MinecraftDevIntelliJ | src/main/kotlin/com/demonwav/mcdev/insight/ListenerEventAnnotator.kt | 1 | 3955 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2020 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.insight
import com.demonwav.mcdev.MinecraftSettings
import com.demonwav.mcdev.facet.MinecraftFacet
import com.intellij.lang.annotation.AnnotationHolder
import com.intellij.lang.annotation.Annotator
import com.intellij.openapi.module.ModuleUtilCore
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiIdentifier
import com.intellij.psi.PsiMethod
import com.intellij.psi.PsiModifier
import com.intellij.psi.impl.source.PsiClassReferenceType
class ListenerEventAnnotator : Annotator {
override fun annotate(element: PsiElement, holder: AnnotationHolder) {
if (!MinecraftSettings.instance.isShowEventListenerGutterIcons) {
return
}
// Since we want to line up with the method declaration, not the annotation
// declaration, we need to target identifiers, not just PsiMethods.
if (!(element is PsiIdentifier && element.getParent() is PsiMethod)) {
return
}
// The PsiIdentifier is going to be a method of course!
val method = element.getParent() as PsiMethod
if (method.hasModifierProperty(PsiModifier.ABSTRACT)) {
// I don't think any implementation allows for abstract
return
}
val modifierList = method.modifierList
val module = ModuleUtilCore.findModuleForPsiElement(element) ?: return
val instance = MinecraftFacet.getInstance(module) ?: return
// Since each platform has their own valid listener annotations,
// some platforms may have multiple allowed annotations for various cases
val moduleTypes = instance.types
var contains = false
for (moduleType in moduleTypes) {
val listenerAnnotations = moduleType.listenerAnnotations
for (listenerAnnotation in listenerAnnotations) {
if (modifierList.findAnnotation(listenerAnnotation) != null) {
contains = true
break
}
}
}
if (!contains) {
return
}
val parameters = method.parameterList.parameters
if (parameters.isEmpty()) {
return
}
val eventParameter = parameters[0] // Listeners must have at least a single parameter
?: return
// Get the type of the parameter so we can start resolving it
val psiEventElement = eventParameter.typeElement ?: return
val type = psiEventElement.type as? PsiClassReferenceType ?: return
// Validate that it is a class reference type
// And again, make sure that we can at least resolve the type, otherwise it's not a valid
// class reference.
val eventClass = type.resolve() ?: return
if (instance.isEventClassValid(eventClass, method)) {
return
}
if (!instance.isStaticListenerSupported(method) && method.hasModifierProperty(PsiModifier.STATIC)) {
if (method.nameIdentifier != null) {
holder.createErrorAnnotation(method.nameIdentifier!!, "Event listener method must not be static")
}
}
if (!isSuperEventListenerAllowed(eventClass, method, instance)) {
holder.createErrorAnnotation(eventParameter, instance.writeErrorMessageForEvent(eventClass, method))
}
}
private fun isSuperEventListenerAllowed(eventClass: PsiClass, method: PsiMethod, facet: MinecraftFacet): Boolean {
val supers = eventClass.supers
for (aSuper in supers) {
if (facet.isEventClassValid(aSuper, method)) {
return true
}
if (isSuperEventListenerAllowed(aSuper, method, facet)) {
return true
}
}
return false
}
}
| mit | a576f8bfaf7a10baca94165b2f32ef80 | 37.028846 | 118 | 0.65512 | 5.245358 | false | false | false | false |
peruukki/SimpleCurrencyConverter | app/src/main/java/com/peruukki/simplecurrencyconverter/db/ConverterDbHelper.kt | 1 | 3082 | package com.peruukki.simplecurrencyconverter.db
import android.content.ContentValues
import android.content.Context
import android.database.Cursor
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteOpenHelper
import android.provider.BaseColumns
import com.peruukki.simplecurrencyconverter.db.ConverterContract.ConversionRateEntry
import com.peruukki.simplecurrencyconverter.models.ConversionRate
class ConverterDbHelper(context: Context) : SQLiteOpenHelper(context, DATABASE_NAME, null, DATABASE_VERSION) {
override fun onCreate(db: SQLiteDatabase) {
// Create table
val createTableSql = CREATE + ConversionRateEntry.TABLE_NAME + " (" +
BaseColumns._ID + PRIMARY_KEY_AUTO_INCR + "," +
ConversionRateEntry.COLUMN_FIXED_CURRENCY + TEXT + "," +
ConversionRateEntry.COLUMN_VARIABLE_CURRENCY + TEXT + "," +
ConversionRateEntry.COLUMN_CONVERSION_RATE + REAL +
")"
db.execSQL(createTableSql)
// Insert initial conversion rates
for (conversionRate in ConversionRate.allRates) {
val values = ContentValues()
values.put(ConversionRateEntry.COLUMN_FIXED_CURRENCY, conversionRate.fixedCurrency)
values.put(ConversionRateEntry.COLUMN_VARIABLE_CURRENCY, conversionRate.variableCurrency)
values.put(ConversionRateEntry.COLUMN_CONVERSION_RATE,
conversionRate.fixedCurrencyInVariableCurrencyRate)
db.insert(ConversionRateEntry.TABLE_NAME, null, values)
}
}
override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {
db.execSQL(DROP + ConversionRateEntry.TABLE_NAME)
onCreate(db)
}
companion object {
private val DATABASE_VERSION = 1
private val DATABASE_NAME = "converter.db"
/* If you change table column order, update these indices as well. */
private val COL_INDEX_FIXED_CURRENCY = 1
private val COL_INDEX_VARIABLE_CURRENCY = 2
private val COL_INDEX_CONVERSION_RATE = 3
private val PRIMARY_KEY_AUTO_INCR = " INTEGER PRIMARY KEY AUTOINCREMENT"
private val TEXT = " TEXT NOT NULL"
private val REAL = " REAL NOT NULL"
private val CREATE = "CREATE TABLE "
private val DROP = "DROP TABLE IF EXISTS "
/**
* Returns a [com.peruukki.simplecurrencyconverter.models.ConversionRate] instance from given
* database cursor.
*
* @param cursor database cursor pointing to a table row
* @return a ConversionRate instance from given table row data
*/
@JvmStatic
fun conversionRateFromCursor(cursor: Cursor): ConversionRate {
val fixedCurrency = cursor.getString(COL_INDEX_FIXED_CURRENCY)
val variableCurrency = cursor.getString(COL_INDEX_VARIABLE_CURRENCY)
val rate = cursor.getFloat(COL_INDEX_CONVERSION_RATE)
return ConversionRate(fixedCurrency, variableCurrency, rate)
}
}
}
| mit | 4f204d9f538bc1fc7798937d82671dce | 41.219178 | 110 | 0.682025 | 4.884311 | false | false | false | false |
Kangmo/korbit-scala-sdk | src/main/kotlin/org/kangmo/http/HTTPActors.kt | 1 | 2624 | package org.kangmo.http
import kotlinx.coroutines.experimental.CommonPool
import kotlinx.coroutines.experimental.async
import kotlinx.coroutines.experimental.channels.actor
import org.kangmo.helper.Excp
import org.slf4j.LoggerFactory
import java.util.*
sealed abstract class AbstractRequest(open val options : List<String>) {
fun addNonceToHeader(httpHeaders : Map<String,String>, nonce : Long?) : Map<String,String> {
val nonceHeader = if (nonce != null) ("Nonce" to nonce.toString()) else null
if (nonceHeader == null )
return httpHeaders
else
return httpHeaders + nonceHeader
}
abstract suspend fun execute(nonce : Long?) : Unit
}
abstract class PostRequest(
open val urlStr:String,
override val options : List<String>,
open val postData:String = "",
val httpHeaders : Map<String,String> = Collections.unmodifiableMap(HashMap()),
open val callback : suspend (String) -> Unit) : AbstractRequest(options) {
override suspend fun execute(nonce : Long?) {
val httpResponse = HTTP.post(urlStr, postData, addNonceToHeader(httpHeaders, nonce) )
callback( httpResponse )
}
}
abstract class GetRequest(
open val urlStr:String,
override val options : List<String>,
val httpHeaders : Map<String,String> = Collections.unmodifiableMap(HashMap()),
open val callback : suspend (String) -> Unit) : AbstractRequest(options) {
override suspend fun execute(nonce : Long?) {
val httpResponse = HTTP.get(urlStr, addNonceToHeader(httpHeaders, nonce) )
callback( httpResponse )
}
}
fun HTTPSerialWorker() = actor<AbstractRequest>(CommonPool) {
val logger = LoggerFactory.getLogger(javaClass)
var counter = 0 // actor state
for (msg in channel) { // iterate over incoming messages
when (msg) {
is AbstractRequest -> {
assert(msg.options.contains("AddNonceOption"))
// If nonce is required, execute the request in serial with nonce set.
try {
msg.execute( System.currentTimeMillis() )
} catch(e : Exception) {
logger.error("Internal Error. " + e.message )
logger.error(Excp.getStackTrace(e))
}
}
}
}
}
fun HTTPDispatcher() = actor<AbstractRequest>(CommonPool) {
for (msg in channel) { // iterate over incoming messages
when (msg) {
is AbstractRequest -> {
if (msg.options.contains("AddNonceOption")) {
// If nonce is required, execute the request in serial with nonce set.
HTTPActor.serialWorker.send(msg)
} else {
// If nonce is not required, execute the request concurrently.
msg.execute( null )
}
}
}
}
}
object HTTPActor {
val serialWorker = HTTPSerialWorker()
val dispatcher = HTTPDispatcher()
}
| apache-2.0 | 185ae23878ae09e75500f62bcc9a2ebb | 29.16092 | 93 | 0.717607 | 3.690577 | false | false | false | false |
StephaneBg/ScoreIt | app/src/main/kotlin/com/sbgapps/scoreit/app/ui/saved/SavedGameViewModel.kt | 1 | 2522 | /*
* Copyright 2020 Stéphane Baiget
*
* 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.sbgapps.scoreit.app.ui.saved
import android.annotation.SuppressLint
import com.sbgapps.scoreit.app.model.SavedGame
import com.sbgapps.scoreit.core.ui.BaseViewModel
import com.sbgapps.scoreit.data.interactor.GameUseCase
import io.uniflow.core.flow.data.UIState
import org.threeten.bp.Instant
import org.threeten.bp.ZoneId
import org.threeten.bp.ZonedDateTime
import org.threeten.bp.format.DateTimeFormatter
class SavedGameViewModel(private val useCase: GameUseCase, private val datePattern: String) : BaseViewModel() {
fun loadGame(name: String) {
action {
useCase.loadGame(name)
setState { SavedAction.Complete }
}
}
fun getSavedFiles() {
action {
setState { SavedAction.Content(getSavedGames()) }
}
}
fun editName(position: Int, newName: String) {
action {
val savedGames = getSavedGames().toMutableList()
useCase.renameGame(savedGames[position].fileName, newName)
setState { SavedAction.Content(getSavedGames()) }
}
}
fun deleteGame(position: Int) {
action {
val savedGames = getSavedGames()
useCase.removeGame(savedGames[position].fileName)
setState { SavedAction.Content(getSavedGames()) }
}
}
@SuppressLint("DefaultLocale")
private fun getSavedGames(): List<SavedGame> =
useCase.getSavedFiles().map { (name, players, timeStamp) ->
val instant = Instant.ofEpochMilli(timeStamp)
val lastModified = ZonedDateTime.ofInstant(instant, ZoneId.systemDefault())
.format(DateTimeFormatter.ofPattern(datePattern))
.capitalize()
SavedGame(name, players, lastModified)
}
}
sealed class SavedAction : UIState() {
data class Content(val games: List<SavedGame>) : SavedAction()
object Complete : SavedAction()
}
| apache-2.0 | bebfa9dcad7d6d9313b381c090985fb0 | 33.067568 | 111 | 0.684252 | 4.422807 | false | false | false | false |
Atsky/haskell-idea-plugin | plugin/src/org/jetbrains/yesod/hamlet/parser/HamletParserDefinition.kt | 1 | 3676 | package org.jetbrains.yesod.hamlet.parser
/**
* @author Leyla H
*/
import com.intellij.extapi.psi.ASTWrapperPsiElement
import com.intellij.lang.ASTNode
import com.intellij.lang.ParserDefinition
import com.intellij.lang.PsiParser
import com.intellij.lexer.Lexer
import com.intellij.openapi.project.Project
import com.intellij.psi.FileViewProvider
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.psi.tree.IFileElementType
import com.intellij.psi.tree.TokenSet
import org.jetbrains.yesod.hamlet.HamletFile
import org.jetbrains.yesod.hamlet.HamletLanguage
import org.jetbrains.yesod.hamlet.psi.*
class HamletParserDefinition : ParserDefinition {
override fun createLexer(project: Project): Lexer {
return HamletLexer()
}
override fun createParser(project: Project): PsiParser {
return HamletParser()
}
override fun getFileNodeType(): IFileElementType {
return HAMLET_FILE
}
override fun getWhitespaceTokens(): TokenSet {
return HamletTokenTypes.WHITESPACES
}
override fun getCommentTokens(): TokenSet {
return TokenSet.EMPTY
}
override fun getStringLiteralElements(): TokenSet {
return TokenSet.EMPTY
}
override fun createElement(astNode: ASTNode): PsiElement {
if (astNode.elementType === HamletTokenTypes.TAG) {
return org.jetbrains.yesod.hamlet.psi.Tag(astNode)
}
if (astNode.elementType === HamletTokenTypes.DOCTYPE) {
return org.jetbrains.yesod.hamlet.psi.Doctype(astNode)
}
if (astNode.elementType === HamletTokenTypes.STRING) {
return org.jetbrains.yesod.hamlet.psi.String(astNode)
}
if (astNode.elementType === HamletTokenTypes.DOT_IDENTIFIER) {
return org.jetbrains.yesod.hamlet.psi.DotIdentifier(astNode)
}
if (astNode.elementType === HamletTokenTypes.COLON_IDENTIFIER) {
return org.jetbrains.yesod.hamlet.psi.ColonIdentifier(astNode)
}
if (astNode.elementType === HamletTokenTypes.INTERPOLATION) {
return org.jetbrains.yesod.hamlet.psi.Interpolation(astNode)
}
if (astNode.elementType === HamletTokenTypes.SHARP_IDENTIFIER) {
return org.jetbrains.yesod.hamlet.psi.SharpIdentifier(astNode)
}
if (astNode.elementType === HamletTokenTypes.OPERATOR) {
return org.jetbrains.yesod.hamlet.psi.Operator(astNode)
}
if (astNode.elementType === HamletTokenTypes.COMMENT) {
return org.jetbrains.yesod.hamlet.psi.Comment(astNode)
}
if (astNode.elementType === HamletTokenTypes.ESCAPE) {
return org.jetbrains.yesod.hamlet.psi.Escape(astNode)
}
if (astNode.elementType === HamletTokenTypes.END_INTERPOLATION) {
return org.jetbrains.yesod.hamlet.psi.Interpolation(astNode)
}
if (astNode.elementType === HamletTokenTypes.ATTRIBUTE) {
return Attribute(astNode)
}
if (astNode.elementType === HamletTokenTypes.ATTRIBUTE_VALUE) {
return org.jetbrains.yesod.hamlet.psi.AttributeValue(astNode)
}
return ASTWrapperPsiElement(astNode)
}
override fun createFile(fileViewProvider: FileViewProvider): PsiFile {
return HamletFile(fileViewProvider)
}
override fun spaceExistanceTypeBetweenTokens(astNode: ASTNode, astNode2: ASTNode): ParserDefinition.SpaceRequirements {
return ParserDefinition.SpaceRequirements.MAY
}
companion object {
var HAMLET_FILE: IFileElementType = IFileElementType(HamletLanguage.INSTANCE)
}
}
| apache-2.0 | ddf13a6993ef0243ba1d2e78625efe9b | 34.68932 | 123 | 0.694777 | 4.418269 | false | false | false | false |
youdonghai/intellij-community | java/java-tests/testSrc/com/intellij/codeInspection/Java9ModuleExportsPackageToItselfTest.kt | 1 | 2219 | /*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.codeInspection
import com.intellij.codeInspection.java19modules.Java9ModuleExportsPackageToItselfInspection
import com.intellij.testFramework.fixtures.LightJava9ModulesCodeInsightFixtureTestCase
import com.intellij.testFramework.fixtures.MultiModuleJava9ProjectDescriptor
/**
* @author Pavel.Dolgov
*/
class Java9ModuleExportsPackageToItselfTest : LightJava9ModulesCodeInsightFixtureTestCase() {
override fun setUp() {
super.setUp()
myFixture.enableInspections(Java9ModuleExportsPackageToItselfInspection())
addFile("module-info.java", "module M2 { }", MultiModuleJava9ProjectDescriptor.ModuleDescriptor.M2)
addFile("module-info.java", "module M4 { }", MultiModuleJava9ProjectDescriptor.ModuleDescriptor.M4)
addFile("pkg/main/C.java", "package pkg.main; public class C {}")
}
fun testNoSelfModule() {
highlight("module M { exports pkg.main to M2, M4; }")
}
fun testOnlySelfModule() {
val message = InspectionsBundle.message("inspection.module.exports.package.to.itself.only.message")
highlight("module M { exports pkg.main to <warning descr=\"$message\">M</warning>; }")
}
fun testSelfModuleInList() {
val message = InspectionsBundle.message("inspection.module.exports.package.to.itself.message")
highlight("module M { exports pkg.main to M2, <warning descr=\"$message\">M</warning>, M4; }")
}
private fun highlight(text: String) = highlight("module-info.java", text)
private fun highlight(path: String, text: String) {
myFixture.configureFromExistingVirtualFile(addFile(path, text))
myFixture.checkHighlighting()
}
} | apache-2.0 | fa50e37d866803248f5a5768e5e92292 | 39.363636 | 103 | 0.756196 | 4.283784 | false | true | false | false |
DmytroTroynikov/aemtools | aem-intellij-core/src/main/kotlin/com/aemtools/index/AemComponentDeclarationIndex.kt | 1 | 1460 | package com.aemtools.index
import com.aemtools.index.dataexternalizer.AemComponentDeclarationExternalizer
import com.aemtools.index.indexer.AemComponentDeclarationIndexer
import com.aemtools.index.model.AemComponentDefinition
import com.intellij.ide.highlighter.XmlFileType
import com.intellij.util.indexing.DataIndexer
import com.intellij.util.indexing.FileBasedIndex
import com.intellij.util.indexing.FileContent
import com.intellij.util.indexing.ID
import com.intellij.util.io.DataExternalizer
import com.intellij.xml.index.XmlIndex
/**
* Indexes content of `.content.xml` files with *jcr:primaryType="cq:Component"*.
*
* @author Dmytro Troynikov
*/
class AemComponentDeclarationIndex : XmlIndex<AemComponentDefinition>() {
companion object {
val AEM_COMPONENT_DECLARATION_INDEX_ID: ID<String, AemComponentDefinition>
= ID.create<String, AemComponentDefinition>("AemComponentDeclarationIndex")
}
override fun getValueExternalizer(): DataExternalizer<AemComponentDefinition>
= AemComponentDeclarationExternalizer
override fun getName(): ID<String, AemComponentDefinition>
= AEM_COMPONENT_DECLARATION_INDEX_ID
override fun getIndexer(): DataIndexer<String, AemComponentDefinition, FileContent>
= AemComponentDeclarationIndexer
override fun getInputFilter(): FileBasedIndex.InputFilter
= FileBasedIndex.InputFilter {
it.fileType == XmlFileType.INSTANCE
&& it.name == ".content.xml"
}
}
| gpl-3.0 | e711a1008a8770b36e347c36afe311b2 | 34.609756 | 85 | 0.795205 | 4.534161 | false | false | false | false |
leafclick/intellij-community | platform/workspaceModel-ide/src/com/intellij/workspace/jps/jpsFormatEntitiesSerialization.kt | 1 | 21998 | package com.intellij.workspace.jps
import com.intellij.application.options.ReplacePathToMacroMap
import com.intellij.openapi.application.PathMacros
import com.intellij.openapi.components.ExpandMacroToPathMap
import com.intellij.openapi.components.PathMacroManager
import com.intellij.openapi.util.io.FileUtil
import com.intellij.util.Function
import com.intellij.util.PathUtil
import com.intellij.util.containers.BidirectionalMap
import com.intellij.util.containers.MultiMap
import com.intellij.util.text.UniqueNameGenerator
import com.intellij.workspace.api.*
import com.intellij.workspace.ide.IdeUiEntitySource
import com.intellij.workspace.ide.JpsFileEntitySource
import com.intellij.workspace.ide.JpsProjectStoragePlace
import gnu.trove.TIntObjectHashMap
import org.jdom.Element
import org.jetbrains.annotations.TestOnly
import org.jetbrains.jps.model.serialization.PathMacroUtil
import org.jetbrains.jps.util.JpsPathUtil
import java.io.File
import java.util.concurrent.ConcurrentHashMap
/**
* Provides read access to components in project or module configuration file. The implementation may cache the file contents to avoid
* reading the same file multiple times.
*/
interface JpsFileContentReader {
fun loadComponent(fileUrl: String, componentName: String): Element?
}
interface JpsFileContentWriter {
fun saveComponent(fileUrl: String, componentName: String, componentTag: Element?)
}
/**
* Represents a serializer for a configuration XML file in JPS format.
*/
interface JpsFileEntitiesSerializer<E : TypedEntity> {
val entitySource: JpsFileEntitySource
val fileUrl: VirtualFileUrl
val mainEntityClass: Class<E>
fun loadEntities(builder: TypedEntityStorageBuilder, reader: JpsFileContentReader)
fun saveEntities(mainEntities: Collection<E>, entities: Map<Class<out TypedEntity>, List<TypedEntity>>, writer: JpsFileContentWriter): List<TypedEntity>
}
/**
* Represents a serializer which is responsible for serializing all entities of the given type (e.g. libraries in *.ipr file).
*/
interface JpsFileEntityTypeSerializer<E : TypedEntity> : JpsFileEntitiesSerializer<E> {
val entityFilter: (E) -> Boolean
get() = { true }
val additionalEntityTypes: List<Class<out TypedEntity>>
get() = emptyList()
}
/**
* Represents a directory containing configuration files (e.g. .idea/libraries).
*/
interface JpsDirectoryEntitiesSerializerFactory<E : TypedEntity> {
val directoryUrl: String
val entityClass: Class<E>
val entityFilter: (E) -> Boolean
get() = { true }
val componentName: String
/** Returns a serializer for a file located in [directoryUrl] directory*/
fun createSerializer(fileUrl: String, entitySource: JpsFileEntitySource.FileInDirectory): JpsFileEntitiesSerializer<E>
fun getDefaultFileName(entity: E): String
}
/**
* Represents a configuration file which contains references to other configuration files (e.g. .idea/modules.xml which contains references
* to *.iml files).
*/
interface JpsFileSerializerFactory<E : TypedEntity> {
val fileUrl: String
val entityClass: Class<E>
/** Returns serializers for individual configuration files referenced from [fileUrl] */
fun loadFileList(reader: JpsFileContentReader): List<VirtualFileUrl>
fun createSerializer(source: JpsFileEntitySource, fileUrl: VirtualFileUrl): JpsFileEntitiesSerializer<E>
fun saveEntitiesList(entities: Sequence<E>, writer: JpsFileContentWriter)
fun getFileName(entity: E): String
fun deleteObsoleteFile(fileUrl: String, writer: JpsFileContentWriter)
}
/**
* Represents set of serializers corresponding to a project.
*/
class JpsEntitiesSerializerFactories(val entityTypeSerializers: List<JpsFileEntityTypeSerializer<*>>,
val directorySerializersFactories: List<JpsDirectoryEntitiesSerializerFactory<*>>,
val fileSerializerFactories: List<JpsFileSerializerFactory<*>>,
val storagePlace: JpsProjectStoragePlace) {
fun createSerializers(reader: JpsFileContentReader): JpsEntitiesSerializationData {
return JpsEntitiesSerializationData(directorySerializersFactories, fileSerializerFactories, reader, entityTypeSerializers, storagePlace)
}
}
data class JpsConfigurationFilesChange(val addedFileUrls: Collection<String>, val removedFileUrls: Collection<String>, val changedFileUrls: Collection<String>)
class JpsEntitiesSerializationData(directorySerializersFactories: List<JpsDirectoryEntitiesSerializerFactory<*>>,
fileSerializerFactories: List<JpsFileSerializerFactory<*>>,
reader: JpsFileContentReader,
private val entityTypeSerializers: List<JpsFileEntityTypeSerializer<*>>,
private val storagePlace: JpsProjectStoragePlace) {
internal val serializerToFileFactory = BidirectionalMap<JpsFileEntitiesSerializer<*>, JpsFileSerializerFactory<*>>()
internal val serializerToDirectoryFactory = BidirectionalMap<JpsFileEntitiesSerializer<*>, JpsDirectoryEntitiesSerializerFactory<*>>()
internal val fileSerializersByUrl = MultiMap.create<String, JpsFileEntitiesSerializer<*>>()
internal val fileIdToFileName = TIntObjectHashMap<String>()
init {
for (factory in directorySerializersFactories) {
createDirectorySerializers(factory).associateWithTo(serializerToDirectoryFactory) { factory }
}
for (factory in fileSerializerFactories) {
val fileList = factory.loadFileList(reader)
fileList
.map { factory.createSerializer(createFileInDirectorySource(it.parent!!, it.file!!.name), it) }
.associateWithTo(serializerToFileFactory) { factory }
}
val allFileSerializers = entityTypeSerializers + serializerToDirectoryFactory.keys + serializerToFileFactory.keys
allFileSerializers.forEach {
fileSerializersByUrl.putValue(it.fileUrl.url, it)
}
}
internal val directorySerializerFactoriesByUrl = directorySerializersFactories.associateBy { it.directoryUrl }
internal val fileSerializerFactoriesByUrl = fileSerializerFactories.associateBy { it.fileUrl }
internal fun createFileInDirectorySource(directoryUrl: VirtualFileUrl, fileName: String): JpsFileEntitySource.FileInDirectory {
val source = JpsFileEntitySource.FileInDirectory(directoryUrl, storagePlace)
fileIdToFileName.put(source.fileNameId, fileName)
return source
}
private fun createDirectorySerializers(factory: JpsDirectoryEntitiesSerializerFactory<*>): List<JpsFileEntitiesSerializer<*>> {
val files = JpsPathUtil.urlToFile(factory.directoryUrl).listFiles { file: File -> file.extension == "xml" && file.isFile }
?: return emptyList()
return files.map {
factory.createSerializer("${factory.directoryUrl}/${it.name}",
createFileInDirectorySource(VirtualFileUrlManager.fromUrl(factory.directoryUrl), it.name))
}
}
fun reloadFromChangedFiles(change: JpsConfigurationFilesChange,
reader: JpsFileContentReader): Pair<Set<EntitySource>, TypedEntityStorageBuilder> {
val obsoleteSerializers = ArrayList<JpsFileEntitiesSerializer<*>>()
val newFileSerializers = ArrayList<JpsFileEntitiesSerializer<*>>()
for (addedFileUrl in change.addedFileUrls) {
val factory = directorySerializerFactoriesByUrl[PathUtil.getParentPath(addedFileUrl)]
val newFileSerializer = factory?.createSerializer(addedFileUrl, createFileInDirectorySource(VirtualFileUrlManager.fromUrl(factory.directoryUrl), PathUtil.getFileName(addedFileUrl)))
if (newFileSerializer != null) {
newFileSerializers.add(newFileSerializer)
serializerToDirectoryFactory[newFileSerializer] = factory
}
}
for (changedUrl in change.changedFileUrls) {
val serializerFactory = fileSerializerFactoriesByUrl[changedUrl]
if (serializerFactory != null) {
val newFileUrls = serializerFactory.loadFileList(reader)
val oldSerializers: List<JpsFileEntitiesSerializer<*>> = serializerToFileFactory.getKeysByValue(serializerFactory) ?: emptyList()
val oldFileUrls = oldSerializers.mapTo(HashSet()) { it.fileUrl }
val newFileUrlsSet = newFileUrls.toSet()
val obsoleteSerializersForFactory = oldSerializers.filter { it.fileUrl !in newFileUrlsSet }
obsoleteSerializersForFactory.forEach { serializerToFileFactory.remove(it, serializerFactory) }
val newFileSerializersForFactory = newFileUrls.filter { it !in oldFileUrls}.map {
serializerFactory.createSerializer(createFileInDirectorySource(it.parent!!, it.file!!.name), it)
}
newFileSerializersForFactory.associateWithTo(serializerToFileFactory) { serializerFactory }
obsoleteSerializers.addAll(obsoleteSerializersForFactory)
newFileSerializers.addAll(newFileSerializersForFactory)
}
}
for (newSerializer in newFileSerializers) {
fileSerializersByUrl.putValue(newSerializer.fileUrl.url, newSerializer)
}
for (obsoleteSerializer in obsoleteSerializers) {
fileSerializersByUrl.remove(obsoleteSerializer.fileUrl.url, obsoleteSerializer)
}
val affectedFileLoaders = (change.changedFileUrls + change.addedFileUrls).toCollection(HashSet()).flatMap { fileSerializersByUrl[it] }
val changedSources = affectedFileLoaders.mapTo(HashSet()) { it.entitySource }
for (fileUrl in change.removedFileUrls) {
val obsolete = fileSerializersByUrl.remove(fileUrl)
if (obsolete != null) {
obsoleteSerializers.addAll(obsolete)
obsolete.forEach {
serializerToDirectoryFactory.remove(it)
}
}
}
obsoleteSerializers.mapTo(changedSources) { it.entitySource }
obsoleteSerializers.asSequence().map { it.entitySource }.filterIsInstance(JpsFileEntitySource.FileInDirectory::class.java).forEach {
fileIdToFileName.remove(it.fileNameId)
}
val builder = TypedEntityStorageBuilder.create()
affectedFileLoaders.forEach {
it.loadEntities(builder, reader)
}
return Pair(changedSources, builder)
}
fun loadAll(reader: JpsFileContentReader, builder: TypedEntityStorageBuilder) {
fileSerializersByUrl.values().forEach {
it.loadEntities(builder, reader)
}
}
@TestOnly
fun saveAllEntities(storage: TypedEntityStorage, writer: JpsFileContentWriter) {
fileSerializerFactoriesByUrl.values.forEach {
saveEntitiesList(it, storage, writer)
}
val allSources = fileSerializersByUrl.values().mapTo(HashSet<EntitySource>()) { it.entitySource }
allSources += IdeUiEntitySource
saveEntities(storage, allSources, writer)
}
internal fun getActualFileUrl(source: JpsFileEntitySource) = when (source) {
is JpsFileEntitySource.ExactFile -> source.file.url
is JpsFileEntitySource.FileInDirectory -> {
val fileName = fileIdToFileName[source.fileNameId]
if (fileName != null) source.directory.url + "/" + fileName else null
}
}
fun saveEntities(storage: TypedEntityStorage, affectedSources: Set<EntitySource>, writer: JpsFileContentWriter): List<Pair<TypedEntity, JpsFileEntitySource>> {
val affectedFileFactories = HashSet<JpsFileSerializerFactory<*>>()
fun processObsoleteSource(fileUrl: String, deleteObsoleteFilesFromFileFactories: Boolean) {
val obsoleteSerializers = fileSerializersByUrl.remove(fileUrl)
obsoleteSerializers?.forEach {
val fileFactory = serializerToFileFactory.remove(it)
if (fileFactory != null) {
if (deleteObsoleteFilesFromFileFactories) {
fileFactory.deleteObsoleteFile(fileUrl, writer)
}
affectedFileFactories.add(fileFactory)
}
}
obsoleteSerializers?.forEach {
val directoryFactory = serializerToDirectoryFactory.remove(it)
if (directoryFactory != null) {
writer.saveComponent(fileUrl, directoryFactory.componentName, null)
}
}
}
val entitiesToSave = storage.entitiesBySource { it in affectedSources }
val obsoleteSources = affectedSources - entitiesToSave.keys
for (source in obsoleteSources) {
if (source is JpsFileEntitySource) {
val fileUrl = getActualFileUrl(source)
if (fileUrl != null) {
processObsoleteSource(fileUrl, false)
if (source is JpsFileEntitySource.FileInDirectory) {
fileIdToFileName.remove(source.fileNameId)
}
}
}
}
val serializersToRun = ArrayList<Pair<JpsFileEntitiesSerializer<*>, Map<Class<out TypedEntity>, List<TypedEntity>>>>()
fun processNewlyAddedDirectoryEntities(entitiesMap: Map<Class<out TypedEntity>, List<TypedEntity>>) {
directorySerializerFactoriesByUrl.values.forEach { factory ->
val added = entitiesMap[factory.entityClass]
if (added != null) {
val newSerializers = createSerializersForDirectoryEntities(factory, added)
newSerializers.forEach {
serializerToDirectoryFactory[it.first] = factory
fileSerializersByUrl.putValue(it.first.fileUrl.url, it.first)
}
serializersToRun.addAll(newSerializers)
}
}
}
entitiesToSave.forEach { (source, entities) ->
if (source is JpsFileEntitySource) {
if (source is JpsFileEntitySource.FileInDirectory) {
val fileNameByEntity = calculateFileNameForEntity(source, entities)
val oldFileName = fileIdToFileName[source.fileNameId]
if (oldFileName != fileNameByEntity) {
fileIdToFileName.put(source.fileNameId, fileNameByEntity)
if (oldFileName != null) {
processObsoleteSource("${source.directory.url}/$oldFileName", true)
}
processNewlyAddedDirectoryEntities(entities)
}
}
val url = getActualFileUrl(source)
if (url != null && url !in fileSerializersByUrl.keySet()) {
fileSerializerFactoriesByUrl.values.forEach { factory ->
if (factory.entityClass in entities) {
val newSerializer = factory.createSerializer(source, VirtualFileUrlManager.fromUrl(url))
fileSerializersByUrl.putValue(url, newSerializer)
serializerToFileFactory[newSerializer] = factory
affectedFileFactories.add(factory)
}
}
}
}
}
entitiesToSave.forEach { (source, entities) ->
if (source is JpsFileEntitySource) {
val serializers = fileSerializersByUrl[getActualFileUrl(source)]
serializers.filter { it !is JpsFileEntityTypeSerializer }.mapTo(serializersToRun) {
Pair(it, entities)
}
}
}
val newEntities = entitiesToSave[IdeUiEntitySource] ?: emptyMap()
fileSerializerFactoriesByUrl.values.forEach {
if (it in affectedFileFactories || it.entityClass in newEntities) {
saveEntitiesList(it, storage, writer)
}
}
processNewlyAddedDirectoryEntities(newEntities)
for (serializer in entityTypeSerializers) {
if (serializer.mainEntityClass in newEntities ||
entitiesToSave.any { serializer.mainEntityClass in it.value }) {
val entitiesMap = mutableMapOf(serializer.mainEntityClass to getFilteredEntitiesForSerializer(serializer, storage))
serializer.additionalEntityTypes.associateWithTo(entitiesMap) {
storage.entities(it.kotlin.java).toList()
}
serializersToRun.add(Pair(serializer, entitiesMap))
}
}
return serializersToRun.flatMap {
saveEntitiesBySerializer(it.first, it.second, writer)
}
}
private fun calculateFileNameForEntity(source: JpsFileEntitySource.FileInDirectory,
entities: Map<Class<out TypedEntity>, List<TypedEntity>>): String? {
val directoryFactory = directorySerializerFactoriesByUrl[source.directory.url]
if (directoryFactory != null) {
return getDefaultFileNameForEntity(directoryFactory, entities)
}
val fileFactory = fileSerializerFactoriesByUrl.values.find { it.entityClass in entities }
if (fileFactory != null) {
return getFileNameForEntity(fileFactory, entities)
}
return null
}
private fun <E : TypedEntity> getDefaultFileNameForEntity(directoryFactory: JpsDirectoryEntitiesSerializerFactory<E>,
entities: Map<Class<out TypedEntity>, List<TypedEntity>>): String? {
@Suppress("UNCHECKED_CAST") val entity = entities[directoryFactory.entityClass]?.singleOrNull() as? E ?: return null
return FileUtil.sanitizeFileName(directoryFactory.getDefaultFileName(entity)) + ".xml"
}
private fun <E : TypedEntity> getFileNameForEntity(fileFactory: JpsFileSerializerFactory<E>,
entities: Map<Class<out TypedEntity>, List<TypedEntity>>): String? {
@Suppress("UNCHECKED_CAST") val entity = entities[fileFactory.entityClass]?.singleOrNull() as? E ?: return null
return fileFactory.getFileName(entity)
}
private fun <E : TypedEntity> getFilteredEntitiesForSerializer(serializer: JpsFileEntityTypeSerializer<E>, storage: TypedEntityStorage): List<E> {
return storage.entities(serializer.mainEntityClass.kotlin.java).filter(serializer.entityFilter).toList()
}
private fun <E : TypedEntity> saveEntitiesBySerializer(serializer: JpsFileEntitiesSerializer<E>,
entities: Map<Class<out TypedEntity>, List<TypedEntity>>,
writer: JpsFileContentWriter): List<Pair<TypedEntity, JpsFileEntitySource>> {
@Suppress("UNCHECKED_CAST")
val savedEntities = serializer.saveEntities(entities[serializer.mainEntityClass] as Collection<E>, entities, writer)
return savedEntities.filter { it.entitySource != serializer.entitySource }.map { Pair(it, serializer.entitySource) }
}
private fun <E : TypedEntity> createSerializersForDirectoryEntities(factory: JpsDirectoryEntitiesSerializerFactory<E>, entities: List<TypedEntity>)
: List<Pair<JpsFileEntitiesSerializer<*>, Map<Class<out TypedEntity>, List<TypedEntity>>>> {
val nameGenerator = UniqueNameGenerator(serializerToDirectoryFactory.getKeysByValue(factory) ?: emptyList(), Function {
PathUtil.getFileName(it.fileUrl.url)
})
return entities
.filter { @Suppress("UNCHECKED_CAST") factory.entityFilter(it as E) }
.map {
@Suppress("UNCHECKED_CAST")
val fileName = nameGenerator.generateUniqueName(FileUtil.sanitizeFileName(factory.getDefaultFileName(it as E)), "", ".xml")
val entityMap = mapOf<Class<out TypedEntity>, List<TypedEntity>>(factory.entityClass to listOf(it))
val currentSource = it.entitySource as? JpsFileEntitySource.FileInDirectory
val source =
if (currentSource != null && fileIdToFileName[currentSource.fileNameId] == fileName) currentSource
else createFileInDirectorySource(VirtualFileUrlManager.fromUrl(factory.directoryUrl), fileName)
Pair(factory.createSerializer("${factory.directoryUrl}/$fileName", source), entityMap)
}
}
private fun <E : TypedEntity> saveEntitiesList(it: JpsFileSerializerFactory<E>, storage: TypedEntityStorage, writer: JpsFileContentWriter) {
it.saveEntitiesList(storage.entities(it.entityClass.kotlin.java), writer)
}
}
internal class CachingJpsFileContentReader(projectBaseDirUrl: String) : JpsFileContentReader {
private val projectPathMacroManager = LegacyBridgeProjectPathMacroManager(JpsPathUtil.urlToPath(projectBaseDirUrl))
private val fileContentCache = ConcurrentHashMap<String, Map<String, Element>>()
override fun loadComponent(fileUrl: String, componentName: String): Element? {
val content = fileContentCache.computeIfAbsent(fileUrl) {
loadComponents(it)
}
return content[componentName]
}
private fun loadComponents(fileUrl: String): Map<String, Element> {
val macroManager = if (FileUtil.extensionEquals(fileUrl, "iml")) {
LegacyBridgeModulePathMacroManager(PathMacros.getInstance(), JpsPathUtil.urlToPath(fileUrl))
}
else {
projectPathMacroManager
}
val file = JpsPathUtil.urlToFile(fileUrl)
if (!file.isFile) return emptyMap()
return loadStorageFile(file, macroManager)
}
internal class LegacyBridgeModulePathMacroManager(pathMacros: PathMacros, private val moduleFilePath: String) : PathMacroManager(pathMacros) {
override fun getExpandMacroMap(): ExpandMacroToPathMap {
val result = super.getExpandMacroMap()
addFileHierarchyReplacements(
result, PathMacroUtil.MODULE_DIR_MACRO_NAME,
PathMacroUtil.getModuleDir(moduleFilePath))
return result
}
public override fun computeReplacePathMap(): ReplacePathToMacroMap {
val result = super.computeReplacePathMap()
val modulePath = PathMacroUtil.getModuleDir(moduleFilePath)
addFileHierarchyReplacements(
result, PathMacroUtil.MODULE_DIR_MACRO_NAME, modulePath,
PathMacroUtil.getUserHomePath())
return result
}
}
internal class LegacyBridgeProjectPathMacroManager(private val projectDirPath: String) : PathMacroManager(PathMacros.getInstance()) {
override fun getExpandMacroMap(): ExpandMacroToPathMap {
val result = super.getExpandMacroMap()
addFileHierarchyReplacements(result, PathMacroUtil.PROJECT_DIR_MACRO_NAME, projectDirPath)
return result
}
override fun computeReplacePathMap(): ReplacePathToMacroMap {
val result = super.computeReplacePathMap()
addFileHierarchyReplacements(result, PathMacroUtil.PROJECT_DIR_MACRO_NAME, projectDirPath, null)
return result
}
}
}
// TODO Add more diagnostics: file path, line etc
internal fun Element.getAttributeValueStrict(name: String): String =
getAttributeValue(name) ?: error("Expected attribute $name under ${this.name} element")
| apache-2.0 | d868e221a86d8f84121295a07a2b55cf | 45.804255 | 187 | 0.731112 | 5.364058 | false | false | false | false |
leafclick/intellij-community | plugins/git4idea/src/git4idea/conflicts/MergeConflictResolveUtil.kt | 1 | 5829 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package git4idea.conflicts
import com.intellij.diff.DiffDialogHints
import com.intellij.diff.DiffManagerEx
import com.intellij.diff.DiffRequestFactory
import com.intellij.diff.chains.DiffRequestProducerException
import com.intellij.diff.merge.*
import com.intellij.diff.util.DiffUserDataKeysEx
import com.intellij.openapi.Disposable
import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.openapi.fileEditor.FileEditor
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.runBackgroundableTask
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.WindowWrapper
import com.intellij.openapi.util.Key
import com.intellij.openapi.util.UserDataHolder
import com.intellij.openapi.vcs.impl.BackgroundableActionLock
import com.intellij.openapi.vcs.merge.MergeDialogCustomizer
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.ui.EditorNotificationPanel
import com.intellij.ui.EditorNotifications
import com.intellij.ui.LightColors
import com.intellij.util.Consumer
import com.intellij.util.ui.UIUtil
import org.jetbrains.annotations.CalledInAwt
import javax.swing.JFrame
object MergeConflictResolveUtil {
private val ACTIVE_MERGE_WINDOW = Key.create<WindowWrapper>("ResolveConflictsWindow")
@CalledInAwt
fun showMergeWindow(project: Project,
file: VirtualFile?,
lock: BackgroundableActionLock,
resolverComputer: () -> GitMergeHandler.Resolver) {
if (focusActiveMergeWindow(file)) return
if (lock.isLocked) return
lock.lock()
val title = if (file != null) MergeDialogCustomizer().getMergeWindowTitle(file) else "Merge"
val windowHandler = Consumer<WindowWrapper> { wrapper ->
UIUtil.runWhenWindowClosed(wrapper.window) { lock.unlock() }
putActiveWindowKey(project, wrapper, file)
}
val hints = DiffDialogHints(WindowWrapper.Mode.FRAME, null, windowHandler)
val producer = MyProducer(project, title, resolverComputer)
DiffManagerEx.getInstance().showMergeBuiltin(project, producer, hints)
}
private class MyProducer(val project: Project,
val title: String,
val resolverComputer: () -> GitMergeHandler.Resolver) : MergeRequestProducer {
override fun getName(): String = title
override fun process(context: UserDataHolder, indicator: ProgressIndicator): MergeRequest {
try {
val resolver = resolverComputer()
val mergeData = resolver.mergeData
val byteContents = listOf(mergeData.CURRENT, mergeData.ORIGINAL, mergeData.LAST)
val request = DiffRequestFactory.getInstance().createMergeRequest(project, resolver.virtualFile, byteContents,
resolver.windowTitle, resolver.contentTitles)
resolver.titleCustomizerList.run {
request.putUserData(DiffUserDataKeysEx.EDITORS_TITLE_CUSTOMIZER,
listOf(leftTitleCustomizer, centerTitleCustomizer, rightTitleCustomizer))
}
MergeUtil.putRevisionInfos(request, mergeData)
MergeCallback.register(request, MyMergeCallback(resolver))
return request
}
catch (e: Throwable) {
throw DiffRequestProducerException(e)
}
}
}
private fun putActiveWindowKey(project: Project, wrapper: WindowWrapper, file: VirtualFile?) {
if (file == null) return
val window = wrapper.window
if (window !is JFrame) return
file.putUserData(ACTIVE_MERGE_WINDOW, wrapper)
EditorNotifications.getInstance(project).updateNotifications(file)
UIUtil.runWhenWindowClosed(window) {
file.putUserData(ACTIVE_MERGE_WINDOW, null)
EditorNotifications.getInstance(project).updateNotifications(file)
}
}
private fun focusActiveMergeWindow(file: VirtualFile?): Boolean {
val wrapper = file?.getUserData(ACTIVE_MERGE_WINDOW) ?: return false
UIUtil.toFront(wrapper.window)
return true
}
private class MyMergeCallback(private val resolver: GitMergeHandler.Resolver) : MergeCallback() {
override fun applyResult(result: MergeResult) {
val project = resolver.project
val file = resolver.virtualFile
val document = FileDocumentManager.getInstance().getCachedDocument(file)
if (document != null) FileDocumentManager.getInstance().saveDocument(document)
MergeUtil.reportProjectFileChangeIfNeeded(project, file)
if (result != MergeResult.CANCEL) {
runBackgroundableTask("Finishing Conflict Resolve", project, false) {
resolver.onConflictResolved(result)
}
}
}
override fun checkIsValid(): Boolean {
return resolver.checkIsValid()
}
override fun addListener(listener: Listener, disposable: Disposable) {
resolver.addListener(listener, disposable)
}
}
class NotificationProvider : EditorNotifications.Provider<EditorNotificationPanel>() {
private val KEY = Key.create<EditorNotificationPanel>("MergeConflictResolveUtil.NotificationProvider")
override fun getKey(): Key<EditorNotificationPanel> = KEY
override fun createNotificationPanel(file: VirtualFile, fileEditor: FileEditor, project: Project): EditorNotificationPanel? {
val wrapper = file.getUserData(ACTIVE_MERGE_WINDOW) ?: return null
val panel = EditorNotificationPanel(LightColors.SLIGHTLY_GREEN)
panel.setText("Merge conflicts resolve in progress.")
panel.createActionLabel("Focus Window") { UIUtil.toFront(wrapper.window) }
panel.createActionLabel("Cancel Resolve") { wrapper.close() }
return panel
}
}
} | apache-2.0 | 05c4e85162ef4d9b09b676219de967ff | 39.206897 | 140 | 0.73323 | 4.939831 | false | false | false | false |
leafclick/intellij-community | plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/model/completion/MavenGroupIdCompletionContributor.kt | 1 | 2877 | // 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.idea.maven.dom.model.completion
import com.intellij.codeInsight.completion.CompletionParameters
import com.intellij.codeInsight.completion.CompletionResultSet
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.progress.ProgressManager
import org.jetbrains.concurrency.Promise
import org.jetbrains.idea.maven.dom.converters.MavenDependencyCompletionUtil
import org.jetbrains.idea.maven.dom.model.MavenDomShortArtifactCoordinates
import org.jetbrains.idea.maven.dom.model.completion.insert.MavenDependencyInsertionHandler
import org.jetbrains.idea.maven.indices.IndicesBundle
import org.jetbrains.idea.maven.onlinecompletion.model.MavenRepositoryArtifactInfo
import org.jetbrains.idea.reposearch.DependencySearchService
import org.jetbrains.idea.reposearch.RepositoryArtifactData
import java.util.concurrent.ConcurrentLinkedDeque
import java.util.function.Consumer
import java.util.function.Predicate
class MavenGroupIdCompletionContributor : MavenCoordinateCompletionContributor("groupId") {
override fun handleEmptyLookup(parameters: CompletionParameters, editor: Editor): String? {
return if (PlaceChecker(parameters).checkPlace().isCorrectPlace()) {
IndicesBundle.message("maven.dependency.completion.group.empty")
}
else null
}
override fun find(service: DependencySearchService,
coordinates: MavenDomShortArtifactCoordinates,
parameters: CompletionParameters,
consumer: Consumer<RepositoryArtifactData>): Promise<Int> {
val searchParameters = createSearchParameters(parameters)
val groupId = trimDummy(coordinates.groupId.stringValue)
val artifactId = trimDummy(coordinates.artifactId.stringValue)
return service.suggestPrefix(groupId, artifactId, searchParameters, withPredicate(consumer,
Predicate { it is MavenRepositoryArtifactInfo && (artifactId.isEmpty() || artifactId == it.artifactId) }))
}
override fun fillResults(result: CompletionResultSet,
coordinates: MavenDomShortArtifactCoordinates,
cld: ConcurrentLinkedDeque<RepositoryArtifactData>,
promise: Promise<Int>) {
val set = HashSet<String>()
while (promise.state == Promise.State.PENDING || !cld.isEmpty()) {
ProgressManager.checkCanceled()
val item = cld.poll()
if (item is MavenRepositoryArtifactInfo && set.add(item.groupId)) {
result
.addElement(
MavenDependencyCompletionUtil.lookupElement(item, item.groupId).withInsertHandler(MavenDependencyInsertionHandler.INSTANCE))
}
}
}
}
| apache-2.0 | ade62b6a3a67e7b97d04505f8121e680 | 51.309091 | 192 | 0.74244 | 5.31793 | false | false | false | false |
Raizlabs/DBFlow | tests/src/androidTest/java/com/dbflow5/models/OneToManyModelTest.kt | 1 | 1446 | package com.dbflow5.models
import com.dbflow5.BaseUnitTest
import com.dbflow5.TestDatabase
import com.dbflow5.config.database
import com.dbflow5.query.select
import com.dbflow5.structure.delete
import com.dbflow5.structure.exists
import com.dbflow5.structure.save
import org.junit.Assert.*
import org.junit.Test
class OneToManyModelTest : BaseUnitTest() {
@Test
fun testOneToManyModel() {
database(TestDatabase::class) { db ->
var testModel2 = TwoColumnModel("Greater", 4)
testModel2.save(db)
testModel2 = TwoColumnModel("Lesser", 1)
testModel2.save(db)
// assert we save
var oneToManyModel = OneToManyModel("HasOrders")
oneToManyModel.save(db)
assertTrue(oneToManyModel.exists(db))
// assert loading works as expected.
oneToManyModel = (select from OneToManyModel::class).requireSingle(db)
assertNotNull(oneToManyModel.getRelatedOrders(db))
assertTrue(!oneToManyModel.getRelatedOrders(db).isEmpty())
// assert the deletion cleared the variable
oneToManyModel.delete(db)
assertFalse(oneToManyModel.exists(db))
assertNull(oneToManyModel.orders)
// assert singular relationship was deleted.
val list = (select from TwoColumnModel::class).queryList(db)
assertTrue(list.size == 1)
}
}
} | mit | ca3bc501e01a9670027049d384e0309b | 31.886364 | 82 | 0.661134 | 4.381818 | false | true | false | false |
grover-ws-1/http4k | http4k-core/src/test/kotlin/org/http4k/lens/BodyTest.kt | 1 | 4995 | package org.http4k.lens
import com.natpryce.hamkrest.assertion.assertThat
import com.natpryce.hamkrest.equalTo
import com.natpryce.hamkrest.should.shouldMatch
import com.natpryce.hamkrest.throws
import org.http4k.core.Body
import org.http4k.core.ContentType.Companion.TEXT_PLAIN
import org.http4k.core.Method
import org.http4k.core.Request
import org.http4k.core.Status.Companion.NOT_ACCEPTABLE
import org.http4k.core.with
import org.http4k.lens.Header.Common.CONTENT_TYPE
import org.junit.Test
class BodyTest {
private val emptyRequest = Request(Method.GET, "")
@Test
fun `can get string body when lax`() {
val laxContentType = Body.string(TEXT_PLAIN).toLens()
assertThat(laxContentType(emptyRequest.body("some value")), equalTo("some value"))
assertThat(laxContentType(emptyRequest.header("Content-type", TEXT_PLAIN.toHeaderValue()).body("some value")), equalTo("some value"))
}
@Test
fun `can get regex body`() {
val regexBody = Body.regex("bob(.+)alice").toLens()
assertThat(regexBody(emptyRequest.body("bobritaalice")), equalTo("rita"))
assertThat({ regexBody(emptyRequest.body("foobaralice")) }, throws(lensFailureWith(Meta(true, "body", ParamMeta.StringParam, "body").invalid())))
}
@Test
fun `non empty string`() {
val nonEmpty = Body.nonEmptyString(TEXT_PLAIN).toLens()
assertThat(nonEmpty(emptyRequest.body("123")), equalTo("123"))
assertThat({ nonEmpty(emptyRequest.body("")) }, throws(lensFailureWith(Meta(true, "body", ParamMeta.StringParam, "body").invalid())))
}
@Test
fun `rejects invalid or missing content type when ContentNegotiation Strict`() {
val strictBody = Body.string(TEXT_PLAIN, contentNegotiation = ContentNegotiation.Strict).toLens()
assertThat({ strictBody(emptyRequest.body("some value")) }, throws(lensFailureWith(CONTENT_TYPE.invalid(), status = NOT_ACCEPTABLE)))
assertThat({ strictBody(emptyRequest.header("content-type", "text/bob;charset=not-utf-8").body("some value")) }, throws(lensFailureWith(CONTENT_TYPE.invalid(), status = NOT_ACCEPTABLE)))
strictBody(emptyRequest.header("content-type", "text/plain; charset = utf-8 ").body("some value")) shouldMatch equalTo("some value")
}
@Test
fun `rejects invalid or missing content type when ContentNegotiation StrictNoDirective`() {
val strictNoDirectiveBody = Body.string(TEXT_PLAIN, contentNegotiation = ContentNegotiation.StrictNoDirective).toLens()
assertThat({ strictNoDirectiveBody(emptyRequest.body("some value")) }, throws(lensFailureWith(CONTENT_TYPE.invalid(), status = NOT_ACCEPTABLE)))
strictNoDirectiveBody(emptyRequest.header("content-type", "text/plain; charset= not-utf-8 ").body("some value")) shouldMatch equalTo("some value")
}
@Test
fun `rejects invalid content type when ContentNegotiation NonStrict`() {
val strictBody = Body.string(TEXT_PLAIN, contentNegotiation = ContentNegotiation.NonStrict).toLens()
assertThat({ strictBody(emptyRequest.header("content-type", "text/bob; charset= not-utf-8 ").body("some value")) }, throws(lensFailureWith(CONTENT_TYPE.invalid(), status = NOT_ACCEPTABLE)))
strictBody(emptyRequest.body("some value")) shouldMatch equalTo("some value")
}
@Test
fun `accept any content type when ContentNegotiation None`() {
val noneBody = Body.string(TEXT_PLAIN, contentNegotiation = ContentNegotiation.None).toLens()
noneBody(emptyRequest.body("some value"))
noneBody(emptyRequest.body("some value").header("content-type", "text/bob"))
}
@Test
fun `sets value on request`() {
val body = Body.string(TEXT_PLAIN).toLens()
val withBody = emptyRequest.with(body of "hello")
assertThat(body(withBody), equalTo("hello"))
assertThat(CONTENT_TYPE(withBody), equalTo(TEXT_PLAIN))
}
@Test
fun `synonym methods roundtrip`() {
val body = Body.string(TEXT_PLAIN).toLens()
body.inject("hello", emptyRequest)
val withBody = emptyRequest.with(body of "hello")
assertThat(body.extract(withBody), equalTo("hello"))
}
@Test
fun `can create a custom Body type and get and set on request`() {
val customBody = Body.string(TEXT_PLAIN).map(::MyCustomBodyType, { it.value }).toLens()
val custom = MyCustomBodyType("hello world!")
val reqWithBody = customBody(custom, emptyRequest)
assertThat(reqWithBody.bodyString(), equalTo("hello world!"))
assertThat(customBody(reqWithBody), equalTo(MyCustomBodyType("hello world!")))
}
@Test
fun `can create a one way custom Body type`() {
val customBody = Body.string(TEXT_PLAIN).map(::MyCustomBodyType).toLens()
assertThat(customBody(emptyRequest
.header("Content-type", TEXT_PLAIN.toHeaderValue())
.body("hello world!")), equalTo(MyCustomBodyType("hello world!")))
}
}
| apache-2.0 | e1f928d361b6efdb36afaed49773eb67 | 45.682243 | 199 | 0.695896 | 4.080882 | false | true | false | false |
cartland/android-UniversalMusicPlayer | common/src/main/java/com/example/android/uamp/media/extensions/MediaMetadataCompatExt.kt | 1 | 11608 | /*
* Copyright 2017 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.uamp.media.extensions
import android.graphics.Bitmap
import android.net.Uri
import android.support.v4.media.MediaBrowserCompat.MediaItem
import android.support.v4.media.MediaDescriptionCompat
import android.support.v4.media.MediaMetadataCompat
import com.google.android.exoplayer2.source.ConcatenatingMediaSource
import com.google.android.exoplayer2.source.ExtractorMediaSource
import com.google.android.exoplayer2.upstream.DataSource
/**
* Useful extensions for [MediaMetadataCompat].
*/
inline val MediaMetadataCompat.id: String
get() = getString(MediaMetadataCompat.METADATA_KEY_MEDIA_ID)
inline val MediaMetadataCompat.title: String?
get() = getString(MediaMetadataCompat.METADATA_KEY_TITLE)
inline val MediaMetadataCompat.artist: String?
get() = getString(MediaMetadataCompat.METADATA_KEY_ARTIST)
inline val MediaMetadataCompat.duration
get() = getLong(MediaMetadataCompat.METADATA_KEY_DURATION)
inline val MediaMetadataCompat.album: String?
get() = getString(MediaMetadataCompat.METADATA_KEY_ALBUM)
inline val MediaMetadataCompat.author: String?
get() = getString(MediaMetadataCompat.METADATA_KEY_AUTHOR)
inline val MediaMetadataCompat.writer: String?
get() = getString(MediaMetadataCompat.METADATA_KEY_WRITER)
inline val MediaMetadataCompat.composer: String?
get() = getString(MediaMetadataCompat.METADATA_KEY_COMPOSER)
inline val MediaMetadataCompat.compilation: String?
get() = getString(MediaMetadataCompat.METADATA_KEY_COMPILATION)
inline val MediaMetadataCompat.date: String?
get() = getString(MediaMetadataCompat.METADATA_KEY_DATE)
inline val MediaMetadataCompat.year: String?
get() = getString(MediaMetadataCompat.METADATA_KEY_YEAR)
inline val MediaMetadataCompat.genre: String?
get() = getString(MediaMetadataCompat.METADATA_KEY_GENRE)
inline val MediaMetadataCompat.trackNumber
get() = getLong(MediaMetadataCompat.METADATA_KEY_TRACK_NUMBER)
inline val MediaMetadataCompat.trackCount
get() = getLong(MediaMetadataCompat.METADATA_KEY_NUM_TRACKS)
inline val MediaMetadataCompat.discNumber
get() = getLong(MediaMetadataCompat.METADATA_KEY_DISC_NUMBER)
inline val MediaMetadataCompat.albumArtist: String?
get() = getString(MediaMetadataCompat.METADATA_KEY_ALBUM_ARTIST)
inline val MediaMetadataCompat.art: Bitmap
get() = getBitmap(MediaMetadataCompat.METADATA_KEY_ART)
inline val MediaMetadataCompat.artUri: Uri
get() = this.getString(MediaMetadataCompat.METADATA_KEY_ART_URI).toUri()
inline val MediaMetadataCompat.albumArt: Bitmap
get() = getBitmap(MediaMetadataCompat.METADATA_KEY_ALBUM_ART)
inline val MediaMetadataCompat.albumArtUri: Uri
get() = this.getString(MediaMetadataCompat.METADATA_KEY_ALBUM_ART_URI).toUri()
inline val MediaMetadataCompat.userRating
get() = getLong(MediaMetadataCompat.METADATA_KEY_USER_RATING)
inline val MediaMetadataCompat.rating
get() = getLong(MediaMetadataCompat.METADATA_KEY_RATING)
inline val MediaMetadataCompat.displayTitle: String?
get() = getString(MediaMetadataCompat.METADATA_KEY_DISPLAY_TITLE)
inline val MediaMetadataCompat.displaySubtitle: String?
get() = getString(MediaMetadataCompat.METADATA_KEY_DISPLAY_SUBTITLE)
inline val MediaMetadataCompat.displayDescription: String?
get() = getString(MediaMetadataCompat.METADATA_KEY_DISPLAY_DESCRIPTION)
inline val MediaMetadataCompat.displayIcon: Bitmap
get() = getBitmap(MediaMetadataCompat.METADATA_KEY_DISPLAY_ICON)
inline val MediaMetadataCompat.displayIconUri: Uri
get() = this.getString(MediaMetadataCompat.METADATA_KEY_DISPLAY_ICON_URI).toUri()
inline val MediaMetadataCompat.mediaUri: Uri
get() = this.getString(MediaMetadataCompat.METADATA_KEY_MEDIA_URI).toUri()
inline val MediaMetadataCompat.downloadStatus
get() = getLong(MediaMetadataCompat.METADATA_KEY_DOWNLOAD_STATUS)
/**
* Custom property for storing whether a [MediaMetadataCompat] item represents an
* item that is [MediaItem.FLAG_BROWSABLE] or [MediaItem.FLAG_PLAYABLE].
*/
@MediaItem.Flags
inline val MediaMetadataCompat.flag
get() = this.getLong(METADATA_KEY_UAMP_FLAGS).toInt()
/**
* Useful extensions for [MediaMetadataCompat.Builder].
*/
// These do not have getters, so create a message for the error.
const val NO_GET = "Property does not have a 'get'"
inline var MediaMetadataCompat.Builder.id: String
@Deprecated(NO_GET, level = DeprecationLevel.ERROR)
get() = throw IllegalAccessException("Cannot get from MediaMetadataCompat.Builder")
set(value) {
putString(MediaMetadataCompat.METADATA_KEY_MEDIA_ID, value)
}
inline var MediaMetadataCompat.Builder.title: String?
@Deprecated(NO_GET, level = DeprecationLevel.ERROR)
get() = throw IllegalAccessException("Cannot get from MediaMetadataCompat.Builder")
set(value) {
putString(MediaMetadataCompat.METADATA_KEY_TITLE, value)
}
inline var MediaMetadataCompat.Builder.artist: String?
@Deprecated(NO_GET, level = DeprecationLevel.ERROR)
get() = throw IllegalAccessException("Cannot get from MediaMetadataCompat.Builder")
set(value) {
putString(MediaMetadataCompat.METADATA_KEY_ARTIST, value)
}
inline var MediaMetadataCompat.Builder.album: String?
@Deprecated(NO_GET, level = DeprecationLevel.ERROR)
get() = throw IllegalAccessException("Cannot get from MediaMetadataCompat.Builder")
set(value) {
putString(MediaMetadataCompat.METADATA_KEY_ALBUM, value)
}
inline var MediaMetadataCompat.Builder.duration: Long
@Deprecated(NO_GET, level = DeprecationLevel.ERROR)
get() = throw IllegalAccessException("Cannot get from MediaMetadataCompat.Builder")
set(value) {
putLong(MediaMetadataCompat.METADATA_KEY_DURATION, value)
}
inline var MediaMetadataCompat.Builder.genre: String?
@Deprecated(NO_GET, level = DeprecationLevel.ERROR)
get() = throw IllegalAccessException("Cannot get from MediaMetadataCompat.Builder")
set(value) {
putString(MediaMetadataCompat.METADATA_KEY_GENRE, value)
}
inline var MediaMetadataCompat.Builder.mediaUri: String?
@Deprecated(NO_GET, level = DeprecationLevel.ERROR)
get() = throw IllegalAccessException("Cannot get from MediaMetadataCompat.Builder")
set(value) {
putString(MediaMetadataCompat.METADATA_KEY_MEDIA_URI, value)
}
inline var MediaMetadataCompat.Builder.albumArtUri: String?
@Deprecated(NO_GET, level = DeprecationLevel.ERROR)
get() = throw IllegalAccessException("Cannot get from MediaMetadataCompat.Builder")
set(value) {
putString(MediaMetadataCompat.METADATA_KEY_ALBUM_ART_URI, value)
}
inline var MediaMetadataCompat.Builder.albumArt: Bitmap?
@Deprecated(NO_GET, level = DeprecationLevel.ERROR)
get() = throw IllegalAccessException("Cannot get from MediaMetadataCompat.Builder")
set(value) {
putBitmap(MediaMetadataCompat.METADATA_KEY_ALBUM_ART, value)
}
inline var MediaMetadataCompat.Builder.trackNumber: Long
@Deprecated(NO_GET, level = DeprecationLevel.ERROR)
get() = throw IllegalAccessException("Cannot get from MediaMetadataCompat.Builder")
set(value) {
putLong(MediaMetadataCompat.METADATA_KEY_TRACK_NUMBER, value)
}
inline var MediaMetadataCompat.Builder.trackCount: Long
@Deprecated(NO_GET, level = DeprecationLevel.ERROR)
get() = throw IllegalAccessException("Cannot get from MediaMetadataCompat.Builder")
set(value) {
putLong(MediaMetadataCompat.METADATA_KEY_NUM_TRACKS, value)
}
inline var MediaMetadataCompat.Builder.displayTitle: String?
@Deprecated(NO_GET, level = DeprecationLevel.ERROR)
get() = throw IllegalAccessException("Cannot get from MediaMetadataCompat.Builder")
set(value) {
putString(MediaMetadataCompat.METADATA_KEY_DISPLAY_TITLE, value)
}
inline var MediaMetadataCompat.Builder.displaySubtitle: String?
@Deprecated(NO_GET, level = DeprecationLevel.ERROR)
get() = throw IllegalAccessException("Cannot get from MediaMetadataCompat.Builder")
set(value) {
putString(MediaMetadataCompat.METADATA_KEY_DISPLAY_SUBTITLE, value)
}
inline var MediaMetadataCompat.Builder.displayDescription: String?
@Deprecated(NO_GET, level = DeprecationLevel.ERROR)
get() = throw IllegalAccessException("Cannot get from MediaMetadataCompat.Builder")
set(value) {
putString(MediaMetadataCompat.METADATA_KEY_DISPLAY_DESCRIPTION, value)
}
inline var MediaMetadataCompat.Builder.displayIconUri: String?
@Deprecated(NO_GET, level = DeprecationLevel.ERROR)
get() = throw IllegalAccessException("Cannot get from MediaMetadataCompat.Builder")
set(value) {
putString(MediaMetadataCompat.METADATA_KEY_DISPLAY_ICON_URI, value)
}
inline var MediaMetadataCompat.Builder.downloadStatus: Long
@Deprecated(NO_GET, level = DeprecationLevel.ERROR)
get() = throw IllegalAccessException("Cannot get from MediaMetadataCompat.Builder")
set(value) {
putLong(MediaMetadataCompat.METADATA_KEY_DOWNLOAD_STATUS, value)
}
/**
* Custom property for storing whether a [MediaMetadataCompat] item represents an
* item that is [MediaItem.FLAG_BROWSABLE] or [MediaItem.FLAG_PLAYABLE].
*/
@MediaItem.Flags
inline var MediaMetadataCompat.Builder.flag: Int
@Deprecated(NO_GET, level = DeprecationLevel.ERROR)
get() = throw IllegalAccessException("Cannot get from MediaMetadataCompat.Builder")
set(value) {
putLong(METADATA_KEY_UAMP_FLAGS, value.toLong())
}
/**
* Custom property for retrieving a [MediaDescriptionCompat] which also includes
* all of the keys from the [MediaMetadataCompat] object in its extras.
*
* These keys are used by the ExoPlayer MediaSession extension when announcing metadata changes.
*/
inline val MediaMetadataCompat.fullDescription
get() =
description.also {
it.extras?.putAll(bundle)
}
/**
* Extension method for building an [ExtractorMediaSource] from a [MediaMetadataCompat] object.
*
* For convenience, place the [MediaDescriptionCompat] into the tag so it can be retrieved later.
*/
fun MediaMetadataCompat.toMediaSource(dataSourceFactory: DataSource.Factory) =
ExtractorMediaSource.Factory(dataSourceFactory)
.setTag(fullDescription)
.createMediaSource(mediaUri)
/**
* Extension method for building a [ConcatenatingMediaSource] given a [List]
* of [MediaMetadataCompat] objects.
*/
fun List<MediaMetadataCompat>.toMediaSource(
dataSourceFactory: DataSource.Factory
): ConcatenatingMediaSource {
val concatenatingMediaSource = ConcatenatingMediaSource()
forEach {
concatenatingMediaSource.addMediaSource(it.toMediaSource(dataSourceFactory))
}
return concatenatingMediaSource
}
/**
* Custom property that holds whether an item is [MediaItem.FLAG_BROWSABLE] or
* [MediaItem.FLAG_PLAYABLE].
*/
const val METADATA_KEY_UAMP_FLAGS = "com.example.android.uamp.media.METADATA_KEY_UAMP_FLAGS" | apache-2.0 | 1431cb364017615fc6733ae69904bb56 | 37.956376 | 97 | 0.765076 | 4.584518 | false | false | false | false |
JuliusKunze/kotlin-native | Interop/Runtime/src/native/kotlin/kotlinx/cinterop/ObjectiveCUtils.kt | 1 | 2087 | /*
* Copyright 2010-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package kotlinx.cinterop
inline fun <R> autoreleasepool(block: () -> R): R {
val pool = objc_autoreleasePoolPush()
return try {
block()
} finally {
objc_autoreleasePoolPop(pool)
}
}
// FIXME: implement a checked cast instead.
fun <T : ObjCObject> ObjCObject.reinterpret() = this.uncheckedCast<T>()
// TODO: null checks
var <T : ObjCObject?> ObjCObjectVar<T>.value: T
get() = interpretObjCPointerOrNull<T>(nativeMemUtils.getNativePtr(this)).uncheckedCast<T>()
set(value) = nativeMemUtils.putNativePtr(this, value.rawPtr)
/**
* Makes Kotlin method in Objective-C class accessible through Objective-C dispatch
* to be used as action sent by control in UIKit or AppKit.
*/
@Target(AnnotationTarget.FUNCTION)
@Retention(AnnotationRetention.SOURCE)
annotation class ObjCAction
/**
* Makes Kotlin property in Objective-C class settable through Objective-C dispatch
* to be used as IB outlet.
*/
@Target(AnnotationTarget.PROPERTY)
@Retention(AnnotationRetention.SOURCE)
annotation class ObjCOutlet
/**
* Makes Kotlin subclass of Objective-C class visible for runtime lookup
* after Kotlin `main` function gets invoked.
*
* Note: runtime lookup can be forced even when the class is referenced statically from
* Objective-C source code by adding `__attribute__((objc_runtime_visible))` to its `@interface`.
*/
@Target(AnnotationTarget.CLASS)
@Retention(AnnotationRetention.SOURCE)
annotation class ExportObjCClass(val name: String = "")
| apache-2.0 | b7103dcec2daa939b7b758ebdf9ed7ca | 33.213115 | 97 | 0.741255 | 3.99044 | false | false | false | false |
JuliusKunze/kotlin-native | backend.native/tests/external/codegen/box/operatorConventions/plusExplicit.kt | 2 | 512 | // WITH_RUNTIME
fun bar1(): String {
val l: List<String> = listOf("O")
val s = l[0].plus("K")
return s
}
fun bar2(): String {
val l: List<String?> = listOf("O")
val s = l[0]?.plus("K")
return s!!
}
fun bar3(): String {
val l: List<String> = listOf("O")
with(l[0]) {
return plus("K")
}
return "fail"
}
fun box(): String {
if (bar1() != "OK") return "fail 1"
if (bar2() != "OK") return "fail 2"
if (bar3() != "OK") return "fail 3"
return "OK"
}
| apache-2.0 | dfe4d3aee55575dd3447a01d3cea02d7 | 16.655172 | 39 | 0.494141 | 2.767568 | false | false | false | false |
exponent/exponent | android/expoview/src/main/java/versioned/host/exp/exponent/modules/api/components/gesturehandler/react/RNGestureHandlerRootView.kt | 2 | 2286 | package versioned.host.exp.exponent.modules.api.components.gesturehandler.react
import android.content.Context
import android.util.Log
import android.view.MotionEvent
import android.view.ViewGroup
import com.facebook.react.bridge.ReactContext
import com.facebook.react.bridge.UiThreadUtil
import com.facebook.react.common.ReactConstants
import com.facebook.react.uimanager.RootView
import com.facebook.react.views.view.ReactViewGroup
class RNGestureHandlerRootView(context: Context?) : ReactViewGroup(context) {
private var _enabled = false
private var rootHelper: RNGestureHandlerRootHelper? = null // TODO: resettable lateinit
override fun onAttachedToWindow() {
super.onAttachedToWindow()
_enabled = !hasGestureHandlerEnabledRootView(this)
if (!_enabled) {
Log.i(
ReactConstants.TAG,
"[GESTURE HANDLER] Gesture handler is already enabled for a parent view"
)
}
if (_enabled && rootHelper == null) {
rootHelper = RNGestureHandlerRootHelper(context as ReactContext, this)
}
}
fun tearDown() {
rootHelper?.tearDown()
}
override fun dispatchTouchEvent(ev: MotionEvent) =
if (_enabled && rootHelper!!.dispatchTouchEvent(ev)) {
true
} else super.dispatchTouchEvent(ev)
override fun requestDisallowInterceptTouchEvent(disallowIntercept: Boolean) {
if (_enabled) {
rootHelper!!.requestDisallowInterceptTouchEvent(disallowIntercept)
}
super.requestDisallowInterceptTouchEvent(disallowIntercept)
}
companion object {
private fun hasGestureHandlerEnabledRootView(viewGroup: ViewGroup): Boolean {
UiThreadUtil.assertOnUiThread()
var parent = viewGroup.parent
while (parent != null) {
if (parent is RNGestureHandlerEnabledRootView || parent is RNGestureHandlerRootView) {
return true
}
// Checks other roots views but it's mainly for ReactModalHostView.DialogRootViewGroup
// since modals are outside RN hierachy and we have to initialize GH's root view for it
// Note that RNGestureHandlerEnabledRootView implements RootView - that's why this check has to be below
if (parent is RootView) {
return false
}
parent = parent.parent
}
return false
}
}
}
| bsd-3-clause | b28fbac15d71bc986f6812f12bb9d92a | 33.636364 | 112 | 0.724847 | 4.832981 | false | false | false | false |
smmribeiro/intellij-community | platform/external-system-impl/testSrc/com/intellij/openapi/externalSystem/service/project/manage/ExternalProjectsDataStorageTest.kt | 2 | 3440 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.externalSystem.service.project.manage
import com.intellij.openapi.externalSystem.model.DataNode
import com.intellij.openapi.externalSystem.model.Key
import com.intellij.openapi.externalSystem.model.ProjectSystemId
import com.intellij.openapi.externalSystem.model.internal.InternalExternalProjectInfo
import com.intellij.openapi.externalSystem.model.project.ProjectData
import com.intellij.openapi.util.io.FileUtil
import com.intellij.testFramework.UsefulTestCase
import com.intellij.testFramework.fixtures.IdeaProjectTestFixture
import com.intellij.testFramework.fixtures.IdeaTestFixtureFactory
import kotlinx.coroutines.runBlocking
import org.assertj.core.api.BDDAssertions.then
import org.junit.Test
import kotlin.reflect.jvm.jvmName
class ExternalProjectsDataStorageTest: UsefulTestCase() {
lateinit var myFixture: IdeaProjectTestFixture
override fun setUp() {
super.setUp()
myFixture = IdeaTestFixtureFactory.getFixtureFactory().createFixtureBuilder(name).fixture
myFixture.setUp()
}
override fun tearDown() {
myFixture.tearDown()
super.tearDown()
}
@Test
fun `test external project data is saved and loaded`() = runBlocking<Unit> {
val dataStorage = ExternalProjectsDataStorage(myFixture.project)
val testSystemId = ProjectSystemId("Test")
val externalName = "external_name"
val externalProjectInfo = createExternalProjectInfo(
testSystemId, externalName, FileUtil.toSystemIndependentName(createTempDir(suffix = externalName).canonicalPath))
dataStorage.update(externalProjectInfo)
dataStorage.save()
dataStorage.load()
val list = dataStorage.list(testSystemId)
then(list).hasSize(1)
then(list.iterator().next().externalProjectStructure?.data?.externalName).isEqualTo(externalName)
}
@Test
fun `test external project data updated before storage initialization is not lost`() = runBlocking<Unit> {
val dataStorage = ExternalProjectsDataStorage(myFixture.project)
val testSystemId = ProjectSystemId("Test")
val externalName1 = "external_name1"
dataStorage.update(createExternalProjectInfo(
testSystemId, externalName1, FileUtil.toSystemIndependentName(createTempDir(suffix = externalName1).canonicalPath)))
dataStorage.load()
val externalName2 = "external_name2"
dataStorage.update(createExternalProjectInfo(
testSystemId, externalName2, FileUtil.toSystemIndependentName(createTempDir(suffix = externalName2).canonicalPath)))
val list = dataStorage.list(testSystemId)
then(list).hasSize(2)
val thenList = then(list)
thenList.anyMatch { it.externalProjectStructure?.data?.externalName == externalName1 }
thenList.anyMatch { it.externalProjectStructure?.data?.externalName == externalName2 }
}
private fun createExternalProjectInfo(testId: ProjectSystemId,
externalName: String,
externalProjectPath: String): InternalExternalProjectInfo {
val projectData = ProjectData(testId, externalName, externalProjectPath, externalProjectPath)
val node = DataNode<ProjectData>(Key(ProjectData::class.jvmName, 0), projectData, null)
return InternalExternalProjectInfo(testId, externalProjectPath, node)
}
} | apache-2.0 | 122dd29ecac3d4efe36887b665826b32 | 43.115385 | 158 | 0.775291 | 5.134328 | false | true | false | false |
android/compose-samples | Jetsnack/app/src/main/java/com/example/jetsnack/ui/theme/Color.kt | 1 | 2770 | /*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.example.jetsnack.ui.theme
import androidx.compose.ui.graphics.Color
val Shadow11 = Color(0xff001787)
val Shadow10 = Color(0xff00119e)
val Shadow9 = Color(0xff0009b3)
val Shadow8 = Color(0xff0200c7)
val Shadow7 = Color(0xff0e00d7)
val Shadow6 = Color(0xff2a13e4)
val Shadow5 = Color(0xff4b30ed)
val Shadow4 = Color(0xff7057f5)
val Shadow3 = Color(0xff9b86fa)
val Shadow2 = Color(0xffc8bbfd)
val Shadow1 = Color(0xffded6fe)
val Shadow0 = Color(0xfff4f2ff)
val Ocean11 = Color(0xff005687)
val Ocean10 = Color(0xff006d9e)
val Ocean9 = Color(0xff0087b3)
val Ocean8 = Color(0xff00a1c7)
val Ocean7 = Color(0xff00b9d7)
val Ocean6 = Color(0xff13d0e4)
val Ocean5 = Color(0xff30e2ed)
val Ocean4 = Color(0xff57eff5)
val Ocean3 = Color(0xff86f7fa)
val Ocean2 = Color(0xffbbfdfd)
val Ocean1 = Color(0xffd6fefe)
val Ocean0 = Color(0xfff2ffff)
val Lavender11 = Color(0xff170085)
val Lavender10 = Color(0xff23009e)
val Lavender9 = Color(0xff3300b3)
val Lavender8 = Color(0xff4400c7)
val Lavender7 = Color(0xff5500d7)
val Lavender6 = Color(0xff6f13e4)
val Lavender5 = Color(0xff8a30ed)
val Lavender4 = Color(0xffa557f5)
val Lavender3 = Color(0xffc186fa)
val Lavender2 = Color(0xffdebbfd)
val Lavender1 = Color(0xffebd6fe)
val Lavender0 = Color(0xfff9f2ff)
val Rose11 = Color(0xff7f0054)
val Rose10 = Color(0xff97005c)
val Rose9 = Color(0xffaf0060)
val Rose8 = Color(0xffc30060)
val Rose7 = Color(0xffd4005d)
val Rose6 = Color(0xffe21365)
val Rose5 = Color(0xffec3074)
val Rose4 = Color(0xfff4568b)
val Rose3 = Color(0xfff985aa)
val Rose2 = Color(0xfffdbbcf)
val Rose1 = Color(0xfffed6e2)
val Rose0 = Color(0xfffff2f6)
val Neutral8 = Color(0xff121212)
val Neutral7 = Color(0xde000000)
val Neutral6 = Color(0x99000000)
val Neutral5 = Color(0x61000000)
val Neutral4 = Color(0x1f000000)
val Neutral3 = Color(0x1fffffff)
val Neutral2 = Color(0x61ffffff)
val Neutral1 = Color(0xbdffffff)
val Neutral0 = Color(0xffffffff)
val FunctionalRed = Color(0xffd00036)
val FunctionalRedDark = Color(0xffea6d7e)
val FunctionalGreen = Color(0xff52c41a)
val FunctionalGrey = Color(0xfff6f6f6)
val FunctionalDarkGrey = Color(0xff2e2e2e)
const val AlphaNearOpaque = 0.95f
| apache-2.0 | b44c5c6174c8a982aef04b86f2b0ff38 | 30.123596 | 75 | 0.775812 | 2.579143 | false | false | false | false |
smmribeiro/intellij-community | plugins/github/src/org/jetbrains/plugins/github/pullrequest/config/GithubPullRequestsProjectUISettings.kt | 3 | 3926 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.github.pullrequest.config
import com.intellij.openapi.components.*
import com.intellij.openapi.project.Project
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.plugins.github.api.GHRepositoryCoordinates
import org.jetbrains.plugins.github.api.GHRepositoryPath
import org.jetbrains.plugins.github.api.GithubServerPath
import org.jetbrains.plugins.github.authentication.accounts.GHAccountSerializer
import org.jetbrains.plugins.github.authentication.accounts.GithubAccount
import org.jetbrains.plugins.github.util.GHGitRepositoryMapping
import org.jetbrains.plugins.github.util.GHProjectRepositoriesManager
@Service
@State(name = "GithubPullRequestsUISettings", storages = [Storage(StoragePathMacros.WORKSPACE_FILE)], reportStatistic = false)
class GithubPullRequestsProjectUISettings(private val project: Project)
: PersistentStateComponentWithModificationTracker<GithubPullRequestsProjectUISettings.SettingsState> {
private var state: SettingsState = SettingsState()
class SettingsState : BaseState() {
var selectedUrlAndAccountId by property<UrlAndAccount?>(null) { it == null }
var recentSearchFilters by list<String>()
var recentNewPullRequestHead by property<RepoCoordinatesHolder?>(null) { it == null }
}
var selectedRepoAndAccount: Pair<GHGitRepositoryMapping, GithubAccount>?
get() {
val (url, accountId) = state.selectedUrlAndAccountId ?: return null
val repo = project.service<GHProjectRepositoriesManager>().knownRepositories.find {
it.gitRemoteUrlCoordinates.url == url
} ?: return null
val account = GHAccountSerializer.deserialize(accountId) ?: return null
return repo to account
}
set(value) {
state.selectedUrlAndAccountId = value?.let { (repo, account) ->
UrlAndAccount(repo.gitRemoteUrlCoordinates.url, GHAccountSerializer.serialize(account))
}
}
fun getRecentSearchFilters(): List<String> = state.recentSearchFilters.toList()
fun addRecentSearchFilter(searchFilter: String) {
val addExisting = state.recentSearchFilters.remove(searchFilter)
state.recentSearchFilters.add(0, searchFilter)
if (state.recentSearchFilters.size > RECENT_SEARCH_FILTERS_LIMIT) {
state.recentSearchFilters.removeLastOrNull()
}
if (!addExisting) {
state.intIncrementModificationCount()
}
}
var recentNewPullRequestHead: GHRepositoryCoordinates?
get() = state.recentNewPullRequestHead?.let { GHRepositoryCoordinates(it.server, GHRepositoryPath(it.owner, it.repository)) }
set(value) {
state.recentNewPullRequestHead = value?.let { RepoCoordinatesHolder(it) }
}
override fun getStateModificationCount() = state.modificationCount
override fun getState() = state
override fun loadState(state: SettingsState) {
this.state = state
}
companion object {
@JvmStatic
fun getInstance(project: Project) = project.service<GithubPullRequestsProjectUISettings>()
private const val RECENT_SEARCH_FILTERS_LIMIT = 10
class UrlAndAccount private constructor() {
var url: String = ""
var accountId: String = ""
constructor(url: String, accountId: String) : this() {
this.url = url
this.accountId = accountId
}
operator fun component1() = url
operator fun component2() = accountId
}
class RepoCoordinatesHolder private constructor() {
var server: GithubServerPath = GithubServerPath.DEFAULT_SERVER
var owner: String = ""
var repository: String = ""
constructor(coordinates: GHRepositoryCoordinates): this() {
server = coordinates.serverPath
owner = coordinates.repositoryPath.owner
repository = coordinates.repositoryPath.repository
}
}
}
} | apache-2.0 | 395949122cafb8dea2f7605a9aff4bd4 | 37.126214 | 140 | 0.748344 | 4.877019 | false | false | false | false |
mdaniel/intellij-community | jvm/jvm-analysis-kotlin-tests/testData/codeInspection/nonExtendableApiUsage/plugin/kotlinExtensions.kt | 13 | 3326 | package plugin.kotlin
import library.JavaClass
import library.JavaInterface
import library.JavaMethodOwner
import library.JavaNestedClassOwner
import library.JavaNonExtendableNestedOwner
import library.KotlinClass
import library.KotlinInterface
import library.KotlinMethodOwner
import library.KotlinNestedClassOwner
import library.KotlinNonExtendableNestedOwner
//Extensions of Java classes
class JavaInheritor : <warning descr="Class 'library.JavaClass' must not be extended">JavaClass</warning>()
class JavaImplementor : <warning descr="Interface 'library.JavaInterface' must not be implemented">JavaInterface</warning>
interface JavaInterfaceInheritor : <warning descr="Interface 'library.JavaInterface' must not be extended">JavaInterface</warning>
class JavaMethodOverrider : JavaMethodOwner() {
override fun <warning descr="Method 'doNotOverride()' must not be overridden">doNotOverride</warning>() = Unit
}
class JavaNestedClassInheritor : library.JavaNestedClassOwner.NestedClass()
class JavaNonExtendableNestedInheritor : JavaNonExtendableNestedOwner.<warning descr="Class 'library.JavaNonExtendableNestedOwner.NonExtendableNested' must not be extended">NonExtendableNested</warning>()
//Extensions of Kotlin classes
class KotlinInheritor : <warning descr="Class 'library.KotlinClass' must not be extended">KotlinClass</warning>()
class KotlinImplementor : <warning descr="Interface 'library.KotlinInterface' must not be implemented">KotlinInterface</warning>
interface KotlinInterfaceInheritor : <warning descr="Interface 'library.KotlinInterface' must not be extended">KotlinInterface</warning>
class KotlinNestedClassInheritor : KotlinNestedClassOwner.NestedClass()
class KotlinNonExtendableNestedInheritor : KotlinNonExtendableNestedOwner.<warning descr="Class 'library.KotlinNonExtendableNestedOwner.NonExtendableNested' must not be extended">NonExtendableNested</warning>()
class KotlinMethodOverrider : KotlinMethodOwner() {
override fun <warning descr="Method 'doNotOverride()' must not be overridden">doNotOverride</warning>() = Unit
}
fun anonymousClasses() {
object : <warning descr="Class 'library.JavaClass' must not be extended">JavaClass</warning>() { }
object : <warning descr="Interface 'library.JavaInterface' must not be implemented">JavaInterface</warning> { }
object : <warning descr="Class 'library.KotlinClass' must not be extended">KotlinClass</warning>() { }
object : <warning descr="Interface 'library.KotlinInterface' must not be implemented">KotlinInterface</warning> { }
object : JavaNonExtendableNestedOwner.<warning descr="Class 'library.JavaNonExtendableNestedOwner.NonExtendableNested' must not be extended">NonExtendableNested</warning>() { }
object : KotlinNonExtendableNestedOwner.<warning descr="Class 'library.KotlinNonExtendableNestedOwner.NonExtendableNested' must not be extended">NonExtendableNested</warning>() { }
//No warnings.
object : JavaNestedClassOwner.NestedClass() { }
object : KotlinNestedClassOwner.NestedClass() { }
object : JavaMethodOwner() {
override fun <warning descr="Method 'doNotOverride()' must not be overridden">doNotOverride</warning>() = Unit
}
object : KotlinMethodOwner() {
override fun <warning descr="Method 'doNotOverride()' must not be overridden">doNotOverride</warning>() = Unit
}
} | apache-2.0 | 19d172168d125cf9e1d521ebe5fac50e | 48.656716 | 210 | 0.804269 | 4.834302 | false | false | false | false |
mdaniel/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/actions/internal/refactoringTesting/MoveRefactoringActionDialog.kt | 1 | 4712 | // 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.actions.internal.refactoringTesting
import com.intellij.ide.util.PropertiesComponent
import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.DialogWrapper
import com.intellij.openapi.ui.TextFieldWithBrowseButton
import com.intellij.openapi.util.Disposer
import com.intellij.refactoring.copy.CopyFilesOrDirectoriesDialog
import com.intellij.ui.components.JBLabelDecorator
import com.intellij.ui.components.JBTextField
import com.intellij.util.ui.FormBuilder
import com.intellij.util.ui.UIUtil
import org.jetbrains.kotlin.idea.base.util.onTextChange
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import javax.swing.InputVerifier
import javax.swing.JComponent
import kotlin.io.path.Path
import kotlin.io.path.exists
import kotlin.io.path.isDirectory
class MoveRefactoringActionDialog(
private val project: Project, private val defaultDirectory: String
) : DialogWrapper(project, true) {
companion object {
val WINDOW_TITLE get() = KotlinBundle.message("move.refactoring.test")
val COUNT_LABEL_TEXT get() = KotlinBundle.message("maximum.count.of.applied.refactoring.before.validity.check")
val LOG_FILE_WILL_BE_PLACED_HERE get() = KotlinBundle.message("test.result.log.file.will.be.placed.here")
const val RECENT_SELECTED_PATH = "org.jetbrains.kotlin.idea.actions.internal.refactoringTesting.RECENT_SELECTED_PATH"
const val RECENT_SELECTED_RUN_COUNT = "org.jetbrains.kotlin.idea.actions.internal.refactoringTesting.RECENT_SELECTED_RUN_COUNT"
}
private val nameLabel = JBLabelDecorator.createJBLabelDecorator().setBold(true)
private val tfTargetDirectory = TextFieldWithBrowseButton()
private val tfRefactoringRunCount = JBTextField()
init {
title = WINDOW_TITLE
init()
initializeData()
}
override fun createActions() = arrayOf(okAction, cancelAction)
override fun getPreferredFocusedComponent() = tfTargetDirectory.childComponent
override fun createCenterPanel(): JComponent? = null
override fun createNorthPanel(): JComponent {
val descriptor = FileChooserDescriptorFactory.createSingleFolderDescriptor()
tfTargetDirectory.addBrowseFolderListener(
WINDOW_TITLE,
LOG_FILE_WILL_BE_PLACED_HERE,
project,
descriptor
)
tfTargetDirectory.setTextFieldPreferredWidth(CopyFilesOrDirectoriesDialog.MAX_PATH_LENGTH)
tfTargetDirectory.textField.onTextChange { validateOKButton() }
Disposer.register(disposable, tfTargetDirectory)
tfRefactoringRunCount.inputVerifier = object : InputVerifier() {
override fun verify(input: JComponent?) = tfRefactoringRunCount.text.toIntOrNull()?.let { it > 0 } ?: false
}
tfRefactoringRunCount.onTextChange { validateOKButton() }
return FormBuilder.createFormBuilder()
.addComponent(nameLabel)
.addLabeledComponent(LOG_FILE_WILL_BE_PLACED_HERE, tfTargetDirectory, UIUtil.LARGE_VGAP)
.addLabeledComponent(COUNT_LABEL_TEXT, tfRefactoringRunCount)
.panel
}
private fun initializeData() {
tfTargetDirectory.childComponent.text = PropertiesComponent.getInstance().getValue(RECENT_SELECTED_PATH, defaultDirectory)
tfRefactoringRunCount.text =
PropertiesComponent.getInstance().getValue(RECENT_SELECTED_RUN_COUNT, "1")
.toIntOrNull()
?.let { if (it < 1) "1" else it.toString() }
validateOKButton()
}
private fun validateOKButton() {
val isCorrectCount = tfRefactoringRunCount.text.toIntOrNull()?.let { it > 0 } ?: false
if (!isCorrectCount) {
isOKActionEnabled = false
return
}
val isCorrectPath = tfTargetDirectory.childComponent.text
?.let { it.isNotEmpty() && Path(it).let { path -> path.exists() && path.isDirectory() } }
?: false
isOKActionEnabled = isCorrectPath
}
val selectedDirectoryName get() = tfTargetDirectory.childComponent.text!!
val selectedCount get() = tfRefactoringRunCount.text.toInt()
override fun doOKAction() {
PropertiesComponent.getInstance().setValue(RECENT_SELECTED_PATH, selectedDirectoryName)
PropertiesComponent.getInstance().setValue(RECENT_SELECTED_RUN_COUNT, tfRefactoringRunCount.text)
close(OK_EXIT_CODE, /* isOk = */ true)
}
} | apache-2.0 | ec932853032828ba367c7733610ea52f | 39.62931 | 158 | 0.725806 | 4.693227 | false | false | false | false |
Briseus/Lurker | app/src/main/java/torille/fi/lurkforreddit/comments/CustomUrlSpan.kt | 1 | 1705 | package torille.fi.lurkforreddit.comments
import android.content.Intent
import android.net.Uri
import android.text.style.URLSpan
import android.view.View
import timber.log.Timber
import torille.fi.lurkforreddit.data.models.view.Post
import torille.fi.lurkforreddit.media.FullscreenActivity
import torille.fi.lurkforreddit.utils.AppLinkActivity
import torille.fi.lurkforreddit.utils.MediaHelper
import java.util.regex.Pattern
/**
* Custom [URLSpan] to modify how to open clicked links in text
*/
internal class CustomUrlSpan(url: String, val color: Int) : URLSpan(url) {
override fun onClick(widget: View) {
val url = url
val uri = Uri.parse(url)
val domain = uri.host
Timber.d("Got url $url")
val intent: Intent
val context = widget.context
when {
MediaHelper.isContentMedia(url, domain) -> {
intent = Intent(context, FullscreenActivity::class.java)
intent.putExtra(FullscreenActivity.EXTRA_POST, Post(url = url))
intent.putExtra(FullscreenActivity.EXTRA_URL, url)
context.startActivity(intent)
}
checkForReddit(url) -> {
Timber.d("Going to checkout subreddit $url")
intent = Intent(context, AppLinkActivity::class.java)
intent.data = Uri.parse(url)
context.startActivity(intent)
}
else -> super.onClick(widget)
}
}
private fun checkForReddit(redditUrl: String): Boolean {
Timber.d("Checking url $redditUrl")
val p = Pattern.compile("(/r/.*)")
val m = p.matcher(redditUrl)
return m.matches()
}
}
| mit | d918140835602ed21367ee6978cb0487 | 31.788462 | 79 | 0.639296 | 4.241294 | false | false | false | false |
jwren/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/branchedTransformations/intentions/IfToWhenIntention.kt | 3 | 10501 | // 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.branchedTransformations.intentions
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiDocumentManager
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiWhiteSpace
import com.intellij.psi.codeStyle.CodeStyleManager
import org.jetbrains.kotlin.config.LanguageFeature
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.core.replaced
import org.jetbrains.kotlin.idea.intentions.SelfTargetingRangeIntention
import org.jetbrains.kotlin.idea.intentions.branchedTransformations.getSubjectToIntroduce
import org.jetbrains.kotlin.idea.intentions.branchedTransformations.introduceSubject
import org.jetbrains.kotlin.idea.intentions.branchedTransformations.unwrapBlockOrParenthesis
import org.jetbrains.kotlin.idea.project.languageVersionSettings
import org.jetbrains.kotlin.idea.quickfix.AddLoopLabelFix
import org.jetbrains.kotlin.idea.util.CommentSaver
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.*
class IfToWhenIntention : SelfTargetingRangeIntention<KtIfExpression>(
KtIfExpression::class.java,
KotlinBundle.lazyMessage("replace.if.with.when")
) {
override fun applicabilityRange(element: KtIfExpression): TextRange? {
if (element.then == null) return null
return element.ifKeyword.textRange
}
private fun canPassThrough(expression: KtExpression?): Boolean = when (expression) {
is KtReturnExpression, is KtThrowExpression ->
false
is KtBlockExpression ->
expression.statements.all { canPassThrough(it) }
is KtIfExpression ->
canPassThrough(expression.then) || canPassThrough(expression.`else`)
else ->
true
}
private fun buildNextBranch(ifExpression: KtIfExpression): KtExpression? {
var nextSibling = ifExpression.getNextSiblingIgnoringWhitespaceAndComments() ?: return null
return when (nextSibling) {
is KtIfExpression ->
if (nextSibling.then == null) null else nextSibling
else -> {
val builder = StringBuilder()
while (true) {
builder.append(nextSibling.text)
nextSibling = nextSibling.nextSibling ?: break
}
KtPsiFactory(ifExpression).createBlock(builder.toString()).takeIf { it.statements.isNotEmpty() }
}
}
}
private fun KtIfExpression.siblingsUpTo(other: KtExpression): List<PsiElement> {
val result = ArrayList<PsiElement>()
var nextSibling = nextSibling
// We delete elements up to the next if (or up to the end of the surrounding block)
while (nextSibling != null && nextSibling != other) {
// RBRACE closes the surrounding block, so it should not be copied / deleted
if (nextSibling !is PsiWhiteSpace && nextSibling.node.elementType != KtTokens.RBRACE) {
result.add(nextSibling)
}
nextSibling = nextSibling.nextSibling
}
return result
}
private class LabelLoopJumpVisitor(private val nearestLoopIfAny: KtLoopExpression?) : KtVisitorVoid() {
val labelName: String? by lazy {
nearestLoopIfAny?.let { loop ->
(loop.parent as? KtLabeledExpression)?.getLabelName() ?: AddLoopLabelFix.getUniqueLabelName(loop)
}
}
var labelRequired = false
fun KtExpressionWithLabel.addLabelIfNecessary(): KtExpressionWithLabel {
if (this.getLabelName() != null) {
// Label is already present, no need to add
return this
}
if (this.getStrictParentOfType<KtLoopExpression>() != nearestLoopIfAny) {
// 'for' inside 'if'
return this
}
if (!languageVersionSettings.supportsFeature(LanguageFeature.AllowBreakAndContinueInsideWhen) && labelName != null) {
val jumpWithLabel = KtPsiFactory(project).createExpression("$text@$labelName") as KtExpressionWithLabel
labelRequired = true
return replaced(jumpWithLabel)
}
return this
}
override fun visitBreakExpression(expression: KtBreakExpression) {
expression.addLabelIfNecessary()
}
override fun visitContinueExpression(expression: KtContinueExpression) {
expression.addLabelIfNecessary()
}
override fun visitKtElement(element: KtElement) {
element.acceptChildren(this)
}
}
private fun BuilderByPattern<*>.appendElseBlock(block: KtExpression?, unwrapBlockOrParenthesis: Boolean = false) {
appendFixedText("else->")
appendExpression(if (unwrapBlockOrParenthesis) block?.unwrapBlockOrParenthesis() else block)
appendFixedText("\n")
}
private fun KtIfExpression.topmostIfExpression(): KtIfExpression {
var target = this
while (true) {
val container = target.parent as? KtContainerNodeForControlStructureBody ?: break
val parent = container.parent as? KtIfExpression ?: break
if (parent.`else` != target) break
target = parent
}
return target
}
override fun applyTo(element: KtIfExpression, editor: Editor?) {
val ifExpression = element.topmostIfExpression()
val siblings = ifExpression.siblings()
val elementCommentSaver = CommentSaver(ifExpression)
val fullCommentSaver = CommentSaver(PsiChildRange(ifExpression, siblings.last()), saveLineBreaks = true)
val toDelete = ArrayList<PsiElement>()
var applyFullCommentSaver = true
val loop = ifExpression.getStrictParentOfType<KtLoopExpression>()
val loopJumpVisitor = LabelLoopJumpVisitor(loop)
var whenExpression = KtPsiFactory(ifExpression).buildExpression {
appendFixedText("when {\n")
var currentIfExpression = ifExpression
var baseIfExpressionForSyntheticBranch = currentIfExpression
var canPassThrough = false
while (true) {
val condition = currentIfExpression.condition
val orBranches = ArrayList<KtExpression>()
if (condition != null) {
orBranches.addOrBranches(condition)
}
appendExpressions(orBranches, separator = "||")
appendFixedText("->")
val currentThenBranch = currentIfExpression.then
appendExpression(currentThenBranch)
appendFixedText("\n")
canPassThrough = canPassThrough || canPassThrough(currentThenBranch)
val currentElseBranch = currentIfExpression.`else`
if (currentElseBranch == null) {
// Try to build synthetic if / else according to KT-10750
val syntheticElseBranch = if (canPassThrough) null else buildNextBranch(baseIfExpressionForSyntheticBranch)
if (syntheticElseBranch == null) {
applyFullCommentSaver = false
break
}
toDelete.addAll(baseIfExpressionForSyntheticBranch.siblingsUpTo(syntheticElseBranch))
if (syntheticElseBranch is KtIfExpression) {
baseIfExpressionForSyntheticBranch = syntheticElseBranch
currentIfExpression = syntheticElseBranch
toDelete.add(syntheticElseBranch)
} else {
appendElseBlock(syntheticElseBranch, unwrapBlockOrParenthesis = true)
break
}
} else if (currentElseBranch is KtIfExpression) {
currentIfExpression = currentElseBranch
} else {
appendElseBlock(currentElseBranch)
applyFullCommentSaver = false
break
}
}
appendFixedText("}")
} as KtWhenExpression
if (whenExpression.getSubjectToIntroduce(checkConstants = false) != null) {
whenExpression = whenExpression.introduceSubject(checkConstants = false) ?: return
}
val result = ifExpression.replaced(whenExpression)
editor?.caretModel?.moveToOffset(result.startOffset)
(if (applyFullCommentSaver) fullCommentSaver else elementCommentSaver).restore(result)
toDelete.forEach(PsiElement::delete)
result.accept(loopJumpVisitor)
val labelName = loopJumpVisitor.labelName
if (loop != null && loopJumpVisitor.labelRequired && labelName != null && loop.parent !is KtLabeledExpression) {
val labeledLoopExpression = KtPsiFactory(result).createLabeledExpression(labelName)
labeledLoopExpression.baseExpression!!.replace(loop)
val replacedLabeledLoopExpression = loop.replace(labeledLoopExpression)
// For some reason previous operation can break adjustments
val project = loop.project
if (editor != null) {
val documentManager = PsiDocumentManager.getInstance(project)
documentManager.commitDocument(editor.document)
documentManager.doPostponedOperationsAndUnblockDocument(editor.document)
val psiFile = documentManager.getPsiFile(editor.document)!!
CodeStyleManager.getInstance(project).adjustLineIndent(psiFile, replacedLabeledLoopExpression.textRange)
}
}
}
private fun MutableList<KtExpression>.addOrBranches(expression: KtExpression): List<KtExpression> {
if (expression is KtBinaryExpression && expression.operationToken == KtTokens.OROR) {
val left = expression.left
val right = expression.right
if (left != null && right != null) {
addOrBranches(left)
addOrBranches(right)
return this
}
}
add(KtPsiUtil.safeDeparenthesize(expression, true))
return this
}
}
| apache-2.0 | 97b7dd75d21b93f337ba8cd201373ee6 | 42.754167 | 158 | 0.648414 | 5.808075 | false | false | false | false |
jwren/intellij-community | plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/idea/decompiler/textBuilder/AbstractDecompiledTextTest.kt | 4 | 3225 | // 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.decompiler.textBuilder
import com.intellij.openapi.module.Module
import com.intellij.openapi.roots.LibraryOrderEntry
import com.intellij.openapi.roots.ModuleRootManager
import com.intellij.openapi.roots.OrderRootType
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.PsiFile
import com.intellij.util.indexing.FileContentImpl
import com.intellij.util.io.exists
import com.intellij.util.io.readText
import org.jetbrains.kotlin.analysis.decompiler.psi.file.KtClsFile
import org.jetbrains.kotlin.analysis.decompiler.stub.file.KotlinClsStubBuilder
import org.jetbrains.kotlin.idea.decompiler.stubBuilder.serializeToString
import org.jetbrains.kotlin.psi.KtPsiFactory
import org.jetbrains.kotlin.psi.stubs.elements.KtFileStubBuilder
import org.junit.Assert
import java.nio.file.Paths
import kotlin.test.assertTrue
abstract class AbstractDecompiledTextTest(baseDirectory: String) : AbstractDecompiledTextBaseTest(baseDirectory) {
private val CUSTOM_PACKAGE_FILE = "package.txt"
override fun fileName(): String {
val testName = getTestName(false)
return "$testName/$testName.kt"
}
override fun getFileToDecompile(): VirtualFile {
val className = getTestName(false)
val customPackageFile = Paths.get(mockSourcesBase.absolutePath, className, CUSTOM_PACKAGE_FILE)
val testFilePackage = customPackageFile.takeIf { it.exists() }?.readText()?.trimEnd() ?: TEST_PACKAGE
return getClassFile(testFilePackage, className, module!!)
}
override fun checkStubConsistency(file: VirtualFile, decompiledText: String) {
val fileWithDecompiledText = KtPsiFactory(project).createFile(decompiledText)
val stubTreeFromDecompiledText = KtFileStubBuilder().buildStubTree(fileWithDecompiledText)
val expectedText = stubTreeFromDecompiledText.serializeToString()
val fileStub = KotlinClsStubBuilder().buildFileStub(FileContentImpl.createByFile(file))!!
Assert.assertEquals(expectedText, fileStub.serializeToString())
}
override fun checkPsiFile(psiFile: PsiFile) =
assertTrue(psiFile is KtClsFile, "Expecting decompiled kotlin file, was: " + psiFile::class.java)
override fun textToCheck(psiFile: PsiFile) = psiFile.text
}
abstract class AbstractCommonDecompiledTextTest : AbstractDecompiledTextTest("/decompiler/decompiledText")
abstract class AbstractJvmDecompiledTextTest : AbstractDecompiledTextTest("/decompiler/decompiledTextJvm")
fun findTestLibraryRoot(module: Module): VirtualFile? {
for (orderEntry in ModuleRootManager.getInstance(module).orderEntries) {
if (orderEntry is LibraryOrderEntry) {
return orderEntry.getFiles(OrderRootType.CLASSES)[0]
}
}
return null
}
fun getClassFile(
packageName: String,
className: String,
module: Module
): VirtualFile {
val root = findTestLibraryRoot(module)!!
val packageDir = root.findFileByRelativePath(packageName.replace(".", "/"))!!
return packageDir.findChild("$className.class")!!
} | apache-2.0 | d1525cb6fe0b38fd351a7b4686cc46a2 | 40.896104 | 158 | 0.774884 | 4.714912 | false | true | false | false |
jwren/intellij-community | platform/diff-impl/src/com/intellij/diff/tools/combined/CombinedDiffRequest.kt | 1 | 1664 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.diff.tools.combined
import com.intellij.diff.chains.DiffRequestProducer
import com.intellij.diff.requests.DiffRequest
import com.intellij.openapi.util.NlsContexts
import org.jetbrains.annotations.Nls
class CombinedDiffRequest(private val title: @Nls String?, requests: List<ChildDiffRequest>) : DiffRequest() {
private val _requests: MutableList<ChildDiffRequest>
init {
_requests = requests.toMutableList()
}
class ChildDiffRequest(val producer: DiffRequestProducer, val blockId: CombinedBlockId)
data class NewChildDiffRequestData(val blockId: CombinedBlockId, val position: InsertPosition)
data class InsertPosition(val blockId: CombinedBlockId, val above: Boolean)
fun getChildRequest(index: Int) = _requests.getOrNull(index)
fun getChildRequests() = _requests.toList()
fun getChildRequestsSize() = _requests.size
fun addChild(childRequest: ChildDiffRequest, position: InsertPosition) {
val above = position.above
val existingIndex = _requests.indexOfFirst { request -> request.blockId == position.blockId }
if (existingIndex != -1) {
val newIndex = if (above) existingIndex else existingIndex + 1
_requests.add(newIndex, childRequest)
}
else {
_requests.add(childRequest)
}
}
fun removeChild(childRequest: ChildDiffRequest) {
_requests.remove(childRequest)
}
override fun getTitle(): @NlsContexts.DialogTitle String? {
return title
}
override fun toString(): String {
return super.toString() + ":" + title
}
}
| apache-2.0 | 8bb0438ff3128ab52827e92aad35c7bd | 30.396226 | 120 | 0.744591 | 4.277635 | false | false | false | false |
dahlstrom-g/intellij-community | plugins/kotlin/j2k/new/src/org/jetbrains/kotlin/nj2k/conversions/InterfaceWithFieldConversion.kt | 6 | 1341 | // 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.nj2k.conversions
import org.jetbrains.kotlin.nj2k.NewJ2kConverterContext
import org.jetbrains.kotlin.nj2k.declarationList
import org.jetbrains.kotlin.nj2k.getOrCreateCompanionObject
import org.jetbrains.kotlin.nj2k.tree.*
class InterfaceWithFieldConversion(context : NewJ2kConverterContext) : RecursiveApplicableConversionBase(context) {
override fun applyToElement(element: JKTreeElement): JKTreeElement {
if (element !is JKClass) return recurse(element)
if (element.classKind != JKClass.ClassKind.INTERFACE
&& element.classKind != JKClass.ClassKind.ANNOTATION
) return recurse(element)
val fieldsToMoveToCompanion = element.declarationList
.filterIsInstance<JKField>()
.filter { field ->
field.modality == Modality.FINAL || element.classKind == JKClass.ClassKind.ANNOTATION
}
if (fieldsToMoveToCompanion.isNotEmpty()) {
element.classBody.declarations -= fieldsToMoveToCompanion
val companion = element.getOrCreateCompanionObject()
companion.classBody.declarations += fieldsToMoveToCompanion
}
return recurse(element)
}
} | apache-2.0 | c9030551e6dfbcee9a8fea07e400d1ef | 43.733333 | 120 | 0.722595 | 5.003731 | false | false | false | false |
androidx/androidx | compose/ui/ui-text/src/commonMain/kotlin/androidx/compose/ui/text/input/ImeOptions.kt | 3 | 4222 | /*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.ui.text.input
import androidx.compose.runtime.Immutable
/**
* The IME configuration options for [TextInputService]. It is not guaranteed if IME
* will comply with the options provided here.
*
* @param singleLine informs the IME that the text field is single line and IME
* should not show return key.
* @param capitalization informs the IME whether to automatically capitalize characters,
* words or sentences. Only applicable to only text based [KeyboardType]s such as
* [KeyboardType.Text], [KeyboardType.Ascii]. It will not be applied to [KeyboardType]s such as
* [KeyboardType.Number] or [KeyboardType.Decimal].
* @param autoCorrect informs the IME whether to enable auto correct. Only applicable to
* text based [KeyboardType]s such as [KeyboardType.Email], [KeyboardType.Uri]. It will not be
* applied to [KeyboardType]s such as [KeyboardType.Number] or [KeyboardType.Decimal]. Most of IME
* implementations ignore this value for [KeyboardType]s such as [KeyboardType.Text].
* @param keyboardType The keyboard type to be used in this text field. Note that this input type
* is honored by IME and shows corresponding keyboard but this is not guaranteed. For example,
* some IME may send non-ASCII character even if you set [KeyboardType.Ascii].
* @param imeAction The IME action. This IME action is honored by IME and may show specific icons
* on the keyboard. For example, search icon may be shown if [ImeAction.Search] is specified.
* When [singleLine] is false, the IME might show return key rather than the action requested here.
*/
@Immutable
class ImeOptions(
val singleLine: Boolean = false,
val capitalization: KeyboardCapitalization = KeyboardCapitalization.None,
val autoCorrect: Boolean = true,
val keyboardType: KeyboardType = KeyboardType.Text,
val imeAction: ImeAction = ImeAction.Default
) {
companion object {
/**
* Default [ImeOptions]. Please see parameter descriptions for default values.
*/
val Default = ImeOptions()
}
fun copy(
singleLine: Boolean = this.singleLine,
capitalization: KeyboardCapitalization = this.capitalization,
autoCorrect: Boolean = this.autoCorrect,
keyboardType: KeyboardType = this.keyboardType,
imeAction: ImeAction = this.imeAction
): ImeOptions {
return ImeOptions(
singleLine = singleLine,
capitalization = capitalization,
autoCorrect = autoCorrect,
keyboardType = keyboardType,
imeAction = imeAction
)
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is ImeOptions) return false
if (singleLine != other.singleLine) return false
if (capitalization != other.capitalization) return false
if (autoCorrect != other.autoCorrect) return false
if (keyboardType != other.keyboardType) return false
if (imeAction != other.imeAction) return false
return true
}
override fun hashCode(): Int {
var result = singleLine.hashCode()
result = 31 * result + capitalization.hashCode()
result = 31 * result + autoCorrect.hashCode()
result = 31 * result + keyboardType.hashCode()
result = 31 * result + imeAction.hashCode()
return result
}
override fun toString(): String {
return "ImeOptions(singleLine=$singleLine, capitalization=$capitalization, " +
"autoCorrect=$autoCorrect, keyboardType=$keyboardType, imeAction=$imeAction)"
}
} | apache-2.0 | ff793ab80553c1b917f0cbbfb1224714 | 41.656566 | 99 | 0.705116 | 4.776018 | false | false | false | false |
androidx/androidx | lint-checks/src/main/java/androidx/build/lint/ObsoleteBuildCompatUsageDetector.kt | 3 | 3067 | /*
* Copyright (C) 2018 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.
*/
@file:Suppress("UnstableApiUsage")
package androidx.build.lint
import com.android.tools.lint.detector.api.Category
import com.android.tools.lint.detector.api.Detector
import com.android.tools.lint.detector.api.Implementation
import com.android.tools.lint.detector.api.Incident
import com.android.tools.lint.detector.api.Issue
import com.android.tools.lint.detector.api.JavaContext
import com.android.tools.lint.detector.api.Scope
import com.android.tools.lint.detector.api.Severity
import com.intellij.psi.PsiMethod
import org.jetbrains.uast.UCallExpression
class ObsoleteBuildCompatUsageDetector : Detector(), Detector.UastScanner {
private val methodsToApiLevels = mapOf(
"isAtLeastN" to 24,
"isAtLeastNMR1" to 25,
"isAtLeastO" to 26,
"isAtLeastOMR1" to 27,
"isAtLeastP" to 28,
"isAtLeastQ" to 29
)
override fun getApplicableMethodNames() = methodsToApiLevels.keys.toList()
override fun visitMethodCall(context: JavaContext, node: UCallExpression, method: PsiMethod) {
if (!context.evaluator.isMemberInClass(method, "androidx.core.os.BuildCompat")) {
return
}
// A receiver indicates the class name is part of the call (as opposed to static import).
val target = if (node.receiver != null) node.uastParent!! else node
val apiLevel = methodsToApiLevels[node.methodName]
val lintFix = fix().name("Use SDK_INT >= $apiLevel")
.replace()
.text(target.asRenderString())
.with("Build.VERSION.SDK_INT >= $apiLevel")
.build()
val incident = Incident(context)
.fix(lintFix)
.issue(ISSUE)
.location(context.getLocation(node))
.message("Using deprecated BuildCompat methods")
.scope(node)
context.report(incident)
}
companion object {
val ISSUE = Issue.create(
"ObsoleteBuildCompat",
"Using deprecated BuildCompat methods",
"BuildConfig methods should only be used prior to an API level's finalization. " +
"Once an API level number is assigned, comparing directly with SDK_INT " +
"is preferred as it enables other lint checks to correctly work.",
Category.CORRECTNESS, 5, Severity.ERROR,
Implementation(ObsoleteBuildCompatUsageDetector::class.java, Scope.JAVA_FILE_SCOPE)
)
}
}
| apache-2.0 | 0c1ac1b682ccfbb0930697ae7f2d07a5 | 38.320513 | 98 | 0.684382 | 4.313643 | false | false | false | false |
faruktoptas/RetrofitRssConverterFactory | library/src/main/java/me/toptas/rssconverter/RssItem.kt | 1 | 924 | package me.toptas.rssconverter
import java.io.Serializable
/**
* Model for Rss Item
*/
class RssItem : Serializable {
var title: String? = null
set(title) {
field = title?.replace("'", "'")?.replace("'", "'")
}
var link: String? = null
set(link) {
field = link?.trim { it <= ' ' }
}
var image: String? = null
var publishDate: String? = null
var description: String? = null
override fun toString(): String {
val builder = StringBuilder()
if (title != null) {
builder.append(title).append("\n")
}
if (link != null) {
builder.append(link).append("\n")
}
if (image != null) {
builder.append(image).append("\n")
}
if (description != null) {
builder.append(description)
}
return builder.toString()
}
}
| apache-2.0 | d0e7fd4d4e97e26db2b0ea4e9f581fbc | 22.692308 | 72 | 0.504329 | 4.143498 | false | false | false | false |
androidx/androidx | tv/tv-foundation/src/androidTest/java/androidx/tv/foundation/lazy/grid/LazyGridsContentPaddingTest.kt | 3 | 42407 | /*
* 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.tv.foundation.lazy.grid
import androidx.compose.animation.core.snap
import androidx.compose.foundation.gestures.animateScrollBy
import androidx.compose.foundation.gestures.scrollBy
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.requiredSize
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.test.assertHeightIsEqualTo
import androidx.compose.ui.test.assertIsNotDisplayed
import androidx.compose.ui.test.assertLeftPositionInRootIsEqualTo
import androidx.compose.ui.test.assertTopPositionInRootIsEqualTo
import androidx.compose.ui.test.assertWidthIsEqualTo
import androidx.compose.ui.test.junit4.createComposeRule
import androidx.compose.ui.test.onNodeWithTag
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.LargeTest
import androidx.tv.foundation.lazy.AutoTestFrameClock
import androidx.tv.foundation.lazy.list.setContentWithTestViewConfiguration
import com.google.common.truth.Truth.assertThat
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.runBlocking
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
@LargeTest
@RunWith(AndroidJUnit4::class)
class LazyGridsContentPaddingTest {
private val LazyListTag = "LazyList"
private val ItemTag = "item"
private val ContainerTag = "container"
@get:Rule
val rule = createComposeRule()
private var itemSize: Dp = Dp.Infinity
private var smallPaddingSize: Dp = Dp.Infinity
private var itemSizePx = 50f
private var smallPaddingSizePx = 12f
@Before
fun before() {
with(rule.density) {
itemSize = itemSizePx.toDp()
smallPaddingSize = smallPaddingSizePx.toDp()
}
}
@Test
fun verticalGrid_contentPaddingIsApplied() {
lateinit var state: TvLazyGridState
val containerSize = itemSize * 2
val largePaddingSize = itemSize
rule.setContent {
TvLazyVerticalGrid(
columns = TvGridCells.Fixed(1),
modifier = Modifier.requiredSize(containerSize)
.testTag(LazyListTag),
state = rememberTvLazyGridState().also { state = it },
contentPadding = PaddingValues(
start = smallPaddingSize,
top = largePaddingSize,
end = smallPaddingSize,
bottom = largePaddingSize
)
) {
items(listOf(1)) {
Spacer(Modifier.height(itemSize).testTag(ItemTag))
}
}
}
rule.onNodeWithTag(ItemTag)
.assertLeftPositionInRootIsEqualTo(smallPaddingSize)
.assertTopPositionInRootIsEqualTo(largePaddingSize)
.assertWidthIsEqualTo(containerSize - smallPaddingSize * 2)
.assertHeightIsEqualTo(itemSize)
state.scrollBy(largePaddingSize)
rule.onNodeWithTag(ItemTag)
.assertTopPositionInRootIsEqualTo(0.dp)
.assertHeightIsEqualTo(itemSize)
}
@Test
fun verticalGrid_contentPaddingIsNotAffectingScrollPosition() {
lateinit var state: TvLazyGridState
rule.setContent {
TvLazyVerticalGrid(
columns = TvGridCells.Fixed(1),
modifier = Modifier.requiredSize(itemSize * 2)
.testTag(LazyListTag),
state = rememberTvLazyGridState().also { state = it },
contentPadding = PaddingValues(
top = itemSize,
bottom = itemSize
)
) {
items(listOf(1)) {
Spacer(Modifier.height(itemSize).testTag(ItemTag))
}
}
}
state.assertScrollPosition(0, 0.dp)
state.scrollBy(itemSize)
state.assertScrollPosition(0, itemSize)
}
@Test
fun verticalGrid_scrollForwardItemWithinStartPaddingDisplayed() {
lateinit var state: TvLazyGridState
val padding = itemSize * 1.5f
rule.setContent {
TvLazyVerticalGrid(
columns = TvGridCells.Fixed(1),
modifier = Modifier.requiredSize(padding * 2 + itemSize)
.testTag(LazyListTag),
state = rememberTvLazyGridState().also { state = it },
contentPadding = PaddingValues(
top = padding,
bottom = padding
)
) {
items((0..3).toList()) {
Spacer(Modifier.requiredSize(itemSize).testTag(it.toString()))
}
}
}
rule.onNodeWithTag("0")
.assertTopPositionInRootIsEqualTo(padding)
rule.onNodeWithTag("1")
.assertTopPositionInRootIsEqualTo(itemSize + padding)
rule.onNodeWithTag("2")
.assertTopPositionInRootIsEqualTo(itemSize * 2 + padding)
state.scrollBy(padding)
state.assertScrollPosition(1, padding - itemSize)
rule.onNodeWithTag("0")
.assertTopPositionInRootIsEqualTo(0.dp)
rule.onNodeWithTag("1")
.assertTopPositionInRootIsEqualTo(itemSize)
rule.onNodeWithTag("2")
.assertTopPositionInRootIsEqualTo(itemSize * 2)
rule.onNodeWithTag("3")
.assertTopPositionInRootIsEqualTo(itemSize * 3)
}
@Test
fun verticalGrid_scrollBackwardItemWithinStartPaddingDisplayed() {
lateinit var state: TvLazyGridState
val padding = itemSize * 1.5f
rule.setContent {
TvLazyVerticalGrid(
columns = TvGridCells.Fixed(1),
modifier = Modifier.requiredSize(itemSize + padding * 2)
.testTag(LazyListTag),
state = rememberTvLazyGridState().also { state = it },
contentPadding = PaddingValues(
top = padding,
bottom = padding
)
) {
items((0..3).toList()) {
Spacer(Modifier.requiredSize(itemSize).testTag(it.toString()))
}
}
}
state.scrollBy(itemSize * 3)
state.scrollBy(-itemSize * 1.5f)
state.assertScrollPosition(1, itemSize * 0.5f)
rule.onNodeWithTag("0")
.assertTopPositionInRootIsEqualTo(itemSize * 1.5f - padding)
rule.onNodeWithTag("1")
.assertTopPositionInRootIsEqualTo(itemSize * 2.5f - padding)
rule.onNodeWithTag("2")
.assertTopPositionInRootIsEqualTo(itemSize * 3.5f - padding)
rule.onNodeWithTag("3")
.assertTopPositionInRootIsEqualTo(itemSize * 4.5f - padding)
}
@Test
fun verticalGrid_scrollForwardTillTheEnd() {
lateinit var state: TvLazyGridState
val padding = itemSize * 1.5f
rule.setContent {
TvLazyVerticalGrid(
columns = TvGridCells.Fixed(1),
modifier = Modifier.requiredSize(padding * 2 + itemSize)
.testTag(LazyListTag),
state = rememberTvLazyGridState().also { state = it },
contentPadding = PaddingValues(
top = padding,
bottom = padding
)
) {
items((0..3).toList()) {
Spacer(Modifier.requiredSize(itemSize).testTag(it.toString()))
}
}
}
state.scrollBy(itemSize * 3)
state.assertScrollPosition(3, 0.dp)
rule.onNodeWithTag("1")
.assertTopPositionInRootIsEqualTo(itemSize - padding)
rule.onNodeWithTag("2")
.assertTopPositionInRootIsEqualTo(itemSize * 2 - padding)
rule.onNodeWithTag("3")
.assertTopPositionInRootIsEqualTo(itemSize * 3 - padding)
// there are no space to scroll anymore, so it should change nothing
state.scrollBy(10.dp)
state.assertScrollPosition(3, 0.dp)
rule.onNodeWithTag("1")
.assertTopPositionInRootIsEqualTo(itemSize - padding)
rule.onNodeWithTag("2")
.assertTopPositionInRootIsEqualTo(itemSize * 2 - padding)
rule.onNodeWithTag("3")
.assertTopPositionInRootIsEqualTo(itemSize * 3 - padding)
}
@Test
fun verticalGrid_scrollForwardTillTheEndAndABitBack() {
lateinit var state: TvLazyGridState
val padding = itemSize * 1.5f
rule.setContent {
TvLazyVerticalGrid(
columns = TvGridCells.Fixed(1),
modifier = Modifier.requiredSize(padding * 2 + itemSize)
.testTag(LazyListTag),
state = rememberTvLazyGridState().also { state = it },
contentPadding = PaddingValues(
top = padding,
bottom = padding
)
) {
items((0..3).toList()) {
Spacer(Modifier.requiredSize(itemSize).testTag(it.toString()))
}
}
}
state.scrollBy(itemSize * 3)
state.scrollBy(-itemSize / 2)
state.assertScrollPosition(2, itemSize / 2)
rule.onNodeWithTag("1")
.assertTopPositionInRootIsEqualTo(itemSize * 1.5f - padding)
rule.onNodeWithTag("2")
.assertTopPositionInRootIsEqualTo(itemSize * 2.5f - padding)
rule.onNodeWithTag("3")
.assertTopPositionInRootIsEqualTo(itemSize * 3.5f - padding)
}
@Test
fun verticalGrid_contentPaddingFixedWidthContainer() {
rule.setContent {
Box(modifier = Modifier.testTag(ContainerTag).width(itemSize + 8.dp)) {
TvLazyVerticalGrid(
columns = TvGridCells.Fixed(1),
contentPadding = PaddingValues(
start = 2.dp,
top = 4.dp,
end = 6.dp,
bottom = 8.dp
)
) {
items(listOf(1)) {
Spacer(Modifier.size(itemSize).testTag(ItemTag))
}
}
}
}
rule.onNodeWithTag(ItemTag)
.assertLeftPositionInRootIsEqualTo(2.dp)
.assertTopPositionInRootIsEqualTo(4.dp)
.assertWidthIsEqualTo(itemSize)
.assertHeightIsEqualTo(itemSize)
rule.onNodeWithTag(ContainerTag)
.assertLeftPositionInRootIsEqualTo(0.dp)
.assertTopPositionInRootIsEqualTo(0.dp)
.assertWidthIsEqualTo(itemSize + 2.dp + 6.dp)
.assertHeightIsEqualTo(itemSize + 4.dp + 8.dp)
}
@Test
fun verticalGrid_contentPaddingAndNoContent() {
rule.setContent {
Box(modifier = Modifier.testTag(ContainerTag)) {
TvLazyVerticalGrid(
columns = TvGridCells.Fixed(1),
contentPadding = PaddingValues(
start = 2.dp,
top = 4.dp,
end = 6.dp,
bottom = 8.dp
)
) { }
}
}
rule.onNodeWithTag(ContainerTag)
.assertLeftPositionInRootIsEqualTo(0.dp)
.assertTopPositionInRootIsEqualTo(0.dp)
.assertWidthIsEqualTo(8.dp)
.assertHeightIsEqualTo(12.dp)
}
@Test
fun verticalGrid_contentPaddingAndZeroSizedItem() {
rule.setContent {
Box(modifier = Modifier.testTag(ContainerTag)) {
TvLazyVerticalGrid(
columns = TvGridCells.Fixed(1),
contentPadding = PaddingValues(
start = 2.dp,
top = 4.dp,
end = 6.dp,
bottom = 8.dp
)
) {
items(0) { }
}
}
}
rule.onNodeWithTag(ContainerTag)
.assertLeftPositionInRootIsEqualTo(0.dp)
.assertTopPositionInRootIsEqualTo(0.dp)
.assertWidthIsEqualTo(8.dp)
.assertHeightIsEqualTo(12.dp)
}
@Test
fun verticalGrid_contentPaddingAndReverseLayout() {
val topPadding = itemSize * 2
val bottomPadding = itemSize / 2
val listSize = itemSize * 3
lateinit var state: TvLazyGridState
rule.setContentWithTestViewConfiguration {
TvLazyVerticalGrid(
TvGridCells.Fixed(1),
reverseLayout = true,
state = rememberTvLazyGridState().also { state = it },
modifier = Modifier.size(listSize),
contentPadding = PaddingValues(top = topPadding, bottom = bottomPadding),
) {
items(3) { index ->
Box(Modifier.size(itemSize).testTag("$index"))
}
}
}
rule.onNodeWithTag("0")
.assertTopPositionInRootIsEqualTo(listSize - bottomPadding - itemSize)
rule.onNodeWithTag("1")
.assertTopPositionInRootIsEqualTo(listSize - bottomPadding - itemSize * 2)
// Partially visible.
rule.onNodeWithTag("2")
.assertTopPositionInRootIsEqualTo(-itemSize / 2)
// Scroll to the top.
state.scrollBy(itemSize * 2.5f)
rule.onNodeWithTag("2").assertTopPositionInRootIsEqualTo(topPadding)
// Shouldn't be visible
rule.onNodeWithTag("1").assertIsNotDisplayed()
rule.onNodeWithTag("0").assertIsNotDisplayed()
}
@Test
fun column_overscrollWithContentPadding() {
lateinit var state: TvLazyGridState
rule.setContent {
state = rememberTvLazyGridState()
Box(modifier = Modifier.testTag(ContainerTag).size(itemSize + smallPaddingSize * 2)) {
TvLazyVerticalGrid(
TvGridCells.Fixed(1),
state = state,
contentPadding = PaddingValues(
vertical = smallPaddingSize
)
) {
items(2) {
Box(Modifier.testTag("$it").height(itemSize))
}
}
}
}
rule.onNodeWithTag("0")
.assertTopPositionInRootIsEqualTo(smallPaddingSize)
.assertHeightIsEqualTo(itemSize)
rule.onNodeWithTag("1")
.assertTopPositionInRootIsEqualTo(smallPaddingSize + itemSize)
.assertHeightIsEqualTo(itemSize)
rule.runOnIdle {
runBlocking {
// itemSizePx is the maximum offset, plus if we overscroll the content padding
// the layout mechanism will decide the item 0 is not needed until we start
// filling the over scrolled gap.
state.scrollBy(value = itemSizePx + smallPaddingSizePx * 1.5f)
}
}
rule.onNodeWithTag("1")
.assertTopPositionInRootIsEqualTo(smallPaddingSize)
.assertHeightIsEqualTo(itemSize)
rule.onNodeWithTag("0")
.assertTopPositionInRootIsEqualTo(smallPaddingSize - itemSize)
.assertHeightIsEqualTo(itemSize)
}
@Test
fun totalPaddingLargerParentSize_initialState() {
lateinit var state: TvLazyGridState
rule.setContent {
state = rememberTvLazyGridState()
Box(modifier = Modifier.testTag(ContainerTag).size(itemSize * 1.5f)) {
TvLazyVerticalGrid(
TvGridCells.Fixed(1),
state = state,
contentPadding = PaddingValues(vertical = itemSize)
) {
items(4) {
Box(Modifier.testTag("$it").size(itemSize))
}
}
}
}
rule.onNodeWithTag("0")
.assertTopPositionInRootIsEqualTo(itemSize)
rule.onNodeWithTag("1")
.assertDoesNotExist()
rule.runOnIdle {
state.assertScrollPosition(0, 0.dp)
state.assertVisibleItems(0 to 0.dp)
state.assertLayoutInfoOffsetRange(-itemSize, itemSize * 0.5f)
}
}
@Test
fun totalPaddingLargerParentSize_scrollByPadding() {
lateinit var state: TvLazyGridState
rule.setContent {
state = rememberTvLazyGridState()
Box(modifier = Modifier.testTag(ContainerTag).size(itemSize * 1.5f)) {
TvLazyVerticalGrid(
TvGridCells.Fixed(1),
state = state,
contentPadding = PaddingValues(vertical = itemSize)
) {
items(4) {
Box(Modifier.testTag("$it").size(itemSize))
}
}
}
}
state.scrollBy(itemSize)
rule.onNodeWithTag("0")
.assertTopPositionInRootIsEqualTo(0.dp)
rule.onNodeWithTag("1")
.assertTopPositionInRootIsEqualTo(itemSize)
rule.onNodeWithTag("2")
.assertIsNotDisplayed()
rule.runOnIdle {
state.assertScrollPosition(1, 0.dp)
state.assertVisibleItems(0 to -itemSize, 1 to 0.dp)
}
}
@Test
fun totalPaddingLargerParentSize_scrollToLastItem() {
lateinit var state: TvLazyGridState
rule.setContent {
state = rememberTvLazyGridState()
Box(modifier = Modifier.testTag(ContainerTag).size(itemSize * 1.5f)) {
TvLazyVerticalGrid(
TvGridCells.Fixed(1),
state = state,
contentPadding = PaddingValues(vertical = itemSize)
) {
items(4) {
Box(Modifier.testTag("$it").size(itemSize))
}
}
}
}
state.scrollTo(3)
rule.onNodeWithTag("1")
.assertDoesNotExist()
rule.onNodeWithTag("2")
.assertTopPositionInRootIsEqualTo(0.dp)
rule.onNodeWithTag("3")
.assertTopPositionInRootIsEqualTo(itemSize)
rule.runOnIdle {
state.assertScrollPosition(3, 0.dp)
state.assertVisibleItems(2 to -itemSize, 3 to 0.dp)
}
}
@Test
fun totalPaddingLargerParentSize_scrollToLastItemByDelta() {
lateinit var state: TvLazyGridState
rule.setContent {
state = rememberTvLazyGridState()
Box(modifier = Modifier.testTag(ContainerTag).size(itemSize * 1.5f)) {
TvLazyVerticalGrid(
TvGridCells.Fixed(1),
state = state,
contentPadding = PaddingValues(vertical = itemSize)
) {
items(4) {
Box(Modifier.testTag("$it").size(itemSize))
}
}
}
}
state.scrollBy(itemSize * 3)
rule.onNodeWithTag("1")
.assertIsNotDisplayed()
rule.onNodeWithTag("2")
.assertTopPositionInRootIsEqualTo(0.dp)
rule.onNodeWithTag("3")
.assertTopPositionInRootIsEqualTo(itemSize)
rule.runOnIdle {
state.assertScrollPosition(3, 0.dp)
state.assertVisibleItems(2 to -itemSize, 3 to 0.dp)
}
}
@Test
fun totalPaddingLargerParentSize_scrollTillTheEnd() {
// the whole end content padding is displayed
lateinit var state: TvLazyGridState
rule.setContent {
state = rememberTvLazyGridState()
Box(modifier = Modifier.testTag(ContainerTag).size(itemSize * 1.5f)) {
TvLazyVerticalGrid(
TvGridCells.Fixed(1),
state = state,
contentPadding = PaddingValues(vertical = itemSize)
) {
items(4) {
Box(Modifier.testTag("$it").size(itemSize))
}
}
}
}
state.scrollBy(itemSize * 4.5f)
rule.onNodeWithTag("2")
.assertIsNotDisplayed()
rule.onNodeWithTag("3")
.assertTopPositionInRootIsEqualTo(-itemSize * 0.5f)
rule.runOnIdle {
state.assertScrollPosition(3, itemSize * 1.5f)
state.assertVisibleItems(3 to -itemSize * 1.5f)
}
}
@Test
fun eachPaddingLargerParentSize_initialState() {
lateinit var state: TvLazyGridState
rule.setContent {
state = rememberTvLazyGridState()
Box(modifier = Modifier.testTag(ContainerTag).size(itemSize * 1.5f)) {
TvLazyVerticalGrid(
TvGridCells.Fixed(1),
state = state,
contentPadding = PaddingValues(vertical = itemSize * 2)
) {
items(4) {
Box(Modifier.testTag("$it").size(itemSize))
}
}
}
}
rule.onNodeWithTag("0")
.assertIsNotDisplayed()
rule.runOnIdle {
state.assertScrollPosition(0, 0.dp)
state.assertVisibleItems(0 to 0.dp)
state.assertLayoutInfoOffsetRange(-itemSize * 2, -itemSize * 0.5f)
}
}
@Test
fun eachPaddingLargerParentSize_scrollByPadding() {
lateinit var state: TvLazyGridState
rule.setContent {
state = rememberTvLazyGridState()
Box(modifier = Modifier.testTag(ContainerTag).size(itemSize * 1.5f)) {
TvLazyVerticalGrid(
TvGridCells.Fixed(1),
state = state,
contentPadding = PaddingValues(vertical = itemSize * 2)
) {
items(4) {
Box(Modifier.testTag("$it").size(itemSize))
}
}
}
}
state.scrollBy(itemSize * 2)
rule.onNodeWithTag("0")
.assertTopPositionInRootIsEqualTo(0.dp)
rule.onNodeWithTag("1")
.assertTopPositionInRootIsEqualTo(itemSize)
rule.onNodeWithTag("2")
.assertIsNotDisplayed()
rule.runOnIdle {
state.assertScrollPosition(2, 0.dp)
state.assertVisibleItems(0 to -itemSize * 2, 1 to -itemSize, 2 to 0.dp)
}
}
@Test
fun eachPaddingLargerParentSize_scrollToLastItem() {
lateinit var state: TvLazyGridState
rule.setContent {
state = rememberTvLazyGridState()
Box(modifier = Modifier.testTag(ContainerTag).size(itemSize * 1.5f)) {
TvLazyVerticalGrid(
TvGridCells.Fixed(1),
state = state,
contentPadding = PaddingValues(vertical = itemSize * 2)
) {
items(4) {
Box(Modifier.testTag("$it").size(itemSize))
}
}
}
}
state.scrollTo(3)
rule.onNodeWithTag("0")
.assertIsNotDisplayed()
rule.onNodeWithTag("1")
.assertTopPositionInRootIsEqualTo(0.dp)
rule.onNodeWithTag("2")
.assertTopPositionInRootIsEqualTo(itemSize)
rule.onNodeWithTag("3")
.assertIsNotDisplayed()
rule.runOnIdle {
state.assertScrollPosition(3, 0.dp)
state.assertVisibleItems(1 to -itemSize * 2, 2 to -itemSize, 3 to 0.dp)
}
}
@Test
fun eachPaddingLargerParentSize_scrollToLastItemByDelta() {
lateinit var state: TvLazyGridState
rule.setContent {
state = rememberTvLazyGridState()
Box(modifier = Modifier.testTag(ContainerTag).size(itemSize * 1.5f)) {
TvLazyVerticalGrid(
TvGridCells.Fixed(1),
state = state,
contentPadding = PaddingValues(vertical = itemSize * 2)
) {
items(4) {
Box(Modifier.testTag("$it").size(itemSize))
}
}
}
}
state.scrollBy(itemSize * 3)
rule.onNodeWithTag("0")
.assertIsNotDisplayed()
rule.onNodeWithTag("1")
.assertTopPositionInRootIsEqualTo(0.dp)
rule.onNodeWithTag("2")
.assertTopPositionInRootIsEqualTo(itemSize)
rule.onNodeWithTag("3")
.assertIsNotDisplayed()
rule.runOnIdle {
state.assertScrollPosition(3, 0.dp)
state.assertVisibleItems(1 to -itemSize * 2, 2 to -itemSize, 3 to 0.dp)
}
}
@Test
fun eachPaddingLargerParentSize_scrollTillTheEnd() {
// only the end content padding is displayed
lateinit var state: TvLazyGridState
rule.setContent {
state = rememberTvLazyGridState()
Box(modifier = Modifier.testTag(ContainerTag).size(itemSize * 1.5f)) {
TvLazyVerticalGrid(
TvGridCells.Fixed(1),
state = state,
contentPadding = PaddingValues(vertical = itemSize * 2)
) {
items(4) {
Box(Modifier.testTag("$it").size(itemSize))
}
}
}
}
state.scrollBy(
itemSize * 1.5f + // container size
itemSize * 2 + // start padding
itemSize * 3 // all items
)
rule.onNodeWithTag("3")
.assertIsNotDisplayed()
rule.runOnIdle {
state.assertScrollPosition(3, itemSize * 3.5f)
state.assertVisibleItems(3 to -itemSize * 3.5f)
}
}
// @Test
// fun row_contentPaddingIsApplied() {
// lateinit var state: LazyGridState
// val containerSize = itemSize * 2
// val largePaddingSize = itemSize
// rule.setContent {
// LazyRow(
// modifier = Modifier.requiredSize(containerSize)
// .testTag(LazyListTag),
// state = rememberTvLazyGridState().also { state = it },
// contentPadding = PaddingValues(
// top = smallPaddingSize,
// start = largePaddingSize,
// bottom = smallPaddingSize,
// end = largePaddingSize
// )
// ) {
// items(listOf(1)) {
// Spacer(Modifier.fillParentMaxHeight().width(itemSize).testTag(ItemTag))
// }
// }
// }
// rule.onNodeWithTag(ItemTag)
// .assertTopPositionInRootIsEqualTo(smallPaddingSize)
// .assertLeftPositionInRootIsEqualTo(largePaddingSize)
// .assertHeightIsEqualTo(containerSize - smallPaddingSize * 2)
// .assertWidthIsEqualTo(itemSize)
// state.scrollBy(largePaddingSize)
// rule.onNodeWithTag(ItemTag)
// .assertLeftPositionInRootIsEqualTo(0.dp)
// .assertWidthIsEqualTo(itemSize)
// }
// @Test
// fun row_contentPaddingIsNotAffectingScrollPosition() {
// lateinit var state: LazyGridState
// val itemSize = with(rule.density) {
// 50.dp.roundToPx().toDp()
// }
// rule.setContent {
// LazyRow(
// modifier = Modifier.requiredSize(itemSize * 2)
// .testTag(LazyListTag),
// state = rememberTvLazyGridState().also { state = it },
// contentPadding = PaddingValues(
// start = itemSize,
// end = itemSize
// )
// ) {
// items(listOf(1)) {
// Spacer(Modifier.fillParentMaxHeight().width(itemSize).testTag(ItemTag))
// }
// }
// }
// state.assertScrollPosition(0, 0.dp)
// state.scrollBy(itemSize)
// state.assertScrollPosition(0, itemSize)
// }
// @Test
// fun row_scrollForwardItemWithinStartPaddingDisplayed() {
// lateinit var state: LazyGridState
// val padding = itemSize * 1.5f
// rule.setContent {
// LazyRow(
// modifier = Modifier.requiredSize(padding * 2 + itemSize)
// .testTag(LazyListTag),
// state = rememberTvLazyGridState().also { state = it },
// contentPadding = PaddingValues(
// start = padding,
// end = padding
// )
// ) {
// items((0..3).toList()) {
// Spacer(Modifier.requiredSize(itemSize).testTag(it.toString()))
// }
// }
// }
// rule.onNodeWithTag("0")
// .assertLeftPositionInRootIsEqualTo(padding)
// rule.onNodeWithTag("1")
// .assertLeftPositionInRootIsEqualTo(itemSize + padding)
// rule.onNodeWithTag("2")
// .assertLeftPositionInRootIsEqualTo(itemSize * 2 + padding)
// state.scrollBy(padding)
// state.assertScrollPosition(1, padding - itemSize)
// rule.onNodeWithTag("0")
// .assertLeftPositionInRootIsEqualTo(0.dp)
// rule.onNodeWithTag("1")
// .assertLeftPositionInRootIsEqualTo(itemSize)
// rule.onNodeWithTag("2")
// .assertLeftPositionInRootIsEqualTo(itemSize * 2)
// rule.onNodeWithTag("3")
// .assertLeftPositionInRootIsEqualTo(itemSize * 3)
// }
// @Test
// fun row_scrollBackwardItemWithinStartPaddingDisplayed() {
// lateinit var state: LazyGridState
// val padding = itemSize * 1.5f
// rule.setContent {
// LazyRow(
// modifier = Modifier.requiredSize(itemSize + padding * 2)
// .testTag(LazyListTag),
// state = rememberTvLazyGridState().also { state = it },
// contentPadding = PaddingValues(
// start = padding,
// end = padding
// )
// ) {
// items((0..3).toList()) {
// Spacer(Modifier.requiredSize(itemSize).testTag(it.toString()))
// }
// }
// }
// state.scrollBy(itemSize * 3)
// state.scrollBy(-itemSize * 1.5f)
// state.assertScrollPosition(1, itemSize * 0.5f)
// rule.onNodeWithTag("0")
// .assertLeftPositionInRootIsEqualTo(itemSize * 1.5f - padding)
// rule.onNodeWithTag("1")
// .assertLeftPositionInRootIsEqualTo(itemSize * 2.5f - padding)
// rule.onNodeWithTag("2")
// .assertLeftPositionInRootIsEqualTo(itemSize * 3.5f - padding)
// rule.onNodeWithTag("3")
// .assertLeftPositionInRootIsEqualTo(itemSize * 4.5f - padding)
// }
// @Test
// fun row_scrollForwardTillTheEnd() {
// lateinit var state: LazyGridState
// val padding = itemSize * 1.5f
// rule.setContent {
// LazyRow(
// modifier = Modifier.requiredSize(padding * 2 + itemSize)
// .testTag(LazyListTag),
// state = rememberTvLazyGridState().also { state = it },
// contentPadding = PaddingValues(
// start = padding,
// end = padding
// )
// ) {
// items((0..3).toList()) {
// Spacer(Modifier.requiredSize(itemSize).testTag(it.toString()))
// }
// }
// }
// state.scrollBy(itemSize * 3)
// state.assertScrollPosition(3, 0.dp)
// rule.onNodeWithTag("1")
// .assertLeftPositionInRootIsEqualTo(itemSize - padding)
// rule.onNodeWithTag("2")
// .assertLeftPositionInRootIsEqualTo(itemSize * 2 - padding)
// rule.onNodeWithTag("3")
// .assertLeftPositionInRootIsEqualTo(itemSize * 3 - padding)
// // there are no space to scroll anymore, so it should change nothing
// state.scrollBy(10.dp)
// state.assertScrollPosition(3, 0.dp)
// rule.onNodeWithTag("1")
// .assertLeftPositionInRootIsEqualTo(itemSize - padding)
// rule.onNodeWithTag("2")
// .assertLeftPositionInRootIsEqualTo(itemSize * 2 - padding)
// rule.onNodeWithTag("3")
// .assertLeftPositionInRootIsEqualTo(itemSize * 3 - padding)
// }
// @Test
// fun row_scrollForwardTillTheEndAndABitBack() {
// lateinit var state: LazyGridState
// val padding = itemSize * 1.5f
// rule.setContent {
// LazyRow(
// modifier = Modifier.requiredSize(padding * 2 + itemSize)
// .testTag(LazyListTag),
// state = rememberTvLazyGridState().also { state = it },
// contentPadding = PaddingValues(
// start = padding,
// end = padding
// )
// ) {
// items((0..3).toList()) {
// Spacer(Modifier.requiredSize(itemSize).testTag(it.toString()))
// }
// }
// }
// state.scrollBy(itemSize * 3)
// state.scrollBy(-itemSize / 2)
// state.assertScrollPosition(2, itemSize / 2)
// rule.onNodeWithTag("1")
// .assertLeftPositionInRootIsEqualTo(itemSize * 1.5f - padding)
// rule.onNodeWithTag("2")
// .assertLeftPositionInRootIsEqualTo(itemSize * 2.5f - padding)
// rule.onNodeWithTag("3")
// .assertLeftPositionInRootIsEqualTo(itemSize * 3.5f - padding)
// }
// @Test
// fun row_contentPaddingAndWrapContent() {
// rule.setContent {
// Box(modifier = Modifier.testTag(ContainerTag)) {
// LazyRow(
// contentPadding = PaddingValues(
// start = 2.dp,
// top = 4.dp,
// end = 6.dp,
// bottom = 8.dp
// )
// ) {
// items(listOf(1)) {
// Spacer(Modifier.requiredSize(itemSize).testTag(ItemTag))
// }
// }
// }
// }
// rule.onNodeWithTag(ItemTag)
// .assertLeftPositionInRootIsEqualTo(2.dp)
// .assertTopPositionInRootIsEqualTo(4.dp)
// .assertWidthIsEqualTo(itemSize)
// .assertHeightIsEqualTo(itemSize)
// rule.onNodeWithTag(ContainerTag)
// .assertLeftPositionInRootIsEqualTo(0.dp)
// .assertTopPositionInRootIsEqualTo(0.dp)
// .assertWidthIsEqualTo(itemSize + 2.dp + 6.dp)
// .assertHeightIsEqualTo(itemSize + 4.dp + 8.dp)
// }
// @Test
// fun row_contentPaddingAndNoContent() {
// rule.setContent {
// Box(modifier = Modifier.testTag(ContainerTag)) {
// LazyRow(
// contentPadding = PaddingValues(
// start = 2.dp,
// top = 4.dp,
// end = 6.dp,
// bottom = 8.dp
// )
// ) { }
// }
// }
// rule.onNodeWithTag(ContainerTag)
// .assertLeftPositionInRootIsEqualTo(0.dp)
// .assertTopPositionInRootIsEqualTo(0.dp)
// .assertWidthIsEqualTo(8.dp)
// .assertHeightIsEqualTo(12.dp)
// }
// @Test
// fun row_contentPaddingAndZeroSizedItem() {
// rule.setContent {
// Box(modifier = Modifier.testTag(ContainerTag)) {
// LazyRow(
// contentPadding = PaddingValues(
// start = 2.dp,
// top = 4.dp,
// end = 6.dp,
// bottom = 8.dp
// )
// ) {
// items(0) {}
// }
// }
// }
// rule.onNodeWithTag(ContainerTag)
// .assertLeftPositionInRootIsEqualTo(0.dp)
// .assertTopPositionInRootIsEqualTo(0.dp)
// .assertWidthIsEqualTo(8.dp)
// .assertHeightIsEqualTo(12.dp)
// }
// @Test
// fun row_contentPaddingAndReverseLayout() {
// val startPadding = itemSize * 2
// val endPadding = itemSize / 2
// val listSize = itemSize * 3
// lateinit var state: LazyGridState
// rule.setContentWithTestViewConfiguration {
// LazyRow(
// reverseLayout = true,
// state = rememberTvLazyGridState().also { state = it },
// modifier = Modifier.requiredSize(listSize),
// contentPadding = PaddingValues(start = startPadding, end = endPadding),
// ) {
// items(3) { index ->
// Box(Modifier.requiredSize(itemSize).testTag("$index"))
// }
// }
// }
// rule.onNodeWithTag("0")
// .assertLeftPositionInRootIsEqualTo(listSize - endPadding - itemSize)
// rule.onNodeWithTag("1")
// .assertLeftPositionInRootIsEqualTo(listSize - endPadding - itemSize * 2)
// // Partially visible.
// rule.onNodeWithTag("2")
// .assertLeftPositionInRootIsEqualTo(-itemSize / 2)
// // Scroll to the top.
// state.scrollBy(itemSize * 2.5f)
// rule.onNodeWithTag("2").assertLeftPositionInRootIsEqualTo(startPadding)
// // Shouldn't be visible
// rule.onNodeWithTag("1").assertIsNotDisplayed()
// rule.onNodeWithTag("0").assertIsNotDisplayed()
// }
// @Test
// fun row_overscrollWithContentPadding() {
// lateinit var state: LazyListState
// rule.setContent {
// state = rememberLazyListState()
// Box(modifier = Modifier.testTag(ContainerTag).size(itemSize + smallPaddingSize * 2)) {
// LazyRow(
// state = state,
// contentPadding = PaddingValues(
// horizontal = smallPaddingSize
// )
// ) {
// items(2) {
// Box(Modifier.testTag("$it").fillParentMaxSize())
// }
// }
// }
// }
// rule.onNodeWithTag("0")
// .assertLeftPositionInRootIsEqualTo(smallPaddingSize)
// .assertWidthIsEqualTo(itemSize)
// rule.onNodeWithTag("1")
// .assertLeftPositionInRootIsEqualTo(smallPaddingSize + itemSize)
// .assertWidthIsEqualTo(itemSize)
// rule.runOnIdle {
// runBlocking {
// // itemSizePx is the maximum offset, plus if we overscroll the content padding
// // the layout mechanism will decide the item 0 is not needed until we start
// // filling the over scrolled gap.
// state.scrollBy(value = itemSizePx + smallPaddingSizePx * 1.5f)
// }
// }
// rule.onNodeWithTag("1")
// .assertLeftPositionInRootIsEqualTo(smallPaddingSize)
// .assertWidthIsEqualTo(itemSize)
// rule.onNodeWithTag("0")
// .assertLeftPositionInRootIsEqualTo(smallPaddingSize - itemSize)
// .assertWidthIsEqualTo(itemSize)
// }
private fun TvLazyGridState.scrollBy(offset: Dp) {
runBlocking(Dispatchers.Main + AutoTestFrameClock()) {
animateScrollBy(with(rule.density) { offset.roundToPx().toFloat() }, snap())
}
}
private fun TvLazyGridState.assertScrollPosition(index: Int, offset: Dp) = with(rule.density) {
assertThat([email protected]).isEqualTo(index)
assertThat(firstVisibleItemScrollOffset.toDp().value).isWithin(0.5f).of(offset.value)
}
private fun TvLazyGridState.assertLayoutInfoOffsetRange(from: Dp, to: Dp) = with(rule.density) {
assertThat(layoutInfo.viewportStartOffset to layoutInfo.viewportEndOffset)
.isEqualTo(from.roundToPx() to to.roundToPx())
}
private fun TvLazyGridState.assertVisibleItems(vararg expected: Pair<Int, Dp>) =
with(rule.density) {
assertThat(layoutInfo.visibleItemsInfo.map { it.index to it.offset.y })
.isEqualTo(expected.map { it.first to it.second.roundToPx() })
}
fun TvLazyGridState.scrollTo(index: Int) {
runBlocking(Dispatchers.Main + AutoTestFrameClock()) {
scrollToItem(index)
}
}
}
| apache-2.0 | cb4722d99236b23c266cd8f8569e80f4 | 34.16335 | 101 | 0.541632 | 5.119763 | false | true | false | false |
GunoH/intellij-community | plugins/markdown/core/src/org/intellij/plugins/markdown/extensions/jcef/commandRunner/CommandRunnerExtension.kt | 4 | 13526 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.intellij.plugins.markdown.extensions.jcef.commandRunner
import com.intellij.execution.Executor
import com.intellij.execution.ExecutorRegistry
import com.intellij.execution.executors.DefaultRunExecutor
import com.intellij.icons.AllIcons
import com.intellij.ide.actions.runAnything.RunAnythingAction
import com.intellij.ide.actions.runAnything.RunAnythingContext
import com.intellij.ide.actions.runAnything.RunAnythingRunConfigurationProvider
import com.intellij.ide.actions.runAnything.activity.RunAnythingCommandProvider
import com.intellij.ide.actions.runAnything.activity.RunAnythingProvider
import com.intellij.ide.actions.runAnything.activity.RunAnythingRecentProjectProvider
import com.intellij.openapi.actionSystem.*
import com.intellij.openapi.actionSystem.impl.SimpleDataContext
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.invokeLater
import com.intellij.openapi.application.runReadAction
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.ui.AppUIUtil
import org.intellij.plugins.markdown.MarkdownBundle
import org.intellij.plugins.markdown.MarkdownUsageCollector.Companion.RUNNER_EXECUTED
import org.intellij.plugins.markdown.extensions.MarkdownBrowserPreviewExtension
import org.intellij.plugins.markdown.extensions.MarkdownExtensionsUtil
import org.intellij.plugins.markdown.injection.aliases.CodeFenceLanguageGuesser
import org.intellij.plugins.markdown.settings.MarkdownExtensionsSettings
import org.intellij.plugins.markdown.ui.preview.MarkdownHtmlPanel
import org.intellij.plugins.markdown.ui.preview.ResourceProvider
import org.intellij.plugins.markdown.ui.preview.html.MarkdownUtil
import java.util.concurrent.ConcurrentHashMap
internal class CommandRunnerExtension(
val panel: MarkdownHtmlPanel,
private val provider: Provider
): MarkdownBrowserPreviewExtension {
override val scripts: List<String> = listOf("commandRunner/commandRunner.js")
override val styles: List<String> = listOf("commandRunner/commandRunner.css")
private val hash2Cmd = mutableMapOf<String, String>()
init {
panel.browserPipe?.subscribe(RUN_LINE_EVENT, this::runLine)
panel.browserPipe?.subscribe(RUN_BLOCK_EVENT, this::runBlock)
Disposer.register(this) {
panel.browserPipe?.removeSubscription(RUN_LINE_EVENT, ::runLine)
panel.browserPipe?.removeSubscription(RUN_BLOCK_EVENT, ::runBlock)
}
}
override val resourceProvider: ResourceProvider = ResourceProvider.aggregating(
CommandRunnerResourceProvider(),
CommandRunnerIconsResourceProvider()
)
private inner class CommandRunnerResourceProvider: ResourceProvider {
override fun canProvide(resourceName: String): Boolean {
return resourceName in scripts || resourceName in styles
}
override fun loadResource(resourceName: String): ResourceProvider.Resource? {
return ResourceProvider.loadInternalResource<CommandRunnerResourceProvider>(resourceName)
}
}
private class CommandRunnerIconsResourceProvider: ResourceProvider {
override fun canProvide(resourceName: String): Boolean {
return resourceName in icons
}
override fun loadResource(resourceName: String): ResourceProvider.Resource? {
val icon = when (resourceName) {
RUN_LINE_ICON -> AllIcons.RunConfigurations.TestState.Run
RUN_BLOCK_ICON -> AllIcons.RunConfigurations.TestState.Run_run
else -> return null
}
val format = resourceName.substringAfterLast(".")
return ResourceProvider.Resource(MarkdownExtensionsUtil.loadIcon(icon, format))
}
companion object {
private val icons = setOf(RUN_LINE_ICON, RUN_BLOCK_ICON)
}
}
fun processCodeLine(rawCodeLine: String, insideFence: Boolean): String {
processLine(rawCodeLine, !insideFence)?.let { hash ->
return getHtmlForLineRunner(insideFence, hash)
}
return ""
}
private fun processLine(rawCodeLine: String, allowRunConfigurations: Boolean): String? {
try {
val project = panel.project
val file = panel.virtualFile
if (project != null && file != null && file.parent != null
&& matches(project, file.parent.canonicalPath, true, rawCodeLine.trim(), allowRunConfigurations)
) {
val hash = MarkdownUtil.md5(rawCodeLine, "")
hash2Cmd[hash] = rawCodeLine
return hash
}
else return null
}
catch (e: Exception) {
LOG.warn(e)
return null
}
}
private fun getHtmlForLineRunner(insideFence: Boolean, hash: String): String {
val cssClass = "run-icon" + if (insideFence) " code-block" else ""
return "<a class='$cssClass' href='#' role='button' data-command='${DefaultRunExecutor.EXECUTOR_ID}:$hash'>" +
"<img src='$RUN_LINE_ICON'>" +
"</a>"
}
fun processCodeBlock(codeFenceRawContent: String, language: String): String {
try {
val lang = CodeFenceLanguageGuesser.guessLanguageForInjection(language)
val runner = MarkdownRunner.EP_NAME.extensionList.firstOrNull {
it.isApplicable(lang)
}
if (runner == null) return ""
val hash = MarkdownUtil.md5(codeFenceRawContent, "")
hash2Cmd[hash] = codeFenceRawContent
val lines = codeFenceRawContent.trimEnd().lines()
val firstLineHash = if (lines.size > 1) processLine(lines[0], false) else null
val firstLineData = if (firstLineHash.isNullOrBlank()) "" else "data-firstLine='$firstLineHash'"
val cssClass = "run-icon code-block"
return "<a class='${cssClass}' href='#' role='button' " +
"data-command='${DefaultRunExecutor.EXECUTOR_ID}:$hash' " +
"data-commandtype='block'" +
firstLineData +
">" +
"<img src='$RUN_BLOCK_ICON'>" +
"</a>"
}
catch (e: Exception) {
LOG.warn(e)
return ""
}
}
private fun runLine(encodedLine: String) {
val executorId = encodedLine.substringBefore(":")
val cmdHash: String = encodedLine.substringAfter(":")
val command = hash2Cmd[cmdHash]
if (command == null) {
LOG.error("Command index $cmdHash not found. Please attach .md file to error report. commandCache = ${hash2Cmd}")
return
}
executeLineCommand(command, executorId)
}
private fun executeLineCommand(command: String, executorId: String) {
val executor = ExecutorRegistry.getInstance().getExecutorById(executorId) ?: DefaultRunExecutor.getRunExecutorInstance()
val project = panel.project
val virtualFile = panel.virtualFile
if (project != null && virtualFile != null) {
execute(project, virtualFile.parent.canonicalPath, true, command, executor, RunnerPlace.PREVIEW)
}
}
private fun executeBlock(command: String, executorId: String) {
val runner = MarkdownRunner.EP_NAME.extensionList.first()
val executor = ExecutorRegistry.getInstance().getExecutorById(executorId) ?: DefaultRunExecutor.getRunExecutorInstance()
val project = panel.project
val virtualFile = panel.virtualFile
if (project != null && virtualFile != null) {
TrustedProjectUtil.executeIfTrusted(project) {
RUNNER_EXECUTED.log(project, RunnerPlace.PREVIEW, RunnerType.BLOCK, runner.javaClass)
invokeLater {
runner.run(command, project, virtualFile.parent.canonicalPath, executor)
}
}
}
}
private fun runBlock(encodedLine: String) {
val args = encodedLine.split(":")
val executorId = args[0]
val cmdHash: String = args[1]
val command = hash2Cmd[cmdHash]
val firstLineCommand = hash2Cmd[args[2]]
if (command == null) {
LOG.error("Command hash $cmdHash not found. Please attach .md file to error report.\n${hash2Cmd}")
return
}
val trimmedCmd = trimPrompt(command)
if (firstLineCommand == null) {
ApplicationManager.getApplication().invokeLater {
executeBlock(trimmedCmd, executorId)
}
return
}
val x = args[3].toInt()
val y = args[4].toInt()
val actionManager = ActionManager.getInstance()
val actionGroup = DefaultActionGroup()
val runBlockAction = object : AnAction({ MarkdownBundle.message("markdown.runner.launch.block") },
AllIcons.RunConfigurations.TestState.Run_run) {
override fun actionPerformed(e: AnActionEvent) {
ApplicationManager.getApplication().invokeLater {
executeBlock(trimmedCmd, executorId)
}
}
}
val runLineAction = object : AnAction({ MarkdownBundle.message("markdown.runner.launch.line") },
AllIcons.RunConfigurations.TestState.Run) {
override fun actionPerformed(e: AnActionEvent) {
ApplicationManager.getApplication().invokeLater {
executeLineCommand(firstLineCommand, executorId)
}
}
}
actionGroup.add(runBlockAction)
actionGroup.add(runLineAction)
AppUIUtil.invokeOnEdt {
actionManager.createActionPopupMenu(ActionPlaces.EDITOR_GUTTER_POPUP, actionGroup)
.component.show(panel.component, x, y)
}
}
override fun dispose() {
provider.extensions.remove(panel.virtualFile)
}
class Provider: MarkdownBrowserPreviewExtension.Provider {
val extensions = ConcurrentHashMap<VirtualFile, CommandRunnerExtension>()
override fun createBrowserExtension(panel: MarkdownHtmlPanel): MarkdownBrowserPreviewExtension? {
val virtualFile = panel.virtualFile ?: return null
if (!isExtensionEnabled()) {
return null
}
return extensions.computeIfAbsent(virtualFile) { CommandRunnerExtension(panel, this) }
}
}
companion object {
private const val RUN_LINE_EVENT = "runLine"
private const val RUN_BLOCK_EVENT = "runBlock"
private const val RUN_LINE_ICON = "commandRunner/run.png"
private const val RUN_BLOCK_ICON = "commandRunner/runrun.png"
const val extensionId = "MarkdownCommandRunnerExtension"
fun isExtensionEnabled(): Boolean {
return MarkdownExtensionsSettings.getInstance().extensionsEnabledState[extensionId] ?: true
}
fun getRunnerByFile(file: VirtualFile) : CommandRunnerExtension? {
val provider = MarkdownExtensionsUtil.findBrowserExtensionProvider<Provider>()
return provider?.extensions?.get(file)
}
fun matches(project: Project, workingDirectory: String?, localSession: Boolean,
command: String,
allowRunConfigurations: Boolean = false): Boolean {
val trimmedCmd = command.trim()
if (trimmedCmd.isEmpty()) return false
val dataContext = createDataContext(project, localSession, workingDirectory)
return runReadAction {
RunAnythingProvider.EP_NAME.extensionList.asSequence()
.filter { checkForCLI(it, allowRunConfigurations) }
.any { provider -> provider.findMatchingValue(dataContext, trimmedCmd) != null }
}
}
fun execute(
project: Project,
workingDirectory: String?,
localSession: Boolean,
command: String,
executor: Executor,
place: RunnerPlace
): Boolean {
val dataContext = createDataContext(project, localSession, workingDirectory, executor)
val trimmedCmd = command.trim()
return runReadAction {
for (provider in RunAnythingProvider.EP_NAME.extensionList) {
val value = provider.findMatchingValue(dataContext, trimmedCmd) ?: continue
return@runReadAction TrustedProjectUtil.executeIfTrusted(project) {
RUNNER_EXECUTED.log(project, place, RunnerType.LINE, provider.javaClass)
invokeLater {
provider.execute(dataContext, value)
}
}
}
return@runReadAction false
}
}
private fun createDataContext(project: Project, localSession: Boolean, workingDirectory: String?, executor: Executor? = null): DataContext {
val virtualFile = if (localSession && workingDirectory != null)
LocalFileSystem.getInstance().findFileByPath(workingDirectory) else null
return SimpleDataContext.builder()
.add(CommonDataKeys.PROJECT, project)
.add(RunAnythingAction.EXECUTOR_KEY, executor)
.apply {
if (virtualFile != null) {
add(CommonDataKeys.VIRTUAL_FILE, virtualFile)
add(RunAnythingProvider.EXECUTING_CONTEXT, RunAnythingContext.RecentDirectoryContext(virtualFile.path))
}
}
.build()
}
private fun checkForCLI(it: RunAnythingProvider<*>?, allowRunConfigurations: Boolean): Boolean {
return (it !is RunAnythingCommandProvider
&& it !is RunAnythingRecentProjectProvider
&& (it !is RunAnythingRunConfigurationProvider || allowRunConfigurations))
}
private val LOG = logger<CommandRunnerExtension>()
internal fun trimPrompt(cmd: String): String {
return cmd.lines()
.filter { line -> line.isNotEmpty() }
.joinToString("\n") { line ->
if (line.startsWith("$")) line.substringAfter("$") else line
}
}
}
}
enum class RunnerPlace {
EDITOR, PREVIEW
}
enum class RunnerType {
BLOCK, LINE
} | apache-2.0 | 88e13ab2cd5c684946b8578228b86d1b | 38.095376 | 158 | 0.707378 | 4.943713 | false | false | false | false |
GunoH/intellij-community | plugins/search-everywhere-ml/src/com/intellij/ide/actions/searcheverywhere/ml/features/statistician/SearchEverywhereFileStatistician.kt | 4 | 1344 | package com.intellij.ide.actions.searcheverywhere.ml.features.statistician
import com.intellij.ide.actions.searcheverywhere.PSIPresentationBgRendererWrapper.PsiItemWithPresentation
import com.intellij.openapi.application.runReadAction
import com.intellij.openapi.module.Module
import com.intellij.openapi.roots.ProjectRootManager
import com.intellij.psi.PsiFileSystemItem
private class SearchEverywhereFileStatistician : SearchEverywhereStatistician<Any>(PsiFileSystemItem::class.java,
PsiItemWithPresentation::class.java) {
override fun getValue(element: Any, location: String) = getFileWithVirtualFile(element)
?.virtualFile
?.path
override fun getContext(element: Any): String? = getFileWithVirtualFile(element)
?.let { getModule(it) }
?.let { "$contextPrefix#${it.name}" }
private fun getModule(file: PsiFileSystemItem): Module? = runReadAction {
val fileIndex = ProjectRootManager.getInstance(file.project).fileIndex
fileIndex.getModuleForFile(file.virtualFile)
}
private fun getFileWithVirtualFile(element: Any): PsiFileSystemItem? = when (element) {
is PsiItemWithPresentation -> (element.item as? PsiFileSystemItem)
is PsiFileSystemItem -> element
else -> null
}?.takeIf { it.virtualFile != null }
}
| apache-2.0 | edd041286b6de77999f30e96c7d08ac6 | 45.344828 | 121 | 0.741071 | 5.014925 | false | false | false | false |
GunoH/intellij-community | platform/execution-impl/src/com/intellij/execution/target/TargetEnvironmentWizardStepKt.kt | 2 | 3655 | // 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.target
import com.intellij.execution.ExecutionBundle
import com.intellij.openapi.ui.DialogPanel
import com.intellij.openapi.util.ClearableLazyValue
import com.intellij.openapi.util.NlsContexts
import com.intellij.openapi.util.NlsSafe
import com.intellij.openapi.util.text.HtmlChunk
import com.intellij.ui.AnimatedIcon
import com.intellij.ui.components.JBLabel
import com.intellij.ui.components.panels.HorizontalLayout
import com.intellij.ui.scale.JBUIScale
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.UIUtil
import org.jetbrains.annotations.Nls
import java.awt.BorderLayout
import javax.swing.JComponent
import javax.swing.JPanel
import javax.swing.border.CompoundBorder
abstract class TargetEnvironmentWizardStepKt(@NlsContexts.DialogTitle title: String) : TargetEnvironmentWizardStep(title) {
private val panel = object : ClearableLazyValue<JComponent>() {
override fun compute(): JComponent = createPanel()
}
private val stepDescriptionLabel = JBLabel(ExecutionBundle.message("run.on.targets.wizard.step.description"))
private val spinningLabel = JBLabel(AnimatedIcon.Default()).also {
it.isVisible = false
}
protected var stepDescription: @NlsContexts.Label String
@NlsContexts.Label get() = stepDescriptionLabel.text
set(@NlsContexts.Label value) {
stepDescriptionLabel.text = value
}
protected fun setSpinningVisible(visible: Boolean) {
spinningLabel.isVisible = visible
with(component) {
revalidate()
repaint()
}
}
final override fun getComponent() = panel.value
protected open fun createPanel(): JComponent {
val result = JPanel(BorderLayout(HGAP, LARGE_VGAP))
val top = createTopPanel()
result.add(top, BorderLayout.NORTH)
val mainPanel = createMainPanel()
val center = JPanel(BorderLayout())
center.add(mainPanel, BorderLayout.CENTER)
val lineBorder = JBUI.Borders.customLine(JBUI.CurrentTheme.CustomFrameDecorations.separatorForeground(), 1, 0, 1, 0)
center.border = if (mainPanel is DialogPanel) {
val mainDialogPanelInsets = JBUI.Borders.empty(UIUtil.LARGE_VGAP, TargetEnvironmentWizard.defaultDialogInsets().right)
CompoundBorder(lineBorder, mainDialogPanelInsets)
}
else {
lineBorder
}
result.add(center, BorderLayout.CENTER)
return result
}
private fun createTopPanel(): JComponent {
return JPanel(HorizontalLayout(ICON_GAP)).also {
val insets = TargetEnvironmentWizard.defaultDialogInsets()
it.border = JBUI.Borders.merge(JBUI.Borders.emptyTop(LARGE_VGAP),
JBUI.Borders.empty(0, insets.left, 0, insets.right),
true)
it.add(stepDescriptionLabel)
spinningLabel.isVisible = false
it.add(spinningLabel)
}
}
protected open fun createMainPanel(): JComponent {
return JPanel()
}
override fun dispose() {
super.dispose()
panel.drop()
}
companion object {
@JvmStatic
val ICON_GAP = JBUIScale.scale(6)
@JvmStatic
val HGAP = JBUIScale.scale(UIUtil.DEFAULT_HGAP)
@JvmStatic
val VGAP = JBUIScale.scale(UIUtil.DEFAULT_VGAP)
@JvmStatic
val LARGE_VGAP = JBUIScale.scale(UIUtil.LARGE_VGAP)
@JvmStatic
@Nls
fun formatStepLabel(step: Int, totalSteps: Int = 3, @Nls message: String): String {
@NlsSafe val description = "$step/$totalSteps. $message"
return HtmlChunk.text(description).wrapWith(HtmlChunk.html()).toString()
}
}
} | apache-2.0 | a7dc596fe8954c41309c6829a2545f8f | 31.642857 | 124 | 0.726676 | 4.335706 | false | false | false | false |
GunoH/intellij-community | platform/usageView-impl/src/com/intellij/usages/impl/usageFilteringRuleActions.kt | 3 | 1714 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
@file:JvmName("UsageFilteringRuleActions")
package com.intellij.usages.impl
import com.intellij.openapi.actionSystem.*
import com.intellij.openapi.project.DumbAware
import com.intellij.openapi.project.Project
import com.intellij.usages.impl.rules.usageFilteringRules
import com.intellij.usages.rules.UsageFilteringRuleProvider
internal fun usageFilteringRuleActions(project: Project, ruleState: UsageFilteringRuleState): List<AnAction> {
val rwAwareState = UsageFilteringRuleStateRWAware(ruleState)
val actionManager = ActionManager.getInstance()
val result = ArrayList<AnAction>()
for (rule in usageFilteringRules(project)) {
val action: AnAction = actionManager.getAction(rule.actionId)
?: continue
check(action is EmptyAction)
result.add(UsageFilteringRuleAction(action, rwAwareState, rule.ruleId))
}
return result
}
private class UsageFilteringRuleAction(
prototype: EmptyAction,
private val ruleState: UsageFilteringRuleState,
private val ruleId: String,
) : ToggleAction(), DumbAware {
init {
templatePresentation.copyFrom(prototype.templatePresentation)
shortcutSet = prototype.shortcutSet
}
override fun isSelected(e: AnActionEvent): Boolean = !ruleState.isActive(ruleId)
override fun setSelected(e: AnActionEvent, state: Boolean) {
ruleState.setActive(ruleId, !state)
val project = e.project ?: return
project.messageBus.syncPublisher(UsageFilteringRuleProvider.RULES_CHANGED).run()
}
override fun getActionUpdateThread() = ActionUpdateThread.EDT
}
| apache-2.0 | 5e296b7bf11848d59408d4de2f7f2b41 | 37.088889 | 158 | 0.778296 | 4.632432 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/frontend-independent/src/org/jetbrains/kotlin/idea/search/ideaExtensions/KotlinOverridingMethodReferenceSearcher.kt | 1 | 5728 | // 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.search.ideaExtensions
import com.intellij.psi.*
import com.intellij.psi.impl.search.MethodTextOccurrenceProcessor
import com.intellij.psi.impl.search.MethodUsagesSearcher
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.psi.search.UsageSearchContext
import com.intellij.psi.search.searches.MethodReferencesSearch
import com.intellij.psi.util.MethodSignatureUtil
import com.intellij.psi.util.TypeConversionUtil
import com.intellij.util.Processor
import org.jetbrains.kotlin.idea.asJava.LightClassProvider.Companion.providedToLightMethods
import org.jetbrains.kotlin.idea.references.KtSimpleNameReference
import org.jetbrains.kotlin.idea.references.SyntheticPropertyAccessorReference
import org.jetbrains.kotlin.idea.references.readWriteAccess
import org.jetbrains.kotlin.idea.search.restrictToKotlinSources
import org.jetbrains.kotlin.idea.util.application.runReadActionInSmartMode
import org.jetbrains.kotlin.load.java.JvmAbi
import org.jetbrains.kotlin.load.java.getPropertyNamesCandidatesByAccessorName
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.psi.KtCallableDeclaration
import org.jetbrains.kotlin.psi.KtNamedFunction
import org.jetbrains.kotlin.psi.KtParameter
import org.jetbrains.kotlin.psi.KtProperty
class KotlinOverridingMethodReferenceSearcher : MethodUsagesSearcher() {
override fun processQuery(p: MethodReferencesSearch.SearchParameters, consumer: Processor<in PsiReference>) {
val method = p.method
val isConstructor = p.project.runReadActionInSmartMode { method.isConstructor }
if (isConstructor) {
return
}
val searchScope = p.project.runReadActionInSmartMode {
p.effectiveSearchScope
.intersectWith(method.useScope)
.restrictToKotlinSources()
}
if (searchScope === GlobalSearchScope.EMPTY_SCOPE) return
super.processQuery(MethodReferencesSearch.SearchParameters(method, searchScope, p.isStrictSignatureSearch, p.optimizer), consumer)
p.project.runReadActionInSmartMode {
val containingClass = method.containingClass ?: return@runReadActionInSmartMode
val nameCandidates = getPropertyNamesCandidatesByAccessorName(Name.identifier(method.name))
for (name in nameCandidates) {
p.optimizer.searchWord(
name.asString(),
searchScope,
UsageSearchContext.IN_CODE,
true,
method,
getTextOccurrenceProcessor(arrayOf(method), containingClass, false)
)
}
}
}
override fun getTextOccurrenceProcessor(
methods: Array<out PsiMethod>,
aClass: PsiClass,
strictSignatureSearch: Boolean
): MethodTextOccurrenceProcessor {
return object : MethodTextOccurrenceProcessor(aClass, strictSignatureSearch, *methods) {
override fun processInexactReference(
ref: PsiReference,
refElement: PsiElement?,
method: PsiMethod,
consumer: Processor<in PsiReference>
): Boolean {
val isGetter = JvmAbi.isGetterName(method.name)
fun isWrongAccessorReference(): Boolean {
if (ref is KtSimpleNameReference) {
val readWriteAccess = ref.expression.readWriteAccess(true)
return readWriteAccess.isRead != isGetter && readWriteAccess.isWrite == isGetter
}
if (ref is SyntheticPropertyAccessorReference) {
return ref.getter != isGetter
}
return false
}
if (refElement !is KtCallableDeclaration) {
if (isWrongAccessorReference()) return true
if (refElement !is PsiMethod) return true
val refMethodClass = refElement.containingClass ?: return true
val substitutor = TypeConversionUtil.getClassSubstitutor(myContainingClass, refMethodClass, PsiSubstitutor.EMPTY)
if (substitutor != null) {
val superSignature = method.getSignature(substitutor)
val refSignature = refElement.getSignature(PsiSubstitutor.EMPTY)
if (MethodSignatureUtil.isSubsignature(superSignature, refSignature)) {
return super.processInexactReference(ref, refElement, method, consumer)
}
}
return true
}
fun countNonFinalLightMethods() = refElement
.providedToLightMethods()
.filterNot { it.hasModifierProperty(PsiModifier.FINAL) }
val lightMethods = when (refElement) {
is KtProperty, is KtParameter -> {
if (isWrongAccessorReference()) return true
countNonFinalLightMethods().filter { JvmAbi.isGetterName(it.name) == isGetter }
}
is KtNamedFunction ->
countNonFinalLightMethods().filter { it.name == method.name }
else ->
countNonFinalLightMethods()
}
return lightMethods.all { super.processInexactReference(ref, it, method, consumer) }
}
}
}
} | apache-2.0 | 66a9920a6a5a4783c0158256b28935a2 | 44.110236 | 158 | 0.643156 | 5.751004 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/frontend-fir/src/org/jetbrains/kotlin/idea/frontend/api/fir/scopes/KtFirNonStarImportingScope.kt | 1 | 3065 | /*
* Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.idea.frontend.api.fir.scopes
import org.jetbrains.kotlin.fir.scopes.impl.FirAbstractSimpleImportingScope
import org.jetbrains.kotlin.fir.scopes.impl.FirDefaultSimpleImportingScope
import org.jetbrains.kotlin.idea.frontend.api.ValidityTokenOwner
import org.jetbrains.kotlin.idea.frontend.api.ValidityToken
import org.jetbrains.kotlin.idea.frontend.api.fir.KtSymbolByFirBuilder
import org.jetbrains.kotlin.idea.frontend.api.fir.utils.cached
import org.jetbrains.kotlin.idea.frontend.api.fir.utils.weakRef
import org.jetbrains.kotlin.idea.frontend.api.scopes.KtNonStarImportingScope
import org.jetbrains.kotlin.idea.frontend.api.scopes.KtScopeNameFilter
import org.jetbrains.kotlin.idea.frontend.api.scopes.NonStarImport
import org.jetbrains.kotlin.idea.frontend.api.symbols.KtCallableSymbol
import org.jetbrains.kotlin.idea.frontend.api.symbols.KtClassifierSymbol
import org.jetbrains.kotlin.idea.frontend.api.symbols.KtConstructorSymbol
import org.jetbrains.kotlin.idea.frontend.api.withValidityAssertion
import org.jetbrains.kotlin.name.Name
internal class KtFirNonStarImportingScope(
firScope: FirAbstractSimpleImportingScope,
private val builder: KtSymbolByFirBuilder,
override val token: ValidityToken
) : KtNonStarImportingScope, ValidityTokenOwner {
private val firScope: FirAbstractSimpleImportingScope by weakRef(firScope)
@OptIn(ExperimentalStdlibApi::class)
override val imports: List<NonStarImport> by cached {
buildList {
firScope.simpleImports.values.forEach { imports ->
imports.forEach { import ->
NonStarImport(
import.packageFqName,
import.relativeClassName,
import.resolvedClassId,
import.importedName
).let(::add)
}
}
}
}
override fun getCallableSymbols(nameFilter: KtScopeNameFilter): Sequence<KtCallableSymbol> = withValidityAssertion {
firScope.getCallableSymbols(getCallableNames().filter(nameFilter), builder)
}
override fun getClassifierSymbols(nameFilter: KtScopeNameFilter): Sequence<KtClassifierSymbol> = withValidityAssertion {
firScope.getClassifierSymbols(getClassifierNames().filter(nameFilter), builder)
}
override fun getConstructors(): Sequence<KtConstructorSymbol> = emptySequence()
override fun getCallableNames(): Set<Name> = withValidityAssertion {
imports.mapNotNullTo(hashSetOf()) { it.callableName }
}
override fun getClassifierNames(): Set<Name> = withValidityAssertion {
imports.mapNotNullTo((hashSetOf())) { it.relativeClassName?.shortName() }
}
override val isDefaultImportingScope: Boolean = withValidityAssertion { firScope is FirDefaultSimpleImportingScope }
}
| apache-2.0 | f6ec1d9e16cd893902fc6ad5f44fb2a4 | 45.439394 | 124 | 0.751713 | 4.650986 | false | false | false | false |
JetBrains/kotlin-native | runtime/src/main/kotlin/kotlin/native/internal/KFunctionImpl.kt | 2 | 1117 | /*
* 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 kotlin.native.internal
import kotlin.reflect.KFunction
import kotlin.reflect.KType
@FixmeReflection
internal abstract class KFunctionImpl<out R>(
override val name: String, val fqName: String, val receiver: Any?,
val arity: Int, val flags: Int, override val returnType: KType
): KFunction<R> {
override fun equals(other: Any?): Boolean {
if (other !is KFunctionImpl<*>) return false
return fqName == other.fqName && receiver == other.receiver
&& arity == other.arity && flags == other.flags
}
private fun evalutePolynom(x: Int, vararg coeffs: Int): Int {
var res = 0
for (coeff in coeffs)
res = res * x + coeff
return res
}
override fun hashCode() = evalutePolynom(31, fqName.hashCode(), receiver.hashCode(), arity, flags)
override fun toString(): String {
return "${if (name == "<init>") "constructor" else "function " + name}"
}
} | apache-2.0 | f0fdaeb4b547f3c9e7b13864fd068d8d | 31.882353 | 102 | 0.644584 | 4.017986 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/inspectionsLocal/branched/ifThenToElvis/notApplicableForLocalUnstableVar.kt | 9 | 299 | // WITH_STDLIB
// PROBLEM: none
fun maybeFoo(): String? {
return "foo"
}
fun capture(block: () -> Unit): Unit = Unit
fun test(): String? {
var foo = maybeFoo()
capture {
foo = null
}
val bar = if (foo == null<caret>)
42
else
foo
return foo
}
| apache-2.0 | 17fb700fca5e6507807e36081c66eb2d | 12.590909 | 43 | 0.511706 | 3.559524 | false | false | false | false |
smmribeiro/intellij-community | plugins/maven/src/main/java/org/jetbrains/idea/maven/externalSystemIntegration/output/importproject/quickfixes/RepositoryBlockedSyncIssue.kt | 1 | 3464 | // 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.idea.maven.externalSystemIntegration.output.importproject.quickfixes
import com.intellij.build.issue.BuildIssue
import com.intellij.build.issue.BuildIssueQuickFix
import com.intellij.build.issue.quickfix.OpenFileQuickFix
import com.intellij.execution.filters.UrlFilter
import com.intellij.find.FindModel
import com.intellij.find.findInProject.FindInProjectManager
import com.intellij.openapi.actionSystem.DataContext
import com.intellij.openapi.project.Project
import com.intellij.pom.Navigatable
import org.jetbrains.idea.maven.buildtool.quickfix.OpenMavenSettingsQuickFix
import org.jetbrains.idea.maven.execution.SyncBundle.message
import org.jetbrains.idea.maven.project.MavenProjectsManager
import java.util.concurrent.CompletableFuture
object RepositoryBlockedSyncIssue {
@JvmStatic
fun getIssue(project: Project, title: String): BuildIssue {
val quickFixes = mutableListOf<BuildIssueQuickFix>()
val issueDescription = StringBuilder(title)
issueDescription.append("\n\n")
.append(message("maven.sync.quickfixes.repository.blocked"))
.append("\n")
val openSettingsXmlQuickFix = MavenProjectsManager.getInstance(project).generalSettings.effectiveUserSettingsIoFile
?.let { if (it.exists()) it else null }
?.toPath()
?.let {
val quickFix = OpenFileQuickFix(it, null)
quickFixes.add(quickFix)
issueDescription
.append(message("maven.sync.quickfixes.repository.blocked.show.settings", quickFix.id))
.append("\n")
quickFix
}
val repoUrls = UrlFilter().applyFilter(title, title.length)
?.resultItems!!
.asSequence()
.filter { it != null }
.map { title.substring(it.highlightStartOffset, it.highlightEndOffset) }
.filter { !it.contains("0.0.0.0", false) }
.toList()
repoUrls.forEach {
val quickFix = FindBlockedRepositoryQuickFix(it)
quickFixes.add(quickFix)
issueDescription
.append(message("maven.sync.quickfixes.repository.blocked.find.repository", quickFix.id, it))
.append("\n")
}
issueDescription
.append(message("maven.sync.quickfixes.repository.blocked.add.mirror", repoUrls.joinToString(),
openSettingsXmlQuickFix?.id ?: ""))
.append("\n")
val quickFix = OpenMavenSettingsQuickFix()
quickFixes.add(quickFix)
issueDescription
.append(message("maven.sync.quickfixes.repository.blocked.downgrade", quickFix.id))
.append("\n")
return object : BuildIssue {
override val title: String = title
override val description: String = issueDescription.toString()
override val quickFixes = quickFixes
override fun getNavigatable(project: Project): Navigatable? = null
}
}
}
class FindBlockedRepositoryQuickFix(val repoUrl: String) : BuildIssueQuickFix {
override val id: String get() = "maven_find_blocked_repository_quick_fix_$repoUrl"
override fun runQuickFix(project: Project, dataContext: DataContext): CompletableFuture<*> {
val findModel = FindModel()
findModel.stringToFind = repoUrl
findModel.isProjectScope = true
FindInProjectManager.getInstance(project).findInProject(dataContext, findModel)
return CompletableFuture.completedFuture(null)
}
}
| apache-2.0 | 27c9deeafdd250dfe9b3cd90e9d1dd4c | 37.921348 | 158 | 0.733256 | 4.539974 | false | false | false | false |
smmribeiro/intellij-community | plugins/svn4idea/src/org/jetbrains/idea/svn/api/Target.kt | 19 | 851 | // Copyright 2000-2017 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.idea.svn.api
import java.io.File
class Target private constructor(val url: Url?, val file: File?, pegRevision: Revision?) {
val pegRevision: Revision = pegRevision ?: Revision.UNDEFINED
val path: String get() = if (isFile()) file!!.path else url!!.toString()
fun isFile(): Boolean = file != null
fun isUrl(): Boolean = url != null
override fun toString(): String = path + '@' + pegRevision
companion object {
@JvmStatic
@JvmOverloads
fun on(url: Url, pegRevision: Revision? = null): Target = Target(url, null, pegRevision)
@JvmStatic
@JvmOverloads
fun on(file: File, pegRevision: Revision? = null): Target = Target(null, file, pegRevision)
}
}
| apache-2.0 | 649f290dfaa0038be4237720295ddc43 | 34.458333 | 140 | 0.695652 | 3.782222 | false | false | false | false |
smmribeiro/intellij-community | java/java-impl/src/com/intellij/refactoring/extractMethod/newImpl/ExtractSelector.kt | 1 | 5660 | // 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.refactoring.extractMethod.newImpl
import com.intellij.codeInsight.CodeInsightUtil
import com.intellij.openapi.util.TextRange
import com.intellij.psi.*
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.refactoring.introduceVariable.IntroduceVariableBase
import com.intellij.refactoring.util.RefactoringUtil
class ExtractSelector {
private fun findElementsInRange(file: PsiFile, range: TextRange): List<PsiElement> {
val expression = CodeInsightUtil.findExpressionInRange(file, range.startOffset, range.endOffset)
if (expression != null) return listOf(expression)
val statements = CodeInsightUtil.findStatementsInRange(file, range.startOffset, range.endOffset)
if (statements.isNotEmpty()) return statements.toList()
val subExpression = IntroduceVariableBase.getSelectedExpression(file.project, file, range.startOffset, range.endOffset)
if (subExpression != null && IntroduceVariableBase.getErrorMessage(subExpression) == null) {
val originalType = RefactoringUtil.getTypeByExpressionWithExpectedType(subExpression)
if (originalType != null) {
return listOf(subExpression)
}
}
return emptyList()
}
fun suggestElementsToExtract(file: PsiFile, range: TextRange): List<PsiElement> {
val selectedElements = findElementsInRange(file, range)
return alignElements(selectedElements)
}
private fun alignElements(elements: List<PsiElement>): List<PsiElement> {
val singleElement = elements.singleOrNull()
val alignedElements = when {
elements.size > 1 -> alignStatements(elements)
singleElement is PsiIfStatement -> listOf(alignIfStatement(singleElement))
singleElement is PsiBlockStatement -> if (singleElement.codeBlock.firstBodyElement != null) listOf(singleElement) else emptyList()
singleElement is PsiCodeBlock -> alignCodeBlock(singleElement)
singleElement is PsiExpression -> listOfNotNull(alignExpression(singleElement))
singleElement is PsiSwitchLabeledRuleStatement -> listOfNotNull(singleElement.body)
singleElement is PsiExpressionStatement -> listOf(alignExpressionStatement(singleElement))
else -> elements
}
return when {
alignedElements.isEmpty() -> emptyList()
alignedElements.all { it is PsiComment } -> emptyList()
alignedElements.first() !== elements.first() || alignedElements.last() !== elements.last() -> alignElements(alignedElements)
else -> alignedElements
}
}
private fun alignExpressionStatement(statement: PsiExpressionStatement): PsiElement {
val switchRule = statement.parent as? PsiSwitchLabeledRuleStatement
val switchExpression = PsiTreeUtil.getParentOfType(switchRule, PsiSwitchExpression::class.java)
if (switchExpression != null) return statement.expression
return statement
}
private fun isControlFlowStatement(statement: PsiStatement?): Boolean {
return statement is PsiBreakStatement || statement is PsiContinueStatement || statement is PsiReturnStatement || statement is PsiYieldStatement
}
private fun alignIfStatement(ifStatement: PsiIfStatement): PsiElement {
return if (ifStatement.elseBranch == null && isControlFlowStatement(ifStatement.thenBranch)) {
ifStatement.condition ?: ifStatement
} else {
ifStatement
}
}
private tailrec fun alignExpression(expression: PsiExpression?): PsiExpression? {
return when {
expression == null -> null
expression.type is PsiLambdaParameterType -> null
hasAssignmentInside(expression) -> null
isInsideAnnotation(expression) -> null
expression is PsiReturnStatement -> alignExpression(expression.returnValue)
expression is PsiParenthesizedExpression -> expression.takeIf { expression.expression != null }
//is PsiAssignmentExpression -> alignExpression(expression.rExpression)
//expression.parent is PsiParenthesizedExpression -> alignExpression(expression.parent as PsiExpression)
// PsiUtil.skipParenthesizedExprDown((PsiExpression)elements[0]);
else -> expression
}
}
private fun hasAssignmentInside(expression: PsiExpression): Boolean {
return PsiTreeUtil.findChildOfType(expression, PsiAssignmentExpression::class.java, false) != null
}
private fun alignStatements(statements: List<PsiElement>): List<PsiElement> {
val filteredStatements = statements
.dropWhile { it is PsiSwitchLabelStatement || it is PsiWhiteSpace }
.dropLastWhile { it is PsiSwitchLabelStatement || it is PsiWhiteSpace }
if (filteredStatements.any { it is PsiSwitchLabelStatementBase }) return emptyList()
return filteredStatements
}
private fun isInsideAnnotation(expression: PsiExpression): Boolean {
return PsiTreeUtil.getParentOfType(expression, PsiAnnotation::class.java) != null
}
private fun alignCodeBlock(codeBlock: PsiCodeBlock): List<PsiElement> {
return if (codeBlock.parent is PsiSwitchStatement) {
listOf(codeBlock.parent)
} else {
codeBlock.children.dropWhile { it !== codeBlock.firstBodyElement }.dropLastWhile { it !== codeBlock.lastBodyElement }
}
}
private fun alignStatement(statement: PsiStatement): PsiElement? {
return when (statement) {
is PsiExpressionStatement -> alignExpression(statement.expression)
is PsiDeclarationStatement -> statement.declaredElements.mapNotNull { (it as? PsiLocalVariable)?.initializer }.singleOrNull()
?: statement
else -> statement
}
}
} | apache-2.0 | 5358524bc42b590d9cb25975dec11cb6 | 45.401639 | 147 | 0.752297 | 5.309568 | false | false | false | false |
Cognifide/gradle-aem-plugin | src/main/kotlin/com/cognifide/gradle/aem/common/instance/LocalInstanceManager.kt | 1 | 25820 | package com.cognifide.gradle.aem.common.instance
import com.cognifide.gradle.aem.AemException
import com.cognifide.gradle.aem.AemExtension
import com.cognifide.gradle.aem.AemVersion
import com.cognifide.gradle.aem.common.instance.action.AwaitDownAction
import com.cognifide.gradle.aem.common.instance.action.AwaitUpAction
import com.cognifide.gradle.aem.common.instance.local.*
import com.cognifide.gradle.aem.instance.LocalInstancePlugin
import com.cognifide.gradle.aem.javaVersions
import com.cognifide.gradle.common.pluginProject
import com.cognifide.gradle.common.utils.Patterns
import com.cognifide.gradle.common.utils.onEachApply
import com.cognifide.gradle.common.utils.using
import org.buildobjects.process.ProcBuilder
import org.gradle.api.JavaVersion
import org.gradle.jvm.toolchain.JavaLauncher
import java.io.File
import java.io.Serializable
import java.util.concurrent.CopyOnWriteArrayList
import java.util.concurrent.TimeUnit
@Suppress("TooManyFunctions", "MagicNumber")
class LocalInstanceManager(internal val aem: AemExtension) : Serializable {
private val project = aem.project
private val common = aem.common
private val logger = aem.logger
val base by lazy { aem.instanceManager }
/**
* Using local AEM instances is acceptable in any project so that lookup for project applying local instance plugin is required
* Needed to determine e.g directory in which AEM quickstart will be stored and override files.
*/
val projectDir = aem.obj.dir {
convention(aem.obj.provider {
project.pluginProject(LocalInstancePlugin.ID)?.layout?.projectDirectory ?: throw LocalInstanceException(
"Using local AEM instances requires having at least one project applying plugin '${LocalInstancePlugin.ID}'" +
" or setting property 'localInstance.projectDir'!"
)
})
aem.prop.string("localInstance.projectDir")?.let { set(project.rootProject.file(it)) }
}
/**
* Path in which local AEM instance related files will be stored.
*/
val rootDir = aem.obj.dir {
convention(projectDir.dir(".gradle/aem/localInstance"))
aem.prop.file("localInstance.rootDir")?.let { set(it) }
}
/**
* Path in which local AEM instances will be stored.
*/
val instanceDir = aem.obj.dir {
convention(rootDir.dir("instance"))
aem.prop.file("localInstance.instanceDir")?.let { set(it) }
}
/**
* Path for storing local AEM instances related resources.
*/
val configDir = aem.obj.dir {
convention(projectDir.dir(aem.prop.string("localInstance.configPath") ?: "src/aem/localInstance"))
aem.prop.file("localInstance.configDir")?.let { set(it) }
}
/**
* Path from which e.g extra files for local AEM instances will be copied.
* Useful for overriding default startup scripts ('start.bat' or 'start.sh') or providing some files inside 'crx-quickstart'.
*/
val overrideDir = aem.obj.dir {
convention(configDir.dir("override"))
aem.prop.file("localInstance.overrideDir")?.let { set(it) }
}
/**
* Determines how instances will be created (from backup or quickstart built from the scratch).
*/
val source = aem.obj.typed<Source> {
convention(Source.AUTO)
aem.prop.string("localInstance.source")?.let { set(Source.of(it)) }
}
fun source(name: String) {
source.set(Source.of(name))
}
val javaLauncher = aem.obj.typed<JavaLauncher> {
convention(aem.common.javaSupport.launcher)
}
val javaExecutablePath get() = javaLauncher.get().executablePath.asFile.absolutePath
/**
* Automatically delete Quickstart JAR after unpacking.
*/
val cleanJar = aem.obj.boolean {
convention(true)
aem.prop.boolean("localInstance.cleanJar")?.let { set(it) }
}
/**
* Automatically open a web browser when instances are up.
*/
val openMode = aem.obj.typed<OpenMode> {
convention(OpenMode.NEVER)
aem.prop.string("localInstance.openMode")?.let { set(OpenMode.of(it)) }
}
fun openMode(name: String) {
openMode.set(OpenMode.of(name))
}
/**
* Maximum time to wait for browser open command response.
*/
val openTimeout = aem.obj.long {
convention(TimeUnit.SECONDS.toMillis(30))
aem.prop.long("localInstance.openTimeout")?.let { set(it) }
}
/**
* System service related options.
*/
val serviceComposer by lazy { ServiceComposer(this) }
fun service(options: ServiceComposer.() -> Unit) = serviceComposer.using(options)
fun resolveFiles() {
logger.info("Resolving local instance files")
logger.info("Resolved local instance files:\n${sourceFiles.joinToString("\n")}")
}
/**
* Maximum time to wait for start script response.
*/
val startTimeout = aem.obj.long {
convention(TimeUnit.SECONDS.toMillis(30))
aem.prop.long("localInstance.startTimeout")?.let { set(it) }
}
/**
* Maximum time to wait for stop script response.
*/
val stopTimeout = aem.obj.long {
convention(TimeUnit.SECONDS.toMillis(30))
aem.prop.long("localInstance.stopTimeout")?.let { set(it) }
}
/**
* Maximum time to wait for status script response.
*/
val statusTimeout = aem.obj.long {
convention(TimeUnit.SECONDS.toMillis(15))
aem.prop.long("localInstance.statusTimeout")?.let { set(it) }
}
val controlTrigger by lazy { ControlTrigger(aem) }
/**
* Configure behavior of triggering instance up/down.
*/
fun controlTrigger(options: ControlTrigger.() -> Unit) = controlTrigger.using(options)
/**
* Collection of files potentially needed to create instance
*/
val sourceFiles = aem.obj.files {
from(aem.obj.provider {
listOfNotNull(backupZip) + quickstart.files + install.files
})
}
/**
* Determines files in which properties can be injected.
*/
val expandFiles = aem.obj.strings {
set(listOf(
"control/*.sh",
"control/*.bat",
"service/*.sh",
"service/*.conf",
"crx-quickstart/bin/*.sh",
"crx-quickstart/bin/*.bat",
"crx-quickstart/bin/start",
"crx-quickstart/bin/status",
"crx-quickstart/bin/stop"
))
}
/**
* Determines files which executable rights will be applied.
*/
val executableFiles = aem.obj.strings {
set(listOf(
"control/*.sh",
"control/*.bat",
"service/*.sh",
"crx-quickstart/bin/*.sh",
"crx-quickstart/bin/*.bat",
"crx-quickstart/bin/start",
"crx-quickstart/bin/status",
"crx-quickstart/bin/stop"
))
}
/**
* Custom properties that can be injected into instance files.
*/
val expandProperties = aem.obj.map<String, Any> { convention(mapOf()) }
val quickstart by lazy { QuickstartResolver(aem) }
/**
* Configure AEM source files when creating instances from the scratch.
*/
fun quickstart(options: QuickstartResolver.() -> Unit) = quickstart.using(options)
/**
* Configure AEM backup sources.
*/
val backup by lazy { BackupManager(this) }
fun backup(options: BackupManager.() -> Unit) = backup.using(options)
val backupZip: File?
get() {
return when (source.get()) {
Source.AUTO, Source.BACKUP_ANY -> backup.any
Source.BACKUP_LOCAL -> backup.local
Source.BACKUP_REMOTE -> backup.remote
else -> null
}
}
val install by lazy { InstallResolver(aem) }
/**
* Configure CRX packages, bundles to be pre-installed on instance(s).
*/
fun install(options: InstallResolver.() -> Unit) = install.using(options)
internal var initOptions: LocalInstance.() -> Unit = {}
/**
* Configure action to be performed only once when instance is up first time.
*/
fun init(options: LocalInstance.() -> Unit) {
this.initOptions = options
}
fun create(instance: LocalInstance) = create(listOf(instance))
fun create(instances: Collection<LocalInstance> = aem.localInstances): List<LocalInstance> {
val uncreatedInstances = instances.filter { !it.created }
if (uncreatedInstances.isEmpty()) {
logger.lifecycle("No instances to create.")
return listOf()
}
logger.info("Creating instances: ${uncreatedInstances.names}")
createBySource(uncreatedInstances)
logger.info("Composing system service configuration")
serviceComposer.compose()
return uncreatedInstances.filter { it.created }
}
@Suppress("ComplexMethod")
fun createBySource(instances: Collection<LocalInstance> = aem.localInstances) = when (source.get()) {
Source.AUTO -> {
val backupZip = backup.any
when {
backupZip != null -> createFromBackup(instances, backupZip)
else -> createFromScratch(instances)
}
}
Source.BACKUP_ANY -> {
val backupZip = backup.any
when {
backupZip != null -> createFromBackup(instances, backupZip)
else -> throw LocalInstanceException("Cannot create instance(s) because no backups available!")
}
}
Source.BACKUP_LOCAL -> {
val backupZip = backup.local
?: throw LocalInstanceException("Cannot create instance(s) because no local backups available!")
createFromBackup(instances, backupZip)
}
Source.BACKUP_REMOTE -> {
val backupZip = backup.remote
?: throw LocalInstanceException("Cannot create instance(s) because no remote backups available!")
createFromBackup(instances, backupZip)
}
Source.SCRATCH -> createFromScratch(instances)
null -> {}
}
fun createFromBackup(instances: Collection<LocalInstance> = aem.localInstances, backupZip: File) {
backup.restore(backupZip, instanceDir.get().asFile, instances)
val missingInstances = instances.filter { !it.created }
if (missingInstances.isNotEmpty()) {
logger.info("Backup ZIP '$backupZip' does not contain all instances. Creating from scratch: ${missingInstances.names}")
createFromScratch(missingInstances)
}
common.progress(instances.size) {
instances.onEachApply {
increment("Customizing instance '$name'") {
logger.info("Customizing: $this")
customizeWhenDown()
logger.info("Customized: $this")
}
}
}
}
fun createFromScratch(instances: Collection<LocalInstance> = aem.localInstances) {
if (quickstart.jar == null) {
throw LocalInstanceException("Cannot create instances due to lacking source files. " +
"Ensure having specified local instance quickstart JAR url.")
}
if (quickstart.license == null) {
throw LocalInstanceException("Cannot create instances due to lacking source files. " +
"Ensure having specified local instance quickstart license url.")
}
common.progress(instances.size) {
instances.onEachApply {
increment("Creating instance '$name'") {
if (created) {
logger.info(("Instance already created: $this"))
return@increment
}
logger.info("Creating: $this")
prepare()
logger.info("Created: $this")
}
}
}
}
fun destroy(instance: LocalInstance): Boolean = destroy(listOf(instance)).isNotEmpty()
fun destroy(instances: Collection<LocalInstance> = aem.localInstances): List<LocalInstance> {
val createdInstances = instances.filter { it.touched }
if (createdInstances.isEmpty()) {
logger.lifecycle("No instances to destroy.")
return listOf()
}
logger.info("Destroying instance(s): ${createdInstances.names}")
common.progress(createdInstances.size) {
createdInstances.onEachApply {
increment("Destroying '$name'") {
logger.info("Destroying: $this")
delete()
logger.info("Destroyed: $this")
}
}
}
return createdInstances
}
fun up(instance: LocalInstance, awaitUpOptions: AwaitUpAction.() -> Unit = {}) = up(listOf(instance), awaitUpOptions).isNotEmpty()
@Suppress("LongMethod")
fun up(instances: Collection<LocalInstance> = aem.localInstances, awaitUpOptions: AwaitUpAction.() -> Unit = {}): List<LocalInstance> {
val downInstances = instances.filter { it.runnable }
if (downInstances.isEmpty()) {
logger.lifecycle("No instances to turn on.")
return listOf()
}
common.progress(downInstances.size) {
downInstances.onEachApply {
increment("Customizing instance '$name'") {
logger.info("Customizing: $this")
customizeWhenDown()
logger.info("Customized: $this")
}
}
}
common.progress(downInstances.size) {
downInstances.onEachApply {
increment("Starting instance '$name'") {
if (!created) {
logger.info("Instance not created, so it could not be up: $this")
return@increment
}
val status = checkStatus()
if (status.running) {
logger.info("Instance already running. No need to start: $this")
return@increment
}
sync {
instance.whenLocal {
if (!initialized) {
http.basicCredentials = Instance.CREDENTIALS_DEFAULT
}
}
controlTrigger.trigger(
action = { triggerUp() },
verify = { [email protected] },
fail = { throw LocalInstanceException("Instance cannot be triggered up: $instance!") }
)
}
}
}
}
base.awaitUp(downInstances, awaitUpOptions)
val uninitializedInstances = downInstances.filter { !it.initialized }
common.progress(uninitializedInstances.size) {
common.parallel.with(uninitializedInstances) {
increment("Initializing instance '$name'") {
logger.info("Initializing: $this")
init(initOptions)
}
}
}
when {
openMode.get() == OpenMode.ALWAYS -> open(downInstances)
openMode.get() == OpenMode.ONCE -> open(uninitializedInstances)
}
return downInstances
}
private fun LocalInstance.triggerUp() {
executeStartScript()
}
fun customize(instances: Collection<LocalInstance> = aem.localInstances) {
common.progress(instances.size) {
common.parallel.with(instances) {
increment("Customizing instance '$name'") {
logger.info("Customizing: $this")
customizeWhenUp()
}
}
}
}
fun down(instance: LocalInstance, awaitDownOptions: AwaitDownAction.() -> Unit = {}) = down(listOf(instance), awaitDownOptions).isNotEmpty()
fun down(instances: Collection<LocalInstance> = aem.localInstances, awaitDownOptions: AwaitDownAction.() -> Unit = {}): List<LocalInstance> {
val upInstances = instances.filter { it.running || it.available }
if (upInstances.isEmpty()) {
logger.lifecycle("No instances to turn off.")
return listOf()
}
common.progress(upInstances.size) {
upInstances.onEachApply {
increment("Stopping instance '$name'") {
sync {
val initReachableStatus = status.checkReachableStatus()
controlTrigger.trigger(
action = { triggerDown() },
verify = { initReachableStatus != status.checkReachableStatus() },
fail = { throw LocalInstanceException("Instance cannot be triggered down: $instance!") }
)
}
}
}
}
base.awaitDown(upInstances, awaitDownOptions)
return upInstances
}
private fun LocalInstance.triggerDown() {
if (created) {
val status = checkStatus()
if (status.running) {
executeStopScript()
} else if (available) {
logger.warn("Instance not running (reports status '$status'), but available. Stopping OSGi on: $this")
sync.osgi.stop()
}
} else if (available) {
sync.osgi.stop()
logger.warn("Instance not created, but available. Stopping OSGi on: $this")
}
}
fun open(instance: LocalInstance) = open(listOf(instance))
fun open(instances: Collection<LocalInstance> = aem.localInstances): List<LocalInstance> {
val upInstances = instances.filter { it.running }
if (upInstances.isEmpty()) {
logger.lifecycle("No instances to open.")
return listOf()
}
val openedInstances = CopyOnWriteArrayList<LocalInstance>()
common.progress(upInstances.size) {
common.parallel.with(upInstances) {
increment("Opening instance '$name'") {
try {
aem.webBrowser.open(httpOpenUrl) { withTimeoutMillis(openTimeout.get()) }
openedInstances += this@with
} catch (e: AemException) {
logger.debug("Instance '$name' open error", e)
logger.warn("Cannot open instance '$name'! Cause: ${e.message}")
}
}
}
}
if (openedInstances.isNotEmpty()) {
logger.lifecycle("Opened instances (${openedInstances.size}) in web browser (tabs):\n" +
openedInstances.joinToString("\n") { "Instance '${it.name}' at URL '${it.httpOpenUrl}'" })
}
return openedInstances
}
fun kill(instance: LocalInstance) = kill(listOf(instance))
fun kill(instances: Collection<LocalInstance> = aem.localInstances): List<LocalInstance> {
val killableInstances = instances.filter { it.pid > 0 }
if (killableInstances.isEmpty()) {
logger.lifecycle("No instances to kill.")
return listOf()
}
val killedInstances = CopyOnWriteArrayList<LocalInstance>()
common.progress(killableInstances.size) {
common.parallel.with(killableInstances) {
increment("Killing instance '$name'") {
try {
aem.processKiller.kill(pid)
killedInstances += this@with
} catch (e: AemException) {
logger.debug("Instance '$name' kill error", e)
logger.warn("Cannot kill instance '$name'! Cause: ${e.message}")
}
}
}
}
if (killedInstances.isEmpty()) {
logger.lifecycle("No instances killed!")
}
return killedInstances
}
val examineEnabled = aem.obj.boolean {
convention(base.examineEnabled)
aem.prop.boolean("localInstance.examination.enabled")?.let { set(it) }
}
fun examine(instances: Collection<LocalInstance> = aem.localInstances) {
if (!examineEnabled.get()) {
return
}
base.examine(instances)
}
val examinePrerequisites = aem.obj.boolean {
convention(base.examineEnabled)
aem.prop.boolean("localInstance.examination.prerequisites")?.let { set(it) }
}
fun examinePrerequisites(instances: Collection<LocalInstance> = aem.localInstances) {
if (!examinePrerequisites.get()) {
return
}
examineJavaAvailable()
examineJavaCompatibility(instances)
examineStatusUncorecognized(instances)
examineRunningOther(instances)
}
/**
* Pre-conditionally check if 'java' is available in shell scripts.
*
* Gradle is intelligently looking by its own for installed Java, but AEM control scripts
* are just requiring 'java' command available in 'PATH' environment variable.
*/
@Suppress("TooGenericExceptionCaught", "MagicNumber")
fun examineJavaAvailable() {
try {
logger.debug("Examining Java properly installed")
val result = ProcBuilder(javaExecutablePath, "-version")
.withWorkingDirectory(rootDir.get().asFile.apply { mkdirs() })
.withTimeoutMillis(statusTimeout.get())
.withExpectedExitStatuses(0)
.run()
logger.debug("Installed Java:\n${result.outputString.ifBlank { result.errorString }}")
} catch (e: Exception) {
throw LocalInstanceException("Local instances support requires Java properly installed! Cause: '${e.message}'\n" +
"Ensure having directory with 'java' executable listed in 'PATH' environment variable.", e)
}
}
/**
* Defines compatibility related to AEM versions and Java versions.
*
* AEM version is definable as range inclusive at a start, exclusive at an end.
* Java Version is definable as list of supported versions pipe delimited.
*/
val javaCompatibility = aem.obj.map<String, String> {
convention(mapOf(
"6.0.0-6.5.0" to "1.7|1.8",
"6.5.0-6.6.0" to "1.8|11",
"*.*.*.*T*Z" to "1.8|11" // cloud service
))
aem.prop.map("localInstance.javaCompatibility")?.let { set(it) }
}
fun examineJavaCompatibility(instances: Collection<LocalInstance> = aem.localInstances) {
if (javaCompatibility.get().isEmpty()) {
logger.debug("Examining Java compatibility skipped as configuration not provided!")
return
}
logger.debug("Examining Java compatibility for configuration: ${javaCompatibility.get()}")
val versionCurrent = JavaVersion.toVersion(javaLauncher.get().metadata.languageVersion)
val errors = instances.fold(mutableListOf<String>()) { result, instance ->
val aemVersion = instance.version
if (aemVersion == AemVersion.UNKNOWN) {
logger.info("Cannot examine Java compatibility because AEM version is unknown for $instance")
} else {
javaCompatibility.get().forEach { (aemVersionValue, versionList) ->
val versions = versionList.javaVersions("|")
if ((aemVersion.inRange(aemVersionValue) || Patterns.wildcard(aemVersion.value, aemVersionValue)) && versionCurrent !in versions) {
result.add("Instance '${instance.name}' using URL '${instance.httpUrl}' is AEM $aemVersion" +
" and requires Java ${versions.joinToString("|")}!")
}
}
}
result
}
if (errors.isNotEmpty()) {
throw LocalInstanceException("Some instances (${errors.size}) require different Java version than current $versionCurrent:\n" +
errors.joinToString("\n")
)
}
}
fun examineStatusUncorecognized(instances: Collection<LocalInstance>) {
val unrecognized = instances.filter { it.created }
.map { it to it.checkStatus() }
.filter { it.second.unrecognized }
if (unrecognized.isNotEmpty()) {
throw LocalInstanceException(
"Some instances are created but their status is unrecognized:\n" +
unrecognized.joinToString("\n") { (i, s) ->
"Instance '${i.name}' located at path '${i.dir}' reports status exit code ${s.exitValue}"
} + "\n\n" +
"Ensure that shell scripts have an ability to execute 'java' process or try rebooting machine."
)
}
}
fun examineRunningOther(instances: Collection<LocalInstance> = aem.localInstances) {
val running = instances.filter { it.runningOther }
if (running.isNotEmpty()) {
throw LocalInstanceException("Other instances (${running.size}) are running:\n" +
running.joinToString("\n") { "Instance '${it.name}' using URL '${it.httpUrl}' located at path '${it.runningDir}'" } + "\n\n" +
"Ensure having these instances down."
)
}
}
}
| apache-2.0 | 78b09c07d44b4ee3f17c721a1af18680 | 36.42029 | 151 | 0.581332 | 4.805509 | false | false | false | false |
Waboodoo/HTTP-Shortcuts | HTTPShortcuts/app/src/main/kotlin/ch/rmy/android/http_shortcuts/activities/execute/ExternalRequestFragment.kt | 1 | 3992 | package ch.rmy.android.http_shortcuts.activities.execute
import android.content.ActivityNotFoundException
import android.os.Bundle
import androidx.activity.result.launch
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import ch.rmy.android.framework.extensions.logException
import ch.rmy.android.framework.extensions.showToast
import ch.rmy.android.framework.utils.FilePickerUtil
import ch.rmy.android.http_shortcuts.R
import ch.rmy.android.http_shortcuts.utils.BarcodeScannerContract
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
class ExternalRequestFragment : Fragment() {
private val pickFiles = registerForActivityResult(FilePickerUtil.PickFiles) { files ->
if (files != null) {
returnResult(ExternalResult.Files(fileUris = files))
} else {
cancel()
}
}
private val openCamera = registerForActivityResult(FilePickerUtil.OpenCamera) { resultCallback ->
resultCallback.invoke(requireContext())
?.let { file ->
returnResult(ExternalResult.Files(fileUris = listOf(file)))
}
?: cancel()
}
private val scanBarcode = registerForActivityResult(BarcodeScannerContract) { result ->
returnResult(
if (result != null) {
ExternalResult.BarcodeScanned(result)
} else {
ExternalResult.Cancelled
}
)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (savedInstanceState == null) {
when (val request = request) {
is ExternalRequest.PickFiles -> pickFiles.launch(request.multiple)
is ExternalRequest.OpenCamera -> openCamera.launch()
is ExternalRequest.ScanBarcode -> try {
scanBarcode.launch()
} catch (e: ActivityNotFoundException) {
returnResult(ExternalResult.AppNotAvailable)
}
null -> error("Request was not set")
}
}
}
private fun returnResult(result: ExternalResult) {
removeSelf()
if (deferred == null) {
context?.showToast(R.string.error_generic)
logException(IllegalStateException("Failed to return result from external app, process was restarted"))
return
}
deferred!!.complete(result)
deferred = null
request = null
}
private fun cancel() {
removeSelf()
if (deferred == null) {
context?.showToast(R.string.error_generic)
logException(IllegalStateException("Failed to cancel from external app, process was restarted"))
return
}
deferred!!.cancel()
deferred = null
request = null
}
private fun removeSelf() {
requireActivity().supportFragmentManager.beginTransaction()
.remove(this)
.commitAllowingStateLoss()
}
companion object {
private const val TAG = "ExternalRequestFragment"
private var request: ExternalRequest? = null
private var deferred: CompletableDeferred<ExternalResult>? = null
suspend fun getResult(activity: FragmentActivity, request: ExternalRequest): ExternalResult =
withContext(Dispatchers.Main) {
assert([email protected] == null && deferred == null) { "A request is already in progress" }
[email protected] = request
val deferred = CompletableDeferred<ExternalResult>()
[email protected] = deferred
activity.supportFragmentManager
.beginTransaction()
.add(ExternalRequestFragment(), TAG)
.commitAllowingStateLoss()
deferred.await()
}
}
}
| mit | 5ebac52adb00a6b76976b6c45f2a2352 | 35.623853 | 115 | 0.62976 | 5.453552 | false | false | false | false |
vlasovskikh/intellij-micropython | src/main/kotlin/com/jetbrains/micropython/settings/MicroPythonFacetDetector.kt | 2 | 2741 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.jetbrains.micropython.settings
import com.intellij.framework.detection.FacetBasedFrameworkDetector
import com.intellij.framework.detection.FileContentPattern
import com.intellij.openapi.fileTypes.FileType
import com.intellij.openapi.roots.ProjectRootManager
import com.intellij.patterns.PatternCondition
import com.intellij.util.ProcessingContext
import com.intellij.util.indexing.FileContent
import com.jetbrains.micropython.devices.MicroPythonDeviceProvider
import com.jetbrains.python.PythonFileType
import com.jetbrains.python.psi.PyFile
import com.jetbrains.python.psi.PyFromImportStatement
import com.jetbrains.python.psi.PyImportStatement
/**
* @author Mikhail Golubev
*/
class MicroPythonFacetDetector : FacetBasedFrameworkDetector<MicroPythonFacet, MicroPythonFacetConfiguration>("MicroPython") {
override fun getFacetType() = MicroPythonFacetType.getInstance()
override fun createSuitableFilePattern() =
FileContentPattern.fileContent().with(object : PatternCondition<FileContent>("Contains MicroPython imports") {
override fun accepts(fileContent: FileContent, context: ProcessingContext?): Boolean {
val fileIndex = ProjectRootManager.getInstance(fileContent.project).fileIndex
if (!fileIndex.isInContent(fileContent.file) || fileIndex.isInLibraryClasses(fileContent.file)) {
return false
}
val detected = MicroPythonDeviceProvider.providers
.asSequence()
.flatMap { it.detectedModuleNames.asSequence() }
.toSet()
return when (val psiFile = fileContent.psiFile) {
is PyFile -> {
return psiFile.importBlock.any { imp ->
when (imp) {
is PyFromImportStatement -> imp.importSourceQName?.firstComponent in detected
is PyImportStatement -> imp.importElements.any { it.importedQName?.firstComponent in detected }
else -> false
}
}
}
else -> false
}
}
})
override fun getFileType(): FileType = PythonFileType.INSTANCE
} | apache-2.0 | 5617fd0aae5e9b5d8a2242f2e343817f | 41.184615 | 126 | 0.717986 | 4.868561 | false | false | false | false |
seventhroot/elysium | bukkit/rpk-crafting-skill-bukkit/src/main/kotlin/com/rpkit/craftingskill/bukkit/listener/InventoryClickListener.kt | 1 | 3944 | /*
* Copyright 2020 Ren Binden
*
* 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.rpkit.craftingskill.bukkit.listener
import com.rpkit.characters.bukkit.character.RPKCharacterProvider
import com.rpkit.core.bukkit.util.addLore
import com.rpkit.craftingskill.bukkit.RPKCraftingSkillBukkit
import com.rpkit.craftingskill.bukkit.craftingskill.RPKCraftingAction
import com.rpkit.craftingskill.bukkit.craftingskill.RPKCraftingSkillProvider
import com.rpkit.players.bukkit.profile.RPKMinecraftProfileProvider
import org.bukkit.Material
import org.bukkit.entity.Player
import org.bukkit.event.EventHandler
import org.bukkit.event.Listener
import org.bukkit.event.inventory.InventoryClickEvent
import org.bukkit.event.inventory.InventoryType
import org.bukkit.inventory.FurnaceInventory
import kotlin.math.min
import kotlin.math.roundToInt
import kotlin.random.Random
class InventoryClickListener(private val plugin: RPKCraftingSkillBukkit): Listener {
@EventHandler
fun onInventoryClick(event: InventoryClickEvent) {
if (event.clickedInventory !is FurnaceInventory) return
if (event.slotType != InventoryType.SlotType.RESULT) return
val minecraftProfileProvider = plugin.core.serviceManager.getServiceProvider(RPKMinecraftProfileProvider::class)
val characterProvider = plugin.core.serviceManager.getServiceProvider(RPKCharacterProvider::class)
val craftingSkillProvider = plugin.core.serviceManager.getServiceProvider(RPKCraftingSkillProvider::class)
val bukkitPlayer = event.whoClicked as? Player ?: return
val minecraftProfile = minecraftProfileProvider.getMinecraftProfile(bukkitPlayer) ?: return
val character = characterProvider.getActiveCharacter(minecraftProfile) ?: return
val item = event.currentItem ?: return
if (item.amount == 0 || item.type == Material.AIR) return
val material = item.type
val craftingSkill = craftingSkillProvider.getCraftingExperience(character, RPKCraftingAction.SMELT, material)
val quality = craftingSkillProvider.getQualityFor(RPKCraftingAction.SMELT, material, craftingSkill)
val amount = craftingSkillProvider.getAmountFor(RPKCraftingAction.SMELT, material, craftingSkill) * item.amount
if (quality != null) {
item.addLore(quality.lore)
}
if (amount > 1) {
item.amount = amount.roundToInt()
} else if (amount < 1) {
val random = Random.nextDouble()
if (random <= amount) {
item.amount = 1
} else {
event.currentItem = null
return
}
}
event.currentItem = item
val maxExperience = plugin.config.getConfigurationSection("smelting.$material")
?.getKeys(false)
?.map(String::toInt)
?.max()
?: 0
if (maxExperience != 0 && craftingSkill < maxExperience) {
val totalExperience = min(craftingSkill + item.amount, maxExperience)
craftingSkillProvider.setCraftingExperience(character, RPKCraftingAction.SMELT, item.type, totalExperience)
event.whoClicked.sendMessage(plugin.messages["smelt-experience", mapOf(
Pair("total-experience", totalExperience.toString()),
Pair("received-experience", item.amount.toString())
)])
}
}
} | apache-2.0 | bb64f1e4ff05ddedbcc7e5beaf778aca | 45.411765 | 120 | 0.713235 | 4.875155 | false | false | false | false |
solokot/Simple-Gallery | app/src/main/kotlin/com/simplemobiletools/gallery/pro/adapters/MediaAdapter.kt | 1 | 23950 | package com.simplemobiletools.gallery.pro.adapters
import android.annotation.SuppressLint
import android.content.Intent
import android.content.pm.ShortcutInfo
import android.content.pm.ShortcutManager
import android.graphics.drawable.Icon
import android.os.Handler
import android.os.Looper
import android.view.Menu
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import com.bumptech.glide.Glide
import com.qtalk.recyclerviewfastscroller.RecyclerViewFastScroller
import com.simplemobiletools.commons.activities.BaseSimpleActivity
import com.simplemobiletools.commons.adapters.MyRecyclerViewAdapter
import com.simplemobiletools.commons.dialogs.PropertiesDialog
import com.simplemobiletools.commons.dialogs.RenameDialog
import com.simplemobiletools.commons.dialogs.RenameItemDialog
import com.simplemobiletools.commons.extensions.*
import com.simplemobiletools.commons.helpers.*
import com.simplemobiletools.commons.models.FileDirItem
import com.simplemobiletools.commons.views.MyRecyclerView
import com.simplemobiletools.gallery.pro.R
import com.simplemobiletools.gallery.pro.activities.ViewPagerActivity
import com.simplemobiletools.gallery.pro.dialogs.DeleteWithRememberDialog
import com.simplemobiletools.gallery.pro.extensions.*
import com.simplemobiletools.gallery.pro.helpers.*
import com.simplemobiletools.gallery.pro.interfaces.MediaOperationsListener
import com.simplemobiletools.gallery.pro.models.Medium
import com.simplemobiletools.gallery.pro.models.ThumbnailItem
import com.simplemobiletools.gallery.pro.models.ThumbnailSection
import kotlinx.android.synthetic.main.photo_item_grid.view.*
import kotlinx.android.synthetic.main.thumbnail_section.view.*
import kotlinx.android.synthetic.main.video_item_grid.view.*
import kotlinx.android.synthetic.main.video_item_grid.view.media_item_holder
import kotlinx.android.synthetic.main.video_item_grid.view.medium_check
import kotlinx.android.synthetic.main.video_item_grid.view.medium_name
import kotlinx.android.synthetic.main.video_item_grid.view.medium_thumbnail
import java.util.*
class MediaAdapter(
activity: BaseSimpleActivity, var media: ArrayList<ThumbnailItem>, val listener: MediaOperationsListener?, val isAGetIntent: Boolean,
val allowMultiplePicks: Boolean, val path: String, recyclerView: MyRecyclerView, itemClick: (Any) -> Unit
) :
MyRecyclerViewAdapter(activity, recyclerView, itemClick), RecyclerViewFastScroller.OnPopupTextUpdate {
private val INSTANT_LOAD_DURATION = 2000L
private val IMAGE_LOAD_DELAY = 100L
private val ITEM_SECTION = 0
private val ITEM_MEDIUM_VIDEO_PORTRAIT = 1
private val ITEM_MEDIUM_PHOTO = 2
private val config = activity.config
private val viewType = config.getFolderViewType(if (config.showAll) SHOW_ALL else path)
private val isListViewType = viewType == VIEW_TYPE_LIST
private var visibleItemPaths = ArrayList<String>()
private var rotatedImagePaths = ArrayList<String>()
private var loadImageInstantly = false
private var delayHandler = Handler(Looper.getMainLooper())
private var currentMediaHash = media.hashCode()
private val hasOTGConnected = activity.hasOTGConnected()
private var scrollHorizontally = config.scrollHorizontally
private var animateGifs = config.animateGifs
private var cropThumbnails = config.cropThumbnails
private var displayFilenames = config.displayFileNames
private var showFileTypes = config.showThumbnailFileTypes
var sorting = config.getFolderSorting(if (config.showAll) SHOW_ALL else path)
var dateFormat = config.dateFormat
var timeFormat = activity.getTimeFormat()
init {
setupDragListener(true)
enableInstantLoad()
}
override fun getActionMenuId() = R.menu.cab_media
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val layoutType = if (viewType == ITEM_SECTION) {
R.layout.thumbnail_section
} else {
if (isListViewType) {
if (viewType == ITEM_MEDIUM_PHOTO) {
R.layout.photo_item_list
} else {
R.layout.video_item_list
}
} else {
if (viewType == ITEM_MEDIUM_PHOTO) {
R.layout.photo_item_grid
} else {
R.layout.video_item_grid
}
}
}
return createViewHolder(layoutType, parent)
}
override fun onBindViewHolder(holder: MyRecyclerViewAdapter.ViewHolder, position: Int) {
val tmbItem = media.getOrNull(position) ?: return
if (tmbItem is Medium) {
visibleItemPaths.add(tmbItem.path)
}
val allowLongPress = (!isAGetIntent || allowMultiplePicks) && tmbItem is Medium
holder.bindView(tmbItem, tmbItem is Medium, allowLongPress) { itemView, adapterPosition ->
if (tmbItem is Medium) {
setupThumbnail(itemView, tmbItem)
} else {
setupSection(itemView, tmbItem as ThumbnailSection)
}
}
bindViewHolder(holder)
}
override fun getItemCount() = media.size
override fun getItemViewType(position: Int): Int {
val tmbItem = media[position]
return when {
tmbItem is ThumbnailSection -> ITEM_SECTION
(tmbItem as Medium).isVideo() || tmbItem.isPortrait() -> ITEM_MEDIUM_VIDEO_PORTRAIT
else -> ITEM_MEDIUM_PHOTO
}
}
override fun prepareActionMode(menu: Menu) {
val selectedItems = getSelectedItems()
if (selectedItems.isEmpty()) {
return
}
val isOneItemSelected = isOneItemSelected()
val selectedPaths = selectedItems.map { it.path } as ArrayList<String>
val isInRecycleBin = selectedItems.firstOrNull()?.getIsInRecycleBin() == true
menu.apply {
findItem(R.id.cab_rename).isVisible = !isInRecycleBin
findItem(R.id.cab_add_to_favorites).isVisible = !isInRecycleBin
findItem(R.id.cab_fix_date_taken).isVisible = !isInRecycleBin
findItem(R.id.cab_move_to).isVisible = !isInRecycleBin
findItem(R.id.cab_open_with).isVisible = isOneItemSelected
findItem(R.id.cab_confirm_selection).isVisible = isAGetIntent && allowMultiplePicks && selectedKeys.isNotEmpty()
findItem(R.id.cab_restore_recycle_bin_files).isVisible = selectedPaths.all { it.startsWith(activity.recycleBinPath) }
findItem(R.id.cab_create_shortcut).isVisible = isOreoPlus() && isOneItemSelected
checkHideBtnVisibility(this, selectedItems)
checkFavoriteBtnVisibility(this, selectedItems)
}
}
override fun actionItemPressed(id: Int) {
if (selectedKeys.isEmpty()) {
return
}
when (id) {
R.id.cab_confirm_selection -> confirmSelection()
R.id.cab_properties -> showProperties()
R.id.cab_rename -> renameFile()
R.id.cab_edit -> editFile()
R.id.cab_hide -> toggleFileVisibility(true)
R.id.cab_unhide -> toggleFileVisibility(false)
R.id.cab_add_to_favorites -> toggleFavorites(true)
R.id.cab_remove_from_favorites -> toggleFavorites(false)
R.id.cab_restore_recycle_bin_files -> restoreFiles()
R.id.cab_share -> shareMedia()
R.id.cab_rotate_right -> rotateSelection(90)
R.id.cab_rotate_left -> rotateSelection(270)
R.id.cab_rotate_one_eighty -> rotateSelection(180)
R.id.cab_copy_to -> copyMoveTo(true)
R.id.cab_move_to -> moveFilesTo()
R.id.cab_create_shortcut -> createShortcut()
R.id.cab_select_all -> selectAll()
R.id.cab_open_with -> openPath()
R.id.cab_fix_date_taken -> fixDateTaken()
R.id.cab_set_as -> setAs()
R.id.cab_delete -> checkDeleteConfirmation()
}
}
override fun getSelectableItemCount() = media.filter { it is Medium }.size
override fun getIsItemSelectable(position: Int) = !isASectionTitle(position)
override fun getItemSelectionKey(position: Int) = (media.getOrNull(position) as? Medium)?.path?.hashCode()
override fun getItemKeyPosition(key: Int) = media.indexOfFirst { (it as? Medium)?.path?.hashCode() == key }
override fun onActionModeCreated() {}
override fun onActionModeDestroyed() {}
override fun onViewRecycled(holder: ViewHolder) {
super.onViewRecycled(holder)
if (!activity.isDestroyed) {
val itemView = holder.itemView
visibleItemPaths.remove(itemView.medium_name?.tag)
val tmb = itemView.medium_thumbnail
if (tmb != null) {
Glide.with(activity).clear(tmb)
}
}
}
fun isASectionTitle(position: Int) = media.getOrNull(position) is ThumbnailSection
private fun checkHideBtnVisibility(menu: Menu, selectedItems: ArrayList<Medium>) {
val isInRecycleBin = selectedItems.firstOrNull()?.getIsInRecycleBin() == true
menu.findItem(R.id.cab_hide).isVisible = !isInRecycleBin && selectedItems.any { !it.isHidden() }
menu.findItem(R.id.cab_unhide).isVisible = !isInRecycleBin && selectedItems.any { it.isHidden() }
}
private fun checkFavoriteBtnVisibility(menu: Menu, selectedItems: ArrayList<Medium>) {
menu.findItem(R.id.cab_add_to_favorites).isVisible = selectedItems.none { it.getIsInRecycleBin() } && selectedItems.any { !it.isFavorite }
menu.findItem(R.id.cab_remove_from_favorites).isVisible = selectedItems.none { it.getIsInRecycleBin() } && selectedItems.any { it.isFavorite }
}
private fun confirmSelection() {
listener?.selectedPaths(getSelectedPaths())
}
private fun showProperties() {
if (selectedKeys.size <= 1) {
val path = getFirstSelectedItemPath() ?: return
PropertiesDialog(activity, path, config.shouldShowHidden)
} else {
val paths = getSelectedPaths()
PropertiesDialog(activity, paths, config.shouldShowHidden)
}
}
private fun renameFile() {
if (selectedKeys.size == 1) {
val oldPath = getFirstSelectedItemPath() ?: return
RenameItemDialog(activity, oldPath) {
ensureBackgroundThread {
activity.updateDBMediaPath(oldPath, it)
activity.runOnUiThread {
enableInstantLoad()
listener?.refreshItems()
finishActMode()
}
}
}
} else {
RenameDialog(activity, getSelectedPaths(), true) {
enableInstantLoad()
listener?.refreshItems()
finishActMode()
}
}
}
private fun editFile() {
val path = getFirstSelectedItemPath() ?: return
activity.openEditor(path)
}
private fun openPath() {
val path = getFirstSelectedItemPath() ?: return
activity.openPath(path, true)
}
private fun setAs() {
val path = getFirstSelectedItemPath() ?: return
activity.setAs(path)
}
private fun toggleFileVisibility(hide: Boolean) {
ensureBackgroundThread {
getSelectedItems().forEach {
activity.toggleFileVisibility(it.path, hide)
}
activity.runOnUiThread {
listener?.refreshItems()
finishActMode()
}
}
}
private fun toggleFavorites(add: Boolean) {
ensureBackgroundThread {
getSelectedItems().forEach {
it.isFavorite = add
activity.updateFavorite(it.path, add)
}
activity.runOnUiThread {
listener?.refreshItems()
finishActMode()
}
}
}
private fun restoreFiles() {
activity.restoreRecycleBinPaths(getSelectedPaths()) {
listener?.refreshItems()
finishActMode()
}
}
private fun shareMedia() {
if (selectedKeys.size == 1 && selectedKeys.first() != -1) {
activity.shareMediumPath(getSelectedItems().first().path)
} else if (selectedKeys.size > 1) {
activity.shareMediaPaths(getSelectedPaths())
}
}
private fun rotateSelection(degrees: Int) {
activity.toast(R.string.saving)
ensureBackgroundThread {
val paths = getSelectedPaths().filter { it.isImageFast() }
var fileCnt = paths.size
rotatedImagePaths.clear()
paths.forEach {
rotatedImagePaths.add(it)
activity.saveRotatedImageToFile(it, it, degrees, true) {
fileCnt--
if (fileCnt == 0) {
activity.runOnUiThread {
listener?.refreshItems()
finishActMode()
}
}
}
}
}
}
private fun moveFilesTo() {
activity.handleDeletePasswordProtection {
copyMoveTo(false)
}
}
private fun copyMoveTo(isCopyOperation: Boolean) {
val paths = getSelectedPaths()
val recycleBinPath = activity.recycleBinPath
val fileDirItems = paths.asSequence().filter { isCopyOperation || !it.startsWith(recycleBinPath) }.map {
FileDirItem(it, it.getFilenameFromPath())
}.toMutableList() as ArrayList
if (!isCopyOperation && paths.any { it.startsWith(recycleBinPath) }) {
activity.toast(R.string.moving_recycle_bin_items_disabled, Toast.LENGTH_LONG)
}
if (fileDirItems.isEmpty()) {
return
}
activity.tryCopyMoveFilesTo(fileDirItems, isCopyOperation) {
val destinationPath = it
config.tempFolderPath = ""
activity.applicationContext.rescanFolderMedia(destinationPath)
activity.applicationContext.rescanFolderMedia(fileDirItems.first().getParentPath())
val newPaths = fileDirItems.map { "$destinationPath/${it.name}" }.toMutableList() as ArrayList<String>
activity.rescanPaths(newPaths) {
activity.fixDateTaken(newPaths, false)
}
if (!isCopyOperation) {
listener?.refreshItems()
activity.updateFavoritePaths(fileDirItems, destinationPath)
}
}
}
@SuppressLint("NewApi")
private fun createShortcut() {
val manager = activity.getSystemService(ShortcutManager::class.java)
if (manager.isRequestPinShortcutSupported) {
val path = getSelectedPaths().first()
val drawable = resources.getDrawable(R.drawable.shortcut_image).mutate()
activity.getShortcutImage(path, drawable) {
val intent = Intent(activity, ViewPagerActivity::class.java).apply {
putExtra(PATH, path)
putExtra(SHOW_ALL, config.showAll)
putExtra(SHOW_FAVORITES, path == FAVORITES)
putExtra(SHOW_RECYCLE_BIN, path == RECYCLE_BIN)
action = Intent.ACTION_VIEW
flags = flags or Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
}
val shortcut = ShortcutInfo.Builder(activity, path)
.setShortLabel(path.getFilenameFromPath())
.setIcon(Icon.createWithBitmap(drawable.convertToBitmap()))
.setIntent(intent)
.build()
manager.requestPinShortcut(shortcut, null)
}
}
}
private fun fixDateTaken() {
ensureBackgroundThread {
activity.fixDateTaken(getSelectedPaths(), true) {
listener?.refreshItems()
finishActMode()
}
}
}
private fun checkDeleteConfirmation() {
if (config.isDeletePasswordProtectionOn) {
activity.handleDeletePasswordProtection {
deleteFiles()
}
} else if (config.tempSkipDeleteConfirmation || config.skipDeleteConfirmation) {
deleteFiles()
} else {
askConfirmDelete()
}
}
private fun askConfirmDelete() {
val itemsCnt = selectedKeys.size
val firstPath = getSelectedPaths().first()
val items = if (itemsCnt == 1) {
"\"${firstPath.getFilenameFromPath()}\""
} else {
resources.getQuantityString(R.plurals.delete_items, itemsCnt, itemsCnt)
}
val isRecycleBin = firstPath.startsWith(activity.recycleBinPath)
val baseString = if (config.useRecycleBin && !isRecycleBin) R.string.move_to_recycle_bin_confirmation else R.string.deletion_confirmation
val question = String.format(resources.getString(baseString), items)
DeleteWithRememberDialog(activity, question) {
config.tempSkipDeleteConfirmation = it
deleteFiles()
}
}
private fun deleteFiles() {
if (selectedKeys.isEmpty()) {
return
}
val SAFPath = getSelectedPaths().firstOrNull { activity.needsStupidWritePermissions(it) } ?: getFirstSelectedItemPath() ?: return
activity.handleSAFDialog(SAFPath) {
if (!it) {
return@handleSAFDialog
}
val fileDirItems = ArrayList<FileDirItem>(selectedKeys.size)
val removeMedia = ArrayList<Medium>(selectedKeys.size)
val positions = getSelectedItemPositions()
getSelectedItems().forEach {
fileDirItems.add(FileDirItem(it.path, it.name))
removeMedia.add(it)
}
media.removeAll(removeMedia)
listener?.tryDeleteFiles(fileDirItems)
listener?.updateMediaGridDecoration(media)
removeSelectedItems(positions)
currentMediaHash = media.hashCode()
}
}
private fun getSelectedItems() = selectedKeys.mapNotNull { getItemWithKey(it) } as ArrayList<Medium>
private fun getSelectedPaths() = getSelectedItems().map { it.path } as ArrayList<String>
private fun getFirstSelectedItemPath() = getItemWithKey(selectedKeys.first())?.path
private fun getItemWithKey(key: Int): Medium? = media.firstOrNull { (it as? Medium)?.path?.hashCode() == key } as? Medium
fun updateMedia(newMedia: ArrayList<ThumbnailItem>) {
val thumbnailItems = newMedia.clone() as ArrayList<ThumbnailItem>
if (thumbnailItems.hashCode() != currentMediaHash) {
currentMediaHash = thumbnailItems.hashCode()
media = thumbnailItems
enableInstantLoad()
notifyDataSetChanged()
finishActMode()
}
}
fun updateDisplayFilenames(displayFilenames: Boolean) {
this.displayFilenames = displayFilenames
enableInstantLoad()
notifyDataSetChanged()
}
fun updateAnimateGifs(animateGifs: Boolean) {
this.animateGifs = animateGifs
notifyDataSetChanged()
}
fun updateCropThumbnails(cropThumbnails: Boolean) {
this.cropThumbnails = cropThumbnails
notifyDataSetChanged()
}
fun updateShowFileTypes(showFileTypes: Boolean) {
this.showFileTypes = showFileTypes
notifyDataSetChanged()
}
private fun enableInstantLoad() {
loadImageInstantly = true
delayHandler.postDelayed({
loadImageInstantly = false
}, INSTANT_LOAD_DURATION)
}
private fun setupThumbnail(view: View, medium: Medium) {
val isSelected = selectedKeys.contains(medium.path.hashCode())
view.apply {
val padding = if (config.thumbnailSpacing <= 1) {
config.thumbnailSpacing
} else {
0
}
media_item_holder.setPadding(padding, padding, padding, padding)
play_portrait_outline?.beVisibleIf(medium.isVideo() || medium.isPortrait())
if (medium.isVideo()) {
play_portrait_outline?.setImageResource(R.drawable.ic_play_outline_vector)
play_portrait_outline?.beVisible()
} else if (medium.isPortrait()) {
play_portrait_outline?.setImageResource(R.drawable.ic_portrait_photo_vector)
play_portrait_outline?.beVisibleIf(showFileTypes)
}
if (showFileTypes && (medium.isGIF() || medium.isRaw() || medium.isSVG())) {
file_type.setText(
when (medium.type) {
TYPE_GIFS -> R.string.gif
TYPE_RAWS -> R.string.raw
else -> R.string.svg
}
)
file_type.beVisible()
} else {
file_type?.beGone()
}
medium_name.beVisibleIf(displayFilenames || isListViewType)
medium_name.text = medium.name
medium_name.tag = medium.path
val showVideoDuration = medium.isVideo() && config.showThumbnailVideoDuration
if (showVideoDuration) {
video_duration?.text = medium.videoDuration.getFormattedDuration()
}
video_duration?.beVisibleIf(showVideoDuration)
medium_check?.beVisibleIf(isSelected)
if (isSelected) {
medium_check?.background?.applyColorFilter(adjustedPrimaryColor)
medium_check.applyColorFilter(contrastColor)
}
if (isListViewType) {
media_item_holder.isSelected = isSelected
}
var path = medium.path
if (hasOTGConnected && context.isPathOnOTG(path)) {
path = path.getOTGPublicPath(context)
}
val roundedCorners = when {
isListViewType -> ROUNDED_CORNERS_SMALL
config.fileRoundedCorners -> ROUNDED_CORNERS_BIG
else -> ROUNDED_CORNERS_NONE
}
if (loadImageInstantly) {
activity.loadImage(
medium.type, path, medium_thumbnail, scrollHorizontally, animateGifs, cropThumbnails, roundedCorners, medium.getKey(),
rotatedImagePaths
)
} else {
medium_thumbnail.setImageDrawable(null)
medium_thumbnail.isHorizontalScrolling = scrollHorizontally
delayHandler.postDelayed({
val isVisible = visibleItemPaths.contains(medium.path)
if (isVisible) {
activity.loadImage(
medium.type, path, medium_thumbnail, scrollHorizontally, animateGifs, cropThumbnails, roundedCorners,
medium.getKey(), rotatedImagePaths
)
}
}, IMAGE_LOAD_DELAY)
}
if (isListViewType) {
medium_name.setTextColor(textColor)
play_portrait_outline?.applyColorFilter(textColor)
}
}
}
private fun setupSection(view: View, section: ThumbnailSection) {
view.apply {
thumbnail_section.text = section.title
thumbnail_section.setTextColor(textColor)
}
}
override fun onChange(position: Int): String {
var realIndex = position
if (isASectionTitle(position)) {
realIndex++
}
return (media[realIndex] as? Medium)?.getBubbleText(sorting, activity, dateFormat, timeFormat) ?: ""
}
}
| gpl-3.0 | 18fd5b10acde3c7421d9c843c42c0016 | 37.566828 | 150 | 0.619123 | 4.916855 | false | false | false | false |
BlueBoxWare/LibGDXPlugin | src/test/kotlin/com/gmail/blueboxware/libgdxplugin/Utils.kt | 1 | 11138 | package com.gmail.blueboxware.libgdxplugin
import com.gmail.blueboxware.libgdxplugin.filetypes.atlas2.Atlas2File
import com.gmail.blueboxware.libgdxplugin.utils.markFileAsGdxJson
import com.intellij.psi.PsiFile
import com.intellij.testFramework.PlatformTestUtil
import com.intellij.testFramework.UsefulTestCase
import java.io.BufferedReader
import java.io.File
/*
* Copyright 2018 Blue Box Ware
*
* 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.
*/
internal fun UsefulTestCase.testname() = if (this.name == null) "" else PlatformTestUtil.getTestName(name, true)
internal fun PsiFile.markAsGdxJson() = project.markFileAsGdxJson(virtualFile)
internal fun loadAtlas(file: Atlas2File): TextureAtlas {
val pages = mutableListOf<AtlasPage>()
val regions = mutableListOf<AtlasRegion>()
var hasIndexes = false
file.getPages().forEach { p ->
val page = AtlasPage()
page.textureFile = p.header.text
p.getFieldValues("size")?.map { it.toInt() }?.let { s ->
page.width = s[0]
page.height = s[1]
}
p.getFieldValue("format")?.let { f ->
page.format = f
}
p.getFieldValues("filter")?.let { f ->
page.minFilter = f[0]
page.magFilter = f[1]
}
p.getFieldValue("repeat")?.let { r ->
if (r.contains('x')) page.uWrap = "Repeat"
if (r.contains('y')) page.vWrap = "Repeat"
}
p.getFieldValue("pma")?.let { pma ->
page.pma = pma == "true"
}
pages.add(page)
p.regionList.forEach { r ->
val region = AtlasRegion()
val names = mutableListOf<String>()
val values = mutableListOf<List<Int>>()
region.file = page.textureFile
region.name = r.header.text
r.getFieldValues("xy")?.map { it.toInt() }?.let { xy ->
region.left = xy[0]
region.top = xy[1]
}
r.getFieldValues("size")?.map { it.toInt() }?.let { s ->
region.width = s[0]
region.height = s[1]
}
r.getFieldValues("bounds")?.map { it.toInt() }?.let { b ->
region.left = b[0]
region.top = b[1]
region.width = b[2]
region.height = b[3]
}
r.getFieldValues("offset")?.map { it.toInt() }?.let { o ->
region.offsetX = o[0]
region.offsetY = o[1]
}
r.getFieldValues("orig")?.map { it.toInt() }?.let { o ->
region.originalWidth = o[0]
region.originalHeight = o[1]
}
r.getFieldValues("offsets")?.let { o ->
region.offsetX = o[0].toInt()
region.offsetY = o[1].toInt()
region.originalWidth = o[2].toInt()
region.originalHeight = o[3].toInt()
}
r.getFieldValue("rotate")?.let { rotate ->
if (rotate == "true") {
region.degrees = 90
} else if (rotate != "false") {
region.degrees = rotate.toInt()
}
region.rotate = region.degrees == 90
}
r.getFieldValue("index")?.let { i ->
region.index = i.toInt()
if (region.index != -1) {
hasIndexes = true
}
}
r.getFieldList()
.filter { it.key !in listOf("xy", "size", "bounds", "offset", "orig", "offsets", "rotate", "index") }
.forEach { field ->
names.add(field.key)
values.add(field.values.map { it.toIntOrNull() ?: 0 })
}
if (region.originalWidth == 0 && region.originalHeight == 0) {
region.originalWidth = region.width
region.originalHeight = region.height
}
if (names.isNotEmpty()) {
region.names = names
region.values = values
}
regions.add(region)
}
}
if (hasIndexes) {
regions.sortWith { r1, r2 ->
var i1 = r1.index
if (i1 == -1) i1 = Int.MAX_VALUE
var i2 = r2.index
if (i2 == -1) i2 = Int.MAX_VALUE
return@sortWith i1 - i2
}
}
return TextureAtlas(pages, regions)
}
internal fun loadAtlas(packFile: File): TextureAtlas {
val pages = mutableListOf<AtlasPage>()
val regions = mutableListOf<AtlasRegion>()
val entry = mutableListOf("", "", "", "", "")
var hasIndexes = false
val pageFields: Map<String, (AtlasPage) -> Unit> = mapOf("size" to { p ->
p.width = entry[1].toInt()
p.height = entry[2].toInt()
}, "format" to { p ->
p.format = entry[1]
}, "filter" to { p ->
p.minFilter = entry[1]
p.magFilter = entry[2]
}, "repeat" to { p ->
if (entry[1].indexOf('x') != -1) p.uWrap = "Repeat"
if (entry[1].indexOf('y') != -1) p.vWrap = "Repeat"
}, "pma" to { p ->
p.pma = entry[1] == "true"
})
val regionFields: Map<String, (AtlasRegion) -> Unit> = mapOf("xy" to { r ->
r.left = entry[1].toInt()
r.top = entry[2].toInt()
}, "size" to { r ->
r.width = entry[1].toInt()
r.height = entry[2].toInt()
}, "bounds" to { r ->
r.left = entry[1].toInt()
r.top = entry[2].toInt()
r.width = entry[3].toInt()
r.height = entry[4].toInt()
}, "offset" to { r ->
r.offsetX = entry[1].toInt()
r.offsetY = entry[2].toInt()
}, "orig" to { r ->
r.originalWidth = entry[1].toInt()
r.originalHeight = entry[2].toInt()
}, "offsets" to { r ->
r.offsetX = entry[1].toInt()
r.offsetY = entry[2].toInt()
r.originalWidth = entry[3].toInt()
r.originalHeight = entry[4].toInt()
}, "rotate" to { r ->
val value = entry[1]
if (value == "true") {
r.degrees = 90
} else if (value != "false") {
r.degrees = value.toInt()
}
r.rotate = r.degrees == 90
}, "index" to { r ->
r.index = entry[1].toInt()
if (r.index != -1) {
hasIndexes = true
}
})
val reader = BufferedReader(packFile.reader())
var line = reader.readLine()
// Ignore empty lines before first entry
while (line != null && line.trim().isEmpty()) {
line = reader.readLine()
}
// Header fields
while (true) {
if (line == null || line.trim().isEmpty()) break
if (readEntry(entry, line) == 0) break // ignore header fields
line = reader.readLine()
}
// Page and region entries
var page: AtlasPage? = null
val names = mutableListOf<String>()
val values = mutableListOf<List<Int>>()
while (true) {
if (line == null) break
if (line.trim().isEmpty()) {
page = null
line = reader.readLine()
} else if (page == null) {
// Page start
page = AtlasPage()
page.textureFile = line
while (true) {
line = reader.readLine()
if (readEntry(entry, line) == 0) break
val field = pageFields[entry[0]]
if (field != null) field(page)
}
pages.add(page)
} else {
val region = AtlasRegion()
region.name = line.trim()
region.file = page.textureFile
while (true) {
line = reader.readLine()
val count = readEntry(entry, line)
if (count == 0) break
val field = regionFields[entry[0]]
if (field != null) {
field(region)
} else {
names.add(entry[0])
val entryValues = MutableList(count) { 0 }
for (i in 0 until count) {
entryValues[i] = entry[i + 1].toIntOrNull() ?: 0
}
values.add(entryValues)
}
}
if (region.originalWidth == 0 && region.originalHeight == 0) {
region.originalWidth = region.width
region.originalHeight = region.height
}
if (names.isNotEmpty()) {
region.names = names.toList()
region.values = values.toList()
names.clear()
values.clear()
}
regions.add(region)
}
}
if (hasIndexes) {
regions.sortWith { r1, r2 ->
var i1 = r1.index
if (i1 == -1) i1 = Int.MAX_VALUE
var i2 = r2.index
if (i2 == -1) i2 = Int.MAX_VALUE
return@sortWith i1 - i2
}
}
return TextureAtlas(pages, regions)
}
internal data class TextureAtlas(
private val pages: List<AtlasPage>, private val regions: List<AtlasRegion>
)
internal data class AtlasRegion(
var name: String = "",
var file: String = "",
var left: Int = 0,
var top: Int = 0,
var width: Int = 0,
var height: Int = 0,
var offsetX: Int = 0,
var offsetY: Int = 0,
var originalWidth: Int = 0,
var originalHeight: Int = 0,
var rotate: Boolean = false,
var degrees: Int = 0,
var index: Int = -1,
var names: List<String> = listOf(),
var values: List<List<Int>> = listOf()
)
internal data class AtlasPage(
var width: Int = 0,
var height: Int = 0,
var format: String = "RGBA8888",
var minFilter: String = "Nearest",
var magFilter: String = "Nearest",
var uWrap: String = "ClampToEdge",
var vWrap: String = "ClampToEdge",
var pma: Boolean = false,
var textureFile: String = "",
var regions: MutableList<AtlasRegion> = mutableListOf()
)
private fun readEntry(entry: MutableList<String>, l: String?): Int {
if (l == null) return 0
var line = l
line = line.trim()
if (line.isEmpty()) return 0
val colon = line.indexOf(':')
if (colon == -1) return 0
entry[0] = line.substring(0, colon).trim()
var lastMatch = colon + 1
var i = 1
while (true) {
val comma = line.indexOf(',', lastMatch)
if (comma == -1) {
entry[i] = line.substring(lastMatch).trim()
return i
}
entry[i] = line.substring(lastMatch, comma).trim()
lastMatch = comma + 1
if (i == 4) return 4
i++
}
}
| apache-2.0 | aef466721b475271b6e0d5b45e58ea31 | 31.662757 | 117 | 0.51248 | 3.983548 | false | false | false | false |
matthieucoisne/LeagueChampions | features/champions/src/test/java/com/leaguechampions/features/champions/presentation/championdetails/ChampionDetailsViewModelTest.kt | 1 | 3344 | package com.leaguechampions.features.champions.presentation.championdetails
import androidx.arch.core.executor.testing.InstantTaskExecutorRule
import androidx.lifecycle.Observer
import com.leaguechampions.features.champions.data.model.ChampionEntity
import com.leaguechampions.features.champions.domain.usecase.GetChampionDetailsUseCase
import org.junit.After
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.rules.TestRule
import org.junit.runner.RunWith
import org.mockito.Mock
import org.mockito.junit.MockitoJUnitRunner
@RunWith(MockitoJUnitRunner::class)
class ChampionDetailsViewModelTest {
private val championId = "Riven"
private val champion = ChampionEntity(championId, "", "")
private val error = "error"
// private val viewStateLoading = ChampionDetailsViewModel.ViewState(status = Status.LOADING)
// private val viewStateSuccess = ChampionDetailsViewModel.ViewState(status = Status.SUCCESS, champion = champion)
// private val viewStateError = ChampionDetailsViewModel.ViewState(status = Status.ERROR, error = error)
private lateinit var viewModel: ChampionDetailsViewModel
@Mock private lateinit var getChampionDetailsUseCase: GetChampionDetailsUseCase
@Mock private lateinit var observerViewState: Observer<ChampionDetailsViewModel.ViewState>
@get:Rule var rule: TestRule = InstantTaskExecutorRule()
@Before
fun setUp() {
viewModel = ChampionDetailsViewModel(getChampionDetailsUseCase)
viewModel.viewState.observeForever(observerViewState)
}
@After
fun tearDown() {
}
@Test
fun testSetChampionId_loading() {
// val resource = MutableLiveData<Resource<Champion>>()
// resource.value = Resource.Loading()
// `when`(repository.getChampion(championId)).thenReturn(resource)
//
// viewModel.setChampionId(championId)
//
// verify(repository).getChampion(championId)
// assertThat(viewModel.viewState.value).isEqualTo(viewStateLoading)
// verifyNoMoreInteractions(repository)
}
// @Test
// fun testSetChampionId_success() {
// val resource = MutableLiveData<Resource<Champion>>()
// resource.value = Resource.success(champion)
// `when`(repository.getChampion(championId)).thenReturn(resource)
//
// viewModel.setChampionId(championId)
//
// verify(repository).getChampion(championId)
// assertThat(viewModel.viewState.value).isEqualTo(viewStateSuccess)
// verifyNoMoreInteractions(repository)
// }
//
// @Test
// fun testSetChampionId_error() {
// val resource = MutableLiveData<Resource<Champion>>()
// resource.value = com.leaguechampions.libraries.core.utils.Resource.error(error)
// `when`(repository.getChampion(championId)).thenReturn(resource)
//
// viewModel.setChampionId(championId)
//
// verify(repository).getChampion(championId)
// assertThat(viewModel.viewState.value).isEqualTo(viewStateError)
// verifyNoMoreInteractions(repository)
// }
//
// @Test
// fun testSetChampionId_null() {
// viewModel.setChampionId(null)
//
// verify(repository, never()).getChampion(anyString())
// assertThat(viewModel.viewState.value).isEqualTo(null)
// verifyNoMoreInteractions(repository)
// }
}
| apache-2.0 | 47e9689523626e9bdfd2e1e24475b43d | 35.747253 | 117 | 0.73116 | 4.417437 | false | true | false | false |
xwiki-contrib/android-authenticator | app/src/main/java/org/xwiki/android/sync/syncadapter/SyncAdapter.kt | 1 | 6777 | package org.xwiki.android.sync.syncadapter
import android.accounts.Account
import android.accounts.AccountManager
import android.content.AbstractThreadedSyncAdapter
import android.content.ContentProviderClient
import android.content.Context
import android.content.SyncResult
import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import kotlinx.coroutines.async
import kotlinx.coroutines.channels.Channel
import org.xwiki.android.sync.*
import org.xwiki.android.sync.bean.XWikiUserFull
import org.xwiki.android.sync.contactdb.ContactManager
import org.xwiki.android.sync.contactdb.setAccountContactsVisibility
import org.xwiki.android.sync.utils.ChannelJavaWaiter
import org.xwiki.android.sync.utils.StringUtils
import org.xwiki.android.sync.utils.awaitBlocking
import rx.Observer
import java.util.*
private const val TAG = "SyncAdapter"
class SyncAdapter(
context: Context,
autoInitialize: Boolean,
allowParallelSyncs: Boolean
) : AbstractThreadedSyncAdapter(
context,
autoInitialize,
allowParallelSyncs
) {
/**
* Account manager to manage synchronization.
*/
private val mAccountManager: AccountManager = AccountManager.get(context)
/**
* @param context will be set to {@link #mContext}
* @param autoInitialize auto initialization sync
*/
constructor(
context: Context,
autoInitialize: Boolean
) : this(
context,
autoInitialize,
false
)
private var updateThread: Thread? = null
set(value) {
synchronized(this) {
field ?.also {
if (it.isAlive) {
it.interrupt()
}
}
field = value
}
}
/**
* Perform all sync process.
*
* @param account the account that should be synced
* @param extras SyncAdapter-specific parameters
* @param authority the authority of this sync request
* @param provider a ContentProviderClient that points to the ContentProvider for this
* authority
* @param syncResult SyncAdapter-specific parameters
*/
override fun onPerformSync(
account: Account?,
extras: Bundle?,
authority: String?,
provider: ContentProviderClient?,
syncResult: SyncResult
) {
account ?: return
setAccountContactsVisibility(
context.contentResolver,
account,
false
)
val triggeringChannel = Channel<Boolean>(1)
val channelJavaWaiter = ChannelJavaWaiter(appCoroutineScope, triggeringChannel)
val updateJob = appCoroutineScope.async {
Log.i(TAG, "onPerformSync start")
val userAccount = userAccountsRepo.findByAccountName(account.name) ?: return@async null
val syncType = userAccount.syncType
Log.i(TAG, "syncType=$syncType")
if (syncType == SYNC_TYPE_NO_NEED_SYNC) return@async null
// get last sync date. return new Date(0) if first onPerformSync
val lastSyncMarker = getServerSyncMarker(account)
Log.d(TAG, lastSyncMarker)
// Get XWiki SyncData from XWiki server , which should be added, updated or deleted after lastSyncMarker.
val (observable, thread) = resolveApiManager(userAccount).xWikiHttp.getSyncData(
syncType,
userAccount.selectedGroupsList
)
thread.setUncaughtExceptionHandler { _, e ->
observable.onError(e)
}
updateThread = thread
// Update the local contacts database with the last modified changes. updateContact()
ContactManager.updateContacts(context, userAccount, observable)
observable.subscribe(
object : Observer<XWikiUserFull> {
override fun onCompleted() {
updateServerSyncMarker(account)
triggeringChannel.offer(true)
setAccountContactsVisibility(
context.contentResolver,
account,
true
)
}
override fun onError(e: Throwable) {
syncResult.stats.numIoExceptions++
triggeringChannel.offer(true)
setAccountContactsVisibility(
context.contentResolver,
account,
true
)
}
override fun onNext(xWikiUserFull: XWikiUserFull) {
syncResult.stats.numEntries++
}
}
).also {
synchronized(observable) {
(observable as Object).notifyAll()
}
}
}
updateJob.invokeOnCompletion { error ->
if (error != null) {
triggeringChannel.offer(true)
}
}
try {
channelJavaWaiter.lock()
} catch (e: InterruptedException) {
updateJob.awaitBlocking(appCoroutineScope) ?.unsubscribe()
} finally {
updateThread = null
}
}
override fun onSyncCanceled() {
super.onSyncCanceled()
updateThread = null
}
/**
* This helper function fetches the last known high-water-mark
* we received from the server - or 0 if we've never synced.
*
* @param account the account we're syncing
* @return the change high-water-mark Iso8601
*/
private fun getServerSyncMarker(account: Account): String {
val lastSyncIso = mAccountManager.getUserData(account, SYNC_MARKER_KEY)
//if empty, just return new Date(0) so that we can get all users from server.
return if (TextUtils.isEmpty(lastSyncIso)) {
StringUtils.dateToIso8601String(Date(0))
} else lastSyncIso
}
/**
* Save off the high-water-mark we receive back from the server.
*
* @param account The account we're syncing
* @param lastSyncIso The high-water-mark we want to save.
*/
private fun setServerSyncMarker(account: Account, lastSyncIso: String) {
mAccountManager.setUserData(account, SYNC_MARKER_KEY, lastSyncIso)
}
private fun updateServerSyncMarker(account: Account) {
// Save off the new sync date. On our next sync, we only want to receive
// contacts that have changed since this sync...
setServerSyncMarker(account, StringUtils.dateToIso8601String(Date()))
}
}
| lgpl-2.1 | ec0774bcd7728bf3708996972d9fdef2 | 32.058537 | 117 | 0.601446 | 5.177235 | false | false | false | false |
vjache/klips | src/main/java/org/klips/engine/rete/builder/AgendaManager.kt | 1 | 2891 | package org.klips.engine.rete.builder
import org.klips.engine.Binding
import org.klips.engine.Modification
import java.util.*
/**
* Agenda manger is a driver which support a collection of activated rules
* and decide what effect of which rule to apply to WM firstly.
* Agenda manager could be also treated as a conflict resolver:
* given a set of rules activated, decide which activated rule to apply first.
*/
interface AgendaManager {
/**
* Return next rule to apply. Once rule is returned, usually it shouldn't be
* returned at next call of `next()`.
*/
fun next(): Pair<Modification<Binding>, RuleClause>?
/**
* Add activated rule to agenda.
*/
fun add(solution: Modification<Binding>, ruleClause: RuleClause)
/**
* Remove activation from agenda and return 'true' if it have been really removed.
*/
fun remove(solution: Modification<Binding>, ruleClause: RuleClause): Boolean
}
/**
* This is a simplest agenda manager which uses internal queue prioritized by priority & serialNo
* of solution causing an activation.
*/
open class PriorityAgendaManager : AgendaManager {
protected val pqueue = PriorityQueue<Pair<Modification<Binding>, RuleClause>>(100) { x, y ->
val cmp = x.second.priority.compareTo(y.second.priority)
if (cmp == 0)
x.first.serialNo.compareTo(y.first.serialNo)
else
cmp
}
override fun next(): Pair<Modification<Binding>, RuleClause>? {
if (pqueue.isEmpty())
return null
return pqueue.remove()
}
override fun add(solution: Modification<Binding>, ruleClause: RuleClause) {
pqueue.add(solution to ruleClause)
}
override fun remove(solution: Modification<Binding>, ruleClause: RuleClause) = pqueue.remove(solution to ruleClause)
}
/**
* This is a utility agenda manager which behave like a 'PriorityAgendaManager' while a priority of activated rules
* have a value less than 'priorityThreshold' otherwise all calls delegated to the 'nextAgendaManager'.
*/
class EscalatingAgendaManager(
private val priorityThreshold: Double,
private val nextAgendaManager: AgendaManager) : PriorityAgendaManager() {
override fun next(): Pair<Modification<Binding>, RuleClause>? {
pqueue.poll()?.let { return it }
return nextAgendaManager.next()
}
override fun add(solution: Modification<Binding>, ruleClause: RuleClause) {
if (ruleClause.priority >= priorityThreshold)
nextAgendaManager.add(solution, ruleClause)
else
super.add(solution, ruleClause)
}
override fun remove(solution: Modification<Binding>, ruleClause: RuleClause) =
if (ruleClause.priority >= priorityThreshold)
nextAgendaManager.remove(solution, ruleClause)
else
super.remove(solution, ruleClause)
}
| apache-2.0 | 30c2567170f76ba0ca6a82a4090cef8f | 32.616279 | 120 | 0.691802 | 4.454545 | false | false | false | false |
RP-Kit/RPKit | bukkit/rpk-experience-bukkit/src/main/kotlin/com/rpkit/experience/bukkit/command/experience/ExperienceAddCommand.kt | 1 | 3674 | /*
* Copyright 2020 Ren Binden
*
* 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.rpkit.experience.bukkit.command.experience
import com.rpkit.characters.bukkit.character.RPKCharacterService
import com.rpkit.core.service.Services
import com.rpkit.experience.bukkit.RPKExperienceBukkit
import com.rpkit.experience.bukkit.experience.RPKExperienceService
import com.rpkit.players.bukkit.profile.minecraft.RPKMinecraftProfileService
import org.bukkit.command.Command
import org.bukkit.command.CommandExecutor
import org.bukkit.command.CommandSender
class ExperienceAddCommand(private val plugin: RPKExperienceBukkit) : CommandExecutor {
override fun onCommand(sender: CommandSender, command: Command, label: String, args: Array<out String>): Boolean {
if (!sender.hasPermission("rpkit.experience.command.experience.add")) {
sender.sendMessage(plugin.messages["no-permission-experience-add"])
return true
}
if (args.size < 2) {
sender.sendMessage(plugin.messages["experience-add-usage"])
return true
}
val minecraftProfileService = Services[RPKMinecraftProfileService::class.java]
if (minecraftProfileService == null) {
sender.sendMessage(plugin.messages["no-minecraft-profile-service"])
return true
}
val characterService = Services[RPKCharacterService::class.java]
if (characterService == null) {
sender.sendMessage(plugin.messages["no-character-service"])
return true
}
val experienceService = Services[RPKExperienceService::class.java]
if (experienceService == null) {
sender.sendMessage(plugin.messages["no-experience-service"])
return true
}
val bukkitPlayer = plugin.server.getPlayer(args[0])
if (bukkitPlayer == null) {
sender.sendMessage(plugin.messages["experience-add-player-invalid-player"])
return true
}
val minecraftProfile = minecraftProfileService.getPreloadedMinecraftProfile(bukkitPlayer)
if (minecraftProfile == null) {
sender.sendMessage(plugin.messages["no-minecraft-profile"])
return true
}
val character = characterService.getPreloadedActiveCharacter(minecraftProfile)
if (character == null) {
sender.sendMessage(plugin.messages["no-character-other"])
return true
}
try {
val experience = args[1].toInt()
if (experience <= 0) {
sender.sendMessage(plugin.messages["experience-add-experience-invalid-negative"])
return true
}
experienceService.getExperience(character).thenAccept { characterExperience ->
experienceService.setExperience(character, characterExperience + experience)
sender.sendMessage(plugin.messages["experience-add-valid"])
}
} catch (exception: NumberFormatException) {
sender.sendMessage(plugin.messages["experience-add-experience-invalid-number"])
}
return true
}
} | apache-2.0 | b78b4f791d110f7fda6d58e6f723ffc4 | 42.75 | 118 | 0.681818 | 4.97832 | false | false | false | false |
JakeWharton/AssistedInject | inflation-inject-processor/src/main/java/app/cash/inject/inflation/processor/InflationInjectProcessor.kt | 1 | 12414 | package app.cash.inject.inflation.processor
import com.google.auto.service.AutoService
import app.cash.inject.inflation.processor.internal.MirrorValue
import app.cash.inject.inflation.processor.internal.applyEach
import app.cash.inject.inflation.processor.internal.cast
import app.cash.inject.inflation.processor.internal.castEach
import app.cash.inject.inflation.processor.internal.createGeneratedAnnotation
import app.cash.inject.inflation.processor.internal.filterNotNullValues
import app.cash.inject.inflation.processor.internal.findElementsAnnotatedWith
import app.cash.inject.inflation.processor.internal.getAnnotation
import app.cash.inject.inflation.processor.internal.getValue
import app.cash.inject.inflation.processor.internal.hasAnnotation
import app.cash.inject.inflation.processor.internal.toClassName
import app.cash.inject.inflation.processor.internal.toTypeName
import app.cash.inject.inflation.InflationInject
import app.cash.inject.inflation.InflationModule
import app.cash.inject.inflation.ViewFactory
import com.squareup.javapoet.ClassName
import com.squareup.javapoet.JavaFile
import net.ltgt.gradle.incap.IncrementalAnnotationProcessor
import net.ltgt.gradle.incap.IncrementalAnnotationProcessorType.AGGREGATING
import javax.annotation.processing.AbstractProcessor
import javax.annotation.processing.Filer
import javax.annotation.processing.Messager
import javax.annotation.processing.ProcessingEnvironment
import javax.annotation.processing.Processor
import javax.annotation.processing.RoundEnvironment
import javax.lang.model.SourceVersion
import javax.lang.model.element.Element
import javax.lang.model.element.ElementKind.CLASS
import javax.lang.model.element.ElementKind.CONSTRUCTOR
import javax.lang.model.element.ExecutableElement
import javax.lang.model.element.Modifier
import javax.lang.model.element.Modifier.PRIVATE
import javax.lang.model.element.Modifier.STATIC
import javax.lang.model.element.TypeElement
import javax.lang.model.type.TypeMirror
import javax.lang.model.util.Elements
import javax.lang.model.util.Types
import javax.tools.Diagnostic.Kind.ERROR
import javax.tools.Diagnostic.Kind.WARNING
@IncrementalAnnotationProcessor(AGGREGATING)
@AutoService(Processor::class)
class InflationInjectProcessor : AbstractProcessor() {
override fun getSupportedSourceVersion() = SourceVersion.latest()
override fun getSupportedAnnotationTypes() = setOf(
InflationInject::class.java.canonicalName,
InflationModule::class.java.canonicalName)
override fun init(env: ProcessingEnvironment) {
super.init(env)
sourceVersion = env.sourceVersion
messager = env.messager
filer = env.filer
types = env.typeUtils
elements = env.elementUtils
viewType = elements.getTypeElement("android.view.View").asType()
}
private lateinit var sourceVersion: SourceVersion
private lateinit var messager: Messager
private lateinit var filer: Filer
private lateinit var types: Types
private lateinit var elements: Elements
private lateinit var viewType: TypeMirror
private var userModule: String? = null
override fun process(annotations: Set<TypeElement>, roundEnv: RoundEnvironment): Boolean {
val inflationInjectElements = roundEnv.findInflationInjectCandidateTypeElements()
.mapNotNull { it.toInflationInjectElementsOrNull() }
inflationInjectElements
.associateWith { it.toAssistedInjectionOrNull() }
.filterNotNullValues()
.forEach(::writeInflationInject)
val inflationModuleElements = roundEnv.findInflationModuleTypeElement()
?.toInflationModuleElementsOrNull(inflationInjectElements)
if (inflationModuleElements != null) {
val moduleType = inflationModuleElements.moduleType
val userModuleFqcn = userModule
if (userModuleFqcn != null) {
val userModuleType = elements.getTypeElement(userModuleFqcn)
error("Multiple @InflationModule-annotated modules found.", userModuleType)
error("Multiple @InflationModule-annotated modules found.", moduleType)
userModule = null
} else {
userModule = moduleType.qualifiedName.toString()
val inflationInjectionModule = inflationModuleElements.toInflationInjectionModule()
writeInflationModule(inflationModuleElements, inflationInjectionModule)
}
}
// Wait until processing is ending to validate that the @InflationModule's @Module annotation
// includes the generated type.
if (roundEnv.processingOver()) {
val userModuleFqcn = userModule
if (userModuleFqcn != null) {
// In the processing round in which we handle the @InflationModule the @Module annotation's
// includes contain an <error> type because we haven't generated the inflation module yet.
// As a result, we need to re-lookup the element so that its referenced types are available.
val userModule = elements.getTypeElement(userModuleFqcn)
// Previous validation guarantees this annotation is present.
val moduleAnnotation = userModule.getAnnotation("dagger.Module")!!
// Dagger guarantees this property is present and is an array of types or errors.
val includes = moduleAnnotation.getValue("includes", elements)!!
.cast<MirrorValue.Array>()
.filterIsInstance<MirrorValue.Type>()
val generatedModuleName = userModule.toClassName().inflationInjectModuleName()
val referencesGeneratedModule = includes
.map { it.toTypeName() }
.any { it == generatedModuleName }
if (!referencesGeneratedModule) {
error("@InflationModule's @Module must include ${generatedModuleName.simpleName()}",
userModule)
}
}
}
return false
}
/**
* Find [TypeElement]s which are candidates for assisted injection by having a constructor
* annotated with [InflationInject].
*/
private fun RoundEnvironment.findInflationInjectCandidateTypeElements(): List<TypeElement> {
return findElementsAnnotatedWith<InflationInject>()
.map { it.enclosingElement as TypeElement }
}
/**
* From this [TypeElement] which is a candidate for inflation injection, find and validate the
* syntactical elements required to generate the factory:
* - Non-private, non-inner target type
* - Single non-private target constructor
*/
private fun TypeElement.toInflationInjectElementsOrNull(): InflationInjectElements? {
var valid = true
if (PRIVATE in modifiers) {
error("@InflationInject-using types must not be private", this)
valid = false
}
if (enclosingElement.kind == CLASS && STATIC !in modifiers) {
error("Nested @InflationInject-using types must be static", this)
valid = false
}
if (!types.isSubtype(asType(), viewType)) {
error("@InflationInject-using types must be subtypes of View", this)
valid = false
}
val constructors = enclosedElements
.filter { it.kind == CONSTRUCTOR }
.filter { it.hasAnnotation<InflationInject>() }
.castEach<ExecutableElement>()
if (constructors.size > 1) {
error("Multiple @InflationInject-annotated constructors found.", this)
valid = false
}
if (!valid) return null
val constructor = constructors.single()
if (PRIVATE in constructor.modifiers) {
error("@InflationInject constructor must not be private.", constructor)
return null
}
return InflationInjectElements(this, constructor)
}
/**
* From this [InflationInjectElements], parse and validate the semantic information of the
* elements which is required to generate the factory:
* - Unqualified assisted parameters of Context and AttributeSet
* - At least one provided parameter and no duplicates
*/
private fun InflationInjectElements.toAssistedInjectionOrNull(): AssistedInjection? {
var valid = true
val requests = targetConstructor.parameters.map { it.asDependencyRequest() }
val (assistedRequests, providedRequests) = requests.partition { it.isAssisted }
val assistedKeys = assistedRequests.map { it.key }
if (assistedKeys.toSet() != FACTORY_KEYS.toSet()) {
error("""
Inflation injection requires Context and AttributeSet @Inflated parameters.
Found:
$assistedKeys
Expected:
$FACTORY_KEYS
""".trimIndent(), targetConstructor)
valid = false
}
if (providedRequests.isEmpty()) {
warn("Inflation injection requires at least one non-@Inflated parameter.", targetConstructor)
} else {
val providedDuplicates = providedRequests.groupBy { it.key }.filterValues { it.size > 1 }
if (providedDuplicates.isNotEmpty()) {
error("Duplicate non-@Inflated parameters declared. Forget a qualifier annotation?"
+ providedDuplicates.values.flatten().joinToString("\n * ", prefix = "\n * "),
targetConstructor)
valid = false
}
}
if (!valid) return null
val targetType = targetType.asType().toTypeName()
val generatedAnnotation = createGeneratedAnnotation(sourceVersion, elements)
return AssistedInjection(targetType, requests, FACTORY, "create", VIEW,
FACTORY_KEYS, generatedAnnotation)
}
private fun writeInflationInject(elements: InflationInjectElements, injection: AssistedInjection) {
val generatedTypeSpec = injection.brewJava()
.toBuilder()
.addOriginatingElement(elements.targetType)
.build()
JavaFile.builder(injection.generatedType.packageName(), generatedTypeSpec)
.addFileComment("Generated by @InflationInject. Do not modify!")
.build()
.writeTo(filer)
}
/**
* Find and validate a [TypeElement] of the inflation module by being annotated
* [InflationModule].
*/
private fun RoundEnvironment.findInflationModuleTypeElement(): TypeElement? {
val inflationModules = findElementsAnnotatedWith<InflationModule>().castEach<TypeElement>()
if (inflationModules.size > 1) {
inflationModules.forEach {
error("Multiple @InflationModule-annotated modules found.", it)
}
return null
}
return inflationModules.singleOrNull()
}
private fun TypeElement.toInflationModuleElementsOrNull(
inflationInjectElements: List<InflationInjectElements>
): InflationModuleElements? {
if (!hasAnnotation("dagger.Module")) {
error("@InflationModule must also be annotated as a Dagger @Module", this)
return null
}
val inflationTargetTypes = inflationInjectElements.map { it.targetType }
return InflationModuleElements(this, inflationTargetTypes)
}
private fun InflationModuleElements.toInflationInjectionModule(): InflationInjectionModule {
val moduleName = moduleType.toClassName()
val inflationNames = inflationTypes.map { it.toClassName() }
val public = Modifier.PUBLIC in moduleType.modifiers
val generatedAnnotation = createGeneratedAnnotation(sourceVersion, elements)
return InflationInjectionModule(moduleName, public, inflationNames, generatedAnnotation)
}
private fun writeInflationModule(
elements: InflationModuleElements,
module: InflationInjectionModule
) {
val generatedTypeSpec = module.brewJava()
.toBuilder()
.addOriginatingElement(elements.moduleType)
.applyEach(elements.inflationTypes) {
addOriginatingElement(it)
}
.build()
JavaFile.builder(module.generatedType.packageName(), generatedTypeSpec)
.addFileComment("Generated by @InflationModule. Do not modify!")
.build()
.writeTo(filer)
}
private fun warn(message: String, element: Element? = null) {
messager.printMessage(WARNING, message, element)
}
private fun error(message: String, element: Element? = null) {
messager.printMessage(ERROR, message, element)
}
private data class InflationInjectElements(
val targetType: TypeElement,
val targetConstructor: ExecutableElement
)
private data class InflationModuleElements(
val moduleType: TypeElement,
val inflationTypes: List<TypeElement>
)
}
private val VIEW = ClassName.get("android.view", "View")
private val FACTORY = ViewFactory::class.toClassName()
private val FACTORY_KEYS = listOf(
Key(ClassName.get("android.content", "Context")),
Key(ClassName.get("android.util", "AttributeSet")))
| apache-2.0 | f503f2dab80dfd3f20d9e126f652d2c2 | 38.916399 | 101 | 0.73836 | 4.77278 | false | false | false | false |
luxons/seven-wonders | sw-engine/src/test/kotlin/org/luxons/sevenwonders/engine/boards/MilitaryTest.kt | 1 | 1867 | package org.luxons.sevenwonders.engine.boards
import org.junit.experimental.theories.DataPoints
import org.junit.experimental.theories.FromDataPoints
import org.junit.experimental.theories.Theories
import org.junit.experimental.theories.Theory
import org.junit.runner.RunWith
import org.luxons.sevenwonders.engine.boards.Military.UnknownAgeException
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
@RunWith(Theories::class)
class MilitaryTest {
@Theory
fun victory_addsCorrectPoints(
@FromDataPoints("ages") age: Int,
@FromDataPoints("points") nbPointsPerVictory: Int,
) {
val military = createMilitary(age, nbPointsPerVictory, 0)
val initialPoints = military.totalPoints
military.victory(age)
assertEquals(initialPoints + nbPointsPerVictory, military.totalPoints)
}
@Theory
fun victory_failsIfUnknownAge(@FromDataPoints("points") nbPointsPerVictory: Int) {
val military = createMilitary(0, nbPointsPerVictory, 0)
assertFailsWith<UnknownAgeException> {
military.victory(1)
}
}
@Theory
fun defeat_removesCorrectPoints(@FromDataPoints("points") nbPointsLostPerDefeat: Int) {
val military = createMilitary(0, 0, nbPointsLostPerDefeat)
val initialPoints = military.totalPoints
military.defeat()
assertEquals(initialPoints - nbPointsLostPerDefeat, military.totalPoints)
}
companion object {
@JvmStatic
@DataPoints("points")
fun points(): IntArray = intArrayOf(0, 1, 3, 5)
@JvmStatic
@DataPoints("ages")
fun ages(): IntArray = intArrayOf(1, 2, 3)
private fun createMilitary(age: Int, nbPointsPerVictory: Int, nbPointsPerDefeat: Int): Military =
Military(nbPointsPerDefeat, mapOf(age to nbPointsPerVictory))
}
}
| mit | 7f2cccce339dfa9638e179d4c96174b7 | 31.754386 | 105 | 0.710766 | 4.167411 | false | true | false | false |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.