repo_name
stringlengths
7
81
path
stringlengths
4
242
copies
stringclasses
95 values
size
stringlengths
1
6
content
stringlengths
3
991k
license
stringclasses
15 values
smmribeiro/intellij-community
plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/ui/toolwindow/panels/repositories/RepositoryManagementPanel.kt
2
2408
package com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.repositories import com.intellij.openapi.actionSystem.DefaultActionGroup import com.intellij.openapi.project.Project import com.intellij.ui.AutoScrollToSourceHandler import com.intellij.ui.components.JBScrollPane import com.intellij.util.ui.UIUtil import com.jetbrains.packagesearch.intellij.plugin.PackageSearchBundle import com.jetbrains.packagesearch.intellij.plugin.actions.ShowSettingsAction import com.jetbrains.packagesearch.intellij.plugin.configuration.PackageSearchGeneralConfiguration import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.PackageSearchPanelBase import com.jetbrains.packagesearch.intellij.plugin.ui.util.emptyBorder import com.jetbrains.packagesearch.intellij.plugin.util.lifecycleScope import com.jetbrains.packagesearch.intellij.plugin.util.packageSearchProjectService import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.flow.onEach import javax.swing.JScrollPane internal class RepositoryManagementPanel( private val project: Project ) : PackageSearchPanelBase(PackageSearchBundle.message("packagesearch.ui.toolwindow.tab.repositories.title")) { private val repositoriesTree = RepositoryTree(project) private val autoScrollToSourceHandler = object : AutoScrollToSourceHandler() { override fun isAutoScrollMode(): Boolean { return PackageSearchGeneralConfiguration.getInstance(project).autoScrollToSource } override fun setAutoScrollMode(state: Boolean) { PackageSearchGeneralConfiguration.getInstance(project).autoScrollToSource = state } } private val mainSplitter = JBScrollPane(repositoriesTree, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER).apply { border = emptyBorder() verticalScrollBar.unitIncrement = 16 UIUtil.putClientProperty(verticalScrollBar, JBScrollPane.IGNORE_SCROLLBAR_IN_INSETS, true) } init { project.packageSearchProjectService.allInstalledKnownRepositoriesFlow .onEach { repositoriesTree.display(it) } .launchIn(project.lifecycleScope) } override fun build() = mainSplitter override fun buildGearActions() = DefaultActionGroup( ShowSettingsAction(project), autoScrollToSourceHandler.createToggleAction() ) }
apache-2.0
Helabs/generator-he-kotlin-mvp
app/templates/app_arch_comp/src/main/kotlin/data/SchedulerProviderContract.kt
1
934
package <%= appPackage %>.data import io.reactivex.Scheduler import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.internal.schedulers.ImmediateThinScheduler import io.reactivex.schedulers.Schedulers interface SchedulerProviderContract { val io: Scheduler val ui: Scheduler val computation: Scheduler } class SchedulerProvider : SchedulerProviderContract { override val io: Scheduler get() = Schedulers.io() override val ui: Scheduler get() = AndroidSchedulers.mainThread() override val computation: Scheduler get() = Schedulers.computation() } class ImmediateSchedulerProvider : SchedulerProviderContract { override val io: Scheduler get() = ImmediateThinScheduler.INSTANCE override val ui: Scheduler get() = ImmediateThinScheduler.INSTANCE override val computation: Scheduler get() = ImmediateThinScheduler.INSTANCE }
mit
smmribeiro/intellij-community
plugins/kotlin/j2k/new/tests/testData/newJ2k/arrayAccessExpression/expressionIndex.kt
13
42
myArray.get(myLibrary.calculateIndex(100))
apache-2.0
google/intellij-community
platform/credential-store-ui/src/PasswordSafeConfigurable.kt
1
15814
// 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.credentialStore import com.intellij.credentialStore.gpg.Pgp import com.intellij.credentialStore.gpg.PgpKey import com.intellij.credentialStore.kdbx.IncorrectMasterPasswordException import com.intellij.credentialStore.keePass.DB_FILE_NAME import com.intellij.credentialStore.keePass.KeePassFileManager import com.intellij.credentialStore.keePass.MasterKeyFileStorage import com.intellij.credentialStore.keePass.getDefaultMasterPasswordFile import com.intellij.ide.IdeBundle import com.intellij.ide.passwordSafe.PasswordSafe import com.intellij.ide.passwordSafe.impl.PasswordSafeImpl import com.intellij.ide.passwordSafe.impl.createPersistentCredentialStore import com.intellij.ide.passwordSafe.impl.getDefaultKeePassDbFile import com.intellij.openapi.actionSystem.ActionUpdateThread import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.components.service import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory import com.intellij.openapi.options.ConfigurableBase import com.intellij.openapi.options.ConfigurableUi import com.intellij.openapi.options.ConfigurationException import com.intellij.openapi.project.DumbAwareAction import com.intellij.openapi.ui.ComboBox import com.intellij.openapi.ui.DialogPanel import com.intellij.openapi.ui.MessageDialogBuilder import com.intellij.openapi.ui.TextFieldWithBrowseButton import com.intellij.openapi.util.NlsContexts import com.intellij.openapi.util.SystemInfo import com.intellij.ui.CollectionComboBoxModel import com.intellij.ui.dsl.builder.* import com.intellij.ui.dsl.builder.panel import com.intellij.ui.dsl.gridLayout.HorizontalAlign import com.intellij.ui.layout.* import com.intellij.util.io.exists import com.intellij.util.io.isDirectory import com.intellij.util.text.nullize import java.io.File import java.nio.file.Paths import javax.swing.JCheckBox import javax.swing.JPanel import javax.swing.JRadioButton class PasswordSafeConfigurable : ConfigurableBase<PasswordSafeConfigurableUi, PasswordSafeSettings>("application.passwordSafe", CredentialStoreBundle.message("password.safe.configurable"), "reference.ide.settings.password.safe") { private val settings = service<PasswordSafeSettings>() override fun getSettings() = settings override fun createUi() = PasswordSafeConfigurableUi(settings) } class PasswordSafeConfigurableUi(private val settings: PasswordSafeSettings) : ConfigurableUi<PasswordSafeSettings> { private lateinit var myPanel: DialogPanel private lateinit var usePgpKey: JCheckBox private lateinit var pgpKeyCombo: ComboBox<PgpKey> private lateinit var keepassRadioButton: JRadioButton private var keePassDbFile: TextFieldWithBrowseButton? = null private val pgpListModel = CollectionComboBoxModel<PgpKey>() private val pgp by lazy { Pgp() } // https://youtrack.jetbrains.com/issue/IDEA-200188 // reuse to avoid delays - on Linux SecureRandom is quite slow private val secureRandom = lazy { createSecureRandom() } override fun reset(settings: PasswordSafeSettings) { val secretKeys = pgp.listKeys() pgpListModel.replaceAll(secretKeys) usePgpKey.text = usePgpKeyText() myPanel.reset() keePassDbFile?.text = settings.keepassDb ?: getDefaultKeePassDbFile().toString() } override fun isModified(settings: PasswordSafeSettings): Boolean { if (myPanel.isModified()) return true if (keePassDbFile == null) { return false } return isKeepassFileLocationChanged(settings) } private fun isKeepassFileLocationChanged(settings: PasswordSafeSettings): Boolean { return keepassRadioButton.isSelected && getNewDbFileAsString() != settings.keepassDb } override fun apply(settings: PasswordSafeSettings) { val pgpKeyChanged = getNewPgpKey()?.keyId != this.settings.state.pgpKeyId val oldProviderType = this.settings.providerType myPanel.apply() val providerType = this.settings.providerType // close if any, it is more reliable just close current store and later it will be recreated lazily with a new settings (PasswordSafe.instance as PasswordSafeImpl).closeCurrentStore(isSave = false, isEvenMemoryOnly = providerType != ProviderType.MEMORY_ONLY) val passwordSafe = PasswordSafe.instance as PasswordSafeImpl if (oldProviderType != providerType) { when (providerType) { ProviderType.MEMORY_ONLY -> { // nothing else is required to setup } ProviderType.KEYCHAIN -> { // create here to ensure that user will get any error during native store creation try { val store = createPersistentCredentialStore() if (store == null) { throw ConfigurationException(IdeBundle.message("settings.password.internal.error.no.available.credential.store.implementation")) } passwordSafe.currentProvider = store } catch (e: UnsatisfiedLinkError) { LOG.warn(e) if (SystemInfo.isLinux) { throw ConfigurationException(IdeBundle.message("settings.password.package.libsecret.1.0.is.not.installed")) } else { throw ConfigurationException(e.message) } } } ProviderType.KEEPASS -> createAndSaveKeePassDatabaseWithNewOptions(settings) else -> throw ConfigurationException(IdeBundle.message("settings.password.unknown.provider.type", providerType)) } } else if (isKeepassFileLocationChanged(settings)) { createAndSaveKeePassDatabaseWithNewOptions(settings) } else if (providerType == ProviderType.KEEPASS && pgpKeyChanged) { try { // not our business in this case, if there is no db file, do not require not null KeePassFileManager createKeePassFileManager()?.saveMasterKeyToApplyNewEncryptionSpec() } catch (e: ConfigurationException) { throw e } catch (e: Exception) { LOG.error(e) throw ConfigurationException(CredentialStoreBundle.message("settings.password.internal.error", e.message ?: e.toString())) } } // not in createAndSaveKeePassDatabaseWithNewOptions (as logically should be) because we want to force users to set custom master passwords even if some another setting (not path) was changed // (e.g. PGP key) if (providerType == ProviderType.KEEPASS) { createKeePassFileManager()?.setCustomMasterPasswordIfNeeded(getDefaultKeePassDbFile()) } settings.providerType = providerType } // existing in-memory KeePass database is not used, the same as if switched to KEYCHAIN // for KeePass not clear - should we append in-memory credentials to existing database or not // (and if database doesn't exist, should we append or not), so, wait first user request (prefer to keep implementation simple) private fun createAndSaveKeePassDatabaseWithNewOptions(settings: PasswordSafeSettings) { val newDbFile = getNewDbFile() ?: throw ConfigurationException(CredentialStoreBundle.message("settings.password.keepass.database.path.is.empty")) if (newDbFile.isDirectory()) { // we do not normalize as we do on file choose because if user decoded to type path manually, // it should be valid path and better to avoid any magic here throw ConfigurationException(CredentialStoreBundle.message("settings.password.keepass.database.file.is.directory.")) } if (!newDbFile.fileName.toString().endsWith(".kdbx")) { throw ConfigurationException(CredentialStoreBundle.message("settings.password.keepass.database.file.should.ends.with.kdbx")) } settings.keepassDb = newDbFile.toString() try { KeePassFileManager(newDbFile, getDefaultMasterPasswordFile(), getEncryptionSpec(), secureRandom).useExisting() } catch (e: IncorrectMasterPasswordException) { throw ConfigurationException(CredentialStoreBundle.message("settings.password.master.password.for.keepass.database.is.not.correct")) } catch (e: Exception) { LOG.error(e) throw ConfigurationException(CredentialStoreBundle.message("settings.password.internal.error", e.message ?: e.toString())) } } private fun getNewDbFile() = getNewDbFileAsString()?.let { Paths.get(it) } private fun getNewDbFileAsString() = keePassDbFile!!.text.trim().nullize() override fun getComponent(): JPanel { myPanel = panel { buttonsGroup(CredentialStoreBundle.message("passwordSafeConfigurable.save.password")) { row { radioButton(CredentialStoreBundle.message("passwordSafeConfigurable.in.native.keychain"), ProviderType.KEYCHAIN) }.visible(CredentialStoreManager.getInstance().isSupported(ProviderType.KEYCHAIN)) row { @Suppress("DialogTitleCapitalization") // KeePass is a proper noun keepassRadioButton = radioButton(CredentialStoreBundle.message("passwordSafeConfigurable.in.keepass"), ProviderType.KEEPASS).component }.visible(CredentialStoreManager.getInstance().isSupported(ProviderType.KEEPASS)) indent { row(CredentialStoreBundle.message("settings.password.database")) { val fileChooserDescriptor = FileChooserDescriptorFactory.createSingleLocalFileDescriptor().withFileFilter { it.isDirectory || it.name.endsWith(".kdbx") } keePassDbFile = textFieldWithBrowseButton(CredentialStoreBundle.message("passwordSafeConfigurable.keepass.database.file"), fileChooserDescriptor = fileChooserDescriptor, fileChosen = { val path = when { it.isDirectory -> "${it.path}${File.separator}$DB_FILE_NAME" else -> it.path } return@textFieldWithBrowseButton File(path).path }) .resizableColumn() .horizontalAlign(HorizontalAlign.FILL) .gap(RightGap.SMALL) .apply { if (!SystemInfo.isWindows) comment(CredentialStoreBundle.message("passwordSafeConfigurable.weak.encryption")) }.component actionsButton( ClearKeePassDatabaseAction(), ImportKeePassDatabaseAction(), ChangeKeePassDatabaseMasterPasswordAction() ) } row { usePgpKey = checkBox(usePgpKeyText()) .bindSelected({ !pgpListModel.isEmpty && settings.state.pgpKeyId != null }, { if (!it) settings.state.pgpKeyId = null }) .gap(RightGap.SMALL) .component pgpKeyCombo = comboBox<PgpKey>(pgpListModel, renderer = listCellRenderer { value, _, _ -> setText("${value.userId} (${value.keyId})") }).bindItem({ getSelectedPgpKey() ?: pgpListModel.items.firstOrNull() }, { settings.state.pgpKeyId = if (usePgpKey.isSelected) it?.keyId else null }) .columns(COLUMNS_MEDIUM) .enabledIf(usePgpKey.selected) .component } } .enabledIf(keepassRadioButton.selected) .visible(CredentialStoreManager.getInstance().isSupported(ProviderType.KEEPASS)) row { radioButton(CredentialStoreBundle.message("passwordSafeConfigurable.do.not.save"), ProviderType.MEMORY_ONLY) }.visible(CredentialStoreManager.getInstance().isSupported(ProviderType.MEMORY_ONLY)) }.bind(settings::providerType) } return myPanel } @NlsContexts.Checkbox private fun usePgpKeyText(): String { return if (pgpListModel.isEmpty) CredentialStoreBundle.message("passwordSafeConfigurable.protect.master.password.using.pgp.key.no.keys") else CredentialStoreBundle.message("passwordSafeConfigurable.protect.master.password.using.pgp.key") } private fun getSelectedPgpKey(): PgpKey? { val currentKeyId = settings.state.pgpKeyId ?: return null return (pgpListModel.items.firstOrNull { it.keyId == currentKeyId }) ?: pgpListModel.items.firstOrNull() } private fun createKeePassFileManager(): KeePassFileManager? { return KeePassFileManager(getNewDbFile() ?: return null, getDefaultMasterPasswordFile(), getEncryptionSpec(), secureRandom) } private fun getEncryptionSpec(): EncryptionSpec { return when (val pgpKey = getNewPgpKey()) { null -> EncryptionSpec(type = getDefaultEncryptionType(), pgpKeyId = null) else -> EncryptionSpec(type = EncryptionType.PGP_KEY, pgpKeyId = pgpKey.keyId) } } private fun getNewPgpKey() = pgpKeyCombo.selectedItem as? PgpKey private inner class ClearKeePassDatabaseAction : DumbAwareAction(CredentialStoreBundle.message("action.text.password.safe.clear")) { override fun actionPerformed(event: AnActionEvent) { if (!MessageDialogBuilder.yesNo(CredentialStoreBundle.message("passwordSafeConfigurable.clear.passwords"), CredentialStoreBundle.message("passwordSafeConfigurable.are.you.sure")).yesText( CredentialStoreBundle.message("passwordSafeConfigurable.remove.passwords")).ask(event.project)) { return } closeCurrentStore() LOG.info("Passwords cleared", Error()) createKeePassFileManager()?.clear() } override fun update(e: AnActionEvent) { e.presentation.isEnabled = getNewDbFile()?.exists() ?: false } override fun getActionUpdateThread() = ActionUpdateThread.BGT } private inner class ImportKeePassDatabaseAction : DumbAwareAction(CredentialStoreBundle.message("action.text.password.safe.import")) { override fun actionPerformed(event: AnActionEvent) { closeCurrentStore() FileChooserDescriptorFactory.createSingleLocalFileDescriptor() .withFileFilter { !it.isDirectory && it.nameSequence.endsWith(".kdbx") } .chooseFile(event) { createKeePassFileManager()?.import(Paths.get(it.path), event) } } } private inner class ChangeKeePassDatabaseMasterPasswordAction : DumbAwareAction( if (MasterKeyFileStorage(getDefaultMasterPasswordFile()).isAutoGenerated()) CredentialStoreBundle.message("action.set.password.text") else CredentialStoreBundle.message("action.change.password.text") ) { override fun actionPerformed(event: AnActionEvent) { closeCurrentStore() // even if current provider is not KEEPASS, all actions for db file must be applied immediately (show error if new master password not applicable for existing db file) if (createKeePassFileManager()?.askAndSetMasterKey(event) == true) { templatePresentation.text = CredentialStoreBundle.message("settings.password.change.master.password") } } override fun update(e: AnActionEvent) { e.presentation.isEnabled = getNewDbFileAsString() != null } override fun getActionUpdateThread() = ActionUpdateThread.BGT } } // we must save and close opened KeePass database before any action that can modify KeePass database files private fun closeCurrentStore() { (PasswordSafe.instance as PasswordSafeImpl).closeCurrentStore(isSave = true, isEvenMemoryOnly = false) }
apache-2.0
anitawoodruff/habitica-android
Habitica/src/main/java/com/habitrpg/android/habitica/ui/fragments/preferences/PreferencesFragment.kt
1
14068
package com.habitrpg.android.habitica.ui.fragments.preferences import android.annotation.SuppressLint import android.app.ProgressDialog import android.content.Intent import android.content.SharedPreferences import android.content.res.Configuration import android.os.Build import android.os.Bundle import androidx.appcompat.app.AlertDialog import androidx.preference.ListPreference import androidx.preference.Preference import androidx.preference.PreferenceScreen import com.habitrpg.android.habitica.BuildConfig import com.habitrpg.android.habitica.HabiticaBaseApplication import com.habitrpg.android.habitica.R import com.habitrpg.android.habitica.data.ApiClient import com.habitrpg.android.habitica.data.ContentRepository import com.habitrpg.android.habitica.helpers.* import com.habitrpg.android.habitica.helpers.notifications.PushNotificationManager import com.habitrpg.android.habitica.models.ContentResult import com.habitrpg.android.habitica.models.user.User import com.habitrpg.android.habitica.prefs.TimePreference import com.habitrpg.android.habitica.ui.activities.ClassSelectionActivity import com.habitrpg.android.habitica.ui.activities.FixCharacterValuesActivity import com.habitrpg.android.habitica.ui.activities.MainActivity import com.habitrpg.android.habitica.ui.activities.PrefsActivity import io.reactivex.functions.Consumer import java.util.* import javax.inject.Inject class PreferencesFragment : BasePreferencesFragment(), SharedPreferences.OnSharedPreferenceChangeListener { @Inject lateinit var contentRepository: ContentRepository @Inject lateinit var soundManager: SoundManager @Inject lateinit var pushNotificationManager: PushNotificationManager @Inject lateinit var configManager: AppConfigManager @Inject lateinit var apiClient: ApiClient private var timePreference: TimePreference? = null private var pushNotificationsPreference: PreferenceScreen? = null private var emailNotificationsPreference: PreferenceScreen? = null private var classSelectionPreference: Preference? = null private var serverUrlPreference: ListPreference? = null override fun onCreate(savedInstanceState: Bundle?) { HabiticaBaseApplication.userComponent?.inject(this) super.onCreate(savedInstanceState) } override fun setupPreferences() { timePreference = findPreference("reminder_time") as? TimePreference val useReminder = preferenceManager.sharedPreferences.getBoolean("use_reminder", false) timePreference?.isEnabled = useReminder pushNotificationsPreference = findPreference("pushNotifications") as? PreferenceScreen val usePushNotifications = preferenceManager.sharedPreferences.getBoolean("usePushNotifications", true) pushNotificationsPreference?.isEnabled = usePushNotifications emailNotificationsPreference = findPreference("emailNotifications") as? PreferenceScreen val useEmailNotifications = preferenceManager.sharedPreferences.getBoolean("useEmailNotifications", true) emailNotificationsPreference?.isEnabled = useEmailNotifications classSelectionPreference = findPreference("choose_class") classSelectionPreference?.isVisible = false serverUrlPreference = findPreference("server_url") as? ListPreference serverUrlPreference?.isVisible = false serverUrlPreference?.summary = preferenceManager.sharedPreferences.getString("server_url", "") val themePreference = findPreference("theme_name") as? ListPreference themePreference?.isVisible = configManager.testingLevel() == AppTestingLevel.ALPHA || BuildConfig.DEBUG themePreference?.summary = themePreference?.entry } override fun onResume() { super.onResume() preferenceManager.sharedPreferences.registerOnSharedPreferenceChangeListener(this) } override fun onPause() { preferenceManager.sharedPreferences.unregisterOnSharedPreferenceChangeListener(this) super.onPause() } override fun onPreferenceTreeClick(preference: Preference): Boolean { when(preference.key) { "logout" -> { context?.let { HabiticaBaseApplication.logout(it) } activity?.finish() } "choose_class" -> { val bundle = Bundle() bundle.putBoolean("isInitialSelection", user?.flags?.classSelected == false) val intent = Intent(activity, ClassSelectionActivity::class.java) intent.putExtras(bundle) if (user?.flags?.classSelected == true && user?.preferences?.disableClasses == false) { context?.let { context -> val builder = AlertDialog.Builder(context) .setMessage(getString(R.string.change_class_confirmation)) .setNegativeButton(getString(R.string.dialog_go_back)) { dialog, _ -> dialog.dismiss() } .setPositiveButton(getString(R.string.change_class)) { _, _ -> startActivityForResult(intent, MainActivity.SELECT_CLASS_RESULT) } val alert = builder.create() alert.show() } } else { startActivityForResult(intent, MainActivity.SELECT_CLASS_RESULT) } return true } "reload_content" -> { @Suppress("DEPRECATION") val dialog = ProgressDialog.show(context, context?.getString(R.string.reloading_content), null, true) contentRepository.retrieveContent(context,true).subscribe({ if (dialog.isShowing) { dialog.dismiss() } }) { throwable -> if (dialog.isShowing) { dialog.dismiss() } RxErrorHandler.reportError(throwable) } } "fixCharacterValues" -> { val intent = Intent(activity, FixCharacterValuesActivity::class.java) activity?.startActivity(intent) } } return super.onPreferenceTreeClick(preference) } @SuppressLint("ObsoleteSdkInt") override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences, key: String) { when (key) { "use_reminder" -> { val useReminder = sharedPreferences.getBoolean(key, false) timePreference?.isEnabled = useReminder if (useReminder) { TaskAlarmManager.scheduleDailyReminder(context) } else { TaskAlarmManager.removeDailyReminder(context) } } "reminder_time" -> { TaskAlarmManager.removeDailyReminder(context) TaskAlarmManager.scheduleDailyReminder(context) } "usePushNotifications" -> { val userPushNotifications = sharedPreferences.getBoolean(key, false) pushNotificationsPreference?.isEnabled = userPushNotifications if (userPushNotifications) { pushNotificationManager.addPushDeviceUsingStoredToken() } else { pushNotificationManager.removePushDeviceUsingStoredToken() } } "useEmailNotifications" -> { val useEmailNotifications = sharedPreferences.getBoolean(key, false) emailNotificationsPreference?.isEnabled = useEmailNotifications } "cds_time" -> { val timeval = sharedPreferences.getString("cds_time", "00:00") val pieces = timeval?.split(":".toRegex())?.dropLastWhile { it.isEmpty() }?.toTypedArray() if (pieces != null) { val hour = Integer.parseInt(pieces[0]) userRepository.changeCustomDayStart(hour).subscribe(Consumer { }, RxErrorHandler.handleEmptyError()) } } "language" -> { val languageHelper = LanguageHelper(sharedPreferences.getString(key, "en")) Locale.setDefault(languageHelper.locale) val configuration = Configuration() if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.JELLY_BEAN) { @Suppress("Deprecation") configuration.locale = languageHelper.locale } else { configuration.setLocale(languageHelper.locale) } @Suppress("DEPRECATION") activity?.resources?.updateConfiguration(configuration, activity?.resources?.displayMetrics) userRepository.updateLanguage(user, languageHelper.languageCode ?: "en") .flatMap<ContentResult> { contentRepository.retrieveContent(context,true) } .subscribe(Consumer { }, RxErrorHandler.handleEmptyError()) if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1) { val intent = Intent(activity, MainActivity::class.java) intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP startActivity(intent) } else { val intent = Intent(activity, MainActivity::class.java) this.startActivity(intent) activity?.finishAffinity() } } "audioTheme" -> { val newAudioTheme = sharedPreferences.getString(key, "off") if (newAudioTheme != null) { compositeSubscription.add(userRepository.updateUser(user, "preferences.sound", newAudioTheme) .subscribe(Consumer { }, RxErrorHandler.handleEmptyError())) soundManager.soundTheme = newAudioTheme soundManager.preloadAllFiles() } } "theme_name" -> { val activity = activity as? PrefsActivity ?: return activity.reload() } "dailyDueDefaultView" -> userRepository.updateUser(user, "preferences.dailyDueDefaultView", sharedPreferences.getBoolean(key, false)) .subscribe(Consumer { }, RxErrorHandler.handleEmptyError()) "server_url" -> { apiClient.updateServerUrl(sharedPreferences.getString(key, "")) findPreference(key).summary = sharedPreferences.getString(key, "") } } } override fun onDisplayPreferenceDialog(preference: Preference) { if (preference is TimePreference) { if (preference.getKey() == "cds_time") { if (fragmentManager?.findFragmentByTag(DayStartPreferenceDialogFragment.TAG) == null) { fragmentManager?.let { DayStartPreferenceDialogFragment.newInstance(this, preference.getKey()) .show(it, DayStartPreferenceDialogFragment.TAG) } } } else { if (fragmentManager?.findFragmentByTag(TimePreferenceDialogFragment.TAG) == null) { fragmentManager?.let { TimePreferenceDialogFragment.newInstance(this, preference.getKey()) .show(it, TimePreferenceDialogFragment.TAG) } } } } else { super.onDisplayPreferenceDialog(preference) } } override fun setUser(user: User?) { super.setUser(user) if (10 <= user?.stats?.lvl ?: 0) { if (user?.flags?.classSelected == true) { if (user.preferences?.disableClasses == true) { classSelectionPreference?.title = getString(R.string.enable_class) } else { classSelectionPreference?.title = getString(R.string.change_class) classSelectionPreference?.summary = getString(R.string.change_class_description) } classSelectionPreference?.isVisible = true } else { classSelectionPreference?.title = getString(R.string.enable_class) classSelectionPreference?.isVisible = true } } val cdsTimePreference = findPreference("cds_time") as? TimePreference cdsTimePreference?.text = user?.preferences?.dayStart.toString() + ":00" findPreference("dailyDueDefaultView").setDefaultValue(user?.preferences?.dailyDueDefaultView) val languagePreference = findPreference("language") as? ListPreference languagePreference?.value = user?.preferences?.language languagePreference?.summary = languagePreference?.entry val audioThemePreference = findPreference("audioTheme") as? ListPreference audioThemePreference?.value = user?.preferences?.sound audioThemePreference?.summary = audioThemePreference?.entry val preference = findPreference("authentication") if (user?.flags?.isVerifiedUsername == true) { preference.layoutResource = R.layout.preference_child_summary preference.summary = context?.getString(R.string.authentication_summary) } else { preference.layoutResource = R.layout.preference_child_summary_error preference.summary = context?.getString(R.string.username_not_confirmed) } if (user?.contributor?.admin == true) { serverUrlPreference?.isVisible = true } } }
gpl-3.0
Flank/flank
test_projects/android/benchmark/src/androidTest/java/com/example/test/benchmark/Run3DMark.kt
1
4423
package com.example.test.benchmark import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.platform.app.InstrumentationRegistry import androidx.test.uiautomator.By import androidx.test.uiautomator.UiDevice import androidx.test.uiautomator.UiSelector import androidx.test.uiautomator.Until import org.junit.Assert import org.junit.Test import org.junit.runner.RunWith private const val TIMEOUT = 10_000L private const val BENCHMARK_TIMEOUT = 15 * 60 * 1000L private const val DOWNLOAD_TIMEOUT = 5 * 60 * 1000L @RunWith(AndroidJUnit4::class) class Run3DMark { private object Text { const val search = "Search" const val ok = "OK" const val allow = "Allow" const val permTitle = "Before we start…" const val appName = "3DMark" const val benchmarkType = "SLING SHOT" } private object Res { const val centerLayout = "com.futuremark.dmandroid.application:id/flm_pager_benchmarks" const val centerLayoutChild = "com.futuremark.dmandroid.application:id/flm_cl_root" const val btnSkip = "com.futuremark.dmandroid.application:id/flm_bt_tutorial_skip" const val fabBenchmark = "com.futuremark.dmandroid.application:id/flm_fab_benchmark" const val fabSettings = "com.futuremark.dmandroid.application:id/flm_fab_settings" const val scoreDetails = "com.futuremark.dmandroid.application:id/flm_ll_score_details_container" } @Test fun run() { UiDevice.getInstance( InstrumentationRegistry.getInstrumentation() ).run { // Start from the home screen pressHome() // Open apps menu on pixel launcher findObject(UiSelector().descriptionContains(Text.search)).apply { swipe(0, visibleBounds.centerY(), 0, 0, 10) } // Wait for 3d mark launcher icon wait(Until.hasObject(By.text(Text.appName)), TIMEOUT) waitForIdle(5000) // Click 3d mark launcher icon findObject(UiSelector().text(Text.appName)).click() waitForIdle(5000) // Check permissions dialog if (findObject(UiSelector().text(Text.permTitle)).exists()) { findObject(UiSelector().text(Text.ok)).click() findObject(UiSelector().text(Text.allow)).click() } waitForIdle(5000) Thread.sleep(4000) // Skip tutorial if needed findObject(UiSelector().resourceId(Res.btnSkip)).apply { if (exists()) click() } waitForIdle(5000) Thread.sleep(2000) // Swipe to the sling shot benchmark if needed var swipeCount = 0 while (findObject(UiSelector().text(Text.benchmarkType)).exists().not()) { findObject(UiSelector().resourceId(Res.centerLayoutChild)).apply { with(visibleBounds) { swipe(right - 80, centerY(), left + 10, centerY(), 10) } } waitForIdle(2000) Thread.sleep(1500) if (swipeCount++ >= 4) Assert.fail("Max swipe count exceeded") } waitForIdle(2000) // Choose proper benchmark screen findObject(UiSelector().text(Text.benchmarkType)).click() waitForIdle(5000) // Settings fab is not visible if the additional software is not installed if (findObject(UiSelector().resourceId(Res.fabSettings)).exists().not()) { // Install additional software findObject(UiSelector().resourceId(Res.fabBenchmark)).click() // Wait until download finish wait( Until.hasObject(By.res(Res.fabSettings)), DOWNLOAD_TIMEOUT ) } // Run benchmark findObject(UiSelector().resourceId(Res.fabBenchmark)).click() waitForIdle(5000) // Wait until benchmark finish wait(Until.hasObject(By.res(Res.scoreDetails)), BENCHMARK_TIMEOUT) // Assert that benchmark results screen is visible Assert.assertTrue(findObject(UiSelector().resourceId(Res.scoreDetails)).exists()) // Make sure that results was recorded Thread.sleep(5000) } } }
apache-2.0
jotomo/AndroidAPS
app/src/test/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Option_Get_User_OptionTest.kt
1
1207
package info.nightscout.androidaps.danars.comm import dagger.android.AndroidInjector import dagger.android.HasAndroidInjector import org.junit.Assert import org.junit.Test import org.junit.runner.RunWith import org.powermock.modules.junit4.PowerMockRunner @RunWith(PowerMockRunner::class) class DanaRS_Packet_Option_Get_User_OptionTest : DanaRSTestBase() { private val packetInjector = HasAndroidInjector { AndroidInjector { if (it is DanaRS_Packet_Option_Get_User_Option) { it.aapsLogger = aapsLogger it.danaPump = danaPump } } } @Test fun runTest() { val packet = DanaRS_Packet_Option_Get_User_Option(packetInjector) // test params Assert.assertEquals(null, packet.requestParams) // test message decoding packet.handleMessage(createArray(20, 0.toByte())) Assert.assertEquals(true, packet.failed) // everything ok :) packet.handleMessage(createArray(20, 5.toByte())) Assert.assertEquals(5, danaPump.lcdOnTimeSec) Assert.assertEquals(false, packet.failed) Assert.assertEquals("OPTION__GET_USER_OPTION", packet.friendlyName) } }
agpl-3.0
michaelkourlas/voipms-sms-client
voipms-sms/src/main/kotlin/net/kourlas/voipms_sms/conversation/MessageTextView.kt
1
3583
/* * VoIP.ms SMS * Copyright (C) 2020 Michael Kourlas * * Portions copyright (C) 2006 The Android Open Source Project (taken from * LinkMovementMethod.java) * Portions copyright (C) saket (taken from BetterLinkMovementMethod.java) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.kourlas.voipms_sms.conversation import android.annotation.SuppressLint import android.content.Context import android.text.Selection import android.text.Spannable import android.text.style.ClickableSpan import android.util.AttributeSet import android.view.HapticFeedbackConstants import android.view.MotionEvent import android.view.ViewConfiguration import androidx.appcompat.widget.AppCompatTextView class MessageTextView @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0 ) : AppCompatTextView( context, attrs, defStyleAttr ) { private var longClick = false var messageLongClickListener: (() -> Unit)? = null @SuppressLint("ClickableViewAccessibility") override fun onTouchEvent(event: MotionEvent?): Boolean { if (!(event?.action == MotionEvent.ACTION_UP || event?.action == MotionEvent.ACTION_DOWN) ) { if (event?.action == MotionEvent.ACTION_CANCEL) { longClick = false } return super.onTouchEvent(event) } val x = event.x.toInt() - totalPaddingLeft + scrollX val y = event.y.toInt() - totalPaddingTop + scrollY val line = layout?.getLineForVertical(y) ?: return super.onTouchEvent(event) val off = layout?.getOffsetForHorizontal(line, x.toFloat()) ?: return super.onTouchEvent(event) val buffer = text if (buffer !is Spannable) { return super.onTouchEvent(event) } val links = buffer.getSpans(off, off, ClickableSpan::class.java) if (links.isNotEmpty()) { val link = links[0] when (event.action) { MotionEvent.ACTION_UP -> { if (!longClick) { link.onClick(this) } longClick = false } MotionEvent.ACTION_DOWN -> { Selection.setSelection( buffer, buffer.getSpanStart(link), buffer.getSpanEnd(link) ) postDelayed( { longClick = true performHapticFeedback( HapticFeedbackConstants.LONG_PRESS ) messageLongClickListener?.invoke() }, ViewConfiguration.getLongPressTimeout().toLong() ) } } return true } else { Selection.removeSelection(buffer) } return super.onTouchEvent(event) } }
apache-2.0
siosio/intellij-community
java/java-tests/testSrc/com/intellij/java/codeInsight/daemon/ModuleHighlightingTest.kt
1
28812
// 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.java.codeInsight.daemon import com.intellij.codeInsight.daemon.impl.JavaHighlightInfoTypes import com.intellij.codeInsight.daemon.impl.analysis.JavaModuleGraphUtil import com.intellij.codeInsight.intention.IntentionActionDelegate import com.intellij.codeInspection.deprecation.DeprecationInspection import com.intellij.codeInspection.deprecation.MarkedForRemovalInspection import com.intellij.java.testFramework.fixtures.LightJava9ModulesCodeInsightFixtureTestCase import com.intellij.java.testFramework.fixtures.MultiModuleJava9ProjectDescriptor.ModuleDescriptor import com.intellij.java.testFramework.fixtures.MultiModuleJava9ProjectDescriptor.ModuleDescriptor.* import com.intellij.openapi.roots.ProjectRootManager import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiManager import com.intellij.psi.search.ProjectScope import org.assertj.core.api.Assertions.assertThat import java.util.jar.JarFile class ModuleHighlightingTest : LightJava9ModulesCodeInsightFixtureTestCase() { override fun setUp() { super.setUp() addFile("module-info.java", "module M2 { }", M2) addFile("module-info.java", "module M3 { }", M3) } fun testPackageStatement() { highlight("package pkg;") highlight(""" <error descr="A module file should not have 'package' statement">package pkg;</error> module M { }""".trimIndent()) fixes("<caret>package pkg;\nmodule M { }", arrayOf("DeleteElementFix", "FixAllHighlightingProblems")) } fun testSoftKeywords() { addFile("pkg/module/C.java", "package pkg.module;\npublic class C { }") myFixture.configureByText("module-info.java", "module M { exports pkg.module; }") val keywords = myFixture.doHighlighting().filter { it.type == JavaHighlightInfoTypes.JAVA_KEYWORD } assertEquals(2, keywords.size) assertEquals(TextRange(0, 6), TextRange(keywords[0].startOffset, keywords[0].endOffset)) assertEquals(TextRange(11, 18), TextRange(keywords[1].startOffset, keywords[1].endOffset)) } fun testWrongFileName() { highlight("M.java", """/* ... */ <error descr="Module declaration should be in a file named 'module-info.java'">module M</error> { }""") } fun testFileDuplicate() { addFile("pkg/module-info.java", """module M.bis { }""") highlight("""<error descr="'module-info.java' already exists in the module">module M</error> { }""") } fun testFileDuplicateInTestRoot() { addTestFile("module-info.java", """module M.test { }""") highlight("""<error descr="'module-info.java' already exists in the module">module M</error> { }""") } fun testWrongFileLocation() { highlight("pkg/module-info.java", """<error descr="Module declaration should be located in a module's source root">module M</error> { }""") } fun testIncompatibleModifiers() { highlight(""" module M { requires static transitive M2; requires <error descr="Modifier 'private' not allowed here">private</error> <error descr="Modifier 'volatile' not allowed here">volatile</error> M3; }""".trimIndent()) } fun testAnnotations() { highlight("""@Deprecated <error descr="'@Override' not applicable to module">@Override</error> module M { }""") } fun testDuplicateStatements() { addFile("pkg/main/C.java", "package pkg.main;\npublic class C { }") addFile("pkg/main/Impl.java", "package pkg.main;\npublic class Impl extends C { }") highlight(""" import pkg.main.C; module M { requires M2; <error descr="Duplicate 'requires': M2">requires M2;</error> exports pkg.main; <error descr="Duplicate 'exports': pkg.main">exports pkg. main;</error> opens pkg.main; <error descr="Duplicate 'opens': pkg.main">opens pkg. main;</error> uses C; <error descr="Duplicate 'uses': pkg.main.C">uses pkg. main . /*...*/ C;</error> provides pkg .main .C with pkg.main.Impl; <error descr="Duplicate 'provides': pkg.main.C">provides C with pkg. main. Impl;</error> }""".trimIndent()) } fun testUnusedServices() { addFile("pkg/main/C1.java", "package pkg.main;\npublic class C1 { }") addFile("pkg/main/C2.java", "package pkg.main;\npublic class C2 { }") addFile("pkg/main/C3.java", "package pkg.main;\npublic class C3 { }") addFile("pkg/main/Impl1.java", "package pkg.main;\npublic class Impl1 extends C1 { }") addFile("pkg/main/Impl2.java", "package pkg.main;\npublic class Impl2 extends C2 { }") addFile("pkg/main/Impl3.java", "package pkg.main;\npublic class Impl3 extends C3 { }") highlight(""" import pkg.main.C2; import pkg.main.C3; module M { uses C2; uses pkg.main.C3; provides pkg.main.<warning descr="Service interface provided but not exported or used">C1</warning> with pkg.main.Impl1; provides pkg.main.C2 with pkg.main.Impl2; provides C3 with pkg.main.Impl3; }""".trimIndent()) } fun testRequires() { addFile("module-info.java", "module M2 { requires M1 }", M2) addFile(JarFile.MANIFEST_NAME, "Manifest-Version: 1.0\nAutomatic-Module-Name: all.fours\n", M4) highlight(""" module M1 { requires <error descr="Module not found: M.missing">M.missing</error>; requires <error descr="Cyclic dependence: M1">M1</error>; requires <error descr="Cyclic dependence: M1, M2">M2</error>; requires <error descr="Module is not in dependencies: M3">M3</error>; requires <warning descr="Ambiguous module reference: lib.auto">lib.auto</warning>; requires lib.multi.release; requires lib.named; requires lib.claimed; requires all.fours; }""".trimIndent()) addFile(JarFile.MANIFEST_NAME, "Manifest-Version: 1.0\n", M4) highlight("""module M1 { requires <error descr="Module not found: all.fours">all.fours</error>; }""") addFile(JarFile.MANIFEST_NAME, "Manifest-Version: 1.0\nAutomatic-Module-Name: all.fours\n", M4) highlight("""module M1 { requires all.fours; }""") } fun testExports() { addFile("pkg/empty/package-info.java", "package pkg.empty;") addFile("pkg/main/C.java", "package pkg.main;\nclass C { }") highlight(""" module M { exports <error descr="Package not found: pkg.missing.unknown">pkg.missing.unknown</error>; exports <error descr="Package is empty: pkg.empty">pkg.empty</error>; exports pkg.main to <warning descr="Module not found: M.missing">M.missing</warning>, M2, <error descr="Duplicate 'exports' target: M2">M2</error>; }""".trimIndent()) addTestFile("pkg/tests/T.java", "package pkg.tests;\nclass T { }", M_TEST) highlight("module-info.java", "module M { exports pkg.tests; }".trimIndent(), M_TEST, true) } fun testOpens() { addFile("pkg/main/C.java", "package pkg.main;\nclass C { }") addFile("pkg/resources/resource.txt", "...") highlight(""" module M { opens <warning descr="Package not found: pkg.missing.unknown">pkg.missing.unknown</warning>; opens pkg.main to <warning descr="Module not found: M.missing">M.missing</warning>, M2, <error descr="Duplicate 'opens' target: M2">M2</error>; opens pkg.resources; }""".trimIndent()) addTestFile("pkg/tests/T.java", "package pkg.tests;\nclass T { }", M_TEST) highlight("module-info.java", "module M { opens pkg.tests; }".trimIndent(), M_TEST, true) } fun testWeakModule() { highlight("""open module M { <error descr="'opens' is not allowed in an open module">opens pkg.missing;</error> }""") } fun testUses() { addFile("pkg/main/C.java", "package pkg.main;\nclass C { void m(); }") addFile("pkg/main/O.java", "package pkg.main;\npublic class O {\n public class I { void m(); }\n}") addFile("pkg/main/E.java", "package pkg.main;\npublic enum E { }") highlight(""" module M { uses pkg.<error descr="Cannot resolve symbol 'main'">main</error>; uses pkg.main.<error descr="Cannot resolve symbol 'X'">X</error>; uses pkg.main.<error descr="'pkg.main.C' is not public in 'pkg.main'. Cannot be accessed from outside package">C</error>; uses pkg.main.<error descr="The service definition is an enum: E">E</error>; uses pkg.main.O.I; uses pkg.main.O.I.<error descr="Cannot resolve symbol 'm'">m</error>; }""".trimIndent()) } fun testProvides() { addFile("pkg/main/C.java", "package pkg.main;\npublic interface C { }") addFile("pkg/main/CT.java", "package pkg.main;\npublic interface CT<T> { }") addFile("pkg/main/Impl1.java", "package pkg.main;\nclass Impl1 { }") addFile("pkg/main/Impl2.java", "package pkg.main;\npublic class Impl2 { }") addFile("pkg/main/Impl3.java", "package pkg.main;\npublic abstract class Impl3 implements C { }") addFile("pkg/main/Impl4.java", "package pkg.main;\npublic class Impl4 implements C {\n public Impl4(String s) { }\n}") addFile("pkg/main/Impl5.java", "package pkg.main;\npublic class Impl5 implements C {\n protected Impl5() { }\n}") addFile("pkg/main/Impl6.java", "package pkg.main;\npublic class Impl6 implements C { }") addFile("pkg/main/Impl7.java", "package pkg.main;\npublic class Impl7 {\n public static void provider();\n}") addFile("pkg/main/Impl8.java", "package pkg.main;\npublic class Impl8 {\n public static C provider();\n}") addFile("pkg/main/Impl9.java", "package pkg.main;\npublic class Impl9 {\n public class Inner implements C { }\n}") addFile("pkg/main/Impl10.java", "package pkg.main;\npublic class Impl10<T> implements CT<T> {\n private Impl10() { }\n public static CT provider();\n}") addFile("module-info.java", "module M2 {\n exports pkg.m2;\n}", M2) addFile("pkg/m2/C.java", "package pkg.m2;\npublic class C { }", M2) addFile("pkg/m2/Impl.java", "package pkg.m2;\npublic class Impl extends C { }", M2) highlight(""" import pkg.main.Impl6; module M { requires M2; provides pkg.main.C with pkg.main.<error descr="Cannot resolve symbol 'NoImpl'">NoImpl</error>; provides pkg.main.C with pkg.main.<error descr="'pkg.main.Impl1' is not public in 'pkg.main'. Cannot be accessed from outside package">Impl1</error>; provides pkg.main.C with pkg.main.<error descr="The service implementation type must be a subtype of the service interface type, or have a public static no-args 'provider' method">Impl2</error>; provides pkg.main.C with pkg.main.<error descr="The service implementation is an abstract class: Impl3">Impl3</error>; provides pkg.main.C with pkg.main.<error descr="The service implementation does not have a public default constructor: Impl4">Impl4</error>; provides pkg.main.C with pkg.main.<error descr="The service implementation does not have a public default constructor: Impl5">Impl5</error>; provides pkg.main.C with pkg.main.Impl6, <error descr="Duplicate implementation: pkg.main.Impl6">Impl6</error>; provides pkg.main.C with pkg.main.<error descr="The 'provider' method return type must be a subtype of the service interface type: Impl7">Impl7</error>; provides pkg.main.C with pkg.main.Impl8; provides pkg.main.C with pkg.main.Impl9.<error descr="The service implementation is an inner class: Inner">Inner</error>; provides pkg.main.CT with pkg.main.Impl10; provides pkg.m2.C with pkg.m2.<error descr="The service implementation must be defined in the same module as the provides directive">Impl</error>; }""".trimIndent()) } fun testQuickFixes() { addFile("pkg/main/impl/X.java", "package pkg.main.impl;\npublic class X { }") addFile("module-info.java", "module M2 { exports pkg.m2; }", M2) addFile("pkg/m2/C2.java", "package pkg.m2;\npublic class C2 { }", M2) addFile("pkg/m3/C3.java", "package pkg.m3;\npublic class C3 { }", M3) addFile("module-info.java", "module M6 { exports pkg.m6; }", M6) addFile("pkg/m6/C6.java", "package pkg.m6;\nimport pkg.m8.*;\nimport java.util.function.*;\npublic class C6 { public void m(Consumer<C8> c) { } }", M6) addFile("module-info.java", "module M8 { exports pkg.m8; }", M8) addFile("pkg/m8/C8.java", "package pkg.m8;\npublic class C8 { }", M8) fixes("module M { requires <caret>M.missing; }", arrayOf()) fixes("module M { requires <caret>M3; }", arrayOf("AddModuleDependencyFix")) fixes("module M { exports pkg.main.impl to <caret>M3; }", arrayOf()) fixes("module M { exports <caret>pkg.missing; }", arrayOf("CreateClassInPackageInModuleFix")) fixes("module M { exports <caret>pkg.m3; }", arrayOf()) fixes("module M { uses pkg.m3.<caret>C3; }", arrayOf("AddModuleDependencyFix")) fixes("pkg/main/C.java", "package pkg.main;\nimport <caret>pkg.m2.C2;", arrayOf("AddRequiresDirectiveFix")) addFile("module-info.java", "module M { requires M6; }") addFile("pkg/main/Util.java", "package pkg.main;\nclass Util {\n static <T> void sink(T t) { }\n}") fixes("pkg/main/C.java", "package pkg.main;\nimport pkg.m6.*;class C {{ new C6().m(<caret>Util::sink); }}", arrayOf("AddRequiresDirectiveFix")) fixes("pkg/main/C.java", "package pkg.main;\nimport pkg.m6.*;class C {{ new C6().m(<caret>t -> Util.sink(t)); }}", arrayOf("AddRequiresDirectiveFix")) addFile("module-info.java", "module M2 { }", M2) fixes("module M { requires M2; uses <caret>pkg.m2.C2; }", arrayOf("AddExportsDirectiveFix")) fixes("pkg/main/C.java", "package pkg.main;\nimport <caret>pkg.m2.C2;", arrayOf("AddExportsDirectiveFix")) addFile("pkg/main/S.java", "package pkg.main;\npublic class S { }") fixes("module M { provides pkg.main.<caret>S with pkg.main.S; }", arrayOf("AddExportsDirectiveFix", "AddUsesDirectiveFix")) } fun testPackageAccessibility() = doTestPackageAccessibility(moduleFileInTests = false, checkFileInTests = false) fun testPackageAccessibilityInNonModularTest() = doTestPackageAccessibility(moduleFileInTests = true, checkFileInTests = false) fun testPackageAccessibilityInModularTest() = doTestPackageAccessibility(moduleFileInTests = true, checkFileInTests = true) private fun doTestPackageAccessibility(moduleFileInTests: Boolean = false, checkFileInTests: Boolean = false) { val moduleFileText = "module M { requires M2; requires M6; requires lib.named; requires lib.auto; }" if (moduleFileInTests) addTestFile("module-info.java", moduleFileText) else addFile("module-info.java", moduleFileText) addFile("module-info.java", "module M2 { exports pkg.m2; exports pkg.m2.impl to close.friends.only; }", M2) addFile("pkg/m2/C2.java", "package pkg.m2;\npublic class C2 { }", M2) addFile("pkg/m2/impl/C2Impl.java", "package pkg.m2.impl;\nimport pkg.m2.C2;\npublic class C2Impl { public static int I; public static C2 make() {} }", M2) addFile("pkg/sub/C2X.java", "package pkg.sub;\npublic class C2X { }", M2) addFile("pkg/unreachable/C3.java", "package pkg.unreachable;\npublic class C3 { }", M3) addFile("pkg/m4/C4.java", "package pkg.m4;\npublic class C4 { }", M4) addFile("module-info.java", "module M5 { exports pkg.m5; }", M5) addFile("pkg/m5/C5.java", "package pkg.m5;\npublic class C5 { }", M5) addFile("module-info.java", "module M6 { requires transitive M7; exports pkg.m6.inner; }", M6) addFile("pkg/sub/C6X.java", "package pkg.sub;\npublic class C6X { }", M6) addFile("pkg/m6/C6_1.java", "package pkg.m6.inner;\npublic class C6_1 {}", M6) //addFile("pkg/m6/C6_2.kt", "package pkg.m6.inner\n class C6_2", M6) TODO: uncomment to fail the test addFile("module-info.java", "module M7 { exports pkg.m7; }", M7) addFile("pkg/m7/C7.java", "package pkg.m7;\npublic class C7 { }", M7) var checkFileText = """ import pkg.m2.C2; import pkg.m2.*; import <error descr="Package 'pkg.m2.impl' is declared in module 'M2', which does not export it to module 'M'">pkg.m2.impl</error>.C2Impl; import <error descr="Package 'pkg.m2.impl' is declared in module 'M2', which does not export it to module 'M'">pkg.m2.impl</error>.*; import <error descr="Package 'pkg.m4' is declared in the unnamed module, but module 'M' does not read it">pkg.m4</error>.C4; import <error descr="Package 'pkg.m5' is declared in module 'M5', but module 'M' does not read it">pkg.m5</error>.C5; import pkg.m7.C7; import <error descr="Package 'pkg.sub' is declared in module 'M2', which does not export it to module 'M'">pkg.sub</error>.*; import <error descr="Package not found: pkg.unreachable">pkg.unreachable</error>.*; import pkg.lib1.LC1; import <error descr="Package 'pkg.lib1.impl' is declared in module 'lib.named', which does not export it to module 'M'">pkg.lib1.impl</error>.LC1Impl; import <error descr="Package 'pkg.lib1.impl' is declared in module 'lib.named', which does not export it to module 'M'">pkg.lib1.impl</error>.*; import pkg.lib2.LC2; import pkg.lib2.impl.LC2Impl; import static <error descr="Package 'pkg.m2.impl' is declared in module 'M2', which does not export it to module 'M'">pkg.m2.impl</error>.C2Impl.make; import java.util.List; import java.util.function.Supplier; import <error descr="Package 'pkg.libInvalid' is declared in module with an invalid name ('lib.invalid.1.2')">pkg.libInvalid</error>.LCInv; import pkg.m6.inner.C6_1; //import pkg.m6.inner.C6_2; /** See also {@link C2Impl#I} and {@link C2Impl#make} */ class C {{ <error descr="Package 'pkg.m2.impl' is declared in module 'M2', which does not export it to module 'M'">C2Impl</error>.I = 0; <error descr="Package 'pkg.m2.impl' is declared in module 'M2', which does not export it to module 'M'">C2Impl</error>.make(); <error descr="Package 'pkg.m2.impl' is declared in module 'M2', which does not export it to module 'M'">pkg.m2.impl</error>.C2Impl.I = 1; <error descr="Package 'pkg.m2.impl' is declared in module 'M2', which does not export it to module 'M'">pkg.m2.impl</error>.C2Impl.make(); List<<error descr="Package 'pkg.m2.impl' is declared in module 'M2', which does not export it to module 'M'">C2Impl</error>> l1 = null; List<<error descr="Package 'pkg.m2.impl' is declared in module 'M2', which does not export it to module 'M'">pkg.m2.impl</error>.C2Impl> l2 = null; Supplier<C2> s1 = <error descr="Package 'pkg.m2.impl' is declared in module 'M2', which does not export it to module 'M'">C2Impl</error>::make; Supplier<C2> s2 = <error descr="Package 'pkg.m2.impl' is declared in module 'M2', which does not export it to module 'M'">pkg.m2.impl</error>.C2Impl::make; }} """.trimIndent() if (moduleFileInTests != checkFileInTests) { checkFileText = Regex("(<error [^>]+>)([^<]+)(</error>)").replace(checkFileText) { if (it.value.contains("unreachable")) it.value else it.groups[2]!!.value } } highlight("test.java", checkFileText, isTest = checkFileInTests) } fun testPackageAccessibilityOverTestScope() { addFile("module-info.java", "module M2 { exports pkg.m2; exports pkg.m2.impl to close.friends.only; }", M2) addFile("pkg/m2/C2.java", "package pkg.m2;\npublic class C2 { }", M2) addFile("pkg/m2/impl/C2Impl.java", "package pkg.m2.impl;\nimport pkg.m2.C2;\npublic class C2Impl { public static int I; public static C2 make() {} }", M2) highlight("module-info.java", "module M.test { requires M2; }", M_TEST, isTest = true) val highlightText = """ import pkg.m2.C2; import pkg.m2.*; import <error descr="Package 'pkg.m2.impl' is declared in module 'M2', which does not export it to module 'M.test'">pkg.m2.impl</error>.C2Impl; import <error descr="Package 'pkg.m2.impl' is declared in module 'M2', which does not export it to module 'M.test'">pkg.m2.impl</error>.*; """.trimIndent() highlight("test.java", highlightText, M_TEST, isTest = true) } fun testPrivateJdkPackage() { addFile("module-info.java", "module M { }") highlight("test.java", """ import <error descr="Package 'jdk.internal' is declared in module 'java.base', which does not export it to module 'M'">jdk.internal</error>.*; """.trimIndent()) } fun testPrivateJdkPackageFromUnnamed() { highlight("test.java", """ import <error descr="Package 'jdk.internal' is declared in module 'java.base', which does not export it to the unnamed module">jdk.internal</error>.*; """.trimIndent()) } fun testNonRootJdkModule() { highlight("test.java", """ import <error descr="Package 'java.non.root' is declared in module 'java.non.root', which is not in the module graph">java.non.root</error>.*; """.trimIndent()) } fun testUpgradeableModuleOnClasspath() { highlight("test.java", """ import java.xml.bind.*; import java.xml.bind.C; """.trimIndent()) } fun testUpgradeableModuleOnModulePath() { myFixture.enableInspections(DeprecationInspection(), MarkedForRemovalInspection()) highlight(""" module M { requires <error descr="'java.xml.bind' is deprecated and marked for removal">java.xml.bind</error>; requires java.xml.ws; }""".trimIndent()) } fun testLinearModuleGraphBug() { addFile("module-info.java", "module M6 { requires M7; }", M6) addFile("module-info.java", "module M7 { }", M7) highlight("module M { requires M6; }") } fun testCorrectedType() { addFile("module-info.java", "module M { requires M6; requires lib.named; }") addFile("module-info.java", "module M6 { requires lib.named; exports pkg;}", M6) addFile("pkg/A.java", "package pkg; public class A {public static void foo(java.util.function.Supplier<pkg.lib1.LC1> f){}}", M6) highlight("pkg/Usage.java","import pkg.lib1.LC1; class Usage { {pkg.A.foo(LC1::new);} }") } fun testDeprecations() { myFixture.enableInspections(DeprecationInspection(), MarkedForRemovalInspection()) addFile("module-info.java", "@Deprecated module M2 { }", M2) highlight("""module M { requires <warning descr="'M2' is deprecated">M2</warning>; }""") } fun testMarkedForRemoval() { myFixture.enableInspections(DeprecationInspection(), MarkedForRemovalInspection()) addFile("module-info.java", "@Deprecated(forRemoval=true) module M2 { }", M2) highlight("""module M { requires <error descr="'M2' is deprecated and marked for removal">M2</error>; }""") } fun testPackageConflicts() { addFile("pkg/collision2/C2.java", "package pkg.collision2;\npublic class C2 { }", M2) addFile("pkg/collision4/C4.java", "package pkg.collision4;\npublic class C4 { }", M4) addFile("pkg/collision7/C7.java", "package pkg.collision7;\npublic class C7 { }", M7) addFile("module-info.java", "module M2 { exports pkg.collision2; }", M2) addFile("module-info.java", "module M4 { exports pkg.collision4 to M88; }", M4) addFile("module-info.java", "module M6 { requires transitive M7; }", M6) addFile("module-info.java", "module M7 { exports pkg.collision7 to M6; }", M7) addFile("module-info.java", "module M { requires M2; requires M4; requires M6; requires lib.auto; }") highlight("test1.java", """<error descr="Package 'pkg.collision2' exists in another module: M2">package pkg.collision2;</error>""") highlight("test2.java", """package pkg.collision4;""") highlight("test3.java", """package pkg.collision7;""") highlight("test4.java", """<error descr="Package 'java.util' exists in another module: java.base">package java.util;</error>""") highlight("test5.java", """<error descr="Package 'pkg.lib2' exists in another module: lib.auto">package pkg.lib2;</error>""") } fun testClashingReads1() { addFile("pkg/collision/C2.java", "package pkg.collision;\npublic class C2 { }", M2) addFile("pkg/collision/C7.java", "package pkg.collision;\npublic class C7 { }", M7) addFile("module-info.java", "module M2 { exports pkg.collision; }", M2) addFile("module-info.java", "module M6 { requires transitive M7; }", M6) addFile("module-info.java", "module M7 { exports pkg.collision; }", M7) highlight(""" <error descr="Module 'M' reads package 'pkg.collision' from both 'M2' and 'M7'">module M</error> { requires M2; requires M6; }""".trimIndent()) } fun testClashingReads2() { addFile("pkg/collision/C2.java", "package pkg.collision;\npublic class C2 { }", M2) addFile("pkg/collision/C4.java", "package pkg.collision;\npublic class C4 { }", M4) addFile("module-info.java", "module M2 { exports pkg.collision; }", M2) addFile("module-info.java", "module M4 { exports pkg.collision to somewhere; }", M4) highlight("module M { requires M2; requires M4; }") } fun testClashingReads3() { addFile("pkg/lib2/C2.java", "package pkg.lib2;\npublic class C2 { }", M2) addFile("module-info.java", "module M2 { exports pkg.lib2; }", M2) highlight(""" <error descr="Module 'M' reads package 'pkg.lib2' from both 'M2' and 'lib.auto'">module M</error> { requires M2; requires <warning descr="Ambiguous module reference: lib.auto">lib.auto</warning>; }""".trimIndent()) } fun testClashingReads4() { addFile("module-info.java", "module M2 { requires transitive lib.auto; }", M2) addFile("module-info.java", "module M4 { requires transitive lib.auto; }", M4) highlight("module M { requires M2; requires M4; }") } fun testInaccessibleMemberType() { addFile("module-info.java", "module C { exports pkg.c; }", M8) addFile("module-info.java", "module B { requires C; exports pkg.b; }", M6) addFile("module-info.java", "module A { requires B; }") addFile("pkg/c/C.java", "package pkg.c;\npublic class C { }", M8) addFile("pkg/b/B.java", """ package pkg.b; import pkg.c.C; public class B { private static class I { } public C f1; public I f2; public C m1(C p1, Class<? extends C> p2) { return new C(); } public I m2(I p1, Class<? extends I> p2) { return new I(); } }""".trimIndent(), M6) highlight("pkg/a/A.java", """ package pkg.a; import pkg.b.B; public class A { void test() { B exposer = new B(); exposer.f1 = null; exposer.f2 = null; Object o1 = exposer.m1(null, null); Object o2 = exposer.m2(null, null); } }""".trimIndent()) } fun testAccessingDefaultPackage() { addFile("X.java", "public class X {\n public static class XX extends X { }\n}") highlight(""" module M { uses <error descr="Class 'X' is in the default package">X</error>; provides <error descr="Class 'X' is in the default package">X</error> with <error descr="Class 'X' is in the default package">X</error>.XX; }""".trimIndent()) } fun testLightModuleDescriptorCaching() { val libClass = myFixture.javaFacade.findClass("pkg.lib2.LC2", ProjectScope.getLibrariesScope(project))!! val libModule = JavaModuleGraphUtil.findDescriptorByElement(libClass)!! PsiManager.getInstance(project).dropPsiCaches() assertSame(libModule, JavaModuleGraphUtil.findDescriptorByElement(libClass)!!) ProjectRootManager.getInstance(project).incModificationCount() assertNotSame(libModule, JavaModuleGraphUtil.findDescriptorByElement(libClass)!!) } //<editor-fold desc="Helpers."> private fun highlight(text: String) = highlight("module-info.java", text) private fun highlight(path: String, text: String, module: ModuleDescriptor = MAIN, isTest: Boolean = false) { myFixture.configureFromExistingVirtualFile(if (isTest) addTestFile(path, text, module) else addFile(path, text, module)) myFixture.checkHighlighting() } private fun fixes(text: String, fixes: Array<String>) = fixes("module-info.java", text, fixes) private fun fixes(path: String, text: String, fixes: Array<String>) { myFixture.configureFromExistingVirtualFile(addFile(path, text)) val available = myFixture.availableIntentions .map { IntentionActionDelegate.unwrap(it)::class.java } .filter { it.name.startsWith("com.intellij.codeInsight.") } .map { it.simpleName } assertThat(available).containsExactlyInAnyOrder(*fixes) } //</editor-fold> }
apache-2.0
kivensolo/UiUsingListView
library/network/src/main/java/com/zeke/reactivehttp/exception/HttpException.kt
1
2025
package com.zeke.reactivehttp.exception import com.zeke.reactivehttp.bean.IHttpWrapBean /** * @Author: leavesC * @Date: 2020/10/22 10:37 * @Desc: Exception * @GitHub:https://github.com/leavesC * 对网络请求过程中发生的各类异常情况的包装类, * 任何透传到外部的异常信息均会被封装为 BaseHttpException 类型。 * BaseHttpException 有两个默认子类,分别用于表示服务器异常和本地异常. * * @param errorCode 服务器返回的错误码 或者是 HttpConfig 中定义的本地错误码 * @param errorMessage 服务器返回的异常信息 或者是 请求过程中抛出的信息,是最原始的异常信息 * @param realException 用于当 code 是本地错误码时,存储真实的运行时异常 */ open class BaseHttpException( val errorCode: Int, val errorMessage: String, val realException: Throwable? ) : Exception(errorMessage) { companion object { /** * 此变量用于表示在网络请求过程过程中抛出了异常 */ const val CODE_ERROR_LOCAL_UNKNOWN = -1024520 } /** * 是否是由于服务器返回的 code != successCode 导致的异常 */ val isServerCodeBadException: Boolean get() = this is ServerCodeBadException /** * 是否是由于网络请求过程中抛出的异常(例如:服务器返回的 Json 解析失败) */ val isLocalBadException: Boolean get() = this is LocalBadException } /** * API 请求成功了,但 code != successCode * @param errorCode * @param errorMessage */ class ServerCodeBadException( errorCode: Int, errorMessage: String ) : BaseHttpException(errorCode, errorMessage, null) { constructor(bean: IHttpWrapBean<*>) : this(bean.httpCode, bean.httpMsg) } /** * 请求过程抛出异常 * @param throwable */ class LocalBadException(throwable: Throwable) : BaseHttpException( CODE_ERROR_LOCAL_UNKNOWN, throwable.message ?: "", throwable)
gpl-2.0
siosio/intellij-community
plugins/kotlin/idea/tests/testData/indentationOnNewline/controlFlowConstructions/Finally4.kt
12
47
fun a() = try { // do smth } finally<caret>
apache-2.0
siosio/intellij-community
plugins/kotlin/idea/tests/testData/inspectionsLocal/scopeFunctions/applyToAlso/innerLambda.kt
4
123
// WITH_RUNTIME // FIX: Convert to 'also' val x = "".also { "".<caret>apply { this.length + it.length } }
apache-2.0
feelfreelinux/WykopMobilny
app/src/main/kotlin/io/github/feelfreelinux/wykopmobilny/ui/helpers/EndlessScrollListener.kt
1
794
package io.github.feelfreelinux.wykopmobilny.ui.helpers class EndlessScrollListener( private val linearLayoutManager: androidx.recyclerview.widget.LinearLayoutManager, val listener: () -> Unit ) : androidx.recyclerview.widget.RecyclerView.OnScrollListener() { private val visibleThreshold = 2 private var lastVisibleItem = 0 private var totalItemCount = 0 override fun onScrolled(recyclerView: androidx.recyclerview.widget.RecyclerView, dx: Int, dy: Int) { super.onScrolled(recyclerView, dx, dy) totalItemCount = linearLayoutManager.itemCount lastVisibleItem = linearLayoutManager.findLastVisibleItemPosition() // End has been reached. Do something if (totalItemCount <= (lastVisibleItem + visibleThreshold)) listener() } }
mit
alexeev/jboss-fuse-mirror
tooling/archetype-builder/src/main/kotlin/org/fusesource/tooling/archetype.builder/ArchetypeBuilder.kt
3
13840
package org.fusesource.tooling.archetype.builder import java.io.File import kotlin.dom.* import org.w3c.dom.Element import org.w3c.dom.Node import org.w3c.dom.Document import org.xml.sax.InputSource import java.io.StringReader import java.io.FileWriter import java.util.TreeSet val sourceFileExtensions = hashSet( "bpmn", "drl", "html", "groovy", "jade", "java", "jbpm", "js", "json", "jsp", "kotlin", "ks", "md", "properties", "scala", "ssp", "ts", "txt", "xml" ) val excludeExtensions = hashSet("iml", "iws", "ipr") val sourceCodeDirNames = arrayList("java", "kotlin", "scala") val sourceCodeDirPaths = ( sourceCodeDirNames.map { "src/main/$it" } + sourceCodeDirNames.map { "src/test/$it" } + arrayList("target", "build", "pom.xml", "archetype-metadata.xml")).toSet() public open class ArchetypeBuilder() { public open fun configure(args: Array<String>): Unit { } public open fun generateArchetypes(sourceDir: File, outputDir: File): Unit { println("Generating archetypes from sourceDir: ${sourceDir.canonicalPath}") val files = sourceDir.listFiles() if (files != null) { for (file in files) { if (file.isDirectory()) { var pom = File(file, "pom.xml") if (pom.exists()) { val outputName = file.name.replace("example", "archetype") generateArchetype(file, pom, File(outputDir, outputName)) } } } } } protected open fun generateArchetype(directory: File, pom: File, outputDir: File): Unit { println("Generating archetype at ${outputDir.canonicalPath} from ${directory.canonicalPath}") val srcDir = File(directory, "src/main") val testDir = File(directory, "src/test") var archetypeOutputDir = File(outputDir, "src/main/resources/archetype-resources") var metadataXmlFile = File(directory, "archetype-metadata.xml") var metadataXmlOutFile = File(outputDir, "src/main/resources-filtered/META-INF/maven/archetype-metadata.xml") var replaceFunction = {(s: String) -> s } val mainSrcDir = sourceCodeDirNames.map{ File(srcDir, it) }.find { it.exists() } if (mainSrcDir != null) { // lets find the first directory which contains more than one child // to find the root-most package val rootPackage = findRootPackage(mainSrcDir) if (rootPackage != null) { val packagePath = mainSrcDir.relativePath(rootPackage) val packageName = packagePath.replaceAll("/", ".") // .replaceAll("/", "\\\\.") val regex = packageName.replaceAll("\\.", "\\\\.") replaceFunction = {(s: String) -> s.replaceAll(regex, "\\\${package}") } // lets recursively copy files replacing the package names val outputMainSrc = File(archetypeOutputDir, directory.relativePath(mainSrcDir)) copyCodeFiles(rootPackage, outputMainSrc, replaceFunction) val testSrcDir = sourceCodeDirNames.map{ File(testDir, it) }.find { it.exists() } if (testSrcDir != null) { val rootTestDir = File(testSrcDir, packagePath) val outputTestSrc = File(archetypeOutputDir, directory.relativePath(testSrcDir)) if (rootTestDir.exists()) { copyCodeFiles(rootTestDir, outputTestSrc, replaceFunction) } else { copyCodeFiles(testSrcDir, outputTestSrc, replaceFunction) } } } } copyPom(pom, File(archetypeOutputDir, "pom.xml"), metadataXmlFile, metadataXmlOutFile, replaceFunction) // now lets copy all non-ignored files across copyOtherFiles(directory, directory, archetypeOutputDir, replaceFunction) } /** * Copies all java/kotlin/scala code */ protected open fun copyCodeFiles(srcDir: File, outDir: File,replaceFn: (String) -> String): Unit { if (srcDir.isFile()) { copyFile(srcDir, outDir, replaceFn) } else { outDir.mkdirs() val names = srcDir.list() if (names != null) { for (name in names) { copyCodeFiles(File(srcDir, name), File(outDir, name), replaceFn) } } } } protected open fun copyPom(pom: File, outFile: File, metadataXmlFile: File, metadataXmlOutFile: File, replaceFn: (String) -> String): Unit { val text = replaceFn(pom.readText()) // lets update the XML val doc = parseXml(InputSource(StringReader(text))) val root = doc.documentElement // TODO would be more concise when this fixed http://youtrack.jetbrains.com/issue/KT-2922 //val propertyNameSet = sortedSet<String>() val propertyNameSet: MutableSet<String> = sortedSet<String>() if (root != null) { // remove the parent element val parents = root.elements("parent") if (parents.notEmpty()) { root.removeChild(parents[0]) } // lets find all the property names for (e in root.elements("*")) { val text = e.childrenText val prefix = "\${" if (text.startsWith(prefix)) { val offset = prefix.size val idx = text.indexOf('}', offset + 1) if (idx > 0) { val name = text.substring(offset, idx) if (isValidRequiredPropertyName(name)) { propertyNameSet.add(name) } } } } // now lets replace the contents of some elements (adding new elements if they are not present) val beforeNames = arrayList("artifactId", "version", "packaging", "name", "properties") replaceOrAddElementText(doc, root, "version", "\${version}", beforeNames) replaceOrAddElementText(doc, root, "artifactId", "\${artifactId}", beforeNames) replaceOrAddElementText(doc, root, "groupId", "\${groupId}", beforeNames) } outFile.getParentFile()?.mkdirs() doc.writeXmlString(FileWriter(outFile), true) // lets update the archetype-metadata.xml file val archetypeXmlText = if (metadataXmlFile.exists()) metadataXmlFile.readText() else defaultArchetypeXmlText() val archDoc = parseXml(InputSource(StringReader(archetypeXmlText))) val archRoot = archDoc.documentElement println("Found property names $propertyNameSet") if (archRoot != null) { // lets add all the properties val requiredProperties = replaceOrAddElement(archDoc, archRoot, "requiredProperties", arrayList("fileSets")) // lets add the various properties in for (propertyName in propertyNameSet) { requiredProperties.addText("\n ") requiredProperties.addElement("requiredProperty") { setAttribute("key", propertyName) addText("\n ") addElement("defaultValue") { addText("\${$propertyName}") } addText("\n ") } } requiredProperties.addText("\n ") } metadataXmlOutFile.getParentFile()?.mkdirs() archDoc.writeXmlString(FileWriter(metadataXmlOutFile), true) } protected fun replaceOrAddElementText(doc: Document, parent: Element, name: String, content: String, beforeNames: Iterable<String>): Element { val element = replaceOrAddElement(doc, parent, name, beforeNames) element.text = content return element } protected fun replaceOrAddElement(doc: Document, parent: Element, name: String, beforeNames: Iterable<String>): Element { val children = parent.children() val elements = children.filter { it.nodeName == name } val element = if (elements.isEmpty()) { val newElement = doc.createElement(name)!! var first: Node? = null; for (n in beforeNames) { first = findChild(parent, n) if (first != null) break } /* val before = beforeNames.map{ n -> findChild(parent, n)} val first = before.first */ val node: Node = if (first != null) first!! else parent.getFirstChild()!! val text = doc.createTextNode("\n ")!! parent.insertBefore(text, node) parent.insertBefore(newElement, text) newElement } else { elements[0] } return element as Element } protected fun findChild(parent: Element, n: String): Node? { val children = parent.children() return children.find { it.nodeName == n } } protected fun copyFile(src: File, dest: File, replaceFn: (String) -> String): Unit { if (isSourceFile(src)) { val text = replaceFn(src.readText()) dest.writeText(text) } else { println("Not a source dir as the extention is ${src.extension}") src.copyTo(dest) } } /** * Copies all other source files which are not excluded */ protected open fun copyOtherFiles(projectDir: File, srcDir: File, outDir: File, replaceFn: (String) -> String): Unit { if (isValidFileToCopy(projectDir, srcDir)) { if (srcDir.isFile()) { copyFile(srcDir, outDir, replaceFn) } else { outDir.mkdirs() val names = srcDir.list() if (names != null) { for (name in names) { copyOtherFiles(projectDir, File(srcDir, name), File(outDir, name), replaceFn) } } } } } protected open fun findRootPackage(directory: File): File? { val children = directory.listFiles { isValidSourceFileOrDir(it) } if (children != null) { val results = children.map { findRootPackage(it) }.filter { it != null } if (results.size == 1) { return results[0] } else { return directory } } return null } /** * Returns true if this file is a valid source file; so * excluding things like .svn directories and whatnot */ protected open fun isValidSourceFileOrDir(file: File): Boolean { val name = file.name return !name.startsWith(".") && !excludeExtensions.contains(file.extension) } /** * Returns true if this file is a valid source file name */ protected open fun isSourceFile(file: File): Boolean { val name = file.extension.toLowerCase() return sourceFileExtensions.contains(name) } /** * Is the file a valid file to copy (excludes files starting with a dot, build output * or java/kotlin/scala source code */ protected open fun isValidFileToCopy(projectDir: File, src: File): Boolean { if (isValidSourceFileOrDir(src)) { if (src == projectDir) return true val relative = projectDir.relativePath(src) return !sourceCodeDirPaths.contains(relative) } return false } /** * Returns true if this is a valid archetype property name, so excluding * basedir and maven "project." names */ protected open fun isValidRequiredPropertyName(name: String): Boolean { return name != "basedir" && !name.startsWith("project.") } protected open fun defaultArchetypeXmlText(): String = """<?xml version="1.0" encoding="UTF-8"?> <archetype-descriptor xsi:schemaLocation="http://maven.apache.org/plugins/maven-archetype-plugin/archetype-descriptor/1.0.0 http://maven.apache.org/xsd/archetype-descriptor-1.0.0.xsd" name="camel-archetype-java" xmlns="http://maven.apache.org/plugins/maven-archetype-plugin/archetype-descriptor/1.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <requiredProperties/> <fileSets> <fileSet filtered="true" packaged="true" encoding="UTF-8"> <directory>src/main/java</directory> <includes> <include>**/*.java</include> </includes> </fileSet> <fileSet filtered="true" encoding="UTF-8"> <directory>src/main/resources</directory> <includes> <include>**/*.bpm*</include> <include>**/*.drl</include> <include>**/*.wsdl</include> <include>**/*.xml</include> <include>**/*.properties</include> </includes> </fileSet> <fileSet filtered="true" packaged="true" encoding="UTF-8"> <directory>src/test/java</directory> <includes> <include>**/*.java</include> </includes> </fileSet> <fileSet filtered="true" encoding="UTF-8"> <directory>src/test/resources</directory> <includes> <include>**/*.xml</include> <include>**/*.properties</include> </includes> </fileSet> <fileSet filtered="true" encoding="UTF-8"> <directory>src/data</directory> <includes> <include>**/*.xml</include> </includes> </fileSet> <fileSet filtered="true" encoding="UTF-8"> <directory></directory> <includes> <include>ReadMe.*</include> </includes> </fileSet> </fileSets> </archetype-descriptor> """ }
apache-2.0
jwren/intellij-community
plugins/kotlin/completion/tests/testData/basic/java/JavaSyntheticProperty.kt
8
223
// FIR_IDENTICAL // FIR_COMPARISON fun foo(a: java.lang.Thread) { a.na<caret> } // EXIST: {"lookupString":"name","tailText":" (from getName()/setName())","allLookupStrings":"getName, name, setName","itemText":"name"}
apache-2.0
BijoySingh/Quick-Note-Android
base/src/main/java/com/maubis/scarlet/base/export/support/GenericFileProvider.kt
1
243
package com.maubis.scarlet.base.export.support import androidx.core.content.FileProvider class GenericFileProvider : FileProvider() { companion object { var PROVIDER = "com.maubis.scarlet.base.export.support.GenericFileProvider" } }
gpl-3.0
JetBrains/kotlin-native
runtime/src/main/kotlin/kotlin/internal/ProgressionUtil.kt
2
2705
/* * 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.internal // a mod b (in arithmetical sense) private fun mod(a: Int, b: Int): Int { val mod = a % b return if (mod >= 0) mod else mod + b } private fun mod(a: Long, b: Long): Long { val mod = a % b return if (mod >= 0) mod else mod + b } // (a - b) mod c private fun differenceModulo(a: Int, b: Int, c: Int): Int { return mod(mod(a, c) - mod(b, c), c) } private fun differenceModulo(a: Long, b: Long, c: Long): Long { return mod(mod(a, c) - mod(b, c), c) } /** * Calculates the final element of a bounded arithmetic progression, i.e. the last element of the progression which is in the range * from [start] to [end] in case of a positive [step], or from [end] to [start] in case of a negative * [step]. * * No validation on passed parameters is performed. The given parameters should satisfy the condition: * * - either `step > 0` and `start <= end`, * - or `step < 0` and `start >= end`. * * @param start first element of the progression * @param end ending bound for the progression * @param step increment, or difference of successive elements in the progression * @return the final element of the progression * @suppress */ @PublishedApi internal fun getProgressionLastElement(start: Int, end: Int, step: Int): Int = when { step > 0 -> if (start >= end) end else end - differenceModulo(end, start, step) step < 0 -> if (start <= end) end else end + differenceModulo(start, end, -step) else -> throw kotlin.IllegalArgumentException("Step is zero.") } /** * Calculates the final element of a bounded arithmetic progression, i.e. the last element of the progression which is in the range * from [start] to [end] in case of a positive [step], or from [end] to [start] in case of a negative * [step]. * * No validation on passed parameters is performed. The given parameters should satisfy the condition: * * - either `step > 0` and `start <= end`, * - or `step < 0` and `start >= end`. * * @param start first element of the progression * @param end ending bound for the progression * @param step increment, or difference of successive elements in the progression * @return the final element of the progression * @suppress */ @PublishedApi internal fun getProgressionLastElement(start: Long, end: Long, step: Long): Long = when { step > 0 -> if (start >= end) end else end - differenceModulo(end, start, step) step < 0 -> if (start <= end) end else end + differenceModulo(start, end, -step) else -> throw kotlin.IllegalArgumentException("Step is zero.") }
apache-2.0
jwren/intellij-community
plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/intentions/elements/CreateFieldAction.kt
4
5800
// 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.plugins.groovy.annotator.intentions.elements import com.intellij.codeInsight.daemon.QuickFixBundle.message import com.intellij.codeInsight.daemon.impl.quickfix.CreateFromUsageBaseFix.positionCursor import com.intellij.codeInsight.daemon.impl.quickfix.CreateFromUsageBaseFix.startTemplate import com.intellij.codeInsight.template.Template import com.intellij.codeInsight.template.TemplateEditingAdapter import com.intellij.lang.jvm.JvmLong import com.intellij.lang.jvm.JvmModifier import com.intellij.lang.jvm.actions.* import com.intellij.openapi.application.runWriteAction import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.psi.PsiDocumentManager import com.intellij.psi.PsiFile import com.intellij.psi.PsiType import com.intellij.psi.codeStyle.CodeStyleManager import com.intellij.psi.presentation.java.ClassPresentationUtil.getNameForClass import com.intellij.psi.util.JavaElementKind import com.intellij.psi.util.PsiTreeUtil import com.intellij.psi.util.PsiUtil import org.jetbrains.plugins.groovy.annotator.intentions.GroovyCreateFieldFromUsageHelper import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElementFactory import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrField import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrTypeDefinition import org.jetbrains.plugins.groovy.lang.psi.impl.synthetic.GroovyScriptClass import org.jetbrains.plugins.groovy.lang.psi.util.GroovyCommonClassNames internal class CreateFieldAction( target: GrTypeDefinition, request: CreateFieldRequest, private val constantField: Boolean ) : CreateFieldActionBase(target, request), JvmGroupIntentionAction { override fun getActionGroup(): JvmActionGroup = if (constantField) CreateConstantActionGroup else CreateFieldActionGroup override fun getText(): String { val what = request.fieldName val where = getNameForClass(target, false) val kind = if (constantField) JavaElementKind.CONSTANT else JavaElementKind.FIELD return message("create.element.in.class", kind.`object`(), what, where) } override fun invoke(project: Project, editor: Editor?, file: PsiFile?) { GroovyFieldRenderer(project, constantField, target, request).doRender() } } internal val constantModifiers = setOf( JvmModifier.STATIC, JvmModifier.FINAL ) private class GroovyFieldRenderer( val project: Project, val constantField: Boolean, val targetClass: GrTypeDefinition, val request: CreateFieldRequest ) { val helper = GroovyCreateFieldFromUsageHelper() val typeConstraints = createConstraints(project, request.fieldType).toTypedArray() private val modifiersToRender: Collection<JvmModifier> get() { return if (constantField) { if (targetClass.isInterface) { // interface fields are public static final implicitly, so modifiers don't have to be rendered request.modifiers - constantModifiers - visibilityModifiers } else { // render static final explicitly request.modifiers + constantModifiers } } else { // render as is request.modifiers } } fun doRender() { var field = renderField() field = insertField(field) startTemplate(field) } private fun renderField(): GrField { val elementFactory = GroovyPsiElementFactory.getInstance(project) val field = elementFactory.createField(request.fieldName, PsiType.INT) // clean template modifiers field.modifierList?.let { list -> list.firstChild?.let { list.deleteChildRange(it, list.lastChild) } } for (annotation in request.annotations) { field.modifierList?.addAnnotation(annotation.qualifiedName) } // setup actual modifiers for (modifier in modifiersToRender.map(JvmModifier::toPsiModifier)) { PsiUtil.setModifierProperty(field, modifier, true) } if (targetClass is GroovyScriptClass) field.modifierList?.addAnnotation(GroovyCommonClassNames.GROOVY_TRANSFORM_FIELD) if (constantField) { field.initializerGroovy = elementFactory.createExpressionFromText("0", null) } val requestInitializer = request.initializer if (requestInitializer is JvmLong) { field.initializerGroovy = elementFactory.createExpressionFromText("${requestInitializer.longValue}L", null) } return field } private fun insertField(field: GrField): GrField { return helper.insertFieldImpl(targetClass, field, null) } private fun startTemplate(field: GrField) { val targetFile = targetClass.containingFile ?: return val newEditor = positionCursor(field.project, targetFile, field) ?: return val substitutor = request.targetSubstitutor.toPsiSubstitutor(project) val template = helper.setupTemplateImpl(field, typeConstraints, targetClass, newEditor, null, constantField, substitutor) val listener = MyTemplateListener(project, newEditor, targetFile) startTemplate(newEditor, template, project, listener, null) } } private class MyTemplateListener(val project: Project, val editor: Editor, val file: PsiFile) : TemplateEditingAdapter() { override fun templateFinished(template: Template, brokenOff: Boolean) { PsiDocumentManager.getInstance(project).commitDocument(editor.document) val offset = editor.caretModel.offset val psiField = PsiTreeUtil.findElementOfClassAtOffset(file, offset, GrField::class.java, false) ?: return runWriteAction { CodeStyleManager.getInstance(project).reformat(psiField) } editor.caretModel.moveToOffset(psiField.textRange.endOffset - 1) } }
apache-2.0
JetBrains/kotlin-native
backend.native/tests/codegen/controlflow/for_loops_empty_range.kt
4
710
/* * Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license * that can be found in the LICENSE file. */ package codegen.controlflow.for_loops_empty_range import kotlin.test.* @Test fun runTest() { // Simple loops for (i in 4..0) { print(i) } for (i in 4 until 0) { print(i) } for (i in 0 downTo 4) { print(i) } // Steps for (i in 4..0 step 2) { print(i) } for (i in 4 until 0 step 2) { print(i) } for (i in 0 downTo 4 step 2) { print(i) } // Two steps for (i in 6..0 step 2 step 3) { print(i) } for (i in 6 until 0 step 2 step 3) { print(i) } for (i in 0 downTo 6 step 2 step 3) { print(i) } println("OK") }
apache-2.0
JetBrains/kotlin-native
backend.native/tests/compilerChecks/t24.kt
3
89
import platform.darwin.* import platform.Foundation.* class Zzz : NSCopyingProtocolMeta
apache-2.0
nimakro/tornadofx
src/main/java/tornadofx/Component.kt
1
49838
@file:Suppress("UNCHECKED_CAST") package tornadofx import javafx.application.HostServices import javafx.beans.binding.BooleanExpression import javafx.beans.property.* import javafx.collections.FXCollections import javafx.concurrent.Task import javafx.event.EventDispatchChain import javafx.event.EventHandler import javafx.event.EventTarget import javafx.fxml.FXMLLoader import javafx.geometry.Orientation import javafx.scene.Node import javafx.scene.Parent import javafx.scene.Scene import javafx.scene.control.* import javafx.scene.image.Image import javafx.scene.image.ImageView import javafx.scene.input.Clipboard import javafx.scene.input.KeyCode import javafx.scene.input.KeyCombination import javafx.scene.input.KeyEvent import javafx.scene.input.KeyEvent.KEY_PRESSED import javafx.scene.layout.BorderPane import javafx.scene.layout.Pane import javafx.scene.layout.StackPane import javafx.scene.paint.Paint import javafx.stage.Modality import javafx.stage.Stage import javafx.stage.StageStyle import javafx.stage.Window import javafx.util.Duration import java.io.Closeable import java.io.InputStream import java.io.StringReader import java.net.URL import java.nio.file.Files import java.nio.file.Path import java.util.* import java.util.logging.Logger import java.util.prefs.Preferences import javax.json.Json import kotlin.properties.ReadOnlyProperty import kotlin.reflect.* @Deprecated("Injectable was a misnomer", ReplaceWith("ScopedInstance")) interface Injectable : ScopedInstance interface ScopedInstance interface Configurable { val config: ConfigProperties val configPath: Path fun loadConfig() = ConfigProperties(this).apply { if (Files.exists(configPath)) Files.newInputStream(configPath).use { load(it) } } } class ConfigProperties(val configurable: Configurable) : Properties(), Closeable { fun set(pair: Pair<String, Any?>) { val value = pair.second?.let { (it as? JsonModel)?.toJSON()?.toString() ?: it.toString() } set(pair.first, value) } fun string(key: String, defaultValue: String? = null) = getProperty(key, defaultValue) fun boolean(key: String, defaultValue: Boolean? = false) = getProperty(key)?.toBoolean() ?: defaultValue fun double(key: String, defaultValue: Double? = null) = getProperty(key)?.toDouble() ?: defaultValue fun int(key: String, defaultValue: Int? = null) = getProperty(key)?.toInt() ?: defaultValue fun jsonObject(key: String) = getProperty(key)?.let { Json.createReader(StringReader(it)).readObject() } fun jsonArray(key: String) = getProperty(key)?.let { Json.createReader(StringReader(it)).readArray() } inline fun <reified M : JsonModel> jsonModel(key: String) = jsonObject(key)?.toModel<M>() fun save() { val path = configurable.configPath.apply { if (!Files.exists(parent)) Files.createDirectories(parent) } Files.newOutputStream(path).use { output -> store(output, "") } } override fun close() { save() } } abstract class Component : Configurable { open val scope: Scope = FX.inheritScopeHolder.get() val workspace: Workspace get() = scope.workspace val paramsProperty = SimpleObjectProperty<Map<String, Any?>>(FX.inheritParamHolder.get() ?: mapOf()) val params: Map<String, Any?> get() = paramsProperty.value val subscribedEvents = HashMap<KClass<out FXEvent>, ArrayList<FXEventRegistration>>() /** * Path to component specific configuration settings. Defaults to javaClass.properties inside * the configured configBasePath of the application (By default conf in the current directory). */ override val configPath: Path get() = app.configBasePath.resolve("${javaClass.name}.properties") override val config: ConfigProperties by lazy { loadConfig() } val clipboard: Clipboard by lazy { Clipboard.getSystemClipboard() } val hostServices: HostServices by lazy { FX.application.hostServices } inline fun <reified T : Component> find(vararg params: Pair<*, Any?>, noinline op: T.() -> Unit = {}): T = find(T::class, scope, params.toMap()).apply(op) inline fun <reified T : Component> find(params: Map<*, Any?>? = null, noinline op: T.() -> Unit = {}): T = find(T::class, scope, params).apply(op) fun <T : Component> find(type: KClass<T>, params: Map<*, Any?>? = null, op: T.() -> Unit = {}) = find(type, scope, params).apply(op) fun <T : Component> find(type: KClass<T>, vararg params: Pair<*, Any?>, op: T.() -> Unit = {}) = find(type, scope, params.toMap()).apply(op) @JvmOverloads fun <T : Component> find(componentType: Class<T>, params: Map<*, Any?>? = null, scope: Scope = [email protected]): T = find(componentType.kotlin, scope, params) fun <T : Any> k(javaClass: Class<T>): KClass<T> = javaClass.kotlin /** * Store and retrieve preferences. * * Preferences are stored automatically in a OS specific way. * <ul> * <li>Windows stores it in the registry at HKEY_CURRENT_USER/Software/JavaSoft/....</li> * <li>Mac OS stores it at ~/Library/Preferences/com.apple.java.util.prefs.plist</li> * <li>Linux stores it at ~/.java</li> * </ul> */ fun preferences(nodename: String? = null, op: Preferences.() -> Unit) { val node = if (nodename != null) Preferences.userRoot().node(nodename) else Preferences.userNodeForPackage(FX.getApplication(scope)!!.javaClass) op(node) } val properties by lazy { FXCollections.observableHashMap<Any, Any>() } val log by lazy { Logger.getLogger([email protected]) } val app: App get() = FX.application as App private val _messages: SimpleObjectProperty<ResourceBundle> = object : SimpleObjectProperty<ResourceBundle>() { override fun get(): ResourceBundle? { if (super.get() == null) { try { val bundle = ResourceBundle.getBundle([email protected], FX.locale, [email protected], FXResourceBundleControl) (bundle as? FXPropertyResourceBundle)?.inheritFromGlobal() set(bundle) } catch (ex: Exception) { FX.log.fine("No Messages found for ${javaClass.name} in locale ${FX.locale}, using global bundle") set(FX.messages) } } return super.get() } } var messages: ResourceBundle get() = _messages.get() set(value) = _messages.set(value) val resources: ResourceLookup by lazy { ResourceLookup(this) } inline fun <reified T> inject( overrideScope: Scope = scope, vararg params: Pair<String, Any?> ): ReadOnlyProperty<Component, T> where T : Component, T : ScopedInstance = inject(overrideScope, params.toMap()) inline fun <reified T> inject( overrideScope: Scope = scope, params: Map<String, Any?>? = null ): ReadOnlyProperty<Component, T> where T : Component, T : ScopedInstance = object : ReadOnlyProperty<Component, T> { override fun getValue(thisRef: Component, property: KProperty<*>) = find<T>(overrideScope, params) } inline fun <reified T> param(defaultValue: T? = null): ReadOnlyProperty<Component, T> = object : ReadOnlyProperty<Component, T> { override fun getValue(thisRef: Component, property: KProperty<*>): T { val param = thisRef.params[property.name] as? T if (param == null) { if (defaultValue != null) return defaultValue @Suppress("ALWAYS_NULL") if (property.returnType.isMarkedNullable) return defaultValue as T throw IllegalStateException("param for name [$property.name] has not been set") } else { return param } } } fun <T : ScopedInstance> setInScope(value: T, scope: Scope = this.scope) = FX.getComponents(scope).put(value.javaClass.kotlin, value) @Deprecated("No need to use the nullableParam anymore, use param instead", ReplaceWith("param(defaultValue)")) inline fun <reified T> nullableParam(defaultValue: T? = null) = param(defaultValue) inline fun <reified T : Fragment> fragment(overrideScope: Scope = scope, vararg params: Pair<String, Any?>): ReadOnlyProperty<Component, T> = fragment(overrideScope, params.toMap()) inline fun <reified T : Fragment> fragment(overrideScope: Scope = scope, params: Map<String, Any?>): ReadOnlyProperty<Component, T> = object : ReadOnlyProperty<Component, T> { val fragment: T by lazy { find<T>(overrideScope, params) } override fun getValue(thisRef: Component, property: KProperty<*>): T = fragment } inline fun <reified T : Any> di(name: String? = null): ReadOnlyProperty<Component, T> = object : ReadOnlyProperty<Component, T> { var injected: T? = null override fun getValue(thisRef: Component, property: KProperty<*>): T { val dicontainer = FX.dicontainer ?: throw AssertionError( "Injector is not configured, so bean of type ${T::class} cannot be resolved") return dicontainer.let { if (name != null) { it.getInstance<T>(name) } else { it.getInstance() } }.also { injected = it } } } val primaryStage: Stage get() = FX.getPrimaryStage(scope)!! // This is here for backwards compatibility. Removing it would require an import for the tornadofx.ui version infix fun <T> Task<T>.ui(func: (T) -> Unit) = success(func) @Deprecated("Clashes with Region.background, so runAsync is a better name", ReplaceWith("runAsync"), DeprecationLevel.WARNING) fun <T> background(func: FXTask<*>.() -> T) = task(func = func) /** * Perform the given operation on an ScopedInstance of the specified type asynchronousyly. * * MyController::class.runAsync { functionOnMyController() } ui { processResultOnUiThread(it) } */ inline fun <reified T, R> KClass<T>.runAsync(noinline op: T.() -> R) where T : Component, T : ScopedInstance = task { op(find(scope)) } /** * Perform the given operation on an ScopedInstance class function member asynchronousyly. * * CustomerController::listContacts.runAsync(customerId) { processResultOnUiThread(it) } */ inline fun <reified InjectableType, reified ReturnType> KFunction1<InjectableType, ReturnType>.runAsync(noinline doOnUi: (ReturnType) -> Unit = {}): Task<ReturnType> where InjectableType : Component, InjectableType : ScopedInstance = task { invoke(find(scope)) }.apply { ui(doOnUi) } /** * Perform the given operation on an ScopedInstance class function member asynchronousyly. * * CustomerController::listCustomers.runAsync { processResultOnUiThread(it) } */ inline fun <reified InjectableType, reified P1, reified ReturnType> KFunction2<InjectableType, P1, ReturnType>.runAsync(p1: P1, noinline doOnUi: (ReturnType) -> Unit = {}) where InjectableType : Component, InjectableType : ScopedInstance = task { invoke(find(scope), p1) }.apply { ui(doOnUi) } inline fun <reified InjectableType, reified P1, reified P2, reified ReturnType> KFunction3<InjectableType, P1, P2, ReturnType>.runAsync(p1: P1, p2: P2, noinline doOnUi: (ReturnType) -> Unit = {}) where InjectableType : Component, InjectableType : ScopedInstance = task { invoke(find(scope), p1, p2) }.apply { ui(doOnUi) } inline fun <reified InjectableType, reified P1, reified P2, reified P3, reified ReturnType> KFunction4<InjectableType, P1, P2, P3, ReturnType>.runAsync(p1: P1, p2: P2, p3: P3, noinline doOnUi: (ReturnType) -> Unit = {}) where InjectableType : Component, InjectableType : ScopedInstance = task { invoke(find(scope), p1, p2, p3) }.apply { ui(doOnUi) } inline fun <reified InjectableType, reified P1, reified P2, reified P3, reified P4, reified ReturnType> KFunction5<InjectableType, P1, P2, P3, P4, ReturnType>.runAsync(p1: P1, p2: P2, p3: P3, p4: P4, noinline doOnUi: (ReturnType) -> Unit = {}) where InjectableType : Component, InjectableType : ScopedInstance = task { invoke(find(scope), p1, p2, p3, p4) }.apply { ui(doOnUi) } /** * Find the given property inside the given ScopedInstance. Useful for assigning a property from a View or Controller * in any Component. Example: * * val person = find(UserController::currentPerson) */ inline fun <reified InjectableType, T> get(prop: KProperty1<InjectableType, T>): T where InjectableType : Component, InjectableType : ScopedInstance { val injectable = find<InjectableType>(scope) return prop.get(injectable) } inline fun <reified InjectableType, T> set(prop: KMutableProperty1<InjectableType, T>, value: T) where InjectableType : Component, InjectableType : ScopedInstance { val injectable = find<InjectableType>(scope) return prop.set(injectable, value) } /** * Runs task in background. If not set directly, looks for `TaskStatus` instance in current scope. */ fun <T> runAsync(status: TaskStatus? = find(scope), func: FXTask<*>.() -> T) = task(status, func) fun <T> runAsync(daemon: Boolean = false, status: TaskStatus? = find(scope), func: FXTask<*>.() -> T) = task(daemon, status, func) @Suppress("UNCHECKED_CAST") inline fun <reified T : FXEvent> subscribe(times: Number? = null, noinline action: EventContext.(T) -> Unit): FXEventRegistration { val registration = FXEventRegistration(T::class, this, times?.toLong(), action as EventContext.(FXEvent) -> Unit) subscribedEvents.getOrPut(T::class) { ArrayList() }.add(registration) val fireNow = (this as? UIComponent)?.isDocked ?: true if (fireNow) FX.eventbus.subscribe<T>(scope, registration) return registration } @Suppress("UNCHECKED_CAST") inline fun <reified T : FXEvent> unsubscribe(noinline action: EventContext.(T) -> Unit) { subscribedEvents[T::class]?.removeAll { it.action == action } FX.eventbus.unsubscribe(action) } fun <T : FXEvent> fire(event: T) { FX.eventbus.fire(event) } } abstract class Controller : Component(), ScopedInstance const val UI_COMPONENT_PROPERTY = "tornadofx.uicomponent" abstract class UIComponent(viewTitle: String? = "", icon: Node? = null) : Component(), EventTarget { override fun buildEventDispatchChain(tail: EventDispatchChain?): EventDispatchChain { throw UnsupportedOperationException("not implemented") } val iconProperty: ObjectProperty<Node> = SimpleObjectProperty(icon) var icon by iconProperty val isDockedProperty: ReadOnlyBooleanProperty = SimpleBooleanProperty() val isDocked by isDockedProperty lateinit var fxmlLoader: FXMLLoader var modalStage: Stage? = null internal var muteDocking = false abstract val root: Parent internal val wrapperProperty = SimpleObjectProperty<Parent>() internal fun getRootWrapper(): Parent = wrapperProperty.value ?: root private var isInitialized = false val currentWindow: Window? get() = modalStage ?: root.scene?.window ?: FX.primaryStage open val refreshable: BooleanExpression get() = properties.getOrPut("tornadofx.refreshable") { SimpleBooleanProperty(Workspace.defaultRefreshable) } as BooleanExpression open val savable: BooleanExpression get() = properties.getOrPut("tornadofx.savable") { SimpleBooleanProperty(Workspace.defaultSavable) } as BooleanExpression open val closeable: BooleanExpression get() = properties.getOrPut("tornadofx.closeable") { SimpleBooleanProperty(Workspace.defaultCloseable) } as BooleanExpression open val deletable: BooleanExpression get() = properties.getOrPut("tornadofx.deletable") { SimpleBooleanProperty(Workspace.defaultDeletable) } as BooleanExpression open val creatable: BooleanExpression get() = properties.getOrPut("tornadofx.creatable") { SimpleBooleanProperty(Workspace.defaultCreatable) } as BooleanExpression open val complete: BooleanExpression get() = properties.getOrPut("tornadofx.complete") { SimpleBooleanProperty(Workspace.defaultComplete) } as BooleanExpression var isComplete: Boolean get() = complete.value set(value) { (complete as? BooleanProperty)?.value = value } fun wrapper(op: () -> Parent) { FX.ignoreParentBuilder = FX.IgnoreParentBuilder.Once wrapperProperty.value = op() } fun savableWhen(savable: () -> BooleanExpression) { properties["tornadofx.savable"] = savable() } fun completeWhen(complete: () -> BooleanExpression) { properties["tornadofx.complete"] = complete() } fun deletableWhen(deletable: () -> BooleanExpression) { properties["tornadofx.deletable"] = deletable() } fun creatableWhen(creatable: () -> BooleanExpression) { properties["tornadofx.creatable"] = creatable() } fun closeableWhen(closeable: () -> BooleanExpression) { properties["tornadofx.closeable"] = closeable() } fun refreshableWhen(refreshable: () -> BooleanExpression) { properties["tornadofx.refreshable"] = refreshable() } fun whenSaved(onSave: () -> Unit) { properties["tornadofx.onSave"] = onSave } fun whenCreated(onCreate: () -> Unit) { properties["tornadofx.onCreate"] = onCreate } fun whenDeleted(onDelete: () -> Unit) { properties["tornadofx.onDelete"] = onDelete } fun whenRefreshed(onRefresh: () -> Unit) { properties["tornadofx.onRefresh"] = onRefresh } /** * Forward the Workspace button states and actions to the TabPane, which * in turn will forward these states and actions to whatever View is represented * by the currently active Tab. */ fun TabPane.connectWorkspaceActions() { savableWhen { savable } whenSaved { onSave() } creatableWhen { creatable } whenCreated { onCreate() } deletableWhen { deletable } whenDeleted { onDelete() } refreshableWhen { refreshable } whenRefreshed { onRefresh() } } /** * Forward the Workspace button states and actions to the TabPane, which * in turn will forward these states and actions to whatever View is represented * by the currently active Tab. */ fun StackPane.connectWorkspaceActions() { savableWhen { savable } whenSaved { onSave() } creatableWhen { creatable } whenCreated { onCreate() } deletableWhen { deletable } whenDeleted { onDelete() } refreshableWhen { refreshable } whenRefreshed { onRefresh() } } /** * Forward the Workspace button states and actions to the given UIComponent. * This will override the currently active forwarding to the docked UIComponent. * * When another UIComponent is docked, that UIComponent will be the new receiver for the * Workspace states and actions, hence voiding this call. */ fun forwardWorkspaceActions(uiComponent: UIComponent) { savableWhen { uiComponent.savable } whenSaved { uiComponent.onSave() } deletableWhen { uiComponent.deletable } whenDeleted { uiComponent.onDelete() } refreshableWhen { uiComponent.refreshable } whenRefreshed { uiComponent.onRefresh() } } /** * Callback that runs before the Workspace navigates back in the View stack. Return false to veto the navigation. */ open fun onNavigateBack() = true /** * Callback that runs before the Workspace navigates forward in the View stack. Return false to veto the navigation. */ open fun onNavigateForward() = true var onDockListeners: MutableList<(UIComponent) -> Unit>? = null var onUndockListeners: MutableList<(UIComponent) -> Unit>? = null val accelerators = HashMap<KeyCombination, () -> Unit>() fun disableSave() { properties["tornadofx.savable"] = SimpleBooleanProperty(false) } fun disableRefresh() { properties["tornadofx.refreshable"] = SimpleBooleanProperty(false) } fun disableCreate() { properties["tornadofx.creatable"] = SimpleBooleanProperty(false) } fun disableDelete() { properties["tornadofx.deletable"] = SimpleBooleanProperty(false) } fun disableClose() { properties["tornadofx.closeable"] = SimpleBooleanProperty(false) } fun init() { if (isInitialized) return root.properties[UI_COMPONENT_PROPERTY] = this root.parentProperty().addListener({ _, oldParent, newParent -> if (modalStage != null) return@addListener if (newParent == null && oldParent != null && isDocked) callOnUndock() if (newParent != null && newParent != oldParent && !isDocked) { callOnDock() // Call `onTabSelected` if/when we are connected to a Tab and it's selected // Note that this only works for builder constructed tabpanes owningTab?.let { it.selectedProperty()?.onChange { if (it) onTabSelected() } if (it.isSelected) onTabSelected() } } }) root.sceneProperty().addListener({ _, oldParent, newParent -> if (modalStage != null || root.parent != null) return@addListener if (newParent == null && oldParent != null && isDocked) callOnUndock() if (newParent != null && newParent != oldParent && !isDocked) { // Call undock when window closes newParent.windowProperty().onChangeOnce { it?.showingProperty()?.onChange { if (!it && isDocked) callOnUndock() } } callOnDock() } }) isInitialized = true } val currentStage: Stage? get() { val stage = (currentWindow as? Stage) if (stage == null) FX.log.warning { "CurrentStage not available for $this" } return stage } fun setWindowMinSize(width: Number, height: Number) = currentStage?.apply { minWidth = width.toDouble() minHeight = height.toDouble() } fun setWindowMaxSize(width: Number, height: Number) = currentStage?.apply { maxWidth = width.toDouble() maxHeight = height.toDouble() } private val acceleratorListener: EventHandler<KeyEvent> by lazy { EventHandler<KeyEvent> { event -> accelerators.keys.asSequence().find { it.match(event) }?.apply { accelerators[this]?.invoke() event.consume() } } } /** * Add a key listener to the current scene and look for matches against the * `accelerators` map in this UIComponent. */ private fun enableAccelerators() { root.scene?.addEventFilter(KEY_PRESSED, acceleratorListener) root.sceneProperty().addListener { obs, old, new -> old?.removeEventFilter(KEY_PRESSED, acceleratorListener) new?.addEventFilter(KEY_PRESSED, acceleratorListener) } } private fun disableAccelerators() { root.scene?.removeEventFilter(KEY_PRESSED, acceleratorListener) } /** * Called when a Component is detached from the Scene */ open fun onUndock() { } /** * Called when a Component becomes the Scene root or * when its root node is attached to another Component. * @see UIComponent.add */ open fun onDock() { } /** * Called when this Component is hosted by a Tab and the corresponding tab is selected */ open fun onTabSelected() { } open fun onRefresh() { (properties["tornadofx.onRefresh"] as? () -> Unit)?.invoke() } /** * Save callback which is triggered when the Save button in the Workspace * is clicked, or when the Next button in a Wizard is clicked. * * For Wizard pages, you should set the complete state of the Page after save * to signal whether the Wizard can move to the next page or finish. * * For Wizards, you should set the complete state of the Wizard * after save to signal whether the Wizard can be closed. */ open fun onSave() { (properties["tornadofx.onSave"] as? () -> Unit)?.invoke() } /** * Create callback which is triggered when the Creaste button in the Workspace * is clicked. */ open fun onCreate() { (properties["tornadofx.onCreate"] as? () -> Unit)?.invoke() } open fun onDelete() { (properties["tornadofx.onDelete"] as? () -> Unit)?.invoke() } open fun onGoto(source: UIComponent) { source.replaceWith(this) } fun goto(target: UIComponent) { target.onGoto(this) } inline fun <reified T : UIComponent> goto(params: Map<String, Any?>? = null) = find<T>(params).onGoto(this) inline fun <reified T : UIComponent> goto(vararg params: Pair<String, Any?>) { goto<T>(params.toMap()) } internal fun callOnDock() { if (!isInitialized) init() if (muteDocking) return if (!isDocked) attachLocalEventBusListeners() (isDockedProperty as SimpleBooleanProperty).value = true enableAccelerators() onDock() onDockListeners?.forEach { it.invoke(this) } } private fun attachLocalEventBusListeners() { subscribedEvents.forEach { event, actions -> actions.forEach { FX.eventbus.subscribe(event, scope, it) } } } private fun detachLocalEventBusListeners() { subscribedEvents.forEach { event, actions -> actions.forEach { FX.eventbus.unsubscribe(event, it.action) } } } internal fun callOnUndock() { if (muteDocking) return detachLocalEventBusListeners() (isDockedProperty as SimpleBooleanProperty).value = false disableAccelerators() onUndock() onUndockListeners?.forEach { it.invoke(this) } } fun Button.shortcut(combo: String) = shortcut(KeyCombination.valueOf(combo)) @Deprecated("Use shortcut instead", ReplaceWith("shortcut(combo)")) fun Button.accelerator(combo: KeyCombination) = shortcut(combo) /** * Add the key combination as a shortcut for this Button's action. */ fun Button.shortcut(combo: KeyCombination) { accelerators[combo] = { fire() } } /** * Configure an action for a key combination. */ fun shortcut(combo: KeyCombination, action: () -> Unit) { accelerators[combo] = action } fun <T> shortcut(combo: KeyCombination, command: Command<T>, param: T? = null) { accelerators[combo] = { command.execute(param) } } /** * Configure an action for a key combination. */ fun shortcut(combo: String, action: () -> Unit) = shortcut(KeyCombination.valueOf(combo), action) inline fun <reified T : UIComponent> TabPane.tab(scope: Scope = [email protected], noinline op: Tab.() -> Unit = {}) = tab(find<T>(scope), op) inline fun <reified C : UIComponent> BorderPane.top() = top(C::class) fun <C : UIComponent> BorderPane.top(nodeType: KClass<C>) = setRegion(scope, BorderPane::topProperty, nodeType) inline fun <reified C : UIComponent> BorderPane.right() = right(C::class) fun <C : UIComponent> BorderPane.right(nodeType: KClass<C>) = setRegion(scope, BorderPane::rightProperty, nodeType) inline fun <reified C : UIComponent> BorderPane.bottom() = bottom(C::class) fun <C : UIComponent> BorderPane.bottom(nodeType: KClass<C>) = setRegion(scope, BorderPane::bottomProperty, nodeType) inline fun <reified C : UIComponent> BorderPane.left() = left(C::class) fun <C : UIComponent> BorderPane.left(nodeType: KClass<C>) = setRegion(scope, BorderPane::leftProperty, nodeType) inline fun <reified C : UIComponent> BorderPane.center() = center(C::class) fun <C : UIComponent> BorderPane.center(nodeType: KClass<C>) = setRegion(scope, BorderPane::centerProperty, nodeType) fun <S, T> TableColumn<S, T>.cellFormat(formatter: TableCell<S, T>.(T) -> Unit) = cellFormat(scope, formatter) fun <S, T, F : TableCellFragment<S, T>> TableColumn<S, T>.cellFragment(fragment: KClass<F>) = cellFragment(scope, fragment) fun <T, F : TreeCellFragment<T>> TreeView<T>.cellFragment(fragment: KClass<F>) = cellFragment(scope, fragment) /** * Calculate a unique Node per item and set this Node as the graphic of the TableCell. * * To support this feature, a custom cellFactory is automatically installed, unless an already * compatible cellFactory is found. The cellFactories installed via #cellFormat already knows * how to retrieve cached values. */ fun <S, T> TableColumn<S, T>.cellCache(cachedGraphicProvider: (T) -> Node) = cellCache(scope, cachedGraphicProvider) fun EventTarget.slideshow(defaultTimeout: Duration? = null, scope: Scope = [email protected], op: Slideshow.() -> Unit) = opcr(this, Slideshow(scope, defaultTimeout), op) fun <T, F : ListCellFragment<T>> ListView<T>.cellFragment(fragment: KClass<F>) = cellFragment(scope, fragment) fun <T> ListView<T>.cellFormat(formatter: (ListCell<T>.(T) -> Unit)) = cellFormat(scope, formatter) fun <T> ListView<T>.onEdit(eventListener: ListCell<T>.(EditEventType, T?) -> Unit) = onEdit(scope, eventListener) fun <T> ListView<T>.cellCache(cachedGraphicProvider: (T) -> Node) = cellCache(scope, cachedGraphicProvider) fun <S> TableColumn<S, out Number?>.useProgressBar(afterCommit: (TableColumn.CellEditEvent<S, Number?>) -> Unit = {}) = useProgressBar(scope, afterCommit) fun <T> ComboBox<T>.cellFormat(formatButtonCell: Boolean = true, formatter: ListCell<T>.(T) -> Unit) = cellFormat(scope, formatButtonCell, formatter) inline fun <reified T : UIComponent> Drawer.item( scope: Scope = [email protected], vararg params: Pair<*, Any?>, expanded: Boolean = false, showHeader: Boolean = false, noinline op: DrawerItem.() -> Unit = {} ) = item(T::class, scope, params.toMap(), expanded, showHeader, op) inline fun <reified T : UIComponent> Drawer.item( scope: Scope = [email protected], params: Map<*, Any?>? = null, expanded: Boolean = false, showHeader: Boolean = false, noinline op: DrawerItem.() -> Unit = {} ) = item(T::class, scope, params, expanded, showHeader, op) inline fun <reified T : UIComponent> TableView<*>.placeholder( scope: Scope = [email protected], params: Map<*, Any?>? = null, noinline op: T.() -> Unit = {} ) { placeholder = find(T::class, scope, params).apply(op).root } inline fun <reified T : UIComponent> TableView<*>.placeholder( scope: Scope = [email protected], vararg params: Pair<*, Any?>, noinline op: T.() -> Unit = {} ) { placeholder(scope, params.toMap(), op) } inline fun <reified T : UIComponent> ListView<*>.placeholder( scope: Scope = [email protected], params: Map<*, Any?>? = null, noinline op: T.() -> Unit = {} ) { placeholder = find(T::class, scope, params).apply(op).root } inline fun <reified T : UIComponent> ListView<*>.placeholder( scope: Scope = [email protected], vararg params: Pair<*, Any?>, noinline op: T.() -> Unit = {} ) { placeholder(scope, params.toMap(), op) } inline fun <reified T : UIComponent> TreeTableView<*>.placeholder( scope: Scope = [email protected], params: Map<*, Any?>? = null, noinline op: T.() -> Unit = {} ) { placeholder = find(T::class, scope, params).apply(op).root } inline fun <reified T : UIComponent> TreeTableView<*>.placeholder( scope: Scope = [email protected], vararg params: Pair<*, Any?>, noinline op: T.() -> Unit = {} ) { placeholder(scope, params.toMap(), op) } fun Drawer.item( uiComponent: KClass<out UIComponent>, scope: Scope = [email protected], params: Map<*, Any?>? = null, expanded: Boolean = false, showHeader: Boolean = false, op: DrawerItem.() -> Unit = {} ) = item(find(uiComponent, scope, params), expanded, showHeader, op) fun Drawer.item( uiComponent: KClass<out UIComponent>, scope: Scope = [email protected], vararg params: Pair<*, Any?>, expanded: Boolean = false, showHeader: Boolean = false, op: DrawerItem.() -> Unit = {} ) { item(uiComponent, scope, params.toMap(), expanded, showHeader, op) } fun <T : UIComponent> EventTarget.add(type: KClass<T>, params: Map<*, Any?>? = null, op: T.() -> Unit = {}) { val view = find(type, scope, params) plusAssign(view.root) op(view) } inline fun <reified T : UIComponent> EventTarget.add(vararg params: Pair<*, Any?>, noinline op: T.() -> Unit = {}) = add(T::class, params.toMap(), op) fun <T : UIComponent> EventTarget.add(uiComponent: Class<T>) = add(find(uiComponent)) fun EventTarget.add(uiComponent: UIComponent) = plusAssign(uiComponent.root) fun EventTarget.add(child: Node) = plusAssign(child) operator fun <T : UIComponent> EventTarget.plusAssign(type: KClass<T>) = plusAssign(find(type, scope).root) protected inline fun <reified T : UIComponent> openInternalWindow( scope: Scope = [email protected], icon: Node? = null, modal: Boolean = true, owner: Node = root, escapeClosesWindow: Boolean = true, closeButton: Boolean = true, overlayPaint: Paint = c("#000", 0.4), params: Map<*, Any?>? = null ) = openInternalWindow(T::class, scope, icon, modal, owner, escapeClosesWindow, closeButton, overlayPaint, params) protected inline fun <reified T : UIComponent> openInternalWindow( scope: Scope = [email protected], icon: Node? = null, modal: Boolean = true, owner: Node = root, escapeClosesWindow: Boolean = true, closeButton: Boolean = true, overlayPaint: Paint = c("#000", 0.4), vararg params: Pair<*, Any?> ) { openInternalWindow<T>(scope, icon, modal, owner, escapeClosesWindow, closeButton, overlayPaint, params.toMap()) } protected fun openInternalWindow( view: KClass<out UIComponent>, scope: Scope = [email protected], icon: Node? = null, modal: Boolean = true, owner: Node = root, escapeClosesWindow: Boolean = true, closeButton: Boolean = true, overlayPaint: Paint = c("#000", 0.4), params: Map<*, Any?>? = null ) = InternalWindow(icon, modal, escapeClosesWindow, closeButton, overlayPaint).open(find(view, scope, params), owner) protected fun openInternalWindow( view: KClass<out UIComponent>, scope: Scope = [email protected], icon: Node? = null, modal: Boolean = true, owner: Node = root, escapeClosesWindow: Boolean = true, closeButton: Boolean = true, overlayPaint: Paint = c("#000", 0.4), vararg params: Pair<*, Any?> ) { openInternalWindow(view, scope, icon, modal, owner, escapeClosesWindow, closeButton, overlayPaint, params.toMap()) } protected fun openInternalWindow( view: UIComponent, icon: Node? = null, modal: Boolean = true, owner: Node = root, escapeClosesWindow: Boolean = true, closeButton: Boolean = true, overlayPaint: Paint = c("#000", 0.4) ) = InternalWindow(icon, modal, escapeClosesWindow, closeButton, overlayPaint).open(view, owner) protected fun openInternalBuilderWindow( title: String, scope: Scope = [email protected], icon: Node? = null, modal: Boolean = true, owner: Node = root, escapeClosesWindow: Boolean = true, closeButton: Boolean = true, overlayPaint: Paint = c("#000", 0.4), rootBuilder: UIComponent.() -> Parent ) = InternalWindow(icon, modal, escapeClosesWindow, closeButton, overlayPaint).open(BuilderFragment(scope, title, rootBuilder), owner) @JvmOverloads fun openWindow( stageStyle: StageStyle = StageStyle.DECORATED, modality: Modality = Modality.NONE, escapeClosesWindow: Boolean = true, owner: Window? = currentWindow, block: Boolean = false, resizable: Boolean? = null) = openModal(stageStyle, modality, escapeClosesWindow, owner, block, resizable) @JvmOverloads fun openModal(stageStyle: StageStyle = StageStyle.DECORATED, modality: Modality = Modality.APPLICATION_MODAL, escapeClosesWindow: Boolean = true, owner: Window? = currentWindow, block: Boolean = false, resizable: Boolean? = null): Stage? { if (modalStage == null) { require(getRootWrapper() is Parent) { "Only Parent Fragments can be opened in a Modal" } modalStage = Stage(stageStyle) // modalStage needs to be set before this code to make close() work in blocking mode with(modalStage!!) { aboutToBeShown = true if (resizable != null) isResizable = resizable titleProperty().bind(titleProperty) initModality(modality) if (owner != null) initOwner(owner) if (getRootWrapper().scene != null) { scene = getRootWrapper().scene [email protected]["tornadofx.scene"] = getRootWrapper().scene } else { Scene(getRootWrapper()).apply { if (escapeClosesWindow) { addEventFilter(KeyEvent.KEY_PRESSED) { if (it.code == KeyCode.ESCAPE) close() } } FX.applyStylesheetsTo(this) val primaryStage = FX.getPrimaryStage(scope) if (primaryStage != null) icons += primaryStage.icons scene = this [email protected]["tornadofx.scene"] = this } } hookGlobalShortcuts() showingProperty().onChange { if (it) { if (owner != null) { x = owner.x + (owner.width / 2) - (scene.width / 2) y = owner.y + (owner.height / 2) - (scene.height / 2) } callOnDock() if (FX.reloadStylesheetsOnFocus || FX.reloadViewsOnFocus) { configureReloading() } aboutToBeShown } else { modalStage = null callOnUndock() } } if (block) showAndWait() else show() } } else { if (!modalStage!!.isShowing) modalStage!!.show() } return modalStage } private fun Stage.configureReloading() { if (FX.reloadStylesheetsOnFocus) reloadStylesheetsOnFocus() if (FX.reloadViewsOnFocus) reloadViewsOnFocus() } @Deprecated("Use close() instead", replaceWith = ReplaceWith("close()")) fun closeModal() = close() fun close() { val internalWindow = root.findParent<InternalWindow>() if (internalWindow != null) { internalWindow.close() return } (modalStage ?: currentStage)?.apply { close() modalStage = null } owningTab?.apply { tabPane?.tabs?.remove(this) } } val owningTab: Tab? get() = properties["tornadofx.tab"] as? Tab open val titleProperty: StringProperty = SimpleStringProperty(viewTitle) var title: String get() = titleProperty.get() ?: "" set(value) = titleProperty.set(value) open val headingProperty: StringProperty = SimpleStringProperty().apply { bind(titleProperty) } var heading: String get() = headingProperty.get() ?: "" set(value) { if (headingProperty.isBound) headingProperty.unbind() headingProperty.set(value) } /** * Load an FXML file from the specified location, or from a file with the same package and name as this UIComponent * if not specified. If the FXML file specifies a controller (handy for content completion in FXML editors) * set the `hasControllerAttribute` parameter to true. This ensures that the `fx:controller` attribute is ignored * by the loader so that this UIComponent can still be the controller for the FXML file. * * Important: If you specify `hasControllerAttribute = true` when infact no `fx:controller` attribute is present, * no controller will be set at all. Make sure to only specify this parameter if you actually have the `fx:controller` * attribute in your FXML. */ fun <T : Node> fxml(location: String? = null, hasControllerAttribute: Boolean = false, root: Any? = null): ReadOnlyProperty<UIComponent, T> = object : ReadOnlyProperty<UIComponent, T> { val value: T = loadFXML(location, hasControllerAttribute, root) override fun getValue(thisRef: UIComponent, property: KProperty<*>) = value } @JvmOverloads fun <T : Node> loadFXML(location: String? = null, hasControllerAttribute: Boolean = false, root: Any? = null): T { val componentType = [email protected] val targetLocation = location ?: componentType.simpleName+".fxml" val fxml = requireNotNull(componentType.getResource(targetLocation)) { "FXML not found for $componentType in $targetLocation" } fxmlLoader = FXMLLoader(fxml).apply { resources = [email protected] if (root != null) setRoot(root) if (hasControllerAttribute) { setControllerFactory { this@UIComponent } } else { setController(this@UIComponent) } } return fxmlLoader.load() } fun <T : Any> fxid(propName: String? = null) = object : ReadOnlyProperty<UIComponent, T> { override fun getValue(thisRef: UIComponent, property: KProperty<*>): T { val key = propName ?: property.name val value = thisRef.fxmlLoader.namespace[key] if (value == null) { log.warning("Property $key of $thisRef was not resolved because there is no matching fx:id in ${thisRef.fxmlLoader.location}") } else { return value as T } throw IllegalArgumentException("Property $key does not match fx:id declaration") } } inline fun <reified T : Parent> EventTarget.include(scope: Scope = [email protected], hasControllerAttribute: Boolean = false, location: String): T { val loader = object : Fragment() { override val scope = scope override val root: T by fxml(location, hasControllerAttribute) } addChildIfPossible(loader.root) return loader.root } /** * Create an fragment by supplying an inline builder expression and optionally open it if the openModality is specified. A fragment can also be assigned * to an existing node hierarchy using `add()` or `this += inlineFragment {}`, or you can specify the behavior inside it using `Platform.runLater {}` before * you return the root node for the builder fragment. */ fun builderFragment( title: String = "", scope: Scope = [email protected], rootBuilder: UIComponent.() -> Parent ) = BuilderFragment(scope, title, rootBuilder) fun builderWindow( title: String = "", modality: Modality = Modality.APPLICATION_MODAL, stageStyle: StageStyle = StageStyle.DECORATED, scope: Scope = [email protected], owner: Window? = currentWindow, rootBuilder: UIComponent.() -> Parent ) = builderFragment(title, scope, rootBuilder).apply { openWindow(modality = modality, stageStyle = stageStyle, owner = owner) } fun dialog( title: String = "", modality: Modality = Modality.APPLICATION_MODAL, stageStyle: StageStyle = StageStyle.DECORATED, scope: Scope = [email protected], owner: Window? = currentWindow, labelPosition: Orientation = Orientation.HORIZONTAL, builder: StageAwareFieldset.() -> Unit ): Stage? { val fragment = builderFragment(title, scope, { form() }) val fieldset = StageAwareFieldset(title, labelPosition) fragment.root.add(fieldset) fieldset.stage = fragment.openWindow(modality = modality, stageStyle = stageStyle, owner = owner)!! builder(fieldset) fieldset.stage.sizeToScene() return fieldset.stage } inline fun <reified T : UIComponent> replaceWith( transition: ViewTransition? = null, sizeToScene: Boolean = false, centerOnScreen: Boolean = false ) = replaceWith(T::class, transition, sizeToScene, centerOnScreen) fun <T : UIComponent> replaceWith( component: KClass<T>, transition: ViewTransition? = null, sizeToScene: Boolean = false, centerOnScreen: Boolean = false ) = replaceWith(find(component, scope), transition, sizeToScene, centerOnScreen) /** * Replace this component with another, optionally using a transition animation. * * @param replacement The component that will replace this one * @param transition The [ViewTransition] used to animate the transition * @return Whether or not the transition will run */ fun replaceWith( replacement: UIComponent, transition: ViewTransition? = null, sizeToScene: Boolean = false, centerOnScreen: Boolean = false ) = root.replaceWith(replacement.root, transition, sizeToScene, centerOnScreen) { if (root == root.scene?.root) (root.scene.window as? Stage)?.titleProperty()?.cleanBind(replacement.titleProperty) } private fun undockFromParent(replacement: UIComponent) { (replacement.root.parent as? Pane)?.children?.remove(replacement.root) } } @Suppress("UNCHECKED_CAST") fun <U : UIComponent> U.whenDocked(listener: (U) -> Unit) { if (onDockListeners == null) onDockListeners = mutableListOf() onDockListeners!!.add(listener as (UIComponent) -> Unit) } @Suppress("UNCHECKED_CAST") fun <U : UIComponent> U.whenDockedOnce(listener: (U) -> Unit) { if (onDockListeners == null) onDockListeners = mutableListOf() onDockListeners!!.add { onDockListeners!!.remove(listener) listener(this) } } @Suppress("UNCHECKED_CAST") fun <U : UIComponent> U.whenUndocked(listener: (U) -> Unit) { if (onUndockListeners == null) onUndockListeners = mutableListOf() onUndockListeners!!.add(listener as (UIComponent) -> Unit) } @Suppress("UNCHECKED_CAST") fun <U : UIComponent> U.whenUndockedOnce(listener: (U) -> Unit) { if (onUndockListeners == null) onUndockListeners = mutableListOf() onUndockListeners!!.add { onUndockListeners!!.remove(listener) listener(this) } } abstract class Fragment @JvmOverloads constructor(title: String? = null, icon: Node? = null) : UIComponent(title, icon) abstract class View @JvmOverloads constructor(title: String? = null, icon: Node? = null) : UIComponent(title, icon), ScopedInstance class ResourceLookup(val component: Any) { operator fun get(resource: String): String = component.javaClass.getResource(resource).toExternalForm() fun url(resource: String): URL = component.javaClass.getResource(resource) fun stream(resource: String): InputStream = component.javaClass.getResourceAsStream(resource) fun image(resource: String): Image = Image(stream(resource)) fun imageview(resource: String, lazyload: Boolean = false): ImageView = ImageView(Image(url(resource).toExternalForm(), lazyload)) fun json(resource: String) = stream(resource).toJSON() fun jsonArray(resource: String) = stream(resource).toJSONArray() fun text(resource: String): String = stream(resource).use { it.bufferedReader().readText() } } class BuilderFragment(overrideScope: Scope, title: String, rootBuilder: Fragment.() -> Parent) : Fragment(title) { override val scope = overrideScope override val root = rootBuilder(this) }
apache-2.0
nrizzio/Signal-Android
core-util/src/main/java/org/signal/core/util/Serializer.kt
1
417
package org.signal.core.util /** * Generic serialization interface for use with database and store operations. */ interface Serializer<T, R> { fun serialize(data: T): R fun deserialize(data: R): T } interface StringSerializer<T> : Serializer<T, String> interface IntSerializer<T> : Serializer<T, Int> interface LongSerializer<T> : Serializer<T, Long> interface ByteSerializer<T> : Serializer<T, ByteArray>
gpl-3.0
GunoH/intellij-community
plugins/markdown/core/src/org/intellij/plugins/markdown/editor/paste/EditorFileDropHandler.kt
2
4608
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.intellij.plugins.markdown.editor.paste import com.intellij.ide.dnd.FileCopyPasteUtil import com.intellij.openapi.application.runWriteAction import com.intellij.openapi.command.executeCommand import com.intellij.openapi.editor.* import com.intellij.openapi.editor.actionSystem.EditorActionManager import com.intellij.openapi.fileTypes.FileTypeRegistry import com.intellij.openapi.project.Project import com.intellij.openapi.ui.Messages import com.intellij.openapi.util.io.FileUtil import com.intellij.psi.PsiFile import com.intellij.psi.util.PsiEditorUtil import com.intellij.refactoring.RefactoringBundle import org.intellij.images.fileTypes.ImageFileTypeManager import org.intellij.images.fileTypes.impl.SvgFileType import org.intellij.plugins.markdown.MarkdownBundle import org.intellij.plugins.markdown.editor.images.ImageUtils import org.intellij.plugins.markdown.editor.runForEachCaret import org.intellij.plugins.markdown.lang.MarkdownLanguageUtils.isMarkdownLanguage import java.awt.datatransfer.Transferable import java.net.URLEncoder import java.nio.charset.Charset import java.nio.file.Path import kotlin.io.path.extension import kotlin.io.path.name import kotlin.io.path.relativeTo internal class EditorFileDropHandler: CustomFileDropHandler() { override fun canHandle(transferable: Transferable, editor: Editor?): Boolean { if (editor == null || !editor.document.isWritable) { return false } val file = PsiEditorUtil.getPsiFile(editor) return file.language.isMarkdownLanguage() } override fun handleDrop(transferable: Transferable, editor: Editor?, project: Project?): Boolean { if (editor == null || project == null) { return false } val file = PsiEditorUtil.getPsiFile(editor) if (!file.language.isMarkdownLanguage() || !editor.document.isWritable) { return false } val files = FileCopyPasteUtil.getFiles(transferable)?.asSequence() ?: return false val content = buildTextContent(files, file) val document = editor.document runWriteAction { handleReadOnlyModificationException(project, document) { executeCommand(project, commandName) { editor.caretModel.runForEachCaret(reverseOrder = true) { caret -> document.insertString(caret.offset, content) caret.moveToOffset(content.length) } } } } return true } companion object { private val commandName get() = MarkdownBundle.message("markdown.image.file.drop.handler.drop.command.name") internal fun buildTextContent(files: Sequence<Path>, file: PsiFile): String { val imageFileType = ImageFileTypeManager.getInstance().imageFileType val registry = FileTypeRegistry.getInstance() val currentDirectory = file.containingDirectory?.virtualFile?.toNioPath() val relativePaths = files.map { obtainRelativePath(it, currentDirectory) } return relativePaths.joinToString(separator = "\n") { path -> when (registry.getFileTypeByExtension(path.extension)) { imageFileType, SvgFileType.INSTANCE -> createImageLink(path) else -> createFileLink(path) } } } private fun obtainRelativePath(path: Path, currentDirectory: Path?): Path { if (currentDirectory == null) { return path } return path.relativeTo(currentDirectory) } private fun createUri(url: String): String { return URLEncoder.encode(url, Charset.defaultCharset()).replace("+", "%20") } private fun createImageLink(file: Path): String { return ImageUtils.createMarkdownImageText( description = file.name, path = createUri(FileUtil.toSystemIndependentName(file.toString())) ) } private fun createFileLink(file: Path): String { val independentPath = createUri(FileUtil.toSystemIndependentName (file.toString())) return "[${file.name}]($independentPath)" } internal fun handleReadOnlyModificationException(project: Project, document: Document, block: () -> Unit) { try { block.invoke() } catch (exception: ReadOnlyModificationException) { Messages.showErrorDialog(project, exception.localizedMessage, RefactoringBundle.message("error.title")) } catch (exception: ReadOnlyFragmentModificationException) { EditorActionManager.getInstance().getReadonlyFragmentModificationHandler(document).handle(exception) } } } }
apache-2.0
GunoH/intellij-community
plugins/kotlin/jvm-debugger/test/testData/stepping/custom/smartStepIntoInlineFun.kt
4
1459
package smartStepIntoInlinedFunLiteral fun main(args: Array<String>) { val array = arrayOf(1, 2) val myClass = MyClass() //Breakpoint! test() // STEP_OVER: 1 // SMART_STEP_INTO_BY_INDEX: 1 myClass.f1 { test() } .f2 { test() } // RESUME: 1 //Breakpoint! test() // STEP_OVER: 1 // SMART_STEP_INTO_BY_INDEX: 3 myClass.f1 { test() } .f2 { test() } // RESUME: 1 //Breakpoint! test() // STEP_OVER: 1 // SMART_STEP_INTO_BY_INDEX: 1 array.map { it *2 } // RESUME: 1 //Breakpoint! test() // STEP_OVER: 1 // SMART_STEP_INTO_BY_INDEX: 1 array.map { it * 2 } .filter { it > 2 } // RESUME: 1 //Breakpoint! test() // STEP_OVER: 1 // SMART_STEP_INTO_BY_INDEX: 3 array.map { it * 2 } .filter { it > 2 } // RESUME: 1 //Breakpoint! test() // STEP_OVER: 1 // SMART_STEP_INTO_BY_INDEX: 1 myClass.f1 { test() }.f2 { test() } // RESUME: 1 //Breakpoint! test() // STEP_OVER: 1 // SMART_STEP_INTO_BY_INDEX: 3 myClass.f1 { test() }.f2 { test() } } class MyClass { inline fun f1(f1Param: () -> Unit): MyClass { test() f1Param() return this } inline fun f2(f1Param: () -> Unit): MyClass { test() f1Param() return this } } fun test() {} // IGNORE_K2
apache-2.0
GunoH/intellij-community
platform/util/ui/src/com/intellij/ui/icons/LoadIconParameters.kt
2
773
// 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.ui.icons import com.intellij.ui.scale.ScaleContext import com.intellij.util.SVGLoader import org.jetbrains.annotations.ApiStatus import java.awt.image.ImageFilter @ApiStatus.Internal data class LoadIconParameters( @JvmField val filters: List<ImageFilter>, @JvmField val scaleContext: ScaleContext, @JvmField val isDark: Boolean, @JvmField val colorPatcher: SVGLoader.SvgElementColorPatcherProvider?, @JvmField val isStroke: Boolean ) { companion object { @JvmStatic fun defaultParameters(isDark: Boolean): LoadIconParameters = LoadIconParameters(emptyList(), ScaleContext.create(), isDark, null, false) } }
apache-2.0
550609334/Twobbble
app/src/main/java/com/twobbble/view/activity/ImageFullActivity.kt
1
1862
package com.twobbble.view.activity import android.os.Bundle import android.support.v7.app.AppCompatActivity import com.twobbble.R import com.twobbble.tools.Constant import com.twobbble.tools.DownloadUtils import com.twobbble.tools.ImageLoad import kotlinx.android.synthetic.main.activity_image_full.* import java.io.File class ImageFullActivity : AppCompatActivity() { companion object { val KEY_URL_NORMAL: String = "key_url_normal" val KEY_URL_LOW: String = "KEY_URL_LOW" val KEY_TITLE: String = "key_title" } private var mUrlNormal: String? = null private var mUrlLow: String? = null private var mTitle: String? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_image_full) mUrlNormal = intent.getStringExtra(KEY_URL_NORMAL) mUrlLow = intent.getStringExtra(KEY_URL_LOW) mTitle = intent.getStringExtra(KEY_TITLE) initView() } private fun initView() { toolbar.inflateMenu(R.menu.image_full_menu) if (mUrlNormal != null) ImageLoad.frescoLoadZoom(mImage, mProgress, mUrlNormal.toString(), mUrlLow, true) } override fun onStart() { super.onStart() bindEvent() } private fun bindEvent() { toolbar.setNavigationOnClickListener { finish() } toolbar.setOnMenuItemClickListener { item -> when (item.itemId) { R.id.mDownload -> { val urls = mUrlNormal?.split(".") DownloadUtils.downloadImg(this@ImageFullActivity, mUrlNormal.toString(), "${Constant.IMAGE_DOWNLOAD_PATH}${File.separator}$mTitle.${urls!![urls.size - 1]}") } } true } } }
apache-2.0
jwren/intellij-community
plugins/kotlin/uast/uast-kotlin/tests/test/org/jetbrains/uast/test/kotlin/AbstractKotlinValuesTest.kt
4
335
// 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.uast.test.kotlin import org.jetbrains.uast.test.common.ValuesTestBase abstract class AbstractKotlinValuesTest : AbstractKotlinUastTest(), ValuesTestBase
apache-2.0
vovagrechka/fucking-everything
alraune/alraune/src/main/java/alraune/fuckaround/FuckAround_doSendOrderForApproval_1.kt
1
4042
package alraune.fuckaround import alraune.* import alraune.entity.* import pieces100.* import vgrechka.* object FuckAround_doSendOrderForApproval_1 { @JvmStatic fun main(args: Array<String>) { clog("--- ${FuckAround_doSendOrderForApproval_1::class.fqnWithoutPackage()} ---") initStandaloneToolMode__envyAda1__drop_create_fuck1() val orderUuid = "f86f0fc4-c7c5-4a97-bf60-1e206a566aa4" val f2 = Fartus2(orderUuid = orderUuid) var approvalTask1 by notNullOnce<Task>() AlDebug.kindaRequest_wait { AlDebug.deleteOrderIfExists(uuid = orderUuid) } AlDebug.kindaRequest_wait { f2.byAnonymousCustomer.fart {ctx-> Context1.get().withProjectStuff({it.copy( newOrder_uuid = orderUuid)}) { val fields = useFields(OrderFields3__killme(), FieldSource.Initial()) CreateOrderPage__killme().let { it.fields = fields fields.accept( contactName = {it.debug_set("Регина Дубовицкая")}, email = {it.debug_set("[email protected]")}, phone = {it.debug_set("+38 (091) 9284485")}, documentType = {it.set(Order.DocumentType.Course)}, documentTitle = {it.debug_set("Пространство и время: сопоставительный анализ предлогов и послелогов")}, documentDetails = {it.debug_set("В любом языке один и тот же предлог может иметь несколько значений, ассоциируемых с ним, и данные значения хранятся в когнитивной базе носителя языка. Категории служебных слов давно ждут серьезных исследований в рамках современной лингвистической парадигмы, поскольку развитие лингвистики предполагает не только появление новых аспектов и новых объектов, но и возврат к давно описанным категориям языка, которые, однако, в свете современных представлений и при использовании современных методик способны дать нам новые знания об уже известном явлении. Такими категориями являются послелог в корейском языке и предлог в русском и английском языках.\n\nКорейский язык является агглютинирующим языком (имеется тенденция к усилению флективности) номинативного строя. Важно отметить, что в корейском языке в передаче грамматических значений велика роль служебных слов, в том числе послелогов.")}, numPages = {it.debug_set("50")}, numSources = {it.debug_set("10")}, documentCategory = {it.set(AlUADocumentCategories.linguisticsID)}, deadline = {it.debug_set(TimePile.daysFromRealNow_stamp(5))})} doCreateOrder__killme(fields) } } } AlDebug.kindaRequest_wait { approvalTask1 = f2.byAnonymousCustomer.sendOrderForReview() } AlDebug.kindaRequest_wait { clog("approvalTask1.id =", approvalTask1.id) val order = dbSelectMaybeOrderByUUID(orderUuid)!! clog("order.data.approvalTaskId =", order.data.approvalTaskID) } clog("\nOK") } }
apache-2.0
GunoH/intellij-community
plugins/kotlin/idea/tests/testData/codeInsight/outOfBlock/InClassPropertyInitializerWithoutInference.kt
13
239
// TODO: it has to be non OCB ! // OUT_OF_CODE_BLOCK: TRUE // ERROR: No value passed for parameter 'i2' // TYPE: '\b\b' class Test { val foo: String? = "a" + bar(1, 2<caret>) fun bar(i: Int, i2: Int) = "" } // SKIP_ANALYZE_CHECK
apache-2.0
smmribeiro/intellij-community
plugins/kotlin/idea/tests/testData/refactoring/renameMultiModule/headersAndImplsByImplFun/before/JS/src/test/test.kt
13
146
package test actual fun /*rename*/foo() { } actual fun foo(n: Int) { } actual fun bar(n: Int) { } fun test() { foo() foo(1) bar(1) }
apache-2.0
smmribeiro/intellij-community
plugins/kotlin/idea/tests/testData/quickfix/createFromUsage/createVariable/primaryParameter/valOnJavaType.before.Main.kt
12
261
// "Create property 'foo' as constructor parameter" "false" // ACTION: Create member property 'A.foo' // ACTION: Create extension property 'A.foo' // ACTION: Rename reference // ERROR: Unresolved reference: foo fun test(): String? { return A().<caret>foo }
apache-2.0
smmribeiro/intellij-community
plugins/kotlin/idea/tests/testData/refactoring/move/java/moveClass/moveAsMember/moveClassToTopLevelClassOfAnotherPackage/after/k/onDemandImportOfPackageMembers.kt
13
68
package k import j.* fun bar(s: String) { val t: B.X = B.X() }
apache-2.0
smmribeiro/intellij-community
plugins/kotlin/idea/tests/testData/codeInsight/moveUpDown/closingBraces/when/whenEntry1.kt
13
182
// IS_APPLICABLE: false // MOVE: down fun foo(n: Int) { when (n) { 0 -> { } 1 -> { } else -> { }<caret> } val x = "" }
apache-2.0
smmribeiro/intellij-community
plugins/editorconfig/src/org/editorconfig/language/psi/base/EditorConfigDescribableElementBase.kt
8
2885
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.editorconfig.language.psi.base import com.intellij.extapi.psi.ASTWrapperPsiElement import com.intellij.lang.ASTNode import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.vfs.newvfs.VfsPresentationUtil import com.intellij.psi.PsiReference import org.editorconfig.language.psi.EditorConfigOption import org.editorconfig.language.psi.EditorConfigSection import org.editorconfig.language.psi.interfaces.EditorConfigDescribableElement import org.editorconfig.language.psi.reference.EditorConfigConstantReference import org.editorconfig.language.psi.reference.EditorConfigDeclarationReference import org.editorconfig.language.psi.reference.EditorConfigIdentifierReference import org.editorconfig.language.schema.descriptors.impl.EditorConfigConstantDescriptor import org.editorconfig.language.schema.descriptors.impl.EditorConfigDeclarationDescriptor import org.editorconfig.language.schema.descriptors.impl.EditorConfigReferenceDescriptor import org.editorconfig.language.schema.descriptors.impl.EditorConfigUnionDescriptor import org.editorconfig.language.util.EditorConfigDescriptorUtil import org.editorconfig.language.util.EditorConfigPsiTreeUtil.getParentOfType abstract class EditorConfigDescribableElementBase(node: ASTNode) : ASTWrapperPsiElement(node), EditorConfigDescribableElement { final override val option: EditorConfigOption get() = getParentOfType() ?: throw IllegalStateException() final override val section: EditorConfigSection get() = getParentOfType() ?: throw IllegalStateException() override val describableParent: EditorConfigDescribableElement? get() = parent as? EditorConfigDescribableElement override val declarationSite: String get() { val project = project val header = section.header.text val virtualFile = containingFile.virtualFile ?: return header val fileName = VfsPresentationUtil.getPresentableNameForUI(project, virtualFile) return "$header ($fileName)" } override fun getReference(): PsiReference? { val descriptor = getDescriptor(false) return when (descriptor) { is EditorConfigDeclarationDescriptor -> EditorConfigDeclarationReference(this) is EditorConfigReferenceDescriptor -> EditorConfigIdentifierReference(this, descriptor.id) is EditorConfigConstantDescriptor -> EditorConfigConstantReference(this) is EditorConfigUnionDescriptor -> { if (EditorConfigDescriptorUtil.isConstant(descriptor)) { EditorConfigConstantReference(this) } else { logger<EditorConfigDescribableElementBase>().warn("Got non-constant union") null } } else -> null } } final override fun toString(): String = text }
apache-2.0
smmribeiro/intellij-community
platform/platform-impl/src/com/intellij/ide/FeedbackDescriptionProvider.kt
14
804
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.ide import com.intellij.openapi.project.Project /** * Allows plugins to add additional details, which we want to see pre-populated in the bug reports. The implementation of this interface * must be registered as an extension of 'com.intellij.feedbackDescriptionProvider' extension point. */ interface FeedbackDescriptionProvider { /** * Return additional details which should be appended to the description of a created issue. It's important to return `null` if your plugin * isn't relevant for the passed `project` to avoid polluting created reports with unrelated data. */ fun getDescription(project: Project?): String? }
apache-2.0
smmribeiro/intellij-community
plugins/kotlin/idea/tests/testData/quickfix/autoImports/infixCall2.before.Main.kt
3
295
// "class org.jetbrains.kotlin.idea.quickfix.ImportFix" "false" // ERROR: Unresolved reference: foo // ACTION: Create extension function 'H.foo' // ACTION: Create member function 'H.foo' // ACTION: Replace infix call with ordinary call package h interface H fun f(h: H) { h <caret>foo h }
apache-2.0
smmribeiro/intellij-community
plugins/kotlin/j2k/old/tests/testData/fileOrElement/comments/commentInsideCall.kt
12
271
package test object Test { @JvmStatic fun main(args: Array<String>) { println()// Comment Test // Comment1 .foo() // Comment2 .indexOf("s") } fun foo(): String { return "" } }
apache-2.0
smmribeiro/intellij-community
plugins/maven/src/main/java/org/jetbrains/idea/maven/execution/run/configuration/MavenRunConfigurationSettingsEditor.kt
1
27640
// 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.execution.run.configuration import com.intellij.compiler.options.CompileStepBeforeRun import com.intellij.diagnostic.logging.LogsGroupFragment import com.intellij.execution.ExecutionBundle import com.intellij.execution.configurations.RuntimeConfigurationError import com.intellij.execution.impl.RunnerAndConfigurationSettingsImpl import com.intellij.execution.ui.* import com.intellij.ide.plugins.newui.HorizontalLayout import com.intellij.ide.wizard.getCanonicalPath import com.intellij.openapi.externalSystem.service.execution.configuration.* import com.intellij.openapi.externalSystem.service.ui.getSelectedJdkReference import com.intellij.openapi.externalSystem.service.ui.project.path.WorkingDirectoryField import com.intellij.openapi.externalSystem.service.ui.properties.PropertiesFiled import com.intellij.openapi.externalSystem.service.ui.properties.PropertiesInfo import com.intellij.openapi.externalSystem.service.ui.properties.PropertiesTable import com.intellij.openapi.externalSystem.service.ui.setSelectedJdkReference import com.intellij.openapi.externalSystem.service.ui.util.LabeledSettingsFragmentInfo import com.intellij.openapi.externalSystem.service.ui.util.PathFragmentInfo import com.intellij.openapi.externalSystem.service.ui.util.SettingsFragmentInfo import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory import com.intellij.openapi.observable.operations.AnonymousParallelOperationTrace import com.intellij.openapi.observable.operations.AnonymousParallelOperationTrace.Companion.task import com.intellij.openapi.options.ShowSettingsUtil import com.intellij.openapi.roots.ui.configuration.SdkComboBox import com.intellij.openapi.roots.ui.configuration.SdkComboBoxModel.Companion.createProjectJdkComboBoxModel import com.intellij.openapi.roots.ui.configuration.SdkLookupProvider import com.intellij.openapi.roots.ui.distribution.DistributionComboBox import com.intellij.openapi.roots.ui.distribution.FileChooserInfo import com.intellij.openapi.ui.TextFieldWithBrowseButton import com.intellij.openapi.util.NlsContexts import com.intellij.ui.components.ActionLink import com.intellij.ui.components.JBTextField import com.intellij.ui.dsl.builder.columns import com.intellij.ui.dsl.builder.impl.CollapsibleTitledSeparator import com.intellij.openapi.observable.util.lockOrSkip import com.intellij.util.ui.UIUtil import org.jetbrains.annotations.Nls import org.jetbrains.idea.maven.execution.MavenRunConfiguration import org.jetbrains.idea.maven.execution.MavenRunner import org.jetbrains.idea.maven.execution.MavenRunnerSettings import org.jetbrains.idea.maven.execution.RunnerBundle import org.jetbrains.idea.maven.execution.run.configuration.MavenDistributionsInfo.Companion.asDistributionInfo import org.jetbrains.idea.maven.execution.run.configuration.MavenDistributionsInfo.Companion.asMavenHome import org.jetbrains.idea.maven.project.MavenConfigurableBundle import org.jetbrains.idea.maven.project.MavenGeneralSettings import org.jetbrains.idea.maven.project.MavenProjectBundle import org.jetbrains.idea.maven.project.MavenProjectsManager import org.jetbrains.idea.maven.server.MavenServerManager import org.jetbrains.idea.maven.utils.MavenUtil import org.jetbrains.idea.maven.utils.MavenWslUtil import java.awt.Component import java.util.concurrent.atomic.AtomicBoolean import javax.swing.JCheckBox import javax.swing.JComponent import javax.swing.JLabel import javax.swing.JPanel class MavenRunConfigurationSettingsEditor( runConfiguration: MavenRunConfiguration ) : RunConfigurationFragmentedEditor<MavenRunConfiguration>( runConfiguration, runConfiguration.extensionsManager ) { private val resetOperation = AnonymousParallelOperationTrace() override fun resetEditorFrom(s: RunnerAndConfigurationSettingsImpl) { resetOperation.task { super.resetEditorFrom(s) } } override fun resetEditorFrom(settings: MavenRunConfiguration) { resetOperation.task { super.resetEditorFrom(settings) } } override fun createRunFragments() = SettingsFragmentsContainer.fragments<MavenRunConfiguration> { add(CommonParameterFragments.createRunHeader()) addBeforeRunFragment(CompileStepBeforeRun.ID) addAll(BeforeRunFragment.createGroup()) add(CommonTags.parallelRun()) val workingDirectoryField = addWorkingDirectoryFragment().component().component addCommandLineFragment(workingDirectoryField) addProfilesFragment(workingDirectoryField) addMavenOptionsGroupFragment() addJavaOptionsGroupFragment() add(LogsGroupFragment()) } private val MavenRunConfiguration.generalSettingsOrDefault: MavenGeneralSettings get() = generalSettings ?: MavenProjectsManager.getInstance(project).generalSettings.clone() private val MavenRunConfiguration.runnerSettingsOrDefault: MavenRunnerSettings get() = runnerSettings ?: MavenRunner.getInstance(project).settings.clone() private fun SettingsFragmentsContainer<MavenRunConfiguration>.addMavenOptionsGroupFragment() = addOptionsGroup( "maven.general.options.group", MavenConfigurableBundle.message("maven.run.configuration.general.options.group.name"), MavenConfigurableBundle.message("maven.run.configuration.general.options.group"), MavenProjectBundle.message("configurable.MavenSettings.display.name"), { generalSettings }, { generalSettingsOrDefault }, { generalSettings = it } ) { val distributionComponent = addDistributionFragment().component().component val userSettingsComponent = addUserSettingsFragment().component().component addLocalRepositoryFragment(distributionComponent, userSettingsComponent) addOutputLevelFragment() addThreadsFragment() addUsePluginRegistryTag() addPrintStacktracesTag() addUpdateSnapshotsTag() addExecuteNonRecursivelyTag() addWorkOfflineTag() addCheckSumPolicyTag() addMultiProjectBuildPolicyTag() } private fun SettingsFragmentsContainer<MavenRunConfiguration>.addJavaOptionsGroupFragment() = addOptionsGroup( "maven.runner.options.group", MavenConfigurableBundle.message("maven.run.configuration.runner.options.group.name"), MavenConfigurableBundle.message("maven.run.configuration.runner.options.group"), RunnerBundle.message("maven.tab.runner"), { runnerSettings }, { runnerSettingsOrDefault }, { runnerSettings = it } ) { addJreFragment() addEnvironmentFragment() addVmOptionsFragment() addPropertiesFragment() addSkipTestsTag() addResolveWorkspaceArtifactsTag() } private fun <S : FragmentedSettings, Settings> SettingsFragmentsContainer<S>.addOptionsGroup( id: String, name: @Nls(capitalization = Nls.Capitalization.Sentence) String, group: @Nls(capitalization = Nls.Capitalization.Title) String, settingsName: @NlsContexts.ConfigurableName String, getSettings: S.() -> Settings?, getDefaultSettings: S.() -> Settings, setSettings: S.(Settings?) -> Unit, configure: SettingsFragmentsContainer<S>.() -> Unit ) = add(object : NestedGroupFragment<S>(id, name, group, { true }) { private val separator = CollapsibleTitledSeparator(group) private val checkBox: JCheckBox private val checkBoxWithLink: JComponent init { val labelText = MavenConfigurableBundle.message("maven.run.configuration.options.group.inherit") @Suppress("HardCodedStringLiteral") val leadingLabelText = labelText.substringBefore("<a>") @Suppress("HardCodedStringLiteral") val linkLabelText = labelText.substringAfter("<a>").substringBefore("</a>") @Suppress("HardCodedStringLiteral") val trailingLabelText = labelText.substringAfter("</a>") checkBox = JCheckBox(leadingLabelText) checkBoxWithLink = JPanel().apply { layout = HorizontalLayout(0) add(checkBox) add(ActionLink(linkLabelText) { val showSettingsUtil = ShowSettingsUtil.getInstance() showSettingsUtil.showSettingsDialog(project, settingsName) }) add(JLabel(trailingLabelText)) } } override fun createChildren() = SettingsFragmentsContainer.fragments<S> { addSettingsEditorFragment( checkBoxWithLink, object : SettingsFragmentInfo { override val settingsId: String = "$id.checkbox" override val settingsName: String? = null override val settingsGroup: String? = null override val settingsPriority: Int = 0 override val settingsType = SettingsEditorFragmentType.EDITOR override val settingsHint: String? = null override val settingsActionHint: String? = null }, { it, _ -> checkBox.isSelected = it.getSettings() == null }, { it, _ -> it.setSettings(if (checkBox.isSelected) null else (it.getSettings() ?: it.getDefaultSettings())) } ) for (fragment in SettingsFragmentsContainer.fragments(configure)) { bind(checkBox, fragment) add(fragment) } } override fun getBuilder() = object : FragmentedSettingsBuilder<S>(children, this, this) { override fun createHeaderSeparator() = separator override fun addLine(component: Component, top: Int, left: Int, bottom: Int) { if (component === checkBoxWithLink) { super.addLine(component, top, left, bottom + TOP_INSET) myGroupInset += LEFT_INSET } else { super.addLine(component, top, left, bottom) } } init { children.forEach { bind(separator, it) } resetOperation.afterOperation { separator.expanded = !checkBox.isSelected } } } }).apply { isRemovable = false } private fun bind(checkBox: JCheckBox, fragment: SettingsEditorFragment<*, *>) { checkBox.addItemListener { val component = fragment.component() if (component != null) { UIUtil.setEnabledRecursively(component, !checkBox.isSelected) } } fragment.addSettingsEditorListener { if (resetOperation.isOperationCompleted()) { checkBox.isSelected = false } } } private fun bind(separator: CollapsibleTitledSeparator, fragment: SettingsEditorFragment<*, *>) { val mutex = AtomicBoolean() separator.onAction { mutex.lockOrSkip { fragment.component.isVisible = fragment.isSelected && separator.expanded fragment.hintComponent?.isVisible = fragment.isSelected && separator.expanded } } fragment.addSettingsEditorListener { mutex.lockOrSkip { if (resetOperation.isOperationCompleted()) { separator.expanded = true } } } } private fun SettingsFragmentsContainer<MavenRunConfiguration>.addSkipTestsTag() { addTag( "maven.skip.tests.tag", MavenConfigurableBundle.message("maven.settings.runner.skip.tests"), MavenConfigurableBundle.message("maven.run.configuration.runner.options.group"), null, { runnerSettingsOrDefault.isSkipTests }, { runnerSettingsOrDefault.isSkipTests = it } ) } private fun SettingsFragmentsContainer<MavenRunConfiguration>.addUsePluginRegistryTag() { addTag( "maven.use.plugin.registry.tag", MavenConfigurableBundle.message("maven.settings.general.use.plugin.registry"), MavenConfigurableBundle.message("maven.run.configuration.general.options.group"), MavenConfigurableBundle.message("maven.settings.general.use.plugin.registry.tooltip"), { generalSettingsOrDefault.isUsePluginRegistry }, { generalSettingsOrDefault.isUsePluginRegistry = it } ) } private fun SettingsFragmentsContainer<MavenRunConfiguration>.addPrintStacktracesTag() { addTag( "maven.print.stacktraces.tag", MavenConfigurableBundle.message("maven.settings.general.print.stacktraces"), MavenConfigurableBundle.message("maven.run.configuration.general.options.group"), MavenConfigurableBundle.message("maven.settings.general.print.stacktraces.tooltip"), { generalSettingsOrDefault.isPrintErrorStackTraces }, { generalSettingsOrDefault.isPrintErrorStackTraces = it } ) } private fun SettingsFragmentsContainer<MavenRunConfiguration>.addUpdateSnapshotsTag() { addTag( "maven.update.snapshots.tag", MavenConfigurableBundle.message("maven.settings.general.update.snapshots"), MavenConfigurableBundle.message("maven.run.configuration.general.options.group"), MavenConfigurableBundle.message("maven.settings.general.update.snapshots.tooltip"), { generalSettingsOrDefault.isAlwaysUpdateSnapshots }, { generalSettingsOrDefault.isAlwaysUpdateSnapshots = it } ) } private fun SettingsFragmentsContainer<MavenRunConfiguration>.addResolveWorkspaceArtifactsTag() { addTag( "maven.workspace.artifacts.tag", MavenConfigurableBundle.message("maven.settings.runner.resolve.workspace.artifacts"), MavenConfigurableBundle.message("maven.run.configuration.runner.options.group"), MavenConfigurableBundle.message("maven.settings.runner.resolve.workspace.artifacts.tooltip"), { runnerParameters.isResolveToWorkspace }, { runnerParameters.isResolveToWorkspace = it } ) } private fun SettingsFragmentsContainer<MavenRunConfiguration>.addExecuteNonRecursivelyTag() { addTag( "maven.execute.non.recursively.tag", MavenConfigurableBundle.message("maven.settings.general.execute.non.recursively"), MavenConfigurableBundle.message("maven.run.configuration.general.options.group"), MavenConfigurableBundle.message("maven.settings.general.execute.recursively.tooltip"), { generalSettingsOrDefault.isNonRecursive }, { generalSettingsOrDefault.isNonRecursive = it } ) } private fun SettingsFragmentsContainer<MavenRunConfiguration>.addWorkOfflineTag() { addTag( "maven.work.offline.tag", MavenConfigurableBundle.message("maven.settings.general.work.offline"), MavenConfigurableBundle.message("maven.run.configuration.general.options.group"), MavenConfigurableBundle.message("maven.settings.general.work.offline.tooltip"), { generalSettingsOrDefault.isWorkOffline }, { generalSettingsOrDefault.isWorkOffline = it } ) } private fun SettingsFragmentsContainer<MavenRunConfiguration>.addCheckSumPolicyTag() { addVariantTag( "maven.checksum.policy.tag", MavenConfigurableBundle.message("maven.run.configuration.checksum.policy"), MavenConfigurableBundle.message("maven.run.configuration.general.options.group"), { generalSettingsOrDefault.checksumPolicy }, { generalSettingsOrDefault.checksumPolicy = it }, { it.displayString } ) } private fun SettingsFragmentsContainer<MavenRunConfiguration>.addOutputLevelFragment() = addVariantFragment( object : LabeledSettingsFragmentInfo { override val editorLabel: String = MavenConfigurableBundle.message("maven.run.configuration.output.level.label") override val settingsId: String = "maven.output.level.fragment" override val settingsName: String = MavenConfigurableBundle.message("maven.run.configuration.output.level.name") override val settingsGroup: String = MavenConfigurableBundle.message("maven.run.configuration.general.options.group") override val settingsHint: String? = null override val settingsActionHint: String? = null }, { generalSettingsOrDefault.outputLevel }, { generalSettingsOrDefault.outputLevel = it }, { it.displayString } ).modifyLabeledComponentSize { columns(10) } private fun SettingsFragmentsContainer<MavenRunConfiguration>.addMultiProjectBuildPolicyTag() { addVariantTag( "maven.multi.project.build.policy.tag", MavenConfigurableBundle.message("maven.run.configuration.multi.project.build.policy"), MavenConfigurableBundle.message("maven.run.configuration.general.options.group"), { generalSettingsOrDefault.failureBehavior }, { generalSettingsOrDefault.failureBehavior = it }, { it.displayString } ) } private fun SettingsFragmentsContainer<MavenRunConfiguration>.addDistributionFragment() = addDistributionFragment( project, MavenDistributionsInfo(), { asDistributionInfo(generalSettingsOrDefault.mavenHome.ifEmpty { MavenServerManager.BUNDLED_MAVEN_3 }) }, { generalSettingsOrDefault.mavenHome = it?.let(::asMavenHome) ?: MavenServerManager.BUNDLED_MAVEN_3 } ).addValidation { if (!MavenUtil.isValidMavenHome(it.generalSettingsOrDefault.mavenHome)) { throw RuntimeConfigurationError(MavenConfigurableBundle.message("maven.run.configuration.distribution.invalid.home.error")) } } private fun SettingsFragmentsContainer<MavenRunConfiguration>.addWorkingDirectoryFragment() = addWorkingDirectoryFragment( project, MavenWorkingDirectoryInfo(project), { runnerParameters.workingDirPath }, { runnerParameters.workingDirPath = it } ) private fun SettingsFragmentsContainer<MavenRunConfiguration>.addCommandLineFragment( workingDirectoryField: WorkingDirectoryField ) = addCommandLineFragment( project, MavenCommandLineInfo(project, workingDirectoryField), { runnerParameters.commandLine }, { runnerParameters.commandLine = it } ) private fun SettingsFragmentsContainer<MavenRunConfiguration>.addEnvironmentFragment() = addEnvironmentFragment( object : LabeledSettingsFragmentInfo { override val editorLabel: String = ExecutionBundle.message("environment.variables.component.title") override val settingsId: String = "maven.environment.variables.fragment" override val settingsName: String = ExecutionBundle.message("environment.variables.fragment.name") override val settingsGroup: String = MavenConfigurableBundle.message("maven.run.configuration.runner.options.group") override val settingsHint: String = ExecutionBundle.message("environment.variables.fragment.hint") override val settingsActionHint: String = ExecutionBundle.message("set.custom.environment.variables.for.the.process") }, { runnerSettingsOrDefault.environmentProperties }, { runnerSettingsOrDefault.environmentProperties = it }, { runnerSettingsOrDefault.isPassParentEnv }, { runnerSettingsOrDefault.isPassParentEnv = it }, hideWhenEmpty = true ) private fun SettingsFragmentsContainer<MavenRunConfiguration>.addVmOptionsFragment() = addVmOptionsFragment( object : LabeledSettingsFragmentInfo { override val editorLabel: String = ExecutionBundle.message("run.configuration.java.vm.parameters.label") override val settingsId: String = "maven.vm.options.fragment" override val settingsName: String = ExecutionBundle.message("run.configuration.java.vm.parameters.name") override val settingsGroup: String = MavenConfigurableBundle.message("maven.run.configuration.runner.options.group") override val settingsHint: String = ExecutionBundle.message("run.configuration.java.vm.parameters.hint") override val settingsActionHint: String = ExecutionBundle.message("specify.vm.options.for.running.the.application") }, { runnerSettingsOrDefault.vmOptions.ifEmpty { null } }, { runnerSettingsOrDefault.setVmOptions(it) } ) private fun SettingsFragmentsContainer<MavenRunConfiguration>.addJreFragment() = SdkLookupProvider.getInstance(project, object : SdkLookupProvider.Id {}) .let { sdkLookupProvider -> addRemovableLabeledSettingsEditorFragment( SdkComboBox(createProjectJdkComboBoxModel(project, this@MavenRunConfigurationSettingsEditor)), object : LabeledSettingsFragmentInfo { override val editorLabel: String = MavenConfigurableBundle.message("maven.run.configuration.jre.label") override val settingsId: String = "maven.jre.fragment" override val settingsName: String = MavenConfigurableBundle.message("maven.run.configuration.jre.name") override val settingsGroup: String = MavenConfigurableBundle.message("maven.run.configuration.runner.options.group") override val settingsHint: String? = null override val settingsActionHint: String = MavenConfigurableBundle.message("maven.run.configuration.jre.action.hint") }, { getSelectedJdkReference(sdkLookupProvider) }, { setSelectedJdkReference(sdkLookupProvider, it) }, { runnerSettingsOrDefault.jreName }, { runnerSettingsOrDefault.setJreName(it) }, { MavenRunnerSettings.USE_PROJECT_JDK } ) } private fun SettingsFragmentsContainer<MavenRunConfiguration>.addPropertiesFragment() = addLabeledSettingsEditorFragment( PropertiesFiled(project, object : PropertiesInfo { override val dialogTitle: String = MavenConfigurableBundle.message("maven.run.configuration.properties.dialog.title") override val dialogTooltip: String = MavenConfigurableBundle.message("maven.run.configuration.properties.dialog.tooltip") override val dialogLabel: String = MavenConfigurableBundle.message("maven.run.configuration.properties.dialog.label") override val dialogEmptyState: String = MavenConfigurableBundle.message("maven.run.configuration.properties.dialog.empty.state") override val dialogOkButton: String = MavenConfigurableBundle.message("maven.run.configuration.properties.dialog.ok.button") }), object : LabeledSettingsFragmentInfo { override val editorLabel: String = MavenConfigurableBundle.message("maven.run.configuration.properties.label") override val settingsId: String = "maven.properties.fragment" override val settingsName: String = MavenConfigurableBundle.message("maven.run.configuration.properties.name") override val settingsGroup: String = MavenConfigurableBundle.message("maven.run.configuration.runner.options.group") override val settingsHint: String? = null override val settingsActionHint: String? = null }, { it, c -> c.properties = it.runnerSettingsOrDefault.mavenProperties.map { PropertiesTable.Property(it.key, it.value) } }, { it, c -> it.runnerSettingsOrDefault.mavenProperties = c.properties.associate { it.name to it.value } }, { it.runnerSettingsOrDefault.mavenProperties.isNotEmpty() } ) private fun SettingsFragmentsContainer<MavenRunConfiguration>.addProfilesFragment( workingDirectoryField: WorkingDirectoryField ) = addLabeledSettingsEditorFragment( MavenProfilesFiled(project, workingDirectoryField), object : LabeledSettingsFragmentInfo { override val editorLabel: String = MavenConfigurableBundle.message("maven.run.configuration.profiles.label") override val settingsId: String = "maven.profiles.fragment" override val settingsName: String = MavenConfigurableBundle.message("maven.run.configuration.profiles.name") override val settingsGroup: String? = null override val settingsHint: String = MavenConfigurableBundle.message("maven.run.configuration.profiles.hint") override val settingsActionHint: String? = null }, { it, c -> c.profiles = it.runnerParameters.profilesMap }, { it, c -> it.runnerParameters.profilesMap = c.profiles } ) private fun SettingsFragmentsContainer<MavenRunConfiguration>.addUserSettingsFragment() = addPathFragment( project, object : PathFragmentInfo { override val editorLabel: String = MavenConfigurableBundle.message("maven.run.configuration.user.settings.label") override val settingsId: String = "maven.user.settings.fragment" override val settingsName: String = MavenConfigurableBundle.message("maven.run.configuration.user.settings.name") override val settingsGroup: String = MavenConfigurableBundle.message("maven.run.configuration.general.options.group") override val fileChooserTitle: String = MavenConfigurableBundle.message("maven.run.configuration.user.settings.title") override val fileChooserDescriptor = FileChooserDescriptorFactory.createSingleFileNoJarsDescriptor() override val fileChooserMacroFilter = FileChooserInfo.DIRECTORY_PATH }, { generalSettingsOrDefault.userSettingsFile }, { generalSettingsOrDefault.setUserSettingsFile(it) }, { val mavenConfig = MavenProjectsManager.getInstance(project)?.generalSettings?.mavenConfig val userSettings = MavenWslUtil.getUserSettings(project, "", mavenConfig) getCanonicalPath(userSettings.path) } ) private fun SettingsFragmentsContainer<MavenRunConfiguration>.addLocalRepositoryFragment( distributionComponent: DistributionComboBox, userSettingsComponent: TextFieldWithBrowseButton ) = addPathFragment( project, object : PathFragmentInfo { override val editorLabel: String = MavenConfigurableBundle.message("maven.run.configuration.local.repository.label") override val settingsId: String = "maven.local.repository.fragment" override val settingsName: String = MavenConfigurableBundle.message("maven.run.configuration.local.repository.name") override val settingsGroup: String = MavenConfigurableBundle.message("maven.run.configuration.general.options.group") override val fileChooserTitle: String = MavenConfigurableBundle.message("maven.run.configuration.local.repository.title") override val fileChooserDescriptor = FileChooserDescriptorFactory.createSingleFolderDescriptor() override val fileChooserMacroFilter = FileChooserInfo.DIRECTORY_PATH }, { generalSettingsOrDefault.localRepository }, { generalSettingsOrDefault.setLocalRepository(it) }, { val mavenConfig = MavenProjectsManager.getInstance(project)?.generalSettings?.mavenConfig val distributionInfo = distributionComponent.selectedDistribution val distribution = distributionInfo?.let(::asMavenHome) ?: MavenServerManager.BUNDLED_MAVEN_3 val userSettingsPath = getCanonicalPath(userSettingsComponent.text.trim()) val userSettingsFile = MavenWslUtil.getUserSettings(project, userSettingsPath, mavenConfig) val userSettings = getCanonicalPath(userSettingsFile.path) val localRepository = MavenWslUtil.getLocalRepo(project, "", distribution, userSettings, mavenConfig) getCanonicalPath(localRepository.path) } ) private fun SettingsFragmentsContainer<MavenRunConfiguration>.addThreadsFragment() = addRemovableLabeledTextSettingsEditorFragment( JBTextField(), object : LabeledSettingsFragmentInfo { override val editorLabel: String = MavenConfigurableBundle.message("maven.run.configuration.threads.label") override val settingsId: String = "maven.threads.fragment" override val settingsName: String = MavenConfigurableBundle.message("maven.run.configuration.threads.name") override val settingsGroup: String = MavenConfigurableBundle.message("maven.run.configuration.general.options.group") override val settingsHint: String? = null override val settingsActionHint: String = MavenConfigurableBundle.message("maven.settings.general.thread.count.tooltip") }, { generalSettingsOrDefault.threads }, { generalSettingsOrDefault.threads = it } ).modifyLabeledComponentSize { columns(10) } }
apache-2.0
smmribeiro/intellij-community
plugins/kotlin/idea/tests/testData/intentions/convertEnumToSealedClass/outOfRange.kt
13
74
// IS_APPLICABLE: false <caret>internal enum class MyEnum { A, B, C }
apache-2.0
smmribeiro/intellij-community
platform/lang-impl/src/com/intellij/openapi/projectRoots/impl/jdkDownloader/JdkAuto.kt
4
12822
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.projectRoots.impl.jdkDownloader import com.intellij.execution.wsl.WslDistributionManager import com.intellij.execution.wsl.WslPath import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.runReadAction import com.intellij.openapi.components.BaseState import com.intellij.openapi.components.SimplePersistentStateComponent import com.intellij.openapi.components.service import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.progress.ProcessCanceledException import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.project.Project import com.intellij.openapi.project.ProjectBundle import com.intellij.openapi.projectRoots.* import com.intellij.openapi.projectRoots.SimpleJavaSdkType.notSimpleJavaSdkTypeIfAlternativeExistsAndNotDependentSdkType import com.intellij.openapi.projectRoots.impl.MockSdk import com.intellij.openapi.projectRoots.impl.UnknownSdkTracker import com.intellij.openapi.roots.OrderRootType import com.intellij.openapi.roots.ui.configuration.* import com.intellij.openapi.roots.ui.configuration.SdkDetector.DetectedSdkListener import com.intellij.openapi.roots.ui.configuration.UnknownSdkResolver.UnknownSdkLookup import com.intellij.openapi.roots.ui.configuration.projectRoot.SdkDownloadTask import com.intellij.openapi.util.registry.Registry import com.intellij.openapi.vfs.JarFileSystem import com.intellij.openapi.vfs.VirtualFile import com.intellij.util.lang.JavaVersion import com.intellij.util.text.nullize import com.intellij.util.xmlb.annotations.XCollection import org.jetbrains.annotations.NotNull import org.jetbrains.jps.model.java.JdkVersionDetector import java.io.File private class JdkAutoHint: BaseState() { val name by string() val path: String? by string() val version by string() @get:XCollection val includeJars by list<String>() } private class JdkAutoHints : BaseState() { @get:XCollection val jdks by list<JdkAutoHint>() } private class JdkAutoHintService(private val project: Project) : SimplePersistentStateComponent<JdkAutoHints>(JdkAutoHints()) { override fun loadState(state: JdkAutoHints) { super.loadState(state) UnknownSdkTracker.getInstance(project).updateUnknownSdks() } companion object { @JvmStatic fun getInstance(project: Project) : JdkAutoHintService = project.service() } } private class JarSdkConfigurator(val extraJars: List<String>) : UnknownSdkFixConfigurator { override fun configureSdk(sdk: Sdk) { val sdkModificator = sdk.sdkModificator for (path in extraJars) { val extraJar = resolveExtraJar(sdk, path) if (extraJar != null) { sdkModificator.addRoot(extraJar, OrderRootType.CLASSES) LOG.info("Jar '$path' has been added to sdk '${sdk.name}'") } else { LOG.warn("Cant resolve path '$path' for jdk home '${sdk.homeDirectory}'") } } sdkModificator.commitChanges() } private fun resolveExtraJar(sdk: Sdk, path: String): VirtualFile? { val homeDirectory = sdk.homeDirectory ?: return null val file = homeDirectory.findFileByRelativePath(path) ?: return null return JarFileSystem.getInstance().getJarRootForLocalFile(file) } } private val LOG = logger<JdkAuto>() class JdkAuto : UnknownSdkResolver, JdkDownloaderBase { override fun supportsResolution(sdkTypeId: SdkTypeId) = notSimpleJavaSdkTypeIfAlternativeExistsAndNotDependentSdkType().value(sdkTypeId) override fun createResolver(project: Project?, indicator: ProgressIndicator): UnknownSdkLookup? { if (!Registry.`is`("jdk.auto.setup")) return null if (ApplicationManager.getApplication().isUnitTestMode) return null return createResolverImpl(project, indicator) } fun createResolverImpl(project: Project?, indicator: ProgressIndicator): UnknownSdkLookup? { val sdkType = SdkType.getAllTypes() .singleOrNull(notSimpleJavaSdkTypeIfAlternativeExistsAndNotDependentSdkType()::value) ?: return null return object : UnknownSdkLookup { val projectWslDistribution by lazy { project?.basePath?.let { WslPath.getDistributionByWindowsUncPath(it) } } val projectInWsl by lazy { project?.basePath?.let { WslDistributionManager.isWslPath(it) } == true } val lazyDownloadModel: List<JdkItem> by lazy { indicator.pushState() indicator.text = ProjectBundle.message("progress.text.downloading.jdk.list") try { val jdkPredicate = when { projectInWsl -> JdkPredicate.forWSL() else -> JdkPredicate.default() } JdkListDownloader.getInstance().downloadModelForJdkInstaller(indicator, jdkPredicate) } catch(e: ProcessCanceledException) { throw e } catch (t: Throwable) { LOG.warn("JdkAuto has failed to download the list of available JDKs. " + t.message, t) listOf() } finally { indicator.popState() } } private fun resolveHint(sdk: UnknownSdk) : JdkAutoHint? { if (sdk.sdkType != sdkType) return null project ?: return null val sdkName = sdk.sdkName ?: return null return JdkAutoHintService .getInstance(project) .state .jdks.singleOrNull { it.name.equals(sdkName, ignoreCase = true) && it.path?.let { path -> projectInWsl == WslDistributionManager.isWslPath(path) } ?: false } } private fun parseSdkRequirement(sdk: UnknownSdk): JdkRequirement? { val hint = resolveHint(sdk) val namePredicate = hint?.version?.trim()?.toLowerCase()?.nullize(true) ?: JavaVersion.tryParse(sdk.expectedVersionString)?.toFeatureMinorUpdateString() ?: sdk.sdkName return JdkRequirements.parseRequirement( namePredicate = namePredicate, versionStringPredicate = sdk.sdkVersionStringPredicate, homePredicate = sdk.sdkHomePredicate ) } private fun resolveHintPath(sdk: UnknownSdk, indicator: ProgressIndicator) :UnknownSdkLocalSdkFix? { val hint = resolveHint(sdk) val path = hint?.path ?: return null indicator.text = ProjectBundle.message("progress.text.resolving.hint.path", path) if (!File(path).isDirectory) return null val version = runCatching { sdkType.getVersionString(hint.path) }.getOrNull() ?: return null return object : UnknownSdkLocalSdkFix, UnknownSdkFixConfigurator by JarSdkConfigurator(hint.includeJars) { override fun getExistingSdkHome(): String = path override fun getVersionString(): String = version override fun getSuggestedSdkName(): @NotNull String { val hintPath = hint.path ?: return "" return sdkType.suggestSdkName(null, hintPath) } override fun toString() = "UnknownSdkLocalSdkFix{hint $version, $path}" } } override fun proposeDownload(sdk: UnknownSdk, indicator: ProgressIndicator): UnknownSdkDownloadableSdkFix? { if (sdk.sdkType != sdkType) return null val req = parseSdkRequirement(sdk) ?: return null LOG.info("Looking for a possible download for ${sdk.sdkType.presentableName} with name ${sdk}") //we select the newest matching version for a possible fix val jdkToDownload = lazyDownloadModel .asSequence() .filter { req.matches(it) } .mapNotNull { val v = JavaVersion.tryParse(it.versionString) if (v != null) { it to v } else null }.maxByOrNull { it.second } ?.first ?: return null val jarConfigurator = JarSdkConfigurator(resolveHint(sdk)?.includeJars ?: listOf()) return object: UnknownSdkDownloadableSdkFix, UnknownSdkFixConfigurator by jarConfigurator { override fun getVersionString() = jdkToDownload.versionString override fun getPresentableVersionString() = jdkToDownload.presentableVersionString override fun getDownloadDescription() = jdkToDownload.fullPresentationText override fun createTask(indicator: ProgressIndicator): SdkDownloadTask { val jdkInstaller = JdkInstaller.getInstance() val homeDir = jdkInstaller.defaultInstallDir(jdkToDownload, projectWslDistribution) val request = jdkInstaller.prepareJdkInstallation(jdkToDownload, homeDir) return newDownloadTask(request, project) } override fun toString() = "UnknownSdkDownloadableFix{${jdkToDownload.fullPresentationText}, wsl=${projectWslDistribution}}" } } val lazyLocalJdks by lazy { indicator.text = ProjectBundle.message("progress.text.detecting.local.jdks") val result = mutableListOf<JavaLocalSdkFix>() SdkDetector.getInstance().detectSdks(sdkType, indicator, object : DetectedSdkListener { override fun onSdkDetected(type: SdkType, version: String, home: String) { val javaVersion = JavaVersion.tryParse(version) ?: return val suggestedName = JdkUtil.suggestJdkName(version) ?: return result += JavaLocalSdkFix(home, javaVersion, suggestedName) } }) result } override fun proposeLocalFix(sdk: UnknownSdk, indicator: ProgressIndicator): UnknownSdkLocalSdkFix? { if (sdk.sdkType != sdkType) return null val hintMatch = resolveHintPath(sdk, indicator) if (hintMatch != null) { LOG.info("Found hint path for local SDK: path ${hintMatch.existingSdkHome}") return hintMatch } val req = parseSdkRequirement(sdk) ?: run { LOG.info("Failed to parse unknown SDK requirement ${sdk}") return null } LOG.info("Looking for a local SDK for ${sdk.sdkType.presentableName} with name ${sdk}") fun List<JavaLocalSdkFix>.pickBestMatch() = this.maxByOrNull { it.version } val localSdkFix = tryUsingExistingSdk(req, sdk.sdkType, indicator).filterByWsl().pickBestMatch() ?: lazyLocalJdks.filter { req.matches(it) }.filterByWsl().pickBestMatch() return localSdkFix?.copy(includeJars = resolveHint(sdk)?.includeJars ?: listOf()) } private fun tryUsingExistingSdk(req: JdkRequirement, sdkType: SdkType, indicator: ProgressIndicator): List<JavaLocalSdkFix> { indicator.text = ProjectBundle.message("progress.text.checking.existing.jdks") val result = mutableListOf<JavaLocalSdkFix>() for (it in runReadAction { ProjectJdkTable.getInstance().allJdks }) { if (it.sdkType != sdkType) continue val homeDir = runCatching { it.homePath }.getOrNull() ?: continue val versionString = runCatching { it.versionString }.getOrNull() ?: continue val version = runCatching { JavaVersion.tryParse(versionString) }.getOrNull() ?: continue val suggestedName = runCatching { JdkUtil.suggestJdkName(versionString) }.getOrNull() ?: continue if (it !is MockSdk && runCatching { val homePath = it.homePath homePath != null && sdkType.isValidSdkHome(homePath) }.getOrNull() != true) continue if (runCatching { req.matches(it) }.getOrNull() != true) continue result += JavaLocalSdkFix(homeDir, version, suggestedName, prototype = it) } return result } private fun List<JavaLocalSdkFix>.filterByWsl(): List<JavaLocalSdkFix> { return filter { WslDistributionManager.isWslPath(it.homeDir) == projectInWsl } } } } private data class JavaLocalSdkFix( val homeDir: String, val version: JavaVersion, val suggestedName: String, val includeJars: List<String> = emptyList(), val prototype: Sdk? = null ) : UnknownSdkLocalSdkFix, UnknownSdkFixConfigurator by JarSdkConfigurator(includeJars) { override fun getExistingSdkHome() = homeDir override fun getVersionString() = JdkVersionDetector.formatVersionString(version) override fun getPresentableVersionString() = version.toFeatureMinorUpdateString() override fun getSuggestedSdkName() : String = suggestedName override fun getRegisteredSdkPrototype(): Sdk? = prototype override fun toString() = "UnknownSdkLocalSdkFix{$presentableVersionString, dir=$homeDir}" } }
apache-2.0
80998062/Fank
presentation/src/main/java/com/sinyuk/fanfou/util/QuickAdapter.kt
1
1609
/* * * * Apache License * * * * Copyright [2017] Sinyuk * * * * 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.sinyuk.fanfou.util import com.chad.library.adapter.base.BaseQuickAdapter import com.chad.library.adapter.base.BaseViewHolder /** * * @author sinyuk * @date 2017/9/30 */ abstract class QuickAdapter<T, K : BaseViewHolder> : BaseQuickAdapter<T, K> { constructor(layoutResId: Int, data: List<T>?) : super(layoutResId, data) constructor(data: List<T>?) : super(data) constructor(layoutResId: Int) : super(layoutResId) override fun onBindViewHolder(holder: K, position: Int, payloads: List<Any>) { if (payloads.isEmpty()) { onBindViewHolder(holder, position) } else { throw TODO("Bind viewHolder with payloads not implement") } } override fun onBindViewHolder(holder: K, positions: Int) { super.onBindViewHolder(holder, positions) } protected fun swapData(data: List<T>) { getData().clear() getData().addAll(data) } }
mit
shalupov/idea-cloudformation
src/main/kotlin/com/intellij/aws/cloudformation/model/CfnResourcesNode.kt
2
1765
package com.intellij.aws.cloudformation.model class CfnMetadataNode(name: CfnScalarValueNode?, val value: CfnObjectValueNode?): CfnNamedNode(name) class CfnTransformNode(name: CfnScalarValueNode?, val transforms: List<CfnScalarValueNode>): CfnNamedNode(name) class CfnResourcesNode(name: CfnScalarValueNode?, val resources: List<CfnResourceNode>) : CfnNamedNode(name) class CfnGlobalsNode(name: CfnScalarValueNode?, val globals: List<CfnServerlessEntityDefaultsNode>) : CfnNamedNode(name) class CfnServerlessEntityDefaultsNode(name: CfnScalarValueNode?, val properties: List<CfnNameValueNode>) : CfnNamedNode(name) class CfnOutputNode(name: CfnScalarValueNode?, value: CfnExpressionNode?) : CfnNameValueNode(name, value) class CfnOutputsNode(name: CfnScalarValueNode?, val properties: List<CfnOutputNode>) : CfnNamedNode(name) class CfnConditionNode(name: CfnScalarValueNode?, value: CfnExpressionNode?) : CfnNameValueNode(name, value) class CfnConditionsNode(name: CfnScalarValueNode?, val conditions: List<CfnConditionNode>) : CfnNamedNode(name) class CfnParameterNode(name: CfnScalarValueNode?, val properties: List<CfnNameValueNode>) : CfnNamedNode(name) class CfnParametersNode(name: CfnScalarValueNode?, val parameters: List<CfnParameterNode>) : CfnNamedNode(name) class CfnMappingValue(name: CfnScalarValueNode?, value: CfnExpressionNode?) : CfnNameValueNode(name, value) class CfnSecondLevelMappingNode(name: CfnScalarValueNode?, val secondLevelMapping: List<CfnMappingValue>) : CfnNamedNode(name) class CfnFirstLevelMappingNode(name: CfnScalarValueNode?, val firstLevelMapping: List<CfnSecondLevelMappingNode>) : CfnNamedNode(name) class CfnMappingsNode(name: CfnScalarValueNode?, val mappings: List<CfnFirstLevelMappingNode>) : CfnNamedNode(name)
apache-2.0
MartinStyk/AndroidApkAnalyzer
app/src/main/java/sk/styk/martin/apkanalyzer/util/TransitionUtils.kt
1
384
package sk.styk.martin.apkanalyzer.util import android.content.Context import android.graphics.Color import com.google.android.material.transition.MaterialContainerTransform fun Context.materialContainerTransform() = MaterialContainerTransform().apply { scrimColor = Color.TRANSPARENT // setAllContainerColors(ColorInfo.SURFACE.toColorInt(this@materialContainerTransform)) }
gpl-3.0
Waboodoo/HTTP-Shortcuts
HTTPShortcuts/app/src/main/kotlin/ch/rmy/android/http_shortcuts/dagger/ApplicationModule.kt
1
786
package ch.rmy.android.http_shortcuts.dagger import android.content.Context import ch.rmy.android.framework.data.RealmFactory import ch.rmy.android.http_shortcuts.Application import ch.rmy.android.http_shortcuts.utils.PlayServicesUtil import ch.rmy.android.http_shortcuts.utils.PlayServicesUtilImpl import dagger.Module import dagger.Provides import ch.rmy.android.http_shortcuts.data.RealmFactory as RealmFactoryImpl @Module class ApplicationModule { @Provides fun provideContext(application: Application): Context = application @Provides fun provideRealmFactory(): RealmFactory = RealmFactoryImpl.getInstance() @Provides fun providePlayServicesUtil(application: Application): PlayServicesUtil = PlayServicesUtilImpl(application) }
mit
DuckDeck/AndroidDemo
app/src/main/java/stan/androiddemo/project/petal/Module/Setting/AppCompatPreferenceActivity.kt
1
2684
package stan.androiddemo.project.petal.Module.Setting import android.content.res.Configuration import android.os.Bundle import android.preference.PreferenceActivity import android.support.annotation.LayoutRes import android.support.v7.app.ActionBar import android.support.v7.app.AppCompatDelegate import android.support.v7.widget.Toolbar import android.view.MenuInflater import android.view.View import android.view.ViewGroup /** * Created by stanhu on 18/8/2017. */ abstract class AppCompatPreferenceActivity: PreferenceActivity() { private var mDelegate: AppCompatDelegate? = null override fun onCreate(savedInstanceState: Bundle?) { getDelegate()?.installViewFactory() getDelegate()?.onCreate(savedInstanceState) super.onCreate(savedInstanceState) } override fun onPostCreate(savedInstanceState: Bundle?) { super.onPostCreate(savedInstanceState) getDelegate()?.onPostCreate(savedInstanceState) } fun getSupportActionBar(): ActionBar? { return getDelegate()?.supportActionBar } fun setSupportActionBar(toolbar: Toolbar?) { getDelegate()?.setSupportActionBar(toolbar) } override fun getMenuInflater(): MenuInflater { return getDelegate()!!.menuInflater } override fun setContentView(@LayoutRes layoutResID: Int) { getDelegate()?.setContentView(layoutResID) } override fun setContentView(view: View) { getDelegate()?.setContentView(view) } override fun setContentView(view: View, params: ViewGroup.LayoutParams) { getDelegate()?.setContentView(view, params) } override fun addContentView(view: View, params: ViewGroup.LayoutParams) { getDelegate()?.addContentView(view, params) } override fun onPostResume() { super.onPostResume() getDelegate()?.onPostResume() } override fun onTitleChanged(title: CharSequence, color: Int) { super.onTitleChanged(title, color) getDelegate()?.setTitle(title) } override fun onConfigurationChanged(newConfig: Configuration) { super.onConfigurationChanged(newConfig) getDelegate()?.onConfigurationChanged(newConfig) } override fun onStop() { super.onStop() getDelegate()?.onStop() } override fun onDestroy() { super.onDestroy() getDelegate()?.onDestroy() } override fun invalidateOptionsMenu() { getDelegate()?.invalidateOptionsMenu() } private fun getDelegate(): AppCompatDelegate? { if (mDelegate == null) { mDelegate = AppCompatDelegate.create(this, null) } return mDelegate } }
mit
googlearchive/android-InteractiveSliceProvider
app/src/main/java/com/example/android/interactivesliceprovider/data/DataRepository.kt
1
1640
/* * Copyright 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. */ package com.example.android.interactivesliceprovider.data class DataRepository(val dataSource: FakeDataSource) { fun getGridData() = dataSource.gridData fun getListData() = dataSource.listData fun registerGridSliceDataCallback(r: Runnable) { dataSource.registerGridDataCallback(r) dataSource.triggerGridDataFetch() } fun unregisterGridSliceDataCallbacks() { dataSource.unregisterGridDataCallbacks() } fun registerListSliceDataCallback(r: Runnable) { dataSource.registerListDataCallback(r) dataSource.triggerListDataFetch() } fun unregisterListSliceDataCallbacks() { dataSource.unregisterListDataCallbacks() } companion object { const val TAG = "DataRepository" } } // Model classes data class GridData( val title: String, val subtitle: String, val home: String, val work: String, val school: String ) data class ListData( val home: String, val work: String, val school: String )
apache-2.0
sg26565/hott-transmitter-config
HoTT-TTS/src/main/kotlin/de/treichels/hott/tts/voicerss/Bits.kt
1
101
package de.treichels.hott.tts.voicerss enum class Bits(val bits: Int) { EIGHT(8), SIXTEEN(16); }
lgpl-3.0
kerubistan/kerub
src/main/kotlin/com/github/kerubistan/kerub/services/socket/SpringSocketClientConnection.kt
1
2251
package com.github.kerubistan.kerub.services.socket import com.fasterxml.jackson.databind.ObjectMapper import com.github.kerubistan.kerub.model.Entity import com.github.kerubistan.kerub.model.messages.EntityMessage import com.github.kerubistan.kerub.model.messages.Message import com.github.kerubistan.kerub.security.EntityAccessController import com.github.kerubistan.kerub.utils.getLogger import io.github.kerubistan.kroki.collections.upsert import org.apache.shiro.subject.Subject import org.springframework.web.socket.CloseStatus import org.springframework.web.socket.TextMessage import org.springframework.web.socket.WebSocketSession import kotlin.reflect.KClass class SpringSocketClientConnection( private val session: WebSocketSession, private val mapper: ObjectMapper, private val entityAccessController: EntityAccessController, private val subject: Subject) : ClientConnection { override fun close() { session.close(CloseStatus.NORMAL) } private var subscriptions: Map<KClass<*>, List<ChannelSubscription>> = services.map { it.key to listOf<ChannelSubscription>() }.toMap() private companion object { private val logger = getLogger() } @Synchronized override fun removeSubscription(channel: String) { val sub = ChannelSubscription.fromChannel(channel) subscriptions = subscriptions.upsert( sub.entityClass, { it - sub }, { listOf() } ) } @Synchronized override fun addSubscription(channel: String) { val sub = ChannelSubscription.fromChannel(channel) subscriptions = subscriptions.upsert( sub.entityClass, { it + sub }, { listOf(sub) } ) } override fun filterAndSend(msg: Message) { if (msg is EntityMessage) { val entity = msg.obj subject.associateWith { entityAccessController.checkAndDo(entity) { val entityClass = entity.javaClass.kotlin as KClass<out Entity<out Any>> val classChannel = channels[entityClass] if (classChannel == null) { logger.warn("Entity type not handled: {}", entityClass) } else { synchronized(subscriptions) { if (subscriptions[entityClass]?.any { it.interested(msg) } == true) session.sendMessage(TextMessage(mapper.writeValueAsString(msg))) } } } }.run() } } }
apache-2.0
seventhroot/elysium
bukkit/rpk-player-lib-bukkit/src/main/kotlin/com/rpkit/players/bukkit/event/ircprofile/RPKIRCProfileEvent.kt
1
818
/* * Copyright 2019 Ross 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.players.bukkit.event.ircprofile import com.rpkit.core.event.RPKEvent import com.rpkit.players.bukkit.profile.RPKIRCProfile interface RPKIRCProfileEvent: RPKEvent { val ircProfile: RPKIRCProfile }
apache-2.0
pvarry/intra42
app/src/main/java/com/paulvarry/intra42/ui/galaxy/Galaxy.kt
1
24609
package com.paulvarry.intra42.ui.galaxy import android.animation.ValueAnimator import android.annotation.SuppressLint import android.content.Context import android.graphics.* import android.os.Build import android.util.AttributeSet import android.util.SparseArray import android.view.GestureDetector import android.view.MotionEvent import android.view.ScaleGestureDetector import android.view.View import android.widget.Scroller import com.paulvarry.intra42.R import com.paulvarry.intra42.ui.galaxy.model.CircleToDraw import com.paulvarry.intra42.ui.galaxy.model.ProjectDataIntra import java.util.* import kotlin.Comparator import kotlin.math.pow import kotlin.math.roundToInt class Galaxy(context: Context, attrs: AttributeSet) : View(context, attrs) { private var weightPath: Float = 0f private var backgroundColor: Int = 0 private var colorProjectUnavailable: Int = 0 private var colorProjectAvailable: Int = 0 private var colorProjectValidated: Int = 0 private var colorProjectInProgress: Int = 0 private var colorProjectFailed: Int = 0 private var colorProjectTextUnavailable: Int = 0 private var colorProjectTextAvailable: Int = 0 private var colorProjectTextValidated: Int = 0 private var colorProjectTextInProgress: Int = 0 private var colorProjectTextFailed: Int = 0 private val mGestureDetector: GestureDetector private val mScroller: Scroller private val mScrollAnimator: ValueAnimator private val mScaleDetector: ScaleGestureDetector /** * Data for current Galaxy. */ private var data: List<ProjectDataIntra>? = null private var dataCircle: MutableList<CircleToDraw>? = null private var noDataMessage: String = context.getString(R.string.galaxy_not_found) /** * Current scale factor. */ private var mScaleFactor = 1f set(value) { // Don't let the object get too small or too large. field = value.coerceIn(0.1f, 2.5f) } private val mPaintBackground: Paint private val mPaintPath: Paint private val mPaintProject: Paint private val mPaintText: Paint private val position = PointF(0f, 0f) /** * semiWidth is the height of the view divided by 2. */ private var semiHeight: Float = 0.toFloat() /** * semiWidth is the width of the view divided by 2. */ private var semiWidth: Float = 0.toFloat() /** * Compute title of each project once when data is added. * This split the title in multi line to display inside of the circle. */ private var projectTitleComputed: SparseArray<List<String>> = SparseArray(0) /** * Save cache for project position. This is computed once per call of onDraw(); */ private var drawPosComputed: SparseArray<PointF> = SparseArray() /** * Listener for project clicks. */ private var onClickListener: OnProjectClickListener? = null private val isAnimationRunning: Boolean get() = !mScroller.isFinished private var projectDataFirstInternship: ProjectDataIntra? = null private var projectDataFinalInternship: ProjectDataIntra? = null init { val attributes = context.theme.obtainStyledAttributes( attrs, R.styleable.Galaxy, 0, 0) try { val defaultTextColor = Color.parseColor("#3F51B5") backgroundColor = attributes.getColor(R.styleable.Galaxy_colorProjectBackground, 0) colorProjectUnavailable = attributes.getColor(R.styleable.Galaxy_colorProjectUnavailable, 0) colorProjectAvailable = attributes.getColor(R.styleable.Galaxy_colorProjectAvailable, 0) colorProjectValidated = attributes.getColor(R.styleable.Galaxy_colorProjectValidated, 0) colorProjectFailed = attributes.getColor(R.styleable.Galaxy_colorProjectFailed, 0) colorProjectInProgress = attributes.getColor(R.styleable.Galaxy_colorProjectInProgress, 0) colorProjectTextUnavailable = attributes.getColor(R.styleable.Galaxy_colorProjectOnUnavailable, defaultTextColor) colorProjectTextAvailable = attributes.getColor(R.styleable.Galaxy_colorProjectOnAvailable, defaultTextColor) colorProjectTextValidated = attributes.getColor(R.styleable.Galaxy_colorProjectOnValidated, defaultTextColor) colorProjectTextFailed = attributes.getColor(R.styleable.Galaxy_colorProjectOnFailed, defaultTextColor) colorProjectTextInProgress = attributes.getColor(R.styleable.Galaxy_colorProjectOnInProgress, defaultTextColor) weightPath = attributes.getDimension(R.styleable.Galaxy_weightPath, 1f) } finally { attributes.recycle() } mPaintBackground = Paint(Paint.ANTI_ALIAS_FLAG) mPaintBackground.color = backgroundColor mPaintBackground.style = Paint.Style.FILL mPaintPath = Paint(Paint.ANTI_ALIAS_FLAG) mPaintPath.isAntiAlias = true mPaintPath.color = colorProjectUnavailable mPaintPath.strokeWidth = weightPath mPaintPath.style = Paint.Style.STROKE mPaintProject = Paint(Paint.ANTI_ALIAS_FLAG) mPaintProject.isAntiAlias = true mPaintProject.color = colorProjectUnavailable mPaintText = Paint(Paint.ANTI_ALIAS_FLAG) mPaintText.isAntiAlias = true mPaintText.isFakeBoldText = true mPaintText.textAlign = Paint.Align.CENTER mPaintText.textSize = TEXT_HEIGHT * mScaleFactor // Create a Scroller to handle the fling gesture. mScroller = Scroller(context, null, true) // The scroller doesn't have any built-in animation functions--it just supplies // values when we ask it to. So we have to have a way to call it every frame // until the fling ends. This code (ab)uses a ValueAnimator object to generate // a callback on every animation frame. We don't use the animated value at all. mScrollAnimator = ValueAnimator.ofInt(0, 1) mScrollAnimator.addUpdateListener { tickScrollAnimation() } // Create a gesture detector to handle onTouch messages mGestureDetector = GestureDetector(this.context, GestureListener()) // Turn off long press--this control doesn't use it, and if long press is enabled, // you can't scroll for a bit, pause, then scroll some more (the pause is interpreted // as a long press, apparently) mGestureDetector.setIsLongpressEnabled(false) mScaleDetector = ScaleGestureDetector(context, ScaleListener()) onUpdateData() } private fun tickScrollAnimation() { if (!mScroller.isFinished) { mScroller.computeScrollOffset() position.set(mScroller.currX.toFloat(), mScroller.currY.toFloat()) } else { mScrollAnimator.cancel() onScrollFinished() } } private fun onUpdateData() { data?.let { mPaintText.textSize = TEXT_HEIGHT * mScaleFactor projectTitleComputed = SparseArray(it.size) drawPosComputed = SparseArray() it.forEach { projectData -> projectTitleComputed.put(projectData.id, TextCalculator.split(projectData, mPaintText, mScaleFactor)) drawPosComputed.put(projectData.id, PointF()) } } } /** * Called when the user finishes a scroll action. */ private fun onScrollFinished() { decelerate() } /** * Disable hardware acceleration (releases memory) */ private fun decelerate() { setLayerToSW(this) } private fun setLayerToSW(v: View) { if (!v.isInEditMode) { setLayerType(LAYER_TYPE_SOFTWARE, null) } } fun setOnProjectClickListener(onClickListener: OnProjectClickListener) { this.onClickListener = onClickListener } fun setData(data: List<ProjectDataIntra>?, cursusId: Int) { val c = Hack.computeData(data, cursusId) this.data = c?.first this.dataCircle = c?.second if (this.data.isNullOrEmpty()) this.data = null if (data != null) { for (projectData in data) { if (projectData.kind == ProjectDataIntra.Kind.FIRST_INTERNSHIP) projectDataFirstInternship = projectData else if (projectData.kind == ProjectDataIntra.Kind.SECOND_INTERNSHIP) projectDataFinalInternship = projectData } projectDataFirstInternship?.let { it.x = 3680 it.y = 3750 } projectDataFinalInternship?.let { it.x = 4600 it.y = 4600 } try { Collections.sort(data, Comparator { o1, o2 -> if (o1.state == null || o2.state == null) return@Comparator 0 o1.state!!.layerIndex.compareTo(o2.state!!.layerIndex) //TODO }) } catch (e: IllegalArgumentException) { e.printStackTrace() } } onUpdateData() onScrollFinished() invalidate() } fun setMessage(string: String) { data = null this.noDataMessage = string onScrollFinished() invalidate() } /** * Enable hardware acceleration (consumes memory) */ fun accelerate() { setLayerToHW(/*this*/) } private fun setLayerToHW(/*v: View*/) { // if (!v.isInEditMode) { // setLayerType(View.LAYER_TYPE_HARDWARE, null); // } } @SuppressLint("ClickableViewAccessibility") override fun onTouchEvent(event: MotionEvent): Boolean { // Let the GestureDetector interpret this event var resultGesture = mGestureDetector.onTouchEvent(event) val resultScale = mScaleDetector.onTouchEvent(event) // If the GestureDetector doesn't want this event, do some custom processing. // This code just tries to detect when the user is done scrolling by looking // for ACTION_UP events. if (!resultGesture && !resultScale) { if (event.action == MotionEvent.ACTION_UP) { // User is done scrolling, it's now safe to do things like autocenter stopScrolling() resultGesture = true } } return resultGesture } /** * Force a stop to all motion. Called when the user taps during a fling. */ private fun stopScrolling() { mScroller.forceFinished(true) onScrollFinished() } override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) { semiHeight = h / 2f semiWidth = w / 2f position.set(0f, 0f) super.onSizeChanged(w, h, oldw, oldh) } override fun onDraw(canvas: Canvas) { super.onDraw(canvas) canvas.drawPaint(mPaintBackground) data?.let { onDrawData(canvas, it) } ?: run { onDrawEmpty(canvas) } } private fun onDrawData(canvas: Canvas, data: List<ProjectDataIntra>) { mPaintPath.strokeWidth = weightPath * mScaleFactor mPaintText.textSize = TEXT_HEIGHT * mScaleFactor onDrawDataPath(canvas, data) onDrawDataCircle(canvas) onDrawDataContent(canvas, data) if (mScrollAnimator.isRunning) { tickScrollAnimation() postInvalidate() } } private fun onDrawDataPath(canvas: Canvas, data: List<ProjectDataIntra>) { var startX: Float var startY: Float var stopX: Float var stopY: Float for (projectData in data) { projectData.by?.forEach { by -> by.points?.let { points -> startX = getDrawPosX(points[0][0]) startY = getDrawPosY(points[0][1]) stopX = getDrawPosX(points[1][0]) stopY = getDrawPosY(points[1][1]) canvas.drawLine(startX, startY, stopX, stopY, getPaintPath(projectData.state)) } } } } private fun onDrawDataCircle(canvas: Canvas) { projectDataFirstInternship?.let { canvas.drawCircle( getDrawPosX(3000f), getDrawPosY(3000f), 1000 * mScaleFactor, getPaintPath(it.state)) } projectDataFinalInternship?.let { canvas.drawCircle( getDrawPosX(3000f), getDrawPosY(3000f), 2250 * mScaleFactor, getPaintPath(it.state)) } dataCircle?.forEach { canvas.drawCircle( getDrawPosX(3000f), getDrawPosY(3000f), it.radius * mScaleFactor, getPaintPath(it.state ?: ProjectDataIntra.State.UNAVAILABLE)) } } private fun onDrawDataContent(canvas: Canvas, data: List<ProjectDataIntra>) { for (projectData in data) { projectData.kind?.data?.let { when (it) { is ProjectDataIntra.Kind.DrawType.Rectangle -> drawRectangle(canvas, projectData, it) is ProjectDataIntra.Kind.DrawType.RoundRect -> drawRoundRect(canvas, projectData, it) is ProjectDataIntra.Kind.DrawType.Circle -> drawCircle(canvas, projectData, it) } } } } private fun onDrawEmpty(canvas: Canvas) { mPaintText.color = colorProjectTextAvailable mPaintText.textSize = 50 * mScaleFactor canvas.drawText(noDataMessage, width / 2f, height * 0.8f, mPaintText) } override fun setBackgroundColor(color: Int) { backgroundColor = color invalidate() requestLayout() } private fun getPaintProject(projectState: ProjectDataIntra.State?): Paint { mPaintProject.color = getColorProject(projectState) return mPaintProject } private fun getPaintPath(projectState: ProjectDataIntra.State?): Paint { mPaintPath.color = getColorProject(projectState) return mPaintPath } private fun getPaintProjectText(projectData: ProjectDataIntra): Paint { mPaintText.color = getColorText(projectData.state) mPaintText.textSize = TEXT_HEIGHT * mScaleFactor if (projectData.kind == ProjectDataIntra.Kind.INNER_SATELLITE) { mPaintText.textSize = TEXT_HEIGHT * mScaleFactor * 0.5f } return mPaintText } private fun getColorProject(projectState: ProjectDataIntra.State?): Int { return when (projectState) { ProjectDataIntra.State.DONE -> colorProjectValidated ProjectDataIntra.State.AVAILABLE -> colorProjectAvailable ProjectDataIntra.State.IN_PROGRESS -> colorProjectInProgress ProjectDataIntra.State.UNAVAILABLE -> colorProjectUnavailable ProjectDataIntra.State.FAIL -> colorProjectFailed null -> colorProjectUnavailable } } private fun getColorText(projectState: ProjectDataIntra.State?): Int { return when (projectState) { ProjectDataIntra.State.DONE -> colorProjectTextValidated ProjectDataIntra.State.AVAILABLE -> colorProjectTextAvailable ProjectDataIntra.State.IN_PROGRESS -> colorProjectTextInProgress ProjectDataIntra.State.UNAVAILABLE -> colorProjectTextUnavailable ProjectDataIntra.State.FAIL -> colorProjectTextFailed null -> colorProjectTextUnavailable } } private fun drawProjectTitle(canvas: Canvas, projectData: ProjectDataIntra) { val paintText = getPaintProjectText(projectData) val textToDraw = projectTitleComputed.get(projectData.id) val textHeight = paintText.textSize val posYStartDraw = getDrawPosY(projectData) - textHeight * (textToDraw.size - 1) / 2 var heightTextDraw: Float for (i in textToDraw.indices) { heightTextDraw = posYStartDraw + textHeight * i - (paintText.descent() + paintText.ascent()) / 2 canvas.drawText( textToDraw[i], getDrawPosX(projectData), heightTextDraw, paintText) } } private fun drawCircle(canvas: Canvas, projectData: ProjectDataIntra, data: ProjectDataIntra.Kind.DrawType.Circle) { canvas.drawCircle( getDrawPosX(projectData, true), getDrawPosY(projectData, true), data.radius * mScaleFactor, getPaintProject(projectData.state)) drawProjectTitle(canvas, projectData) } private fun drawRectangle(canvas: Canvas, projectData: ProjectDataIntra, data: ProjectDataIntra.Kind.DrawType.Rectangle) { val x = getDrawPosX(projectData, true) val y = getDrawPosY(projectData, true) val width = data.width * mScaleFactor val height = data.height * mScaleFactor val left = x - width / 2 val top = y + height / 2 val right = x + width / 2 val bottom = y - height / 2 canvas.drawRect(left, top, right, bottom, getPaintProject(projectData.state)) drawProjectTitle(canvas, projectData) } private fun drawRoundRect(canvas: Canvas, projectData: ProjectDataIntra, data: ProjectDataIntra.Kind.DrawType.RoundRect) { val x = getDrawPosX(projectData, true) val y = getDrawPosY(projectData, true) val width = data.width * mScaleFactor val height = data.height * mScaleFactor val left = x - width / 2 val top = y + height / 2 val right = x + width / 2 val bottom = y - height / 2 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) canvas.drawRoundRect(left, top, right, bottom, 100f, 100f, getPaintProject(projectData.state)) else canvas.drawRect(left, top, right, bottom, getPaintProject(projectData.state)) drawProjectTitle(canvas, projectData) } private fun getDrawPosX(projectData: ProjectDataIntra, forceReCompute: Boolean = false): Float { if (forceReCompute) drawPosComputed.get(projectData.id).x = getDrawPosX(projectData.x.toFloat()) return drawPosComputed.get(projectData.id).x } private fun getDrawPosX(pos: Float): Float { return (pos - centerPoint.x + position.x) * mScaleFactor + semiWidth } private fun getDrawPosY(projectData: ProjectDataIntra, forceReCompute: Boolean = false): Float { if (forceReCompute) drawPosComputed.get(projectData.id).y = getDrawPosY(projectData.y.toFloat()) return drawPosComputed.get(projectData.id).y } private fun getDrawPosY(pos: Float): Float { return (pos - centerPoint.y + position.y) * mScaleFactor + semiHeight } internal fun ptInsideCircle(x: Float, y: Float, projectData: ProjectDataIntra, data: ProjectDataIntra.Kind.DrawType.Circle): Boolean { val projectCenterX = getDrawPosX(projectData) val projectCenterY = getDrawPosY(projectData) val distanceBetween = (x - projectCenterX).pow(2f) + (y - projectCenterY).pow(2f) val radius = data.radius.times(mScaleFactor).pow(2f) return distanceBetween <= radius } internal fun ptInsideRectangle(clickX: Float, clickY: Float, projectData: ProjectDataIntra, data: ProjectDataIntra.Kind.DrawType.Rectangle): Boolean { val x = getDrawPosX(projectData) val y = getDrawPosY(projectData) val semiWidth = data.width * mScaleFactor / 2f val semiHeight = data.height * mScaleFactor / 2f return clickX >= x - semiWidth && clickX <= x + semiWidth / 2 && clickY >= y - semiHeight / 2 && clickY <= y + semiHeight / 2 } internal fun ptInsideRoundRect(clickX: Float, clickY: Float, projectData: ProjectDataIntra, data: ProjectDataIntra.Kind.DrawType.RoundRect): Boolean { val x = getDrawPosX(projectData) val y = getDrawPosY(projectData) val semiWidth = data.width * mScaleFactor / 2f val semiHeight = data.height * mScaleFactor / 2f return clickX >= x - semiWidth && clickX <= x + semiWidth / 2 && clickY >= y - semiHeight / 2 && clickY <= y + semiHeight / 2 } /* ********** interfaces and classes ********** */ interface OnProjectClickListener { fun onClick(projectData: ProjectDataIntra) } /** * Extends [GestureDetector.SimpleOnGestureListener] to provide custom gesture * processing. */ private inner class GestureListener : GestureDetector.SimpleOnGestureListener() { override fun onScroll(e1: MotionEvent, e2: MotionEvent, distanceX: Float, distanceY: Float): Boolean { var tmpX = position.x - distanceX * (1 / mScaleFactor) var tmpY = position.y - distanceY * (1 / mScaleFactor) tmpX = tmpX.coerceIn(GRAPH_MAP_LIMIT_MIN.toFloat(), GRAPH_MAP_LIMIT_MAX.toFloat()) tmpY = tmpY.coerceIn(GRAPH_MAP_LIMIT_MIN.toFloat(), GRAPH_MAP_LIMIT_MAX.toFloat()) position.set(tmpX, tmpY) postInvalidate() return true } override fun onFling(e1: MotionEvent, e2: MotionEvent, velocityX: Float, velocityY: Float): Boolean { mScroller.fling( position.x.roundToInt(), position.y.roundToInt(), velocityX.toInt(), velocityY.toInt(), GRAPH_MAP_LIMIT_MIN, GRAPH_MAP_LIMIT_MAX, GRAPH_MAP_LIMIT_MIN, GRAPH_MAP_LIMIT_MAX) // Start the animator and tell it to animate for the expected duration of the fling. mScrollAnimator.duration = mScroller.duration.toLong() mScrollAnimator.start() return true } override fun onDown(e: MotionEvent): Boolean { // The user is interacting with the pie, so we want to turn on acceleration // so that the interaction is smooth. accelerate() if (isAnimationRunning) { stopScrolling() } return true } override fun onDoubleTap(e: MotionEvent): Boolean { mScaleFactor *= 1.5f postInvalidate() return true } override fun onSingleTapConfirmed(e: MotionEvent): Boolean { var clicked = false data?.forEach { projectData -> projectData.kind?.let { val x = e.x val y = e.y when (it.data) { is ProjectDataIntra.Kind.DrawType.Circle -> { if (ptInsideCircle(x, y, projectData, it.data)) { clicked = true onClickListener?.onClick(projectData) } } is ProjectDataIntra.Kind.DrawType.RoundRect -> { if (ptInsideRoundRect(x, y, projectData, it.data)) { clicked = true onClickListener?.onClick(projectData) } } is ProjectDataIntra.Kind.DrawType.Rectangle -> { if (ptInsideRectangle(x, y, projectData, it.data)) { clicked = true onClickListener?.onClick(projectData) } } } } } return clicked } } private inner class ScaleListener : ScaleGestureDetector.SimpleOnScaleGestureListener() { override fun onScale(detector: ScaleGestureDetector): Boolean { mScaleFactor *= detector.scaleFactor invalidate() return true } } companion object { val centerPoint = Point(3000, 3000) val graphSize = Point(6000, 6000) var GRAPH_MAP_LIMIT_MIN = -2000 var GRAPH_MAP_LIMIT_MAX = 2000 var TEXT_HEIGHT = 25 } }
apache-2.0
google-developer-training/basic-android-kotlin-compose-training-mars-photos
app/src/main/java/com/example/marsphotos/network/MarsApiService.kt
1
1110
/* * 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 com.example.marsphotos.network import com.example.marsphotos.model.MarsPhoto import retrofit2.http.GET /** * A public interface that exposes the [getPhotos] method */ interface MarsApiService { /** * Returns a [List] of [MarsPhoto] and this method can be called from a Coroutine. * The @GET annotation indicates that the "photos" endpoint will be requested with the GET * HTTP method */ @GET("photos") suspend fun getPhotos(): List<MarsPhoto> }
apache-2.0
holgerbrandl/kscript
src/integration/kotlin/kscript/integration/KtSupportTest.kt
1
1925
package kscript.integration import kscript.integration.tools.TestAssertion.any import kscript.integration.tools.TestAssertion.verify import kscript.integration.tools.TestContext.projectDir import kscript.integration.tools.TestContext.resolvePath import org.junit.jupiter.api.Tag import org.junit.jupiter.api.Test class KtSupportTest : TestBase { @Test @Tag("posix") fun `Run kt via interpreter mode`() { verify(resolvePath("$projectDir/test/resources/kt_tests/simple_app.kt"), 0, "main was called\n", any()) } @Test @Tag("posix") @Tag("windows") fun `Run kt via interpreter mode with dependencies`() { verify("kscript ${resolvePath("$projectDir/test/resources/kt_tests/main_with_deps.kt")}", 0, "made it!\n", "[kscript] Resolving log4j:log4j:1.2.14...\n") } @Test @Tag("linux") @Tag("macos") @Tag("msys") @Tag("windows") //TODO: Additional new lines are in stdout for cygwin fun `Test misc entry point with or without package configurations (no cygwin)`() { verify("kscript ${resolvePath("$projectDir/test/resources/kt_tests/default_entry_nopckg.kt")}", 0, "main was called\n") verify("kscript ${resolvePath("$projectDir/test/resources/kt_tests/default_entry_withpckg.kt")}", 0, "main was called\n") } @Test @Tag("posix") @Tag("windows") fun `Test misc entry point with or without package configurations`() { verify("kscript ${resolvePath("$projectDir/test/resources/kt_tests/custom_entry_nopckg.kt")}", 0, "foo companion was called\n") verify("kscript ${resolvePath("$projectDir/test/resources/kt_tests/custom_entry_withpckg.kt")}", 0, "foo companion was called\n") } @Test @Tag("posix") fun `Also make sure that kts in package can be run via kscript`() { verify(resolvePath("$projectDir/test/resources/script_in_pckg.kts"), 0, "I live in a package!\n") } }
mit
BlueBoxWare/LibGDXPlugin
src/test/testdata/inspections/unsafeIterators/ObjectSet.kt
1
383
package main import com.badlogic.gdx.utils.ObjectSet @Suppress("UNUSED_PARAMETER") class ObjectSetTest { var set = ObjectSet<ObjectSet<String>>() fun test() { for (e in <warning>set</warning>) { for (s in <warning>e</warning>) { } } <warning>set.iterator()</warning> <warning><warning>set.iterator()</warning>.next().iterator()</warning> } }
apache-2.0
Nice3point/ScheduleMVP
app/src/main/java/nice3point/by/schedule/CardSheduleFragment/VCardFragment.kt
1
2208
package nice3point.by.schedule.CardSheduleFragment import android.app.Activity import android.os.Bundle import android.support.v4.app.Fragment import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import nice3point.by.schedule.Adapters.RVAdapter import nice3point.by.schedule.R import nice3point.by.schedule.TechnicalModule class VCardFragment : Fragment(), iVCardFragment { private lateinit var day_ofWeek: TextView private lateinit var presenter: PCardFragment private lateinit var instanceBundle: Bundle private lateinit var activity: Activity private lateinit var rv: RecyclerView override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? { val view = inflater!!.inflate(R.layout.recyclerview_activity, container, false) rv = view.findViewById(R.id.rv) day_ofWeek = view.findViewById(R.id.day_ofWeek) presenter = PCardFragment(this) instanceBundle = this.arguments activity = getActivity() presenter.requestAdapter() day_ofWeek.text = TechnicalModule.dayInString(presenter.getLoadDay()) return view } override fun getInstanceBundle(): Bundle { return instanceBundle } override fun getFragmentActivity(): Activity { return activity } override fun setRVAdapter(adapter: RVAdapter) { rv.layoutManager = LinearLayoutManager(context) rv.setHasFixedSize(true) rv.adapter = adapter } override fun activityDestroyed() { presenter.activityDestroyed() } companion object { private val ARG_POS = "Position" private val ARG_DAY = "Day" fun newInstance(day_of_week: Int, pos: Int): VCardFragment { val fragment = VCardFragment() val args = Bundle() args.putInt(ARG_DAY, day_of_week) args.putInt(ARG_POS, pos) fragment.arguments = args return fragment } } }
apache-2.0
RocketChat/Rocket.Chat.Android
app/src/main/java/chat/rocket/android/core/behaviours/MessageView.kt
2
544
package chat.rocket.android.core.behaviours import androidx.annotation.StringRes import chat.rocket.common.util.ifNull interface MessageView { /** * Show message given by resource id. * * @param resId The resource id on strings.xml of the message. */ fun showMessage(@StringRes resId: Int) fun showMessage(message: String) fun showGenericErrorMessage() } fun MessageView.showMessage(ex: Exception) { ex.message?.let { showMessage(it) }.ifNull { showGenericErrorMessage() } }
mit
Jire/Acelta
src/main/kotlin/com/acelta/world/mob/Movement.kt
1
2048
package com.acelta.world.mob import com.acelta.world.mob.player.Player import it.unimi.dsi.fastutil.ints.IntArrayFIFOQueue import java.lang.Math.abs import java.lang.Math.max class Movement(val mob: Mob) { private val xList = IntArrayFIFOQueue(64) private val yList = IntArrayFIFOQueue(64) var direction = Direction.NONE val moving: Boolean get() = direction != Direction.NONE var running = false var teleporting = false var regionChanging = false fun reset() { xList.clear() yList.clear() } fun addFirstStep(nextX: Int, nextY: Int) { reset() addStep(nextX, nextY) } fun addStep(nextX: Int, nextY: Int) { val currentX = if (xList.isEmpty) mob.position.x else xList.firstInt() val currentY = if (yList.isEmpty) mob.position.y else yList.firstInt() addStep(currentX, currentY, nextX, nextY) } private fun addStep(currentX: Int, currentY: Int, nextX: Int, nextY: Int) { var deltaX = nextX - currentX var deltaY = nextY - currentY val max = max(abs(deltaX), abs(deltaY)) repeat(max) { if (deltaX < 0) deltaX++ else if (deltaX > 0) deltaX-- if (deltaY < 0) deltaY++ else if (deltaY > 0) deltaY-- val x = nextX - deltaX val y = nextY - deltaY xList.enqueueFirst(x) yList.enqueueFirst(y) } } fun tick() = with(mob.position) { if (xList.isEmpty) direction = Direction.NONE else { var nextX = xList.dequeueLastInt() var nextY = yList.dequeueLastInt() direction = Direction.between(x, y, nextX, nextY) x = nextX y = nextY if (running && !xList.isEmpty) { nextX = xList.dequeueLastInt() nextY = yList.dequeueLastInt() direction = Direction.between(x, y, nextX, nextY) x = nextX y = nextY } val diffX = x - (centerX /* should really be last center X */ * 8) val diffY = y - (centerY /* should really be last center Y */ * 8) if (diffX < 16 || diffX >= 88 || diffY < 16 || diffY >= 88) { //regionChanging = true // TODO: set last region X and Y } } if (regionChanging && mob is Player) mob.send.sector() } }
gpl-3.0
KotlinPorts/pooled-client
postgresql-async/src/main/kotlin/com/github/mauricio/async/db/postgresql/messages/backend/ParameterStatusMessage.kt
2
822
/* * Copyright 2013 Maurício Linhares * * Maurício Linhares licenses this file to you under the Apache License, * version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.github.mauricio.async.db.postgresql.messages.backend data class ParameterStatusMessage(val key: String, val value: String) : ServerMessage(ServerMessage.ParameterStatus)
apache-2.0
tangying91/profit
src/main/java/org/profit/app/analyse/StockDownAnalyzer.kt
1
1330
package org.profit.app.analyse import org.profit.app.StockHall import org.profit.app.pojo.StockHistory import org.profit.util.DateUtils import org.profit.util.FileUtils import org.profit.util.StockUtils import java.lang.Exception /** * 【积】周期内,连续下跌天数较多 */ class StockDownAnalyzer(code: String, private val statCount: Int, private val downPercent: Double) : StockAnalyzer(code) { /** * 1.周期内总天数 * 2.周期内连续下跌最大天数 * 3.周内总下跌天数 */ override fun analyse(results: MutableList<String>) { // 获取数据,后期可以限制天数 val list = readHistories(statCount) // 如果没有数据 if (list.size < statCount) { return } val totalDay = list.size val downDays = list.count { it.close < it.open } val percent = (list[0].close - list[statCount - 1].open).div(list[statCount - 1].open) * 100 if (downDays > totalDay * downPercent) { val content = "$code${StockHall.stockName(code)} 一共$totalDay 天,累计一共下跌$downDays 天,区间涨幅${StockUtils.twoDigits(percent)}% ,快速查看: http://stockpage.10jqka.com.cn/$code/" FileUtils.writeStat(content) } } }
apache-2.0
facebook/fresco
imagepipeline-base/src/main/java/com/facebook/imagepipeline/cache/package-info.kt
1
288
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ /** Memory cache implementations for image pipeline. */ package com.facebook.imagepipeline.cache
mit
bk138/multivnc
android/app/src/main/java/com/coboltforge/dontmind/multivnc/ConnectionBean.kt
1
4363
package com.coboltforge.dontmind.multivnc import android.os.Parcelable import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.PrimaryKey import kotlinx.parcelize.Parcelize import kotlinx.serialization.Serializable @Parcelize @Serializable @Entity(tableName = "CONNECTION_BEAN") data class ConnectionBean( @JvmField @PrimaryKey(autoGenerate = true) @ColumnInfo(name = "_id") var id: Long = 0, @JvmField @ColumnInfo(name = "NICKNAME") var nickname: String? = "", @JvmField @ColumnInfo(name = "ADDRESS") var address: String? = "", @JvmField @ColumnInfo(name = "PORT") var port: Int = 5900, @JvmField @ColumnInfo(name = "PASSWORD") var password: String? = "", @JvmField @ColumnInfo(name = "COLORMODEL") var colorModel: String? = COLORMODEL.C24bit.nameString(), @JvmField @ColumnInfo(name = "FORCEFULL") var forceFull: Long = 0, @JvmField @ColumnInfo(name = "REPEATERID") var repeaterId: String? = "", @JvmField @ColumnInfo(name = "INPUTMODE") var inputMode: String? = null, @JvmField @ColumnInfo(name = "SCALEMODE") var scalemode: String? = null, @JvmField @ColumnInfo(name = "USELOCALCURSOR") var useLocalCursor: Boolean = false, @JvmField @ColumnInfo(name = "KEEPPASSWORD") var keepPassword: Boolean = true, @JvmField @ColumnInfo(name = "FOLLOWMOUSE") var followMouse: Boolean = true, @JvmField @ColumnInfo(name = "USEREPEATER") var useRepeater: Boolean = false, @JvmField @ColumnInfo(name = "METALISTID") var metaListId: Long = 1, @JvmField @ColumnInfo(name = "LAST_META_KEY_ID") var lastMetaKeyId: Long = 0, @JvmField @ColumnInfo(name = "FOLLOWPAN", defaultValue = "0") var followPan: Boolean = false, @JvmField @ColumnInfo(name = "USERNAME") var userName: String? = "", @JvmField @ColumnInfo(name = "SECURECONNECTIONTYPE") var secureConnectionType: String? = null, @JvmField @ColumnInfo(name = "SHOWZOOMBUTTONS", defaultValue = "1") var showZoomButtons: Boolean = false, @JvmField @ColumnInfo(name = "DOUBLE_TAP_ACTION") var doubleTapAction: String? = null ) : Comparable<ConnectionBean>, Parcelable { override fun toString(): String { return "$id $nickname: $address, port $port" } override fun compareTo(other: ConnectionBean): Int { var result = nickname!!.compareTo(other.nickname!!) if (result == 0) { result = address!!.compareTo(other.address!!) if (result == 0) { result = port - other.port } } return result } /** * parse host:port or [host]:port and split into address and port fields * @param hostport_str * @return true if there was a port, false if not */ fun parseHostPort(hostport_str: String): Boolean { val nr_colons = hostport_str.replace("[^:]".toRegex(), "").length val nr_endbrackets = hostport_str.replace("[^]]".toRegex(), "").length if (nr_colons == 1) { // IPv4 val p = hostport_str.substring(hostport_str.indexOf(':') + 1) try { port = p.toInt() } catch (e: Exception) { } address = hostport_str.substring(0, hostport_str.indexOf(':')) return true } if (nr_colons > 1 && nr_endbrackets == 1) { val p = hostport_str.substring(hostport_str.indexOf(']') + 2) // it's [addr]:port try { port = p.toInt() } catch (e: Exception) { } address = hostport_str.substring(0, hostport_str.indexOf(']') + 1) return true } return false } companion object { //These are used by ConnectionListActivity const val GEN_FIELD_NICKNAME = "NICKNAME" const val GEN_FIELD_ADDRESS = "ADDRESS" const val GEN_FIELD_PORT = "PORT" const val GEN_FIELD_REPEATERID = "REPEATERID" } }
gpl-3.0
fobo66/BookcrossingMobile
app/src/test/java/com/bookcrossing/mobile/interactor/StashInteractorTest.kt
1
2993
/* * Copyright 2019 Andrey Mukamolov * * 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.bookcrossing.mobile.interactor import com.bookcrossing.mobile.data.AuthRepository import com.bookcrossing.mobile.data.BooksRepository import com.bookcrossing.mobile.data.NotificationRepository import io.mockk.every import io.mockk.mockk import io.reactivex.Completable import io.reactivex.Single import org.junit.Before import org.junit.Test class StashInteractorTest { private lateinit var stashInteractor: StashInteractor private val authRepository: AuthRepository = mockk() private val booksRepository: BooksRepository = mockk() private val notificationRepository: NotificationRepository = mockk() @Before fun setUp() { every { authRepository.userId } returns "test" every { booksRepository.addBookToStash(any(), any()) } returns Completable.complete() every { booksRepository.removeBookFromStash(any(), any()) } returns Completable.complete() every { notificationRepository.subscribeToBookStashNotifications(any()) } returns Completable.complete() every { notificationRepository.unsubscribeFromBookStashNotifications(any()) } returns Completable.complete() stashInteractor = StashInteractor(booksRepository, authRepository, notificationRepository) } @Test fun `check existing stashed state`() { every { booksRepository.onBookStashed(any(), any()) } returns Single.just(true) stashInteractor.checkStashedState("test") .test() .assertValue(true) .assertComplete() .dispose() } @Test fun `check missing stashed state`() { every { booksRepository.onBookStashed(any(), any()) } returns Single.just(false) stashInteractor.checkStashedState("test") .test() .assertValue(false) .assertComplete() .dispose() } @Test fun `error during checking stashed state`() { every { booksRepository.onBookStashed(any(), any()) } returns Single.error(Exception()) stashInteractor.checkStashedState("test") .test() .assertValue(false) .assertNoErrors() .dispose() } @Test fun stashBook() { stashInteractor.stashBook("test") .test() .assertComplete() .dispose() } @Test fun unstashBook() { stashInteractor.unstashBook("test") .test() .assertComplete() .dispose() } }
apache-2.0
FutureioLab/FastPeak
app/src/main/java/com/binlly/fastpeak/business/test/adapter/SectionDelegate.kt
1
674
package com.binlly.fastpeak.business.test.adapter import android.content.Context import android.widget.TextView import com.binlly.fastpeak.R import com.binlly.fastpeak.base.adapter.BaseDelegate import com.binlly.fastpeak.business.test.model.TestModel import com.chad.library.adapter.base.BaseViewHolder /** * Created by binlly on 2017/5/13. */ class SectionDelegate(context: Context): BaseDelegate<TestModel>(context) { override val layoutResId: Int get() = R.layout.test_item_section override fun childConvert(holder: BaseViewHolder, item: TestModel) { val text = holder.getView<TextView>(R.id.text) text.text = item.section } }
mit
pie-flavor/Kludge
src/main/kotlin/flavor/pie/kludge/advancements.kt
1
3394
package flavor.pie.kludge import org.spongepowered.api.advancement.Advancement import org.spongepowered.api.advancement.TreeLayout import org.spongepowered.api.advancement.TreeLayoutElement import org.spongepowered.api.advancement.criteria.AdvancementCriterion import org.spongepowered.api.advancement.criteria.ScoreCriterionProgress import org.spongepowered.api.text.Text import java.time.Instant /** * @see Advancement.toToastText */ val Advancement.toastText: List<Text> get() = toToastText() /** * @see TreeLayout.getElement */ operator fun TreeLayout.get(advancement: Advancement): TreeLayoutElement? = getElement(advancement).unwrap() /** * @see AdvancementCriterion.and */ infix fun AdvancementCriterion.and(criterion: AdvancementCriterion): AdvancementCriterion = and(criterion) /** * @see AdvancementCriterion.and */ infix fun AdvancementCriterion.and(criteria: Iterable<AdvancementCriterion>): AdvancementCriterion = and(criteria) /** * @see AdvancementCriterion.or */ infix fun AdvancementCriterion.or(criterion: AdvancementCriterion): AdvancementCriterion = or(criterion) /** * @see AdvancementCriterion.or */ infix fun AdvancementCriterion.or(criteria: Iterable<AdvancementCriterion>): AdvancementCriterion = or(criteria) /** * @see ScoreCriterionProgress.add */ operator fun ScoreCriterionProgress.plusAssign(score: Int) { add(score) } /** * @see ScoreCriterionProgress.add */ operator fun ScoreCriterionProgress.plus(score: Int): Instant? = add(score).unwrap() /** * @see ScoreCriterionProgress.remove */ operator fun ScoreCriterionProgress.minusAssign(score: Int) { remove(score) } /** * @see ScoreCriterionProgress.remove */ operator fun ScoreCriterionProgress.minus(score: Int): Instant? = remove(score).unwrap() /** * Multiplies the score by [score]. * @see ScoreCriterionProgress.set */ operator fun ScoreCriterionProgress.timesAssign(score: Int) { set(this.score * score) } /** * Multiplies the score by [score]. * @see ScoreCriterionProgress.set */ operator fun ScoreCriterionProgress.times(score: Int): Instant? = set(this.score * score).unwrap() /** * Divides the score by [score]. * @see ScoreCriterionProgress.set */ operator fun ScoreCriterionProgress.divAssign(score: Int) { set(this.score / score) } /** * Divides the score by [score]. * @see ScoreCriterionProgress.set */ operator fun ScoreCriterionProgress.div(score: Int): Instant? = set(this.score / score).unwrap() /** * Adds 1 to the score. * @see ScoreCriterionProgress.add */ operator fun ScoreCriterionProgress.inc(): ScoreCriterionProgress = apply { add(1) } /** * Subtracts 1 from the score. * @see ScoreCriterionProgress.remove */ operator fun ScoreCriterionProgress.dec(): ScoreCriterionProgress = apply { remove(1) } /** * @see ScoreCriterionProgress.getScore */ operator fun ScoreCriterionProgress.unaryPlus(): Int = +score /** * Gets the score multiplied by -1. * @see ScoreCriterionProgress.getScore */ operator fun ScoreCriterionProgress.unaryMinus(): Int = -score /** * Compares the score to [i]. * @see ScoreCriterionProgress.getScore */ operator fun ScoreCriterionProgress.compareTo(i: Int): Int = score.compareTo(i) /** * Compares the scores of both progresses. * @see ScoreCriterionProgress.getScore */ operator fun ScoreCriterionProgress.compareTo(progress: ScoreCriterionProgress): Int = score.compareTo(progress.score)
mit
NLPIE/BioMedICUS
biomedicus-core/src/main/kotlin/edu/umn/biomedicus/sentences/SentenceEndingStats.kt
1
2220
/* * Copyright (c) 2018 Regents of the University of Minnesota. * * 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 edu.umn.biomedicus.sentences import edu.umn.nlpengine.Document import edu.umn.nlpengine.DocumentsProcessor import edu.umn.nlpengine.labelIndex class SentenceEndingStats : DocumentsProcessor { val periodRegex = Regex("[.]\\s*$") val exRegex = Regex("[!]\\s*$") val questRegex = Regex("[?]\\s*$") val semiRegex = Regex("[;]\\s*$") val colonRegex = Regex("[:]\\s*$") val quoteRegex = Regex("[.!?;:][\"”]\\s*\$") var periods = 0 var exclams = 0 var questions = 0 var semicolon = 0 var colon = 0 var quote = 0 var none = 0 override fun process(document: Document) { val sentences = document.labelIndex<Sentence>() for (sentence in sentences) { if (sentence.sentenceClass == Sentence.unknown) continue val text = sentence.coveredText(document.text) when { periodRegex.containsMatchIn(text) -> periods++ exRegex.containsMatchIn(text) -> exclams++ questRegex.containsMatchIn(text) -> questions++ semiRegex.containsMatchIn(text) -> semicolon++ colonRegex.containsMatchIn(text) -> colon++ quoteRegex.containsMatchIn(text) -> quote++ else -> none++ } } } override fun done() { println("periods: $periods") println("exclams: $exclams") println("questions: $questions") println("semicolon: $semicolon") println("colon: $colon") println("quote: $quote") println("none: $none") } }
apache-2.0
mpecan/chat
src/test/kotlin/si/pecan/RepositoryTests.kt
1
2050
package si.pecan import com.winterbe.expekt.should import org.junit.Test import org.junit.runner.RunWith import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.test.context.SpringBootTest import org.springframework.test.context.junit4.SpringRunner import si.pecan.Stubs.Companion.ANOTHER_VALID_USER import si.pecan.Stubs.Companion.VALID_USER import si.pecan.model.ChatRoom import si.pecan.model.InstantMessage import javax.transaction.Transactional @RunWith(SpringRunner::class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK) @Transactional open class RepositoryTests { @Autowired lateinit var userRepository: UserRepository @Autowired lateinit var chatRepository: ChatRoomRepository @Autowired lateinit var instantMessageRepository: InstantMessageRepository @Test fun testUserRepository() { val user = userRepository.save(VALID_USER) user.id.should.not.be.`null` userRepository.count().should.equal(1) } @Test fun testUserFound() { userRepository.save(VALID_USER) userRepository.findByUsername("testuser").should.not.be.`null` } @Test fun testCreateChatRoom() { val chatRoom = createChatRoom() chatRoom.created.should.not.be.`null` } @Test fun testCreateChat() { val chatRoom = createChatRoom() val user = userRepository.findByUsername("testuser") ?: throw Exception() val message = instantMessageRepository.save(InstantMessage().apply { room = chatRoom postedBy = user content = "some chat" }) message.id.should.not.be.`null` } private fun createChatRoom(): ChatRoom { val users = userRepository.save(arrayListOf(VALID_USER, ANOTHER_VALID_USER)).toCollection(mutableListOf()) val chatRoom = chatRepository.save(ChatRoom().apply { this.users = users this.createdBy = users.first() }) return chatRoom } }
apache-2.0
RP-Kit/RPKit
bukkit/rpk-professions-lib-bukkit/src/main/kotlin/com/rpkit/professions/bukkit/profession/RPKProfessionName.kt
1
688
/* * Copyright 2021 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.professions.bukkit.profession data class RPKProfessionName(val value: String)
apache-2.0
Doist/TodoistModels
src/main/java/com/todoist/pojo/EventExtraData.kt
1
543
package com.todoist.pojo open class EventExtraData( open var content: String?, open var lastContent: String?, open var description: String?, open var lastDescription: String?, open var dueDate: Long?, open var lastDueDate: Long?, open var responsibleUid: Long?, open var lastResponsibleUid: Long?, open var name: String?, open var lastName: String?, open var parentProjectName: String?, open var parentProjectColor: Int?, open var parentItemContent: String?, open var noteCount: Int? )
mit
siosio/kotlin-jsr352-jsl
src/main/kotlin/siosio/jsr352/jsl/Properties.kt
1
547
package siosio.jsr352.jsl interface Properties { val properties: MutableList<Property> fun property(name: String, value: String) { properties.add(Property(name, value)) } fun buildProperties(): String { if (properties.isEmpty()) { return "" } val xml = StringBuilder() xml.append("<properties>") properties.map { it.build() }.forEach { xml.append(it) } xml.append("</properties>") return xml.toString() } }
mit
waicool20/SKrypton
src/main/kotlin/com/waicool20/skrypton/jni/objects/SKryptonApp.kt
1
6637
/* * The MIT License (MIT) * * Copyright (c) SKrypton by waicool20 * * 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.waicool20.skrypton.jni.objects import com.waicool20.skrypton.jni.CPointer import com.waicool20.skrypton.jni.NativeInterface import com.waicool20.skrypton.util.OS import com.waicool20.skrypton.util.SystemUtils import com.waicool20.skrypton.util.div import com.waicool20.skrypton.util.loggerFor import java.nio.file.Files import java.nio.file.Path import java.nio.file.Paths import kotlin.streams.toList import kotlin.system.exitProcess import javafx.application.Platform /** * A singleton app instance for this library and is the main entry point for any program that wants * to use any of the SKrypton APIs. This object is in charge of initializing the native components * and managing it. */ object SKryptonApp : NativeInterface() { /** * Holds a [Path] pointing to the directory used by SKrypton, this directory contains all the * native libraries and resources that SKrypton will use. */ val APP_DIRECTORY: Path = Paths.get(System.getProperty("user.home")) / ".skrypton" private val logger = loggerFor<SKryptonApp>() /** * Native pointer, initialized in [initialize]. */ override lateinit var handle: CPointer // Get the load order from the nativeLibraries-<OS> file in resources private val nativeDependencies = run { val resourceFile = when { OS.isLinux() -> "nativeLibraries-linux.txt" OS.isWindows() -> "nativeLibraries-windows.txt" OS.isMac() -> TODO("I don't have a mac to test this stuff yet") else -> error("Unsupported system") } SKryptonApp::class.java .getResourceAsStream("/com/waicool20/skrypton/resources/$resourceFile") ?.bufferedReader()?.lines()?.toList()?.filterNot { it.isNullOrEmpty() } ?: error("Could not read '$resourceFile' from classpath.") } init { if (Files.notExists(APP_DIRECTORY)) error("Could not find SKrypton Native components folder, did you install it?") val libs = Files.walk(APP_DIRECTORY / "lib") .filter { Files.isRegularFile(it) && "${it.fileName}".dropWhile { it != '.' }.contains(OS.libraryExtention) } .sorted { path1, path2 -> nativeDependencies.indexOfFirst { "${path1.fileName}".contains(it) } - nativeDependencies.indexOfFirst { "${path2.fileName}".contains(it) } }.toList() libs.plusElement(APP_DIRECTORY / System.mapLibraryName("SKryptonNative")).forEach { logger.debug { "Loading library at $it" } SystemUtils.loadLibrary(it, true) } } /** * Initializes the native components. * * @param args Arguments to pass to the native components, recommended to just pass the array * received from the main function. Default is an empty array. * @param remoteDebugPort The remote debug port is initialized if given a valid value from 0 to 65535 * and that the port is not previously occupied. Default is -1 (Not initialized). * @param action Action to be executed with the SKryptonApp instance as its receiver. * @return [SKryptonApp] instance (Can be used to chain [exec] function). */ fun initialize(args: Array<String> = emptyArray(), remoteDebugPort: Int = -1, action: SKryptonApp.() -> Unit = {} ): SKryptonApp { if (remoteDebugPort in 0..65535) { putEnv("QTWEBENGINE_REMOTE_DEBUGGING", remoteDebugPort.toString()) } handle = CPointer(initialize_N(args)) this.action() return this } /** * Blocking function which starts the execution of the SKryptonApp. * * @param exit Whether or not to exit when SKryptonApp instance is done. Defaults to false * @return If [exit] is false, this function will return the exit code of the native side. */ fun exec(exit: Boolean = false): Int { val exitCode = exec_N() if (exit) exitProcess(exitCode) return exitCode } /** * Executes the given action on the thread where SKryptonApp exists. This is similar to the * [Platform.runLater] method. * * @param action Action to be executed. */ fun runOnMainThread(action: () -> Unit) = runOnMainThread_N(Runnable { action() }) //<editor-fold desc="Environment functions"> /** * Puts an variable into the native environment, it is lost when the SKryptonApp is done executing. * * @param key The name of the environment variable. * @param value The value of the environment variable. */ fun putEnv(key: String, value: String) = putEnv_N(key, value) /** * Gets the value of the native environment variable. * * @param key The name of the environment variable. * @return The value of the environment variable. */ fun getEnv(key: String) = getEnv_N(key) //</editor-fold> /** * Closes the SKryptonApp instance explicitly. */ override fun close() { dispose_N() } //<editor-fold desc="Native functions"> private external fun putEnv_N(key: String, value: String) private external fun getEnv_N(key: String): String private external fun runOnMainThread_N(action: Runnable) private external fun initialize_N(args: Array<String>): Long private external fun exec_N(): Int private external fun dispose_N() //</editor-fold> }
mit
ujpv/intellij-rust
src/main/kotlin/org/rust/cargo/runconfig/CargoRunState.kt
1
1773
package org.rust.cargo.runconfig import com.intellij.execution.configurations.CommandLineState import com.intellij.execution.process.KillableColoredProcessHandler import com.intellij.execution.process.ProcessHandler import com.intellij.execution.process.ProcessTerminatedListener import com.intellij.execution.runners.ExecutionEnvironment import com.intellij.openapi.module.Module import com.intellij.openapi.vfs.VirtualFile import org.rust.cargo.toolchain.RustToolchain class CargoRunState( environment: ExecutionEnvironment, private val toolchain: RustToolchain, module: Module, private val cargoProjectDirectory: VirtualFile, private val command: String, private val additionalArguments: List<String>, private val environmentVariables: Map<String, String> ) : CommandLineState(environment) { init { consoleBuilder.addFilter(RustConsoleFilter(environment.project, cargoProjectDirectory)) consoleBuilder.addFilter(RustExplainFilter()) consoleBuilder.addFilter(RustPanicFilter(environment.project, cargoProjectDirectory)) consoleBuilder.addFilter(RustBacktraceFilter(environment.project, cargoProjectDirectory, module)) } override fun startProcess(): ProcessHandler { val cmd = toolchain.cargo(cargoProjectDirectory.path) .generalCommand(command, additionalArguments, environmentVariables) // Explicitly use UTF-8. // Even though default system encoding is usually not UTF-8 on windows, // most Rust programs are UTF-8 only. .withCharset(Charsets.UTF_8) val handler = KillableColoredProcessHandler(cmd) ProcessTerminatedListener.attach(handler) // shows exit code upon termination return handler } }
mit
konrad-jamrozik/droidmate
dev/droidmate/buildSrc/src/main/kotlin/org/droidmate/buildsrc/build.kt
1
6575
// DroidMate, an automated execution generator for Android apps. // Copyright (C) 2012-2016 Konrad Jamrozik // // 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/>. // // email: [email protected] // web: www.droidmate.org // "unused" warning is suppressed because vals in this project are being used in the 'droidmate' project gradle build scripts // as well as in the 'droidmate' project itself. The "unused" warning doesn't properly recognize some of the usages. @file:Suppress("unused") package org.droidmate.buildsrc import com.konradjamrozik.OS import com.konradjamrozik.asEnvDir import com.konradjamrozik.resolveDir import com.konradjamrozik.resolveRegularFile import org.zeroturnaround.exec.ProcessExecutor import java.io.ByteArrayOutputStream import java.io.File import java.nio.file.Paths import java.util.* import java.util.concurrent.TimeUnit private val exeExt = if (OS.isWindows) ".exe" else "" //region Values directly based on system environment variables val java_home = "JAVA_HOME".asEnvDir private val android_sdk_dir = "ANDROID_HOME".asEnvDir //endregion val jarsigner_relative_path = "bin/jarsigner$exeExt" val jarsigner = java_home.resolveRegularFile(jarsigner_relative_path) //region Android SDK components private val build_tools_version = "25.0.1" private val android_platform_version_api19 = "19" private val android_platform_version_api23 = "23" val aapt_command_relative = "build-tools/$build_tools_version/aapt$exeExt" val adb_command_relative = "platform-tools/adb$exeExt" val aapt_command = android_sdk_dir.resolveRegularFile(aapt_command_relative) val adb_command = android_sdk_dir.resolveRegularFile(adb_command_relative) private val android_platform_dir_api19 = android_sdk_dir.resolveDir("platforms/android-$android_platform_version_api19") private val android_platform_dir_api23 = android_sdk_dir.resolveDir("platforms/android-$android_platform_version_api23") val uiautomator_jar_api19 = android_platform_dir_api19.resolveRegularFile("uiautomator.jar") val uiautomator_jar_api23 = android_platform_dir_api23.resolveRegularFile("uiautomator.jar") val android_jar_api19 = android_platform_dir_api19.resolveRegularFile("android.jar") val android_jar_api23 = android_platform_dir_api23.resolveRegularFile("android.jar") val android_extras_m2repo = android_sdk_dir.resolveDir("extras/android/m2repository") //endregion val monitor_generator_res_name_monitor_template = "monitorTemplate.txt" private val monitor_generator_output_dir = "temp" fun generated_monitor(apiLevel: Int) : String { return "$monitor_generator_output_dir/generated_Monitor_api$apiLevel.java" } val monitor_generator_output_relative_path_api19 = generated_monitor(19) val monitor_generator_output_relative_path_api23 = generated_monitor(23) val apk_inliner_param_input_default = Paths.get("input-apks") val apk_inliner_param_output_dir_default = Paths.get("output-apks") val apk_inliner_param_input = "-input" val apk_inliner_param_output_dir = "-outputDir" val AVD_dir_for_temp_files = "/data/local/tmp/" val uia2_daemon_project_name = "uiautomator2-daemon" val uia2_daemon_relative_project_dir = File("projects", uia2_daemon_project_name) val monitored_apk_fixture_api19_name = "MonitoredApkFixture_api19-debug.apk" val monitored_apk_fixture_api23_name = "MonitoredApkFixture_api23-debug.apk" val monitored_inlined_apk_fixture_api19_name = "${monitored_apk_fixture_api19_name.removeSuffix(".apk")}-inlined.apk" val monitored_inlined_apk_fixture_api23_name = "${monitored_apk_fixture_api23_name.removeSuffix(".apk")}-inlined.apk" val monitor_api19_apk_name = "monitor_api19.apk" val monitor_api23_apk_name = "monitor_api23.apk" val monitor_on_avd_apk_name = "monitor.apk" /** * Denotes name of directory containing apk fixtures for testing. The handle to this path is expected to be obtained * in following ways: * * From a build.gradle script: * * new File(sourceSets.test.resources.srcDirs[0], <this_var_reference>) * * From compiled source code: * * new Resource("<this_var_reference>").extractTo(fs.getPath(BuildConstants.dir_name_temp_extracted_resources)) */ val apk_fixtures = "fixtures/apks" val test_temp_dir_name = "temp_dir_for_tests" val monitored_apis_txt = "monitored_apis.txt" /** * Directory for resources extracted from jars in the classpath. * * Some resources have to be extracted to a directory. For example, an .apk file that is inside a .jar needs to be pushed * to a device. */ val dir_name_temp_extracted_resources = "temp_extracted_resources" // !!! DUPLICATION WARNING !!! with org.droidmate.MonitorConstants.monitor_time_formatter_locale val locale = Locale.US fun executeCommand(commandName: String, commandContent: String): Int { val cmd = if (OS.isWindows) "cmd /c " else "" val commandString = cmd + commandContent println("=========================") println("Executing command named: $commandName") println("Command string:") println(commandString) val err = ByteArrayOutputStream() val out = ByteArrayOutputStream() val process = ProcessExecutor() .readOutput(true) .redirectOutput(out) .redirectError(err) .timeout(120, TimeUnit.SECONDS) print("executing...") val result = process.commandSplit(commandString).execute() println(" DONE") println("return code: ${result.exitValue}") val stderrContent = err.toString(Charsets.UTF_8.toString()) val stdoutContent = out.toString(Charsets.UTF_8.toString()) if (stderrContent != "") { println("----------------- stderr:") println(stderrContent) println("----------------- /stderr") } else println("stderr is empty") if (stdoutContent != "") { if (result.exitValue == 0) println("stdout is ${stdoutContent.length} chars long") else { println("----------------- stdout:") println(stdoutContent) println("----------------- /stderr") } } else println("stdout is empty") println("=========================") return result.exitValue }
gpl-3.0
MaibornWolff/codecharta
analysis/import/MetricGardenerImporter/src/test/resources/MetricGardenerRawFile.kt
1
1199
package de.maibornwolff.codecharta.importer.metricgardenerimporter.model import com.fasterxml.jackson.annotation.JsonIgnoreProperties import com.fasterxml.jackson.annotation.JsonProperty import de.maibornwolff.codecharta.model.Path @JsonIgnoreProperties("types") class MetricGardenerRawFile( @JsonProperty("name") var name: String?, @JsonProperty("type") var type: String?, @JsonProperty("metrics") var metrics: Map<String, Any> ) { fun getPathWithoutFileName(): Path { if (!name.isNullOrBlank()) { return Path(name!!.split("\\").dropLast(1)) } return Path(emptyList()) } override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as MetricGardenerRawFile if (name != other.name) return false if (type != other.type) return false if (metrics != other.metrics) return false return true } override fun hashCode(): Int { var result = name?.hashCode() ?: 0 result = 31 * result + (type?.hashCode() ?: 0) result = 31 * result + metrics.hashCode() return result } }
bsd-3-clause
LorittaBot/Loritta
discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/morenitta/commands/vanilla/utils/OCRCommand.kt
1
2291
package net.perfectdreams.loritta.morenitta.commands.vanilla.utils import com.github.salomonbrys.kotson.get import com.github.salomonbrys.kotson.jsonArray import com.github.salomonbrys.kotson.jsonObject import com.github.salomonbrys.kotson.string import com.google.gson.JsonParser import net.perfectdreams.loritta.morenitta.commands.AbstractCommand import net.perfectdreams.loritta.morenitta.commands.CommandContext import net.perfectdreams.loritta.morenitta.utils.Constants import net.perfectdreams.loritta.morenitta.utils.gson import io.ktor.client.request.* import io.ktor.client.statement.* import io.ktor.http.* import net.dv8tion.jda.api.EmbedBuilder import net.perfectdreams.loritta.common.locale.BaseLocale import net.perfectdreams.loritta.common.locale.LocaleKeyData import java.io.ByteArrayOutputStream import java.util.* import javax.imageio.ImageIO import net.perfectdreams.loritta.morenitta.LorittaBot class OCRCommand(loritta: LorittaBot) : AbstractCommand(loritta, "ocr", listOf("ler", "read"), net.perfectdreams.loritta.common.commands.CommandCategory.UTILS) { override fun getDescriptionKey() = LocaleKeyData("commands.command.ocr.description") override suspend fun run(context: CommandContext,locale: BaseLocale) { val contextImage = context.getImageAt(0, createTextAsImageIfNotFound = false) ?: run { Constants.INVALID_IMAGE_REPLY.invoke(context); return; } ByteArrayOutputStream().use { ImageIO.write(contextImage, "png", it) val json = jsonObject( "requests" to jsonArray( jsonObject( "features" to jsonArray( jsonObject( "maxResults" to 1, "type" to "TEXT_DETECTION" ) ), "image" to jsonObject( "content" to Base64.getEncoder().encodeToString(it.toByteArray()) ) ) ) ) val responses = loritta.googleVisionOCRClient.ocr(it.toByteArray()) val builder = EmbedBuilder() builder.setTitle("\uD83D\uDCDD\uD83D\uDD0D OCR") try { builder.setDescription("```${responses.responses.first().textAnnotations!!.first().description}```") } catch (e: Exception) { builder.setDescription("**${locale["commands.command.ocr.couldntFind"]}**") } context.sendMessage(context.getAsMention(true), builder.build()) } } }
agpl-3.0
f3401pal/CSM
app/src/main/kotlin/com/f3401pal/csm/model/DataSource.kt
1
194
package com.f3401pal.csm.model enum class DataSource(value: String) { CBE("CBE Data"), CSSD("CSSD Data"), PROVINCIAL("Provincial Data"), POST_SECONDARY("Post Secondary Data") }
apache-2.0
cbeyls/fosdem-companion-android
app/src/main/java/be/digitalia/fosdem/fragments/RecycledViewPoolProvider.kt
1
294
package be.digitalia.fosdem.fragments import androidx.recyclerview.widget.RecyclerView /** * Components implementing this interface allow to share a RecycledViewPool between similar fragments. */ interface RecycledViewPoolProvider { val recycledViewPool: RecyclerView.RecycledViewPool }
apache-2.0
JayNewstrom/Concrete
concrete/src/main/java/com/jaynewstrom/concrete/FoundationConcreteBlock.kt
1
226
package com.jaynewstrom.concrete internal class FoundationConcreteBlock<out C>(private val component: C) : ConcreteBlock<C> { override fun name(): String = "Foundation" override fun createComponent(): C = component }
apache-2.0
r-artworks/game-seed
core/src/com/rartworks/engine/collisions/CollisionInfo.kt
1
876
package com.rartworks.engine.collisions /** * Contains a [shape] and info container for collision filtering. */ class CollisionInfo(val shape: CollisionShape, private val id: Int, vararg private val collidesWith: Int) { val categoryBits: Short get() = this.id.toShort() val maskBits: Short init { val others = this.collidesWith.toList() this.maskBits = others.fold(0) { prev, elem -> prev.or(elem) }.toShort() } /** * Sets the [maskBits] to the body. */ fun enable() { this.setMaskBits(this.maskBits) } /** * Clear the body's maskBits to disable collisions. */ fun disable() { this.setMaskBits(0) } /** * Sets the [maskBits] to the body. */ private fun setMaskBits(maskBits: Short) { this.shape.body.fixtureList.forEach { val filterData = it.filterData filterData.maskBits = maskBits it.filterData = filterData } } }
mit
seventhmoon/GeoIp-android
app/src/main/java/com/androidfung/geoip/MainActivity.kt
1
1902
package com.androidfung.geoip import android.os.Bundle import android.util.Log import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.widget.Toolbar import androidx.databinding.DataBindingUtil import com.androidfung.geoip.ServicesManager.geoIpService import com.androidfung.geoip.databinding.ActivityMainBinding import com.androidfung.geoip.model.GeoIpResponseModel import retrofit2.Call import retrofit2.Callback import retrofit2.Response class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val binding: ActivityMainBinding = DataBindingUtil.setContentView(this, R.layout.activity_main) val toolbar = findViewById<Toolbar>(R.id.toolbar) setSupportActionBar(toolbar) val ipApiService = geoIpService ipApiService.getGeoIp().enqueue(object : Callback<GeoIpResponseModel> { override fun onResponse(call: Call<GeoIpResponseModel>, response: Response<GeoIpResponseModel>) { binding.response = response.body() Log.d(TAG, response.toString()) response.body()?.let { Log.d(TAG, it.toString()) // Log.d(TAG, it.body().toString()) if (it.isError) { showError(it.reason) Log.e(TAG, it.reason.toString()) } } } override fun onFailure(call: Call<GeoIpResponseModel>, t: Throwable) { showError(t.toString()) Log.e(TAG, t.toString()) } }) } private fun showError(message: String?) { Toast.makeText(this, message, Toast.LENGTH_SHORT).show() } companion object { private val TAG = MainActivity::class.java.simpleName } }
mit
christophpickl/kpotpourri
http4k/src/test/kotlin/com/github/christophpickl/kpotpourri/http4k/internal/ResponseCasterTest.kt
1
4990
package com.github.christophpickl.kpotpourri.http4k.internal import com.fasterxml.jackson.core.type.TypeReference import com.github.christophpickl.kpotpourri.common.KPotpourriException import com.github.christophpickl.kpotpourri.http4k.Http4kException import com.github.christophpickl.kpotpourri.http4k.Response4k import com.github.christophpickl.kpotpourri.http4k.SC_200_Ok import com.github.christophpickl.kpotpourri.http4k.internal.ResponseCaster.cast import com.github.christophpickl.kpotpourri.test4k.assertThrown import com.github.christophpickl.kpotpourri.test4k.hamkrest_matcher.allOf import com.github.christophpickl.kpotpourri.test4k.hamkrest_matcher.isA import com.natpryce.hamkrest.assertion.assertThat import com.natpryce.hamkrest.equalTo import org.testng.annotations.DataProvider import org.testng.annotations.Test import kotlin.reflect.KClass @Test class ResponseCasterTest { fun `cast return class - primitives`() { assertReturnClass("body", Unit::class, Unit) assertReturnClass("", Unit::class, Unit) assertReturnClass("body", Any::class, response("body")) assertReturnClass("body", Response4k::class, response("body")) assertReturnClass("body", String::class, "body") assertReturnClass("", String::class, "") assertReturnClass("1.0", Float::class, 1.0F) assertReturnClass("1.0", Double::class, 1.0) assertReturnClass("1", Byte::class, 1.toByte()) assertReturnClass("1", Short::class, 1.toShort()) assertReturnClass("1", Int::class, 1) assertReturnClass("1", Long::class, 1.toLong()) assertReturnClass("true", Boolean::class, true) assertReturnClass("1", Boolean::class, true) } @Test(dataProvider = "invalidNumberProvider") fun `cast return class - invalid number`(body: String, type: KClass<*>, ignore: Any) { assertThrown<NumberFormatException> { cast(response(body), ReturnOption.ReturnClass(type)) } } fun `cast return class - invalid boolean`() { assertThrown<KPotpourriException> { cast(response("x"), ReturnOption.ReturnClass(Boolean::class)) } } fun `cast return class - dto`() { assertReturnClass("""{ "name": "foo" }""", Dto::class, Dto("foo")) assertReturnClass("""{ "dtos": [ { "name": "foo" } ] }""", Dtos::class, Dtos(listOf(Dto("foo")))) } fun `cast return class - list fails`() { assertThrown<Http4kException>(listOf("TypeReference")) { cast(response("""[ { "name": "foo" } ]"""), ReturnOption.ReturnClass(List::class)) } } fun `cast return type`() { assertReturnType("", Unit) assertReturnType<Any>("", response("")) assertReturnType("body", response("body")) assertReturnType("", response("")) assertReturnType("body", "body") assertReturnType("", "") assertReturnType("1.0", 1.0F) assertReturnType("1.0", 1.0) assertReturnType("1", 1.toByte()) assertReturnType("1", 1.toShort()) assertReturnType("1", 1) assertReturnType("1", 1.toLong()) assertReturnType("1", true) assertReturnType("""{ "name": "foo" }""", Dto("foo")) assertReturnType("""{ "dtos": [ { "name": "foo" } ] }""", Dtos(listOf(Dto("foo")))) assertReturnType("""[ { "name": "foo" } ]""", listOf(Dto("foo"))) } @Test(dataProvider = "invalidNumberProvider") fun <R : Any> `cast return type - invalid number`(body: String, ignore: Any, typeRef: TypeReference<R>) { assertThrown<NumberFormatException> { cast(response(body), ReturnOption.ReturnType(typeRef)) } } @Suppress("PLATFORM_CLASS_MAPPED_TO_KOTLIN") @DataProvider fun invalidNumberProvider() = arrayOf( arrayOf("x", Float::class, typeOf<Float>()), arrayOf("x", Double::class, typeOf<Double>()), arrayOf("x", Byte::class, typeOf<Byte>()), arrayOf("x", Short::class, typeOf<Short>()), arrayOf("x", Int::class, typeOf<Int>()), arrayOf("x", Integer::class, typeOf<Integer>()), arrayOf("x", Long::class, typeOf<Long>()) ) private inline fun <reified R: Any> typeOf() = object : TypeReference<R>() {} private inline fun <reified R : Any> assertReturnType(body: String, expected: R) { assertThat(cast(response(body), ReturnOption.ReturnType(object : TypeReference<R>() {})), allOf(isA(R::class), equalTo(expected))) } private fun assertReturnClass(body: String, returnClass: KClass<*>, expected: Any) { assertThat(cast(response(body), ReturnOption.ReturnClass(returnClass)), allOf(isA(returnClass), equalTo(expected))) } private fun response(body: String) = Response4k(statusCode = SC_200_Ok, bodyAsString = body) } private data class Dto( val name: String ) private data class Dtos( val dtos: List<Dto> )
apache-2.0
kotlintest/kotlintest
kotest-assertions/src/jvmTest/kotlin/com/sksamuel/kotest/matchers/date/timestampTest.kt
2
3916
package com.sksamuel.kotest.matchers.date import io.kotest.core.spec.style.FreeSpec import io.kotest.matchers.date.shouldBeAfter import io.kotest.matchers.date.shouldBeBefore import io.kotest.matchers.date.shouldBeBetween import io.kotest.matchers.date.shouldNotBeAfter import io.kotest.matchers.date.shouldNotBeBefore import io.kotest.matchers.date.shouldNotBeBetween import io.kotest.matchers.shouldBe import io.kotest.matchers.shouldNotBe import java.sql.Timestamp import java.time.Instant class TimeStampTest : FreeSpec() { init { "two timestamp of same instance should be same" { val nowInstance = Instant.now() Timestamp.from(nowInstance) shouldBe Timestamp.from(nowInstance) } "two timestamp of different instance should be not be same" { val nowInstance = Instant.now() val anotherInstance = nowInstance.plusMillis(1000L) Timestamp.from(nowInstance) shouldNotBe Timestamp.from(anotherInstance) } "timestamp of current instance should be after the timestamp of past instance" { val nowInstance = Instant.now() val instanceBeforeFiveSecond = nowInstance.minusMillis(5000L) Timestamp.from(nowInstance) shouldBeAfter Timestamp.from(instanceBeforeFiveSecond) } "timestamp of current instance should not be after the timestamp of future instance" { val nowInstance = Instant.now() val instanceAfterFiveSecond = nowInstance.plusMillis(5000L) Timestamp.from(nowInstance) shouldNotBeAfter Timestamp.from(instanceAfterFiveSecond) } "timestamp of current instance should not be after the another timestamp of same instance" { val nowInstance = Instant.now() Timestamp.from(nowInstance) shouldNotBeAfter Timestamp.from(nowInstance) } "timestamp of current instance should be before the timestamp of future instance" { val nowInstance = Instant.now() val instanceAfterFiveSecond = nowInstance.plusMillis(5000L) Timestamp.from(nowInstance) shouldBeBefore Timestamp.from(instanceAfterFiveSecond) } "timestamp of current instance should not be before the timestamp of past instance" { val nowInstance = Instant.now() val instanceBeforeFiveSecond = nowInstance.minusMillis(5000L) Timestamp.from(nowInstance) shouldNotBeBefore Timestamp.from(instanceBeforeFiveSecond) } "timestamp of current instance should not be before the another timestamp of same instance" { val nowInstance = Instant.now() Timestamp.from(nowInstance) shouldNotBeBefore Timestamp.from(nowInstance) } "current timestamp should be between timestamp of past and future" { val nowInstant = Instant.now() val currentTimestamp = Timestamp.from(nowInstant) val pastTimestamp = Timestamp.from(nowInstant.minusMillis(5000)) val futureTimestamp = Timestamp.from(nowInstant.plusMillis(5000)) currentTimestamp.shouldBeBetween(pastTimestamp, futureTimestamp) } "past timestamp should not be between timestamp of current instant and future" { val nowInstant = Instant.now() val currentTimestamp = Timestamp.from(nowInstant) val pastTimestamp = Timestamp.from(nowInstant.minusMillis(5000)) val futureTimestamp = Timestamp.from(nowInstant.plusMillis(5000)) pastTimestamp.shouldNotBeBetween(currentTimestamp, futureTimestamp) } "future timestamp should not be between timestamp of current instant and future" { val nowInstant = Instant.now() val currentTimestamp = Timestamp.from(nowInstant) val pastTimestamp = Timestamp.from(nowInstant.minusMillis(5000)) val futureTimestamp = Timestamp.from(nowInstant.plusMillis(5000)) futureTimestamp.shouldNotBeBetween(pastTimestamp, currentTimestamp) } } }
apache-2.0
luoyuan800/NeverEnd
dataModel/src/cn/luo/yuan/maze/model/real/NoDebris.kt
1
271
package cn.luo.yuan.maze.model.real import cn.luo.yuan.maze.utils.Field /** * Copyright @Luo * Created by Gavin Luo on 9/12/2017. */ class NoDebris : RealState() { companion object { private const val serialVersionUID: Long = Field.SERVER_VERSION } }
bsd-3-clause
kotlintest/kotlintest
kotest-extensions/src/jvmMain/kotlin/io/kotest/extensions/system/SystemPropertiesExtensions.kt
1
12219
package io.kotest.extensions.system import io.kotest.core.test.TestCase import io.kotest.core.test.TestResult import io.kotest.core.listeners.ProjectListener import io.kotest.core.listeners.TestListener import io.kotest.extensions.system.OverrideMode.SetOrError import java.util.Properties /** * Changes System Properties with chosen key and value * * This is a helper function for code that uses System Properties. It changes the specific [key] from [System.getProperties] * with the specified [value], only during the execution of [block]. * * If the chosen key is in the properties, it will be changed according to [mode]. If the chosen key is not in the * properties, it will be included. * * After the execution of [block], the properties are set to what they were before. * * **ATTENTION**: This code is susceptible to race conditions. If you attempt to change the properties while it was * already changed, the result is inconsistent, as the System Properties Map is a single map. */ inline fun <T> withSystemProperty(key: String, value: String?, mode: OverrideMode = SetOrError, block: () -> T): T { return withSystemProperties(key to value, mode, block) } /** * Changes System Properties with chosen key and value * * This is a helper function for code that uses System Properties. It changes the specific key from [System.getProperties] * with the specified value, only during the execution of [block]. * * If the chosen key is in the properties, it will be changed according to [mode]. If the chosen key is not in the * properties, it will be included. * * After the execution of [block], the properties are set to what they were before. * * **ATTENTION**: This code is susceptible to race conditions. If you attempt to change the properties while it was * already changed, the result is inconsistent, as the System Properties Map is a single map. */ inline fun <T> withSystemProperties(pair: Pair<String, String?>, mode: OverrideMode = SetOrError, block: () -> T): T { return withSystemProperties(mapOf(pair), mode, block) } /** * Changes System Properties with chosen properties * * This is a helper function for code that uses System Properties. It changes the specific keys from [System.getProperties] * with the specified values, only during the execution of [block]. * * If the chosen key is in the properties, it will be changed according to [mode]. If the chosen key is not in the * properties, it will be included. * * After the execution of [block], the properties are set to what they were before. * * **ATTENTION**: This code is susceptible to race conditions. If you attempt to change the properties while it was * already changed, the result is inconsistent, as the System Properties Map is a single map. */ inline fun <T> withSystemProperties(props: Properties, mode: OverrideMode = SetOrError, block: () -> T): T { val map = props.toStringStringMap() return withSystemProperties(map, mode, block) } /** * Changes System Properties with chosen keys and values * * This is a helper function for code that uses System Properties. It changes the specific key from [System.getProperties] * with the specified value, only during the execution of [block]. * * If the chosen key is in the properties, it will be changed according to [mode]. If the chosen key is not in the * properties, it will be included. * * After the execution of [block], the properties are set to what they were before. * * **ATTENTION**: This code is susceptible to race conditions. If you attempt to change the properties while it was * already changed, the result is inconsistent, as the System Properties Map is a single map. */ inline fun <T> withSystemProperties(props: Map<String, String?>, mode: OverrideMode = SetOrError, block: () -> T): T { val previous = Properties().apply { putAll(System.getProperties()) }.toStringStringMap() // Safe copying to ensure immutability setSystemProperties(mode.override(previous, props)) try { return block() } finally { setSystemProperties(previous) } } @PublishedApi internal fun Properties.toStringStringMap(): Map<String, String> { return this.map { it.key.toString() to it.value.toString() }.toMap() } @PublishedApi internal fun setSystemProperties(map: Map<String, String>) { val propertiesToSet = Properties().apply { putAll(map) } System.setProperties(propertiesToSet) } abstract class SystemPropertyListener( private val newProperties: Map<String, String?>, private val mode: OverrideMode ) { private val originalProperties = System.getProperties().toStringStringMap() protected fun changeSystemProperties() { setSystemProperties(mode.override(originalProperties, newProperties)) } protected fun resetSystemProperties() { setSystemProperties(originalProperties) } } /** * Changes System Properties with chosen keys and values * * This is a Listener for code that uses System Properties. It changes the specific keys from [System.getProperties] * with the specified values, only during the execution of a test. * * If the chosen key is in the properties, it will be changed according to [mode]. If the chosen key is not in the * properties, it will be included. * * After the execution of the test, the properties are set to what they were before. * * **ATTENTION**: This code is susceptible to race conditions. If you attempt to change the environment while it was * already changed, the result is inconsistent, as the System Properties Map is a single map. */ class SystemPropertyTestListener(newProperties: Map<String, String?>, mode: OverrideMode = SetOrError) : SystemPropertyListener(newProperties, mode), TestListener { /** * Changes System Properties with chosen keys and values * * This is a Listener for code that uses System Properties. It changes the specific keys from [System.getProperties] * with the specified values, only during the execution of a test. * * If the chosen key is in the properties, it will be changed according to [mode]. If the chosen key is not in the * properties, it will be included. * * After the execution of the test, the properties are set to what they were before. * * **ATTENTION**: This code is susceptible to race conditions. If you attempt to change the environment while it was * already changed, the result is inconsistent, as the System Properties Map is a single map. */ constructor(listOfPairs: List<Pair<String, String?>>, mode: OverrideMode = SetOrError) : this( listOfPairs.toMap(), mode ) /** * Changes System Properties with chosen keys and values * * This is a Listener for code that uses System Properties. It changes the specific keys from [System.getProperties] * with the specified values, only during the execution of a test. * * If the chosen key is in the properties, it will be changed according to [mode]. If the chosen key is not in the * properties, it will be included. * * After the execution of the test, the properties are set to what they were before. * * **ATTENTION**: This code is susceptible to race conditions. If you attempt to change the environment while it was * already changed, the result is inconsistent, as the System Properties Map is a single map. */ constructor(key: String, value: String?, mode: OverrideMode = SetOrError) : this(mapOf(key to value), mode) /** * Changes System Properties with chosen keys and values * * This is a Listener for code that uses System Properties. It changes the specific keys from [System.getProperties] * with the specified values, only during the execution of a test. * * If the chosen key is in the properties, it will be changed according to [mode]. If the chosen key is not in the * properties, it will be included. * * After the execution of the test, the properties are set to what they were before. * * **ATTENTION**: This code is susceptible to race conditions. If you attempt to change the environment while it was * already changed, the result is inconsistent, as the System Properties Map is a single map. */ constructor(properties: Properties, mode: OverrideMode = SetOrError) : this(properties.toStringStringMap(), mode) override suspend fun beforeTest(testCase: TestCase) { changeSystemProperties() } override suspend fun afterTest(testCase: TestCase, result: TestResult) { resetSystemProperties() } } /** * Changes System Properties with chosen keys and values * * This is a Listener for code that uses System Properties. It changes the specific keys from [System.getProperties] * with the specified values, only during the execution of a test. * * If the chosen key is in the properties, it will be changed according to [mode]. If the chosen key is not in the * properties, it will be included. * * After the execution of the test, the properties are set to what they were before. * * **ATTENTION**: This code is susceptible to race conditions. If you attempt to change the environment while it was * already changed, the result is inconsistent, as the System Properties Map is a single map. */ class SystemPropertyProjectListener(newProperties: Map<String, String?>, mode: OverrideMode = SetOrError) : SystemPropertyListener(newProperties, mode), ProjectListener { /** * Changes System Properties with chosen keys and values * * This is a Listener for code that uses System Properties. It changes the specific keys from [System.getProperties] * with the specified values, only during the execution of a test. * * If the chosen key is in the properties, it will be changed according to [mode]. If the chosen key is not in the * properties, it will be included. * * After the execution of the test, the properties are set to what they were before. * * **ATTENTION**: This code is susceptible to race conditions. If you attempt to change the environment while it was * already changed, the result is inconsistent, as the System Properties Map is a single map. */ constructor(listOfPairs: List<Pair<String, String?>>, mode: OverrideMode = SetOrError) : this( listOfPairs.toMap(), mode ) /** * Changes System Properties with chosen keys and values * * This is a Listener for code that uses System Properties. It changes the specific keys from [System.getProperties] * with the specified values, only during the execution of a test. * * If the chosen key is in the properties, it will be changed according to [mode]. If the chosen key is not in the * properties, it will be included. * * After the execution of the test, the properties are set to what they were before. * * **ATTENTION**: This code is susceptible to race conditions. If you attempt to change the environment while it was * already changed, the result is inconsistent, as the System Properties Map is a single map. */ constructor(key: String, value: String?, mode: OverrideMode = SetOrError) : this(mapOf(key to value), mode) /** * Changes System Properties with chosen keys and values * * This is a Listener for code that uses System Properties. It changes the specific keys from [System.getProperties] * with the specified values, only during the execution of a test. * * If the chosen key is in the properties, it will be changed according to [mode]. If the chosen key is not in the * properties, it will be included. * * After the execution of the test, the properties are set to what they were before. * * **ATTENTION**: This code is susceptible to race conditions. If you attempt to change the environment while it was * already changed, the result is inconsistent, as the System Properties Map is a single map. */ constructor(properties: Properties, mode: OverrideMode = SetOrError) : this(properties.toStringStringMap(), mode) override fun beforeProject() { changeSystemProperties() } override fun afterProject() { resetSystemProperties() } }
apache-2.0
kotlintest/kotlintest
kotest-property/src/commonMain/kotlin/io/kotest/property/arbitrary/doubles.kt
1
1539
package io.kotest.property.arbitrary import io.kotest.property.Shrinker import kotlin.math.abs import kotlin.math.round /** * Returns an [Arb] where each value is a randomly chosen Double. */ fun Arb.Companion.double(): Arb<Double> { val edgecases = listOf( 0.0, 1.0, -1.0, 1e300, Double.MIN_VALUE, Double.MAX_VALUE, Double.NEGATIVE_INFINITY, Double.NaN, Double.POSITIVE_INFINITY ) return arb(DoubleShrinker, edgecases) { it.random.nextDouble() } } /** * Returns an [Arb] which is the same as [double] but does not include +INFINITY, -INFINITY or NaN. * * This will only generate numbers ranging from [from] (inclusive) to [to] (inclusive) */ fun Arb.Companion.numericDoubles( from: Double = Double.MIN_VALUE, to: Double = Double.MAX_VALUE ): Arb<Double> { val edgecases = listOf(0.0, 1.0, -1.0, 1e300, Double.MIN_VALUE, Double.MAX_VALUE).filter { it in (from..to) } return arb(DoubleShrinker, edgecases) { it.random.nextDouble(from, to) } } fun Arb.Companion.positiveDoubles(): Arb<Double> = double().filter { it > 0.0 } fun Arb.Companion.negativeDoubles(): Arb<Double> = double().filter { it < 0.0 } object DoubleShrinker : Shrinker<Double> { override fun shrink(value: Double): List<Double> { return if (value == 0.0) emptyList() else { val a = listOf(0.0, 1.0, -1.0, abs(value), value / 3, value / 2) val b = (1..5).map { value - it }.reversed().filter { it > 0 } (a + b + round(value)).distinct() } } }
apache-2.0
FurhatRobotics/example-skills
Interviewee/src/main/kotlin/furhatos/app/interview/main.kt
1
281
package furhatos.app.interview import furhatos.app.interview.flow.Init import furhatos.skills.Skill import furhatos.flow.kotlin.* class InterviewSkill : Skill() { override fun start() { Flow().run(Init) } } fun main(args: Array<String>) { Skill.main(args) }
mit
mcxiaoke/kotlin-koi
core/src/main/kotlin/com/mcxiaoke/koi/ext/String.kt
1
5839
package com.mcxiaoke.koi.ext import com.mcxiaoke.koi.Const import com.mcxiaoke.koi.Encoding import java.io.File import java.io.UnsupportedEncodingException import java.math.BigInteger import java.net.URLDecoder import java.util.* /** * User: mcxiaoke * Date: 16/1/22 * Time: 13:35 */ fun String.quote(): String { return "'$this'" } fun CharSequence.isBlank(): Boolean { val len: Int = this.length if (len == 0) { return true } forEach { c -> if (!Character.isWhitespace(c)) { return false } } return true } fun String.toHexBytes(): ByteArray { val len = this.length val data = ByteArray(len / 2) var i = 0 while (i < len) { data[i / 2] = ((Character.digit(this[i], 16) shl 4) + Character.digit(this[i + 1], 16)).toByte() i += 2 } return data } fun String.withoutQuery(): String { return this.split("\\?".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()[0] } fun String?.isNameSafe(): Boolean { // Note, we check whether it matches what's known to be safe, // rather than what's known to be unsafe. Non-ASCII, control // characters, etc. are all unsafe by default. if (this == null) { return false } return Const.SAFE_FILENAME_PATTERN.matcher(this).matches() } fun String.toSafeFileName(): String { val size = this.length val builder = StringBuilder(size * 2) forEachIndexed { i, c -> var valid = c in 'a'..'z' valid = valid || c in 'A'..'Z' valid = valid || c in '0'..'9' valid = valid || c == '_' || c == '-' || c == '.' if (valid) { builder.append(c) } else { // Encode the character using hex notation builder.append('x') builder.append(Integer.toHexString(i)) } } return builder.toString() } fun String.toQueries(): Map<String, String> { val map: Map<String, String> = mapOf() if (this.isEmpty()) { return map } try { val queries = HashMap<String, String>() for (param in this.split("&".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()) { val pair = param.split("=".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray() val key = URLDecoder.decode(pair[0], Encoding.UTF_8) if (pair.size > 1) { val value = URLDecoder.decode(pair[1], Encoding.UTF_8) queries.put(key, value) } } return queries } catch (ex: UnsupportedEncodingException) { throw RuntimeException(ex) } } @JvmOverloads fun String.toStringList(delimiters: String = "?", trimTokens: Boolean = true, ignoreEmptyTokens: Boolean = true): List<String> { val st = StringTokenizer(this, delimiters) val tokens = ArrayList<String>() while (st.hasMoreTokens()) { var token = st.nextToken() if (trimTokens) { token = token.trim { it <= ' ' } } if (!ignoreEmptyTokens || token.isNotEmpty()) { tokens.add(token) } } return tokens } @JvmOverloads fun String.toStringArray(delimiters: String = "?", trimTokens: Boolean = true, ignoreEmptyTokens: Boolean = true): Array<String> { return toStringList(delimiters, trimTokens, ignoreEmptyTokens).toTypedArray() } fun String.trimLeadingCharacter(leadingCharacter: Char): String { if (this.isEmpty()) { return this } val sb = StringBuilder(this) while (sb.isNotEmpty() && sb[0] == leadingCharacter) { sb.deleteCharAt(0) } return sb.toString() } fun String.trimTrailingCharacter(trailingCharacter: Char): String { if (this.isEmpty()) { return this } val sb = StringBuilder(this) while (sb.isNotEmpty() && sb[sb.length - 1] == trailingCharacter) { sb.deleteCharAt(sb.length - 1) } return sb.toString() } fun String.trimAllWhitespace(): String { if (this.isEmpty()) { return this } val sb = StringBuilder(this) var index = 0 while (sb.length > index) { if (Character.isWhitespace(sb[index])) { sb.deleteCharAt(index) } else { index++ } } return sb.toString() } fun CharSequence.containsWhitespace(): Boolean { if (this.isEmpty()) { return false } forEach { c -> if (Character.isWhitespace(c)) { return true } } return false } fun String.fileNameWithoutExtension(): String { if (isEmpty()) { return this } var filePath = this val extenPosi = filePath.lastIndexOf(Const.FILE_EXTENSION_SEPARATOR) val filePosi = filePath.lastIndexOf(File.separator) if (filePosi == -1) { return if (extenPosi == -1) filePath else filePath.substring(0, extenPosi) } if (extenPosi == -1) { return filePath.substring(filePosi + 1) } return if (filePosi < extenPosi) filePath.substring(filePosi + 1, extenPosi) else filePath.substring(filePosi + 1) } fun String.fileName(): String { if (isEmpty()) { return this } var filePath = this val filePosi = filePath.lastIndexOf(File.separator) return if (filePosi == -1) filePath else filePath.substring(filePosi + 1) } fun String.fileExtension(): String { if (isEmpty()) { return this } var filePath = this val extenPosi = filePath.lastIndexOf(Const.FILE_EXTENSION_SEPARATOR) val filePosi = filePath.lastIndexOf(File.separator) if (extenPosi == -1) { return "" } return if (filePosi >= extenPosi) "" else filePath.substring(extenPosi + 1) }
apache-2.0
FurhatRobotics/example-skills
JokeBot/src/main/kotlin/furhatos/app/jokebot/flow/main/jokeSequence.kt
1
3481
package furhatos.app.jokebot.flow.main import furhatos.app.jokebot.flow.Parent import furhatos.app.jokebot.jokes.* import furhatos.app.jokebot.nlu.BadJoke import furhatos.app.jokebot.nlu.GoodJoke import furhatos.app.jokebot.util.calculateJokeScore import furhatos.flow.kotlin.* import furhatos.nlu.common.No import furhatos.nlu.common.Yes import furhatos.skills.emotions.UserGestures /** * This state gets jokes, tells jokes, and records the user's response to it. * * Once the joke has been told, prompts the user if they want to hear another joke. */ val JokeSequence: State = state(Parent) { onEntry { //Get joke from the JokeHandler val joke = JokeHandler.getJoke() //Build an utterance with the joke. val utterance = utterance { +getJokeComment(joke.score) //Get comment on joke, using the score +delay(200) //Short delay +joke.intro //Deliver the intro of the joke +delay(1500) //Always let the intro sink in +joke.punchline //Deliver the punchline of the joke. } furhat.say(utterance) /** * Calls a state which we know returns a joke score. */ JokeHandler.changeJokeScore(call(JokeScore) as Double) //Prompt the user if they want to hear another joke. furhat.ask(continuePrompt.random()) } onResponse<Yes> { furhat.say("Sweet!") reentry() } onResponse<No> { furhat.say("Alright, thanks for letting me practice!") if (users.count > 1) { furhat.attend(users.other) furhat.ask("How about you? do you want some jokes?") } else { goto(Idle) } } onResponse { furhat.ask("Yes or no?") } onNoResponse { furhat.ask("I didn't hear you.") } } /** * This state records the users reaction to a joke, and terminates with calculated joke value. * Joke value is based on if the user smiled and/or the user said it was a good/bad joke. */ val JokeScore: State = state(Parent) { var saidBadJoke = false var saidGoodJoke = false var timeSmiledAtJoke = 0L var timestampStartedLaughing = 0L val jokeTimeout = 4000 // We wait for a reaction for 4 seconds onEntry { furhat.listen() } onResponse<GoodJoke>(instant = true) { saidGoodJoke = true } onResponse<BadJoke>(instant = true) { saidBadJoke = true } onResponse(instant = true) { //Do nothing } onNoResponse(instant = true) { //Do nothing } onUserGesture(UserGestures.Smile, cond = { it.isCurrentUser }, instant = true) { timestampStartedLaughing = System.currentTimeMillis() //Timestamp the moment the user started smiling. propagate() } onUserGestureEnd(UserGestures.Smile, cond = { it.isCurrentUser }, instant = true) { timeSmiledAtJoke += System.currentTimeMillis() - timestampStartedLaughing //Calculating the amount of millis spent laughing timestampStartedLaughing = 0L propagate() } onTime(delay = jokeTimeout) { if (timestampStartedLaughing != 0L) { timeSmiledAtJoke += System.currentTimeMillis() - timestampStartedLaughing } furhat.say(getResponseOnUser(timeSmiledAtJoke != 0L, saidBadJoke, saidGoodJoke)) terminate(calculateJokeScore(timeSmiledAtJoke, jokeTimeout, saidBadJoke, saidGoodJoke)) } }
mit
maskaravivek/apps-android-commons
app/src/main/java/fr/free/nrw/commons/customselector/ui/selector/CustomSelectorActivity.kt
3
7150
package fr.free.nrw.commons.customselector.ui.selector import android.app.Activity import android.app.Dialog import android.content.Intent import android.content.SharedPreferences import android.net.Uri import android.os.Bundle import android.view.View import android.view.Window import android.widget.Button import android.widget.ImageButton import android.widget.TextView import androidx.lifecycle.ViewModelProvider import fr.free.nrw.commons.R import fr.free.nrw.commons.customselector.listeners.FolderClickListener import fr.free.nrw.commons.customselector.listeners.ImageSelectListener import fr.free.nrw.commons.customselector.model.Image import fr.free.nrw.commons.media.ZoomableActivity import fr.free.nrw.commons.theme.BaseActivity import java.io.File import javax.inject.Inject /** * Custom Selector Activity. */ class CustomSelectorActivity: BaseActivity(), FolderClickListener, ImageSelectListener { /** * View model. */ private lateinit var viewModel: CustomSelectorViewModel /** * isImageFragmentOpen is true when the image fragment is in view. */ private var isImageFragmentOpen = false /** * Current ImageFragment attributes. */ private var bucketId: Long = 0L private lateinit var bucketName: String /** * Pref for saving selector state. */ private lateinit var prefs: SharedPreferences /** * View Model Factory. */ @Inject lateinit var customSelectorViewModelFactory: CustomSelectorViewModelFactory /** * onCreate Activity, sets theme, initialises the view model, setup view. */ override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_custom_selector) prefs = applicationContext.getSharedPreferences("CustomSelector", MODE_PRIVATE) viewModel = ViewModelProvider(this, customSelectorViewModelFactory).get( CustomSelectorViewModel::class.java ) setupViews() if(prefs.getBoolean("customSelectorFirstLaunch", true)) { // show welcome dialog on first launch showWelcomeDialog() prefs.edit().putBoolean("customSelectorFirstLaunch", false).apply() } // Open folder if saved in prefs. if(prefs.contains(FOLDER_ID)){ val lastOpenFolderId: Long = prefs.getLong(FOLDER_ID, 0L) val lastOpenFolderName: String? = prefs.getString(FOLDER_NAME, null) val lastItemId: Long = prefs.getLong(ITEM_ID, 0) lastOpenFolderName?.let { onFolderClick(lastOpenFolderId, it, lastItemId) } } } /** * Show Custom Selector Welcome Dialog. */ private fun showWelcomeDialog() { val dialog = Dialog(this) dialog.requestWindowFeature(Window.FEATURE_NO_TITLE) dialog.setContentView(R.layout.custom_selector_info_dialog) (dialog.findViewById(R.id.btn_ok) as Button).setOnClickListener { dialog.dismiss() } dialog.show() } /** * Set up view, default folder view. */ private fun setupViews() { supportFragmentManager.beginTransaction() .replace(R.id.fragment_container, FolderFragment.newInstance()) .commit() fetchData() setUpToolbar() } /** * Start data fetch in view model. */ private fun fetchData() { viewModel.fetchImages() } /** * Change the title of the toolbar. */ private fun changeTitle(title: String) { val titleText = findViewById<TextView>(R.id.title) if(titleText != null) { titleText.text = title } } /** * Set up the toolbar, back listener, done listener. */ private fun setUpToolbar() { val back : ImageButton = findViewById(R.id.back) back.setOnClickListener { onBackPressed() } val done : ImageButton = findViewById(R.id.done) done.setOnClickListener { onDone() } } /** * override on folder click, change the toolbar title on folder click. */ override fun onFolderClick(folderId: Long, folderName: String, lastItemId: Long) { supportFragmentManager.beginTransaction() .add(R.id.fragment_container, ImageFragment.newInstance(folderId, lastItemId)) .addToBackStack(null) .commit() changeTitle(folderName) bucketId = folderId bucketName = folderName isImageFragmentOpen = true } /** * override Selected Images Change, update view model selected images. */ override fun onSelectedImagesChanged(selectedImages: ArrayList<Image>) { viewModel.selectedImages.value = selectedImages val done : ImageButton = findViewById(R.id.done) done.visibility = if (selectedImages.isEmpty()) View.INVISIBLE else View.VISIBLE } /** * onLongPress * @param imageUri : uri of image */ override fun onLongPress(imageUri: Uri) { val intent = Intent(this, ZoomableActivity::class.java).setData(imageUri); startActivity(intent) } /** * OnDone clicked. * Get the selected images. Remove any non existent file, forward the data to finish selector. */ fun onDone() { val selectedImages = viewModel.selectedImages.value if(selectedImages.isNullOrEmpty()) { finishPickImages(arrayListOf()) return } var i = 0 while (i < selectedImages.size) { val path = selectedImages[i].path val file = File(path) if (!file.exists()) { selectedImages.removeAt(i) i-- } i++ } finishPickImages(selectedImages) } /** * finishPickImages, Load the data to the intent and set result. * Finish the activity. */ private fun finishPickImages(images: ArrayList<Image>) { val data = Intent() data.putParcelableArrayListExtra("Images", images) setResult(Activity.RESULT_OK, data) finish() } /** * Back pressed. * Change toolbar title. */ override fun onBackPressed() { super.onBackPressed() val fragment = supportFragmentManager.findFragmentById(R.id.fragment_container) if(fragment != null && fragment is FolderFragment){ isImageFragmentOpen = false changeTitle(getString(R.string.custom_selector_title)) } } /** * On activity destroy * If image fragment is open, overwrite its attributes otherwise discard the values. */ override fun onDestroy() { if(isImageFragmentOpen){ prefs.edit().putLong(FOLDER_ID, bucketId).putString(FOLDER_NAME, bucketName).apply() } else { prefs.edit().remove(FOLDER_ID).remove(FOLDER_NAME).apply() } super.onDestroy() } companion object { const val FOLDER_ID : String = "FolderId" const val FOLDER_NAME : String = "FolderName" const val ITEM_ID : String = "ItemId" } }
apache-2.0
DUCodeWars/TournamentFramework
src/main/java/org/DUCodeWars/framework/server/net/packets/notifications/packets/IdPacket.kt
2
1293
package org.DUCodeWars.framework.server.net.packets.notifications.packets import com.google.gson.JsonObject import org.DUCodeWars.framework.server.net.packets.JsonSerialiser import org.DUCodeWars.framework.server.net.packets.notifications.NotificationPacketSer import org.DUCodeWars.framework.server.net.packets.notifications.NotificationRequest private val action = "id" class IdPS : NotificationPacketSer<IdRequest>(action) { override val reqSer = IdReqSer() } class IdRequest(val id: Int) : NotificationRequest(action) { override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false if (!super.equals(other)) return false other as IdRequest if (id != other.id) return false return true } override fun hashCode(): Int { var result = super.hashCode() result = 31 * result + id return result } } class IdReqSer() : JsonSerialiser<IdRequest>() { override fun ser(packet: IdRequest): JsonObject { val json = JsonObject() json.addProperty("id", packet.id) return json } override fun deserialise(json: JsonObject): IdRequest { val id = json["id"].asInt return IdRequest(id) } }
mit
Bombe/Sone
src/main/kotlin/net/pterodactylus/sone/utils/DefaultOption.kt
1
631
package net.pterodactylus.sone.utils /** * Basic implementation of an [Option]. * * @param <T> The type of the option */ class DefaultOption<T> @JvmOverloads constructor( private val defaultValue: T, private val validator: ((T) -> Boolean)? = null ) : Option<T> { @Volatile private var value: T? = null override fun get() = value ?: defaultValue override fun getReal(): T? = value override fun validate(value: T?): Boolean = value == null || validator?.invoke(value) ?: true override fun set(value: T?) { require(validate(value)) { "New Value ($value) could not be validated." } this.value = value } }
gpl-3.0
Magneticraft-Team/Magneticraft
src/main/kotlin/com/cout970/magneticraft/systems/gui/AutoGui.kt
2
5218
package com.cout970.magneticraft.systems.gui import com.cout970.magneticraft.IVector2 import com.cout970.magneticraft.misc.gui.SlotType import com.cout970.magneticraft.misc.gui.TypedSlot import com.cout970.magneticraft.misc.guiTexture import com.cout970.magneticraft.misc.vector.vec2Of import com.cout970.magneticraft.systems.gui.render.DrawableBox import net.minecraft.client.Minecraft import net.minecraft.client.gui.ScaledResolution import net.minecraft.inventory.Slot class AutoGui(override val container: AutoContainer) : GuiBase(container) { lateinit var background: List<DrawableBox> lateinit var slots: List<DrawableBox> var oldGuiScale = 0 override fun initGui() { val config = container.builder.config this.xSize = config.background.xi this.ySize = config.background.yi super.initGui() this.slots = createSlots(container.inventorySlots) this.background = if (config.top) { createRectWithBorders(pos, size) } else { createRectWithBorders(pos + vec2Of(0, 76), size - vec2Of(0, 76)) } } override fun setWorldAndResolution(mc: Minecraft, width: Int, height: Int) { val size = container.builder.config.background oldGuiScale = mc.gameSettings.guiScale if (width < size.xi || height < size.yi) { mc.gameSettings.guiScale = 3 val sr = ScaledResolution(mc) super.setWorldAndResolution(mc, sr.scaledWidth, sr.scaledHeight) return } super.setWorldAndResolution(mc, width, height) } override fun onGuiClosed() { super.onGuiClosed() mc.gameSettings.guiScale = oldGuiScale } override fun initComponents() { container.builder.build(this, container) } override fun drawGuiContainerBackgroundLayer(partialTicks: Float, mouseX: Int, mouseY: Int) { bindTexture(guiTexture("misc")) background.forEach { it.draw() } super.drawGuiContainerBackgroundLayer(partialTicks, mouseX, mouseY) bindTexture(guiTexture("misc")) slots.forEach { it.draw() } } fun createRectWithBorders(pPos: IVector2, pSize: IVector2): List<DrawableBox> { val leftUp = DrawableBox( screenPos = pPos, screenSize = vec2Of(4), texturePos = vec2Of(0), textureSize = vec2Of(4) ) val leftDown = DrawableBox( screenPos = pPos + vec2Of(0, pSize.yi - 4), screenSize = vec2Of(4), texturePos = vec2Of(0, 5), textureSize = vec2Of(4) ) val rightUp = DrawableBox( screenPos = pPos + vec2Of(pSize.xi - 4, 0), screenSize = vec2Of(4), texturePos = vec2Of(5, 0), textureSize = vec2Of(4) ) val rightDown = DrawableBox( screenPos = pPos + vec2Of(pSize.xi - 4, pSize.yi - 4), screenSize = vec2Of(4), texturePos = vec2Of(5, 5), textureSize = vec2Of(4) ) val left = DrawableBox( screenPos = pPos + vec2Of(0, 4), screenSize = vec2Of(4, pSize.y - 8), texturePos = vec2Of(0, 10), textureSize = vec2Of(4, 1) ) val right = DrawableBox( screenPos = pPos + vec2Of(pSize.xi - 4, 4), screenSize = vec2Of(4, pSize.yi - 8), texturePos = vec2Of(5, 10), textureSize = vec2Of(4, 1) ) val up = DrawableBox( screenPos = pPos + vec2Of(4, 0), screenSize = vec2Of(pSize.xi - 8, 4), texturePos = vec2Of(10, 0), textureSize = vec2Of(1, 4) ) val down = DrawableBox( screenPos = pPos + vec2Of(4, pSize.yi - 4), screenSize = vec2Of(pSize.xi - 8, 4), texturePos = vec2Of(10, 5), textureSize = vec2Of(1, 4) ) val center = DrawableBox( screenPos = pPos + vec2Of(4, 4), screenSize = vec2Of(pSize.xi - 8, pSize.yi - 8), texturePos = vec2Of(5, 3), textureSize = vec2Of(1, 1) ) return listOf( leftUp, leftDown, rightUp, rightDown, left, right, up, down, center ) } fun createSlots(slots: List<Slot>): List<DrawableBox> { val boxes = mutableListOf<DrawableBox>() slots.forEach { slot -> val x = guiLeft + slot.xPos - 1 val y = guiTop + slot.yPos - 1 val type = (slot as? TypedSlot)?.type ?: SlotType.NORMAL val icon = when (type) { SlotType.INPUT -> vec2Of(55, 81) SlotType.OUTPUT -> vec2Of(36, 81) SlotType.FILTER -> vec2Of(74, 81) SlotType.NORMAL -> vec2Of(36, 100) SlotType.BUTTON -> vec2Of(74, 100) SlotType.FLOPPY -> vec2Of(144, 69) SlotType.BATTERY -> vec2Of(144, 87) } boxes += DrawableBox( screenPos = vec2Of(x, y), screenSize = vec2Of(18), texturePos = icon ) } return boxes } }
gpl-2.0
mozilla-mobile/focus-android
app/src/main/java/org/mozilla/focus/telemetry/startuptelemetry/StartupPathProvider.kt
1
4203
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package org.mozilla.focus.telemetry.startuptelemetry import android.app.Activity import android.content.Intent import androidx.annotation.VisibleForTesting import androidx.annotation.VisibleForTesting.Companion.NONE import androidx.annotation.VisibleForTesting.Companion.PRIVATE import androidx.lifecycle.DefaultLifecycleObserver import androidx.lifecycle.Lifecycle import androidx.lifecycle.LifecycleOwner /** * This should be a member variable of [Activity] because its data is tied to the lifecycle of an * Activity. Call [attachOnActivityOnCreate] & [onIntentReceived] for this class to work correctly. */ class StartupPathProvider { enum class StartupPath { MAIN, VIEW, /** * The start up path if we received an Intent but we're unable to categorize it into other buckets. */ UNKNOWN, /** * The start up path has not been set. This state includes: * - this API is accessed before it is set * - if no intent is received before the activity is STARTED (e.g. app switcher) */ NOT_SET, } /** * Returns the [StartupPath] for the currently started activity. This value will be set * after an [Intent] is received that causes this activity to move into the STARTED state. */ var startupPathForActivity = StartupPath.NOT_SET private set private var wasResumedSinceStartedState = false fun attachOnActivityOnCreate(lifecycle: Lifecycle, intent: Intent?) { lifecycle.addObserver(StartupPathLifecycleObserver()) onIntentReceived(intent) } // N.B.: this method duplicates the actual logic for determining what page to open. // Unfortunately, it's difficult to re-use that logic because it occurs in many places throughout // the code so we do the simple thing for now and duplicate it. It's noticeably different from // what you might expect: e.g. ACTION_MAIN can open a URL and if ACTION_VIEW provides an invalid // URL, it'll perform a MAIN action. However, it's fairly representative of what users *intended* // to do when opening the app and shouldn't change much because it's based on Android system-wide // conventions, so it's probably fine for our purposes. private fun getStartupPathFromIntent(intent: Intent): StartupPath = when (intent.action) { Intent.ACTION_MAIN -> StartupPath.MAIN Intent.ACTION_VIEW -> StartupPath.VIEW else -> StartupPath.UNKNOWN } /** * Expected to be called when a new [Intent] is received by the [Activity]: i.e. * [Activity.onCreate] and [Activity.onNewIntent]. */ fun onIntentReceived(intent: Intent?) { // We want to set a path only if the intent causes the Activity to move into the STARTED state. // This means we want to discard any intents that are received when the app is foregrounded. // However, we can't use the Lifecycle.currentState to determine this because: // - the app is briefly paused (state becomes STARTED) before receiving the Intent in // the foreground so we can't say <= STARTED // - onIntentReceived can be called from the CREATED or STARTED state so we can't say == CREATED // So we're forced to track this state ourselves. if (!wasResumedSinceStartedState && intent != null) { startupPathForActivity = getStartupPathFromIntent(intent) } } @VisibleForTesting(otherwise = NONE) fun getTestCallbacks() = StartupPathLifecycleObserver() @VisibleForTesting(otherwise = PRIVATE) inner class StartupPathLifecycleObserver : DefaultLifecycleObserver { override fun onResume(owner: LifecycleOwner) { wasResumedSinceStartedState = true } override fun onStop(owner: LifecycleOwner) { // Clear existing state. startupPathForActivity = StartupPath.NOT_SET wasResumedSinceStartedState = false } } }
mpl-2.0
wireapp/wire-android
app/src/test/kotlin/com/waz/zclient/core/network/accesstoken/AccessTokenRepositoryTest.kt
1
6454
package com.waz.zclient.core.network.accesstoken import com.waz.zclient.UnitTest import com.waz.zclient.any import com.waz.zclient.core.exception.ServerError import com.waz.zclient.core.functional.Either import com.waz.zclient.core.functional.map import com.waz.zclient.core.functional.onFailure import com.waz.zclient.core.network.api.token.AccessTokenResponse import com.waz.zclient.storage.db.accountdata.AccessTokenEntity import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.test.runBlockingTest import org.amshove.kluent.shouldBe import org.junit.Before import org.junit.Test import org.mockito.Mock import org.mockito.Mockito.`when` import org.mockito.Mockito.never import org.mockito.Mockito.verify import org.mockito.Mockito.verifyNoMoreInteractions @ExperimentalCoroutinesApi class AccessTokenRepositoryTest : UnitTest() { @Mock private lateinit var remoteDataSource: AccessTokenRemoteDataSource @Mock private lateinit var localDataSource: AccessTokenLocalDataSource @Mock private lateinit var accessTokenMapper: AccessTokenMapper @Mock private lateinit var refreshTokenMapper: RefreshTokenMapper private lateinit var accessTokenRepository: AccessTokenRepository @Before fun setUp() { accessTokenRepository = AccessTokenRepository(remoteDataSource, localDataSource, accessTokenMapper, refreshTokenMapper) } @Test fun `given localDataSource with accessTokenPref, when accessToken called, returns its accessToken mapping`() = runBlockingTest { `when`(localDataSource.accessToken()).thenReturn(ACCESS_TOKEN_LOCAL) `when`(accessTokenMapper.from(ACCESS_TOKEN_LOCAL)).thenReturn(ACCESS_TOKEN) val token = accessTokenRepository.accessToken() verify(localDataSource).accessToken() token shouldBe ACCESS_TOKEN } @Test fun `given localDataSource doesn't have an accessToken, when accessToken called, returns empty AccessToken`() = runBlockingTest { `when`(localDataSource.accessToken()).thenReturn(null) val token = accessTokenRepository.accessToken() verify(localDataSource).accessToken() token shouldBe AccessToken.EMPTY } @Test fun `when updateAccessToken is called, calls localDataSource with the mapping of given token`() = runBlockingTest { `when`(accessTokenMapper.toEntity(ACCESS_TOKEN)).thenReturn(ACCESS_TOKEN_LOCAL) accessTokenRepository.updateAccessToken(ACCESS_TOKEN) verify(accessTokenMapper).toEntity(ACCESS_TOKEN) verify(localDataSource).updateAccessToken(ACCESS_TOKEN_LOCAL) verifyNoMoreInteractions(remoteDataSource, localDataSource) } @Test fun `given localDataSource has a refreshToken, when refreshToken called, returns mapping of local refreshToken`() = runBlockingTest { `when`(localDataSource.refreshToken()).thenReturn(REFRESH_TOKEN_LOCAL) `when`(refreshTokenMapper.fromTokenText(REFRESH_TOKEN_LOCAL)).thenReturn(REFRESH_TOKEN) val token = accessTokenRepository.refreshToken() verify(localDataSource).refreshToken() token shouldBe REFRESH_TOKEN } @Test fun `given localDataSource doesn't have a refreshToken, when refreshToken called, returns empty RefreshToken`() = runBlockingTest { `when`(localDataSource.refreshToken()).thenReturn(null) val token = accessTokenRepository.refreshToken() verify(localDataSource).refreshToken() token shouldBe RefreshToken.EMPTY } @Test fun `when updateRefreshToken is called, calls localDataSource with mapping of given token`() = runBlockingTest { `when`(refreshTokenMapper.toEntity(REFRESH_TOKEN)).thenReturn(REFRESH_TOKEN_LOCAL) accessTokenRepository.updateRefreshToken(REFRESH_TOKEN) verify(localDataSource).updateRefreshToken(REFRESH_TOKEN_LOCAL) verifyNoMoreInteractions(remoteDataSource, localDataSource) } @Test fun `when renewAccessToken is called, calls remoteDataSource with given refresh token`() = runBlockingTest { `when`(accessTokenMapper.from(ACCESS_TOKEN_REMOTE)).thenReturn(ACCESS_TOKEN) `when`(remoteDataSource.renewAccessToken(REFRESH_TOKEN.token)).thenReturn(Either.Right(ACCESS_TOKEN_REMOTE)) accessTokenRepository.renewAccessToken(REFRESH_TOKEN) verify(remoteDataSource).renewAccessToken(REFRESH_TOKEN.token) verifyNoMoreInteractions(remoteDataSource, localDataSource) } @Test fun `given remote call's successful, when renewAccessToken's called, returns mapping of the accessTokenResponse`() = runBlockingTest { `when`(remoteDataSource.renewAccessToken(REFRESH_TOKEN.token)) .thenReturn(Either.Right(ACCESS_TOKEN_REMOTE)) `when`(accessTokenMapper.from(ACCESS_TOKEN_REMOTE)).thenReturn(ACCESS_TOKEN) val tokenResponse = accessTokenRepository.renewAccessToken(REFRESH_TOKEN) verify(accessTokenMapper).from(ACCESS_TOKEN_REMOTE) tokenResponse.isRight shouldBe true tokenResponse.map { it shouldBe ACCESS_TOKEN } } @Test fun `given remote call fails, when renewAccessToken is called, returns the error without any mapping`() = runBlockingTest { `when`(remoteDataSource.renewAccessToken(REFRESH_TOKEN.token)).thenReturn(Either.Left(ServerError)) val tokenResponse = accessTokenRepository.renewAccessToken(REFRESH_TOKEN) verify(accessTokenMapper, never()).from(any<AccessTokenResponse>()) tokenResponse.isLeft shouldBe true tokenResponse.onFailure { it shouldBe ServerError } verifyNoMoreInteractions(accessTokenMapper) } companion object { private val ACCESS_TOKEN = AccessToken("newToken", "newType", "newExpiry") private val ACCESS_TOKEN_LOCAL = AccessTokenEntity("token", "tokenType", 1000L) private val ACCESS_TOKEN_REMOTE = AccessTokenResponse("respToken", "respType", "respUser", "respExpiry") private val REFRESH_TOKEN = RefreshToken("refreshToken") private const val REFRESH_TOKEN_LOCAL = "refreshToken" } }
gpl-3.0
ice1000/Castle-game
src/funcs/using/FuncSleep.kt
1
1143
package funcs.using import castle.Game import funcs.FuncSrc class FuncSleep : FuncSrc { constructor(game: Game) : super(game) { } constructor() { } override fun DoFunc(cmd: String) { // int bloodMore = Integer.parseInt(cmd); if (game.map.currentRoom.toString().matches("宾馆|卧室".toRegex())) { if (!game.map.currentRoom.isBossGetItem) { game.echo("女仆顺从地送你进入梦乡。睡觉中") for (i in 0..7) { try { Thread.sleep(50) } catch (e: InterruptedException) { e.printStackTrace() } } game.echo("\n已经睡觉,体力") if (game.player.treat()) game.echoln("恢复至120.") else game.echoln("超过120不用恢复的~") } else game.echoln("睡觉需要女仆服侍,然而她看起来不大愿意啊。。。") } else game.echoln("只有宾馆或卧室能睡觉。") } }
lgpl-3.0
wireapp/wire-android
app/src/main/java/com/waz/zclient/markdown/spans/commonmark/StrongEmphasisSpan.kt
1
1180
/** * Wire * Copyright (C) 2018 Wire Swiss GmbH * * 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.waz.zclient.markdown.spans.commonmark import android.graphics.Typeface import android.text.style.StyleSpan import com.waz.zclient.markdown.spans.InlineSpan import org.commonmark.node.Node import org.commonmark.node.StrongEmphasis /** * The span corresponding to the markdown "StrongEmphasis" unit. */ class StrongEmphasisSpan : InlineSpan() { init { add(StyleSpan(Typeface.BOLD)) } override fun toNode(literal: String?): Node = StrongEmphasis("**") }
gpl-3.0
stephanenicolas/toothpick
toothpick-runtime/src/test/kotlin/toothpick/inject/lazy/KInjectionOfLazyProviderTest.kt
1
2926
/* * Copyright 2019 Stephane Nicolas * Copyright 2019 Daniel Molinero Reguera * * 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 toothpick.inject.lazy import org.hamcrest.CoreMatchers.isA import org.hamcrest.CoreMatchers.notNullValue import org.hamcrest.CoreMatchers.sameInstance import org.hamcrest.MatcherAssert.assertThat import org.junit.Test import toothpick.Lazy import toothpick.ScopeImpl import toothpick.Toothpick import toothpick.config.Module import toothpick.data.KBar import toothpick.data.KFooWithLazy import toothpick.data.KFooWithNamedLazy /* * Test injection of {@code Lazy}s. */ class KInjectionOfLazyProviderTest { @Test @Throws(Exception::class) fun testSimpleInjection() { // GIVEN val scope = ScopeImpl("") val fooWithLazy = KFooWithLazy() // WHEN Toothpick.inject(fooWithLazy, scope) // THEN assertThat(fooWithLazy.bar, notNullValue()) assertThat(fooWithLazy.bar, isA(Lazy::class.java)) val bar1 = fooWithLazy.bar.get() assertThat(bar1, isA(KBar::class.java)) val bar2 = fooWithLazy.bar.get() assertThat(bar2, isA(KBar::class.java)) assertThat(bar2, sameInstance(bar1)) } @Test @Throws(Exception::class) fun testNamedInjection() { // GIVEN val scope = ScopeImpl("") scope.installModules(object : Module() { init { bind(KBar::class.java).withName("foo").to(KBar::class.java) } }) val fooWithLazy = KFooWithNamedLazy() // WHEN Toothpick.inject(fooWithLazy, scope) // THEN assertThat(fooWithLazy.bar, notNullValue()) assertThat(fooWithLazy.bar, isA(Lazy::class.java)) val bar1 = fooWithLazy.bar.get() assertThat(bar1, isA(KBar::class.java)) val bar2 = fooWithLazy.bar.get() assertThat(bar2, isA(KBar::class.java)) assertThat(bar2, sameInstance(bar1)) } @Test(expected = IllegalStateException::class) @Throws(Exception::class) fun testLazyAfterClosingScope() { // GIVEN val scopeName = "" val fooWithLazy = KFooWithLazy() // WHEN Toothpick.inject(fooWithLazy, Toothpick.openScope(scopeName)) Toothpick.closeScope(scopeName) System.gc() // THEN fooWithLazy.bar.get() // should crash } }
apache-2.0
wireapp/wire-android
common-test/src/main/kotlin/com/waz/zclient/framework/data/users/UsersTestDataProvider.kt
1
2145
package com.waz.zclient.framework.data.users import com.waz.zclient.framework.data.TestDataProvider import java.util.UUID data class UsersTestData( val id: String, val domain: String, val teamId: String, val name: String, val email: String, val phone: String, val trackingId: String, val picture: String, val accentId: Int, val sKey: String, val connection: String, val connectionTimestamp: Long, val connectionMessage: String, val conversation: String, val conversationDomain: String, val relation: String, val timestamp: Long, val verified: String, val deleted: Boolean, val availability: Int, val handle: String, val providerId: String, val integrationId: String, val expiresAt: Long, val managedBy: String, val selfPermission: Int, val copyPermission: Int, val createdBy: String ) object UsersTestDataProvider : TestDataProvider<UsersTestData>() { override fun provideDummyTestData(): UsersTestData = UsersTestData( id = UUID.randomUUID().toString(), domain = "staging.zinfra.io", teamId = UUID.randomUUID().toString(), name = "name", email = "[email protected]", phone = "0123456789", trackingId = UUID.randomUUID().toString(), picture = UUID.randomUUID().toString(), accentId = 0, sKey = "key", connection = "0", connectionTimestamp = 0, connectionMessage = "connectionMessage", conversation = UUID.randomUUID().toString(), conversationDomain = "staging.zinfra.io", relation = "0", timestamp = System.currentTimeMillis(), verified = "", deleted = false, availability = 0, handle = "handle", providerId = UUID.randomUUID().toString(), integrationId = UUID.randomUUID().toString(), expiresAt = 0, managedBy = "", selfPermission = 0, copyPermission = 0, createdBy = "" ) }
gpl-3.0
wuan/bo-android2
app/src/main/java/org/blitzortung/android/v2/StateFragment.kt
1
2421
/* Blitzortung.org lightning monitor android app Copyright (C) 2012 - 2015 Andreas Würl 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 org.blitzortung.android.v2 import android.app.Fragment import android.os.Bundle import org.blitzortung.android.data.result.Result import org.slf4j.LoggerFactory import rx.schedulers.Schedulers import rx.subjects.BehaviorSubject class StateFragment : Fragment() { interface OnCreateListener { fun onStateCreated(stateFragment: StateFragment) } var resultSubject: BehaviorSubject<Result?>? = null private set private var onCreateListener: OnCreateListener? = null override fun onCreate(savedInstanceState: Bundle?) { LOGGER.info("StateFragment.onCreate()") super.onCreate(savedInstanceState) retainInstance = true resultSubject = BehaviorSubject.create<Result>() resultSubject!!.subscribeOn(Schedulers.newThread()).observeOn(Schedulers.newThread()) } override fun onPause() { LOGGER.info("StateFragment.onPause()") super.onPause() onCreateListener = null } override fun onResume() { LOGGER.info("StateFragment.onResume()") super.onResume() if (onCreateListener != null) { LOGGER.info("StateFragment.onResume() call onCreateListener") onCreateListener!!.onStateCreated(this) } } override fun onDestroy() { LOGGER.debug("StateFragment.onDestroy()") super.onDestroy() resultSubject = null } fun setOnCreateListener(onCreateListener: OnCreateListener) { this.onCreateListener = onCreateListener } companion object { val TAG = StateFragment::class.java.getSimpleName() private val LOGGER = LoggerFactory.getLogger(StateFragment::class.java) } }
gpl-3.0
anton-okolelov/intellij-rust
src/main/kotlin/org/rust/lang/core/types/ty/TyInfer.kt
2
964
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.lang.core.types.ty import org.rust.lang.core.types.infer.Node import org.rust.lang.core.types.infer.NodeOrValue import org.rust.lang.core.types.infer.VarValue sealed class TyInfer : Ty(HAS_TY_INFER_MASK) { // Note these classes must NOT be `data` classes and must provide equality by identity class TyVar( val origin: Ty? = null, override var parent: NodeOrValue = VarValue(null, 0) ) : TyInfer(), Node class IntVar(override var parent: NodeOrValue = VarValue(null, 0)) : TyInfer(), Node class FloatVar(override var parent: NodeOrValue = VarValue(null, 0)) : TyInfer(), Node } /** Used for caching only */ sealed class FreshTyInfer : Ty() { data class TyVar(val id: Int) : FreshTyInfer() data class IntVar(val id: Int) : FreshTyInfer() data class FloatVar(val id: Int) : FreshTyInfer() }
mit
npryce/result4k
src/main/kotlin/com/natpryce/nullables.kt
1
1057
package com.natpryce /* * Translate between the Result and Nullable/Optional/Maybe monads */ /** * Convert a nullable value to a Result, using the result of [failureDescription] as the failure reason * if the value is null. */ inline fun <T, E> T?.asResultOr(failureDescription: () -> E) = if (this != null) Success(this) else Failure(failureDescription()) /** * Convert a Success of a nullable value to a Success of a non-null value or a Failure, * using the result of [failureDescription] as the failure reason, if the value is null. */ inline fun <T: Any, E> Result<T?,E>.filterNotNull(failureDescription: () -> E) = flatMap { it.asResultOr(failureDescription) } /** * Returns the success value, or null if the Result is a failure. */ fun <T, E> Result<T, E>.valueOrNull() = when (this) { is Success<T> -> value is Failure<E> -> null } /** * Returns the failure reason, or null if the Result is a success. */ fun <T, E> Result<T, E>.failureOrNull() = when (this) { is Success<T> -> null is Failure<E> -> reason }
apache-2.0
diyaakanakry/Diyaa
functionPolmorphisiom.kt
1
251
fun show(name:String):Unit{ print("name:"+ name) } fun show(number:Int):Unit{ print("number:"+ number) } fun show(numberD:Double):Unit{ print("numberD:"+ numberD) } fun main(args:Array<String>){ show("hssein") show(100) }
unlicense