repo_name
stringlengths
7
79
path
stringlengths
8
206
copies
stringclasses
36 values
size
stringlengths
2
6
content
stringlengths
55
523k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
7.18
99.5
line_max
int64
16
979
alpha_frac
float64
0.3
0.87
ratio
float64
2.01
8.07
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
rei-m/android_hyakuninisshu
feature/examresult/src/main/java/me/rei_m/hyakuninisshu/feature/examresult/ui/ExamFinisherFragment.kt
1
2585
/* * Copyright (c) 2020. Rei Matsushita. * * 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 me.rei_m.hyakuninisshu.feature.examresult.ui import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.fragment.app.viewModels import androidx.navigation.fragment.findNavController import me.rei_m.hyakuninisshu.feature.corecomponent.helper.EventObserver import me.rei_m.hyakuninisshu.feature.examresult.databinding.ExamFinisherFragmentBinding import me.rei_m.hyakuninisshu.feature.examresult.di.ExamResultComponent import javax.inject.Inject class ExamFinisherFragment : Fragment() { @Inject lateinit var viewModelFactory: ExamFinisherViewModel.Factory private var _binding: ExamFinisherFragmentBinding? = null private val binding get() = _binding!! private val viewModel by viewModels<ExamFinisherViewModel> { viewModelFactory } override fun onCreate(savedInstanceState: Bundle?) { (requireActivity() as ExamResultComponent.Injector) .examResultComponent() .create() .inject(this) super.onCreate(savedInstanceState) } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { _binding = ExamFinisherFragmentBinding.inflate(inflater, container, false) binding.lifecycleOwner = viewLifecycleOwner return binding.root } override fun onDestroyView() { _binding = null super.onDestroyView() } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) binding.viewModel = viewModel viewModel.onFinishEvent.observe(viewLifecycleOwner, EventObserver { val action = ExamFinisherFragmentDirections.actionExamFinisherToExamResult( examId = it ) findNavController().navigate(action) }) } }
apache-2.0
d410b58bcfb1f1bf0ec833344bf10656
33.466667
88
0.725725
4.822761
false
false
false
false
GlimpseFramework/glimpse-framework
jogl/src/main/kotlin/glimpse/jogl/io/FileChoosers.kt
1
1164
package glimpse.jogl.io import java.io.File import javax.swing.JFileChooser import javax.swing.JFrame /** * Displays a Swing file chooser for opening a file. * @param fileFilter File filter. * @param onOpen Action to be run when the user chooses to open the file. * @param onCancel Action to be run when the user cancels. */ fun JFrame.openFile(fileFilter: PredicateFileFilter, onOpen: (File) -> Unit, onCancel: () -> Unit = {}) { val fileChooser = JFileChooser() fileChooser.addChoosableFileFilter(fileFilter) fileChooser.isAcceptAllFileFilterUsed = false when (fileChooser.showOpenDialog(this)) { JFileChooser.APPROVE_OPTION -> onOpen(fileChooser.selectedFile) else -> onCancel() } } /** * Displays a Swing file chooser for opening an OBJ file. * @param onOpen Action to be run when the user chooses to open the file. */ fun JFrame.openOBJFile(onOpen: (File) -> Unit): Unit = openFile(objFileFilter, onOpen) /** * Displays a Swing file chooser for opening an image file. * @param onOpen Action to be run when the user chooses to open the file. */ fun JFrame.openImageFile(onOpen: (File) -> Unit): Unit = openFile(imageFileFilter, onOpen)
apache-2.0
1015fe1a5296996f108d0a277982865f
34.272727
105
0.743127
3.854305
false
false
false
false
langara/USpek
uspekx-junit5/src/jvmMain/kotlin/USpekXJUnit5.kt
1
1271
package pl.mareklangiewicz.uspek import org.junit.jupiter.api.DynamicContainer import org.junit.jupiter.api.DynamicNode import org.junit.jupiter.api.DynamicTest import java.net.URI fun uspekTestFactory(code: () -> Unit): DynamicNode { uspek(code) return GlobalUSpekContext.root.dynamicNode() } fun suspekTestFactory(ucontext: USpekContext = USpekContext(), code: suspend () -> Unit): DynamicNode = suspekBlocking(ucontext, code).dynamicNode() private fun USpekTree.dynamicNode(): DynamicNode = if (branches.isEmpty()) dynamicTest() else DynamicContainer.dynamicContainer(name, branches.values.map { it.dynamicNode() } + dynamicTest()) private fun USpekTree.dynamicTest(): DynamicTest = DynamicTest.dynamicTest(name) { println(status) end?.cause?.let { throw it } } // TODO: use JUnit5 URIs: https://junit.org/junit5/docs/current/user-guide/#writing-tests-dynamic-tests-uri-test-source // to be able to click (or F4) on the test in the Intellij test tree and to be navigated to exact test line // TODO: check why this doesn't do the trick (or similar for dynamicContainer): // dynamicTest(name, location?.tsource) { end?.cause?.let { throw it } } private fun CodeLocation.testSource() = URI("classpath:/$fileName?line=$lineNumber")
apache-2.0
a741087a684c5a6901fcd4b76e273837
40
119
0.74823
3.67341
false
true
false
false
BrianLusina/MovieReel
app/src/main/kotlin/com/moviereel/ui/settings/SettingsActivity.kt
1
9605
package com.moviereel.ui.settings import android.annotation.TargetApi import android.content.Context import android.content.Intent import android.content.res.Configuration import android.media.Ringtone import android.media.RingtoneManager import android.net.Uri import android.os.Build import android.os.Bundle import android.preference.ListPreference import android.preference.Preference import android.preference.PreferenceActivity import android.preference.PreferenceFragment import android.preference.PreferenceManager import android.preference.RingtonePreference import android.support.v7.app.ActionBar import android.text.TextUtils import android.view.MenuItem import com.moviereel.R /** * A [PreferenceActivity] that presents a set of application settings. On * handset devices, settings are presented as a single list. On tablets, * settings are split by category, with category headers shown to the left of * the list of settings. * * * See [ * Android Design: Settings](http://developer.android.com/design/patterns/settings.html) for design guidelines and the [Settings * API Guide](http://developer.android.com/guide/topics/ui/settings.html) for more information on developing a Settings UI. */ class SettingsActivity : AppCompatPreferenceActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setupActionBar() } /** * Set up the [android.app.ActionBar], if the API is available. */ private fun setupActionBar() { val actionBar = supportActionBar actionBar?.setDisplayHomeAsUpEnabled(true) } /** * {@inheritDoc} */ override fun onIsMultiPane(): Boolean { return isXLargeTablet(this) } /** * {@inheritDoc} */ @TargetApi(Build.VERSION_CODES.HONEYCOMB) override fun onBuildHeaders(target: List<PreferenceActivity.Header>) { loadHeadersFromResource(R.xml.pref_headers, target) } /** * This method stops fragment injection in malicious applications. * Make sure to deny any unknown fragments here. */ override fun isValidFragment(fragmentName: String): Boolean { return PreferenceFragment::class.java.name == fragmentName || GeneralPreferenceFragment::class.java.name == fragmentName || DataSyncPreferenceFragment::class.java.name == fragmentName || NotificationPreferenceFragment::class.java.name == fragmentName } /** * This fragment shows general preferences only. It is used when the * activity is showing a two-pane settings UI. */ @TargetApi(Build.VERSION_CODES.HONEYCOMB) class GeneralPreferenceFragment : PreferenceFragment() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) addPreferencesFromResource(R.xml.pref_general) setHasOptionsMenu(true) // Bind the summaries of EditText/List/Dialog/Ringtone preferences // to their values. When their values change, their summaries are // updated to reflect the new value, per the Android Design // guidelines. bindPreferenceSummaryToValue(findPreference("example_text")) bindPreferenceSummaryToValue(findPreference("example_list")) } override fun onOptionsItemSelected(item: MenuItem): Boolean { val id = item.itemId if (id == android.R.id.home) { startActivity(Intent(activity, SettingsActivity::class.java)) return true } return super.onOptionsItemSelected(item) } } /** * This fragment shows notification preferences only. It is used when the * activity is showing a two-pane settings UI. */ @TargetApi(Build.VERSION_CODES.HONEYCOMB) class NotificationPreferenceFragment : PreferenceFragment() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) addPreferencesFromResource(R.xml.pref_notification) setHasOptionsMenu(true) // Bind the summaries of EditText/List/Dialog/Ringtone preferences // to their values. When their values change, their summaries are // updated to reflect the new value, per the Android Design // guidelines. bindPreferenceSummaryToValue(findPreference("notifications_new_message_ringtone")) } override fun onOptionsItemSelected(item: MenuItem): Boolean { val id = item.itemId if (id == android.R.id.home) { startActivity(Intent(activity, SettingsActivity::class.java)) return true } return super.onOptionsItemSelected(item) } } /** * This fragment shows data and sync preferences only. It is used when the * activity is showing a two-pane settings UI. */ @TargetApi(Build.VERSION_CODES.HONEYCOMB) class DataSyncPreferenceFragment : PreferenceFragment() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) addPreferencesFromResource(R.xml.pref_data_sync) setHasOptionsMenu(true) // Bind the summaries of EditText/List/Dialog/Ringtone preferences // to their values. When their values change, their summaries are // updated to reflect the new value, per the Android Design // guidelines. bindPreferenceSummaryToValue(findPreference("sync_frequency")) } override fun onOptionsItemSelected(item: MenuItem): Boolean { val id = item.itemId if (id == android.R.id.home) { startActivity(Intent(activity, SettingsActivity::class.java)) return true } return super.onOptionsItemSelected(item) } } companion object { /** * A preference value change listener that updates the preference's summary * to reflect its new value. */ private val sBindPreferenceSummaryToValueListener = Preference.OnPreferenceChangeListener { preference, value -> val stringValue = value.toString() if (preference is ListPreference) { // For list preferences, look up the correct display value in // the preference's 'entries' list. val listPreference = preference val index = listPreference.findIndexOfValue(stringValue) // Set the summary to reflect the new value. preference.setSummary( if (index >= 0) listPreference.entries[index] else null) } else if (preference is RingtonePreference) { // For ringtone preferences, look up the correct display value // using RingtoneManager. if (TextUtils.isEmpty(stringValue)) { // Empty values correspond to 'silent' (no ringtone). preference.setSummary(R.string.pref_ringtone_silent) } else { val ringtone = RingtoneManager.getRingtone( preference.getContext(), Uri.parse(stringValue)) if (ringtone == null) { // Clear the summary if there was a lookup error. preference.setSummary(null) } else { // Set the summary to reflect the new ringtone display // name. val name = ringtone.getTitle(preference.getContext()) preference.setSummary(name) } } } else { // For all other preferences, set the summary to the value's // simple string representation. preference.summary = stringValue } true } /** * Helper method to determine if the device has an extra-large screen. For * example, 10" tablets are extra-large. */ private fun isXLargeTablet(context: Context): Boolean { return context.resources.configuration.screenLayout and Configuration.SCREENLAYOUT_SIZE_MASK >= Configuration.SCREENLAYOUT_SIZE_XLARGE } /** * Binds a preference's summary to its value. More specifically, when the * preference's value is changed, its summary (line of text below the * preference title) is updated to reflect the value. The summary is also * immediately updated upon calling this method. The exact display format is * dependent on the type of preference. * @see .sBindPreferenceSummaryToValueListener */ private fun bindPreferenceSummaryToValue(preference: Preference) { // Set the listener to watch for value changes. preference.onPreferenceChangeListener = sBindPreferenceSummaryToValueListener // Trigger the listener immediately with the preference's // current value. sBindPreferenceSummaryToValueListener.onPreferenceChange(preference, PreferenceManager .getDefaultSharedPreferences(preference.context) .getString(preference.key, "")) } } }
mit
60a6388e8f841e4b80f6bc731a87afe5
38.526749
146
0.63113
5.646678
false
false
false
false
tokenbrowser/token-android-client
app/src/main/java/com/toshi/view/activity/SendETHActivity.kt
1
13126
/* * Copyright (c) 2017. Toshi Inc * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.toshi.view.activity import android.app.Activity import android.arch.lifecycle.Observer import android.arch.lifecycle.ViewModelProviders import android.content.ClipboardManager import android.content.Context import android.content.Intent import android.os.Bundle import android.support.v7.app.AppCompatActivity import com.toshi.R import com.toshi.crypto.util.isPaymentAddressValid import com.toshi.extensions.isVisible import com.toshi.extensions.startActivityForResult import com.toshi.extensions.toast import com.toshi.model.network.Balance import com.toshi.model.network.token.EtherToken import com.toshi.util.DialogUtil import com.toshi.util.PaymentType import com.toshi.util.QrCodeHandler import com.toshi.util.ScannerResultType import com.toshi.view.adapter.listeners.TextChangedListener import com.toshi.view.fragment.PaymentConfirmationFragment import com.toshi.viewModel.SendEtherViewModel import kotlinx.android.synthetic.main.activity_send_erc20_token.addressError import kotlinx.android.synthetic.main.activity_send_erc20_token.amountError import kotlinx.android.synthetic.main.activity_send_erc20_token.balance import kotlinx.android.synthetic.main.activity_send_erc20_token.closeButton import kotlinx.android.synthetic.main.activity_send_erc20_token.continueBtn import kotlinx.android.synthetic.main.activity_send_erc20_token.currencySwitcher import kotlinx.android.synthetic.main.activity_send_erc20_token.max import kotlinx.android.synthetic.main.activity_send_erc20_token.networkStatusView import kotlinx.android.synthetic.main.activity_send_erc20_token.paste import kotlinx.android.synthetic.main.activity_send_erc20_token.qrCodeBtn import kotlinx.android.synthetic.main.activity_send_erc20_token.toAddress import kotlinx.android.synthetic.main.activity_send_erc20_token.toAmount import kotlinx.android.synthetic.main.activity_send_erc20_token.toAmountConverted import kotlinx.android.synthetic.main.activity_send_erc20_token.toolbarTitle class SendETHActivity : AppCompatActivity() { companion object { private const val PAYMENT_SCAN_REQUEST_CODE = 200 } private lateinit var viewModel: SendEtherViewModel override fun onCreate(inState: Bundle?) { super.onCreate(inState) setContentView(R.layout.activity_send_erc20_token) init() } private fun init() { initViewModel() initNetworkView() initClickListeners() updateUi() initObservers() initTextListeners() } private fun initViewModel() { viewModel = ViewModelProviders.of(this).get(SendEtherViewModel::class.java) } private fun initNetworkView() { networkStatusView.setNetworkVisibility(viewModel.getNetworks()) } private fun initClickListeners() { max.setOnClickListener { setMaxAmount() } currencySwitcher.setOnClickListener { viewModel.switchCurrencyMode({ switchFromFiatToEthValue() }, { switchFromEthToFiatValue() }) } closeButton.setOnClickListener { finish() } qrCodeBtn.setOnClickListener { startScanQrActivity() } paste.setOnClickListener { pasteToAddress() } continueBtn.setOnClickListener { validateAddressAndShowPaymentConfirmation() } } private fun setMaxAmount() { if (viewModel.isSendingMaxAmount.value == true) { viewModel.isSendingMaxAmount.value = false toAmount.setText("") toAmount.requestFocus() return } showMaxAmountPaymentConfirmation() } private fun showMaxAmountPaymentConfirmation() { DialogUtil.getBaseDialog( this, R.string.send_max_amount_title, R.string.send_max_amount_message, R.string.ok, R.string.cancel, { _, _ -> handleMaxAmountAccepted() }, { _, _ -> handleMaxAmountCanceled() } ).show() } private fun handleMaxAmountAccepted() { viewModel.isSendingMaxAmount.value = true val maxAmount = viewModel.getMaxAmount() toAmount.setText(maxAmount) } private fun handleMaxAmountCanceled() { viewModel.isSendingMaxAmount.value = false } private fun switchFromFiatToEthValue() { val inputValue = toAmount.text.toString() val ethAmount = when { viewModel.isSendingMaxAmount.value == true -> viewModel.getMaxAmount() inputValue.isNotEmpty() -> viewModel.fiatToEth(inputValue) else -> "" } toAmount.setText(ethAmount) toAmount.setSuffix(getString(R.string.eth_currency_code)) toAmount.setPrefix("") toAmount.setSelection(toAmount.text.length) } private fun switchFromEthToFiatValue() { val inputValue = toAmount.text.toString() val fiatAmount = when { viewModel.isSendingMaxAmount.value == true -> viewModel.getMaxAmount() inputValue.isNotEmpty() -> viewModel.ethToFiat(inputValue) else -> "" } toAmount.setText(fiatAmount) toAmount.setSuffix(viewModel.getFiatCurrencyCode()) toAmount.setPrefix(viewModel.getFiatCurrencySymbol()) toAmount.setSelection(toAmount.text.length) } private fun startScanQrActivity() = startActivityForResult<ScannerActivity>(PAYMENT_SCAN_REQUEST_CODE) { putExtra(ScannerActivity.SCANNER_RESULT_TYPE, ScannerResultType.PAYMENT_ADDRESS) } private fun pasteToAddress() { val clipboard = getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager val clipData = clipboard.primaryClip if (clipData == null || clipData.itemCount == 0) return val clipItem = clipData.getItemAt(0) if (clipItem == null || clipItem.text == null) return val textFromClipboard = clipItem.text.toString() toAddress.setText(textFromClipboard) } private fun validateAddressAndShowPaymentConfirmation() { addressError.isVisible(false) val address = toAddress.text.toString() val amount = toAmount.text.toString() val encodedEthAmount = viewModel.getEncodedEthAmount(amount) showPaymentConfirmation(encodedEthAmount, address) } private fun showPaymentConfirmation(value: String, toAddress: String) { val dialog = PaymentConfirmationFragment.newInstanceExternalPayment( paymentAddress = toAddress, value = value, paymentType = PaymentType.TYPE_SEND, currencyMode = viewModel.currencyMode, sendMaxAmount = viewModel.isSendingMaxAmount.value == true ) dialog.show(supportFragmentManager, PaymentConfirmationFragment.TAG) dialog.setOnPaymentConfirmationFinishedListener { finish() } } private fun updateUi() { renderToolbar() setAmountSuffix() showCurrencySwitcher() showConvertedAmount() } private fun showCurrencySwitcher() = currencySwitcher.isVisible(true) private fun showConvertedAmount() { toAmountConverted.isVisible(true) if (toAmountConverted.text.isEmpty()) updateConvertedAmount("0.0") } private fun setAmountSuffix() { val suffix = viewModel.getCurrencyCode() toAmount.setSuffix(suffix) } private fun renderToolbar() { val token = EtherToken.getTokenFromIntent(intent) if (token == null) { toast(R.string.invalid_token) finish() return } toolbarTitle.text = getString(R.string.send_token, token.symbol) } private fun initObservers() { viewModel.ethBalance.observe(this, Observer { if (it != null) renderEthBalance(it) }) viewModel.isSendingMaxAmount.observe(this, Observer { if (it != null) updateMaxButtonState(it) }) } private fun renderEthBalance(currentBalance: Balance) { val totalEthAmount = viewModel.getTotalEthAmount(currentBalance) val ethAmountString = getString(R.string.eth_amount, totalEthAmount) val statusMessage = getString(R.string.your_balance_eth_fiat, ethAmountString, currentBalance.localBalance) balance.text = statusMessage } private fun updateMaxButtonState(isSendingMaxAmount: Boolean) { if (isSendingMaxAmount) enableMaxAmountButtonAndDisableAmountInput() else disableMaxAmountButtonAndEnableAmountInput() } private fun enableMaxAmountButtonAndDisableAmountInput() { max.setBackgroundResource(R.drawable.background_with_round_corners_enabled) max.setTextColor(R.color.textColorContrast) toAmount.updateTextColor(R.color.textColorHint) toAmount.isFocusable = false toAmount.isFocusableInTouchMode = false } private fun disableMaxAmountButtonAndEnableAmountInput() { max.setBackgroundResource(R.drawable.background_with_round_corners_disabled) max.setTextColor(R.color.textColorPrimary) toAmount.updateTextColor(R.color.textColorPrimary) toAmount.isFocusable = true toAmount.isFocusableInTouchMode = true } private fun initTextListeners() { toAmount.addTextChangedListener(object : TextChangedListener() { override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) { updateConvertedAmount(s.toString()) validateAmount(s.toString()) enableOrDisableContinueButton() } }) toAddress.addTextChangedListener(object : TextChangedListener() { override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) { validateAddress(s.toString()) enableOrDisableContinueButton() } }) } private fun updateConvertedAmount(amountInput: String) { val convertedValue = viewModel.getConvertedValue(amountInput) toAmountConverted.text = convertedValue } private fun validateAmount(amountInput: String) { amountError.isVisible(false) if (amountInput.isEmpty()) return val hasEnoughBalance = viewModel.hasEnoughBalance(amountInput) val isValidAmount = viewModel.isAmountValid(amountInput) if (!isValidAmount) showInvalidAmountError() if (!hasEnoughBalance) showAmountError() } private fun validateAddress(addressInput: String) { addressError.isVisible(false) if (addressInput.isEmpty()) return val isAddressValid = isPaymentAddressValid(addressInput) if (!isAddressValid) showAddressError() } private fun enableOrDisableContinueButton() { val amount = toAmount.text.toString() val address = toAddress.text.toString() val isAmountValid = viewModel.isAmountValid(amount) && viewModel.hasEnoughBalance(amount) val isAddressValid = isPaymentAddressValid(address) if (isAmountValid && isAddressValid) enableContinueButton() else disableContinueButton() } private fun showAmountError() { val ethBalance = getString(R.string.eth_balance, viewModel.getEtherBalance()) amountError.isVisible(true) amountError.text = getString(R.string.insufficient_balance, ethBalance) } private fun showInvalidAmountError() { amountError.isVisible(true) amountError.text = getString(R.string.invalid_format) } private fun showAddressError() { addressError.isVisible(true) addressError.text = getString(R.string.invalid_payment_address) } private fun enableContinueButton() { continueBtn.isEnabled = true continueBtn.setBackgroundResource(R.drawable.background_with_radius_primary_color) } private fun disableContinueButton() { continueBtn.isEnabled = false continueBtn.setBackgroundResource(R.drawable.background_with_radius_disabled) } override fun onActivityResult(requestCode: Int, resultCode: Int, resultIntent: Intent?) { super.onActivityResult(requestCode, resultCode, resultIntent) if (requestCode != PAYMENT_SCAN_REQUEST_CODE || resultCode != Activity.RESULT_OK || resultIntent == null) return val paymentAddress = resultIntent.getStringExtra(QrCodeHandler.ACTIVITY_RESULT) toAddress.setText(paymentAddress) } }
gpl-3.0
56067581b6a5f3ef1b546d11e9b6b0bc
38.539157
140
0.701356
4.59433
false
false
false
false
BasinMC/Basin
faucet/src/main/kotlin/org/basinmc/faucet/util/VersionRange.kt
1
5898
/* * Copyright 2019 Johannes Donath <johannesd@torchmind.com> * and other copyright owners as documented in the project's IP log. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.basinmc.faucet.util import java.util.* /** * * Represents a range which may match one or multiple versions. * * * Each range may consist of one or two versions in the format of `&lt;version&gt;[,&lt;version&gt;]` as well as a prefix and/or suffix which expresses whether a * given version is included or excluded from the range. Where: * * * * `[` and `]` indicate that the start or end of the range is to be included * * `(` and `)` indicate that the start or end of the range is to be excluded * * * * As such: * * * * `1.0.0` includes 1.0.0 * * `[1.0.0` includes all versions newer than or equal to 1.0.0 * * `(1.0.0` includes all versions newer than 1.0.0 * * `1.0.0]` includes all versions older than or equal to 1.0.0 * * `1.0.0)` includes all versions older than 1.0.0 * * `[1.0.0,2.0.0)` includes all versions newer than or equal to 1.0.0 up to (excluding) * 2.0.0 * * * * Note that none or only one prefix may be present when only a single version is specified * (e.g. `1.0.0`, `(1.0.0` and `1.0.0)` are valid while `(1.0.0]` is * considered invalid). When two versions are given, both prefixes must be present at the same time * to specify the bounds. * * @author [Johannes Donath](mailto:johannesd@torchmind.com) * @since 1.0 */ class VersionRange(range: String) { private val start: Version? private val startInclusive: Boolean private val end: Version? private val endInclusive: Boolean companion object { private val prefixCharacters = "([" private val suffixCharacters = "])" } init { var startString = range var endString = range val i = range.indexOf(',') if (i != -1) { startString = range.substring(0, i) endString = range.substring(i + 1) } val prefix = startString[0] val suffix = endString[endString.length - 1] val validPrefix = prefixCharacters.indexOf(prefix) != -1 val validSuffix = suffixCharacters.indexOf(suffix) != -1 if (validPrefix) { startString = startString.substring(1) } if (validSuffix) { endString = endString.substring(0, endString.length - 1) } if (i == -1) { if (validSuffix) { startString = startString.substring(0, startString.length - 1) } if (validPrefix) { endString = endString.substring(1) } } var start: Version? var end: Version? try { start = Version(startString) } catch (ex: IllegalArgumentException) { throw IllegalArgumentException("Illegal range start: $startString", ex) } if (i != -1) { try { end = Version(endString) } catch (ex: IllegalArgumentException) { throw IllegalArgumentException("Illegal range end: $endString", ex) } } else { end = start } if (i == -1) { if (validPrefix && validSuffix) { throw IllegalArgumentException( "Illegal range: \"$range\" specifies upper and lower bound with single version") } if (validPrefix) { end = null } else if (validSuffix) { start = null } } else if (!validPrefix || !validSuffix) { throw IllegalArgumentException( "Illegal range: \"$range\" must specify upper and lower bound") } this.start = start this.end = end this.startInclusive = i == -1 && !validPrefix && !validSuffix || validPrefix && prefix == '[' this.endInclusive = i == -1 && !validPrefix && !validSuffix || validSuffix && suffix == ']' } /** * Evaluates whether a given version is part of this version range. * * @param version a version range. * @return true if within range, false otherwise. */ operator fun contains(version: Version): Boolean { if (this.start != null && (this.start > version || !this.startInclusive && this.start == version)) { return false } return !(this.end != null && (this.end < version || !this.endInclusive && this.end == version)) } override fun toString(): String { if (this.start === this.end) { return this.start!!.toString() } val builder = StringBuilder() if (this.start != null) { if (this.startInclusive) { builder.append('[') } else if (this.end != null) { builder.append('(') } builder.append(this.start) } if (this.end != null) { if (this.start != null) { builder.append(',') } builder.append(this.end) if (this.endInclusive) { builder.append(']') } else if (this.start != null) { builder.append(')') } } return builder.toString() } /** * {@inheritDoc} */ override fun equals(other: Any?): Boolean { if (this === other) { return true } if (other !is VersionRange) { return false } val that = other as VersionRange? return this.startInclusive == that!!.startInclusive && this.endInclusive == that.endInclusive && this.start == that.start && this.end == that.end } /** * {@inheritDoc} */ override fun hashCode(): Int { return Objects.hash(this.start, this.startInclusive, this.end, this.endInclusive) } }
apache-2.0
735adddec1be982b9b4bb4f2aab005b1
27.085714
161
0.620549
3.792926
false
false
false
false
WijayaPrinting/wp-javafx
openpss-client-javafx/src/com/hendraanggrian/openpss/ui/price/EditPlatePriceDialog.kt
1
1543
package com.hendraanggrian.openpss.ui.price import com.hendraanggrian.openpss.FxComponent import com.hendraanggrian.openpss.R2 import com.hendraanggrian.openpss.api.OpenPSSApi import com.hendraanggrian.openpss.schema.PlatePrice import javafx.beans.property.ReadOnlyDoubleWrapper import javafx.beans.value.ObservableValue import kotlinx.coroutines.CoroutineScope import ktfx.cells.textFieldCellFactory import ktfx.coroutines.onEditCommit import ktfx.text.buildStringConverter @Suppress("UNCHECKED_CAST") class EditPlatePriceDialog( component: FxComponent ) : EditPriceDialog<PlatePrice>(component, R2.string.plate_price) { init { getString(R2.string.price)<Double> { minWidth = 128.0 style = "-fx-alignment: center-right;" setCellValueFactory { ReadOnlyDoubleWrapper(it.value.price) as ObservableValue<Double> } textFieldCellFactory(buildStringConverter { fromString { it.toDoubleOrNull() ?: 0.0 } }) onEditCommit { cell -> val plate = cell.rowValue OpenPSSApi.editPlatePrice(plate.apply { price = cell.newValue }) } } } override suspend fun CoroutineScope.refresh(): List<PlatePrice> = OpenPSSApi.getPlatePrices() override suspend fun CoroutineScope.add(name: String): PlatePrice? = OpenPSSApi.addPlatePrice(PlatePrice.new(name)) override suspend fun CoroutineScope.delete(selected: PlatePrice): Boolean = OpenPSSApi.deletePlatePrice(selected.id) }
apache-2.0
a70867fc15b1f177bf10511198be7bd3
36.634146
100
0.720026
4.33427
false
false
false
false
googleapis/gapic-generator-kotlin
generator/src/main/kotlin/com/google/api/kotlin/generator/grpc/Functions.kt
1
20506
/* * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.api.kotlin.generator.grpc import com.google.api.kotlin.GeneratorContext import com.google.api.kotlin.TestableFunSpec import com.google.api.kotlin.asTestable import com.google.api.kotlin.config.FlattenedMethod import com.google.api.kotlin.config.MethodOptions import com.google.api.kotlin.indent import com.google.api.kotlin.types.GrpcTypes import com.google.api.kotlin.types.ProtoTypes import com.google.api.kotlin.types.isNotProtobufEmpty import com.google.api.kotlin.types.isProtobufEmpty import com.google.api.kotlin.util.FieldNamer import com.google.api.kotlin.util.Flattening import com.google.api.kotlin.util.ParameterInfo import com.google.api.kotlin.util.ResponseTypes.getLongRunningResponseType import com.google.api.kotlin.util.ResponseTypes.getResponseListElementType import com.google.api.kotlin.util.isLongRunningOperation import com.google.api.kgax.Page import com.google.protobuf.DescriptorProtos import com.squareup.kotlinpoet.CodeBlock import com.squareup.kotlinpoet.FunSpec import com.squareup.kotlinpoet.KModifier import com.squareup.kotlinpoet.LambdaTypeName import com.squareup.kotlinpoet.ParameterSpec import com.squareup.kotlinpoet.ParameterizedTypeName.Companion.parameterizedBy import com.squareup.kotlinpoet.UNIT import com.squareup.kotlinpoet.asClassName import com.squareup.kotlinpoet.asTypeName import kotlinx.coroutines.channels.ReceiveChannel import mu.KotlinLogging import java.util.concurrent.TimeUnit private val log = KotlinLogging.logger {} /** Generate the API method functions for the client. */ internal interface Functions { fun generate(context: GeneratorContext): List<TestableFunSpec> companion object { const val FUN_PREPARE = "prepare" const val PARAM_REQUEST = "request" } } internal class FunctionsImpl( private val documentation: Documentation, private val unitTest: UnitTest ) : Functions { override fun generate(context: GeneratorContext): List<TestableFunSpec> { // we'll use this in the example text val firstMethodName = context.service.methodList .firstOrNull()?.name?.decapitalize() // extra methods (not part of the target API) val extras = listOf( FunSpec.builder(Functions.FUN_PREPARE) .addKdoc( """ |Prepare for an API call by setting any desired options. For example: | |``` |%L |val response = client.prepare { | withMetadata("my-custom-header", listOf("some", "thing")) |}.%N(request) |``` | |You may save the client returned by this call and reuse it if you |plan to make multiple requests with the same settings. |""".trimMargin(), documentation.getClientInitializer(context), firstMethodName ?: "method" ) .returns(context.className) .addParameter( ParameterSpec.builder( "init", LambdaTypeName.get( GrpcTypes.Support.ClientCallOptionsBuilder, listOf(), Unit::class.asTypeName() ) ).build() ) .addStatement( "val optionsBuilder = %T(%N)", GrpcTypes.Support.ClientCallOptionsBuilder, Properties.PROP_CALL_OPTS ) .addStatement("optionsBuilder.init()") .addStatement( "return %T(%N, optionsBuilder.build())", context.className, Properties.PROP_CHANNEL ) .build() .asTestable(), FunSpec.builder("shutdownChannel") .addKdoc("Shutdown the [channel] associated with this client.\n") .addParameter( ParameterSpec.builder("waitForSeconds", Long::class.java.asTypeName()) .defaultValue("5") .build() ) .addStatement( "%L.shutdown().awaitTermination(waitForSeconds, %T.SECONDS)", Properties.PROP_CHANNEL, TimeUnit::class.java.asTypeName() ) .build() .asTestable() ) // API methods val apiMethods = context.service.methodList.flatMap { method -> log.debug { "processing proto method: ${method.name}" } val options = context.metadata[context.service].methods .firstOrNull { it.name == method.name } ?: MethodOptions(method.name) when { method.hasClientStreaming() || method.hasServerStreaming() -> createStreamingMethods(context, method, options) else -> createUnaryMethods(context, method, options) } } return extras + apiMethods } private fun createUnaryMethods( context: GeneratorContext, method: DescriptorProtos.MethodDescriptorProto, options: MethodOptions ): List<TestableFunSpec> { val methods = mutableListOf<TestableFunSpec>() // add flattened methods methods.addAll(options.flattenedMethods.map { flattenedMethod -> val (parameters, request) = Flattening.getFlattenedParameters( context, method, flattenedMethod ) createUnaryMethod( context = context, method = method, methodOptions = options, parameters = parameters, requestObject = request, flattenedMethod = flattenedMethod ) }) // add normal method if (options.keepOriginalMethod) { val inputType = context.typeMap.getKotlinType(method.inputType) val parameters = if (inputType.isNotProtobufEmpty()) { listOf( ParameterInfo( ParameterSpec.builder(Functions.PARAM_REQUEST, inputType).build() ) ) } else { listOf() } methods.add( createUnaryMethod( context = context, method = method, methodOptions = options, parameters = parameters, requestObject = if (parameters.isNotEmpty()) { CodeBlock.of(Functions.PARAM_REQUEST) } else { CodeBlock.of("%T.getDefaultInstance()", ProtoTypes.EMPTY) } ) ) } return methods.toList() } private fun createUnaryMethod( context: GeneratorContext, method: DescriptorProtos.MethodDescriptorProto, methodOptions: MethodOptions, parameters: List<ParameterInfo>, requestObject: CodeBlock, flattenedMethod: FlattenedMethod? = null ): TestableFunSpec { val name = methodOptions.name.decapitalize() // init function val m = FunSpec.builder(name) .addParameters(parameters.map { it.spec }) .addModifiers(KModifier.SUSPEND) // add request object to documentation val extraParamDocs = mutableListOf<CodeBlock>() if (flattenedMethod == null) { extraParamDocs.add( CodeBlock.of( "@param %L the request object for the API call", Functions.PARAM_REQUEST ) ) } // build method body when { method.isLongRunningOperation(context.proto) -> { val realResponseType = getLongRunningResponseType(context, method, methodOptions.longRunningResponse) val returnType = GrpcTypes.Support.LongRunningCall(realResponseType) m.returns(returnType) m.addCode( """ |return coroutineScope·{ | %T( | %N.%N, | async·{ | %N.%N.execute(context·=·%S)·{ | it.%L( | %L | ) | } | }, | %T::class.java | ) |} |""".trimMargin(), returnType, Properties.PROP_STUBS, Stubs.PROP_STUBS_OPERATION, Properties.PROP_STUBS, Stubs.PROP_STUBS_API, name, name, requestObject.indent(3), realResponseType ) } methodOptions.pagedResponse != null -> { val outputType = context.typeMap.getKotlinType(method.outputType) val responseListItemType = getResponseListElementType(context, method, methodOptions.pagedResponse) val pageType = Page::class.asClassName().parameterizedBy(responseListItemType) // getters and setters for setting the page sizes, etc. val pageTokenSetter = FieldNamer.getJavaBuilderRawSetterName(methodOptions.pagedResponse.requestPageToken) val nextPageTokenGetter = FieldNamer.getFieldName(methodOptions.pagedResponse.responsePageToken) val responseListGetter = FieldNamer.getJavaBuilderAccessorRepeatedName(methodOptions.pagedResponse.responseList) // build method body using a pager m.returns(ReceiveChannel::class.asClassName().parameterizedBy(pageType)) m.addCode( """ |return pager( | method·=·{·request·-> | %N.%N.execute(context·=·%S)·{ | it.%L(request) | } | }, | initialRequest·=·{ | %L | }, | nextRequest·=·{·request,·token·-> | request.toBuilder().%L(token).build() | }, | nextPage·=·{·response:·%T·-> | %T( | response.%L, | response.%L | ) | } |) |""".trimMargin(), Properties.PROP_STUBS, Stubs.PROP_STUBS_API, name, name, requestObject.indent(2), pageTokenSetter, outputType, pageType, responseListGetter, nextPageTokenGetter ) } else -> { val originalReturnType = context.typeMap.getKotlinType(method.outputType) val returnsNothing = originalReturnType.isProtobufEmpty() m.returns(if (returnsNothing) UNIT else originalReturnType) if (flattenedMethod?.parameters?.size ?: 0 > 1) { m.addCode( """ |${if (returnsNothing) "" else "return "}%N.%N.execute(context·=·%S)·{ | it.%L( | %L | ) |} |""".trimMargin(), Properties.PROP_STUBS, Stubs.PROP_STUBS_API, name, name, requestObject.indent(2) ) } else { m.addCode( """ |${if (returnsNothing) "" else "return "}%N.%N.execute(context·=·%S)·{ | it.%L(%L) |} |""".trimMargin(), Properties.PROP_STUBS, Stubs.PROP_STUBS_API, name, name, requestObject.indent(1) ) } } } // add documentation m.addKdoc( documentation.generateMethodKDoc( context = context, method = method, methodOptions = methodOptions, parameters = parameters, flatteningConfig = flattenedMethod, extras = extraParamDocs ) ) // add unit test val test = unitTest.createUnaryMethodUnitTest( context, method, methodOptions, parameters, flattenedMethod ) return TestableFunSpec(m.build(), test) } private fun createStreamingMethods( context: GeneratorContext, method: DescriptorProtos.MethodDescriptorProto, methodOptions: MethodOptions ): List<TestableFunSpec> { val name = methodOptions.name.decapitalize() val methods = mutableListOf<TestableFunSpec>() // input / output types val normalInputType = context.typeMap.getKotlinType(method.inputType) val normalOutputType = context.typeMap.getKotlinType(method.outputType) // add flattened methods methods.addAll(methodOptions.flattenedMethods.map { flattenedMethod -> val (parameters, request) = Flattening.getFlattenedParameters(context, method, flattenedMethod) val flattened = FunSpec.builder(name) if (method.hasClientStreaming() && method.hasServerStreaming()) { flattened.addKdoc( documentation.generateMethodKDoc( context = context, method = method, methodOptions = methodOptions, flatteningConfig = flattenedMethod, parameters = parameters ) ) flattened.addParameters(parameters.map { it.spec }) flattened.returns( GrpcTypes.Support.StreamingCall( normalInputType, normalOutputType ) ) flattened.addCode( """ |return %N.%N.prepare·{ | withInitialRequest( | %L | ) |}.executeStreaming(context·=·%S)·{ it::%N } |""".trimMargin(), Properties.PROP_STUBS, Stubs.PROP_STUBS_API, request.indent(2), name, name ) } else if (method.hasClientStreaming()) { // client only flattened.addKdoc( documentation.generateMethodKDoc( context = context, method = method, methodOptions = methodOptions, flatteningConfig = flattenedMethod, parameters = parameters ) ) flattened.returns( GrpcTypes.Support.ClientStreamingCall( normalInputType, normalOutputType ) ) flattened.addCode( "return %N.%N.executeClientStreaming(context·=·%S)·{ it::%N }\n", Properties.PROP_STUBS, Stubs.PROP_STUBS_API, name, name ) } else if (method.hasServerStreaming()) { // server only flattened.addKdoc( documentation.generateMethodKDoc( context = context, method = method, methodOptions = methodOptions, flatteningConfig = flattenedMethod, parameters = parameters ) ) flattened.addParameters(parameters.map { it.spec }) flattened.returns(GrpcTypes.Support.ServerStreamingCall(normalOutputType)) flattened.addCode( """ |return %N.%N.executeServerStreaming(context·=·%S)·{·stub,·observer·-> | stub.%N( | %L, | observer | ) |} |""".trimMargin(), Properties.PROP_STUBS, Stubs.PROP_STUBS_API, name, name, request.indent(2) ) } else { throw IllegalArgumentException("Unknown streaming type (not client or server)!") } // generate test val test = unitTest.createStreamingMethodTest( context, method, methodOptions, parameters, flattenedMethod ) TestableFunSpec(flattened.build(), test) }) // unchanged method if (methodOptions.keepOriginalMethod) { val normal = FunSpec.builder(name) .addKdoc(documentation.generateMethodKDoc(context, method, methodOptions)) val parameters = mutableListOf<ParameterInfo>() if (method.hasClientStreaming() && method.hasServerStreaming()) { normal.returns( GrpcTypes.Support.StreamingCall( normalInputType, normalOutputType ) ) normal.addCode( "return %N.%N.executeStreaming(context·=·%S)·{ it::%N }\n", Properties.PROP_STUBS, Stubs.PROP_STUBS_API, name, name ) } else if (method.hasClientStreaming()) { // client only normal.returns( GrpcTypes.Support.ClientStreamingCall( normalInputType, normalOutputType ) ) normal.addCode( "return %N.%N.executeClientStreaming(context·=·%S)·{ it::%N }\n", Properties.PROP_STUBS, Stubs.PROP_STUBS_API, name, name ) } else if (method.hasServerStreaming()) { // server only val param = ParameterSpec.builder(Functions.PARAM_REQUEST, normalInputType).build() parameters.add(ParameterInfo(param)) normal.addParameter(param) normal.returns(GrpcTypes.Support.ServerStreamingCall(normalOutputType)) normal.addCode( """ |return %N.%N.executeServerStreaming(context·=·%S)·{·stub,·observer·-> | stub.%N(%N, observer) |} |""".trimMargin(), Properties.PROP_STUBS, Stubs.PROP_STUBS_API, name, name, Functions.PARAM_REQUEST ) } else { throw IllegalArgumentException("Unknown streaming type (not client or server)!") } // generate test val test = unitTest.createStreamingMethodTest( context, method, methodOptions, parameters.toList(), null ) methods.add(TestableFunSpec(normal.build(), test)) } return methods.toList() } }
apache-2.0
4b690621e0930bd48b405b50c38500c2
39.257874
117
0.509168
5.549796
false
true
false
false
ursjoss/scipamato
public/public-web/src/main/kotlin/ch/difty/scipamato/publ/web/common/BasePage.kt
1
4656
package ch.difty.scipamato.publ.web.common import ch.difty.scipamato.common.logger import ch.difty.scipamato.common.navigator.ItemNavigator import ch.difty.scipamato.common.web.AbstractPage import ch.difty.scipamato.common.web.ScipamatoWebSessionFacade import ch.difty.scipamato.publ.config.ApplicationPublicProperties import ch.difty.scipamato.publ.misc.LocaleExtractor import ch.difty.scipamato.publ.web.CommercialFontResourceProvider import ch.difty.scipamato.publ.web.PublicPageParameters import ch.difty.scipamato.publ.web.pym.PymScripts import ch.difty.scipamato.publ.web.resources.MainCssResourceReference import ch.difty.scipamato.publ.web.resources.PymJavaScriptResourceReference import de.agilecoders.wicket.extensions.markup.html.bootstrap.icon.FontAwesome5CDNCSSReference import org.apache.wicket.markup.head.CssHeaderItem import org.apache.wicket.markup.head.IHeaderResponse import org.apache.wicket.markup.head.JavaScriptContentHeaderItem import org.apache.wicket.markup.head.JavaScriptHeaderItem import org.apache.wicket.markup.head.OnLoadHeaderItem import org.apache.wicket.model.IModel import org.apache.wicket.request.mapper.parameter.PageParameters import org.apache.wicket.spring.injection.annot.SpringBean private val log = logger() abstract class BasePage<T> : AbstractPage<T> { @SpringBean private lateinit var sessionFacade: ScipamatoWebSessionFacade @SpringBean private lateinit var applicationProperties: ApplicationPublicProperties @SpringBean(name = "parentUrlLocaleExtractor") private lateinit var localeExtractor: LocaleExtractor @SpringBean(name = "metaOTFontResourceProvider") private lateinit var metaOtFontResourceProvider: CommercialFontResourceProvider override val isNavbarVisible: Boolean protected val languageCode: String get() = sessionFacade.languageCode protected val paperIdManager: ItemNavigator<Long> get() = sessionFacade.paperIdManager override val properties: ApplicationPublicProperties get() = applicationProperties protected constructor(parameters: PageParameters) : super(parameters) { val showNavbarValue = parameters[PublicPageParameters.SHOW_NAVBAR.parameterName] isNavbarVisible = showNavbarValue.toBoolean(properties.isNavbarVisibleByDefault) considerSettingLocaleFromParentUrl(parameters) } protected constructor(model: IModel<T>?) : super(model) { isNavbarVisible = properties.isNavbarVisibleByDefault } private fun considerSettingLocaleFromParentUrl(parameters: PageParameters) { val puValue = parameters[PublicPageParameters.PARENT_URL.parameterName] if (!puValue.isNull) { val locale = localeExtractor.extractLocaleFrom(puValue.toString()) log.info("Switching Locale to {}", locale.language) session.locale = locale } } override fun renderHead(response: IHeaderResponse) { super.renderHead(response) response.render(CssHeaderItem.forReference(MainCssResourceReference)) response.render(CssHeaderItem.forReference(FontAwesome5CDNCSSReference.instance())) if (properties.isCommercialFontPresent) renderCommercialFonts(response) if (properties.isResponsiveIframeSupportEnabled) renderPymForResponsiveIframe(response) } private fun renderCommercialFonts(response: IHeaderResponse) = with(response) { render(CssHeaderItem.forReference(metaOtFontResourceProvider.cssResourceReference)) renderAdditionalCommercialFonts(this) } /** * Override to render page specific additional commercial fonts. Note: This code * is only called if the property `commercial-font-present` is set to true. * * @param response the response to render the css header item references on */ open fun renderAdditionalCommercialFonts(response: IHeaderResponse) { // no default implementation } /** * Adds pym.js to the page and instantiates the `pymChild`. * * @param response the response to render the javascript for */ private fun renderPymForResponsiveIframe(response: IHeaderResponse) = with(response) { render(JavaScriptHeaderItem.forReference(PymJavaScriptResourceReference)) render(JavaScriptContentHeaderItem(PymScripts.INSTANTIATE.script, PymScripts.INSTANTIATE.id)) render(OnLoadHeaderItem(PymScripts.RESIZE.script)) } companion object { private const val serialVersionUID = 1L const val SELECT_ALL_RESOURCE_TAG = "multiselect.selectAll" const val DESELECT_ALL_RESOURCE_TAG = "multiselect.deselectAll" } }
bsd-3-clause
b8e573998f8e53f4772110f62343049b
42.514019
101
0.773625
4.609901
false
false
false
false
aucd29/common
library/src/main/java/net/sarangnamu/common/BkView.kt
1
4477
/* * Copyright 2016 Burke Choi All rights reserved. * http://www.sarangnamu.net * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ @file:Suppress("NOTHING_TO_INLINE", "unused") package net.sarangnamu.common import android.content.Context import android.graphics.Bitmap import android.graphics.drawable.Drawable import android.graphics.drawable.StateListDrawable import android.os.Build import android.support.v4.content.ContextCompat import android.view.* import android.widget.TextView /** * Created by <a href="mailto:aucd29@gmail.com">Burke Choi</a> on 2017. 11. 2.. <p/> */ /** * https://antonioleiva.com/kotlin-ongloballayoutlistener/\ * https://stackoverflow.com/questions/38827186/what-is-the-difference-between-crossinline-and-noinline-in-kotlin */ @Suppress("DEPRECATION") inline fun View.layoutListener(crossinline f: () -> Unit) = with (viewTreeObserver) { addOnGlobalLayoutListener(object: ViewTreeObserver.OnGlobalLayoutListener { override fun onGlobalLayout() { if (Build.VERSION.SDK_INT > Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1) { viewTreeObserver.removeOnGlobalLayoutListener(this) } else { viewTreeObserver.removeGlobalOnLayoutListener(this) } f() } }) } inline fun View.capture(): Bitmap? { clearFocus() isPressed = false val cacheDrawing = willNotCacheDrawing() setWillNotCacheDrawing(false) invalidate() buildDrawingCache() val color = drawingCacheBackgroundColor drawingCacheBackgroundColor = 0 if (color != 0) { destroyDrawingCache() } val cache = drawingCache if (cache == null) { return null } val bmp = Bitmap.createBitmap(cache) destroyDrawingCache() setWillNotCacheDrawing(cacheDrawing) drawingCacheBackgroundColor = color return bmp } inline fun TextView.gravityCenter() { gravity = Gravity.CENTER } inline fun Context.drawable(name: String): Drawable? { val id = resources.getIdentifier(name, "drawable", packageName) return ContextCompat.getDrawable(this, id) } inline fun StateListDrawable.normalState(drawable: Drawable) { addState(intArrayOf(), drawable) } inline fun StateListDrawable.pressedState(drawable: Drawable) { addState(intArrayOf(android.R.attr.state_pressed), drawable) } inline fun StateListDrawable.disabledState(drawable: Drawable) { addState(intArrayOf(-android.R.attr.state_enabled), drawable) } class DrawableSelector(context: Context): SelectorBase(context) { override fun drawable(name: String): Drawable { return context.drawable(name)!! } } abstract class SelectorBase(var context: Context) { companion object { val MASK: Int = 0X1 val TP_DISABLED: Int = 0x1 val TP_PRESSED: Int = 0x2 val TP_NORMAL: Int = 0x3 val TP_DEFAULT: Int = TP_NORMAL or TP_PRESSED val TP_ALL: Int = TP_DISABLED or TP_PRESSED or TP_NORMAL } var disableSuffix = "_disabled" var pressedSuffix = "_pressed" var normalSuffix = "_normal" fun select(name: String, type: Int): StateListDrawable { val drawable = StateListDrawable() (0..3).forEach { i -> when (type and (MASK shl i)) { TP_NORMAL -> drawable.normalState(drawable(name + normalSuffix)) TP_PRESSED -> drawable.pressedState(drawable(name + pressedSuffix)) TP_DISABLED -> drawable.disabledState(drawable(name + disableSuffix)) } } return drawable } abstract fun drawable(name : String): Drawable } inline fun Window.statusBar(color: Int) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS) clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS) setStatusBarColor(color) } }
apache-2.0
ccc2b86f76274053da96675aa82ffc4f
29.25
113
0.687291
4.203756
false
false
false
false
PaulWoitaschek/Voice
data/src/main/kotlin/voice/data/legacy/LegacyBookMetaData.kt
1
680
package voice.data.legacy import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.PrimaryKey import java.util.UUID @Entity(tableName = "bookMetaData") data class LegacyBookMetaData( @ColumnInfo(name = "id") @PrimaryKey val id: UUID, @ColumnInfo(name = "type") val type: LegacyBookType, @ColumnInfo(name = "author") val author: String?, @ColumnInfo(name = "name") val name: String, @ColumnInfo(name = "root") val root: String, @ColumnInfo(name = "addedAtMillis") val addedAtMillis: Long, ) { init { require(name.isNotEmpty()) { "name must not be empty" } require(root.isNotEmpty()) { "root must not be empty" } } }
gpl-3.0
b30bccdfa07864e62b96ab3cf3c3fbec
22.448276
59
0.697059
3.523316
false
false
false
false
DSolyom/ViolinDS
ViolinDS/app/src/main/java/ds/violin/v1/widget/adapter/SectionedAdapter.kt
1
5753
/* Copyright 2016 Dániel Sólyom 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 ds.violin.v1.widget.adapter import android.support.v7.widget.RecyclerView import ds.violin.v1.app.violin.PlayingViolin import ds.violin.v1.model.modeling.ListModeling import ds.violin.v1.model.modeling.Modeling import ds.violin.v1.model.modeling.SerializableMapModel import ds.violin.v1.util.common.Debug import ds.violin.v1.viewmodel.AbsModelRecyclerViewItemBinder import ds.violin.v1.viewmodel.AbsModelSectionBinder import ds.violin.v1.viewmodel.binding.ModelViewBinding import java.util.* /** * */ open class SectionInfo() : SerializableMapModel() interface SectionedAdapter { /** = ArrayList(), section information */ var sectionInfos: ArrayList<SectionInfo> /** = ArrayList(), sections' position */ var sectionPositions: ArrayList<Int> /** * return section number for [position] */ fun sectionFor(position: Int): Int? { if (sectionPositions.isEmpty()) { return null } val sectionCount = sectionPositions.size var prox = (sectionCount - 1) / 2 while(true) { val slp = sectionPositions[prox] if (slp <= position) { if (prox == sectionCount - 1 || sectionPositions[prox + 1] > position) { return prox } prox = (sectionCount + prox + 1) / 2 } else if (slp > position) { if (prox == 0) { return null } if (sectionPositions[prox - 1] <= position) { return prox - 1 } prox /= 2 } } } /** * return real item view type for given !data! position and section * * !note: meaning of the dataPosition may differ in implementation */ fun getItemViewType(dataPosition: Int, section: Int): Int { return AbsHeaderedAdapter.VIEWTYPE_DEFAULT } /** * return section view type for given section position */ fun getSectionViewType(section: Int): Int { return AbsHeaderedAdapter.VIEWTYPE_SECTION_HEADER } } /** * an adapter with headers and with data separated by sections * * [AbsMultiDataAdapter] handles it's data separated in sections */ abstract class AbsMultiDataAdapter(on: PlayingViolin, sectionData: Array<ListModeling<*, *>>, sectionInfos: ArrayList<SectionInfo>) : AbsHeaderedAdapter(on), SectionedAdapter { val values: Array<ListModeling<*, *>> = sectionData override var sectionInfos = sectionInfos override var sectionPositions = ArrayList<Int>() override fun getRealItemViewType(position: Int): Int { val section = sectionFor(position) ?: -1 // it's never -1 if (sectionPositions.contains(position)) { /** section header requires section header view type */ return getSectionViewType(section!!) } else { /** normal item - [getItemViewType]s position is the position in the item's section */ var dataPosition = position - sectionPositions[section] - 1 return getItemViewType(dataPosition, section) } } override fun onBindViewHolder(binder: AbsModelRecyclerViewItemBinder, position: Int) { try { val section = sectionFor(position) ?: -1 // it's never -1 if (sectionPositions.contains(position)) { /** section header */ when (binder) { is AbsModelSectionBinder -> binder.bind(sectionInfos[section], section) is AbsModelRecyclerViewItemBinder -> binder.bind(sectionInfos[section], position, section) else -> (binder as ModelViewBinding<Modeling<*, *>>).bind(sectionInfos[section]!!) } } else { /** normal data - [getItemDataModel]'s and [binder]'s position is the position in the item's section */ val dataPosition = position - sectionPositions[section] - 1 val rowDataModel = getItemDataModel(dataPosition, section) if (binder is AbsModelRecyclerViewItemBinder) { binder.bind(rowDataModel, dataPosition, section) } else { (binder as ModelViewBinding<Modeling<*, *>>).bind(rowDataModel) } } } catch(e: Throwable) { Debug.logException(e) } } override fun getRealCount(): Int { sectionPositions.clear() var count = 0 val max = values.size - 1 for (i in 0..max) { sectionPositions.add(count + sectionPositions.size) count += values[i].size } return count } override fun getItemCount(): Int { var count = getRealCount() + sectionPositions.size return count + when (headerView) { null -> 0 else -> 1 } + when (footerView) { null -> 0 else -> 1 } } }
apache-2.0
2ae65bf2c9dbe06cfc92c513f7722aef
33.238095
119
0.59294
4.698529
false
false
false
false
andrei-heidelbacher/metanalysis
chronolens-test/src/main/kotlin/org/chronolens/test/core/model/EditBuilders.kt
1
4345
/* * Copyright 2018 Andrei Heidelbacher <andrei.heidelbacher@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.chronolens.test.core.model import org.chronolens.core.model.EditFunction import org.chronolens.core.model.EditType import org.chronolens.core.model.EditVariable import org.chronolens.core.model.ListEdit import org.chronolens.core.model.SetEdit import org.chronolens.test.core.BuilderMarker import org.chronolens.test.core.Init import org.chronolens.test.core.apply public class SetEditsBuilder<T> { private val setEdits = mutableListOf<SetEdit<T>>() public fun add(value: T): SetEditsBuilder<T> { setEdits += SetEdit.Add(value) return this } public operator fun T.unaryPlus() { setEdits += SetEdit.Add(this) } public fun remove(value: T): SetEditsBuilder<T> { setEdits += SetEdit.Remove(value) return this } public operator fun T.unaryMinus() { setEdits += SetEdit.Remove(this) } public fun build(): List<SetEdit<T>> = setEdits } @BuilderMarker public class ListEditsBuilder<T> { private val listEdits = mutableListOf<ListEdit<T>>() public fun add(index: Int, value: T): ListEditsBuilder<T> { listEdits += ListEdit.Add(index, value) return this } public fun remove(index: Int): ListEditsBuilder<T> { listEdits += ListEdit.Remove(index) return this } public fun build(): List<ListEdit<T>> = listEdits } @BuilderMarker public class EditTypeBuilder(private val id: String) { private val supertypeEdits = mutableListOf<SetEdit<String>>() private val modifierEdits = mutableListOf<SetEdit<String>>() public fun supertypes( init: Init<SetEditsBuilder<String>>, ): EditTypeBuilder { supertypeEdits += SetEditsBuilder<String>().apply(init).build() return this } public fun modifiers(init: Init<SetEditsBuilder<String>>): EditTypeBuilder { modifierEdits += SetEditsBuilder<String>().apply(init).build() return this } public fun build(): EditType = EditType(id, supertypeEdits, modifierEdits) } @BuilderMarker public class EditFunctionBuilder(private val id: String) { private val modifierEdits = mutableListOf<SetEdit<String>>() private val parameterEdits = mutableListOf<ListEdit<String>>() private val bodyEdits = mutableListOf<ListEdit<String>>() public fun parameters( init: Init<ListEditsBuilder<String>>, ): EditFunctionBuilder { parameterEdits += ListEditsBuilder<String>().apply(init).build() return this } public fun modifiers( init: Init<SetEditsBuilder<String>>, ): EditFunctionBuilder { modifierEdits += SetEditsBuilder<String>().apply(init).build() return this } public fun body( init: Init<ListEditsBuilder<String>>, ): EditFunctionBuilder { bodyEdits += ListEditsBuilder<String>().apply(init).build() return this } public fun build(): EditFunction = EditFunction(id, parameterEdits, modifierEdits, bodyEdits) } @BuilderMarker public class EditVariableBuilder(private val id: String) { private val modifierEdits = mutableListOf<SetEdit<String>>() private val initializerEdits = mutableListOf<ListEdit<String>>() public fun modifiers( init: Init<SetEditsBuilder<String>>, ): EditVariableBuilder { modifierEdits += SetEditsBuilder<String>().apply(init).build() return this } public fun initializer( init: Init<ListEditsBuilder<String>>, ): EditVariableBuilder { initializerEdits += ListEditsBuilder<String>().apply(init).build() return this } public fun build(): EditVariable = EditVariable(id, modifierEdits, initializerEdits) }
apache-2.0
2b39748918f468de286d6801efeeab4d
29.815603
80
0.693441
4.214355
false
false
false
false
NextFaze/dev-fun
devfun/src/main/java/com/nextfaze/devfun/invoke/InvokeUi.kt
1
9180
package com.nextfaze.devfun.invoke import android.app.Dialog import android.os.Bundle import android.os.Handler import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.view.Window import android.widget.Button import android.widget.ProgressBar import android.widget.Spinner import android.widget.Switch import android.widget.TextView import android.widget.Toast import android.widget.Toast.LENGTH_LONG import androidx.fragment.app.FragmentActivity import com.google.android.material.textfield.TextInputLayout import com.nextfaze.devfun.DebugException import com.nextfaze.devfun.core.R import com.nextfaze.devfun.error.ErrorHandler import com.nextfaze.devfun.internal.android.* import com.nextfaze.devfun.internal.log.* import com.nextfaze.devfun.internal.splitCamelCase import com.nextfaze.devfun.invoke.view.From import com.nextfaze.devfun.invoke.view.InvokeParameterView import com.nextfaze.devfun.invoke.view.WithValue import com.nextfaze.devfun.invoke.view.simple.ErrorParameterView import com.nextfaze.devfun.invoke.view.simple.InjectedParameterView import com.nextfaze.devfun.invoke.view.types.getTypeOrNull import kotlinx.android.synthetic.main.df_devfun_invoker_dialog_fragment.* internal class InvokingDialogFragment : BaseDialogFragment() { companion object { fun show(activity: FragmentActivity, function: UiFunction) = showNow(activity) { InvokingDialogFragment().apply { this.function = function } } } private val log = logger() private lateinit var function: UiFunction private val devFun = com.nextfaze.devfun.core.devFun private val errorHandler by lazy { devFun.get<ErrorHandler>() } private var canExecute = true override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) if (savedInstanceState != null) { Toast.makeText(context, "Invocation dialog does not support recreation from a saved state at this time.", LENGTH_LONG).show() dismissAllowingStateLoss() } setStyle(STYLE_NO_TITLE, 0) } override fun onCreateDialog(savedInstanceState: Bundle?): Dialog = super.onCreateDialog(savedInstanceState).apply { requestWindowFeature(Window.FEATURE_NO_TITLE) } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? = inflater.inflate(R.layout.df_devfun_invoker_dialog_fragment, container, false) private val Parameter.displayName: CharSequence get() = name.let { name -> when (name) { is String -> name.capitalize().splitCamelCase() else -> name ?: "Unknown" } } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { try { canExecute = true performOnViewCreated() } catch (t: Throwable) { errorHandler.onError( t, "View Creation Failure", "Something when wrong when trying to create the invocation dialog view for $function." ) Handler().post { dismissAllowingStateLoss() } } } override fun onResume() { super.onResume() dialog?.window?.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT) } private fun performOnViewCreated() { titleText.text = function.title subtitleText.text = function.subtitle subtitleText.visibility = if (function.subtitle == null) View.GONE else View.VISIBLE functionSignatureText.text = function.signature functionSignatureText.visibility = if (function.signature == null) View.GONE else View.VISIBLE function.parameters.forEach { buildParameterView(it) } fun Button.setUiButton(uiButton: UiButton) { visibility = View.VISIBLE uiButton.text?.also { text = it } uiButton.textId?.also { text = getText(it) } setOnClickListener { val invoke = uiButton.invoke when { invoke != null -> onInvokeButtonClick(invoke) else -> uiButton.onClick?.invoke() } dialog.dismiss() } if (!canExecute && uiButton.invoke != null) { isEnabled = false } } (function.negativeButton ?: uiButton()).also { negativeButton.setUiButton(it) } function.neutralButton?.also { neutralButton.setUiButton(it) } (function.positiveButton ?: uiButton()).also { positiveButton.setUiButton(it) } if (!canExecute) { (0 until inputsList.childCount).forEach { inputsList.getChildAt(it).also { view -> view as InvokeParameterView val paramView = view.view // we want to leave these enabled so we can click to show error details if (paramView !is ErrorParameterView) { view.isEnabled = false } } } errorMessageText.visibility = View.VISIBLE } } private fun onInvokeButtonClick(simpleInvoke: SimpleInvoke) { try { fun View?.getValue(): Any? { return when (this) { is InvokeParameterView -> if (isNull) null else view.getValue() is InjectedParameterView -> devFun.instanceOf(value) is WithValue<*> -> value is TextInputLayout -> editText!!.text is Switch -> isChecked is Spinner -> selectedItem is ProgressBar -> progress is TextView -> text else -> throw RuntimeException("Unexpected view type $this. If this is a custom view, add the WithValue interface. If this is a standard platform view, create an issue to have it handled.") } } val params = (0 until inputsList.childCount).map { inputsList.getChildAt(it).getValue() } log.d { "Invoke $function\nwith params: $params" } simpleInvoke(params) } catch (de: DebugException) { throw de } catch (t: Throwable) { errorHandler.onError(t, "Invocation Failure", "Something went wrong when trying to execute requested method for $function.") } } @Suppress("UNCHECKED_CAST") private fun buildParameterView(parameter: Parameter) { val paramView = layoutInflater.inflate(R.layout.df_devfun_parameter, inputsList, false) as ViewGroup paramView as InvokeParameterView paramView.label = parameter.displayName paramView.nullable = if (parameter is WithNullability) parameter.isNullable else false val injectException = try { devFun.instanceOf(parameter.type).let { null } } catch (t: Throwable) { t } if (injectException == null) { paramView.view = devFun.viewFactories[InjectedParameterView::class]?.inflate(layoutInflater, inputsList)?.apply { if (this is InjectedParameterView) { value = parameter.type paramView.attributes = getText(R.string.df_devfun_injected) } } } else { val inputViewFactory = devFun.parameterViewFactories[parameter] if (inputViewFactory != null) { paramView.view = inputViewFactory.inflate(layoutInflater, inputsList).apply { if (this is WithValue<*>) { if (parameter is WithInitialValue<*>) { val value = parameter.value when (value) { null -> paramView.isNull = paramView.nullable else -> (this as WithValue<Any>).value = value } } else { parameter.annotations.getTypeOrNull<From> { (this as WithValue<Any>).value = devFun.instanceOf(it.source).value } } } } } else { canExecute = false devFun.viewFactories[ErrorParameterView::class]?.inflate(layoutInflater, inputsList)?.apply { this as ErrorParameterView value = parameter.type paramView.attributes = getText(R.string.df_devfun_missing) paramView.view = this paramView.setOnClickListener { devFun.get<ErrorHandler>() .onError(injectException, "Instance Not Found", getString(R.string.df_devfun_cannot_execute)) } } } } inputsList.addView(paramView) } }
apache-2.0
4f9c2d2f3f1c427100ed54108d53b318
39.619469
209
0.596732
5.111359
false
false
false
false
jospint/Architecture-Components-DroidDevs
ArchitectureComponents/app/src/main/java/com/jospint/droiddevs/architecturecomponents/view/start/PlacesAdapter.kt
1
1367
package com.jospint.droiddevs.architecturecomponents.view.start import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.jospint.droiddevs.architecturecomponents.R import com.jospint.droiddevs.architecturecomponents.data.googlemaps.model.PlaceResult import com.jospint.droiddevs.architecturecomponents.util.extension.singleClick import kotlinx.android.synthetic.main.view_locality.view.* import kotlin.properties.Delegates class PlacesAdapter : RecyclerView.Adapter<PlacesAdapter.LocalityVH>() { var listener: (PlaceResult) -> Unit = {} var places: List<PlaceResult> by Delegates.observable(emptyList()) { _, _, _ -> notifyDataSetChanged() } override fun onBindViewHolder(holder: LocalityVH, position: Int) { val place = places[position] holder.itemView.apply { singleClick { listener(place) } locality_name.text = place.name locality_address.text = place.formattedAddress } } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): LocalityVH = LocalityVH(LayoutInflater.from(parent.context).inflate(R.layout.view_locality, parent, false)) override fun getItemCount(): Int = places.size class LocalityVH(itemView: View) : RecyclerView.ViewHolder(itemView) }
apache-2.0
7e1b1a6112bfee0af1d76d9bd4f8877a
39.235294
108
0.754206
4.423948
false
false
false
false
nickthecoder/paratask
paratask-core/src/main/kotlin/uk/co/nickthecoder/paratask/parameters/FloatParameter.kt
1
3112
/* ParaTask Copyright (C) 2017 Nick Robinson This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package uk.co.nickthecoder.paratask.parameters import javafx.util.StringConverter import uk.co.nickthecoder.paratask.ParameterException import uk.co.nickthecoder.paratask.parameters.fields.FloatField import uk.co.nickthecoder.paratask.util.uncamel import java.text.DecimalFormat private val doubleFormat = DecimalFormat("0.#######") open class FloatParameter( name: String, label: String = name.uncamel(), description: String = "", hint: String = "", value: Float? = null, required: Boolean = true, val columnCount: Int = 8, val minValue: Float = -Float.MAX_VALUE, val maxValue: Float = Float.MAX_VALUE) : AbstractValueParameter<Float?>( name = name, label = label, description = description, hint = hint, value = value, required = required) { override val converter = object : StringConverter<Float?>() { override fun fromString(str: String): Float? { val trimmed = str.trim() if (trimmed.isEmpty()) { return null } try { return trimmed.toFloat() } catch (e: Exception) { throw ParameterException(this@FloatParameter, "Not a number") } } override fun toString(obj: Float?): String { if (obj == null) { return "" } val l = obj.toLong() if (obj == l.toFloat()) { return l.toString() } else { return doubleFormat.format(obj) } } } override fun errorMessage(v: Float?): String? { if (isProgrammingMode()) return null if (v == null) { return super.errorMessage(v) } if (v < minValue) { return "Cannot be less than $minValue" } else if (v > maxValue) { return "Cannot be more than $maxValue" } return null } override fun isStretchy() = false override fun createField(): FloatField = FloatField(this).build() as FloatField override fun toString(): String = "Double" + super.toString() override fun copy() = FloatParameter(name = name, label = label, description = description, hint = hint, value = value, required = required, minValue = minValue, maxValue = maxValue, columnCount = columnCount) }
gpl-3.0
fdadf24c637a9441f9511aa2afde83ad
30.755102
116
0.612468
4.60355
false
false
false
false
wiltonlazary/kotlin-native
build-tools/src/main/kotlin/org/jetbrains/kotlin/benchmark/SwiftBenchmarkingPlugin.kt
1
4537
package org.jetbrains.kotlin.benchmark import org.gradle.api.NamedDomainObjectContainer import org.gradle.api.Project import org.gradle.api.Task import org.jetbrains.kotlin.* import org.jetbrains.kotlin.gradle.plugin.KotlinSourceSet import org.jetbrains.kotlin.gradle.plugin.mpp.Framework import org.jetbrains.kotlin.gradle.plugin.mpp.KotlinNativeTarget import org.jetbrains.kotlin.gradle.plugin.mpp.AbstractKotlinNativeTargetPreset import org.jetbrains.kotlin.gradle.plugin.mpp.NativeBuildType import java.io.File import javax.inject.Inject import java.nio.file.Paths import kotlin.reflect.KClass enum class CodeSizeEntity { FRAMEWORK, EXECUTABLE } open class SwiftBenchmarkExtension @Inject constructor(project: Project) : BenchmarkExtension(project) { var swiftSources: List<String> = emptyList() var useCodeSize: CodeSizeEntity = CodeSizeEntity.FRAMEWORK // use as code size metric framework size or executable } /** * A plugin configuring a benchmark Kotlin/Native project. */ open class SwiftBenchmarkingPlugin : BenchmarkingPlugin() { override fun Project.configureJvmJsonTask(jvmRun: Task): Task { return tasks.create("jvmJsonReport") { logger.info("JVM run is unsupported") jvmRun.finalizedBy(it) } } override fun Project.configureJvmTask(): Task { return tasks.create("jvmRun") { task -> task.doLast { logger.info("JVM run is unsupported") } } } override val benchmarkExtensionClass: KClass<*> get() = SwiftBenchmarkExtension::class override val Project.benchmark: SwiftBenchmarkExtension get() = extensions.getByName(benchmarkExtensionName) as SwiftBenchmarkExtension override val benchmarkExtensionName: String = "swiftBenchmark" override val Project.nativeExecutable: String get() = Paths.get(buildDir.absolutePath, benchmark.applicationName).toString() override val Project.nativeLinkTask: Task get() = tasks.getByName("buildSwift") private lateinit var framework: Framework val nativeFrameworkName = "benchmark" override fun NamedDomainObjectContainer<KotlinSourceSet>.configureSources(project: Project) { project.benchmark.let { commonMain.kotlin.srcDirs(*it.commonSrcDirs.toTypedArray()) nativeMain.kotlin.srcDirs(*(it.nativeSrcDirs).toTypedArray()) } } override fun Project.determinePreset(): AbstractKotlinNativeTargetPreset<*> = kotlin.presets.macosX64 as AbstractKotlinNativeTargetPreset<*> override fun KotlinNativeTarget.configureNativeOutput(project: Project) { binaries.framework(nativeFrameworkName, listOf(project.benchmark.buildType)) { // Specify settings configured by a user in the benchmark extension. project.afterEvaluate { linkerOpts.addAll(project.benchmark.linkerOpts) } } } override fun Project.configureExtraTasks() { val nativeTarget = kotlin.targets.getByName(NATIVE_TARGET_NAME) as KotlinNativeTarget // Build executable from swift code. framework = nativeTarget.binaries.getFramework(nativeFrameworkName, benchmark.buildType) val buildSwift = tasks.create("buildSwift") { task -> task.dependsOn(framework.linkTaskName) task.doLast { val frameworkParentDirPath = framework.outputDirectory.absolutePath val options = listOf("-O", "-wmo", "-Xlinker", "-rpath", "-Xlinker", frameworkParentDirPath, "-F", frameworkParentDirPath) compileSwift(project, nativeTarget.konanTarget, benchmark.swiftSources, options, Paths.get(buildDir.absolutePath, benchmark.applicationName), false) } } } override fun Project.collectCodeSize(applicationName: String) = getCodeSizeBenchmark(applicationName, if (benchmark.useCodeSize == CodeSizeEntity.FRAMEWORK) File("${framework.outputFile.absolutePath}/$nativeFrameworkName").canonicalPath else nativeExecutable ) override fun getCompilerFlags(project: Project, nativeTarget: KotlinNativeTarget) = if (project.benchmark.useCodeSize == CodeSizeEntity.FRAMEWORK) { super.getCompilerFlags(project, nativeTarget) + framework.freeCompilerArgs.map { "\"$it\"" } } else { listOf("-O", "-wmo") } }
apache-2.0
de7e8b3a1af18966380c203efed7331d
41.411215
144
0.694071
4.878495
false
true
false
false
ashdavies/data-binding
mobile/src/main/kotlin/io/ashdavies/playground/conferences/ConferencesFragment.kt
1
1660
package io.ashdavies.playground.conferences import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.fragment.app.viewModels import androidx.lifecycle.Observer import androidx.lifecycle.lifecycleScope import io.ashdavies.playground.R import io.ashdavies.playground.binding import io.ashdavies.playground.common.MainViewModel import io.ashdavies.playground.databinding.ConferencesFragmentBinding import io.ashdavies.playground.extensions.navigate import kotlinx.coroutines.launch internal class ConferencesFragment : Fragment() { private val model: ConferencesViewModel by viewModels { ConferencesViewModel.Factory(requireContext()) } private val parent: MainViewModel by viewModels() private val adapter = ConferencesAdapter(R.layout.list_item) private lateinit var binding: ConferencesFragmentBinding override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { binding = inflater.binding(R.layout.conferences_fragment, container, false) binding.lifecycleOwner = viewLifecycleOwner binding.model = model return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) viewLifecycleOwner .lifecycleScope .launch { navigate(model) } binding .recycler .adapter = adapter with(model) { items.observe(viewLifecycleOwner, Observer(adapter::submitList)) errors.observe(viewLifecycleOwner, Observer(parent::onError)) } } }
apache-2.0
ae1179ff6d02b57d675dea2b71c9515d
32.2
114
0.787952
4.729345
false
false
false
false
antoniolg/Bandhook-Kotlin
app/src/main/java/com/antonioleiva/bandhookkotlin/ui/screens/detail/BiographyFragment.kt
1
2197
/* * Copyright (C) 2016 Alexey Verein * * 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.antonioleiva.bandhookkotlin.ui.screens.detail import android.os.Bundle import android.support.v4.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import com.antonioleiva.bandhookkotlin.R import com.antonioleiva.bandhookkotlin.ui.activity.ViewAnkoComponent import com.antonioleiva.bandhookkotlin.ui.util.fromHtml import com.antonioleiva.bandhookkotlin.ui.util.setTextAppearanceC import org.jetbrains.anko.* import org.jetbrains.anko.support.v4.nestedScrollView class BiographyFragment : Fragment() { private var component: Component? = null override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { component = container?.let { Component(container) } return component?.inflate() } fun setBiographyText(biographyText: String?) { component?.textView?.text = biographyText?.fromHtml() } fun getBiographyText(): String? { return component?.textView?.text?.toString() } private class Component(override val view: ViewGroup) : ViewAnkoComponent<ViewGroup> { lateinit var textView: TextView override fun createView(ui: AnkoContext<ViewGroup>): View = with(ui) { nestedScrollView { textView = textView { backgroundResource = android.R.color.white padding = dip(16) setTextAppearanceC(R.style.TextAppearance_AppCompat_Body1) } } } } }
apache-2.0
8cccc5a98ef5752b2227964fce0e16e3
33.888889
116
0.71188
4.548654
false
false
false
false
LarsKrogJensen/graphql-kotlin
src/main/kotlin/graphql/validation/rules/LoneAnonymousOperation.kt
1
1412
package graphql.validation.rules import graphql.language.Document import graphql.language.OperationDefinition import graphql.validation.IValidationContext import graphql.validation.ValidationErrorType import graphql.validation.* class LoneAnonymousOperation(validationContext: IValidationContext, validationErrorCollector: ValidationErrorCollector) : AbstractRule(validationContext, validationErrorCollector) { private var _hasAnonymousOp = false private var _count = 0 override fun checkOperationDefinition(operationDefinition: OperationDefinition) { super.checkOperationDefinition(operationDefinition) val name = operationDefinition.name var message: String? = null if (name == null) { _hasAnonymousOp = true if (_count > 0) { message = "Anonymous operation with other operations." } } else { if (_hasAnonymousOp) { message = "Operation $name is following anonymous operation." } } _count++ if (message != null) { addError(ValidationError(ValidationErrorType.LoneAnonymousOperationViolation, operationDefinition.sourceLocation, message)) } } override fun documentFinished(document: Document) { super.documentFinished(document) _hasAnonymousOp = false } }
mit
24cf79b679fd05d10c0ac063c0fea5d8
33.439024
135
0.675637
5.308271
false
false
false
false
nickbutcher/plaid
core/src/main/java/io/plaidapp/core/dribbble/data/api/model/Shot.kt
1
1564
/* * Copyright 2018 Google LLC. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.plaidapp.core.dribbble.data.api.model import com.google.gson.annotations.SerializedName import io.plaidapp.core.data.PlaidItem import java.util.Date /** * Models a dibbble shot */ data class Shot( @SerializedName("id") override val id: Long, @SerializedName("title") override val title: String, @SerializedName("page") override val page: Int, @SerializedName("description") val description: String, @SerializedName("images") val images: Images, @SerializedName("views_count") val viewsCount: Int = 0, @SerializedName("likes_count") val likesCount: Int = 0, @SerializedName("created_at") val createdAt: Date? = null, @SerializedName("html_url") val htmlUrl: String = "https://dribbble.com/shots/$id", @SerializedName("animated") val animated: Boolean = false, @SerializedName("user") val user: User ) : PlaidItem(id, title, htmlUrl, page) { // todo move this into a decorator var hasFadedIn = false }
apache-2.0
1d081bb45f799a449de92eef2b1010bc
36.238095
87
0.719309
3.989796
false
false
false
false
hummatli/MAHAds
app-cross-promoter/src/main/java/com/mobapphome/appcrosspromoter/ProgramItmAdpt.kt
2
3755
package com.mobapphome.appcrosspromoter import android.support.v7.widget.RecyclerView import android.util.Log import android.util.TypedValue import android.view.View import android.view.ViewGroup import com.bumptech.glide.Glide import com.mobapphome.appcrosspromoter.commons.* import com.mobapphome.appcrosspromoter.tools.Constants import com.mobapphome.appcrosspromoter.tools.Program import com.mobapphome.appcrosspromoter.tools.checkPackageIfExists import com.mobapphome.appcrosspromoter.tools.getUrlOfImage import kotlinx.android.synthetic.main.program_item_programs.view.* /** * Created by settar on 6/30/17. */ class ProgramItmAdpt(val items: List<Any>, val urlRootOnServer: String?, val fontName: String?, val listenerOnClick: (Any) -> Unit, val listenerOnMoreClick: (Any, View) -> Unit) : RecyclerView.Adapter<ProgramItmAdpt.ViewHolder>() { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder = ViewHolder(parent.inflate(R.layout.program_item_programs)!!) override fun onBindViewHolder(holder: ViewHolder, position: Int) = holder.bind(items[position], listenerOnClick, listenerOnMoreClick)!! override fun getItemCount(): Int = items.size inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { fun bind(item: Any, listenerOnClick: (Any) -> Unit, listenerOnMoreClick: (Any, View) -> Unit) = with(itemView) { if (item is Program) { val pckgName = item.uri.trim { it <= ' ' } tvProgramNewText.makeGone() val freshnestStr = item.getFreshnestStr(context) if (freshnestStr != null) { tvProgramNewText.setTextSize(TypedValue.COMPLEX_UNIT_SP, item.getFreshnestStrTextSizeInSP(context).toFloat()) tvProgramNewText.text = freshnestStr tvProgramNewText.startAnimationFillAfter(R.anim.tv_rotate, true) tvProgramNewText.makeVisible() } else { tvProgramNewText.makeGone() } if (checkPackageIfExists(context, pckgName)) { tvOpenInstall.text = context.resources.getString(R.string.cmnd_verb_acp_open_program) } else { tvOpenInstall.text = context.resources.getString(R.string.cmnd_verb_acp_install_program) } tvProgramName.text = item.name tvProgramDesc.text = item.desc Log.i(Constants.LOG_TAG_MAH_ADS, getUrlOfImage(urlRootOnServer!!, item.img)) Glide.with(context) .load(getUrlOfImage(urlRootOnServer, item.img)) //.diskCacheStrategy(DiskCacheStrategy.ALL) .centerCrop() .placeholder(R.drawable.img_place_holder_normal) .crossFade() .error(context.getDrawableWithColorFilter(R.drawable.img_not_found, R.color.acp_no_image_color)) .into(ivProgramImg) imgBtnMore.setColorFilterCompat(R.color.acp_all_and_btn_text_color) imgBtnMore.setImageResource(R.drawable.ic_more_vert_grey600_24dp) tvProgramNewText.setFontTextView(fontName) tvProgramName.setFontTextView(fontName) tvProgramDesc.setFontTextView(fontName) tvOpenInstall.setFontTextView(fontName) setOnClickListener { listenerOnClick(item) } imgBtnMore.setOnClickListener { v -> listenerOnMoreClick(item, v) } } } } }
apache-2.0
57489b3b41ebd8844f9ecff138ba47c3
41.681818
144
0.626897
4.45433
false
false
false
false
equeim/tremotesf-android
app/src/main/kotlin/org/equeim/tremotesf/ui/AboutFragment.kt
1
5312
/* * Copyright (C) 2017-2022 Alexey Rochev <equeim@gmail.com> * * This file is part of Tremotesf. * * Tremotesf 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. * * Tremotesf 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.equeim.tremotesf.ui import android.os.Bundle import androidx.annotation.LayoutRes import androidx.annotation.StringRes import androidx.core.text.HtmlCompat import androidx.fragment.app.Fragment import androidx.viewpager2.adapter.FragmentStateAdapter import com.google.android.material.tabs.TabLayoutMediator import org.equeim.tremotesf.BuildConfig import org.equeim.tremotesf.R import org.equeim.tremotesf.databinding.AboutFragmentBaseTabFragmentBinding import org.equeim.tremotesf.databinding.AboutFragmentBinding import org.equeim.tremotesf.databinding.AboutFragmentLicenseTabFragmentBinding class AboutFragment : NavigationFragment(R.layout.about_fragment) { private var pagerAdapter: PagerAdapter? = null override fun onViewStateRestored(savedInstanceState: Bundle?) { super.onViewStateRestored(savedInstanceState) toolbar.title = "%s %s".format(getString(R.string.app_name), BuildConfig.VERSION_NAME) pagerAdapter = PagerAdapter(this) with(AboutFragmentBinding.bind(requireView())) { pager.adapter = pagerAdapter TabLayoutMediator(tabLayout, pager) { tab, position -> tab.setText(PagerAdapter.getTitle(position)) }.attach() } } private class PagerAdapter(fragment: Fragment) : FragmentStateAdapter(fragment) { companion object { private val tabs = Tab.values().toList() @StringRes fun getTitle(position: Int): Int { return when (tabs[position]) { Tab.Main -> R.string.about Tab.Authors -> R.string.authors Tab.Translators -> R.string.translators Tab.License -> R.string.license } } } private enum class Tab { Main, Authors, Translators, License } override fun getItemCount() = tabs.size override fun createFragment(position: Int): Fragment { return when (tabs[position]) { Tab.Main -> MainTabFragment() Tab.Authors -> AuthorsTabFragment() Tab.Translators -> TranslatorsTabFragment() Tab.License -> LicenseTabFragment() } } } open class PagerFragment(@LayoutRes contentLayoutId: Int) : Fragment(contentLayoutId) { override fun onViewStateRestored(savedInstanceState: Bundle?) { super.onViewStateRestored(savedInstanceState) applyNavigationBarBottomInset() } } class MainTabFragment : PagerFragment(R.layout.about_fragment_base_tab_fragment) { override fun onViewStateRestored(savedInstanceState: Bundle?) { super.onViewStateRestored(savedInstanceState) resources.openRawResource(R.raw.about).use { inputStream -> with(AboutFragmentBaseTabFragmentBinding.bind(requireView())) { textView.text = HtmlCompat.fromHtml(inputStream.reader().readText(), 0) } } } } class AuthorsTabFragment : PagerFragment(R.layout.about_fragment_base_tab_fragment) { override fun onViewStateRestored(savedInstanceState: Bundle?) { super.onViewStateRestored(savedInstanceState) resources.openRawResource(R.raw.authors).use { inputStream -> with(AboutFragmentBaseTabFragmentBinding.bind(requireView())) { textView.text = HtmlCompat.fromHtml(inputStream.reader().readText(), 0) } } } } class TranslatorsTabFragment : PagerFragment(R.layout.about_fragment_base_tab_fragment) { override fun onViewStateRestored(savedInstanceState: Bundle?) { super.onViewStateRestored(savedInstanceState) resources.openRawResource(R.raw.translators).use { AboutFragmentBaseTabFragmentBinding.bind(requireView()).textView.text = it.reader().readText() } } } class LicenseTabFragment : PagerFragment(R.layout.about_fragment_license_tab_fragment) { override fun onViewStateRestored(savedInstanceState: Bundle?) { super.onViewStateRestored(savedInstanceState) resources.openRawResource(R.raw.license).use { AboutFragmentLicenseTabFragmentBinding.bind(requireView()).webView.loadData( it.reader().readText(), "text/html", null ) } } } }
gpl-3.0
a7acf3810545f30e453d838d1e72dcf0
37.773723
94
0.656438
5.088123
false
false
false
false
MimiReader/mimi-reader
mimi-app/src/main/java/com/emogoth/android/phone/mimi/activity/SlidingPanelActivity.kt
1
12646
package com.emogoth.android.phone.mimi.activity import android.content.Intent import android.graphics.Color import android.os.Bundle import android.text.TextUtils import android.view.Menu import android.view.MenuItem import android.view.View import android.view.ViewGroup import androidx.appcompat.widget.Toolbar import androidx.core.content.res.ResourcesCompat import androidx.slidingpanelayout.widget.SlidingPaneLayout import androidx.slidingpanelayout.widget.SlidingPaneLayout.PanelSlideListener import com.emogoth.android.phone.mimi.R import com.emogoth.android.phone.mimi.activity.GalleryActivity2.Companion.start import com.emogoth.android.phone.mimi.db.HistoryTableConnection import com.emogoth.android.phone.mimi.fragment.* import com.emogoth.android.phone.mimi.interfaces.* import com.emogoth.android.phone.mimi.util.* import com.google.android.material.floatingactionbutton.FloatingActionButton import com.mimireader.chanlib.models.ChanBoard import com.mimireader.chanlib.models.ChanPost import com.novoda.simplechromecustomtabs.SimpleChromeCustomTabs class SlidingPanelActivity : MimiActivity(), BoardItemClickListener, View.OnClickListener, ThumbnailClickListener, GalleryMenuItemClickListener, IToolbarContainer { private var listType = BOARD_LIST_ID private var boardName: String? = null private var boardTitle: String? = null private var listFragment: MimiFragmentBase? = null private var detailFragment: MimiFragmentBase? = null private var boardsFragment: MimiFragmentBase? = null private var openPage = Pages.NONE private var addContentFab: FloatingActionButton? = null private var panelLayout: SlidingPaneLayout? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_sliding_panel) var sliderFadeColor = if (MimiUtil.getInstance().theme == MimiUtil.THEME_LIGHT) { ResourcesCompat.getColor(resources, R.color.background_light, theme) } else { ResourcesCompat.getColor(resources, R.color.background_dark, theme) } val coverFadeColor = sliderFadeColor sliderFadeColor = Color.argb(0xAA, Color.red(sliderFadeColor), Color.green(sliderFadeColor), Color.blue(sliderFadeColor)) panelLayout = findViewById<View>(R.id.panel_layout) as SlidingPaneLayout panelLayout?.sliderFadeColor = sliderFadeColor panelLayout?.coveredFadeColor = coverFadeColor panelLayout?.setPanelSlideListener(object : PanelSlideListener { override fun onPanelSlide(panel: View, slideOffset: Float) {} override fun onPanelOpened(panel: View) { if (listFragment != null) { listFragment?.initMenu() } } override fun onPanelClosed(panel: View) { if (detailFragment != null) { detailFragment?.initMenu() } } }) panelLayout?.openPane() addContentFab = findViewById<View>(R.id.fab_add_content) as FloatingActionButton addContentFab?.setOnClickListener { val fragment = if (panelLayout?.isOpen == true) { listFragment } else { detailFragment } if (fragment is ContentInterface) { (fragment as ContentInterface).addContent() } } val toolbar: Toolbar? = findViewById<View>(R.id.mimi_toolbar) as Toolbar if (toolbar != null) { toolbar.setNavigationOnClickListener(this) this.toolbar = toolbar } extractExtras(intent.extras) initDrawers(R.id.nav_drawer, R.id.nav_drawer_container, true) createDrawers(R.id.nav_drawer) initFragments() if (openPage == Pages.BOOKMARKS) { openHistoryPage(true) } } private fun initFragments() { val ft = supportFragmentManager.beginTransaction() when (listType) { BOARD_LIST_ID -> { val fragment = BoardItemListFragment() val extras = Bundle() extras.putBoolean(Extras.EXTRAS_OPTIONS_MENU_ENABLED, false) fragment.arguments = extras ft.add(R.id.postitem_list, fragment, TAG_BOARD_LIST) ft.commit() fragment.setActivateOnItemClick(true) detailFragment = fragment listFragment = fragment boardsFragment = fragment } BOOKMARKS_ID -> { val fragment = HistoryFragment() val args = Bundle() args.putInt(Extras.EXTRAS_HISTORY_QUERY_TYPE, HistoryTableConnection.BOOKMARKS) args.putInt(Extras.EXTRAS_VIEWING_HISTORY, VIEWING_BOOKMARKS) args.putBoolean(Extras.EXTRAS_OPTIONS_MENU_ENABLED, false) fragment.arguments = args ft.add(R.id.postitem_list, fragment, TAG_BOARD_LIST) ft.commit() detailFragment = fragment listFragment = fragment } HISTORY_ID -> { val fragment = HistoryFragment() val args = Bundle() args.putInt(Extras.EXTRAS_HISTORY_QUERY_TYPE, HistoryTableConnection.HISTORY) args.putInt(Extras.EXTRAS_VIEWING_HISTORY, VIEWING_HISTORY) args.putBoolean(Extras.EXTRAS_OPTIONS_MENU_ENABLED, false) fragment.arguments = args ft.add(R.id.postitem_list, fragment, TAG_BOARD_LIST) ft.commit() detailFragment = fragment listFragment = fragment } } } private fun extractExtras(extras: Bundle?) { if (extras != null) { boardName = extras.getString(Extras.EXTRAS_BOARD_NAME) if (extras.containsKey(Extras.EXTRAS_LIST_TYPE)) { listType = extras.getInt(Extras.EXTRAS_LIST_TYPE) } if (extras.containsKey(Extras.OPEN_PAGE)) { val page = extras.getString(Extras.OPEN_PAGE) if (!TextUtils.isEmpty(page)) { openPage = Pages.valueOf(page!!) } } } } private fun setFabVisibility(visible: Boolean) { if (addContentFab?.isShown == true && !visible) { addContentFab?.hide() } else if (addContentFab?.isShown == false && visible) { addContentFab?.show() } } override fun onPause() { SimpleChromeCustomTabs.getInstance().disconnectFrom(this) super.onPause() } override fun onResume() { SimpleChromeCustomTabs.getInstance().connectTo(this) super.onResume() } override fun onCreateOptionsMenu(menu: Menu): Boolean { val inflater = menuInflater if (panelLayout?.isOpen == true) { listFragment?.onCreateOptionsMenu(menu, inflater) } else { detailFragment?.onCreateOptionsMenu(menu, inflater) } return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { if (item.itemId == android.R.id.home) { toggleNavDrawer() return true } return if (panelLayout?.isOpen == true) { listFragment?.onOptionsItemSelected(item) == true } else { detailFragment?.onOptionsItemSelected(item) == true } } override val pageName: String get() = "sliding_drawer_activity" override fun onClick(v: View) { if (listType == BOARD_LIST_ID) { toggleNavDrawer() } else { finish() } } override fun onBoardItemClick(board: ChanBoard, saveBackStack: Boolean) { val arguments = Bundle() arguments.putString(Extras.EXTRAS_BOARD_NAME, board.name) arguments.putString(Extras.EXTRAS_BOARD_TITLE, board.title) arguments.putBoolean(Extras.EXTRAS_OPTIONS_MENU_ENABLED, false) val fragment = PostItemsListFragment() fragment.arguments = arguments val fm = supportFragmentManager val ft = fm.beginTransaction() val catalogItemsFragment = fm.findFragmentByTag(TAG_POST_LIST) if (catalogItemsFragment != null) { ft.remove(catalogItemsFragment) } ft.replace(R.id.postitem_list, fragment, TAG_POST_LIST) if (saveBackStack) { ft.addToBackStack(null) } ft.commit() listFragment = fragment setFabVisibility(fragment.showFab()) } override fun onGalleryMenuItemClick(boardPath: String, threadId: Long) { start(this, GalleryActivity2.GALLERY_TYPE_GRID, 0, boardPath, threadId, LongArray(0)) } override fun setExpandedToolbar(expanded: Boolean, animate: Boolean) { // no op } override fun onPostItemClick(v: View?, posts: List<ChanPost>, position: Int, boardTitle: String, boardName: String, threadId: Long) { openThread(posts, position, boardName, boardTitle, threadId) } private fun openThread(posts: List<ChanPost>, position: Int, boardName: String, boardTitle: String, threadId: Long) { this.boardName = boardName this.boardTitle = boardTitle val threadDetailFragment = if (posts.size > position) { ThreadDetailFragment.newInstance(posts[position].no, boardName, boardTitle, posts[position], true, false) } else { ThreadDetailFragment.newInstance(threadId, boardName, boardTitle, null, true, false) } val fm = supportFragmentManager val ft = fm.beginTransaction() ft.replace(R.id.postitem_detail, threadDetailFragment, TAG_THREAD_DETAIL) ft.commit() panelLayout?.closePane() detailFragment = threadDetailFragment } override fun onBackPressed() { if (panelLayout?.isOpen == true) { if (listFragment is HistoryFragment) { val fm = supportFragmentManager val ft = fm.beginTransaction() ft.remove(listFragment as HistoryFragment).commit() } listFragment = boardsFragment super.onBackPressed() listFragment?.initMenu() } else { panelLayout?.openPane() } } override fun onHistoryItemClicked(boardName: String, threadId: Long, boardTitle: String, position: Int, watched: Boolean) { this.boardName = boardName this.boardTitle = boardTitle val fm = supportFragmentManager val ft = fm.beginTransaction() val threadDetailFragment = ThreadDetailFragment.newInstance(threadId, boardName, boardTitle, null, false, false) ft.replace(R.id.postitem_detail, threadDetailFragment, TAG_THREAD_DETAIL) ft.commit() if (panelLayout?.isOpen == true) { panelLayout?.closePane() } detailFragment = threadDetailFragment } override fun openHistoryPage(watched: Boolean) { val fm = supportFragmentManager val ft = fm.beginTransaction() val saveBackStack = listFragment === boardsFragment val fragment = HistoryFragment.newInstance(watched) ft.replace(R.id.postitem_list, fragment, TAG_POST_LIST) if (saveBackStack) { ft.addToBackStack(null) } ft.commit() listFragment = fragment panelLayout?.openPane() } override fun onReplyClicked(boardName: String, threadId: Long, id: Long, replies: List<String>) { if (detailFragment is ReplyClickListener) { val frag = detailFragment as ReplyClickListener frag.onReplyClicked(boardName, threadId, id, replies) } } override fun onNewIntent(intent: Intent) { super.onNewIntent(intent) val page = intent.getStringExtra(Extras.OPEN_PAGE) if (!TextUtils.isEmpty(page)) { try { val pageEnum = Pages.valueOf(page!!) val watched: Boolean watched = pageEnum == Pages.BOOKMARKS openHistoryPage(watched) } catch (e: Exception) { } } } companion object { const val BOARD_LIST_ID = 0 const val BOOKMARKS_ID = 1 const val HISTORY_ID = 2 private const val TAG_BOARD_LIST = "board_list_fragment" private const val TAG_POST_LIST = "post_list_fragment" private const val TAG_THREAD_DETAIL = "thread_detail_fragment" } }
apache-2.0
112e2fc160599bd423209b6d8ab3af7d
38.398754
164
0.628815
4.764883
false
false
false
false
ffc-nectec/FFC
ffc/src/main/kotlin/ffc/app/health/service/HealthCareServiceAdapter.kt
1
5968
package ffc.app.health.service import android.support.annotation.DrawableRes import android.support.annotation.StringRes 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.ImageButton import android.widget.ImageView import android.widget.TextView import com.felipecsl.asymmetricgridview.AsymmetricRecyclerView import ffc.android.drawable import ffc.android.getString import ffc.android.gone import ffc.android.onClick import ffc.android.visible import ffc.app.R import ffc.app.photo.asymmetric.bind import ffc.app.util.AdapterClickListener import ffc.app.util.datetime.toBuddistString import ffc.app.util.takeIfNotEmpty import ffc.app.util.takeIfNotNullOrBlank import ffc.app.util.timeago.toTimeAgo import ffc.app.util.value.Value import ffc.app.util.value.ValueAdapter import ffc.entity.Lang import ffc.entity.Lookup import ffc.entity.healthcare.CommunityService import ffc.entity.healthcare.Diagnosis import ffc.entity.healthcare.HealthCareService import ffc.entity.healthcare.HomeVisit import ffc.entity.healthcare.SpecialPP import org.jetbrains.anko.find import org.joda.time.LocalDate class HealthCareServiceAdapter( val services: List<HealthCareService>, val limit: Int = 10, onClickDsl: AdapterClickListener<HealthCareService>.() -> Unit ) : RecyclerView.Adapter<HealthCareServiceViewHolder>() { private val listener = AdapterClickListener<HealthCareService>().apply(onClickDsl) override fun onCreateViewHolder(parent: ViewGroup, type: Int): HealthCareServiceViewHolder { val view = LayoutInflater.from(parent.context).inflate(R.layout.hs_service_item, parent, false) return HealthCareServiceViewHolder(view) } override fun getItemCount() = if (services.size > limit) limit else services.size override fun onBindViewHolder(holder: HealthCareServiceViewHolder, position: Int) { holder.bind(services[position]) holder.itemView.onClick { listener.onItemClick!!.invoke(holder.itemView, services[position]) } listener.bindOnViewClick(holder.itemView, services[position], holder.editButton) } } class HealthCareServiceViewHolder(view: View) : RecyclerView.ViewHolder(view) { private val icon = view.find<ImageView>(R.id.serviceIconView) private val title = view.find<TextView>(R.id.serviceTitleView) private val date = view.find<TextView>(R.id.serviceDateView) private val detailView = view.find<RecyclerView>(R.id.detailView) private val photos = view.find<AsymmetricRecyclerView>(R.id.photos) val editButton = view.find<ImageButton>(R.id.editButton) init { detailView.layoutManager = LinearLayoutManager(itemView.context) } private val HealthCareService.isEditable: Boolean get() = time.toLocalDate().isEqual(LocalDate.now()) fun bind(services: HealthCareService) { with(services) { date.text = services.time.toTimeAgo() val type = typeOf(services) title.text = getString(type.titleRes) icon.setImageDrawable(itemView.context.drawable(type.iconRes)) photos.bind(photosUrl) detailView.adapter = ValueAdapter(toValue(), ValueAdapter.Style.SMALL, true) if (type == ServiceType.HOME_VISIT && isEditable) { editButton.visible() } else { editButton.gone() } } } private fun typeOf(services: HealthCareService): ServiceType { return when { services.specialPPs.isNotEmpty() -> ServiceType.SPECIAL_PP services.communityServices.isNotEmpty() -> { if (services.communityServices.firstOrNull { it is HomeVisit } != null) ServiceType.HOME_VISIT else ServiceType.COMMUNITY_SERVICE } services.ncdScreen != null -> ServiceType.NCD_SCREENING else -> ServiceType.SERVICE } } enum class ServiceType( @DrawableRes val iconRes: Int = R.drawable.ic_stethoscope_color_24dp, @StringRes val titleRes: Int = R.string.general_service ) { SERVICE, NCD_SCREENING(R.drawable.ic_loupe_color_24dp, R.string.ncd_screen), HOME_VISIT(R.drawable.ic_home_visit_color_24dp, R.string.home_visit), COMMUNITY_SERVICE(R.drawable.ic_home_visit_color_24dp, R.string.community_service), SPECIAL_PP(R.drawable.ic_shield_color_24dp, R.string.special_pp) } } private fun HealthCareService.toValue(): List<Value> { val values = mutableListOf<Value>() syntom.takeIfNotNullOrBlank()?.let { values.add(Value("อาการเบื้องต้น", it)) } nextAppoint?.let { values.add(Value("นัดครั้งต่อไป", it.toBuddistString())) } diagnosises.toValue().takeIfNotEmpty()?.let { values.addAll(it) } specialPPs.toSpecialPpValues().takeIfNotEmpty()?.let { values.addAll(it) } communityServices.toCommunityServiceValues().takeIfNotEmpty()?.let { values.addAll(it) } suggestion.takeIfNotNullOrBlank()?.let { values.add(Value("คำแนะนำ", it)) } note.takeIfNotNullOrBlank()?.let { values.add(Value("บันทึก", it)) } return values } private fun List<SpecialPP>.toSpecialPpValues(): List<Value> { return map { Value("ส่งเสริมป้องกัน", "· ${it.ppType.nameTh}") } } private fun List<CommunityService>.toCommunityServiceValues(): List<Value> { return map { Value("บริการชุมชน", "· ${it.serviceType.nameTh}") } } private fun List<Diagnosis>.toValue(): List<Value> { return sortedBy { it.dxType }.map { Value("วินิจฉัย", "· ${it.disease.nameTh}") } } val Lookup.nameTh: String get() = translation[Lang.th].takeIfNotNullOrBlank() ?: name
apache-2.0
1039da83ead762ad2981a6656d622306
39.117241
103
0.71291
3.745654
false
false
false
false
sugnakys/UsbSerialConsole
UsbSerialConsole/app/src/main/java/jp/sugnakys/usbserialconsole/presentation/home/HomeFragment.kt
1
7815
package jp.sugnakys.usbserialconsole.presentation.home import android.graphics.Color import android.graphics.drawable.ColorDrawable import android.os.Bundle import android.view.LayoutInflater import android.view.Menu import android.view.MenuInflater import android.view.MenuItem import android.view.View import android.view.ViewGroup import android.widget.Toast import androidx.core.net.toUri import androidx.core.widget.addTextChangedListener import androidx.fragment.app.Fragment import androidx.fragment.app.viewModels import androidx.navigation.fragment.findNavController import androidx.recyclerview.widget.RecyclerView import androidx.recyclerview.widget.RecyclerView.OnScrollListener import androidx.recyclerview.widget.RecyclerView.SCROLL_STATE_DRAGGING import com.google.android.material.snackbar.Snackbar import dagger.hilt.android.AndroidEntryPoint import java.io.File import java.util.Date import javax.inject.Inject import jp.sugnakys.usbserialconsole.R import jp.sugnakys.usbserialconsole.databinding.FragmentHomeBinding import jp.sugnakys.usbserialconsole.preference.DefaultPreference import jp.sugnakys.usbserialconsole.presentation.log.LogViewFragmentArgs @AndroidEntryPoint class HomeFragment : Fragment() { @Inject lateinit var preference: DefaultPreference private val viewModel by viewModels<HomeViewModel>() private lateinit var binding: FragmentHomeBinding private var isAutoScroll = true override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { binding = FragmentHomeBinding.inflate(inflater, container, false) return binding.root } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setHasOptionsMenu(true) } override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { inflater.inflate(R.menu.menu_main, menu) } override fun onPrepareOptionsMenu(menu: Menu) { val item = menu.findItem(R.id.action_connect) item.isEnabled = viewModel.isUSBReady item.title = if (viewModel.isConnect.value == true) { getString(R.string.action_disconnect) } else { getString(R.string.action_connect) } super.onPrepareOptionsMenu(menu) } override fun onOptionsItemSelected(item: MenuItem): Boolean { return when (item.itemId) { R.id.action_connect -> { if (viewModel.isConnect.value == true) { viewModel.changeConnection(false) Toast.makeText( requireContext(), getString(R.string.stop_connection), Toast.LENGTH_SHORT ).show() } else { viewModel.changeConnection(true) Toast.makeText( requireContext(), getString(R.string.start_connection), Toast.LENGTH_SHORT ).show() } true } R.id.action_clear_log -> { viewModel.clearReceivedMessage() true } R.id.action_save_log -> { val fileName = viewModel.getFileName(Date(System.currentTimeMillis())) val dirName = viewModel.getLogDir() val targetFile = File(dirName, fileName) if (viewModel.writeToFile( file = targetFile, isTimestamp = preference.timestampVisibility ) ) { val snackBar = Snackbar.make( requireContext(), binding.mainLayout, "${requireContext().getString(R.string.action_save_log)} : $fileName", Snackbar.LENGTH_LONG ) snackBar.setAction(R.string.open) { val args = LogViewFragmentArgs(targetFile.toUri().toString()).toBundle() findNavController() .navigate( R.id.action_homeFragment_to_logViewFragment, args ) } snackBar.show() } true } R.id.action_settings -> { findNavController().navigate(R.id.action_homeFragment_to_settingsFragment) true } R.id.action_log_list -> { findNavController().navigate(R.id.action_homeFragment_to_logListFragment) true } else -> false } } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) binding.lifecycleOwner = viewLifecycleOwner binding.viewmodel = viewModel setDefaultColor() val adapter = LogViewListAdapter(preference) binding.receivedMsgView.adapter = adapter binding.receivedMsgView.itemAnimator = null binding.receivedMsgView.addOnScrollListener(object : OnScrollListener() { override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) { super.onScrollStateChanged(recyclerView, newState) if (newState == SCROLL_STATE_DRAGGING) { isAutoScroll = false } } override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) { super.onScrolled(recyclerView, dx, dy) if (!recyclerView.canScrollVertically(1)) { isAutoScroll = true } } }) binding.sendMsgView.addTextChangedListener { text -> binding.sendBtn.isEnabled = text?.isNotEmpty() ?: false } binding.sendBtn.setOnClickListener { viewModel.sendMessage(binding.sendMsgView.text.toString()) binding.sendMsgView.text.clear() } viewModel.receivedMessage.observe(viewLifecycleOwner, { adapter.submitList(it) if (isAutoScroll) { binding.receivedMsgView.scrollToPosition(adapter.itemCount - 1) } }) binding.sendViewLayout.visibility = if (preference.sendFormVisibility) { View.VISIBLE } else { View.GONE } preference.colorConsoleBackground?.let { binding.mainLayout.setBackgroundColor(it) } preference.colorConsoleText?.let { binding.sendMsgView.setTextColor(it) } } private fun setDefaultColor() { if (preference.colorConsoleBackgroundDefault == null) { var defaultBackgroundColor = Color.TRANSPARENT val background = binding.mainLayout.background if (background is ColorDrawable) { defaultBackgroundColor = background.color } preference.colorConsoleBackgroundDefault = defaultBackgroundColor if (preference.colorConsoleBackground == null) { preference.colorConsoleBackground = preference.colorConsoleBackgroundDefault } } if (preference.colorConsoleTextDefault == null) { val defaultTextColor = binding.sendMsgView.textColors.defaultColor preference.colorConsoleTextDefault = defaultTextColor if (preference.colorConsoleText == null) { preference.colorConsoleText = preference.colorConsoleTextDefault } } } }
mit
a7b7ddffd91304567d128ce3e3f99e52
35.353488
96
0.601536
5.442201
false
false
false
false
panpf/sketch
sketch/src/androidTest/java/com/github/panpf/sketch/test/http/HttpHeadersTest.kt
1
11263
/* * Copyright (C) 2022 panpf <panpfpanpf@outlook.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.panpf.sketch.test.http import androidx.test.ext.junit.runners.AndroidJUnit4 import com.github.panpf.sketch.http.HttpHeaders import com.github.panpf.sketch.http.isNotEmpty import com.github.panpf.sketch.http.merged import org.junit.Assert import org.junit.Test import org.junit.runner.RunWith @RunWith(AndroidJUnit4::class) class HttpHeadersTest { @Test fun testNewBuilder() { val httpHeaders = HttpHeaders.Builder().apply { set("key1", "value1") set("key2", "value2") add("key3", "value3") add("key3", "value31") }.build() Assert.assertEquals(httpHeaders, httpHeaders.newBuilder().build()) Assert.assertNotEquals(httpHeaders, httpHeaders.newBuilder { add("key3", "value32") }.build()) Assert.assertEquals(httpHeaders, httpHeaders.newHttpHeaders()) Assert.assertNotEquals(httpHeaders, httpHeaders.newHttpHeaders() { add("key3", "value32") }) } @Test fun testSizeAndCount() { HttpHeaders.Builder().build().apply { Assert.assertEquals(0, size) Assert.assertEquals(0, addSize) Assert.assertEquals(0, setSize) } HttpHeaders.Builder().apply { set("key1", "value1") }.build().apply { Assert.assertEquals(1, size) Assert.assertEquals(0, addSize) Assert.assertEquals(1, setSize) } HttpHeaders.Builder().apply { set("key1", "value1") set("key2", "value2") set("key1", "value11") add("key3", "value3") add("key3", "value31") }.build().apply { Assert.assertEquals(4, size) Assert.assertEquals(2, addSize) Assert.assertEquals(2, setSize) } } @Test fun testIsEmptyAndIsNotEmpty() { HttpHeaders.Builder().build().apply { Assert.assertTrue(isEmpty()) Assert.assertFalse(isNotEmpty()) } HttpHeaders.Builder().apply { set("key1", "value1") }.build().apply { Assert.assertFalse(isEmpty()) Assert.assertTrue(isNotEmpty()) } HttpHeaders.Builder().apply { add("key1", "value1") }.build().apply { Assert.assertFalse(isEmpty()) Assert.assertTrue(isNotEmpty()) } HttpHeaders.Builder().apply { set("key1", "value1") add("key2", "value2") }.build().apply { Assert.assertFalse(isEmpty()) Assert.assertTrue(isNotEmpty()) } } @Test fun testAddSetGetRemove() { HttpHeaders.Builder().build().apply { Assert.assertNull(getSet("key1")) Assert.assertNull(getAdd("key2")) } HttpHeaders.Builder().apply { set("key1", "value1") }.build().apply { Assert.assertEquals("value1", getSet("key1")) Assert.assertNull(getAdd("key2")) } HttpHeaders.Builder().apply { add("key2", "value2") }.build().apply { Assert.assertNull(getSet("key1")) Assert.assertEquals(listOf("value2"), getAdd("key2")) } HttpHeaders.Builder().apply { set("key1", "value1") add("key2", "value2") }.build().apply { Assert.assertEquals("value1", getSet("key1")) Assert.assertEquals(listOf("value2"), getAdd("key2")) } // key conflict HttpHeaders.Builder().apply { set("key1", "value1") set("key1", "value11") add("key2", "value2") add("key2", "value21") }.build().apply { Assert.assertEquals("value11", getSet("key1")) Assert.assertEquals(listOf("value2", "value21"), getAdd("key2")) } // key conflict on add set HttpHeaders.Builder().apply { set("key1", "value1") add("key1", "value11") }.build().apply { Assert.assertNull(getSet("key1")) Assert.assertEquals(listOf("value11"), getAdd("key1")) } HttpHeaders.Builder().apply { add("key1", "value11") set("key1", "value1") }.build().apply { Assert.assertEquals("value1", getSet("key1")) Assert.assertNull(getAdd("key1")) } // remove HttpHeaders.Builder().apply { set("key1", "value1") add("key2", "value2") }.build().apply { Assert.assertEquals("value1", getSet("key1")) Assert.assertEquals(listOf("value2"), getAdd("key2")) }.newHttpHeaders { removeAll("key1") }.apply { Assert.assertNull(getSet("key1")) Assert.assertEquals(listOf("value2"), getAdd("key2")) } HttpHeaders.Builder().apply { set("key1", "value1") add("key2", "value2") }.build().apply { Assert.assertEquals("value1", getSet("key1")) Assert.assertEquals(listOf("value2"), getAdd("key2")) }.newHttpHeaders { removeAll("key2") }.apply { Assert.assertEquals("value1", getSet("key1")) Assert.assertNull(getAdd("key2")) } } @Test fun testEqualsAndHashCode() { val element1 = HttpHeaders.Builder().apply { set("key1", "value1") add("key2", "value2") }.build() val element11 = HttpHeaders.Builder().apply { set("key1", "value1") add("key2", "value2") }.build() val element2 = HttpHeaders.Builder().apply { set("key1", "value1") add("key3", "value3") }.build() val element3 = HttpHeaders.Builder().apply { set("key3", "value3") add("key2", "value2") }.build() Assert.assertNotSame(element1, element11) Assert.assertNotSame(element1, element2) Assert.assertNotSame(element1, element3) Assert.assertNotSame(element2, element11) Assert.assertNotSame(element2, element3) Assert.assertEquals(element1, element1) Assert.assertEquals(element1, element11) Assert.assertNotEquals(element1, element2) Assert.assertNotEquals(element1, element3) Assert.assertNotEquals(element2, element11) Assert.assertNotEquals(element2, element3) Assert.assertNotEquals(element1, null) Assert.assertNotEquals(element1, Any()) Assert.assertEquals(element1.hashCode(), element1.hashCode()) Assert.assertEquals(element1.hashCode(), element11.hashCode()) Assert.assertNotEquals(element1.hashCode(), element2.hashCode()) Assert.assertNotEquals(element1.hashCode(), element3.hashCode()) Assert.assertNotEquals(element2.hashCode(), element11.hashCode()) Assert.assertNotEquals(element2.hashCode(), element3.hashCode()) } @Test fun testToString() { HttpHeaders.Builder().build().apply { Assert.assertEquals("HttpHeaders(sets=[],adds=[])", toString()) } HttpHeaders.Builder().apply { set("key1", "value1") add("key2", "value2") }.build().apply { Assert.assertEquals("HttpHeaders(sets=[key1:value1],adds=[key2:value2])", toString()) } HttpHeaders.Builder().apply { set("key1", "value1") add("key2", "value2") add("key2", "value21") }.build().apply { Assert.assertEquals( "HttpHeaders(sets=[key1:value1],adds=[key2:value2,key2:value21])", toString() ) } } @Test fun testMerged() { val httpHeaders0 = HttpHeaders.Builder().build().apply { Assert.assertEquals("HttpHeaders(sets=[],adds=[])", toString()) } val httpHeaders1 = HttpHeaders.Builder().apply { set("set1", "setValue1") add("add1", "addValue1") }.build().apply { Assert.assertEquals( "HttpHeaders(sets=[set1:setValue1],adds=[add1:addValue1])", toString() ) } val httpHeaders11 = HttpHeaders.Builder().apply { set("set1", "setValue11") add("add1", "addValue11") }.build().apply { Assert.assertEquals( "HttpHeaders(sets=[set1:setValue11],adds=[add1:addValue11])", toString() ) } val httpHeaders2 = HttpHeaders.Builder().apply { set("set21", "setValue21") set("set22", "setValue22") add("add21", "addValue21") add("add22", "addValue22") }.build().apply { Assert.assertEquals( "HttpHeaders(sets=[set21:setValue21,set22:setValue22],adds=[add21:addValue21,add22:addValue22])", toString() ) } httpHeaders0.merged(httpHeaders0).apply { Assert.assertEquals("HttpHeaders(sets=[],adds=[])", toString()) } httpHeaders0.merged(httpHeaders1).apply { Assert.assertEquals( "HttpHeaders(sets=[set1:setValue1],adds=[add1:addValue1])", toString() ) } httpHeaders0.merged(httpHeaders2).apply { Assert.assertEquals( "HttpHeaders(sets=[set21:setValue21,set22:setValue22],adds=[add21:addValue21,add22:addValue22])", toString() ) } httpHeaders1.merged(httpHeaders2).apply { Assert.assertEquals( "HttpHeaders(sets=[set1:setValue1,set21:setValue21,set22:setValue22],adds=[add1:addValue1,add21:addValue21,add22:addValue22])", toString() ) } httpHeaders1.merged(httpHeaders11).apply { Assert.assertEquals( "HttpHeaders(sets=[set1:setValue1],adds=[add1:addValue1,add1:addValue11])", toString() ) } httpHeaders11.merged(httpHeaders1).apply { Assert.assertEquals( "HttpHeaders(sets=[set1:setValue11],adds=[add1:addValue11,add1:addValue1])", toString() ) } httpHeaders1.merged(null).apply { Assert.assertSame(httpHeaders1, this) } null.merged(httpHeaders1).apply { Assert.assertSame(httpHeaders1, this) } } }
apache-2.0
ef1b135eea97c70a60b004b445baaded
32.227139
143
0.554559
4.399609
false
true
false
false
lare96/luna
plugins/api/predef/EventPredef.kt
1
4009
package api.predef import api.event.InterceptBy import api.event.InterceptUseItem import api.event.Matcher import io.luna.game.event.Event import io.luna.game.event.EventListener import io.luna.game.event.impl.ButtonClickEvent import io.luna.game.event.impl.CommandEvent import io.luna.game.event.impl.ItemClickEvent.* import io.luna.game.event.impl.ItemOnItemEvent import io.luna.game.event.impl.ItemOnObjectEvent import io.luna.game.event.impl.NpcClickEvent.* import io.luna.game.event.impl.ObjectClickEvent.* import io.luna.game.model.mob.PlayerRights import java.util.* import kotlin.reflect.KClass /** * The player dedicated event listener consumer alias. */ private typealias EventAction<E> = E.() -> Unit /** * The command key, used to match [CommandEvent]s. */ class CommandKey(val name: String, val rights: PlayerRights) { override fun hashCode() = Objects.hash(name) override fun equals(other: Any?) = when (other) { is CommandKey -> name == other.name else -> false } } /** * The main event interception function. Forwards to [InterceptBy]. */ fun <E : Event> on(eventClass: KClass<E>) = InterceptBy(eventClass) /** * The main event interception function. Runs the action without any forwarding. */ fun <E : Event> on(eventClass: KClass<E>, action: EventAction<E>) { scriptListeners += EventListener(eventClass.java, action) } /** * The [ItemOnItemEvent] and [ItemOnObjectEvent] matcher function. Forwards to [InterceptUseItem]. */ fun useItem(id: Int) = InterceptUseItem(id) /** * The [ButtonClickEvent] matcher function. */ fun button(id: Int, action: EventAction<ButtonClickEvent>) = Matcher.get<ButtonClickEvent, Int>().set(id, action) /** The [NpcFirstClickEvent] matcher function.*/ fun npc1(id: Int, action: EventAction<NpcFirstClickEvent>) = Matcher.get<NpcFirstClickEvent, Int>().set(id, action) /** The [NpcSecondClickEvent] matcher function.*/ fun npc2(id: Int, action: EventAction<NpcSecondClickEvent>) = Matcher.get<NpcSecondClickEvent, Int>().set(id, action) /** The [NpcThirdClickEvent] matcher function.*/ fun npc3(id: Int, action: EventAction<NpcThirdClickEvent>) = Matcher.get<NpcThirdClickEvent, Int>().set(id, action) /** The [NpcFourthClickEvent] matcher function.*/ fun npc4(id: Int, action: EventAction<NpcFourthClickEvent>) = Matcher.get<NpcFourthClickEvent, Int>().set(id, action) /** The [NpcFifthClickEvent] matcher function.*/ fun npc5(id: Int, action: EventAction<NpcFifthClickEvent>) = Matcher.get<NpcFifthClickEvent, Int>().set(id, action) /** The [ItemFirstClickEvent] matcher function.*/ fun item1(id: Int, action: EventAction<ItemFirstClickEvent>) = Matcher.get<ItemFirstClickEvent, Int>().set(id, action) /** The [ItemSecondClickEvent] matcher function.*/ fun item2(id: Int, action: EventAction<ItemSecondClickEvent>) = Matcher.get<ItemSecondClickEvent, Int>().set(id, action) /** The [ItemThirdClickEvent] matcher function.*/ fun item3(id: Int, action: EventAction<ItemThirdClickEvent>) = Matcher.get<ItemThirdClickEvent, Int>().set(id, action) /** The [ItemFourthClickEvent] matcher function.*/ fun item4(id: Int, action: EventAction<ItemFourthClickEvent>) = Matcher.get<ItemFourthClickEvent, Int>().set(id, action) /** The [ItemFifthClickEvent] matcher function.*/ fun item5(id: Int, action: EventAction<ItemFifthClickEvent>) = Matcher.get<ItemFifthClickEvent, Int>().set(id, action) /** The [ObjectFirstClickEvent] matcher function.*/ fun object1(id: Int, action: EventAction<ObjectFirstClickEvent>) = Matcher.get<ObjectFirstClickEvent, Int>().set(id, action) /** The [ObjectSecondClickEvent] matcher function.*/ fun object2(id: Int, action: EventAction<ObjectSecondClickEvent>) = Matcher.get<ObjectSecondClickEvent, Int>().set(id, action) /** The [ObjectThirdClickEvent] matcher function.*/ fun object3(id: Int, action: EventAction<ObjectThirdClickEvent>) = Matcher.get<ObjectThirdClickEvent, Int>().set(id, action)
mit
81824c326fcdd3acbd0cd9e6cbea7111
34.803571
98
0.738339
3.618231
false
false
false
false
vondear/RxTools
RxKit/src/main/java/com/tamsiree/rxkit/RxConstants.kt
1
5506
package com.tamsiree.rxkit import java.io.File import java.text.DecimalFormat import java.util.* /** * @author tamsiree * @date 2017/1/13 */ object RxConstants { const val FAST_CLICK_TIME = 100 const val VIBRATE_TIME = 100 //----------------------------------------------------常用链接- start ------------------------------------------------------------ /** * RxTool的Github地址 */ const val URL_RXTOOL = "https://github.com/tamsiree/RxTool" /** * 百度文字搜索 */ const val URL_BAIDU_SEARCH = "http://www.baidu.com/s?wd=" /** * ACFUN */ const val URL_ACFUN = "http://www.acfun.tv/" const val URL_JPG_TO_FONT = "http://ku.cndesign.com/pic/" //===================================================常用链接== end ============================================================== const val URL_BORING_PICTURE = "http://jandan.net/?oxwlxojflwblxbsapi=jandan.get_pic_comments&page=" const val URL_PERI_PICTURE = "http://jandan.net/?oxwlxojflwblxbsapi=jandan.get_ooxx_comments&page=" const val URL_JOKE_MUSIC = "http://route.showapi.com/255-1?type=31&showapi_appid=20569&showapi_sign=0707a6bfb3e842fb8c8aa450012d9756&page=" const val SP_MADE_CODE = "MADE_CODE" //==========================================煎蛋 API end========================================= const val SP_SCAN_CODE = "SCAN_CODE" //微信统一下单接口 const val WX_TOTAL_ORDER = "https://api.mch.weixin.qq.com/pay/unifiedorder" //------------------------------------------煎蛋 API start-------------------------------------- var URL_JOKE = "http://ic.snssdk.com/neihan/stream/mix/v1/?" + "mpic=1&essence=1" + "&content_type=-102" + "&message_cursor=-1" + "&bd_Stringitude=113.369569" + "&bd_latitude=23.149678" + "&bd_city=%E5%B9%BF%E5%B7%9E%E5%B8%82" + "&am_Stringitude=113.367846" + "&am_latitude=23.149878" + "&am_city=%E5%B9%BF%E5%B7%9E%E5%B8%82" + "&am_loc_time=1465213692154&count=30" + "&min_time=1465213700&screen_width=720&iid=4512422578" + "&device_id=17215021497" + "&ac=wifi" + "&channel=NHSQH5AN" + "&aid=7" + "&app_name=joke_essay" + "&version_code=431" + "&device_platform=android" + "&ssmix=a" + "&device_type=6s+Plus" + "&os_api=19" + "&os_version=4.4.2" + "&uuid=864394108025091" + "&openudid=80FA5B208E050000" + "&manifest_version_code=431" //高德地图APP 包名 const val GAODE_PACKAGE_NAME = "com.autonavi.minimap" //百度地图APP 包名 const val BAIDU_PACKAGE_NAME = "com.baidu.BaiduMap" /** * 速度格式化 */ val FORMAT_ONE = DecimalFormat("#.#") /** * 距离格式化 */ @JvmField val FORMAT_TWO = DecimalFormat("#.##") /** * 速度格式化 */ val FORMAT_THREE = DecimalFormat("#.###") //默认保存下载文件目录 val DOWNLOAD_DIR = RxFileTool.rootPath.toString() + File.separator + "Download" + File.separator + RxDeviceTool.appPackageName + File.separator //图片缓存路径 @JvmField val PICTURE_CACHE_PATH = RxFileTool.getCacheFolder(RxTool.getContext()).toString() + File.separator + "Picture" + File.separator + "Cache" + File.separator //图片原始路径 val PICTURE_ORIGIN_PATH = RxFileTool.rootPath.toString() + File.separator + RxDeviceTool.appPackageName + File.separator + "Picture" + File.separator + "Origin" + File.separator //图片压缩路径 val PICTURE_COMPRESS_PATH = RxFileTool.rootPath.toString() + File.separator + RxDeviceTool.appPackageName + File.separator + "Picture" + File.separator + "Compress" + File.separator //默认导出文件目录 val EXPORT_FILE_PATH = RxFileTool.rootPath.toString() + File.separator + RxDeviceTool.appPackageName + File.separator + "ExportFile" + File.separator //图片名称 val pictureName: String get() = RxTimeTool.getCurrentDateTime(DATE_FORMAT_LINK) + "_" + Random().nextInt(1000) + ".jpg" //Date格式 const val DATE_FORMAT_LINK = "yyyyMMddHHmmssSSS" //Date格式 常用 const val DATE_FORMAT_DETACH = "yyyy-MM-dd HH:mm:ss" const val DATE_FORMAT_DETACH_CN = "yyyy年MM月dd日 HH:mm:ss" const val DATE_FORMAT_DETACH_CN_SSS = "yyyy年MM月dd日 HH:mm:ss SSS" //Date格式 带毫秒 const val DATE_FORMAT_DETACH_SSS = "yyyy-MM-dd HH:mm:ss SSS" //时间格式 分钟:秒钟 一般用于视频时间显示 const val DATE_FORMAT_MM_SS = "mm:ss" // Performance testing notes (JDK 1.4, Jul03, scolebourne) // Whitespace: // Character.isWhitespace() is faster than WHITESPACE.indexOf() // where WHITESPACE is a string of all whitespace characters // // Character access: // String.charAt(n) versus toCharArray(), then array[n] // String.charAt(n) is about 15% worse for a 10K string // They are about equal for a length 50 string // String.charAt(n) is about 4 times better for a length 3 string // String.charAt(n) is best bet overall // // Append: // String.concat about twice as fast as StringBuffer.append // (not sure who tested this) /** * A String for a space character. * * @since 3.2 */ const val SPACE = " " }
apache-2.0
02fe767c1588910d9a1202a78074e17f
34.187919
185
0.567531
3.349521
false
false
false
false
wikimedia/apps-android-wikipedia
app/src/main/java/org/wikipedia/talk/NotificationDirectReplyHelper.kt
1
4823
package org.wikipedia.talk import android.app.NotificationManager import android.content.Context import android.os.Build import android.widget.Toast import androidx.core.app.NotificationCompat import androidx.core.app.NotificationManagerCompat import androidx.core.content.getSystemService import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers import io.reactivex.rxjava3.core.Observable import io.reactivex.rxjava3.schedulers.Schedulers import org.wikipedia.Constants import org.wikipedia.R import org.wikipedia.auth.AccountUtil import org.wikipedia.csrf.CsrfTokenClient import org.wikipedia.dataclient.ServiceFactory import org.wikipedia.dataclient.WikiSite import org.wikipedia.dataclient.okhttp.HttpStatusException import org.wikipedia.edit.Edit import org.wikipedia.page.PageTitle import org.wikipedia.util.StringUtil import org.wikipedia.util.log.L import java.util.concurrent.TimeUnit object NotificationDirectReplyHelper { const val DIRECT_REPLY_EDIT_COMMENT = "#directreply-1.0" // TODO: update this to use DiscussionTools API, and enable. fun handleReply(context: Context, wiki: WikiSite, title: PageTitle, replyText: String, replyTo: String, notificationId: Int) { Toast.makeText(context, context.getString(R.string.notifications_direct_reply_progress, replyTo), Toast.LENGTH_SHORT).show() Observable.zip(CsrfTokenClient.getToken(wiki).subscribeOn(Schedulers.io()), ServiceFactory.getRest(wiki).getTalkPage(title.prefixedText).subscribeOn(Schedulers.io())) { token, response -> Pair(token, response) }.subscribeOn(Schedulers.io()) .flatMap { pair -> val topic = pair.second.topics!!.find { it.id > 0 && it.html?.trim().orEmpty() == StringUtil.removeUnderscores(title.fragment) } if (topic == null || title.fragment.isNullOrEmpty()) { Observable.just(Edit()) } else { ServiceFactory.get(wiki).postEditSubmit( title.prefixedText, topic.id.toString(), null, DIRECT_REPLY_EDIT_COMMENT, if (AccountUtil.isLoggedIn) "user" else null, null, replyText, pair.second.revision, pair.first, null, null ) } } .subscribe({ if (it.edit?.editSucceeded == true) { waitForUpdatedRevision(context, wiki, title, it.edit.newRevId, notificationId) } else { fallBackToTalkPage(context, title) } }, { L.e(it) fallBackToTalkPage(context, title) }) } private fun waitForUpdatedRevision(context: Context, wiki: WikiSite, title: PageTitle, newRevision: Long, notificationId: Int) { ServiceFactory.getRest(wiki).getTalkPage(title.prefixedText) .delay(2, TimeUnit.SECONDS) .subscribeOn(Schedulers.io()) .map { if (it.revision < newRevision) { throw IllegalStateException() } it.revision } .retry(20) { (it is IllegalStateException) || (it is HttpStatusException && it.code == 404) } .observeOn(AndroidSchedulers.mainThread()) .doOnTerminate { cancelNotification(context, notificationId) } .subscribe({ // revisionForUndo = it Toast.makeText(context, R.string.notifications_direct_reply_success, Toast.LENGTH_LONG).show() }, { L.e(it) fallBackToTalkPage(context, title) }) } private fun fallBackToTalkPage(context: Context, title: PageTitle) { Toast.makeText(context, R.string.notifications_direct_reply_error, Toast.LENGTH_LONG).show() context.startActivity(TalkTopicsActivity.newIntent(context, title, Constants.InvokeSource.NOTIFICATION)) } private fun cancelNotification(context: Context, notificationId: Int) { if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.O) { return } context.getSystemService<NotificationManager>()?.activeNotifications?.find { it.id == notificationId }?.run { val n = NotificationCompat.Builder(context, this.notification) .setRemoteInputHistory(null) .setPriority(NotificationCompat.PRIORITY_MIN) .setVibrate(null) .setTimeoutAfter(1) .build() NotificationManagerCompat.from(context).notify(notificationId, n) } } }
apache-2.0
5060f4450340be79203b7b14328a527a
42.0625
132
0.618495
4.866801
false
false
false
false
slartus/4pdaClient-plus
app/src/main/java/org/softeg/slartus/forpdaplus/fragments/search/ForumsTreeDialogFragment.kt
1
9017
package org.softeg.slartus.forpdaplus.fragments.search import android.app.Dialog import android.content.Context import android.content.Intent import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.* import android.widget.AdapterView.OnItemClickListener import android.widget.AdapterView.OnItemSelectedListener import androidx.fragment.app.DialogFragment import com.afollestad.materialdialogs.MaterialDialog import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.disposables.Disposable import io.reactivex.schedulers.Schedulers import org.softeg.slartus.forpdaplus.MainActivity import org.softeg.slartus.forpdaplus.R import org.softeg.slartus.forpdaplus.classes.ForumsAdapter import org.softeg.slartus.forpdaplus.common.AppLog import org.softeg.slartus.forpdaplus.repositories.ForumsRepository import java.util.* /* * Created by slinkin on 24.04.2014. */ class ForumsTreeDialogFragment : DialogFragment() { private var m_ListView: ListView? = null private var m_Spinner: Spinner? = null private var m_ListViewAdapter: ForumsAdapter? = null private var m_SpinnerAdapter: SpinnerAdapter? = null private var m_Progress: View? = null private val m_Forums = ArrayList<CheckableForumItem>() override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { val inflater = activity!!.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater val view = inflater.inflate(R.layout.forums_tree_dialog_fragment, null as ViewGroup?)!! m_ListView = view.findViewById(android.R.id.list) initListView() m_Spinner = view.findViewById(R.id.selected_spinner) initSpinner() m_Progress = view.findViewById(R.id.progress) //dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE); return MaterialDialog.Builder(activity!!) .customView(view, false) .title(R.string.forum) .positiveText(R.string.accept) .negativeText(R.string.cancel) .onPositive { _, _ -> val intent = Intent() intent.putExtra( FORUM_IDS_KEY, m_ListViewAdapter!!.checkedIds.toTypedArray() ) targetFragment!!.onActivityResult( SearchSettingsDialogFragment.FORUMS_DIALOG_REQUEST, OK_RESULT, intent ) } .onNegative { _, _ -> targetFragment!!.onActivityResult( SearchSettingsDialogFragment.FORUMS_DIALOG_REQUEST, CANCEL_RESULT, null ) } .build() } private fun initListView() { m_ListView!!.isFastScrollEnabled = true m_ListViewAdapter = ForumsAdapter( activity, m_Forums ) m_ListView!!.adapter = m_ListViewAdapter m_ListView!!.onItemClickListener = OnItemClickListener { _, _, position, _ -> m_ListViewAdapter!!.toggleChecked(position) m_SpinnerAdapter!!.notifyDataSetChanged() } } private fun initSpinner() { m_SpinnerAdapter = SpinnerAdapter( activity, m_Forums ) m_Spinner!!.adapter = m_SpinnerAdapter m_Spinner!!.onItemSelectedListener = object : OnItemSelectedListener { override fun onItemSelected(adapterView: AdapterView<*>?, view: View, i: Int, l: Long) { if (l == 0L) return val item = m_SpinnerAdapter!!.getItem(l.toInt()) m_ListView!!.setSelection(m_ListViewAdapter!!.getPosition(item)) m_Spinner!!.setSelection(0) } override fun onNothingSelected(adapterView: AdapterView<*>?) {} } } private var dataSubscriber: Disposable? = null private fun subscribesData() { dataSubscriber?.dispose() setLoading(true) dataSubscriber = ForumsRepository.instance .forumsSubject .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .doOnSubscribe { setLoading(true) } .doAfterTerminate { setLoading(false) } .subscribe( { items -> deliveryResult(items) setLoading(false) }, { setLoading(false) AppLog.e(activity, it) } ) } override fun onPause() { super.onPause() dataSubscriber?.dispose() MainActivity.searchSettings = SearchSettingsDialogFragment.createDefaultSearchSettings() } override fun onResume() { super.onResume() subscribesData() } private fun deliveryResult(result: List<org.softeg.slartus.forpdaapi.Forum>) { m_Forums.clear() addForumCaptions( m_Forums, result, null, 0, Arrays.asList( *arguments!!.getStringArray( FORUM_IDS_KEY ) ) ) m_ListViewAdapter!!.notifyDataSetChanged() m_SpinnerAdapter!!.notifyDataSetChanged() } private fun setLoading(b: Boolean) { m_Progress!!.visibility = if (b) View.VISIBLE else View.GONE } private fun addForumCaptions( forums: ArrayList<CheckableForumItem>, forum: List<org.softeg.slartus.forpdaapi.Forum>, parentForum: org.softeg.slartus.forpdaapi.Forum?, level: Int, checkIds: Collection<String?> ) { if (parentForum == null) { forums.add(CheckableForumItem("all", ">> " + getString(R.string.all_forums)).apply { this.level = level IsChecked = checkIds.contains(this.Id) }) addForumCaptions( forums, forum, org.softeg.slartus.forpdaapi.Forum(null, ""), level + 1, checkIds ) } else { forum .filter { it.parentId == parentForum.id } .forEach { forums.add(CheckableForumItem(it.id, it.title).apply { this.level = level IsChecked = checkIds.contains(this.Id) }) addForumCaptions(forums, forum, it, level + 1, checkIds) } } } inner class SpinnerAdapter( context: Context?, private val mForums: ArrayList<CheckableForumItem> ) : BaseAdapter() { private val m_Inflater: LayoutInflater = LayoutInflater.from(context) override fun getCount(): Int { var c = 1 for (f in mForums) { if (f.IsChecked) c++ } return c } override fun getItem(i: Int): CheckableForumItem? { if (i == 0) { return CheckableForumItem("", getString(R.string.total) + ": " + (count - 1)) } var c = 1 for (f in mForums) { if (f.IsChecked && c == i) return f if (f.IsChecked) c++ } return null } override fun getItemId(i: Int): Long { return i.toLong() } override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View? { val holder: ViewHolder var rowView = convertView if (rowView == null) { rowView = m_Inflater.inflate(android.R.layout.simple_spinner_dropdown_item, null) holder = ViewHolder() assert(rowView != null) holder.text = rowView .findViewById(android.R.id.text1) rowView.tag = holder } else { holder = rowView.tag as ViewHolder } val item = getItem(position) holder.text!!.text = item?.Title return rowView } inner class ViewHolder { var text: TextView? = null } } companion object { const val IS_DIALOG_KEY = "IS_DIALOG_KEY" const val FORUM_IDS_KEY = "FORUM_IDS_KEY" const val OK_RESULT = 0 const val CANCEL_RESULT = 1 @JvmStatic fun newInstance( dialog: Boolean?, checkedForumIds: Collection<String?> ): ForumsTreeDialogFragment { val args = Bundle() args.putBoolean(IS_DIALOG_KEY, dialog!!) args.putStringArray(FORUM_IDS_KEY, checkedForumIds.toTypedArray()) val fragment = ForumsTreeDialogFragment() fragment.arguments = args return fragment } } }
apache-2.0
ac4a0121a3d928894c472e8f1ce8b4d7
33.551724
100
0.566929
5.001109
false
false
false
false
hannesa2/owncloud-android
owncloudDomain/src/main/java/com/owncloud/android/domain/sharing/shares/model/OCShare.kt
2
1932
/** * ownCloud Android client application * * @author David González Verdugo * Copyright (C) 2020 ownCloud GmbH. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.owncloud.android.domain.sharing.shares.model import android.os.Parcelable import kotlinx.parcelize.Parcelize @Parcelize data class OCShare( val id: Int? = null, val shareType: ShareType, val shareWith: String?, val path: String, val permissions: Int, val sharedDate: Long, val expirationDate: Long, val token: String?, val sharedWithDisplayName: String?, val sharedWithAdditionalInfo: String?, val isFolder: Boolean, val remoteId: String, var accountOwner: String = "", val name: String?, val shareLink: String? ) : Parcelable { val isPasswordProtected: Boolean get() = shareType == ShareType.PUBLIC_LINK && !shareWith.isNullOrEmpty() } /** * Enum for Share Type, with values: * -1 - Unknown * 0 - Shared by user * 1 - Shared by group * 3 - Shared by public link * 4 - Shared by e-mail * 5 - Shared by contact * 6 - Federated * * @author masensio */ enum class ShareType constructor(val value: Int) { UNKNOWN(-1), USER(0), GROUP(1), PUBLIC_LINK(3), EMAIL(4), CONTACT(5), FEDERATED(6); companion object { fun fromValue(value: Int) = values().firstOrNull { it.value == value } } }
gpl-2.0
5e68178a922ad6e006c47b514831c639
25.452055
80
0.683584
3.956967
false
false
false
false
AndroidX/androidx
compose/ui/ui-text/src/androidMain/kotlin/androidx/compose/ui/text/platform/AndroidTextPaint.android.kt
3
5267
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.ui.text.platform import android.text.TextPaint import androidx.annotation.VisibleForTesting import androidx.compose.ui.geometry.Size import androidx.compose.ui.geometry.isSpecified import androidx.compose.ui.graphics.Brush import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.Paint import androidx.compose.ui.graphics.PaintingStyle import androidx.compose.ui.graphics.ShaderBrush import androidx.compose.ui.graphics.Shadow import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.drawscope.DrawStyle import androidx.compose.ui.graphics.drawscope.Fill import androidx.compose.ui.graphics.drawscope.Stroke import androidx.compose.ui.graphics.isSpecified import androidx.compose.ui.graphics.toArgb import androidx.compose.ui.graphics.toComposePaint import androidx.compose.ui.text.platform.extensions.correctBlurRadius import androidx.compose.ui.text.style.TextDecoration import kotlin.math.roundToInt internal class AndroidTextPaint(flags: Int, density: Float) : TextPaint(flags) { init { this.density = density } // A wrapper to use Compose Paint APIs on this TextPaint private val composePaint: Paint = this.toComposePaint() private var textDecoration: TextDecoration = TextDecoration.None @VisibleForTesting(otherwise = VisibleForTesting.PRIVATE) internal var shadow: Shadow = Shadow.None private var drawStyle: DrawStyle? = null fun setTextDecoration(textDecoration: TextDecoration?) { if (textDecoration == null) return if (this.textDecoration != textDecoration) { this.textDecoration = textDecoration isUnderlineText = TextDecoration.Underline in this.textDecoration isStrikeThruText = TextDecoration.LineThrough in this.textDecoration } } fun setShadow(shadow: Shadow?) { if (shadow == null) return if (this.shadow != shadow) { this.shadow = shadow if (this.shadow == Shadow.None) { clearShadowLayer() } else { setShadowLayer( correctBlurRadius(this.shadow.blurRadius), this.shadow.offset.x, this.shadow.offset.y, this.shadow.color.toArgb() ) } } } fun setColor(color: Color) { color.toArgb() if (color.isSpecified) { composePaint.color = color composePaint.shader = null } } fun setBrush(brush: Brush?, size: Size, alpha: Float = Float.NaN) { // if size is unspecified and brush is not null, nothing should be done. // it basically means brush is given but size is not yet calculated at this time. if ((brush is SolidColor && brush.value.isSpecified) || (brush is ShaderBrush && size.isSpecified)) { // alpha is always applied even if Float.NaN is passed to applyTo function. // if it's actually Float.NaN, we simply send the current value brush.applyTo( size, composePaint, if (alpha.isNaN()) composePaint.alpha else alpha.coerceIn(0f, 1f) ) } else if (brush == null) { composePaint.shader = null } } fun setDrawStyle(drawStyle: DrawStyle?) { if (drawStyle == null) return if (this.drawStyle != drawStyle) { this.drawStyle = drawStyle when (drawStyle) { Fill -> { // Stroke properties such as strokeWidth, strokeMiter are not re-set because // Fill style should make those properties no-op. Next time the style is set // as Stroke, stroke properties get re-set as well. composePaint.style = PaintingStyle.Fill } is Stroke -> { composePaint.style = PaintingStyle.Stroke composePaint.strokeWidth = drawStyle.width composePaint.strokeMiterLimit = drawStyle.miter composePaint.strokeJoin = drawStyle.join composePaint.strokeCap = drawStyle.cap composePaint.pathEffect = drawStyle.pathEffect } } } } } /** * Accepts an alpha value in the range [0f, 1f] then maps to an integer value * in [0, 255] range. */ internal fun TextPaint.setAlpha(alpha: Float) { if (!alpha.isNaN()) { val alphaInt = alpha.coerceIn(0f, 1f).times(255).roundToInt() setAlpha(alphaInt) } }
apache-2.0
0a1fd01162ee987d924d22cb82436e3a
36.899281
96
0.647238
4.604021
false
false
false
false
takuji31/Dagger2Android
app/src/main/java/jp/takuji31/dagger2android/example/A.kt
1
633
package jp.takuji31.dagger2android.example import android.os.Bundle import jp.takuji31.dagger2android.lifecycle.ActivityLifecycle import javax.inject.Inject import javax.inject.Singleton /** * @author Takuji Nishibayashi */ @Singleton public class A @Inject constructor() : ActivityLifecycle { var onDestroyCalled = false var saved = false var restored = false override fun onSaveInstanceState(outState: Bundle) { saved = true } override fun onRestoreInstanceState(savedInstanceStete: Bundle) { restored = true } override fun onDestroy() { onDestroyCalled = true } }
apache-2.0
a2b86f94cca30c1b8af131503645524a
21.642857
69
0.720379
4.457746
false
false
false
false
Undin/intellij-rust
src/main/kotlin/org/rust/lang/core/macros/RsMacroDataWithHash.kt
2
3563
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.lang.core.macros import org.rust.lang.core.macros.errors.ResolveMacroWithoutPsiError import org.rust.lang.core.psi.RsFunction import org.rust.lang.core.psi.ext.RsMacroDefinitionBase import org.rust.lang.core.psi.ext.RsNamedElement import org.rust.lang.core.psi.ext.isProcMacroDef import org.rust.lang.core.psi.ext.procMacroName import org.rust.lang.core.resolve2.DeclMacro2DefInfo import org.rust.lang.core.resolve2.DeclMacroDefInfo import org.rust.lang.core.resolve2.MacroDefInfo import org.rust.lang.core.resolve2.ProcMacroDefInfo import org.rust.stdext.HashCode import org.rust.stdext.RsResult import org.rust.stdext.RsResult.Err import org.rust.stdext.RsResult.Ok class RsMacroDataWithHash<out T : RsMacroData>( val data: T, val bodyHash: HashCode? ) { fun mixHash(call: RsMacroCallDataWithHash): HashCode? { @Suppress("USELESS_CAST") // False-positive val callHash = when (data as RsMacroData) { is RsDeclMacroData -> call.bodyHash is RsProcMacroData -> call.hashWithEnv() is RsBuiltinMacroData -> call.bodyHash } return HashCode.mix(bodyHash ?: return null, callHash ?: return null) } companion object { fun fromPsi(def: RsNamedElement): RsMacroDataWithHash<*>? { return when { def is RsMacroDefinitionBase -> if (def.hasRustcBuiltinMacro) { RsBuiltinMacroData(def.name ?: return null).withHash() } else { RsMacroDataWithHash(RsDeclMacroData(def), def.bodyHash) } def is RsFunction && def.isProcMacroDef -> { val name = def.procMacroName ?: return null val procMacro = def.containingCrate.procMacroArtifact ?: return null val hash = HashCode.mix(procMacro.hash, HashCode.compute(name)) RsMacroDataWithHash(RsProcMacroData(name, procMacro), hash) } else -> null } } fun fromDefInfo(def: MacroDefInfo): RsResult<RsMacroDataWithHash<*>, ResolveMacroWithoutPsiError> { return when (def) { is DeclMacroDefInfo -> Ok( if (def.hasRustcBuiltinMacro) { RsBuiltinMacroData(def.path.name).withHash() } else { RsMacroDataWithHash(RsDeclMacroData(def.body), def.bodyHash) } ) is DeclMacro2DefInfo -> Ok( if (def.hasRustcBuiltinMacro) { RsBuiltinMacroData(def.path.name).withHash() } else { RsMacroDataWithHash(RsDeclMacroData(def.body), def.bodyHash) } ) is ProcMacroDefInfo -> { val name = def.path.name val procMacroArtifact = def.procMacroArtifact ?: return Err(ResolveMacroWithoutPsiError.NoProcMacroArtifact) if (def.kind.treatAsBuiltinAttr) { return Err(ResolveMacroWithoutPsiError.HardcodedProcMacroAttribute) } val hash = HashCode.mix(procMacroArtifact.hash, HashCode.compute(name)) Ok(RsMacroDataWithHash(RsProcMacroData(name, procMacroArtifact), hash)) } } } } }
mit
f08975aa273acf3edd3a6605906a9c18
41.416667
107
0.600056
4.437111
false
false
false
false
Senspark/ee-x
src/android/ad_mob/src/main/java/com/ee/internal/AdMobRewardedInterstitialAd.kt
1
5610
package com.ee.internal import android.app.Activity import androidx.annotation.AnyThread import com.ee.IFullScreenAd import com.ee.ILogger import com.ee.IMessageBridge import com.ee.Thread import com.ee.Utils import com.google.android.gms.ads.AdError import com.google.android.gms.ads.AdRequest import com.google.android.gms.ads.FullScreenContentCallback import com.google.android.gms.ads.LoadAdError import com.google.android.gms.ads.rewardedinterstitial.RewardedInterstitialAd import com.google.android.gms.ads.rewardedinterstitial.RewardedInterstitialAdLoadCallback import kotlinx.serialization.Serializable import java.util.concurrent.atomic.AtomicBoolean internal class AdMobRewardedInterstitialAd( private val _bridge: IMessageBridge, private val _logger: ILogger, private var _activity: Activity?, private val _adId: String) : IFullScreenAd { @Serializable @Suppress("unused") private class ErrorResponse( val code: Int, val message: String ) companion object { private val kTag = AdMobRewardedInterstitialAd::class.java.name } private val _messageHelper = MessageHelper("AdMobRewardedInterstitialAd", _adId) private val _helper = FullScreenAdHelper(_bridge, this, _messageHelper) private val _isLoaded = AtomicBoolean(false) private var _ad: RewardedInterstitialAd? = null private var _rewarded = false init { _logger.info("$kTag: constructor: adId = $_adId") registerHandlers() } override fun onCreate(activity: Activity) { _activity = activity } override fun onResume() { } override fun onPause() { } override fun onDestroy() { _activity = null } override fun destroy() { _logger.info("$kTag: destroy: adId = $_adId") deregisterHandlers() } @AnyThread private fun registerHandlers() { _helper.registerHandlers() } @AnyThread private fun deregisterHandlers() { _helper.deregisterHandlers() } override val isLoaded: Boolean @AnyThread get() = _isLoaded.get() @AnyThread override fun load() { Thread.runOnMainThread { _logger.debug("$kTag: ${this::load.name}: id = $_adId") val activity = _activity if (activity == null) { _bridge.callCpp(_messageHelper.onFailedToLoad, "Null activity") return@runOnMainThread } val showCallback = object : FullScreenContentCallback() { override fun onAdShowedFullScreenContent() { Thread.runOnMainThread { _logger.debug("$kTag: ${this::onAdShowedFullScreenContent.name}: id = $_adId") } } override fun onAdFailedToShowFullScreenContent(error: AdError) { Thread.runOnMainThread { _logger.debug("$kTag: ${this::onAdFailedToShowFullScreenContent.name}: id = $_adId message = ${error.message}") _isLoaded.set(false) _ad = null _bridge.callCpp(_messageHelper.onFailedToShow, ErrorResponse(error.code, error.message).serialize()) } } override fun onAdDismissedFullScreenContent() { Thread.runOnMainThread { _logger.debug("$kTag: ${this::onAdDismissedFullScreenContent.name}: id = $_adId") _isLoaded.set(false) _ad = null _bridge.callCpp(_messageHelper.onClosed, Utils.toString(_rewarded)) } } } val loadCallback = object : RewardedInterstitialAdLoadCallback() { override fun onAdLoaded(ad: RewardedInterstitialAd) { Thread.runOnMainThread { _logger.debug("$kTag: ${this::onAdLoaded.name}: id = $_adId") ad.fullScreenContentCallback = showCallback _isLoaded.set(true) _ad = ad _bridge.callCpp(_messageHelper.onLoaded) } } override fun onAdFailedToLoad(error: LoadAdError) { Thread.runOnMainThread { _logger.debug("$kTag: ${this::onAdFailedToLoad.name}: id = $_adId message = ${error.message} response = ${error.responseInfo ?: ""}") _bridge.callCpp(_messageHelper.onFailedToLoad, ErrorResponse(error.code, error.message).serialize()) } } } RewardedInterstitialAd.load(activity, _adId, AdRequest.Builder().build(), loadCallback) } } @AnyThread override fun show() { Thread.runOnMainThread { _logger.debug("$kTag: ${this::show.name}: id = $_adId") val ad = _ad if (ad == null) { _bridge.callCpp(_messageHelper.onFailedToShow, ErrorResponse(-1, "Null ad").serialize()) return@runOnMainThread } val activity = _activity if (activity == null) { _bridge.callCpp(_messageHelper.onFailedToShow, ErrorResponse(-1, "Null activity").serialize()) return@runOnMainThread } _rewarded = false ad.show(activity) { Thread.runOnMainThread { _rewarded = true } } } } }
mit
fcd803b75d3eb77b223f06facd4ee37f
34.738854
157
0.576649
5.022381
false
false
false
false
androidx/androidx
metrics/integration-tests/janktest/src/main/java/androidx/metrics/performance/janktest/MessageListFragment.kt
3
2813
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.metrics.performance.janktest import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.metrics.performance.PerformanceMetricsState import androidx.recyclerview.widget.RecyclerView /** * A simple [Fragment] subclass as the second destination in the navigation. */ class MessageListFragment : Fragment() { private val metricsStateCache = MetricsStateCache() val messageList: Array<String> = Array<String>(100) { "Message #" + it } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { return inflater.inflate(R.layout.fragment_message_list, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { val recyclerView = view.findViewById<RecyclerView>(R.id.MessageList) recyclerView.addOnAttachStateChangeListener(metricsStateCache) recyclerView.adapter = MessageListAdapter(messageList) recyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() { override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) { if (newState == RecyclerView.SCROLL_STATE_DRAGGING) { metricsStateCache.state?.putState("RecyclerView", "Dragging") } else if (newState == RecyclerView.SCROLL_STATE_SETTLING) { metricsStateCache.state?.putState("RecyclerView", "Settling") } else { metricsStateCache.state?.removeState("RecyclerView") } } }) } class MetricsStateCache : View.OnAttachStateChangeListener { private var holder: PerformanceMetricsState.Holder? = null val state: PerformanceMetricsState? get() = holder?.state override fun onViewAttachedToWindow(view: View) { holder = PerformanceMetricsState.getHolderForHierarchy(view) } override fun onViewDetachedFromWindow(view: View) { holder = null } } }
apache-2.0
055a16a36c501ef04c762a97d3ef027a
35.545455
90
0.691433
4.978761
false
false
false
false
dracula/jetbrains
src/main/kotlin/com/draculatheme/jetbrains/notifications/DraculaNotification.kt
1
2832
package com.draculatheme.jetbrains.notifications import com.draculatheme.jetbrains.DraculaMeta import com.intellij.ide.BrowserUtil import com.intellij.notification.Notification import com.intellij.notification.NotificationAction import com.intellij.notification.NotificationGroupManager import com.intellij.notification.NotificationType import com.intellij.openapi.project.Project import com.intellij.openapi.util.IconLoader import org.intellij.lang.annotations.Language object DraculaNotification { @Language("HTML") private val whatsNew = """ <ul> <li>Fix notification message layout & typo</li> </ul> """.trimIndent() @Language("HTML") private val releaseNote = """ <p>What's New?</p> $whatsNew """.trimIndent() @Language("HTML") private val welcomeMessage = """ <p>Thank you for choosing Dracula.</p> """.trimIndent() private const val notificationGroupId = "Dracula Theme" @JvmField val notificationIcon = IconLoader.getIcon("/icons/dracula-logo.svg", javaClass) private const val changelogLink = "https://github.com/dracula/jetbrains/blob/master/CHANGELOG.md" private const val draculaProLink = "https://gumroad.com/a/477820019" private const val githubRepoLink = "https://github.com/dracula/jetbrains" fun notifyReleaseNote(project: Project) { val title = "Dracula Theme updated to v${DraculaMeta.currentVersion}" val notification = NotificationGroupManager.getInstance().getNotificationGroup(notificationGroupId) .createNotification(title, releaseNote, NotificationType.INFORMATION) addNotificationActions(notification) notification.icon = notificationIcon notification.notify(project) } fun notifyFirstlyDownloaded(project: Project) { val title = "Dracula Theme is installed" val notification = NotificationGroupManager.getInstance().getNotificationGroup(notificationGroupId) .createNotification(title, welcomeMessage, NotificationType.INFORMATION) addNotificationActions(notification) notification.icon = notificationIcon notification.notify(project) } private fun addNotificationActions(notification: Notification) { val actionChangelog = NotificationAction.createSimple("Changelog") { BrowserUtil.browse(changelogLink) } val actionDraculaPro = NotificationAction.createSimple("Dracula Pro") { BrowserUtil.browse(draculaProLink) } val actionGithubRepo = NotificationAction.createSimple("GitHub") { BrowserUtil.browse(githubRepoLink) } notification.addAction(actionChangelog) notification.addAction(actionDraculaPro) notification.addAction(actionGithubRepo) } }
mit
65717d52d933f8f34e04bf41cf941b99
36.76
107
0.721045
4.841026
false
false
false
false
codebutler/odyssey
retrograde-metadata-ovgdb/src/main/java/com/codebutler/retrograde/metadata/ovgdb/db/entity/OvgdbRelease.kt
1
2090
/* * Release.kt * * Copyright (C) 2017 Retrograde Project * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.codebutler.retrograde.metadata.ovgdb.db.entity import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.Index import androidx.room.PrimaryKey @Entity( tableName = "releases", indices = [Index("releaseID"), Index("romID")]) data class OvgdbRelease( @PrimaryKey @ColumnInfo(name = "releaseID") val id: Int, @ColumnInfo(name = "romID") val romId: Int, @ColumnInfo(name = "releaseTitleName") val titleName: String, @ColumnInfo(name = "regionLocalizedID") val regionLocalizedId: Int, @ColumnInfo(name = "releaseCoverFront") val coverFront: String?, @ColumnInfo(name = "releaseCoverBack") val coverBack: String?, @ColumnInfo(name = "releaseCoverCart") val coverCart: String?, @ColumnInfo(name = "releaseCoverDisc") val coverDisc: String?, @ColumnInfo(name = "releaseDescription") val description: String?, @ColumnInfo(name = "releaseDeveloper") val developer: String?, @ColumnInfo(name = "releasePublisher") val publisher: String?, @ColumnInfo(name = "releaseGenre") val genre: String?, @ColumnInfo(name = "releaseDate") val date: String?, @ColumnInfo(name = "releaseReferenceURL") val referenceURL: String?, @ColumnInfo(name = "releaseReferenceImageURL") val referenceImageURL: String? )
gpl-3.0
7e1effebeac805cd325ae07469d79f7f
26.5
72
0.701435
4.058252
false
false
false
false
TCA-Team/TumCampusApp
app/src/main/java/de/tum/in/tumcampusapp/component/tumui/grades/GradeNotificationDeleteReceiver.kt
1
1332
package de.tum.`in`.tumcampusapp.component.tumui.grades import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import de.tum.`in`.tumcampusapp.di.app import java.util.ArrayList import javax.inject.Inject /** * Receives delete intents from grade notification and updates the [GradesStore] with the newly * released grades. This helps to prevent repeated notifications. */ class GradeNotificationDeleteReceiver : BroadcastReceiver() { @Inject lateinit var gradesStore: GradesStore override fun onReceive(context: Context, intent: Intent) { context.app.appComponent.downloadComponent().inject(this) val newGrades = intent.getStringArrayListExtra(KEY_NEW_GRADES) val existingGrades = gradesStore.gradedCourses val updatedGrades = existingGrades + newGrades!! gradesStore.store(updatedGrades) } companion object { private const val KEY_NEW_GRADES = "KEY_NEW_GRADES" fun newIntent(context: Context, newGrades: List<String>): Intent { val gradesMutable = ArrayList<String>() gradesMutable.addAll(newGrades) return Intent(context, GradeNotificationDeleteReceiver::class.java) .putStringArrayListExtra(KEY_NEW_GRADES, gradesMutable) } } }
gpl-3.0
4f2b991defe76f16d99df3c77fe8261f
33.153846
95
0.722973
4.57732
false
false
false
false
rhdunn/xquery-intellij-plugin
src/lang-xquery/test/uk/co/reecedunn/intellij/plugin/xquery/tests/lang/highlighter/XQuerySyntaxHighlighterTest.kt
1
86185
/* * Copyright (C) 2016-2021 Reece H. Dunn * * 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 uk.co.reecedunn.intellij.plugin.xquery.tests.lang.highlighter import org.hamcrest.CoreMatchers.`is` import org.junit.jupiter.api.DisplayName import org.junit.jupiter.api.Test import uk.co.reecedunn.intellij.plugin.core.tests.assertion.assertThat import uk.co.reecedunn.intellij.plugin.xpath.lexer.XPathTokenType import uk.co.reecedunn.intellij.plugin.xquery.lang.highlighter.XQuerySyntaxHighlighter import uk.co.reecedunn.intellij.plugin.xquery.lang.highlighter.XQuerySyntaxHighlighterColors import uk.co.reecedunn.intellij.plugin.xquery.lexer.XQDocTokenType import uk.co.reecedunn.intellij.plugin.xquery.lexer.XQueryTokenType import xqt.platform.intellij.ft.XPathFTTokenProvider import xqt.platform.intellij.marklogic.MarkLogicXPathTokenProvider import xqt.platform.intellij.saxon.SaxonXPathTokenProvider import xqt.platform.intellij.xpath.XPathTokenProvider @Suppress("Reformat") @DisplayName("IntelliJ - Custom Language Support - Syntax Highlighting - XQuery SyntaxHighlighter") class XQuerySyntaxHighlighterTest { @Test @DisplayName("syntax highlighter factory") fun testFactory() { val highlighter = XQuerySyntaxHighlighter.Factory().getSyntaxHighlighter(null, null) assertThat(highlighter.javaClass.name, `is`(XQuerySyntaxHighlighter::class.java.name)) } @Test @DisplayName("bad character") fun testTokenHighlights_BadCharacter() { val highlighter = XQuerySyntaxHighlighter assertThat(highlighter.getTokenHighlights(XPathTokenType.BAD_CHARACTER).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XPathTokenType.BAD_CHARACTER)[0], `is`(XQuerySyntaxHighlighterColors.BAD_CHARACTER)) } @Test @DisplayName("comment") fun testTokenHighlights_Comment() { val highlighter = XQuerySyntaxHighlighter assertThat(highlighter.getTokenHighlights(XPathTokenProvider.CommentOpen).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.CommentOpen)[0], `is`(XQuerySyntaxHighlighterColors.COMMENT)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.CommentContents).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.CommentContents)[0], `is`(XQuerySyntaxHighlighterColors.COMMENT)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.CommentClose).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.CommentClose)[0], `is`(XQuerySyntaxHighlighterColors.COMMENT)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.XML_COMMENT_START_TAG).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.XML_COMMENT_START_TAG)[0], `is`(XQuerySyntaxHighlighterColors.COMMENT)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.XML_COMMENT).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.XML_COMMENT)[0], `is`(XQuerySyntaxHighlighterColors.COMMENT)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.XML_COMMENT_END_TAG).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.XML_COMMENT_END_TAG)[0], `is`(XQuerySyntaxHighlighterColors.COMMENT)) assertThat(highlighter.getTokenHighlights(XQDocTokenType.XQDOC_COMMENT_MARKER).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XQDocTokenType.XQDOC_COMMENT_MARKER)[0], `is`(XQuerySyntaxHighlighterColors.COMMENT)) assertThat(highlighter.getTokenHighlights(XQDocTokenType.CONTENTS).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XQDocTokenType.CONTENTS)[0], `is`(XQuerySyntaxHighlighterColors.COMMENT)) assertThat(highlighter.getTokenHighlights(XQDocTokenType.TRIM).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XQDocTokenType.TRIM)[0], `is`(XQuerySyntaxHighlighterColors.COMMENT)) assertThat(highlighter.getTokenHighlights(XQDocTokenType.XML_ELEMENT_CONTENTS).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XQDocTokenType.XML_ELEMENT_CONTENTS)[0], `is`(XQuerySyntaxHighlighterColors.COMMENT)) } @Test @DisplayName("number") fun testTokenHighlights_Number() { val highlighter = XQuerySyntaxHighlighter assertThat(highlighter.getTokenHighlights(XPathTokenProvider.IntegerLiteral).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.IntegerLiteral)[0], `is`(XQuerySyntaxHighlighterColors.NUMBER)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.DecimalLiteral).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.DecimalLiteral)[0], `is`(XQuerySyntaxHighlighterColors.NUMBER)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.DoubleLiteral).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.DoubleLiteral)[0], `is`(XQuerySyntaxHighlighterColors.NUMBER)) // NOTE: This token is for the parser, so that a parser error will be emitted for incomplete double literals. assertThat(highlighter.getTokenHighlights(XPathTokenType.PARTIAL_DOUBLE_LITERAL_EXPONENT).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XPathTokenType.PARTIAL_DOUBLE_LITERAL_EXPONENT)[0], `is`(XQuerySyntaxHighlighterColors.NUMBER)) } @Test @DisplayName("string") fun testTokenHighlights_String() { val highlighter = XQuerySyntaxHighlighter assertThat(highlighter.getTokenHighlights(XPathTokenType.STRING_LITERAL_START).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XPathTokenType.STRING_LITERAL_START)[0], `is`(XQuerySyntaxHighlighterColors.STRING)) assertThat(highlighter.getTokenHighlights(XPathTokenType.STRING_LITERAL_CONTENTS).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XPathTokenType.STRING_LITERAL_CONTENTS)[0], `is`(XQuerySyntaxHighlighterColors.STRING)) assertThat(highlighter.getTokenHighlights(XPathTokenType.STRING_LITERAL_END).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XPathTokenType.STRING_LITERAL_END)[0], `is`(XQuerySyntaxHighlighterColors.STRING)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.STRING_CONSTRUCTOR_START).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.STRING_CONSTRUCTOR_START)[0], `is`(XQuerySyntaxHighlighterColors.STRING)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.STRING_CONSTRUCTOR_CONTENTS).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.STRING_CONSTRUCTOR_CONTENTS)[0], `is`(XQuerySyntaxHighlighterColors.STRING)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.STRING_CONSTRUCTOR_END).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.STRING_CONSTRUCTOR_END)[0], `is`(XQuerySyntaxHighlighterColors.STRING)) assertThat(highlighter.getTokenHighlights(XPathTokenType.BRACED_URI_LITERAL_START).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XPathTokenType.BRACED_URI_LITERAL_START)[0], `is`(XQuerySyntaxHighlighterColors.STRING)) assertThat(highlighter.getTokenHighlights(XPathTokenType.BRACED_URI_LITERAL_END).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XPathTokenType.BRACED_URI_LITERAL_END)[0], `is`(XQuerySyntaxHighlighterColors.STRING)) } @Test @DisplayName("escaped character") fun testTokenHighlights_EscapedCharacter() { val highlighter = XQuerySyntaxHighlighter assertThat(highlighter.getTokenHighlights(XPathTokenType.ESCAPED_CHARACTER).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XPathTokenType.ESCAPED_CHARACTER)[0], `is`(XQuerySyntaxHighlighterColors.ESCAPED_CHARACTER)) } @Test @DisplayName("entity reference") fun testTokenHighlights_EntityReference() { val highlighter = XQuerySyntaxHighlighter assertThat(highlighter.getTokenHighlights(XQueryTokenType.PREDEFINED_ENTITY_REFERENCE).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.PREDEFINED_ENTITY_REFERENCE)[0], `is`(XQuerySyntaxHighlighterColors.ENTITY_REFERENCE)) // NOTE: This token is for the parser, so that a parser error will be emitted for invalid entity references. assertThat(highlighter.getTokenHighlights(XQueryTokenType.ENTITY_REFERENCE_NOT_IN_STRING).size, `is`(0)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.CHARACTER_REFERENCE).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.CHARACTER_REFERENCE)[0], `is`(XQuerySyntaxHighlighterColors.ENTITY_REFERENCE)) // NOTE: This token is for the parser, so that a parser error will be emitted for invalid entity references. assertThat(highlighter.getTokenHighlights(XQueryTokenType.PARTIAL_ENTITY_REFERENCE).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.PARTIAL_ENTITY_REFERENCE)[0], `is`(XQuerySyntaxHighlighterColors.ENTITY_REFERENCE)) // NOTE: This token is for the parser, so that a parser error will be emitted for invalid entity references. assertThat(highlighter.getTokenHighlights(XQueryTokenType.EMPTY_ENTITY_REFERENCE).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.EMPTY_ENTITY_REFERENCE)[0], `is`(XQuerySyntaxHighlighterColors.ENTITY_REFERENCE)) } @Test @DisplayName("identifier") fun testTokenHighlights_Identifier() { val highlighter = XQuerySyntaxHighlighter assertThat(highlighter.getTokenHighlights(XPathTokenProvider.NCName).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.NCName)[0], `is`(XQuerySyntaxHighlighterColors.IDENTIFIER)) } @Test @DisplayName("keywords") fun testTokenHighlights_Keywords() { val highlighter = XQuerySyntaxHighlighter assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_AFTER).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_AFTER)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XPathFTTokenProvider.KAll).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XPathFTTokenProvider.KAll)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_ALLOWING).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_ALLOWING)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.KAncestor).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.KAncestor)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.KAncestorOrSelf).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.KAncestorOrSelf)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.KAnd).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.KAnd)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(SaxonXPathTokenProvider.KAndAlso).size, `is`(1)) assertThat(highlighter.getTokenHighlights(SaxonXPathTokenProvider.KAndAlso)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XPathFTTokenProvider.KAny).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XPathFTTokenProvider.KAny)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.KArray).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.KArray)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(MarkLogicXPathTokenProvider.KArrayNode).size, `is`(1)) assertThat(highlighter.getTokenHighlights(MarkLogicXPathTokenProvider.KArrayNode)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.KAs).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.KAs)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_ASCENDING).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_ASCENDING)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_ASSIGNABLE).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_ASSIGNABLE)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XPathFTTokenProvider.KAt).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XPathFTTokenProvider.KAt)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.KAttribute).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.KAttribute)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(MarkLogicXPathTokenProvider.KAttributeDecl).size, `is`(1)) assertThat(highlighter.getTokenHighlights(MarkLogicXPathTokenProvider.KAttributeDecl)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_BASE_URI).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_BASE_URI)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_BEFORE).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_BEFORE)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(MarkLogicXPathTokenProvider.KBinary).size, `is`(1)) assertThat(highlighter.getTokenHighlights(MarkLogicXPathTokenProvider.KBinary)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_BLOCK).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_BLOCK)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(MarkLogicXPathTokenProvider.KBooleanNode).size, `is`(1)) assertThat(highlighter.getTokenHighlights(MarkLogicXPathTokenProvider.KBooleanNode)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_BOUNDARY_SPACE).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_BOUNDARY_SPACE)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_BY).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_BY)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XPathFTTokenProvider.KCase).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XPathFTTokenProvider.KCase)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.KCast).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.KCast)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.KCastable).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.KCastable)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_CATCH).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_CATCH)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.KChild).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.KChild)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_COLLATION).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_COLLATION)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.KComment).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.KComment)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(MarkLogicXPathTokenProvider.KComplexType).size, `is`(1)) assertThat(highlighter.getTokenHighlights(MarkLogicXPathTokenProvider.KComplexType)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_CONSTRUCTION).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_CONSTRUCTION)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XPathFTTokenProvider.KContains).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XPathFTTokenProvider.KContains)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XPathFTTokenProvider.KContent).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XPathFTTokenProvider.KContent)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_CONTEXT).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_CONTEXT)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_COPY).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_COPY)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_COPY_NAMESPACES).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_COPY_NAMESPACES)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_COUNT).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_COUNT)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_DECIMAL_FORMAT).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_DECIMAL_FORMAT)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_DECIMAL_SEPARATOR).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_DECIMAL_SEPARATOR)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_DECLARE).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_DECLARE)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XPathFTTokenProvider.KDefault).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XPathFTTokenProvider.KDefault)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_DELETE).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_DELETE)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.KDescendant).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.KDescendant)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.KDescendantOrSelf).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.KDescendantOrSelf)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_DESCENDING).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_DESCENDING)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XPathFTTokenProvider.KDiacritics).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XPathFTTokenProvider.KDiacritics)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XPathFTTokenProvider.KDifferent).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XPathFTTokenProvider.KDifferent)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_DIGIT).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_DIGIT)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XPathFTTokenProvider.KDistance).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XPathFTTokenProvider.KDistance)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.KDiv).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.KDiv)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_DOCUMENT).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_DOCUMENT)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.KDocumentNode).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.KDocumentNode)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.KElement).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.KElement)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(MarkLogicXPathTokenProvider.KElementDecl).size, `is`(1)) assertThat(highlighter.getTokenHighlights(MarkLogicXPathTokenProvider.KElementDecl)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.KEmpty).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.KEmpty)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.KEmptySequence).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.KEmptySequence)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_ENCODING).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_ENCODING)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XPathFTTokenProvider.KEnd).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XPathFTTokenProvider.KEnd)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XPathFTTokenProvider.KEntire).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XPathFTTokenProvider.KEntire)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.KEnum).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.KEnum)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.KEq).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.KEq)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.KEvery).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.KEvery)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XPathFTTokenProvider.KExactly).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XPathFTTokenProvider.KExactly)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.KExcept).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.KExcept)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_EXIT).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_EXIT)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_EXTERNAL).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_EXTERNAL)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_FIRST).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_FIRST)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(SaxonXPathTokenProvider.KFn).size, `is`(1)) assertThat(highlighter.getTokenHighlights(SaxonXPathTokenProvider.KFn)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.KFollowing).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.KFollowing)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.KFollowingSibling).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.KFollowingSibling)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.KFor).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.KFor)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XPathFTTokenProvider.KFrom).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XPathFTTokenProvider.KFrom)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_FT_OPTION).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_FT_OPTION)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XPathFTTokenProvider.KFtAnd).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XPathFTTokenProvider.KFtAnd)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XPathFTTokenProvider.KFtNot).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XPathFTTokenProvider.KFtNot)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XPathFTTokenProvider.KFtOr).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XPathFTTokenProvider.KFtOr)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.KFunction).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.KFunction)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_FULL).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_FULL)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_FUZZY).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_FUZZY)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.KGe).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.KGe)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_GREATEST).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_GREATEST)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_GROUP).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_GROUP)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_GROUPING_SEPARATOR).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_GROUPING_SEPARATOR)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.KGt).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.KGt)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.KIDiv).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.KIDiv)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_IMPORT).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_IMPORT)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.KIn).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.KIn)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_INFINITY).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_INFINITY)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_INHERIT).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_INHERIT)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XPathFTTokenProvider.KInsensitive).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XPathFTTokenProvider.KInsensitive)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_INSERT).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_INSERT)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.KInstance).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.KInstance)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.KIntersect).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.KIntersect)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_INTO).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_INTO)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_INVOKE).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_INVOKE)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.KIs).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.KIs)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.KItem).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.KItem)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_ITEM_TYPE).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_ITEM_TYPE)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XPathFTTokenProvider.KLanguage).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XPathFTTokenProvider.KLanguage)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_LAST).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_LAST)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_LAX).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_LAX)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.KLe).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.KLe)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XPathFTTokenProvider.KLeast).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XPathFTTokenProvider.KLeast)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.KLet).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.KLet)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XPathFTTokenProvider.KLevels).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XPathFTTokenProvider.KLevels)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XPathFTTokenProvider.KLowerCase).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XPathFTTokenProvider.KLowerCase)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.KLt).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.KLt)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.KMap).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.KMap)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.KMember).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.KMember)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_MINUS_SIGN).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_MINUS_SIGN)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.KMod).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.KMod)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_MODIFY).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_MODIFY)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_MODULE).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_MODULE)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(MarkLogicXPathTokenProvider.KModelGroup).size, `is`(1)) assertThat(highlighter.getTokenHighlights(MarkLogicXPathTokenProvider.KModelGroup)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XPathFTTokenProvider.KMost).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XPathFTTokenProvider.KMost)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.KNamespace).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.KNamespace)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.KNamespaceNode).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.KNamespaceNode)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_NAN).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_NAN)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.KNe).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.KNe)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_NEXT).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_NEXT)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XPathFTTokenProvider.KNo).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XPathFTTokenProvider.KNo)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_NO_INHERIT).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_NO_INHERIT)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_NO_PRESERVE).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_NO_PRESERVE)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.KNode).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.KNode)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_NODES).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_NODES)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_NON_DETERMINISTIC).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_NON_DETERMINISTIC)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XPathFTTokenProvider.KNot).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XPathFTTokenProvider.KNot)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(MarkLogicXPathTokenProvider.KNullNode).size, `is`(1)) assertThat(highlighter.getTokenHighlights(MarkLogicXPathTokenProvider.KNullNode)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(MarkLogicXPathTokenProvider.KNumberNode).size, `is`(1)) assertThat(highlighter.getTokenHighlights(MarkLogicXPathTokenProvider.KNumberNode)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(MarkLogicXPathTokenProvider.KObjectNode).size, `is`(1)) assertThat(highlighter.getTokenHighlights(MarkLogicXPathTokenProvider.KObjectNode)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XPathFTTokenProvider.KOccurs).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XPathFTTokenProvider.KOccurs)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.KOf).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.KOf)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_ONLY).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_ONLY)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XPathFTTokenProvider.KOption).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XPathFTTokenProvider.KOption)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.KOr).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.KOr)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_ORDER).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_ORDER)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XPathFTTokenProvider.KOrdered).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XPathFTTokenProvider.KOrdered)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_ORDERING).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_ORDERING)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(SaxonXPathTokenProvider.KOrElse).size, `is`(1)) assertThat(highlighter.getTokenHighlights(SaxonXPathTokenProvider.KOrElse)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.KOtherwise).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.KOtherwise)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XPathFTTokenProvider.KParagraph).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XPathFTTokenProvider.KParagraph)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XPathFTTokenProvider.KParagraphs).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XPathFTTokenProvider.KParagraphs)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.KParent).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.KParent)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_PATTERN_SEPARATOR).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_PATTERN_SEPARATOR)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_PER_MILLE).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_PER_MILLE)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_PERCENT).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_PERCENT)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XPathFTTokenProvider.KPhrase).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XPathFTTokenProvider.KPhrase)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.KPreceding).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.KPreceding)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.KPrecedingSibling).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.KPrecedingSibling)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_PRESERVE).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_PRESERVE)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_PREVIOUS).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_PREVIOUS)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.KProcessingInstruction).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.KProcessingInstruction)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(MarkLogicXPathTokenProvider.KProperty).size, `is`(1)) assertThat(highlighter.getTokenHighlights(MarkLogicXPathTokenProvider.KProperty)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.KRecord).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.KRecord)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XPathFTTokenProvider.KRelationship).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XPathFTTokenProvider.KRelationship)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_RENAME).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_RENAME)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_REPLACE).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_REPLACE)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.KReturn).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.KReturn)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_RETURNING).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_RETURNING)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_REVALIDATION).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_REVALIDATION)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XPathFTTokenProvider.KSame).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XPathFTTokenProvider.KSame)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.KSatisfies).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.KSatisfies)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_SCHEMA).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_SCHEMA)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.KSchemaAttribute).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.KSchemaAttribute)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(MarkLogicXPathTokenProvider.KSchemaComponent).size, `is`(1)) assertThat(highlighter.getTokenHighlights(MarkLogicXPathTokenProvider.KSchemaComponent)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.KSchemaElement).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.KSchemaElement)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(MarkLogicXPathTokenProvider.KSchemaFacet).size, `is`(1)) assertThat(highlighter.getTokenHighlights(MarkLogicXPathTokenProvider.KSchemaFacet)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(MarkLogicXPathTokenProvider.KSchemaParticle).size, `is`(1)) assertThat(highlighter.getTokenHighlights(MarkLogicXPathTokenProvider.KSchemaParticle)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(MarkLogicXPathTokenProvider.KSchemaRoot).size, `is`(1)) assertThat(highlighter.getTokenHighlights(MarkLogicXPathTokenProvider.KSchemaRoot)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(MarkLogicXPathTokenProvider.KSchemaType).size, `is`(1)) assertThat(highlighter.getTokenHighlights(MarkLogicXPathTokenProvider.KSchemaType)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(MarkLogicXPathTokenProvider.KSchemaWildcard).size, `is`(1)) assertThat(highlighter.getTokenHighlights(MarkLogicXPathTokenProvider.KSchemaWildcard)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XPathFTTokenProvider.KScore).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XPathFTTokenProvider.KScore)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.KSelf).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.KSelf)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XPathFTTokenProvider.KSensitive).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XPathFTTokenProvider.KSensitive)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XPathFTTokenProvider.KSentence).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XPathFTTokenProvider.KSentence)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XPathFTTokenProvider.KSentences).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XPathFTTokenProvider.KSentences)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(MarkLogicXPathTokenProvider.KSimpleType).size, `is`(1)) assertThat(highlighter.getTokenHighlights(MarkLogicXPathTokenProvider.KSimpleType)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_SKIP).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_SKIP)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_SLIDING).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_SLIDING)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.KSome).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.KSome)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_STABLE).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_STABLE)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XPathFTTokenProvider.KStart).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XPathFTTokenProvider.KStart)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XPathFTTokenProvider.KStemming).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XPathFTTokenProvider.KStemming)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XPathFTTokenProvider.KStop).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XPathFTTokenProvider.KStop)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_STRICT).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_STRICT)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_STRIP).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_STRIP)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_STYLESHEET).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_STYLESHEET)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_SWITCH).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_SWITCH)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.KText).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.KText)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.KThen).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.KThen)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XPathFTTokenProvider.KThesaurus).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XPathFTTokenProvider.KThesaurus)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XPathFTTokenProvider.KTimes).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XPathFTTokenProvider.KTimes)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.KTo).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.KTo)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_TRANSFORM).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_TRANSFORM)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.KTreat).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.KTreat)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_TRY).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_TRY)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_TUMBLING).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_TUMBLING)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(SaxonXPathTokenProvider.KTuple).size, `is`(1)) assertThat(highlighter.getTokenHighlights(SaxonXPathTokenProvider.KTuple)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.KType).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.KType)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_TYPESWITCH).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_TYPESWITCH)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_UNASSIGNABLE).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_UNASSIGNABLE)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.KUnion).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.KUnion)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_UNORDERED).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_UNORDERED)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_UPDATE).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_UPDATE)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XPathFTTokenProvider.KUpperCase).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XPathFTTokenProvider.KUpperCase)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XPathFTTokenProvider.KUsing).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XPathFTTokenProvider.KUsing)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_VALIDATE).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_VALIDATE)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_VALUE).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_VALUE)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_VARIABLE).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_VARIABLE)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_VERSION).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_VERSION)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XPathFTTokenProvider.KWeight).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XPathFTTokenProvider.KWeight)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_WHEN).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_WHEN)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_WHERE).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_WHERE)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_WHILE).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_WHILE)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XPathFTTokenProvider.KWildcards).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XPathFTTokenProvider.KWildcards)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XPathFTTokenProvider.KWindow).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XPathFTTokenProvider.KWindow)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.KWith).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.KWith)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XPathFTTokenProvider.KWithout).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XPathFTTokenProvider.KWithout)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XPathFTTokenProvider.KWord).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XPathFTTokenProvider.KWord)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XPathFTTokenProvider.KWords).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XPathFTTokenProvider.KWords)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_XQUERY).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_XQUERY)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_ZERO_DIGIT).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_ZERO_DIGIT)[0], `is`(XQuerySyntaxHighlighterColors.KEYWORD)) } @Test @DisplayName("xml processing instruction tag") fun testTokenHighlights_XmlPITag() { val highlighter = XQuerySyntaxHighlighter assertThat(highlighter.getTokenHighlights(XQueryTokenType.PROCESSING_INSTRUCTION_BEGIN).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.PROCESSING_INSTRUCTION_BEGIN)[0], `is`(XQuerySyntaxHighlighterColors.XML_PI_TAG)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.PROCESSING_INSTRUCTION_END).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.PROCESSING_INSTRUCTION_END)[0], `is`(XQuerySyntaxHighlighterColors.XML_PI_TAG)) } @Test @DisplayName("xml tag") fun testTokenHighlights_XmlTag() { val highlighter = XQuerySyntaxHighlighter assertThat(highlighter.getTokenHighlights(XQueryTokenType.OPEN_XML_TAG).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.OPEN_XML_TAG)[0], `is`(XQuerySyntaxHighlighterColors.XML_TAG)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.END_XML_TAG).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.END_XML_TAG)[0], `is`(XQuerySyntaxHighlighterColors.XML_TAG)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.CLOSE_XML_TAG).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.CLOSE_XML_TAG)[0], `is`(XQuerySyntaxHighlighterColors.XML_TAG)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.SELF_CLOSING_XML_TAG).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.SELF_CLOSING_XML_TAG)[0], `is`(XQuerySyntaxHighlighterColors.XML_TAG)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.XML_WHITE_SPACE).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.XML_WHITE_SPACE)[0], `is`(XQuerySyntaxHighlighterColors.XML_TAG)) } @Test @DisplayName("xml tag name") fun testTokenHighlights_XmlTagName() { val highlighter = XQuerySyntaxHighlighter assertThat(highlighter.getTokenHighlights(XQueryTokenType.XML_TAG_NCNAME).size, `is`(2)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.XML_TAG_NCNAME)[0], `is`(XQuerySyntaxHighlighterColors.XML_TAG)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.XML_TAG_NCNAME)[1], `is`(XQuerySyntaxHighlighterColors.ELEMENT)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.XML_TAG_QNAME_SEPARATOR).size, `is`(2)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.XML_TAG_QNAME_SEPARATOR)[0], `is`(XQuerySyntaxHighlighterColors.XML_TAG)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.XML_TAG_QNAME_SEPARATOR)[1], `is`(XQuerySyntaxHighlighterColors.ELEMENT)) } @Test @DisplayName("xml attribute name") fun testTokenHighlights_XmlAttributeName() { val highlighter = XQuerySyntaxHighlighter assertThat(highlighter.getTokenHighlights(XQueryTokenType.XML_ATTRIBUTE_NCNAME).size, `is`(2)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.XML_ATTRIBUTE_NCNAME)[0], `is`(XQuerySyntaxHighlighterColors.XML_TAG)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.XML_ATTRIBUTE_NCNAME)[1], `is`(XQuerySyntaxHighlighterColors.ATTRIBUTE)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.XML_ATTRIBUTE_XMLNS).size, `is`(2)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.XML_ATTRIBUTE_XMLNS)[0], `is`(XQuerySyntaxHighlighterColors.XML_TAG)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.XML_ATTRIBUTE_XMLNS)[1], `is`(XQuerySyntaxHighlighterColors.ATTRIBUTE)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.XML_ATTRIBUTE_QNAME_SEPARATOR).size, `is`(2)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.XML_ATTRIBUTE_QNAME_SEPARATOR)[0], `is`(XQuerySyntaxHighlighterColors.XML_TAG)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.XML_ATTRIBUTE_QNAME_SEPARATOR)[1], `is`(XQuerySyntaxHighlighterColors.ATTRIBUTE)) } @Test @DisplayName("xml attribute value") fun testTokenHighlights_XmlAttributeValue() { val highlighter = XQuerySyntaxHighlighter assertThat(highlighter.getTokenHighlights(XQueryTokenType.XML_EQUAL).size, `is`(2)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.XML_EQUAL)[0], `is`(XQuerySyntaxHighlighterColors.XML_TAG)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.XML_EQUAL)[1], `is`(XQuerySyntaxHighlighterColors.XML_ATTRIBUTE_VALUE)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.XML_ATTRIBUTE_VALUE_START).size, `is`(2)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.XML_ATTRIBUTE_VALUE_START)[0], `is`(XQuerySyntaxHighlighterColors.XML_TAG)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.XML_ATTRIBUTE_VALUE_START)[1], `is`(XQuerySyntaxHighlighterColors.XML_ATTRIBUTE_VALUE)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.XML_ATTRIBUTE_VALUE_CONTENTS).size, `is`(2)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.XML_ATTRIBUTE_VALUE_CONTENTS)[0], `is`(XQuerySyntaxHighlighterColors.XML_TAG)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.XML_ATTRIBUTE_VALUE_CONTENTS)[1], `is`(XQuerySyntaxHighlighterColors.XML_ATTRIBUTE_VALUE)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.XML_ATTRIBUTE_VALUE_END).size, `is`(2)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.XML_ATTRIBUTE_VALUE_END)[0], `is`(XQuerySyntaxHighlighterColors.XML_TAG)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.XML_ATTRIBUTE_VALUE_END)[1], `is`(XQuerySyntaxHighlighterColors.XML_ATTRIBUTE_VALUE)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.XML_PARTIAL_ENTITY_REFERENCE).size, `is`(2)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.XML_PARTIAL_ENTITY_REFERENCE)[0], `is`(XQuerySyntaxHighlighterColors.XML_TAG)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.XML_PARTIAL_ENTITY_REFERENCE)[1], `is`(XQuerySyntaxHighlighterColors.XML_ATTRIBUTE_VALUE)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.XML_EMPTY_ENTITY_REFERENCE).size, `is`(2)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.XML_EMPTY_ENTITY_REFERENCE)[0], `is`(XQuerySyntaxHighlighterColors.XML_TAG)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.XML_EMPTY_ENTITY_REFERENCE)[1], `is`(XQuerySyntaxHighlighterColors.XML_ATTRIBUTE_VALUE)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.PROCESSING_INSTRUCTION_CONTENTS).size, `is`(2)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.PROCESSING_INSTRUCTION_CONTENTS)[0], `is`(XQuerySyntaxHighlighterColors.XML_TAG)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.PROCESSING_INSTRUCTION_CONTENTS)[1], `is`(XQuerySyntaxHighlighterColors.XML_ATTRIBUTE_VALUE)) } @Test @DisplayName("xml escaped character") fun testTokenHighlights_XmlEscapedCharacter() { val highlighter = XQuerySyntaxHighlighter assertThat(highlighter.getTokenHighlights(XQueryTokenType.XML_ESCAPED_CHARACTER).size, `is`(2)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.XML_ESCAPED_CHARACTER)[0], `is`(XQuerySyntaxHighlighterColors.XML_TAG)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.XML_ESCAPED_CHARACTER)[1], `is`(XQuerySyntaxHighlighterColors.XML_ESCAPED_CHARACTER)) } @Test @DisplayName("xml entity reference") fun testTokenHighlights_XmlEntityReference() { val highlighter = XQuerySyntaxHighlighter assertThat(highlighter.getTokenHighlights(XQueryTokenType.XML_PREDEFINED_ENTITY_REFERENCE).size, `is`(2)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.XML_PREDEFINED_ENTITY_REFERENCE)[0], `is`(XQuerySyntaxHighlighterColors.XML_TAG)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.XML_PREDEFINED_ENTITY_REFERENCE)[1], `is`(XQuerySyntaxHighlighterColors.XML_ENTITY_REFERENCE)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.XML_CHARACTER_REFERENCE).size, `is`(2)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.XML_CHARACTER_REFERENCE)[0], `is`(XQuerySyntaxHighlighterColors.XML_TAG)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.XML_CHARACTER_REFERENCE)[1], `is`(XQuerySyntaxHighlighterColors.XML_ENTITY_REFERENCE)) } @Test @DisplayName("other token") fun testTokenHighlights_OtherToken() { val highlighter = XQuerySyntaxHighlighter assertThat(highlighter.getTokenHighlights(XQueryTokenType.INVALID).size, `is`(0)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.CDATA_SECTION_START_TAG).size, `is`(0)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.CDATA_SECTION).size, `is`(0)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.CDATA_SECTION_END_TAG).size, `is`(0)) assertThat(highlighter.getTokenHighlights(XPathFTTokenProvider.PragmaOpen).size, `is`(0)) assertThat(highlighter.getTokenHighlights(XPathFTTokenProvider.PragmaContents).size, `is`(0)) assertThat(highlighter.getTokenHighlights(XPathFTTokenProvider.PragmaClose).size, `is`(0)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.XML_ELEMENT_CONTENTS).size, `is`(0)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.NotEquals).size, `is`(0)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.VariableIndicator).size, `is`(0)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.ParenthesisOpen).size, `is`(0)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.ParenthesisClose).size, `is`(0)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.Star).size, `is`(0)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.Plus).size, `is`(0)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.Comma).size, `is`(0)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.Minus).size, `is`(0)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.ContextItem).size, `is`(0)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.Equals).size, `is`(0)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.CurlyBracketOpen).size, `is`(0)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.CurlyBracketClose).size, `is`(0)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.SEPARATOR).size, `is`(0)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.LessThan).size, `is`(0)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.GreaterThan).size, `is`(0)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.LessThanOrEquals).size, `is`(0)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.GreaterThanOrEquals).size, `is`(0)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.Union).size, `is`(0)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.QuestionMark).size, `is`(0)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.AxisSeparator).size, `is`(0)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.Colon).size, `is`(0)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.AssignEquals).size, `is`(0)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.PathOperator).size, `is`(0)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.AbbrevDescendantOrSelf).size, `is`(0)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.SquareBracketOpen).size, `is`(0)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.SquareBracketClose).size, `is`(0)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.AbbrevParent).size, `is`(0)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.NodePrecedes).size, `is`(0)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.NodeFollows).size, `is`(0)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.Concatenation).size, `is`(0)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.MapOperator).size, `is`(0)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.FunctionRef).size, `is`(0)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.ThickArrow).size, `is`(0)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.ThinArrow).size, `is`(0)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.STRING_INTERPOLATION_OPEN).size, `is`(0)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.STRING_INTERPOLATION_CLOSE).size, `is`(0)) assertThat(highlighter.getTokenHighlights(SaxonXPathTokenProvider.ContextFunctionOpen).size, `is`(0)) assertThat(highlighter.getTokenHighlights(XPathTokenType.ELLIPSIS).size, `is`(0)) assertThat(highlighter.getTokenHighlights(XPathTokenType.ELVIS).size, `is`(0)) assertThat(highlighter.getTokenHighlights(SaxonXPathTokenProvider.LambdaFunctionOpen).size, `is`(0)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.TernaryElse).size, `is`(0)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.TernaryIfThen).size, `is`(0)) assertThat(highlighter.getTokenHighlights(SaxonXPathTokenProvider.TypeAlias).size, `is`(0)) assertThat(highlighter.getTokenHighlights(XPathTokenType.K_).size, `is`(0)) // Saxon 10.0 lambda function. } @Test @DisplayName("xqdoc tag") fun testTokenHighlights_XQDocTag() { val highlighter = XQuerySyntaxHighlighter assertThat(highlighter.getTokenHighlights(XQDocTokenType.TAG_MARKER).size, `is`(2)) assertThat(highlighter.getTokenHighlights(XQDocTokenType.TAG_MARKER)[0], `is`(XQuerySyntaxHighlighterColors.COMMENT)) assertThat(highlighter.getTokenHighlights(XQDocTokenType.TAG_MARKER)[1], `is`(XQuerySyntaxHighlighterColors.XQDOC_TAG)) assertThat(highlighter.getTokenHighlights(XQDocTokenType.TAG).size, `is`(2)) assertThat(highlighter.getTokenHighlights(XQDocTokenType.TAG)[0], `is`(XQuerySyntaxHighlighterColors.COMMENT)) assertThat(highlighter.getTokenHighlights(XQDocTokenType.TAG)[1], `is`(XQuerySyntaxHighlighterColors.XQDOC_TAG)) assertThat(highlighter.getTokenHighlights(XQDocTokenType.T_AUTHOR).size, `is`(2)) assertThat(highlighter.getTokenHighlights(XQDocTokenType.T_AUTHOR)[0], `is`(XQuerySyntaxHighlighterColors.COMMENT)) assertThat(highlighter.getTokenHighlights(XQDocTokenType.T_AUTHOR)[1], `is`(XQuerySyntaxHighlighterColors.XQDOC_TAG)) assertThat(highlighter.getTokenHighlights(XQDocTokenType.T_DEPRECATED).size, `is`(2)) assertThat(highlighter.getTokenHighlights(XQDocTokenType.T_DEPRECATED)[0], `is`(XQuerySyntaxHighlighterColors.COMMENT)) assertThat(highlighter.getTokenHighlights(XQDocTokenType.T_DEPRECATED)[1], `is`(XQuerySyntaxHighlighterColors.XQDOC_TAG)) assertThat(highlighter.getTokenHighlights(XQDocTokenType.T_ERROR).size, `is`(2)) assertThat(highlighter.getTokenHighlights(XQDocTokenType.T_ERROR)[0], `is`(XQuerySyntaxHighlighterColors.COMMENT)) assertThat(highlighter.getTokenHighlights(XQDocTokenType.T_ERROR)[1], `is`(XQuerySyntaxHighlighterColors.XQDOC_TAG)) assertThat(highlighter.getTokenHighlights(XQDocTokenType.T_PARAM).size, `is`(2)) assertThat(highlighter.getTokenHighlights(XQDocTokenType.T_PARAM)[0], `is`(XQuerySyntaxHighlighterColors.COMMENT)) assertThat(highlighter.getTokenHighlights(XQDocTokenType.T_PARAM)[1], `is`(XQuerySyntaxHighlighterColors.XQDOC_TAG)) assertThat(highlighter.getTokenHighlights(XQDocTokenType.T_RETURN).size, `is`(2)) assertThat(highlighter.getTokenHighlights(XQDocTokenType.T_RETURN)[0], `is`(XQuerySyntaxHighlighterColors.COMMENT)) assertThat(highlighter.getTokenHighlights(XQDocTokenType.T_RETURN)[1], `is`(XQuerySyntaxHighlighterColors.XQDOC_TAG)) assertThat(highlighter.getTokenHighlights(XQDocTokenType.T_SEE).size, `is`(2)) assertThat(highlighter.getTokenHighlights(XQDocTokenType.T_SEE)[0], `is`(XQuerySyntaxHighlighterColors.COMMENT)) assertThat(highlighter.getTokenHighlights(XQDocTokenType.T_SEE)[1], `is`(XQuerySyntaxHighlighterColors.XQDOC_TAG)) assertThat(highlighter.getTokenHighlights(XQDocTokenType.T_SINCE).size, `is`(2)) assertThat(highlighter.getTokenHighlights(XQDocTokenType.T_SINCE)[0], `is`(XQuerySyntaxHighlighterColors.COMMENT)) assertThat(highlighter.getTokenHighlights(XQDocTokenType.T_SINCE)[1], `is`(XQuerySyntaxHighlighterColors.XQDOC_TAG)) assertThat(highlighter.getTokenHighlights(XQDocTokenType.T_VERSION).size, `is`(2)) assertThat(highlighter.getTokenHighlights(XQDocTokenType.T_VERSION)[0], `is`(XQuerySyntaxHighlighterColors.COMMENT)) assertThat(highlighter.getTokenHighlights(XQDocTokenType.T_VERSION)[1], `is`(XQuerySyntaxHighlighterColors.XQDOC_TAG)) } @Test @DisplayName("xqdoc tag value") fun testTokenHighlights_XQDocTagValue() { val highlighter = XQuerySyntaxHighlighter assertThat(highlighter.getTokenHighlights(XQDocTokenType.VARIABLE_INDICATOR).size, `is`(2)) assertThat(highlighter.getTokenHighlights(XQDocTokenType.VARIABLE_INDICATOR)[0], `is`(XQuerySyntaxHighlighterColors.COMMENT)) assertThat(highlighter.getTokenHighlights(XQDocTokenType.VARIABLE_INDICATOR)[1], `is`(XQuerySyntaxHighlighterColors.XQDOC_TAG_VALUE)) assertThat(highlighter.getTokenHighlights(XQDocTokenType.NCNAME).size, `is`(2)) assertThat(highlighter.getTokenHighlights(XQDocTokenType.NCNAME)[0], `is`(XQuerySyntaxHighlighterColors.COMMENT)) assertThat(highlighter.getTokenHighlights(XQDocTokenType.NCNAME)[1], `is`(XQuerySyntaxHighlighterColors.XQDOC_TAG_VALUE)) } @Test @DisplayName("xqdoc xml markup") fun testTokenHighlights_XQDocMarkup() { val highlighter = XQuerySyntaxHighlighter assertThat(highlighter.getTokenHighlights(XQDocTokenType.OPEN_XML_TAG).size, `is`(2)) assertThat(highlighter.getTokenHighlights(XQDocTokenType.OPEN_XML_TAG)[0], `is`(XQuerySyntaxHighlighterColors.COMMENT)) assertThat(highlighter.getTokenHighlights(XQDocTokenType.OPEN_XML_TAG)[1], `is`(XQuerySyntaxHighlighterColors.XQDOC_MARKUP)) assertThat(highlighter.getTokenHighlights(XQDocTokenType.END_XML_TAG).size, `is`(2)) assertThat(highlighter.getTokenHighlights(XQDocTokenType.END_XML_TAG)[0], `is`(XQuerySyntaxHighlighterColors.COMMENT)) assertThat(highlighter.getTokenHighlights(XQDocTokenType.END_XML_TAG)[1], `is`(XQuerySyntaxHighlighterColors.XQDOC_MARKUP)) assertThat(highlighter.getTokenHighlights(XQDocTokenType.CLOSE_XML_TAG).size, `is`(2)) assertThat(highlighter.getTokenHighlights(XQDocTokenType.CLOSE_XML_TAG)[0], `is`(XQuerySyntaxHighlighterColors.COMMENT)) assertThat(highlighter.getTokenHighlights(XQDocTokenType.CLOSE_XML_TAG)[1], `is`(XQuerySyntaxHighlighterColors.XQDOC_MARKUP)) assertThat(highlighter.getTokenHighlights(XQDocTokenType.SELF_CLOSING_XML_TAG).size, `is`(2)) assertThat(highlighter.getTokenHighlights(XQDocTokenType.SELF_CLOSING_XML_TAG)[0], `is`(XQuerySyntaxHighlighterColors.COMMENT)) assertThat(highlighter.getTokenHighlights(XQDocTokenType.SELF_CLOSING_XML_TAG)[1], `is`(XQuerySyntaxHighlighterColors.XQDOC_MARKUP)) assertThat(highlighter.getTokenHighlights(XQDocTokenType.XML_TAG).size, `is`(2)) assertThat(highlighter.getTokenHighlights(XQDocTokenType.XML_TAG)[0], `is`(XQuerySyntaxHighlighterColors.COMMENT)) assertThat(highlighter.getTokenHighlights(XQDocTokenType.XML_TAG)[1], `is`(XQuerySyntaxHighlighterColors.XQDOC_MARKUP)) assertThat(highlighter.getTokenHighlights(XQDocTokenType.XML_EQUAL).size, `is`(2)) assertThat(highlighter.getTokenHighlights(XQDocTokenType.XML_EQUAL)[0], `is`(XQuerySyntaxHighlighterColors.COMMENT)) assertThat(highlighter.getTokenHighlights(XQDocTokenType.XML_EQUAL)[1], `is`(XQuerySyntaxHighlighterColors.XQDOC_MARKUP)) assertThat(highlighter.getTokenHighlights(XQDocTokenType.XML_ATTRIBUTE_VALUE_START).size, `is`(2)) assertThat(highlighter.getTokenHighlights(XQDocTokenType.XML_ATTRIBUTE_VALUE_START)[0], `is`(XQuerySyntaxHighlighterColors.COMMENT)) assertThat(highlighter.getTokenHighlights(XQDocTokenType.XML_ATTRIBUTE_VALUE_START)[1], `is`(XQuerySyntaxHighlighterColors.XQDOC_MARKUP)) assertThat(highlighter.getTokenHighlights(XQDocTokenType.XML_ATTRIBUTE_VALUE_CONTENTS).size, `is`(2)) assertThat(highlighter.getTokenHighlights(XQDocTokenType.XML_ATTRIBUTE_VALUE_CONTENTS)[0], `is`(XQuerySyntaxHighlighterColors.COMMENT)) assertThat(highlighter.getTokenHighlights(XQDocTokenType.XML_ATTRIBUTE_VALUE_CONTENTS)[1], `is`(XQuerySyntaxHighlighterColors.XQDOC_MARKUP)) assertThat(highlighter.getTokenHighlights(XQDocTokenType.XML_ATTRIBUTE_VALUE_END).size, `is`(2)) assertThat(highlighter.getTokenHighlights(XQDocTokenType.XML_ATTRIBUTE_VALUE_END)[0], `is`(XQuerySyntaxHighlighterColors.COMMENT)) assertThat(highlighter.getTokenHighlights(XQDocTokenType.XML_ATTRIBUTE_VALUE_END)[1], `is`(XQuerySyntaxHighlighterColors.XQDOC_MARKUP)) assertThat(highlighter.getTokenHighlights(XQDocTokenType.INVALID).size, `is`(2)) assertThat(highlighter.getTokenHighlights(XQDocTokenType.INVALID)[0], `is`(XQuerySyntaxHighlighterColors.COMMENT)) assertThat(highlighter.getTokenHighlights(XQDocTokenType.INVALID)[1], `is`(XQuerySyntaxHighlighterColors.XQDOC_MARKUP)) assertThat(highlighter.getTokenHighlights(XQDocTokenType.PREDEFINED_ENTITY_REFERENCE).size, `is`(2)) assertThat(highlighter.getTokenHighlights(XQDocTokenType.PREDEFINED_ENTITY_REFERENCE)[0], `is`(XQuerySyntaxHighlighterColors.COMMENT)) assertThat(highlighter.getTokenHighlights(XQDocTokenType.PREDEFINED_ENTITY_REFERENCE)[1], `is`(XQuerySyntaxHighlighterColors.XQDOC_MARKUP)) assertThat(highlighter.getTokenHighlights(XQDocTokenType.PARTIAL_ENTITY_REFERENCE).size, `is`(2)) assertThat(highlighter.getTokenHighlights(XQDocTokenType.PARTIAL_ENTITY_REFERENCE)[0], `is`(XQuerySyntaxHighlighterColors.COMMENT)) assertThat(highlighter.getTokenHighlights(XQDocTokenType.PARTIAL_ENTITY_REFERENCE)[1], `is`(XQuerySyntaxHighlighterColors.XQDOC_MARKUP)) assertThat(highlighter.getTokenHighlights(XQDocTokenType.EMPTY_ENTITY_REFERENCE).size, `is`(2)) assertThat(highlighter.getTokenHighlights(XQDocTokenType.EMPTY_ENTITY_REFERENCE)[0], `is`(XQuerySyntaxHighlighterColors.COMMENT)) assertThat(highlighter.getTokenHighlights(XQDocTokenType.EMPTY_ENTITY_REFERENCE)[1], `is`(XQuerySyntaxHighlighterColors.XQDOC_MARKUP)) assertThat(highlighter.getTokenHighlights(XQDocTokenType.CHARACTER_REFERENCE).size, `is`(2)) assertThat(highlighter.getTokenHighlights(XQDocTokenType.CHARACTER_REFERENCE)[0], `is`(XQuerySyntaxHighlighterColors.COMMENT)) assertThat(highlighter.getTokenHighlights(XQDocTokenType.CHARACTER_REFERENCE)[1], `is`(XQuerySyntaxHighlighterColors.XQDOC_MARKUP)) } @Test @DisplayName("annotation") fun testTokenHighlights_Annotation() { val highlighter = XQuerySyntaxHighlighter assertThat(highlighter.getTokenHighlights(XQueryTokenType.ANNOTATION_INDICATOR).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.ANNOTATION_INDICATOR)[0], `is`(XQuerySyntaxHighlighterColors.ANNOTATION)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_PUBLIC).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_PUBLIC)[0], `is`(XQuerySyntaxHighlighterColors.ANNOTATION)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_PRIVATE).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_PRIVATE)[0], `is`(XQuerySyntaxHighlighterColors.ANNOTATION)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_SEQUENTIAL).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_SEQUENTIAL)[0], `is`(XQuerySyntaxHighlighterColors.ANNOTATION)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_SIMPLE).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_SIMPLE)[0], `is`(XQuerySyntaxHighlighterColors.ANNOTATION)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_UPDATING).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XQueryTokenType.K_UPDATING)[0], `is`(XQuerySyntaxHighlighterColors.ANNOTATION)) } @Test @DisplayName("attribute") fun testTokenHighlights_Attribute() { val highlighter = XQuerySyntaxHighlighter assertThat(highlighter.getTokenHighlights(XPathTokenProvider.AbbrevAttribute).size, `is`(1)) assertThat(highlighter.getTokenHighlights(XPathTokenProvider.AbbrevAttribute)[0], `is`(XQuerySyntaxHighlighterColors.ATTRIBUTE)) } }
apache-2.0
78a35632e67178a94af650c22b4d8e56
71.061037
160
0.782271
4.740649
false
false
false
false
dhleong/ideavim
src/com/maddyhome/idea/vim/action/copy/PutVisualTextMoveCursorAction.kt
1
2759
/* * IdeaVim - Vim emulator for IDEs based on the IntelliJ platform * Copyright (C) 2003-2019 The IdeaVim authors * * 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 2 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.maddyhome.idea.vim.action.copy import com.intellij.openapi.actionSystem.DataContext import com.intellij.openapi.editor.Caret import com.intellij.openapi.editor.Editor import com.maddyhome.idea.vim.VimPlugin import com.maddyhome.idea.vim.action.VimCommandAction import com.maddyhome.idea.vim.command.Command import com.maddyhome.idea.vim.command.CommandFlags import com.maddyhome.idea.vim.command.MappingMode import com.maddyhome.idea.vim.group.copy.PutData import com.maddyhome.idea.vim.group.visual.VimSelection import com.maddyhome.idea.vim.handler.VimActionHandler import com.maddyhome.idea.vim.handler.VisualOperatorActionHandler import com.maddyhome.idea.vim.helper.enumSetOf import java.util.* import javax.swing.KeyStroke /** * @author vlan */ class PutVisualTextMoveCursorAction : VimCommandAction() { override fun makeActionHandler(): VimActionHandler = object : VisualOperatorActionHandler.SingleExecution() { override fun executeForAllCarets(editor: Editor, context: DataContext, cmd: Command, caretsAndSelections: Map<Caret, VimSelection>): Boolean { if (caretsAndSelections.isEmpty()) return false val textData = VimPlugin.getRegister().lastRegister?.let { PutData.TextData(it.text, it.type, it.transferableData) } VimPlugin.getRegister().resetRegister() val insertTextBeforeCaret = cmd.keys[1].keyChar == 'P' val selection = PutData.VisualSelection(caretsAndSelections, caretsAndSelections.values.first().type) val putData = PutData(textData, selection, cmd.count, insertTextBeforeCaret, _indent = true, caretAfterInsertedText = true) return VimPlugin.getPut().putText(editor, context, putData) } } override val mappingModes: Set<MappingMode> = MappingMode.V override val keyStrokesSet: Set<List<KeyStroke>> = parseKeysSet("gp", "gP") override val type: Command.Type = Command.Type.OTHER_SELF_SYNCHRONIZED override val flags: EnumSet<CommandFlags> = enumSetOf(CommandFlags.FLAG_EXIT_VISUAL) }
gpl-2.0
24e7887c58a4302e75015b4a2e5c8a63
43.5
146
0.777818
4.251156
false
false
false
false
StepicOrg/stepic-android
app/src/main/java/org/stepik/android/domain/course_reviews/analytic/EditCourseReviewPressedAnalyticEvent.kt
2
667
package org.stepik.android.domain.course_reviews.analytic import org.stepik.android.domain.base.analytic.AnalyticEvent class EditCourseReviewPressedAnalyticEvent( courseId: Long, title: String, source: String ) : AnalyticEvent { companion object { private const val PARAM_COURSE = "course" private const val PARAM_TITLE = "title" private const val PARAM_SOURCE = "source" } override val name: String = "Edit course review pressed" override val params: Map<String, Any> = mapOf( PARAM_COURSE to courseId, PARAM_TITLE to title, PARAM_SOURCE to source ) }
apache-2.0
03afd5fcfea5e6bf98aa9af9dd372f9b
26.833333
60
0.653673
4.47651
false
false
false
false
google/zsldemo
app/src/main/java/com/hadrosaur/zsldemo/CircularResultBuffer.kt
1
3525
/* * Copyright 2019 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hadrosaur.zsldemo import android.hardware.camera2.CaptureResult import android.hardware.camera2.TotalCaptureResult import com.hadrosaur.zsldemo.MainActivity.Companion.Logd import java.util.* // When users presses the screen, there will probably be a wiggle // skip a couple of frames to improve picture quality val FRAMES_TO_SKIP = 2 class CircularResultBuffer { val buffer: ArrayDeque<TotalCaptureResult> = ArrayDeque(CIRCULAR_BUFFER_SIZE) fun add(result: TotalCaptureResult) { if (CIRCULAR_BUFFER_SIZE <= buffer.size) { buffer.removeLast() } buffer.addFirst(result) } //Returns null if no good frame fun findBestFrame() : TotalCaptureResult? { val resultArray = arrayOfNulls<TotalCaptureResult>(buffer.size) buffer.toArray(resultArray) var bestFrame: TotalCaptureResult? = null var backupFrame: TotalCaptureResult? = null // We want frame 3-10, if they are good (AF/AE converged) // If no good frames in that range, we're ok with frame 2 or 1 if they seem ok for (i in 0 until resultArray.size) { if (resultArray[i] == null) continue if (i < FRAMES_TO_SKIP) { if (isResultGood(resultArray[i]!!)) { backupFrame = resultArray[i]!! } } else { if (isResultGood(resultArray[i]!!)) { bestFrame = resultArray[i]!! break } } } if (null != bestFrame) return bestFrame if (null != backupFrame) return backupFrame Logd("CircularResultBuffer: Could not find focused frame 1-10.") //If we didn't find the matching image, or there is no timestamp just return one //Note: we pick the 3rd newest if we have it to account for the finger press causing capture to be unfocused //TODO: Add check for flash if (buffer.size >= 3) return buffer.elementAt(2) else return buffer.first } //We think a frame is good if it's AF is focused and AE is converged and we don't need flash fun isResultGood(result: TotalCaptureResult) : Boolean { val afState = result.get(CaptureResult.CONTROL_AF_STATE) val aeState = result.get(CaptureResult.CONTROL_AE_STATE) // Logd("Auto-Focus State: " + afState) // Logd("Auto-Exposure State: " + aeState) //Need AF state to be focused and AE state converged if ( (afState == CaptureResult.CONTROL_AF_STATE_FOCUSED_LOCKED || afState == CaptureResult.CONTROL_AF_STATE_PASSIVE_FOCUSED) && (aeState == CaptureResult.CONTROL_AE_STATE_CONVERGED || aeState == null)) { return true } return false } fun remove(result: TotalCaptureResult) { buffer.remove(result) } }
apache-2.0
d5804b6896cc45f96a0832507fd994f3
33.910891
132
0.637447
4.241877
false
false
false
false
MrSugarCaney/DirtyArrows
src/main/kotlin/nl/sugcube/dirtyarrows/bow/ability/BabyBow.kt
1
1318
package nl.sugcube.dirtyarrows.bow.ability import nl.sugcube.dirtyarrows.DirtyArrows import nl.sugcube.dirtyarrows.bow.BowAbility import nl.sugcube.dirtyarrows.bow.DefaultBow import nl.sugcube.dirtyarrows.util.showHealParticle import org.bukkit.attribute.Attribute import org.bukkit.entity.Ageable import org.bukkit.entity.Arrow import org.bukkit.entity.Player import org.bukkit.event.entity.ProjectileHitEvent /** * Turns baby animals into adults. Turns adult animals into babies. Heals the animal. * * @author SugarCaney */ open class BabyBow(plugin: DirtyArrows) : BowAbility( plugin = plugin, type = DefaultBow.BABY, canShootInProtectedRegions = false, protectionRange = 1.0, description = "Turn babies into adults, and adults into babies.", removeArrow = false ) { override fun land(arrow: Arrow, player: Player, event: ProjectileHitEvent) { val entity = event.hitEntity as? Ageable ?: return val maxHealthAttribute = entity.getAttribute(Attribute.GENERIC_MAX_HEALTH) ?: return if (entity.isAdult) { entity.setBaby() } else entity.setAdult() entity.health = maxHealthAttribute.value repeat(5) { entity.location.showHealParticle(1) } arrow.remove() } }
gpl-3.0
75e86da3bb47a1afe59c06c293a52d31
29.674419
92
0.701062
4.144654
false
false
false
false
NerdNumber9/TachiyomiEH
app/src/main/java/eu/kanade/tachiyomi/data/backup/BackupRestoreService.kt
1
19708
package eu.kanade.tachiyomi.data.backup import android.app.Service import android.content.Context import android.content.Intent import android.net.Uri import android.os.Build import android.os.IBinder import android.os.PowerManager import com.elvishew.xlog.XLog import com.github.salomonbrys.kotson.fromJson import com.google.gson.JsonArray import com.google.gson.JsonParser import com.google.gson.stream.JsonReader import eu.kanade.tachiyomi.R import eu.kanade.tachiyomi.data.backup.models.Backup.CATEGORIES import eu.kanade.tachiyomi.data.backup.models.Backup.CHAPTERS import eu.kanade.tachiyomi.data.backup.models.Backup.HISTORY import eu.kanade.tachiyomi.data.backup.models.Backup.MANGA import eu.kanade.tachiyomi.data.backup.models.Backup.MANGAS import eu.kanade.tachiyomi.data.backup.models.Backup.TRACK import eu.kanade.tachiyomi.data.backup.models.Backup.VERSION import eu.kanade.tachiyomi.data.backup.models.DHistory import eu.kanade.tachiyomi.data.database.DatabaseHelper import eu.kanade.tachiyomi.data.database.models.* import eu.kanade.tachiyomi.data.track.TrackManager import eu.kanade.tachiyomi.source.Source import eu.kanade.tachiyomi.util.chop import eu.kanade.tachiyomi.util.isServiceRunning import eu.kanade.tachiyomi.util.sendLocalBroadcast import exh.BackupEntry import exh.EH_SOURCE_ID import exh.EXHMigrations import exh.EXH_SOURCE_ID import exh.eh.EHentaiThrottleManager import exh.eh.EHentaiUpdateWorker import rx.Observable import rx.Subscription import rx.schedulers.Schedulers import uy.kohesive.injekt.injectLazy import java.io.File import java.text.SimpleDateFormat import java.util.Date import java.util.Locale import java.util.concurrent.ExecutorService import java.util.concurrent.Executors /** * Restores backup from json file */ class BackupRestoreService : Service() { companion object { /** * Returns the status of the service. * * @param context the application context. * @return true if the service is running, false otherwise. */ private fun isRunning(context: Context): Boolean = context.isServiceRunning(BackupRestoreService::class.java) /** * Starts a service to restore a backup from Json * * @param context context of application * @param uri path of Uri */ fun start(context: Context, uri: Uri) { if (!isRunning(context)) { val intent = Intent(context, BackupRestoreService::class.java).apply { putExtra(BackupConst.EXTRA_URI, uri) } context.startService(intent) } } /** * Stops the service. * * @param context the application context. */ fun stop(context: Context) { context.stopService(Intent(context, BackupRestoreService::class.java)) } } /** * Wake lock that will be held until the service is destroyed. */ private lateinit var wakeLock: PowerManager.WakeLock /** * Subscription where the update is done. */ private var subscription: Subscription? = null /** * The progress of a backup restore */ private var restoreProgress = 0 /** * Amount of manga in Json file (needed for restore) */ private var restoreAmount = 0 /** * List containing errors */ private val errors = mutableListOf<Pair<Date, String>>() /** * Backup manager */ private lateinit var backupManager: BackupManager /** * Database */ private val db: DatabaseHelper by injectLazy() /** * Tracking manager */ internal val trackManager: TrackManager by injectLazy() private lateinit var executor: ExecutorService private val throttleManager = EHentaiThrottleManager() /** * Method called when the service is created. It injects dependencies and acquire the wake lock. */ override fun onCreate() { super.onCreate() wakeLock = (getSystemService(Context.POWER_SERVICE) as PowerManager).newWakeLock( PowerManager.PARTIAL_WAKE_LOCK, "BackupRestoreService:WakeLock") wakeLock.acquire() executor = Executors.newSingleThreadExecutor() } /** * Method called when the service is destroyed. It destroys the running subscription and * releases the wake lock. */ override fun onDestroy() { subscription?.unsubscribe() executor.shutdown() // must be called after unsubscribe if (wakeLock.isHeld) { wakeLock.release() } super.onDestroy() } /** * This method needs to be implemented, but it's not used/needed. */ override fun onBind(intent: Intent): IBinder? = null /** * Method called when the service receives an intent. * * @param intent the start intent from. * @param flags the flags of the command. * @param startId the start id of this command. * @return the start value of the command. */ override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { if (intent == null) return Service.START_NOT_STICKY val uri = intent.getParcelableExtra<Uri>(BackupConst.EXTRA_URI) throttleManager.resetThrottle() // Unsubscribe from any previous subscription if needed. subscription?.unsubscribe() subscription = Observable.using( { // Pause auto-gallery-update during restore if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { EHentaiUpdateWorker.cancelBackground(this) } db.lowLevel().beginTransaction() }, { getRestoreObservable(uri).doOnNext { db.lowLevel().setTransactionSuccessful() } }, { // Resume auto-gallery-update if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { EHentaiUpdateWorker.scheduleBackground(this) } executor.execute { db.lowLevel().endTransaction() } }) .doAfterTerminate { stopSelf(startId) } .subscribeOn(Schedulers.from(executor)) .subscribe() return Service.START_NOT_STICKY } /** * Returns an [Observable] containing restore process. * * @param uri restore file * @return [Observable<Manga>] */ private fun getRestoreObservable(uri: Uri): Observable<List<Manga>> { val startTime = System.currentTimeMillis() return Observable.just(Unit) .map { val reader = JsonReader(contentResolver.openInputStream(uri).bufferedReader()) val json = JsonParser().parse(reader).asJsonObject // Get parser version val version = json.get(VERSION)?.asInt ?: 1 // Initialize manager backupManager = BackupManager(this, version) val mangasJson = json.get(MANGAS).asJsonArray restoreAmount = mangasJson.size() + 1 // +1 for categories restoreProgress = 0 errors.clear() // Restore categories json.get(CATEGORIES)?.let { backupManager.restoreCategories(it.asJsonArray) restoreProgress += 1 showRestoreProgress(restoreProgress, restoreAmount, "Categories added", errors.size) } mangasJson } .flatMap { Observable.from(it) } .concatMap { val obj = it.asJsonObject val manga = backupManager.parser.fromJson<MangaImpl>(obj.get(MANGA)) val chapters = backupManager.parser.fromJson<List<ChapterImpl>>(obj.get(CHAPTERS) ?: JsonArray()) val categories = backupManager.parser.fromJson<List<String>>(obj.get(CATEGORIES) ?: JsonArray()) val history = backupManager.parser.fromJson<List<DHistory>>(obj.get(HISTORY) ?: JsonArray()) val tracks = backupManager.parser.fromJson<List<TrackImpl>>(obj.get(TRACK) ?: JsonArray()) // EXH --> val migrated = EXHMigrations.migrateBackupEntry( BackupEntry( manga, chapters, categories, history, tracks ) ) val observable = migrated.flatMap { (manga, chapters, categories, history, tracks) -> getMangaRestoreObservable(manga, chapters, categories, history, tracks) } // EXH <-- if (observable != null) { observable } else { errors.add(Date() to "${manga.title} - ${getString(R.string.source_not_found)}") restoreProgress += 1 val content = getString(R.string.dialog_restoring_source_not_found, manga.title.chop(15)) showRestoreProgress(restoreProgress, restoreAmount, manga.title, errors.size, content) Observable.just(manga) } } .toList() .doOnNext { val endTime = System.currentTimeMillis() val time = endTime - startTime val logFile = writeErrorLog() val completeIntent = Intent(BackupConst.INTENT_FILTER).apply { putExtra(BackupConst.EXTRA_TIME, time) putExtra(BackupConst.EXTRA_ERRORS, errors.size) putExtra(BackupConst.EXTRA_ERROR_FILE_PATH, logFile.parent) putExtra(BackupConst.EXTRA_ERROR_FILE, logFile.name) putExtra(BackupConst.ACTION, BackupConst.ACTION_RESTORE_COMPLETED_DIALOG) } sendLocalBroadcast(completeIntent) } .doOnError { error -> // [EXH] XLog.w("> Failed to perform restore!", error) XLog.w("> (uri: %s)", uri) writeErrorLog() val errorIntent = Intent(BackupConst.INTENT_FILTER).apply { putExtra(BackupConst.ACTION, BackupConst.ACTION_ERROR_RESTORE_DIALOG) putExtra(BackupConst.EXTRA_ERROR_MESSAGE, error.message) } sendLocalBroadcast(errorIntent) } .onErrorReturn { emptyList() } } /** * Write errors to error log */ private fun writeErrorLog(): File { try { if (errors.isNotEmpty()) { val destFile = File(externalCacheDir, "tachiyomi_restore.log") val sdf = SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS", Locale.getDefault()) destFile.bufferedWriter().use { out -> errors.forEach { (date, message) -> out.write("[${sdf.format(date)}] $message\n") } } return destFile } } catch (e: Exception) { // Empty } return File("") } /** * Returns a manga restore observable * * @param manga manga data from json * @param chapters chapters data from json * @param categories categories data from json * @param history history data from json * @param tracks tracking data from json * @return [Observable] containing manga restore information */ private fun getMangaRestoreObservable(manga: Manga, chapters: List<Chapter>, categories: List<String>, history: List<DHistory>, tracks: List<Track>): Observable<Manga>? { // Get source val source = backupManager.sourceManager.getOrStub(manga.source) val dbManga = backupManager.getMangaFromDatabase(manga) return if (dbManga == null) { // Manga not in database mangaFetchObservable(source, manga, chapters, categories, history, tracks) } else { // Manga in database // Copy information from manga already in database backupManager.restoreMangaNoFetch(manga, dbManga) // Fetch rest of manga information mangaNoFetchObservable(source, manga, chapters, categories, history, tracks) } } /** * [Observable] that fetches manga information * * @param manga manga that needs updating * @param chapters chapters of manga that needs updating * @param categories categories that need updating */ private fun mangaFetchObservable(source: Source, manga: Manga, chapters: List<Chapter>, categories: List<String>, history: List<DHistory>, tracks: List<Track>): Observable<Manga> { if(source.id == EH_SOURCE_ID || source.id == EXH_SOURCE_ID) throttleManager.throttle() return backupManager.restoreMangaFetchObservable(source, manga) .onErrorReturn { // [EXH] XLog.w("> Failed to restore manga!", it) XLog.w("> (source.id: %s, source.name: %s, manga.id: %s, manga.url: %s)", source.id, source.name, manga.id, manga.url) errors.add(Date() to "${manga.title} - ${it.message}") manga } .filter { it.id != null } .flatMap { chapterFetchObservable(source, it, chapters) // Convert to the manga that contains new chapters. .map { manga } } .doOnNext { restoreExtraForManga(it, categories, history, tracks) } .flatMap { trackingFetchObservable(it, tracks) // Convert to the manga that contains new chapters. .map { manga } } .doOnCompleted { restoreProgress += 1 showRestoreProgress(restoreProgress, restoreAmount, manga.title, errors.size) } } private fun mangaNoFetchObservable(source: Source, backupManga: Manga, chapters: List<Chapter>, categories: List<String>, history: List<DHistory>, tracks: List<Track>): Observable<Manga> { return Observable.just(backupManga) .flatMap { manga -> if (!backupManager.restoreChaptersForManga(manga, chapters)) { chapterFetchObservable(source, manga, chapters) .map { manga } } else { Observable.just(manga) } } .doOnNext { restoreExtraForManga(it, categories, history, tracks) } .flatMap { manga -> trackingFetchObservable(manga, tracks) // Convert to the manga that contains new chapters. .map { manga } } .doOnCompleted { restoreProgress += 1 showRestoreProgress(restoreProgress, restoreAmount, backupManga.title, errors.size) } } private fun restoreExtraForManga(manga: Manga, categories: List<String>, history: List<DHistory>, tracks: List<Track>) { // Restore categories backupManager.restoreCategoriesForManga(manga, categories) // Restore history backupManager.restoreHistoryForManga(history) // Restore tracking backupManager.restoreTrackForManga(manga, tracks) } /** * [Observable] that fetches chapter information * * @param source source of manga * @param manga manga that needs updating * @return [Observable] that contains manga */ private fun chapterFetchObservable(source: Source, manga: Manga, chapters: List<Chapter>): Observable<Pair<List<Chapter>, List<Chapter>>> { return backupManager.restoreChapterFetchObservable(source, manga, chapters, throttleManager) // If there's any error, return empty update and continue. .onErrorReturn { // [EXH] XLog.w("> Failed to restore chapter!", it) XLog.w("> (source.id: %s, source.name: %s, manga.id: %s, manga.url: %s, chapters.size: %s)", source.id, source.name, manga.id, manga.url, chapters.size) errors.add(Date() to "${manga.title} - ${it.message}") Pair(emptyList(), emptyList()) } } /** * [Observable] that refreshes tracking information * @param manga manga that needs updating. * @param tracks list containing tracks from restore file. * @return [Observable] that contains updated track item */ private fun trackingFetchObservable(manga: Manga, tracks: List<Track>): Observable<Track> { return Observable.from(tracks) .concatMap { track -> val service = trackManager.getService(track.sync_id) if (service != null && service.isLogged) { service.refresh(track) .doOnNext { db.insertTrack(it).executeAsBlocking() } .onErrorReturn { errors.add(Date() to "${manga.title} - ${it.message}") track } } else { errors.add(Date() to "${manga.title} - ${service?.name} not logged in") Observable.empty() } } } /** * Called to update dialog in [BackupConst] * * @param progress restore progress * @param amount total restoreAmount of manga * @param title title of restored manga */ private fun showRestoreProgress(progress: Int, amount: Int, title: String, errors: Int, content: String = getString(R.string.dialog_restoring_backup, title.chop(15))) { val intent = Intent(BackupConst.INTENT_FILTER).apply { putExtra(BackupConst.EXTRA_PROGRESS, progress) putExtra(BackupConst.EXTRA_AMOUNT, amount) putExtra(BackupConst.EXTRA_CONTENT, content) putExtra(BackupConst.EXTRA_ERRORS, errors) putExtra(BackupConst.ACTION, BackupConst.ACTION_SET_PROGRESS_DIALOG) } sendLocalBroadcast(intent) } }
apache-2.0
ca2f1815219420a685c1d76ee7b9cebf
38.025743
143
0.554343
5.34962
false
false
false
false
GKZX-HN/MyGithub
app/src/main/java/com/gkzxhn/mygithub/mvp/presenter/ProfilePresenter.kt
1
6166
package com.gkzxhn.mygithub.mvp.presenter import android.util.Log import com.gkzxhn.balabala.mvp.contract.BaseView import com.gkzxhn.mygithub.api.OAuthApi import com.gkzxhn.mygithub.bean.info.Organization import com.gkzxhn.mygithub.bean.info.User import com.gkzxhn.mygithub.constant.SharedPreConstant import com.gkzxhn.mygithub.extension.getSharedPreference import com.gkzxhn.mygithub.ui.activity.UserActivity import com.gkzxhn.mygithub.ui.fragment.ProfileFragment import com.gkzxhn.mygithub.utils.rxbus.RxBus import com.google.gson.Gson import com.trello.rxlifecycle2.kotlin.bindToLifecycle import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.schedulers.Schedulers import java.lang.Exception import javax.inject.Inject /** * Created by 方 on 2017/10/24. */ class ProfilePresenter @Inject constructor(private val oAuthApi: OAuthApi, private val view: BaseView, private val gson: Gson, private val rxBus: RxBus) { fun loadUserData(username: String) { view.showLoading() oAuthApi.getUserOrgs(username) .bindToLifecycle(view as ProfileFragment) .subscribeOn(Schedulers.io()) .unsubscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe({ t -> view.hideLoading() val datas = arrayListOf<Organization>() datas.addAll(t) view.loadData(datas!!) Log.i(javaClass.simpleName, t.toString()) }, { e -> view.hideLoading() Log.e(javaClass.simpleName, e.message) }) } fun getOrg(orgName: String) { view.showLoading() oAuthApi.getOrg(orgName) .bindToLifecycle(view as UserActivity) .subscribeOn(Schedulers.io()) .unsubscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe({ t -> view.hideLoading() view.loadData(t) Log.i(javaClass.simpleName, t.toString()) }, { e -> view.hideLoading() Log.e(javaClass.simpleName, e.message) }) } fun subscribe() { rxBus.toFlowable(User::class.java) .bindToLifecycle(view as ProfileFragment) .subscribe( { user: User? -> view.getNewData() } ) } fun getUser(username: String) { view.showLoading() oAuthApi.getUser(username) .bindToLifecycle(view as UserActivity) .subscribeOn(Schedulers.io()) .unsubscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe({ user -> view.hideLoading() view.loadData(user) Log.i(javaClass.simpleName, user.toString()) }, { e -> view.hideLoading() Log.e(javaClass.simpleName, e.message) }) } fun getLocalUser(): User? { try { return gson.fromJson(SharedPreConstant.USER_SP .getSharedPreference() .getString(SharedPreConstant.USER_JSON, ""), User::class.java) } catch (e: Exception) { Log.e(javaClass.simpleName, e.message) return null } } /** * 检查是否关注该用户 */ fun checkIfFollowIng(username: String){ (view as UserActivity).updateListFollowStatus(-1) oAuthApi.checkIfFollowUser(username) .bindToLifecycle(view) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe({ t -> //TODO Log.i(javaClass.simpleName, t.message()) if (t.code() == 204) { view.updateListFollowStatus(0) }else{ view.updateListFollowStatus(1) } },{ e -> Log.i(javaClass.simpleName, e.message) }) } /** * 关注用户 */ fun followUser(username: String) { (view as UserActivity).updateListFollowStatus(-1) oAuthApi.followUser(username) .bindToLifecycle(view as UserActivity) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe({ t -> //TODO Log.i(javaClass.simpleName, t.message()) if (t.code() == 204) { view.updateListFollowStatus(0) }else { view.updateListFollowStatus(1) } }, { e -> Log.e(javaClass.simpleName, e.message) }) } /** * 取消关注用户 */ fun unFollowUser(username: String) { (view as UserActivity).updateListFollowStatus(-1) oAuthApi.unFollowUser(username) .bindToLifecycle(view as UserActivity) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe({ t -> //TODO Log.i(javaClass.simpleName, t.message()) if (t.code() == 204) { view.updateListFollowStatus(1) }else { view.updateListFollowStatus(0) } }, { e -> Log.e(javaClass.simpleName, e.message) }) } }
gpl-3.0
e09ec781e70bde82bdeab9cc6972c657
33.615819
82
0.497551
5.378402
false
false
false
false
exponentjs/exponent
packages/expo-dev-menu/android/src/main/java/expo/modules/devmenu/detectors/ShakeDetector.kt
2
3205
package expo.modules.devmenu.detectors import android.hardware.Sensor import android.hardware.SensorEvent import android.hardware.SensorEventListener import android.hardware.SensorManager import java.util.concurrent.TimeUnit import kotlin.math.abs /** * Number of nanoseconds that must elapse before we start detecting next gesture. */ private val MIN_TIME_AFTER_SHAKE_NS = TimeUnit.NANOSECONDS.convert(600, TimeUnit.MILLISECONDS) /** * Required force to constitute a rage shake. Need to multiply gravity by 1.33 because a rage * shake in one direction should have more force than just the magnitude of free fall. */ private const val REQUIRED_FORCE = SensorManager.GRAVITY_EARTH * 1.33f /** * Listens for the user shaking their phone. Allocation-less once it starts listening. */ class ShakeDetector(private val shakeListener: () -> Unit) : SensorEventListener { private var accelerationX = 0F private var accelerationY = 0F private var accelerationZ = 0F private var sensorManager: SensorManager? = null private var numShakes = 0 private var lastDispatchedShakeTimestamp = 0L var minRecordedShakes = 3 //region publics /** * Start listening for shakes. */ fun start(manager: SensorManager) { manager .getDefaultSensor(Sensor.TYPE_ACCELEROMETER) ?.let { sensorManager = manager manager.registerListener(this, it, SensorManager.SENSOR_DELAY_UI) lastDispatchedShakeTimestamp = 0 reset() } } /** * Stop listening for shakes. */ fun stop() { sensorManager?.unregisterListener(this) sensorManager = null } //endregion publics //region SensorEventListener override fun onSensorChanged(sensorEvent: SensorEvent) { if (sensorEvent.timestamp - lastDispatchedShakeTimestamp < MIN_TIME_AFTER_SHAKE_NS) { return } val ax = sensorEvent.values[0] val ay = sensorEvent.values[1] val az = sensorEvent.values[2] - SensorManager.GRAVITY_EARTH when { atLeastRequiredForce(ax) && ax * accelerationX <= 0 -> { numShakes++ accelerationX = ax } atLeastRequiredForce(ay) && ay * accelerationY <= 0 -> { numShakes++ accelerationY = ay } atLeastRequiredForce(az) && az * accelerationZ <= 0 -> { numShakes++ accelerationZ = az } } if (numShakes >= minRecordedShakes) { reset() shakeListener.invoke() lastDispatchedShakeTimestamp = sensorEvent.timestamp } } override fun onAccuracyChanged(sensor: Sensor, i: Int) {} //endregion SensorEventListener //region internals /** Reset all variables used to keep track of number of shakes recorded. */ private fun reset() { numShakes = 0 accelerationX = 0f accelerationY = 0f accelerationZ = 0f } /** * Determine if acceleration applied to sensor is large enough to count as a rage shake. * * @param a acceleration in x, y, or z applied to the sensor * @return true if the magnitude of the force exceeds the minimum required amount of force. false * otherwise. */ private fun atLeastRequiredForce(a: Float) = abs(a) > REQUIRED_FORCE //endregion internals }
bsd-3-clause
e5697bd9bf8cef85c3e33ee6fbed27f6
26.393162
99
0.693604
4.261968
false
false
false
false
aarmea/noise
app/src/main/java/com/alternativeinfrastructures/noise/models/LocalIdentity.kt
1
2941
package com.alternativeinfrastructures.noise.models import com.alternativeinfrastructures.noise.NoiseDatabase import com.alternativeinfrastructures.noise.models.signal.TypeConverters import com.alternativeinfrastructures.noise.storage.IdentityAnnouncementMessage import com.alternativeinfrastructures.noise.storage.UnknownMessage import com.raizlabs.android.dbflow.annotation.Column import com.raizlabs.android.dbflow.annotation.ForeignKey import com.raizlabs.android.dbflow.annotation.Index import com.raizlabs.android.dbflow.annotation.PrimaryKey import com.raizlabs.android.dbflow.annotation.Table import com.raizlabs.android.dbflow.rx2.structure.BaseRXModel import org.whispersystems.libsignal.IdentityKeyPair import org.whispersystems.libsignal.InvalidKeyException import org.whispersystems.libsignal.state.SignedPreKeyRecord import org.whispersystems.libsignal.util.KeyHelper import java.io.IOException import io.reactivex.Single @Table(database = NoiseDatabase::class) class LocalIdentity : BaseRXModel() { @Index var username: String = "" protected set var registrationId: Int = 0 protected set @PrimaryKey @Column(typeConverter = TypeConverters.IdentityKeyPairConverter::class) lateinit var identityKeyPair: IdentityKeyPair @Column(typeConverter = TypeConverters.SignedPreKeyRecordConverter::class) lateinit var signedPreKey: SignedPreKeyRecord @ForeignKey var remoteIdentity: RemoteIdentity? = null private fun createRemoteIdentity(): RemoteIdentity { // TODO: Is using the registrationId as the deviceId okay? return RemoteIdentity(username, registrationId, identityKeyPair.publicKey) } companion object { fun validUsername(username: String?): Boolean { // TODO: Other constraints? return username != null && username.length >= 5 && username.length <= 31 } @Throws(IOException::class, InvalidKeyException::class, UnknownMessage.PayloadTooLargeException::class) fun createNew(username: String): Single<Boolean> { val identity = LocalIdentity() identity.username = username identity.registrationId = KeyHelper.generateRegistrationId(true /*extendedRange*/) identity.identityKeyPair = KeyHelper.generateIdentityKeyPair() // TODO: Once there's support for multiple identities, increment the signedPreKeyId identity.signedPreKey = KeyHelper.generateSignedPreKey( identity.identityKeyPair, 0 /*signedPreKeyId*/) val remoteIdentity = identity.createRemoteIdentity() identity.remoteIdentity = remoteIdentity return IdentityAnnouncementMessage.createAndSignAsync(remoteIdentity, IdentityAnnouncementMessage.DEFAULT_ZERO_BITS) .flatMap { UnknownMessage -> identity.save() } } } class MissingLocalIdentity : Exception() }
mit
64fdb3a2a89b81160d2864d3f79815c3
39.847222
128
0.752125
4.91806
false
false
false
false
fcostaa/kotlin-rxjava-android
feature/listing/src/main/kotlin/com/github/felipehjcosta/marvelapp/listing/presentation/CharacterListViewModelInputOutput.kt
1
2609
package com.github.felipehjcosta.marvelapp.listing.presentation import com.felipecosta.rxaction.RxAction import com.felipecosta.rxaction.RxCommand import com.github.felipehjcosta.marvelapp.base.character.data.pojo.Character import com.github.felipehjcosta.marvelapp.listing.datamodel.ListingDataModel import com.jakewharton.rxrelay2.BehaviorRelay import io.reactivex.Observable import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.schedulers.Schedulers import javax.inject.Inject class CharacterListViewModelInputOutput @Inject constructor( private val dataModel: ListingDataModel ) : CharacterListViewModel(), CharacterListViewModelInput, CharacterListViewModelOutput { private val asyncLoadItemsCommand: RxAction<Any, List<Character>> = RxAction { dataModel.loadItems() .subscribeOn(Schedulers.newThread()) .observeOn(AndroidSchedulers.mainThread()) } private val asyncLoadMoreCommand: RxAction<Any, List<Character>> = RxAction { currentItemsOffsetRelay .take(1) .flatMap { dataModel.loadItems(offset = it) } .subscribeOn(Schedulers.newThread()) .observeOn(AndroidSchedulers.mainThread()) } private val currentItemsOffsetRelay = BehaviorRelay.createDefault(0) override val input: CharacterListViewModelInput = this override val output: CharacterListViewModelOutput = this override val items: Observable<List<CharacterItemViewModel>> get() = asyncLoadItemsCommand.elements.map { it.size to it } .doOnNext { currentItemsOffsetRelay.accept(it.first) } .map { it.second } .map { it.map { CharacterItemViewModel(it.id, it.name, it.thumbnail.url) } } override val newItems: Observable<List<CharacterItemViewModel>> get() = asyncLoadMoreCommand.elements.map { currentItemsOffsetRelay.value!! + it.size to it } .doOnNext { currentItemsOffsetRelay.accept(it.first) } .map { it.second } .map { it.map { CharacterItemViewModel(it.id, it.name, it.thumbnail.url) } } override val showLoading: Observable<Boolean> get() = asyncLoadItemsCommand.executing override val showLoadItemsError: Observable<Boolean> get() = asyncLoadItemsCommand.errors.map { true } override val showLoadingMore: Observable<Boolean> get() = asyncLoadMoreCommand.executing override val loadItemsCommand: RxCommand<Any> get() = asyncLoadItemsCommand override val loadMoreItemsCommand: RxCommand<Any> get() = asyncLoadMoreCommand }
mit
1f79fb80dd7e14482d537befb3071ebe
40.412698
101
0.730165
4.617699
false
false
false
false
shibafu528/SperMaster
app/src/main/kotlin/info/shibafu528/spermaster/util/TypefaceManager.kt
1
837
package info.shibafu528.spermaster.util import android.content.Context import android.graphics.Typeface import android.support.v4.util.SparseArrayCompat /** * Created by shibafu on 15/07/20. */ public final class TypefaceManager { companion object { private val typefaces = SparseArrayCompat<Typeface>() public fun getTypeface(context: Context, asset: AssetTypeface): Typeface { var typeface = typefaces.get(asset.ordinal) if (typeface == null) { typeface = Typeface.createFromAsset(context.assets, asset.fileName) typefaces[asset.ordinal] = typeface } return typeface } } public enum class AssetTypeface(val fileName: String) { KORURI("Koruri-Regular.ttf"), KORURI_LIGHT("Koruri-Light.ttf") } }
mit
975f660e73c312239ec91a4f9d0429e9
28.928571
83
0.655914
4.314433
false
false
false
false
kelsos/mbrc
app/src/main/kotlin/com/kelsos/mbrc/ui/dialogs/SettingsDialogFragment.kt
1
3368
package com.kelsos.mbrc.ui.dialogs import android.app.Dialog import android.content.Context import android.os.Bundle import android.text.TextUtils import android.widget.EditText import androidx.fragment.app.DialogFragment import com.google.android.material.dialog.MaterialAlertDialogBuilder import com.kelsos.mbrc.R import com.kelsos.mbrc.data.ConnectionSettings class SettingsDialogFragment : DialogFragment() { lateinit var hostEdit: EditText lateinit var nameEdit: EditText lateinit var portEdit: EditText private var mListener: SettingsSaveListener? = null private lateinit var settings: ConnectionSettings private var edit: Boolean = false private fun setConnectionSettings(settings: ConnectionSettings) { this.settings = settings } override fun onAttach(context: Context) { super.onAttach(context) try { mListener = context as SettingsSaveListener? } catch (e: ClassCastException) { throw ClassCastException("$context must implement SettingsDialogListener") } } override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { val dialog = MaterialAlertDialogBuilder(requireActivity()) .setView(R.layout.ui_dialog_settings) .setTitle(if (edit) R.string.settings_dialog_edit else R.string.settings_dialog_add) .setPositiveButton(if (edit) R.string.settings_dialog_save else R.string.settings_dialog_add) { dialog, _ -> var shouldIClose = true val hostname = hostEdit.text.toString() val computerName = nameEdit.text.toString() if (hostname.isEmpty() || computerName.isEmpty()) { shouldIClose = false } val portText = portEdit.text.toString() val portNum = if (TextUtils.isEmpty(portText)) 0 else Integer.parseInt(portText) if (isValid(portNum) && shouldIClose) { settings.name = computerName settings.address = hostname settings.port = portNum mListener?.onSave(settings) dialog.dismiss() } }.setNegativeButton(android.R.string.cancel) { dialog, _ -> dialog.dismiss() } .show() hostEdit = dialog.findViewById(R.id.settings_dialog_host) ?: error("not found") nameEdit = dialog.findViewById(R.id.settings_dialog_name) ?: error("not found") portEdit = dialog.findViewById(R.id.settings_dialog_port) ?: error("not found") return dialog } override fun onStart() { super.onStart() nameEdit.setText(settings.name) hostEdit.setText(settings.address) if (settings.port > 0) { portEdit.setText(settings.port.toString()) } } private fun isValid(port: Int): Boolean = if (port < MIN_PORT || port > MAX_PORT) { portEdit.error = getString(R.string.alert_invalid_port_number) false } else { true } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) if (!edit) { settings = ConnectionSettings() } } interface SettingsSaveListener { fun onSave(settings: ConnectionSettings) } companion object { private const val MAX_PORT = 65535 private const val MIN_PORT = 1 fun newInstance(settings: ConnectionSettings): SettingsDialogFragment { val fragment = SettingsDialogFragment() fragment.setConnectionSettings(settings) fragment.edit = true return fragment } } }
gpl-3.0
52972b7ddadfe9abba8fc8c498f1c309
29.618182
114
0.70101
4.362694
false
false
false
false
JordyLangen/vaultbox
app/src/main/java/com/jlangen/vaultbox/architecture/state/StateStore.kt
1
1803
package com.jlangen.vaultbox.architecture.state import android.content.Context class StateStore { // works based on the assumption that view id + activity name is unique // if you use an id twice in the same view tree, well that's just on you companion object { private val states: MutableList<StateHolder<*>> = mutableListOf() fun <TState> update(id: Int, state: TState, context: Context) { val contextName = context.javaClass.name val currentState = states.find { it.viewId == id && it.contextName == contextName } if (currentState == null) { states.add(StateHolder(id, state, context.javaClass.name)) } else if (!currentState.activityFinished) { states.remove(currentState) states.add(StateHolder(id, state, context.javaClass.name)) } else { states.remove(currentState) } } @Suppress("UNCHECKED_CAST") fun <TState> resolve(id: Int, context: Context): TState? { val contextName = context.javaClass.name val stateHolder = states.find { it.viewId == id && it.contextName == contextName && !it.activityFinished } if (stateHolder == null) { return null } else { return stateHolder.state as TState } } fun markFinished(context: Context) { val contextName = context.javaClass.name states.forEach { stateHolder -> stateHolder.activityFinished = contextName == stateHolder.contextName } } } private data class StateHolder<out TState>(val viewId: Int, val state: TState, val contextName: String, var activityFinished: Boolean = false) }
apache-2.0
b9c4652958f038703c7830dbbb660da7
36.583333
146
0.602329
4.859838
false
false
false
false
micolous/metrodroid
src/commonMain/kotlin/au/id/micolous/metrodroid/transit/smartrider/SmartRiderTransitData.kt
1
7726
/* * SmartRiderTransitData.kt * * Copyright 2016-2018 Michael Farrell <micolous+git@gmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package au.id.micolous.metrodroid.transit.smartrider import au.id.micolous.metrodroid.card.classic.ClassicCard import au.id.micolous.metrodroid.card.classic.ClassicCardTransitFactory import au.id.micolous.metrodroid.card.classic.ClassicSector import au.id.micolous.metrodroid.multi.Log import au.id.micolous.metrodroid.multi.Parcelize import au.id.micolous.metrodroid.multi.R import au.id.micolous.metrodroid.transit.* import au.id.micolous.metrodroid.util.HashUtils /** * Reader for SmartRider (Western Australia) and MyWay (Australian Capital Territory / Canberra) * https://github.com/micolous/metrodroid/wiki/SmartRider * https://github.com/micolous/metrodroid/wiki/MyWay */ @Parcelize class SmartRiderTransitData (override val serialNumber: String?, private val mBalance: Int, override val trips: List<TransactionTripAbstract>, private val mCardType: CardType): TransitData() { public override val balance: TransitCurrency? get() = TransitCurrency.AUD(mBalance) override val cardName: String get() = mCardType.friendlyName enum class CardType constructor(val friendlyName: String) { UNKNOWN("Unknown SmartRider"), SMARTRIDER(SMARTRIDER_NAME), MYWAY(MYWAY_NAME) } companion object { private const val SMARTRIDER_NAME = "SmartRider" private const val MYWAY_NAME = "MyWay" private const val TAG = "SmartRiderTransitData" private val SMARTRIDER_CARD_INFO = CardInfo( imageId = R.drawable.smartrider_card, name = SMARTRIDER_NAME, locationId = R.string.location_wa_australia, cardType = au.id.micolous.metrodroid.card.CardType.MifareClassic, keysRequired = true, region = TransitRegion.AUSTRALIA, preview = true) // We don't know about ferries. private val MYWAY_CARD_INFO = CardInfo( imageId = R.drawable.myway_card, name = MYWAY_NAME, locationId = R.string.location_act_australia, cardType = au.id.micolous.metrodroid.card.CardType.MifareClassic, region = TransitRegion.AUSTRALIA, keysRequired = true) private fun parse(card: ClassicCard): SmartRiderTransitData { val mCardType = detectKeyType(card.sectors) val serialNumber = getSerialData(card) // Read trips. val tagBlocks = (10..13).flatMap { s -> (0..2).map { b -> card[s,b] } } val tagRecords = tagBlocks.map { b -> SmartRiderTagRecord.parse(mCardType, b.data) }.filter { it.isValid } // Build the Tag events into trips. val trips = TransactionTrip.merge(tagRecords) // TODO: Figure out balance priorities properly. // This presently only picks whatever balance is lowest. Recharge events aren't understood, // and parking fees (SmartRider only) are also not understood. So just pick whatever is // the lowest balance, and we're probably right, unless the user has just topped up their // card. val recordA = card.getSector(2).getBlock(2).data val recordB = card.getSector(3).getBlock(2).data val balanceA = recordA.byteArrayToIntReversed(7, 2) val balanceB = recordB.byteArrayToIntReversed(7, 2) Log.d(TAG, "balanceA = $balanceA, balanceB = $balanceB") val mBalance = if (balanceA < balanceB) balanceA else balanceB return SmartRiderTransitData(mBalance = mBalance, trips = trips, mCardType = mCardType, serialNumber = serialNumber) } // Unfortunately, there's no way to reliably identify these cards except for the "standard" keys // which are used for some empty sectors. It is not enough to read the whole card (most data is // protected by a unique key). // // We don't want to actually include these keys in the program, so include a hashed version of // this key. private const val MYWAY_KEY_SALT = "myway" // md5sum of Salt + Common Key 2 + Salt, used on sector 7 key A and B. private const val MYWAY_KEY_DIGEST = "29a61b3a4d5c818415350804c82cd834" private const val SMARTRIDER_KEY_SALT = "smartrider" // md5sum of Salt + Common Key 2 + Salt, used on Sector 7 key A. private const val SMARTRIDER_KEY2_DIGEST = "e0913518a5008c03e1b3f2bb3a43ff78" // md5sum of Salt + Common Key 3 + Salt, used on Sector 7 key B. private const val SMARTRIDER_KEY3_DIGEST = "bc510c0183d2c0316533436038679620" private fun detectKeyType(sectors: List<ClassicSector>): CardType { try { val sector = sectors[7] Log.d(TAG, "Checking for MyWay key...") if (HashUtils.checkKeyHash(sector, MYWAY_KEY_SALT, MYWAY_KEY_DIGEST) >= 0) { return CardType.MYWAY } Log.d(TAG, "Checking for SmartRider key...") if (HashUtils.checkKeyHash(sector, SMARTRIDER_KEY_SALT, SMARTRIDER_KEY2_DIGEST, SMARTRIDER_KEY3_DIGEST) >= 0) { return CardType.SMARTRIDER } } catch (ignored: IndexOutOfBoundsException) { // If that sector number is too high, then it's not for us. } return CardType.UNKNOWN } val FACTORY: ClassicCardTransitFactory = object : ClassicCardTransitFactory { override val allCards: List<CardInfo> get() = listOf(SMARTRIDER_CARD_INFO, MYWAY_CARD_INFO) override val earlySectors: Int get() = 8 override fun earlyCheck(sectors: List<ClassicSector>): Boolean = detectKeyType(sectors) != CardType.UNKNOWN override fun parseTransitIdentity(card: ClassicCard): TransitIdentity = TransitIdentity(detectKeyType(card.sectors).friendlyName, getSerialData(card)) override fun earlyCardInfo(sectors: List<ClassicSector>): CardInfo? = when (detectKeyType(sectors)) { SmartRiderTransitData.CardType.MYWAY -> MYWAY_CARD_INFO SmartRiderTransitData.CardType.SMARTRIDER -> SMARTRIDER_CARD_INFO else -> null } override fun parseTransitData(card: ClassicCard) = parse(card) } private fun getSerialData(card: ClassicCard): String { val serialData = card.getSector(0).getBlock(1).data var serial = serialData.getHexString(6, 5) if (serial.startsWith("0")) { serial = serial.substring(1) } return serial } } }
gpl-3.0
1242e8ee933634616a746af158d16508
42.649718
104
0.629304
4.338012
false
false
false
false
iPoli/iPoli-android
app/src/main/java/io/ipoli/android/player/profile/ProfileChallengeListViewController.kt
1
8893
package io.ipoli.android.player.profile import android.content.res.ColorStateList import android.os.Bundle import android.support.annotation.ColorRes import android.support.v7.widget.LinearLayoutManager import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import com.mikepenz.iconics.IconicsDrawable import com.mikepenz.iconics.typeface.IIcon import com.mikepenz.ionicons_typeface_library.Ionicons import io.ipoli.android.R import io.ipoli.android.common.datetime.daysUntil import io.ipoli.android.common.redux.android.BaseViewController import io.ipoli.android.common.text.DateFormatter import io.ipoli.android.common.view.* import io.ipoli.android.common.view.recyclerview.MultiViewRecyclerViewAdapter import io.ipoli.android.common.view.recyclerview.RecyclerViewViewModel import io.ipoli.android.player.profile.ProfileViewState.StateType.* import kotlinx.android.synthetic.main.controller_profile_challenge_list.view.* import kotlinx.android.synthetic.main.item_profile_challenge.view.* import kotlinx.android.synthetic.main.view_empty_list.view.* import kotlinx.android.synthetic.main.view_loader.view.* import kotlinx.android.synthetic.main.view_require_login.view.* import org.threeten.bp.LocalDate /** * Created by Polina Zhelyazkova <polina@mypoli.fun> * on 7/17/18. */ class ProfileChallengeListViewController(args: Bundle? = null) : BaseViewController<ProfileAction, ProfileViewState>(args) { private var friendId: String? = null override var stateKey = "" constructor(reducerKey: String, friendId: String?) : this() { this.stateKey = reducerKey this.friendId = friendId } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup, savedViewState: Bundle? ): View { val view = inflater.inflate(R.layout.controller_profile_challenge_list, container, false) view.challengeList.layoutManager = LinearLayoutManager(view.context) view.challengeList.adapter = ChallengeAdapter() view.emptyAnimation.setAnimation("empty_challenge_list.json") return view } override fun onCreateLoadAction() = if (friendId == null) ProfileAction.LoadPlayerChallenges else ProfileAction.LoadFriendChallenges(friendId!!) override fun colorStatusBars() { } override fun render(state: ProfileViewState, view: View) { if (state.friendId == null) { view.shareItem.onDebounceClick { navigateFromRoot().toPostItemPicker() } } else { view.shareItem.gone() } when (state.type) { SHOW_REQUIRE_LOGIN -> { view.loader.gone() view.emptyAnimation.pauseAnimation() view.emptyContainer.gone() view.shareItem.gone() view.challengeList.gone() view.loginMessageContainer.visible() view.loginMessage.setText(R.string.challenges_sign_in) view.loginButton.onDebounceClick { navigateFromRoot().toAuth(isSigningUp = true) } } NO_INTERNET_CONNECTION -> { view.loader.gone() view.emptyContainer.visible() view.emptyAnimation.pauseAnimation() view.emptyAnimation.gone() view.challengeList.gone() view.shareItem.gone() view.loginMessageContainer.gone() view.emptyTitle.text = stringRes(R.string.error_no_internet_title) view.emptyText.text = stringRes(R.string.challenges_no_internet_text) } CHALLENGE_LIST_DATA_CHANGED -> { showShareItemIfNotFriend(state.friendId, view) if (state.challenges!!.isEmpty()) { view.loader.gone() view.emptyContainer.visible() view.challengeList.gone() view.loginMessageContainer.gone() view.emptyAnimation.playAnimation() view.emptyAnimation.visible() view.emptyTitle.setText(R.string.empty_shared_challenges_title) view.emptyText.setText(R.string.empty_shared_challenges_text) } else { view.loader.gone() view.emptyContainer.gone() view.emptyAnimation.pauseAnimation() view.loginMessageContainer.gone() view.challengeList.visible() (view.challengeList.adapter as ChallengeAdapter).updateAll(state.challengeViewModels) } } else -> { } } } private fun showShareItemIfNotFriend(friendId: String?, view: View) { if (friendId == null) { view.shareItem.visible() } } enum class ItemType { LABEL, CHALLENGE } sealed class ChallengeViewModel( override val id: String ) : RecyclerViewViewModel { data class Challenge( override val id: String, val name: String, val icon: IIcon, @ColorRes val color: Int, val end: String ) : ChallengeViewModel(id) data class CompleteLabel(val label: String) : ChallengeViewModel(label) } inner class ChallengeAdapter : MultiViewRecyclerViewAdapter<ChallengeViewModel>() { override fun onRegisterItemBinders() { registerBinder<ChallengeViewModel.Challenge>( ItemType.CHALLENGE.ordinal, R.layout.item_profile_challenge ) { vm, view, _ -> view.cIcon.backgroundTintList = ColorStateList.valueOf(view.context.colorRes(vm.color)) view.cIcon.setImageDrawable( IconicsDrawable(view.context).listItemIcon(vm.icon) ) view.cName.text = vm.name view.cEnd.text = vm.end } registerBinder<ChallengeViewModel.CompleteLabel>( ItemType.LABEL.ordinal, R.layout.item_list_section ) { vm, view, _ -> (view as TextView).text = vm.label } } } private val ProfileViewState.challengeViewModels: List<ChallengeViewModel> get() { val (incomplete, complete) = challenges!!.partition { it.completedAtDate == null } val result = mutableListOf<ChallengeViewModel>() result.addAll( incomplete.map { val daysUntilComplete = LocalDate.now().daysUntil(it.endDate) ChallengeViewModel.Challenge( id = it.id, name = it.name, icon = it.icon?.let { AndroidIcon.valueOf(it.name).icon } ?: Ionicons.Icon.ion_checkmark, color = it.color.androidColor.color500, end = when { daysUntilComplete < 0L -> stringRes( R.string.inbox_overdue_by, Math.abs(daysUntilComplete), stringRes(R.string.days).toLowerCase() ) daysUntilComplete == 0L -> stringRes(R.string.ends_today) daysUntilComplete <= 7 -> stringRes( R.string.ends_in_days, daysUntilComplete ) else -> stringRes( R.string.ends_at_date, DateFormatter.formatWithoutYear(activity!!, it.endDate) ) } ) } ) if (complete.isNotEmpty()) { result.add( ChallengeViewModel.CompleteLabel(stringRes(R.string.completed)) ) } result.addAll( complete.map { ChallengeViewModel.Challenge( id = it.id, name = it.name, icon = it.icon?.let { AndroidIcon.valueOf(it.name).icon } ?: Ionicons.Icon.ion_checkmark, color = it.color.androidColor.color500, end = stringRes( R.string.completed_at_date, DateFormatter.format(activity!!, it.completedAtDate) ) ) } ) return result } }
gpl-3.0
eb9127f85537c14c54cd7f739485cea4
36.527426
105
0.560666
5.055713
false
false
false
false
iPoli/iPoli-android
app/src/main/java/io/ipoli/android/challenge/persistence/ChallengeRepository.kt
1
27627
package io.ipoli.android.challenge.persistence import android.arch.lifecycle.LiveData import android.arch.persistence.room.* import android.arch.persistence.room.ForeignKey.CASCADE import com.google.firebase.firestore.CollectionReference import com.google.firebase.firestore.FirebaseFirestore import io.ipoli.android.challenge.entity.Challenge import io.ipoli.android.challenge.entity.SharingPreference import io.ipoli.android.common.Reward import io.ipoli.android.common.datetime.* import io.ipoli.android.common.persistence.* import io.ipoli.android.pet.Food import io.ipoli.android.player.data.Player import io.ipoli.android.quest.Color import io.ipoli.android.quest.Icon import io.ipoli.android.quest.Quest import io.ipoli.android.quest.data.persistence.DbBounty import io.ipoli.android.quest.data.persistence.DbEmbedTag import io.ipoli.android.tag.Tag import io.ipoli.android.tag.persistence.RoomTag import io.ipoli.android.tag.persistence.RoomTagMapper import io.ipoli.android.tag.persistence.TagDao import org.jetbrains.annotations.NotNull import org.threeten.bp.LocalDate import java.util.* /** * Created by Venelin Valkov <venelin@mypoli.fun> * on 03/07/2018. */ interface ChallengeRepository : CollectionRepository<Challenge> { fun findForFriend(friendId: String): List<Challenge> fun hasActivePresetChallenge(presetChallengeId: String): Boolean } @Dao abstract class ChallengeDao : BaseDao<RoomChallenge>() { @Query("SELECT * FROM challenges") abstract fun findAll(): List<RoomChallenge> @Query("SELECT * FROM challenges WHERE id = :id") abstract fun findById(id: String): RoomChallenge @Query("SELECT * FROM challenges WHERE removedAt IS NULL") abstract fun listenForNotRemoved(): LiveData<List<RoomChallenge>> @Query("SELECT * FROM challenges WHERE id = :id") abstract fun listenById(id: String): LiveData<RoomChallenge> @Query("UPDATE challenges $REMOVE_QUERY") abstract fun remove(id: String, currentTimeMillis: Long = System.currentTimeMillis()) @Query("UPDATE challenges $UNDO_REMOVE_QUERY") abstract fun undoRemove(id: String, currentTimeMillis: Long = System.currentTimeMillis()) @Insert(onConflict = OnConflictStrategy.IGNORE) abstract fun saveTags(joins: List<RoomChallenge.Companion.RoomTagJoin>) @Query("DELETE FROM challenge_tag_join WHERE challengeId = :challengeId") abstract fun deleteAllTags(challengeId: String) @Query("DELETE FROM challenge_tag_join WHERE challengeId IN (:challengeIds)") abstract fun deleteAllTags(challengeIds: List<String>) @Query("SELECT * FROM challenges $FIND_SYNC_QUERY") abstract fun findAllForSync(lastSync: Long): List<RoomChallenge> @Query("SELECT EXISTS(SELECT * FROM challenges WHERE presetChallengeId = :presetChallengeId AND removedAt IS NULL AND completedAtDate IS NULL AND endDate >= :currentDate)") abstract fun hasActivePresetChallenge(presetChallengeId: String, currentDate: Long): Boolean } class RoomChallengeRepository( dao: ChallengeDao, private val tagDao: TagDao, private val remoteDatabase: FirebaseFirestore ) : ChallengeRepository, BaseRoomRepositoryWithTags<Challenge, RoomChallenge, ChallengeDao, RoomChallenge.Companion.RoomTagJoin>( dao ) { private val tagMapper = RoomTagMapper() override fun findForFriend(friendId: String) = FirestoreChallengeRepository(remoteDatabase).findSharedForFriend(friendId) override fun findAllForSync(lastSync: Duration<Millisecond>) = dao.findAllForSync(lastSync.millisValue).map { toEntityObject(it) } override fun createTagJoin( entityId: String, tagId: String ) = RoomChallenge.Companion.RoomTagJoin(entityId, tagId) override fun newIdForEntity(id: String, entity: Challenge) = entity.copy(id = id) override fun saveTags(joins: List<RoomChallenge.Companion.RoomTagJoin>) = dao.saveTags(joins) override fun deleteAllTags(entityId: String) = dao.deleteAllTags(entityId) override fun findById(id: String) = toEntityObject(dao.findById(id)) override fun findAll() = dao.findAll().map { toEntityObject(it) } override fun listenById(id: String) = dao.listenById(id).notifySingle() override fun listenForAll() = dao.listenForNotRemoved().notify() override fun remove(entity: Challenge) { remove(entity.id) } override fun remove(id: String) { dao.remove(id) } override fun undoRemove(id: String) { dao.undoRemove(id) } override fun hasActivePresetChallenge(presetChallengeId: String) = dao.hasActivePresetChallenge(presetChallengeId, LocalDate.now().startOfDayUTC()) override fun toEntityObject(dbObject: RoomChallenge) = Challenge( id = dbObject.id, name = dbObject.name, color = Color.valueOf(dbObject.color), icon = dbObject.icon?.let { Icon.valueOf(it) }, difficulty = Challenge.Difficulty.valueOf(dbObject.difficulty), tags = tagDao.findForChallenge(dbObject.id).map { tagMapper.toEntityObject(it) }, startDate = dbObject.startDate.startOfDayUTC, endDate = dbObject.endDate.startOfDayUTC, motivations = dbObject.motivations, reward = dbObject.coins?.let { val dbBounty = DbBounty(dbObject.bounty!!.toMutableMap()) Reward( attributePoints = dbObject.attributePoints!!.map { a -> Player.AttributeType.valueOf( a.key ) to a.value.toInt() }.toMap(), healthPoints = 0, experience = dbObject.experience!!.toInt(), coins = dbObject.coins.toInt(), bounty = when { dbBounty.type == DbBounty.Type.NONE.name -> Quest.Bounty.None dbBounty.type == DbBounty.Type.FOOD.name -> Quest.Bounty.Food( Food.valueOf( dbBounty.name!! ) ) else -> throw IllegalArgumentException("Unknown bounty type ${dbBounty.type}") } ) }, completedAtDate = dbObject.completedAtDate?.startOfDayUTC, completedAtTime = dbObject.completedAtMinute?.let { Time.of(it.toInt()) }, trackedValues = dbObject.trackedValues.map { data -> val valueData = data.toMutableMap() // Due to JSON parsing bug/issue parsing 0.0f to 0 valueData["startValue"] = valueData["startValue"]?.toString()?.toFloat() valueData["targetValue"] = valueData["targetValue"]?.toString()?.toFloat() valueData["lowerBound"] = valueData["lowerBound"]?.toString()?.toFloat() valueData["upperBound"] = valueData["upperBound"]?.toString()?.toFloat() DbTrackedValue(valueData).let { when (DbTrackedValue.Type.valueOf(it.type)) { DbTrackedValue.Type.PROGRESS -> Challenge.TrackedValue.Progress( id = it.id, history = emptyMap<LocalDate, Challenge.TrackedValue.Log>().toSortedMap() ) DbTrackedValue.Type.TARGET -> Challenge.TrackedValue.Target( id = it.id, name = it.name!!, units = it.units!!, startValue = it.startValue!!.toDouble(), targetValue = it.targetValue!!.toDouble(), currentValue = 0.0, remainingValue = 0.0, isCumulative = it.isCumulative!!, history = it.logs!!.map { logData -> DbLog(logData.toMutableMap()).let { dbLog -> dbLog.date.startOfDayUTC to Challenge.TrackedValue.Log( dbLog.value.toDouble(), Time.of(dbLog.minuteOfDay.toInt()), dbLog.date.startOfDayUTC ) } }.toMap().toSortedMap() ) DbTrackedValue.Type.AVERAGE -> Challenge.TrackedValue.Average( id = it.id, name = it.name!!, units = it.units!!, targetValue = it.targetValue!!.toDouble(), lowerBound = it.lowerBound!!.toDouble(), upperBound = it.upperBound!!.toDouble(), history = it.logs!!.map { logData -> DbLog(logData.toMutableMap()).let { dbLog -> dbLog.date.startOfDayUTC to Challenge.TrackedValue.Log( dbLog.value.toDouble(), Time.of(dbLog.minuteOfDay.toInt()), dbLog.date.startOfDayUTC ) } }.toMap().toSortedMap() ) } } }, note = dbObject.note, sharingPreference = SharingPreference.valueOf(dbObject.sharingPreference), presetChallengeId = dbObject.presetChallengeId, createdAt = dbObject.createdAt.instant, updatedAt = dbObject.updatedAt.instant, removedAt = dbObject.removedAt?.instant ) override fun toDatabaseObject(entity: Challenge) = RoomChallenge( id = if (entity.id.isEmpty()) UUID.randomUUID().toString() else entity.id, name = entity.name, color = entity.color.name, icon = entity.icon?.name, difficulty = entity.difficulty.name, startDate = entity.startDate.startOfDayUTC(), endDate = entity.endDate.startOfDayUTC(), motivations = entity.motivations, experience = entity.reward?.experience?.toLong(), coins = entity.reward?.coins?.toLong(), attributePoints = entity.reward?.attributePoints?.map { a -> a.key.name to a.value.toLong() }?.toMap(), bounty = entity.reward?.let { DbBounty().apply { type = when (it.bounty) { is Quest.Bounty.None -> DbBounty.Type.NONE.name is Quest.Bounty.Food -> DbBounty.Type.FOOD.name } name = if (it.bounty is Quest.Bounty.Food) it.bounty.food.name else null }.map }, completedAtDate = entity.completedAtDate?.startOfDayUTC(), completedAtMinute = entity.completedAtTime?.toMinuteOfDay()?.toLong(), trackedValues = entity.trackedValues.map { val dbVal = DbTrackedValue() dbVal.id = it.id when (it) { is Challenge.TrackedValue.Progress -> dbVal.type = DbTrackedValue.Type.PROGRESS.name is Challenge.TrackedValue.Target -> { dbVal.type = DbTrackedValue.Type.TARGET.name dbVal.name = it.name dbVal.units = it.units dbVal.targetValue = it.targetValue.toFloat() dbVal.isCumulative = it.isCumulative dbVal.startValue = it.startValue.toFloat() dbVal.logs = it.history.values.map { log -> val dbLog = DbLog() dbLog.value = log.value.toFloat() dbLog.minuteOfDay = log.time.toMinuteOfDay().toLong() dbLog.date = log.date.startOfDayUTC() dbLog.map } } is Challenge.TrackedValue.Average -> { dbVal.type = DbTrackedValue.Type.AVERAGE.name dbVal.name = it.name dbVal.units = it.units dbVal.targetValue = it.targetValue.toFloat() dbVal.lowerBound = it.lowerBound.toFloat() dbVal.upperBound = it.upperBound.toFloat() dbVal.logs = it.history.values.map { log -> val dbLog = DbLog() dbLog.value = log.value.toFloat() dbLog.minuteOfDay = log.time.toMinuteOfDay().toLong() dbLog.date = log.date.startOfDayUTC() dbLog.map } } } dbVal.map }, note = entity.note, sharingPreference = entity.sharingPreference.name, presetChallengeId = entity.presetChallengeId, updatedAt = System.currentTimeMillis(), createdAt = entity.createdAt.toEpochMilli(), removedAt = entity.removedAt?.toEpochMilli() ) } data class DbTrackedValue(val map: MutableMap<String, Any?> = mutableMapOf()) { var id: String by map var type: String by map var name: String? by map var units: String? by map var targetValue: Float? by map var startValue: Float? by map var isCumulative: Boolean? by map var lowerBound: Float? by map var upperBound: Float? by map var logs: List<Map<String, Any?>>? by map enum class Type { PROGRESS, TARGET, AVERAGE } } data class DbLog(val map: MutableMap<String, Any?> = mutableMapOf()) { var value: Float by map var minuteOfDay: Long by map var date: Long by map } @Entity( tableName = "challenges", indices = [ Index("updatedAt"), Index("removedAt") ] ) data class RoomChallenge( @NotNull @PrimaryKey(autoGenerate = false) override val id: String, val name: String, val color: String, val icon: String?, val difficulty: String, val startDate: Long, val endDate: Long, val motivations: List<String>, val experience: Long?, val coins: Long?, val bounty: Map<String, Any?>?, val attributePoints: Map<String, Long>?, val completedAtDate: Long?, val completedAtMinute: Long?, val trackedValues: List<Map<String, Any?>>, val note: String, val sharingPreference: String, val presetChallengeId: String?, val createdAt: Long, val updatedAt: Long, val removedAt: Long? ) : RoomEntity { companion object { @Entity( tableName = "challenge_tag_join", primaryKeys = ["challengeId", "tagId"], foreignKeys = [ ForeignKey( entity = RoomChallenge::class, parentColumns = ["id"], childColumns = ["challengeId"], onDelete = CASCADE ), ForeignKey( entity = RoomTag::class, parentColumns = ["id"], childColumns = ["tagId"], onDelete = CASCADE ) ], indices = [Index("challengeId"), Index("tagId")] ) data class RoomTagJoin(val challengeId: String, val tagId: String) } } class FirestoreChallengeRepository( database: FirebaseFirestore ) : BaseCollectionFirestoreRepository<Challenge, FirestoreChallenge>( database ) { override val collectionReference: CollectionReference get() { return database.collection("players").document(playerId).collection("challenges") } fun findSharedForFriend(friendId: String) = database .collection("players") .document(friendId) .collection("challenges") .whereEqualTo("sharingPreference", SharingPreference.FRIENDS.name) .notRemovedEntities override fun toEntityObject(dataMap: MutableMap<String, Any?>): Challenge { if (!dataMap.containsKey("sharingPreference")) { dataMap["sharingPreference"] = SharingPreference.PRIVATE.name } if (!dataMap.containsKey("trackedValues")) { val dbVal = DbTrackedValue() dbVal.id = UUID.randomUUID().toString() dbVal.type = DbTrackedValue.Type.PROGRESS.name dataMap["trackedValues"] = listOf(dbVal.map) } if (dataMap["coins"] != null) { if (!dataMap.containsKey("bounty")) { dataMap["bounty"] = DbBounty().apply { type = DbBounty.Type.NONE.name name = null }.map } if (!dataMap.containsKey("attributePoints")) { dataMap["attributePoints"] = emptyMap<String, Long>() } } val c = FirestoreChallenge(dataMap.withDefault { null }) return Challenge( id = c.id, name = c.name, color = Color.valueOf(c.color), icon = c.icon?.let { Icon.valueOf(it) }, difficulty = Challenge.Difficulty.valueOf(c.difficulty), tags = c.tags.values.map { createTag(it) }, startDate = c.startDate.startOfDayUTC, endDate = c.endDate.startOfDayUTC, motivations = c.motivations, reward = c.coins?.let { val dbBounty = DbBounty(c.bounty!!.toMutableMap()) Reward( attributePoints = c.attributePoints!!.map { a -> Player.AttributeType.valueOf( a.key ) to a.value.toInt() }.toMap(), healthPoints = 0, experience = c.experience!!.toInt(), coins = c.coins!!.toInt(), bounty = when { dbBounty.type == DbBounty.Type.NONE.name -> Quest.Bounty.None dbBounty.type == DbBounty.Type.FOOD.name -> Quest.Bounty.Food( Food.valueOf( dbBounty.name!! ) ) else -> throw IllegalArgumentException("Unknown bounty type ${dbBounty.type}") } ) }, completedAtDate = c.completedAtDate?.startOfDayUTC, completedAtTime = c.completedAtMinute?.let { Time.of(it.toInt()) }, note = c.note, sharingPreference = SharingPreference.valueOf(c.sharingPreference), presetChallengeId = c.presetChallengeId, trackedValues = c.trackedValues.map { data -> val valueData = data.toMutableMap() // Due to JSON parsing bug/issue parsing 0.0f to 0 valueData["startValue"] = valueData["startValue"]?.toString()?.toFloat() valueData["targetValue"] = valueData["targetValue"]?.toString()?.toFloat() valueData["lowerBound"] = valueData["lowerBound"]?.toString()?.toFloat() valueData["upperBound"] = valueData["upperBound"]?.toString()?.toFloat() DbTrackedValue(valueData).let { when (DbTrackedValue.Type.valueOf(it.type)) { DbTrackedValue.Type.PROGRESS -> Challenge.TrackedValue.Progress( id = it.id, history = emptyMap<LocalDate, Challenge.TrackedValue.Log>().toSortedMap() ) DbTrackedValue.Type.TARGET -> Challenge.TrackedValue.Target( id = it.id, name = it.name!!, units = it.units!!, startValue = it.startValue!!.toDouble(), targetValue = it.targetValue!!.toDouble(), currentValue = 0.0, remainingValue = 0.0, isCumulative = it.isCumulative!!, history = it.logs!!.map { logData -> DbLog(logData.toMutableMap()).let { dbLog -> dbLog.date.startOfDayUTC to Challenge.TrackedValue.Log( dbLog.value.toDouble(), Time.of(dbLog.minuteOfDay.toInt()), dbLog.date.startOfDayUTC ) } }.toMap().toSortedMap() ) DbTrackedValue.Type.AVERAGE -> Challenge.TrackedValue.Average( id = it.id, name = it.name!!, units = it.units!!, targetValue = it.targetValue!!.toDouble(), lowerBound = it.lowerBound!!.toDouble(), upperBound = it.upperBound!!.toDouble(), history = emptyMap<LocalDate, Challenge.TrackedValue.Log>().toSortedMap() ) } } }, createdAt = c.createdAt.instant, updatedAt = c.updatedAt.instant, removedAt = c.removedAt?.instant ) } override fun toDatabaseObject(entity: Challenge): FirestoreChallenge { val c = FirestoreChallenge() c.id = entity.id c.name = entity.name c.color = entity.color.name c.icon = entity.icon?.name c.difficulty = entity.difficulty.name c.tags = entity.tags.map { it.id to createDbTag(it).map }.toMap() c.startDate = entity.startDate.startOfDayUTC() c.endDate = entity.endDate.startOfDayUTC() c.motivations = entity.motivations entity.reward?.let { c.experience = it.experience.toLong() c.coins = it.coins.toLong() c.attributePoints = it.attributePoints.map { a -> a.key.name to a.value.toLong() }.toMap() c.bounty = DbBounty().apply { type = when (it.bounty) { is Quest.Bounty.None -> DbBounty.Type.NONE.name is Quest.Bounty.Food -> DbBounty.Type.FOOD.name } name = if (it.bounty is Quest.Bounty.Food) it.bounty.food.name else null }.map } c.completedAtDate = entity.completedAtDate?.startOfDayUTC() c.completedAtMinute = entity.completedAtTime?.toMinuteOfDay()?.toLong() c.note = entity.note c.sharingPreference = entity.sharingPreference.name c.presetChallengeId = entity.presetChallengeId c.trackedValues = entity.trackedValues.map { val dbVal = DbTrackedValue() dbVal.id = it.id when (it) { is Challenge.TrackedValue.Progress -> dbVal.type = DbTrackedValue.Type.PROGRESS.name is Challenge.TrackedValue.Target -> { dbVal.type = DbTrackedValue.Type.TARGET.name dbVal.name = it.name dbVal.units = it.units dbVal.targetValue = it.targetValue.toFloat() dbVal.isCumulative = it.isCumulative dbVal.startValue = it.startValue.toFloat() dbVal.logs = it.history.values.map { log -> val dbLog = DbLog() dbLog.value = log.value.toFloat() dbLog.minuteOfDay = log.time.toMinuteOfDay().toLong() dbLog.date = log.date.startOfDayUTC() dbLog.map } } is Challenge.TrackedValue.Average -> { dbVal.type = DbTrackedValue.Type.AVERAGE.name dbVal.name = it.name dbVal.units = it.units dbVal.targetValue = it.targetValue.toFloat() dbVal.lowerBound = it.lowerBound.toFloat() dbVal.upperBound = it.upperBound.toFloat() dbVal.logs = it.history.values.map { log -> val dbLog = DbLog() dbLog.value = log.value.toFloat() dbLog.minuteOfDay = log.time.toMinuteOfDay().toLong() dbLog.date = log.date.startOfDayUTC() dbLog.map } } } dbVal.map } c.updatedAt = entity.updatedAt.toEpochMilli() c.createdAt = entity.createdAt.toEpochMilli() c.removedAt = entity.removedAt?.toEpochMilli() return c } private fun createDbTag(tag: Tag) = DbEmbedTag().apply { id = tag.id name = tag.name isFavorite = tag.isFavorite color = tag.color.name icon = tag.icon?.name } private fun createTag(dataMap: MutableMap<String, Any?>) = with( DbEmbedTag(dataMap.withDefault { null }) ) { Tag( id = id, name = name, color = Color.valueOf(color), icon = icon?.let { Icon.valueOf(it) }, isFavorite = isFavorite ) } } data class FirestoreChallenge(override val map: MutableMap<String, Any?> = mutableMapOf()) : FirestoreModel { override var id: String by map var name: String by map var color: String by map var icon: String? by map var difficulty: String by map var tags: Map<String, MutableMap<String, Any?>> by map var startDate: Long by map var endDate: Long by map var motivations: List<String> by map var experience: Long? by map var coins: Long? by map var bounty: Map<String, Any?>? by map var attributePoints: Map<String, Long>? by map var completedAtDate: Long? by map var completedAtMinute: Long? by map var note: String by map var sharingPreference: String by map var presetChallengeId: String? by map var trackedValues: List<MutableMap<String, Any?>> by map override var createdAt: Long by map override var updatedAt: Long by map override var removedAt: Long? by map }
gpl-3.0
148b512e62050e9164e23ed072420c95
40.545865
176
0.530749
5.037746
false
false
false
false
GunoH/intellij-community
plugins/github/src/org/jetbrains/plugins/github/authentication/GHAccountsUtil.kt
2
9624
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.plugins.github.authentication import com.intellij.ide.DataManager import com.intellij.openapi.actionSystem.ActionGroup import com.intellij.openapi.actionSystem.DefaultActionGroup import com.intellij.openapi.actionSystem.Separator import com.intellij.openapi.components.service import com.intellij.openapi.project.DumbAwareAction import com.intellij.openapi.project.Project import com.intellij.openapi.ui.MessageDialogBuilder import com.intellij.openapi.ui.Messages import com.intellij.openapi.ui.popup.JBPopupFactory import com.intellij.openapi.util.NlsContexts import com.intellij.ui.CollectionComboBoxModel import com.intellij.ui.components.DropDownLink import com.intellij.util.AuthData import com.intellij.util.concurrency.annotations.RequiresEdt import git4idea.DialogManager import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import org.jetbrains.plugins.github.api.GithubServerPath import org.jetbrains.plugins.github.authentication.accounts.GHAccountManager import org.jetbrains.plugins.github.authentication.accounts.GithubAccount import org.jetbrains.plugins.github.authentication.accounts.GithubProjectDefaultAccountHolder import org.jetbrains.plugins.github.authentication.ui.GHLoginDialog import org.jetbrains.plugins.github.authentication.ui.GHLoginModel import org.jetbrains.plugins.github.i18n.GithubBundle import java.awt.Component import javax.swing.JButton import javax.swing.JComponent private val accountManager: GHAccountManager get() = service() object GHAccountsUtil { @JvmStatic val accounts: Set<GithubAccount> get() = accountManager.accountsState.value @JvmStatic fun getDefaultAccount(project: Project): GithubAccount? = project.service<GithubProjectDefaultAccountHolder>().account @JvmStatic fun setDefaultAccount(project: Project, account: GithubAccount?) { project.service<GithubProjectDefaultAccountHolder>().account = account } @JvmStatic fun getSingleOrDefaultAccount(project: Project): GithubAccount? = getDefaultAccount(project) ?: accounts.singleOrNull() fun createAddAccountLink(project: Project, accountSelectionModel: CollectionComboBoxModel<GithubAccount>): JButton { val model = object : GHLoginModel { override fun isAccountUnique(server: GithubServerPath, login: String): Boolean = accountSelectionModel.items.none { it.name == login && it.server.equals(server, true) } override suspend fun saveLogin(server: GithubServerPath, login: String, token: String) { val account = GHAccountManager.createAccount(login, server) accountManager.updateAccount(account, token) withContext(Dispatchers.Main.immediate) { accountSelectionModel.add(account) accountSelectionModel.selectedItem = account } } } return DropDownLink(GithubBundle.message("accounts.add.dropdown.link")) { val group = createAddAccountActionGroup(model, project, it) JBPopupFactory.getInstance() .createActionGroupPopup(null, group, DataManager.getInstance().getDataContext(it), JBPopupFactory.ActionSelectionAid.MNEMONICS, false) } } internal fun createAddAccountActionGroup(model: GHLoginModel, project: Project, parentComponent: JComponent): ActionGroup { val group = DefaultActionGroup() group.add( DumbAwareAction.create(GithubBundle.message("action.Github.Accounts.AddGHAccount.text")) { GHLoginDialog.OAuth(model, project, parentComponent).apply { setServer(GithubServerPath.DEFAULT_HOST, false) showAndGet() } }) group.add( DumbAwareAction.create(GithubBundle.message("action.Github.Accounts.AddGHAccountWithToken.text")) { GHLoginDialog.Token(model, project, parentComponent).apply { title = GithubBundle.message("dialog.title.add.github.account") setLoginButtonText(GithubBundle.message("accounts.add.button")) setServer(GithubServerPath.DEFAULT_HOST, false) showAndGet() } } ) group.add(Separator()) group.add( DumbAwareAction.create(GithubBundle.message("action.Github.Accounts.AddGHEAccount.text")) { GHLoginDialog.Token(model, project, parentComponent).apply { title = GithubBundle.message("dialog.title.add.github.account") setServer("", true) setLoginButtonText(GithubBundle.message("accounts.add.button")) showAndGet() } } ) return group } @RequiresEdt @JvmOverloads @JvmStatic internal fun requestNewToken( account: GithubAccount, project: Project?, parentComponent: Component? = null ): String? { val model = AccountManagerLoginModel(account) login( model, GHLoginRequest( text = GithubBundle.message("account.token.missing.for", account), server = account.server, login = account.name ), project, parentComponent, ) return model.authData?.token } @RequiresEdt @JvmOverloads @JvmStatic fun requestReLogin( account: GithubAccount, project: Project?, parentComponent: Component? = null, authType: AuthorizationType = AuthorizationType.UNDEFINED ): GHAccountAuthData? { val model = AccountManagerLoginModel(account) login( model, GHLoginRequest(server = account.server, login = account.name, authType = authType), project, parentComponent) return model.authData } @RequiresEdt @JvmOverloads @JvmStatic fun requestNewAccount( server: GithubServerPath? = null, login: String? = null, project: Project?, parentComponent: Component? = null, authType: AuthorizationType = AuthorizationType.UNDEFINED ): GHAccountAuthData? { val model = AccountManagerLoginModel() login( model, GHLoginRequest(server = server, login = login, isLoginEditable = login != null, authType = authType), project, parentComponent ) return model.authData } @RequiresEdt @JvmStatic internal fun login(model: GHLoginModel, request: GHLoginRequest, project: Project?, parentComponent: Component?) { if (request.server != GithubServerPath.DEFAULT_SERVER) { request.loginWithToken(model, project, parentComponent) } else when (request.authType) { AuthorizationType.OAUTH -> request.loginWithOAuth(model, project, parentComponent) AuthorizationType.TOKEN -> request.loginWithToken(model, project, parentComponent) AuthorizationType.UNDEFINED -> request.loginWithOAuthOrToken(model, project, parentComponent) } } } class GHAccountAuthData(val account: GithubAccount, login: String, token: String) : AuthData(login, token) { val server: GithubServerPath get() = account.server val token: String get() = password!! } internal class GHLoginRequest( val text: @NlsContexts.DialogMessage String? = null, val error: Throwable? = null, val server: GithubServerPath? = null, val isServerEditable: Boolean = server == null, val login: String? = null, val isLoginEditable: Boolean = true, val authType: AuthorizationType = AuthorizationType.UNDEFINED ) private fun GHLoginRequest.configure(dialog: GHLoginDialog) { error?.let { dialog.setError(it) } server?.let { dialog.setServer(it.toString(), isServerEditable) } login?.let { dialog.setLogin(it, isLoginEditable) } } private fun GHLoginRequest.loginWithToken(model: GHLoginModel, project: Project?, parentComponent: Component?) { val dialog = GHLoginDialog.Token(model, project, parentComponent) configure(dialog) DialogManager.show(dialog) } private fun GHLoginRequest.loginWithOAuth(model: GHLoginModel, project: Project?, parentComponent: Component?) { val dialog = GHLoginDialog.OAuth(model, project, parentComponent) configure(dialog) DialogManager.show(dialog) } private fun GHLoginRequest.loginWithOAuthOrToken(model: GHLoginModel, project: Project?, parentComponent: Component?) { when (promptOAuthLogin(this, project, parentComponent)) { Messages.YES -> loginWithOAuth(model, project, parentComponent) Messages.NO -> loginWithToken(model, project, parentComponent) } } private fun promptOAuthLogin(request: GHLoginRequest, project: Project?, parentComponent: Component?): Int { val builder = MessageDialogBuilder.yesNoCancel(title = GithubBundle.message("login.to.github"), message = request.text ?: GithubBundle.message("dialog.message.login.to.continue")) .yesText(GithubBundle.message("login.via.github.action")) .noText(GithubBundle.message("button.use.token")) .icon(Messages.getWarningIcon()) if (parentComponent != null) { return builder.show(parentComponent) } else { return builder.show(project) } } private class AccountManagerLoginModel(private val account: GithubAccount? = null) : GHLoginModel { private val accountManager: GHAccountManager = service() var authData: GHAccountAuthData? = null override fun isAccountUnique(server: GithubServerPath, login: String): Boolean = accountManager.accountsState.value.filter { it != account }.none { it.name == login && it.server.equals(server, true) } override suspend fun saveLogin(server: GithubServerPath, login: String, token: String) { val acc = account ?: GHAccountManager.createAccount(login, server) acc.name = login accountManager.updateAccount(acc, token) authData = GHAccountAuthData(acc, login, token) } }
apache-2.0
30353674ecdcaff4cc61da32d2c7aba8
36.745098
132
0.741584
4.649275
false
false
false
false
GunoH/intellij-community
java/java-impl-refactorings/src/com/intellij/java/refactoring/suggested/JavaSuggestedRefactoringAvailability.kt
2
9263
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.java.refactoring.suggested import com.intellij.openapi.util.Key import com.intellij.psi.* import com.intellij.psi.codeStyle.VariableKind import com.intellij.psi.search.LocalSearchScope import com.intellij.psi.search.searches.OverridingMethodsSearch import com.intellij.psi.search.searches.ReferencesSearch import com.intellij.psi.util.PsiUtil import com.intellij.refactoring.RefactoringBundle import com.intellij.refactoring.suggested.* import com.intellij.refactoring.suggested.SuggestedRefactoringSupport.Parameter import com.intellij.refactoring.suggested.SuggestedRefactoringSupport.Signature import com.siyeh.ig.psiutils.VariableNameGenerator class JavaSuggestedRefactoringAvailability(refactoringSupport: SuggestedRefactoringSupport) : SuggestedRefactoringAvailability(refactoringSupport) { private val HAS_OVERRIDES = Key<Boolean>("JavaSuggestedRefactoringAvailability.HAS_OVERRIDES") private val HAS_USAGES = Key<Boolean>("JavaSuggestedRefactoringAvailability.HAS_USAGES") // disable refactoring suggestion for method which overrides another method override fun shouldSuppressRefactoringForDeclaration(state: SuggestedRefactoringState): Boolean { if (state.anchor !is PsiMethod && state.anchor !is PsiCallExpression) return false val restoredDeclarationCopy = state.restoredDeclarationCopy() return restoredDeclarationCopy is PsiMethod && restoredDeclarationCopy.findSuperMethods().isNotEmpty() } override fun amendStateInBackground(state: SuggestedRefactoringState): Iterator<SuggestedRefactoringState> { return iterator { if (state.additionalData[HAS_OVERRIDES] == null) { val method = state.declaration as? PsiMethod if (method != null && method.canHaveOverrides(state.oldSignature)) { val restoredMethod = state.restoredDeclarationCopy() as PsiMethod val hasOverrides = OverridingMethodsSearch.search(restoredMethod, false).findFirst() != null yield(state.withAdditionalData(HAS_OVERRIDES, hasOverrides)) } } if (state.additionalData[HAS_USAGES] == null) { val declarationCopy = state.restoredDeclarationCopy() val useScope = declarationCopy?.useScope if (useScope is LocalSearchScope) { val hasUsages = ReferencesSearch.search(declarationCopy, useScope).findFirst() != null yield(state.withAdditionalData(HAS_USAGES, hasUsages)) } } } } private fun callStateToDeclarationState(state: SuggestedRefactoringState): SuggestedRefactoringState? { val anchor = state.anchor as? PsiCallExpression ?: return null val resolveResult = anchor.resolveMethodGenerics() if (resolveResult.isValidResult) return null val method = resolveResult.element as? PsiMethod ?: return null if (method is PsiCompiledElement) return null // TODO: support vararg methods if (method.isVarArgs) return null val expressions = anchor.argumentList!!.expressions val args = expressions.map { ex -> ex.text } val psiParameters = method.parameterList.parameters val oldSignature = state.oldSignature val origArgs = ArrayList((oldSignature.additionalData as? JavaCallAdditionalData)?.origArguments ?: return null) if (psiParameters.size != origArgs.size) return null val oldDeclarationSignature = method.signature() ?: return null val parameters = oldDeclarationSignature.parameters val newParams = args.mapIndexed { idx, argText -> val origIdx = origArgs.indexOf(argText) if (origIdx >= 0) { origArgs[origIdx] = null parameters[origIdx] } else { val newArg = expressions[idx] val type = newArg.type val name = VariableNameGenerator(method, VariableKind.PARAMETER).byExpression(newArg).byType(type).generate(true) Parameter(Any(), name, type?.presentableText ?: "Object", JavaParameterAdditionalData("", newArg.text)) } } val newDeclarationSignature = Signature.create( oldDeclarationSignature.name, oldDeclarationSignature.type, newParams, oldDeclarationSignature.additionalData) ?: return null return state .withOldSignature(oldDeclarationSignature) .withNewSignature(newDeclarationSignature) } // we use resolve to filter out annotations that we don't want to spread over hierarchy override fun refineSignaturesWithResolve(state: SuggestedRefactoringState): SuggestedRefactoringState { val anchor = state.anchor if (anchor is PsiCallExpression) return state // TODO val declaration = anchor as? PsiMethod ?: return state val restoredDeclarationCopy = state.restoredDeclarationCopy() as PsiMethod val psiFile = declaration.containingFile return state .withOldSignature(extractAnnotationsWithResolve(state.oldSignature, restoredDeclarationCopy, psiFile)) .withNewSignature(extractAnnotationsWithResolve(state.newSignature, declaration, psiFile)) } override fun detectAvailableRefactoring(state: SuggestedRefactoringState): SuggestedRefactoringData? { var updatedState = state val whatToUpdate: String val declaration: PsiElement val anchor = state.anchor if (anchor is PsiCallExpression) { updatedState = callStateToDeclarationState(updatedState) ?: return null declaration = anchor.resolveMethod() ?: return null whatToUpdate = RefactoringBundle.message("suggested.refactoring.declaration") } else { whatToUpdate = RefactoringBundle.message("suggested.refactoring.usages") declaration = anchor } val oldSignature = updatedState.oldSignature val newSignature = updatedState.newSignature if (declaration !is PsiMethod) { if (updatedState.additionalData[HAS_USAGES] == false) return null return SuggestedRenameData(declaration as PsiNamedElement, oldSignature.name) } val canHaveOverrides = declaration.canHaveOverrides(oldSignature) && updatedState.additionalData[HAS_OVERRIDES] != false if (updatedState.additionalData[HAS_USAGES] == false && !canHaveOverrides) return null val updateUsagesData = SuggestedChangeSignatureData.create(updatedState, whatToUpdate) if (hasParameterAddedRemovedOrReordered(oldSignature, newSignature)) return updateUsagesData val updateOverridesData = if (canHaveOverrides) updateUsagesData.copy(nameOfStuffToUpdate = if (declaration.hasModifierProperty(PsiModifier.ABSTRACT)) RefactoringBundle.message( "suggested.refactoring.implementations") else RefactoringBundle.message("suggested.refactoring.overrides")) else null val (nameChanges, renameData) = nameChanges(oldSignature, newSignature, declaration, declaration.parameterList.parameters.asList()) val methodNameChanged = oldSignature.name != newSignature.name if (hasTypeChanges(oldSignature, newSignature) || oldSignature.visibility != newSignature.visibility) { return if (methodNameChanged || nameChanges > 0 && declaration.body != null) updateUsagesData else updateOverridesData } return when { renameData != null -> renameData nameChanges > 0 -> if (methodNameChanged || declaration.body != null) updateUsagesData else updateOverridesData else -> null } } private fun PsiMethod.canHaveOverrides(oldSignature: Signature): Boolean { return PsiUtil.canBeOverridden(this) && oldSignature.visibility != PsiModifier.PRIVATE } override fun hasTypeChanges(oldSignature: Signature, newSignature: Signature): Boolean { return super.hasTypeChanges(oldSignature, newSignature) || oldSignature.annotations != newSignature.annotations || oldSignature.exceptionTypes != newSignature.exceptionTypes } override fun hasParameterTypeChanges(oldParam: Parameter, newParam: Parameter): Boolean { return super.hasParameterTypeChanges(oldParam, newParam) || oldParam.annotations != newParam.annotations } // Annotations were extracted without use of resolve. We must extract them again using more precise method. private fun extractAnnotationsWithResolve(signature: Signature, declaration: PsiMethod, psiFile: PsiFile): Signature { val psiParameters = declaration.parameterList.parameters require(signature.parameters.size == psiParameters.size) return Signature.create( signature.name, signature.type, signature.parameters.zip(psiParameters.asList()).map { (parameter, psiParameter) -> val annotations = extractAnnotations(psiParameter.type, psiParameter, psiFile) parameter.copy(additionalData = JavaParameterAdditionalData(annotations)) }, JavaDeclarationAdditionalData( signature.visibility, extractAnnotations(declaration.returnType, declaration, psiFile), signature.exceptionTypes ) )!! } private fun extractAnnotations(type: PsiType?, owner: PsiModifierListOwner, psiFile: PsiFile): String { if (type == null) return "" return JavaSuggestedRefactoringSupport.extractAnnotationsToCopy(type, owner, psiFile) .joinToString(separator = " ") { it.text } //TODO: strip comments and line breaks } }
apache-2.0
47b2ff98f69580b36ed9203713ccb5a8
48.276596
140
0.75807
5.215653
false
false
false
false
walleth/kethereum
erc1328/src/main/kotlin/org/kethereum/erc1328/ERC1328Generator.kt
1
555
package org.kethereum.erc1328 fun ERC1328.generateURL(): String { var res = "$ERC1328_SCHEMA:" if (topic == null) { valid = false } res += topic if (version != null) { res += "@$version" } val paramList = mutableListOf<Pair<String, String>>() bridge?.let { paramList.add("bridge" to it) } symKey?.let { paramList.add("key" to it) } if (paramList.isNotEmpty()) { res += "?" + paramList.joinToString("&") { it.first + "=" + it.second } } return res }
mit
875a780b8b4438bd228999cdec38f2c5
16.34375
79
0.527928
3.75
false
false
false
false
inorichi/mangafeed
app/src/main/java/eu/kanade/tachiyomi/ui/browse/extension/ExtensionHolder.kt
1
3303
package eu.kanade.tachiyomi.ui.browse.extension import android.view.View import androidx.core.view.isVisible import coil.clear import coil.load import eu.davidea.viewholders.FlexibleViewHolder import eu.kanade.tachiyomi.R import eu.kanade.tachiyomi.databinding.ExtensionItemBinding import eu.kanade.tachiyomi.extension.model.Extension import eu.kanade.tachiyomi.extension.model.InstallStep import eu.kanade.tachiyomi.util.system.LocaleHelper class ExtensionHolder(view: View, val adapter: ExtensionAdapter) : FlexibleViewHolder(view, adapter) { private val binding = ExtensionItemBinding.bind(view) init { binding.extButton.setOnClickListener { adapter.buttonClickListener.onButtonClick(bindingAdapterPosition) } binding.cancelButton.setOnClickListener { adapter.buttonClickListener.onCancelButtonClick(bindingAdapterPosition) } } fun bind(item: ExtensionItem) { val extension = item.extension binding.name.text = extension.name binding.version.text = extension.versionName binding.lang.text = LocaleHelper.getSourceDisplayName(extension.lang, itemView.context) binding.warning.text = when { extension is Extension.Untrusted -> itemView.context.getString(R.string.ext_untrusted) extension is Extension.Installed && extension.isUnofficial -> itemView.context.getString(R.string.ext_unofficial) extension is Extension.Installed && extension.isObsolete -> itemView.context.getString(R.string.ext_obsolete) extension.isNsfw -> itemView.context.getString(R.string.ext_nsfw_short) else -> "" }.uppercase() binding.icon.clear() if (extension is Extension.Available) { binding.icon.load(extension.iconUrl) } else if (extension is Extension.Installed) { binding.icon.load(extension.icon) } bindButtons(item) } @Suppress("ResourceType") fun bindButtons(item: ExtensionItem) = with(binding.extButton) { val extension = item.extension val installStep = item.installStep setText( when (installStep) { InstallStep.Pending -> R.string.ext_pending InstallStep.Downloading -> R.string.ext_downloading InstallStep.Installing -> R.string.ext_installing InstallStep.Installed -> R.string.ext_installed InstallStep.Error -> R.string.action_retry InstallStep.Idle -> { when (extension) { is Extension.Installed -> { if (extension.hasUpdate) { R.string.ext_update } else { R.string.action_settings } } is Extension.Untrusted -> R.string.ext_trust is Extension.Available -> R.string.ext_install } } } ) val isIdle = installStep == InstallStep.Idle || installStep == InstallStep.Error binding.cancelButton.isVisible = !isIdle isEnabled = isIdle isClickable = isIdle } }
apache-2.0
7dd16376f7c6d98b6d3305491f102922
38.321429
125
0.622767
5.01214
false
false
false
false
code-disaster/lwjgl3
modules/lwjgl/opengl/src/templates/kotlin/opengl/templates/GL46Core.kt
4
10444
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license */ package opengl.templates import org.lwjgl.generator.* import opengl.* val GL46C = "GL46C".nativeClassGL("GL46C") { extends = GL45C documentation = """ The OpenGL functionality up to version 4.6. Includes only Core Profile symbols. OpenGL 4.6 implementations support revision 4.60 of the OpenGL Shading Language. Extensions promoted to core in this release: ${ul( registryLinkTo("ARB", "indirect_parameters"), registryLinkTo("ARB", "pipeline_statistics_query"), registryLinkTo("ARB", "polygon_offset_clamp"), registryLinkTo("KHR", "no_error"), registryLinkTo("ARB", "shader_atomic_counter_ops"), registryLinkTo("ARB", "shader_draw_parameters"), registryLinkTo("ARB", "shader_group_vote"), registryLinkTo("ARB", "gl_spirv"), registryLinkTo("ARB", "spirv_extensions"), registryLinkTo("ARB", "texture_filter_anisotropic"), registryLinkTo("ARB", "transform_feedback_overflow_query") )} """ // ARB_indirect_parameters IntConstant( """ Accepted by the {@code target} parameters of BindBuffer, BufferData, BufferSubData, MapBuffer, UnmapBuffer, GetBufferSubData, GetBufferPointerv, MapBufferRange, FlushMappedBufferRange, GetBufferParameteriv, and CopyBufferSubData. """, "PARAMETER_BUFFER"..0x80EE ) IntConstant( "Accepted by the {@code value} parameter of GetIntegerv, GetBooleanv, GetFloatv, and GetDoublev.", "PARAMETER_BUFFER_BINDING"..0x80EF ) var src = GL43["MultiDrawArraysIndirect"] void( "MultiDrawArraysIndirectCount", """ Behaves similarly to #MultiDrawArraysIndirect(), except that {@code drawcount} defines an offset (in bytes) into the buffer object bound to the #PARAMETER_BUFFER binding point at which a single {@code sizei} typed value is stored, which contains the draw count. {@code maxdrawcount} specifies the maximum number of draws that are expected to be stored in the buffer. If the value stored at {@code drawcount} into the buffer is greater than {@code maxdrawcount}, the implementation stops processing draws after {@code maxdrawcount} parameter sets. {@code drawcount} must be a multiple of four. """, src["mode"], Check("maxdrawcount * (stride == 0 ? (4 * 4) : stride)")..MultiType( PointerMapping.DATA_INT )..RawPointer..void.const.p("indirect", "an array of structures containing the draw parameters"), GLintptr("drawcount", "the offset into the parameter buffer object"), GLsizei("maxdrawcount", "the maximum number of draws"), src["stride"] ) src = GL43["MultiDrawElementsIndirect"] void( "MultiDrawElementsIndirectCount", """ Behaves similarly to #MultiDrawElementsIndirect(), except that {@code drawcount} defines an offset (in bytes) into the buffer object bound to the #PARAMETER_BUFFER binding point at which a single {@code sizei} typed value is stored, which contains the draw count. {@code maxdrawcount} specifies the maximum number of draws that are expected to be stored in the buffer. If the value stored at {@code drawcount} into the buffer is greater than {@code maxdrawcount}, the implementation stops processing draws after {@code maxdrawcount} parameter sets. {@code drawcount} must be a multiple of four. """, src["mode"], src["type"], Check("maxdrawcount * (stride == 0 ? (5 * 4) : stride)")..MultiType( PointerMapping.DATA_INT )..RawPointer..void.const.p("indirect", "a structure containing an array of draw parameters"), GLintptr("drawcount", "the offset into the parameter buffer object"), GLsizei("maxdrawcount", "the maximum number of draws"), src["stride"] ) // ARB_pipeline_statistics_query IntConstant( """ Accepted by the {@code target} parameter of #BeginQuery(), #EndQuery(), #GetQueryiv(), #BeginQueryIndexed(), #EndQueryIndexed() and #GetQueryIndexediv(). """, "VERTICES_SUBMITTED"..0x82EE, "PRIMITIVES_SUBMITTED"..0x82EF, "VERTEX_SHADER_INVOCATIONS"..0x82F0, "TESS_CONTROL_SHADER_PATCHES"..0x82F1, "TESS_EVALUATION_SHADER_INVOCATIONS"..0x82F2, "GEOMETRY_SHADER_PRIMITIVES_EMITTED"..0x82F3, "FRAGMENT_SHADER_INVOCATIONS"..0x82F4, "COMPUTE_SHADER_INVOCATIONS"..0x82F5, "CLIPPING_INPUT_PRIMITIVES"..0x82F6, "CLIPPING_OUTPUT_PRIMITIVES"..0x82F7 ) // ARB_polygon_offset_clamp IntConstant( "Accepted by the {@code pname} parameters of GetBooleanv, GetIntegerv, GetInteger64v, GetFloatv, and GetDoublev.", "POLYGON_OFFSET_CLAMP"..0x8E1B ) void( "PolygonOffsetClamp", """ The depth values of all fragments generated by the rasterization of a polygon may be offset by a single value that is computed for that polygon. This function determines this value. {@code factor} scales the maximum depth slope of the polygon, and {@code units} scales an implementation-dependent constant that relates to the usable resolution of the depth buffer. The resulting values are summed to produce the polygon offset value, which may then be clamped to a minimum or maximum value specified by {@code clamp}. The values {@code factor}, {@code units}, and {@code clamp} may each be positive, negative, or zero. Calling the command #PolygonOffset() is equivalent to calling the command {@code PolygonOffsetClamp} with clamp equal to zero. """, GLfloat("factor", "scales the maximum depth slope of the polygon"), GLfloat("units", "scales an implementation-dependent constant that relates to the usable resolution of the depth buffer"), GLfloat("clamp", "the minimum or maximum polygon offset value") ) // KHR_no_error IntConstant( "If set in #CONTEXT_FLAGS, then no error behavior is enabled for this context.", "CONTEXT_FLAG_NO_ERROR_BIT"..0x00000008 ) // ARB_gl_spirv IntConstant( "Accepted by the {@code binaryformat} parameter of #ShaderBinary().", "SHADER_BINARY_FORMAT_SPIR_V"..0x9551 ) IntConstant( "Accepted by the {@code pname} parameter of #GetShaderiv().", "SPIR_V_BINARY"..0x9552 ) void( "SpecializeShader", """ Specializes a shader created from a SPIR-V module. Shaders associated with SPIR-V modules must be specialized before they can be linked into a program object. It is not necessary to specialize the shader before it is attached to a program object. Once specialized, a shader may not be specialized again without first re-associating the original SPIR-V module with it, through #ShaderBinary(). Specialization does two things: ${ul( "Selects the name of the entry point, for that shader’s stage, from the SPIR-V module.", "Sets the values of all, or a subset of, the specialization constants in the SPIRV module." )} On successful shader specialization, the compile status for shader is set to #TRUE. On failure, the compile status for shader is set to #FALSE and additional information about the cause of the failure may be available in the shader compilation log. """, GLuint( "shader", """ the name of a shader object containing unspecialized SPIR-V as created from a successful call to #ShaderBinary() to which a SPIR-V module was passed """ ), GLcharUTF8.const.p( "pEntryPoint", "a pointer to a null-terminated UTF-8 string specifying the name of the entry point in the SPIR-V module to use for this shader" ), AutoSize("pConstantIndex", "pConstantValue")..GLuint( "numSpecializationConstants", "the number of specialization constants whose values to set in this call" ), nullable..GLuint.const.p( "pConstantIndex", """ is a pointer to an array of {@code numSpecializationConstants} unsigned integers, each holding the index of a specialization constant in the SPIR-V module whose value to set. Specialization constants not referenced by {@code pConstantIndex} retain their default values as specified in the SPIR-V module. """ ), nullable..GLuint.const.p( "pConstantValue", """ an entry in {@code pConstantValue} is used to set the value of the specialization constant indexed by the corresponding entry in {@code pConstantIndex}. Although this array is of unsigned integer, each entry is bitcast to the appropriate type for the module, and therefore, floating-point constants may be set by including their IEEE-754 bit representation in the {@code pConstantValue} array. """ ) ) // ARB_spirv_extensions IntConstant( "Accepted by the {@code name} parameter of #GetStringi().", "SPIR_V_EXTENSIONS"..0x9553 ) IntConstant( "Accepted by the {@code pname} parameter of #GetIntegerv().", "NUM_SPIR_V_EXTENSIONS"..0x9554 ) // ARB_texture_filter_anisotropic IntConstant( "Accepted by the {@code pname} parameters of GetTexParameterfv, GetTexParameteriv, TexParameterf, TexParameterfv, TexParameteri, and TexParameteriv.", "TEXTURE_MAX_ANISOTROPY"..0x84FE ) IntConstant( "Accepted by the {@code pname} parameters of GetBooleanv, GetDoublev, GetFloatv, and GetIntegerv.", "MAX_TEXTURE_MAX_ANISOTROPY"..0x84FF ) // ARB_transform_feedback_overflow_query IntConstant( """ Accepted by the {@code target} parameter of #BeginQuery(), #EndQuery(), #GetQueryiv(), #BeginQueryIndexed(), #EndQueryIndexed() and #GetQueryIndexediv(). """, "TRANSFORM_FEEDBACK_OVERFLOW"..0x82EC, "TRANSFORM_FEEDBACK_STREAM_OVERFLOW"..0x82ED ) }
bsd-3-clause
1dba020831750d34f8d3d7df2ef2e833
39.792969
159
0.652078
4.634709
false
false
false
false
sharkspeed/dororis
languages/kotlin/programming-kotlin/6-chapter/6-Observables.kt
1
837
import kotlin.properties.Delegates fun main(args: Array<String>) { val onChange = WithObservableProp() onChange.value = 10 onChange.value = -30 val positiveVal = OnlyPositiveValues() positiveVal.value = 100 println("positiveVal value is ${positiveVal.value}") positiveVal.value = -100 println("positiveVal value is ${positiveVal.value}") positiveVal.value = 120 println("positiveVal value is ${positiveVal.value}") } class WithObservableProp { var value: Int by Delegates.observable(0) {p, oldNew, newVal -> onValueChanged() } private fun onValueChanged() { println("value has changed: $value") } } // another observable implementation offered out of the box class OnlyPositiveValues { var value: Int by Delegates.vetoable(0) { p, oldNew, newVal -> newVal >=0 } }
bsd-2-clause
299f7e2231811e66cc7b38c597000d04
27.862069
84
0.694146
4.004785
false
false
false
false
reinterpretcat/utynote
app/src/main/java/com/utynote/components/search/SearchAdapter.kt
1
2471
package com.utynote.components.search import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.ViewGroup import com.utynote.R import com.utynote.databinding.SearchViewBusyBinding import com.utynote.databinding.SearchViewErrorBinding import com.utynote.databinding.SearchViewItemBinding import com.utynote.extensions.Either import com.utynote.extensions.getOrThrow typealias EitherBinding = Either<SearchViewBusyBinding, SearchViewItemBinding, SearchViewErrorBinding> internal class SearchAdapter : RecyclerView.Adapter<SearchAdapter.ViewHolder>() { private var model: SearchViewModel? = null override fun getItemViewType(position: Int): Int = when (model) { is SearchViewModel.Busy -> R.layout.search_view_busy is SearchViewModel.Error -> R.layout.search_view_error else -> R.layout.search_view_item } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val inflater = LayoutInflater.from(parent.context) return when (viewType) { R.layout.search_view_busy -> ViewHolder(Either.First<SearchViewBusyBinding>(SearchViewBusyBinding.inflate(inflater, parent, false))) R.layout.search_view_error -> ViewHolder(Either.Third<SearchViewErrorBinding>(SearchViewErrorBinding.inflate(inflater, parent, false))) else -> ViewHolder(Either.Second<SearchViewItemBinding>(SearchViewItemBinding.inflate(inflater, parent, false))) } } override fun onBindViewHolder(holder: ViewHolder, position: Int) = holder.bind(model!!, position) override fun getItemCount(): Int { val m = model when (m) { is SearchViewModel.Data -> return m.data.size null -> return 0 else -> return 1 } } fun setModel(model: SearchViewModel) { this.model = model notifyDataSetChanged() } internal class ViewHolder(val binding : EitherBinding) : RecyclerView.ViewHolder(binding.fold( {it.root}, {it.root}, {it.root})) { fun bind(model : SearchViewModel, position : Int) = when (model) { is SearchViewModel.Busy -> binding.firstProjection().getOrThrow() .model = model.progress is SearchViewModel.Data -> binding.secondProjection().getOrThrow().model = model.data[position] is SearchViewModel.Error -> binding.thirdProjection().getOrThrow() .model = model.description } } }
agpl-3.0
bab6e3dac5342300a7f3b02e6efd8fe9
41.603448
147
0.713072
4.517367
false
false
false
false
Talentica/AndroidWithKotlin
networking/src/main/java/com/talentica/androidkotlin/networking/repoui/RepoPresenter.kt
1
4832
package com.talentica.androidkotlin.networking.repoui import android.app.Activity import com.google.gson.Gson import com.talentica.androidkotlin.networking.R import com.talentica.androidkotlin.networking.dto.Repository import com.talentica.androidkotlin.networking.network.OkHttpService import com.talentica.androidkotlin.networking.network.RetrofitService import com.talentica.androidkotlin.networking.network.VolleyService import org.json.JSONArray import org.json.JSONObject import retrofit2.Call import retrofit2.Callback import retrofit2.Response import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory import java.io.IOException /** * Created by kaushald on 14/06/17. */ class RepoPresenter(cxt: Activity, view: RepositoryContract.View) : RepositoryContract.Presenter { val context: Activity = cxt val view: RepositoryContract.View = view val gson = Gson() var isAlive = true init { } override fun start(type: String, username: String) { view.showLoading() when (type.toLowerCase()) { "okhttp" -> { loadWithOkHttp(username) } "volley" -> { loadWithVolley(username) } "retrofit" -> { loadWithRetrofit(username) } else -> { loadSampleDataFromAssets() } } } override fun destroy() { isAlive = false } private fun loadWithRetrofit(username: String) { val retrofit = Retrofit.Builder().baseUrl("https://api.github.com/") .addConverterFactory(GsonConverterFactory.create()).build() val retrofitService = retrofit.create(RetrofitService::class.java) val retrofitCall = retrofitService.listRepos(username) retrofitCall.enqueue(object : Callback<Array<Repository>> { override fun onFailure(call: Call<Array<Repository>>?, t: Throwable?) { if (!isAlive) { return } view.displayError(context.getString(R.string.some_error_occured)) view.hideLoading() view.destroy() } override fun onResponse(call: Call<Array<Repository>>?, response: Response<Array<Repository>>?) { if (!isAlive) { return } if (response?.body() != null) { view.onReposAvailable(response.body()!!) view.hideLoading() } else { view.displayError(context.getString(R.string.some_error_occured)) view.hideLoading() view.destroy() } } }) } private fun loadWithVolley(username: String) { VolleyService.httpGet(context, username, com.android.volley.Response.Listener<JSONArray> { if (isAlive) { val repoList = gson.fromJson(it.toString(), Array<Repository>::class.java) view.onReposAvailable(repoList) view.hideLoading() } }, com.android.volley.Response.ErrorListener { if (isAlive) { view.displayError(context.getString(R.string.some_error_occured)) view.hideLoading() view.destroy() } }) } private fun loadWithOkHttp(username: String) { OkHttpService.httpGet(username, object : okhttp3.Callback { override fun onFailure(call: okhttp3.Call, e: IOException) { if (!isAlive) { return } view.displayError(context.getString(R.string.some_error_occured)) view.hideLoading() view.destroy() } override fun onResponse(call: okhttp3.Call, response: okhttp3.Response) { if (!isAlive) { return } if (response.body != null) { val strResponse = response.body!!.string() val repoList = gson.fromJson(strResponse, Array<Repository>::class.java) view.onReposAvailable(repoList) view.hideLoading() } else { view.displayError(context.getString(R.string.some_error_occured)) view.hideLoading() view.destroy() } } }) } private fun loadSampleDataFromAssets() { val sampleJson: String = JSONObject(test.getTestData(context)).getString("repos") val repos = gson.fromJson(sampleJson, Array<Repository>::class.java) view.onReposAvailable(repos) view.hideLoading() } }
apache-2.0
e6363032183c5155100e619710ea21c9
31.006623
98
0.569743
4.890688
false
false
false
false
jguerinet/MyMartlet-Android
app/src/main/java/util/retrofit/CourseResultConverter.kt
2
11635
/* * Copyright 2014-2019 Julien Guerinet * * 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.guerinet.mymartlet.util.retrofit import androidx.core.util.Pair import com.guerinet.mymartlet.model.CourseResult import com.guerinet.mymartlet.model.Term import com.guerinet.mymartlet.util.DayUtils import com.squareup.moshi.Types import okhttp3.ResponseBody import org.jsoup.Jsoup import org.threeten.bp.DayOfWeek import org.threeten.bp.LocalDate import org.threeten.bp.LocalTime import retrofit2.Converter import retrofit2.Retrofit import timber.log.Timber import java.io.IOException import java.lang.reflect.ParameterizedType import java.lang.reflect.Type import java.util.ArrayList /** * Retrofit converter to parse a list of course results when searching for courses * @author Julien Guerinet * @since 2.2.0 */ class CourseResultConverter : Converter.Factory(), Converter<ResponseBody, List<CourseResult>> { /** [ParameterizedType] representing a list of [CourseResult]s */ private val type = Types.newParameterizedType(List::class.java, CourseResult::class.java) override fun responseBodyConverter( type: Type?, annotations: Array<Annotation>?, retrofit: Retrofit? ): Converter<ResponseBody, *>? { return if (type?.toString() != this.type.toString()) { //This can only convert a list of course results null } else CourseResultConverter() } @Throws(IOException::class) override fun convert(value: ResponseBody): List<CourseResult> { val html = value.string() val courses = ArrayList<CourseResult>() val document = Jsoup.parse(html, "UTF-8") //Parse the response body into a list of rows val rows = document.getElementsByClass("dddefault") // Parse the currentTerm from the page header val header = document.getElementsByClass("staticheaders")[0] val term = Term.parseTerm(header.childNode(2).toString()) // Get the table in the form of a set of rows val table = document.getElementsByClass("datadisplaytable")[0].select("tbody")[0] // Go through the rows in the table for (row in table.select("tr")) { // Check that there at least 19 elements in the row val rowElements = row.select("td") if (rowElements.size < 19) { // If there aren't, it must not be a course row continue } // Create a new course object with the default values var credits = 99.0 var subject: String? = null var number: String? = null var title = "" var type = "" val days = ArrayList<DayOfWeek>() var crn = 0 var instructor = "" var location = "" //So that the rounded start time will be 0 var startTime = ScheduleConverter.defaultStartTime var endTime = ScheduleConverter.defaultEndTime var capacity = 0 var seatsRemaining = 0 var waitlistRemaining = 0 var startDate: LocalDate? = LocalDate.now() var endDate: LocalDate? = LocalDate.now() try { var i = 0 while (i < rowElements.size) { if (rowElements[i].toString().contains("&nbsp;")) { // Empty row: continue i++ continue } var rowString = rowElements[i].text() when (i) { // CRN 1 -> crn = Integer.parseInt(rowString) // Subject 2 -> subject = rowString // Number 3 -> number = rowString // Type 5 -> type = rowString // Number of credits 6 -> credits = java.lang.Double.parseDouble(rowString) // Course title 7 -> //Remove the extra period at the end of the course title title = rowString.substring(0, rowString.length - 1) // Days of the week 8 -> if (rowString == "TBA") { // TBA Stuff: no time associated so skip the next one // and add a dummy to keep the index correct rowElements.add(9, null) i++ } else { // Day Parsing rowString = rowString.replace('\u00A0', ' ').trim { it <= ' ' } for (k in 0 until rowString.length) { days.add(DayUtils.getDay(rowString[k])) } } // Time 9 -> { val times = rowString.split("-".toRegex()).dropLastWhile { it.isEmpty() } .toTypedArray() try { var startHour = Integer.parseInt( times[0].split(" ".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()[0].split( ":".toRegex() ).dropLastWhile { it.isEmpty() }.toTypedArray()[0] ) val startMinute = Integer.parseInt( times[0].split(" ".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()[0].split( ":".toRegex() ).dropLastWhile { it.isEmpty() }.toTypedArray()[1] ) var endHour = Integer.parseInt( times[1].split(" ".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()[0].split( ":".toRegex() ).dropLastWhile { it.isEmpty() }.toTypedArray()[0] ) val endMinute = Integer.parseInt( times[1].split(" ".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()[0].split( ":".toRegex() ).dropLastWhile { it.isEmpty() }.toTypedArray()[1] ) //If it's PM, then add 12 hours to the hours for 24 hours format //Make sure it isn't noon val startPM = times[0].split(" ".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()[1] if (startPM == "PM" && startHour != 12) { startHour += 12 } val endPM = times[1].split(" ".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()[1] if (endPM == "PM" && endHour != 12) { endHour += 12 } startTime = LocalTime.of(startHour, startMinute) endTime = LocalTime.of(endHour, endMinute) } catch (e: NumberFormatException) { //Courses sometimes don't have assigned times startTime = ScheduleConverter.defaultStartTime endTime = ScheduleConverter.defaultEndTime } } // Capacity 10 -> capacity = Integer.parseInt(rowString) // Seats remaining 12 -> seatsRemaining = Integer.parseInt(rowString) // Waitlist remaining 15 -> waitlistRemaining = Integer.parseInt(rowString) // Instructor 16 -> instructor = rowString // Start/end date 17 -> { val dates = parseDateRange(term, rowString) startDate = dates.first endDate = dates.second } // Location 18 -> location = rowString } i++ } } catch (e: Exception) { Timber.e(e, "Course Results Parser Error") } // Don't add any courses with errors if (subject != null && number != null) { // Create a new course object and add it to list // TODO Should we be parsing the course section? courses.add( CourseResult( term, subject, number, title, crn, "", startTime, endTime, days, type, location, instructor, credits, startDate!!, endDate!!, capacity, seatsRemaining, waitlistRemaining ) ) } } return courses } /** * Parses a String into a LocalDate object * * @param term Current currentTerm * @param date The date String * @return The corresponding local date */ fun parseDate(term: Term, date: String): LocalDate { val dateFields = date.split("/".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray() return LocalDate.of( term.year, Integer.parseInt(dateFields[0]), Integer.parseInt(dateFields[1]) ) } /** * Parses the date range String into 2 dates * * @param term Current currentTerm * @param dateRange The date range String * @return A pair representing the starting and ending dates of the range * @throws IllegalArgumentException */ @Throws(IllegalArgumentException::class) fun parseDateRange(term: Term, dateRange: String): Pair<LocalDate, LocalDate> { //Split the range into the 2 date Strings val dates = dateRange.split("-".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray() val startDate = dates[0].trim { it <= ' ' } val endDate = dates[1].trim { it <= ' ' } //Parse the dates, return them as a pair return Pair(parseDate(term, startDate), parseDate(term, endDate)) } }
apache-2.0
d8c7b8cacb3660ef77b3414d593f6d6b
42.90566
125
0.477439
5.648058
false
false
false
false
JesusM/FingerprintManager
kfingerprintmanager/src/main/kotlin/com/jesusm/kfingerprintmanager/base/ui/FingerprintBaseDialogFragment.kt
1
5572
package com.jesusm.kfingerprintmanager.base.ui import android.app.Dialog import android.content.Context import android.content.DialogInterface import android.os.Bundle import android.support.annotation.CallSuper import android.support.annotation.StringRes import android.support.v4.hardware.fingerprint.FingerprintManagerCompat import android.support.v7.app.AlertDialog import android.support.v7.app.AppCompatDialogFragment import android.support.v7.view.ContextThemeWrapper import android.view.LayoutInflater import android.view.View import com.jesusm.kfingerprintmanager.KFingerprintManager import com.jesusm.kfingerprintmanager.R import com.jesusm.kfingerprintmanager.base.FingerprintAssetsManager import com.jesusm.kfingerprintmanager.base.hardware.FingerprintHardware import com.jesusm.kfingerprintmanager.base.ui.presenter.FingerprintBaseDialogPresenter import kotlin.properties.Delegates abstract class FingerprintBaseDialogFragment<T : FingerprintBaseDialogPresenter> : AppCompatDialogFragment(), FingerprintBaseDialogPresenter.View { var callback: KFingerprintManager.FingerprintBaseCallback? = null lateinit var dialogRootView: View lateinit var fingerprintContainer: View lateinit var alertDialog: AlertDialog private var customDialogStyle: Int = 0 var presenter by Delegates.observable<T?>(null) { _, _, new -> onPresenterChanged(new) } open fun onPresenterChanged(new: T?) {} override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { val context = buildDialogContext() val layoutInflater = context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater dialogRootView = layoutInflater.inflate(R.layout.fingerprint_dialog_container, null, false) fingerprintContainer = dialogRootView.findViewById(R.id.fingerprint_dialog_content) inflateViews(dialogRootView) val builder = AlertDialog.Builder(context, customDialogStyle) builder.setView(dialogRootView) addDialogButtons(builder) return builder.create().apply { alertDialog = this setOnShowListener({ onDialogShown() }) } } @CallSuper open fun inflateViews(rootView: View) {} @CallSuper open fun onDialogShown() { presenter?.onViewShown() } @CallSuper open fun addDialogButtons(dialogBuilder: AlertDialog.Builder) { dialogBuilder.setNegativeButton(R.string.cancel, { _, _ -> presenter?.onDialogCancelled() }) } override fun onPause() { super.onPause() presenter?.pause() } private fun buildDialogContext(): Context = if (customDialogStyle == 1) context else ContextThemeWrapper(context, customDialogStyle) override fun onFingerprintDisplayed() { updateDialogButtonText(DialogInterface.BUTTON_NEGATIVE, R.string.cancel) fingerprintContainer.visibility = View.VISIBLE } fun updateDialogButtonText(whichButton: Int, @StringRes resId: Int) { alertDialog.getButton(whichButton)?.setText(resId) } override fun onCancelled() { callback?.onCancelled() } override fun close() { dismissAllowingStateLoss() } override fun onCancel(dialog: DialogInterface?) { super.onCancel(dialog) presenter?.onDialogCancelled() } override fun onFingerprintNotRecognized() { callback?.onFingerprintNotRecognized() } override fun onAuthenticationFailedWithHelp(help: String?) { callback?.onAuthenticationFailedWithHelp(help) } override fun onFingerprintNotAvailable() { callback?.onFingerprintNotAvailable() } abstract class Builder<D : FingerprintBaseDialogFragment<P>, P : FingerprintBaseDialogPresenter> { private var customStyle: Int = 0 private var callback: KFingerprintManager.FingerprintBaseCallback? = null private lateinit var fingerPrintHardware: FingerprintHardware private lateinit var cryptoObject: FingerprintManagerCompat.CryptoObject fun withCustomStyle(customStyle: Int): Builder<*, *> { this.customStyle = customStyle return this } fun withCallback(callback: KFingerprintManager.FingerprintBaseCallback): Builder<*, *> { this.callback = callback return this } fun withFingerprintHardwareInformation(fingerprintAssetsManager: FingerprintAssetsManager): Builder<*, *> { this.fingerPrintHardware = fingerprintAssetsManager.fingerprintHardware this.cryptoObject = fingerprintAssetsManager.getCryptoObject() return this } @Throws(RuntimeException::class) internal fun build(): D { if (callback == null) { throw RuntimeException("You need to provide a callback") } val dialogFragment = createDialogFragment() dialogFragment.callback = callback val presenter = createPresenter(dialogFragment) dialogFragment.presenter = presenter presenter.setFingerprintHardware(fingerPrintHardware, cryptoObject) if (customStyle != -1) { dialogFragment.customDialogStyle = customStyle } addProperties(dialogFragment) return dialogFragment } protected abstract fun createDialogFragment(): D protected abstract fun createPresenter(view: D): P protected abstract fun addProperties(dialogFragment: D) } }
mit
1d5d2514ddc863d618ed0b9b76e8303a
33.401235
115
0.710337
5.430799
false
false
false
false
Pinkal7600/Todo
app/src/main/java/com/pinkal/todo/Intro/activity/IntroActivity.kt
1
3444
package com.pinkal.todo.Intro.activity import android.app.Activity import android.content.Intent import android.graphics.Color import android.os.Bundle import android.support.v4.view.ViewPager import android.support.v7.app.AppCompatActivity import android.view.View import android.view.WindowManager import com.pinkal.todo.Intro.adapter.IntroAdapter import com.pinkal.todo.MainActivity import com.pinkal.todo.R import com.pinkal.todo.utils.TOTAL_INTRO_PAGES import kotlinx.android.synthetic.main.activity_intro.* /** * Created by Pinkal on 13/6/17. */ class IntroActivity : AppCompatActivity() { val mActivity: Activity = this@IntroActivity override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_intro) initialize() } private fun initialize() { val window = window window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS) window.statusBarColor = resources.getColor(R.color.redPrimaryDark) viewPagerIntro.isFocusable = true viewPagerIntro.adapter = IntroAdapter(supportFragmentManager) circleIndicator.radius = 12f circleIndicator.setViewPager(viewPagerIntro) val density = resources.displayMetrics.density circleIndicator.setBackgroundColor(Color.TRANSPARENT) circleIndicator.strokeWidth = 0f circleIndicator.radius = 5 * density circleIndicator.pageColor = resources.getColor(R.color.redPrimaryDark) // background color circleIndicator.fillColor = resources.getColor(R.color.colorWhite) // dots fill color txtSkipIntro.setOnClickListener({ startActivity(Intent(mActivity, MainActivity::class.java)) finish() }) circleIndicator.setOnPageChangeListener(object : ViewPager.OnPageChangeListener { override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) { } override fun onPageSelected(position: Int) { if (position < TOTAL_INTRO_PAGES - 1) { txtSkipIntro.visibility = View.VISIBLE } else if (position == TOTAL_INTRO_PAGES - 1) { txtSkipIntro.visibility = View.GONE } when (position) { 0 -> { circleIndicator.pageColor = resources.getColor(R.color.redPrimaryDark) window.statusBarColor = resources.getColor(R.color.redPrimaryDark) } 1 -> { circleIndicator.pageColor = resources.getColor(R.color.purplePrimaryDark) window.statusBarColor = resources.getColor(R.color.purplePrimaryDark) } 2 -> { circleIndicator.pageColor = resources.getColor(R.color.tealPrimaryDark) window.statusBarColor = resources.getColor(R.color.tealPrimaryDark) } 3 -> { circleIndicator.pageColor = resources.getColor(R.color.indigoPrimaryDark) window.statusBarColor = resources.getColor(R.color.indigoPrimaryDark) } } } override fun onPageScrollStateChanged(state: Int) { } }) } }
apache-2.0
e43790bfac7ac21e4530961e691a97ad
34.515464
106
0.634727
5.079646
false
false
false
false
MarkusAmshove/Kluent
jvm/src/main/kotlin/org/amshove/kluent/StackTraces.kt
1
904
@file:JvmName("stacktracesjvm") package org.amshove.kluent actual val stacktraces: StackTraces = object : StackTraces { override fun throwableLocation(t: Throwable): String? { return throwableLocation(t, 1).firstOrNull() } override fun throwableLocation(t: Throwable, n: Int): List<String> { return (t.cause ?: t).stackTrace?.dropWhile { it.className.startsWith("org.amshove.kluent") && !it.className.startsWith("org.amshove.kluent.test") }?.take(n)?.map { it.toString() } ?: emptyList() } override fun <T : Throwable> cleanStackTrace(throwable: T): T { throwable.stackTrace = UserStackTraceConverter.getUserStacktrace(throwable.stackTrace) return throwable } override fun root(throwable: Throwable): Throwable { val cause = throwable.cause return if (cause == null) throwable else root(cause) } }
mit
bd5b98875ce124aa71be10d3df53fb04
33.769231
112
0.672566
4.264151
false
false
false
false
sreich/ore-infinium
core/src/com/ore/infinium/components/PowerGeneratorComponent.kt
1
2577
/** MIT License Copyright (c) 2016 Shaun Reich <sreich02@gmail.com> 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.ore.infinium.components import com.artemis.Component import com.ore.infinium.GeneratorInventory import com.ore.infinium.util.DoNotCopy import com.ore.infinium.util.DoNotPrint import com.ore.infinium.util.ExtendedComponent import com.ore.infinium.util.defaultCopyFrom /** * Any device that can generate some amount of power on a circuit */ class PowerGeneratorComponent : Component(), ExtendedComponent<PowerGeneratorComponent> { /** * current EU supply rate, adjusted according to * conditions or fuel changes. */ var supplyRateEU: Int = 0 enum class GeneratorType { Solar, Wind, Combustion, Geothermal, Nuclear } var type = GeneratorType.Combustion @Transient @DoNotCopy @DoNotPrint /** * generators tend to have inventory slots * where you can store fuel sources. * we also consider the first slot to be the primary * fuel source (the one being burnt right now). * * the others are the reserves * * only valid for certain types of generators. * e.g. solar doesn't have anything in it */ var fuelSources: GeneratorInventory? = null override fun canCombineWith(other: PowerGeneratorComponent) = this.type == other.type override fun copyFrom(other: PowerGeneratorComponent) = this.defaultCopyFrom(other) }
mit
8fe875018bb7c88282df9c8874ec3974
33.824324
89
0.714397
4.577265
false
false
false
false
zbeboy/ISY
src/main/java/top/zbeboy/isy/service/util/OperatorWordUtils.kt
1
16289
package top.zbeboy.isy.service.util import org.apache.commons.lang3.StringUtils import org.apache.poi.xwpf.usermodel.* import org.openxmlformats.schemas.wordprocessingml.x2006.main.* import java.io.FileOutputStream import java.math.BigInteger /** * Created by zbeboy 2017-11-30 . **/ class OperatorWordUtils { /** * 添加方块♢ */ @Throws(Exception::class) fun setCellContentCommonFunction(cell: XWPFTableCell, content: String) { val p = cell.addParagraph() setParagraphSpacingInfo(p, true, "0", "0", "0", "0", true, "300", STLineSpacingRule.AUTO) setParagraphAlignInfo(p, ParagraphAlignment.BOTH, TextAlignment.CENTER) var pRun = getOrAddParagraphFirstRun(p, false, false) setParagraphRunSymInfo(p, pRun, "宋体", "Times New Roman", "21", true, false, false, 0, 6, 0) pRun = getOrAddParagraphFirstRun(p, true, false) setParagraphRunFontInfo(p, pRun, content, "宋体", "Times New Roman", "21", true, false, false, false, null, null, 0, 6, 0) } /** * 保存文档 */ @Throws(Exception::class) fun saveDocument(document: XWPFDocument, savePath: String) { val fos = FileOutputStream(savePath) document.write(fos) fos.close() } /** * 得到单元格第一个Paragraph */ fun getCellFirstParagraph(cell: XWPFTableCell): XWPFParagraph { return if (cell.paragraphs != null && cell.paragraphs.size > 0) { cell.paragraphs[0] } else { cell.addParagraph() } } /** * 得到段落CTPPr */ fun getParagraphCTPPr(p: XWPFParagraph): CTPPr? { var pPPr: CTPPr? = null if (p.ctp != null) { pPPr = if (p.ctp.pPr != null) { p.ctp.pPr } else { p.ctp.addNewPPr() } } return pPPr } /** * 设置段落间距信息, 一行=100 一磅=20 */ fun setParagraphSpacingInfo(p: XWPFParagraph, isSpace: Boolean, before: String?, after: String?, beforeLines: String?, afterLines: String?, isLine: Boolean, line: String?, lineValue: STLineSpacingRule.Enum?) { val pPPr = getParagraphCTPPr(p) val pSpacing = if (pPPr!!.spacing != null) pPPr.spacing else pPPr.addNewSpacing() if (isSpace) { // 段前磅数 if (before != null) { pSpacing.before = BigInteger(before) } // 段后磅数 if (after != null) { pSpacing.after = BigInteger(after) } // 段前行数 if (beforeLines != null) { pSpacing.beforeLines = BigInteger(beforeLines) } // 段后行数 if (afterLines != null) { pSpacing.afterLines = BigInteger(afterLines) } } // 间距 if (isLine) { if (line != null) { pSpacing.line = BigInteger(line) } if (lineValue != null) { pSpacing.lineRule = lineValue } } } fun setParagraphRunFontInfo(p: XWPFParagraph, pRun: XWPFRun, content: String, cnFontFamily: String, enFontFamily: String, fontSize: String, isBlod: Boolean, isItalic: Boolean, isStrike: Boolean, isShd: Boolean, shdColor: String?, shdStyle: STShd.Enum?, position: Int, spacingValue: Int, indent: Int) { val pRpr = getRunCTRPr(p, pRun) if (StringUtils.isNotBlank(content)) { // pRun.setText(content); if (content.contains("\n")) {// System.properties("line.separator") val lines = content.split("\n".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray() pRun.setText(lines[0], 0) // set first line into XWPFRun for (i in 1 until lines.size) { // add break and insert new text pRun.addBreak() pRun.setText(lines[i]) } } else { pRun.setText(content, 0) } } // 设置字体 val fonts = if (pRpr.isSetRFonts) pRpr.rFonts else pRpr .addNewRFonts() if (StringUtils.isNotBlank(enFontFamily)) { fonts.ascii = enFontFamily fonts.hAnsi = enFontFamily } if (StringUtils.isNotBlank(cnFontFamily)) { fonts.eastAsia = cnFontFamily fonts.hint = STHint.EAST_ASIA } // 设置字体大小 val sz = if (pRpr.isSetSz) pRpr.sz else pRpr.addNewSz() sz.`val` = BigInteger(fontSize) val szCs = if (pRpr.isSetSzCs) pRpr.szCs else pRpr .addNewSzCs() szCs.`val` = BigInteger(fontSize) // 设置字体样式 // 加粗 pRun.isBold = isBlod // 倾斜 pRun.isItalic = isItalic // 删除线 pRun.isStrikeThrough = isStrike if (isShd) { // 设置底纹 val shd = if (pRpr.isSetShd) pRpr.shd else pRpr.addNewShd() if (shdStyle != null) { shd.`val` = shdStyle } if (shdColor != null) { shd.color = shdColor shd.fill = shdColor } } // 设置文本位置 if (position != 0) { pRun.textPosition = position } if (spacingValue > 0) { // 设置字符间距信息 val ctSTwipsMeasure = if (pRpr.isSetSpacing) pRpr .spacing else pRpr.addNewSpacing() ctSTwipsMeasure.`val` = BigInteger(spacingValue.toString()) } if (indent > 0) { val paramCTTextScale = if (pRpr.isSetW) pRpr.w else pRpr .addNewW() paramCTTextScale.`val` = indent } } /** * 得到XWPFRun的CTRPr */ fun getRunCTRPr(p: XWPFParagraph, pRun: XWPFRun): CTRPr { var pRpr: CTRPr if (pRun.ctr != null) { pRpr = pRun.ctr.rPr if (pRpr == null) { pRpr = pRun.ctr.addNewRPr() } } else { pRpr = p.ctp.addNewR().addNewRPr() } return pRpr } /** * 设置段落对齐 */ fun setParagraphAlignInfo(p: XWPFParagraph, pAlign: ParagraphAlignment?, valign: TextAlignment?) { if (pAlign != null) { p.alignment = pAlign } if (valign != null) { p.verticalAlignment = valign } } fun getOrAddParagraphFirstRun(p: XWPFParagraph, isInsert: Boolean, isNewLine: Boolean): XWPFRun { val pRun: XWPFRun = if (isInsert) { p.createRun() } else { if (p.runs != null && p.runs.size > 0) { p.runs[0] } else { p.createRun() } } if (isNewLine) { pRun.addBreak() } return pRun } /** * 设置Table的边框 */ fun setTableBorders(table: XWPFTable, borderType: STBorder.Enum, size: String, color: String, space: String) { val tblPr = getTableCTTblPr(table) val borders = if (tblPr.isSetTblBorders) tblPr.tblBorders else tblPr.addNewTblBorders() val hBorder = if (borders.isSetInsideH) borders.insideH else borders.addNewInsideH() hBorder.`val` = borderType hBorder.sz = BigInteger(size) hBorder.color = color hBorder.space = BigInteger(space) val vBorder = if (borders.isSetInsideV) borders.insideV else borders.addNewInsideV() vBorder.`val` = borderType vBorder.sz = BigInteger(size) vBorder.color = color vBorder.space = BigInteger(space) val lBorder = if (borders.isSetLeft) borders.left else borders .addNewLeft() lBorder.`val` = borderType lBorder.sz = BigInteger(size) lBorder.color = color lBorder.space = BigInteger(space) val rBorder = if (borders.isSetRight) borders.right else borders .addNewRight() rBorder.`val` = borderType rBorder.sz = BigInteger(size) rBorder.color = color rBorder.space = BigInteger(space) val tBorder = if (borders.isSetTop) borders.top else borders .addNewTop() tBorder.`val` = borderType tBorder.sz = BigInteger(size) tBorder.color = color tBorder.space = BigInteger(space) val bBorder = if (borders.isSetBottom) borders.bottom else borders.addNewBottom() bBorder.`val` = borderType bBorder.sz = BigInteger(size) bBorder.color = color bBorder.space = BigInteger(space) } /** * 得到Table的CTTblPr, 不存在则新建 */ fun getTableCTTblPr(table: XWPFTable): CTTblPr { val ttbl = table.ctTbl return if (ttbl.tblPr == null) ttbl.addNewTblPr() else ttbl .tblPr } /** * 设置列宽和垂直对齐方式 */ fun setCellWidthAndVAlign(cell: XWPFTableCell, width: String?, typeEnum: STTblWidth.Enum?, vAlign: STVerticalJc.Enum?) { val tcPr = getCellCTTcPr(cell) val tcw = if (tcPr.isSetTcW) tcPr.tcW else tcPr.addNewTcW() if (width != null) { tcw.w = BigInteger(width) } if (typeEnum != null) { tcw.type = typeEnum } if (vAlign != null) { val vJc = if (tcPr.isSetVAlign) tcPr.vAlign else tcPr .addNewVAlign() vJc.`val` = vAlign } } /** * 跨列合并 */ fun mergeCellsHorizontal(table: XWPFTable, row: Int, fromCell: Int, toCell: Int) { for (cellIndex in fromCell..toCell) { val cell = table.getRow(row).getCell(cellIndex) if (cellIndex == fromCell) { // The first merged cell is set with RESTART merge value getCellCTTcPr(cell).addNewHMerge().`val` = STMerge.RESTART } else { // Cells which join (merge) the first one,are set with CONTINUE getCellCTTcPr(cell).addNewHMerge().`val` = STMerge.CONTINUE } } } /** * 得到Cell的CTTcPr, 不存在则新建 */ fun getCellCTTcPr(cell: XWPFTableCell): CTTcPr { val cttc = cell.ctTc return if (cttc.isSetTcPr) cttc.tcPr else cttc.addNewTcPr() } /** * @Description: 设置表格列宽 */ fun setTableGridCol(table: XWPFTable, colWidths: IntArray) { val ttbl = table.ctTbl val tblGrid = if (ttbl.tblGrid != null) ttbl.tblGrid else ttbl.addNewTblGrid() var j = 0 val len = colWidths.size while (j < len) { val gridCol = tblGrid.addNewGridCol() gridCol.w = BigInteger(colWidths[j].toString()) j++ } } @Throws(Exception::class) fun setParagraphRunSymInfo(p: XWPFParagraph, pRun: XWPFRun, cnFontFamily: String, enFontFamily: String, fontSize: String, isBlod: Boolean, isItalic: Boolean, isStrike: Boolean, position: Int, spacingValue: Int, indent: Int) { val pRpr = getRunCTRPr(p, pRun) // 设置字体 val fonts = if (pRpr.isSetRFonts) pRpr.rFonts else pRpr .addNewRFonts() if (StringUtils.isNotBlank(enFontFamily)) { fonts.ascii = enFontFamily fonts.hAnsi = enFontFamily } if (StringUtils.isNotBlank(cnFontFamily)) { fonts.eastAsia = cnFontFamily fonts.hint = STHint.EAST_ASIA } // 设置字体大小 val sz = if (pRpr.isSetSz) pRpr.sz else pRpr.addNewSz() sz.`val` = BigInteger(fontSize) val szCs = if (pRpr.isSetSzCs) pRpr.szCs else pRpr .addNewSzCs() szCs.`val` = BigInteger(fontSize) // 设置字体样式 // 加粗 pRun.isBold = isBlod // 倾斜 pRun.isItalic = isItalic // 删除线 pRun.isStrikeThrough = isStrike // 设置文本位置 if (position != 0) { pRun.textPosition = position } if (spacingValue > 0) { // 设置字符间距信息 val ctSTwipsMeasure = if (pRpr.isSetSpacing) pRpr .spacing else pRpr.addNewSpacing() ctSTwipsMeasure.`val` = BigInteger(spacingValue.toString()) } if (indent > 0) { val paramCTTextScale = if (pRpr.isSetW) pRpr.w else pRpr .addNewW() paramCTTextScale.`val` = indent } val symList = pRun.ctr.symList val sym = CTSym.Factory .parse("<xml-fragment w:font=\"Wingdings 2\" w:char=\"00A3\" xmlns:w=\"http://schemas.openxmlformats.org/wordprocessingml/2006/main\" xmlns:wne=\"http://schemas.microsoft.com/office/word/2006/wordml\"> </xml-fragment>") symList.add(sym) } /** * 设置表格总宽度与水平对齐方式 */ fun setTableWidthAndHAlign(table: XWPFTable, width: String, enumValue: STJc.Enum?) { val tblPr = getTableCTTblPr(table) val tblWidth = if (tblPr.isSetTblW) tblPr.tblW else tblPr .addNewTblW() if (enumValue != null) { val cTJc = tblPr.addNewJc() cTJc.`val` = enumValue } tblWidth.w = BigInteger(width) tblWidth.type = STTblWidth.DXA } /** * 设置单元格Margin */ fun setTableCellMargin(table: XWPFTable, top: Int, left: Int, bottom: Int, right: Int) { table.setCellMargins(top, left, bottom, right) } /** * 得到CTTrPr, 不存在则新建 */ fun getRowCTTrPr(row: XWPFTableRow): CTTrPr { val ctRow = row.ctRow return if (ctRow.isSetTrPr) ctRow.trPr else ctRow.addNewTrPr() } /** * 设置行高 */ fun setRowHeight(row: XWPFTableRow, hight: String, heigthEnum: STHeightRule.Enum?) { val trPr = getRowCTTrPr(row) val trHeight: CTHeight if (trPr.trHeightList != null && trPr.trHeightList.size > 0) { trHeight = trPr.trHeightList[0] } else { trHeight = trPr.addNewTrHeight() } trHeight.`val` = BigInteger(hight) if (heigthEnum != null) { trHeight.hRule = heigthEnum } } /** * 设置底纹 */ fun setCellShdStyle(cell: XWPFTableCell, isShd: Boolean, shdColor: String?, shdStyle: STShd.Enum?) { val tcPr = getCellCTTcPr(cell) if (isShd) { // 设置底纹 val shd = if (tcPr.isSetShd) tcPr.shd else tcPr.addNewShd() if (shdStyle != null) { shd.`val` = shdStyle } if (shdColor != null) { shd.color = shdColor shd.fill = shdColor } } } }
mit
eabe3363821f6a9bf8633c55c495034e
29.229008
235
0.502052
3.82862
false
false
false
false
paplorinc/intellij-community
platform/xdebugger-impl/src/com/intellij/xdebugger/impl/actions/RestoreBreakpointAction.kt
2
1141
// 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 com.intellij.xdebugger.impl.actions import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.application.WriteAction import com.intellij.openapi.project.DumbAwareAction import com.intellij.xdebugger.impl.XDebuggerManagerImpl import com.intellij.xdebugger.impl.breakpoints.XBreakpointManagerImpl /** * @author egor */ class RestoreBreakpointAction : DumbAwareAction() { override fun actionPerformed(e: AnActionEvent) { val project = e.project if (project != null) { WriteAction.run<Throwable> { (XDebuggerManagerImpl.getInstance(project).breakpointManager as XBreakpointManagerImpl) .restoreLastRemovedBreakpoint()?.navigatable?.navigate(true) } } } override fun update(e: AnActionEvent) { val project = e.project if (project != null) { e.presentation.isEnabledAndVisible = (XDebuggerManagerImpl.getInstance(project).breakpointManager as XBreakpointManagerImpl).canRestoreLastRemovedBreakpoint() } } }
apache-2.0
60b9196e672c04480c16bcf22a2c3308
37.066667
140
0.77213
4.600806
false
false
false
false
paplorinc/intellij-community
java/java-tests/testSrc/com/intellij/java/codeInsight/daemon/inlays/JavaParameterNameHintsTest.kt
3
25692
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.java.codeInsight.daemon.inlays import com.intellij.codeInsight.daemon.impl.ParameterHintsPresentationManager import com.intellij.codeInsight.hints.JavaInlayParameterHintsProvider import com.intellij.codeInsight.hints.settings.ParameterNameHintsSettings import com.intellij.ide.highlighter.JavaFileType import com.intellij.lang.java.JavaLanguage import com.intellij.openapi.editor.Inlay import com.intellij.testFramework.fixtures.LightCodeInsightFixtureTestCase import org.assertj.core.api.Assertions.assertThat class JavaInlayParameterHintsTest : LightCodeInsightFixtureTestCase() { override fun tearDown() { val default = ParameterNameHintsSettings() ParameterNameHintsSettings.getInstance().loadState(default.state) super.tearDown() } fun check(text: String) { myFixture.configureByText("A.java", text) myFixture.testInlays() } fun `test insert literal arguments`() { check(""" class Groo { public void test(File file) { boolean testNow = System.currentTimeMillis() > 34000; int times = 1; float pi = 4; String title = "Testing..."; char ch = 'q'; configure(<hint text="testNow:"/>true, <hint text="times:"/>555, <hint text="pii:"/>3.141f, <hint text="title:"/>"Huge Title", <hint text="terminate:"/>'c', <hint text="file:"/>null); configure(testNow, shouldIgnoreRoots(), fourteen, pi, title, c, file); } public void configure(boolean testNow, int times, float pii, String title, char terminate, File file) { System.out.println(); System.out.println(); } }""") } fun `test do not show for Exceptions`() { check(""" class Fooo { public void test() { Throwable t = new IllegalStateException("crime"); } } """) } fun `test show hint for single string literal if there is multiple string params`() { check("""class Groo { public void test() { String message = "sdfsdfdsf"; assertEquals(<hint text="expected:"/>"fooo", message); String title = "TT"; show(title, <hint text="message:"/>"Hi"); } public void assertEquals(String expected, String actual) {} public void show(String title, String message) {} }""") } fun `test no hints for generic builders`() { check(""" class Foo { void test() { new IntStream().skip(10); new Stream<Integer>().skip(10); } } class IntStream { public IntStream skip(int n) {} } class Stream<T> { public Stream<T> skip(int n) {} } """) JavaInlayParameterHintsProvider.getInstance().isDoNotShowForBuilderLikeMethods.set(false) check(""" class Foo { void test() { new IntStream().skip(<hint text="n:"/>10); new Stream<Integer>().skip(<hint text="n:"/>10); } } class IntStream { public IntStream skip(int n) {} } class Stream<T> { public Stream<T> skip(int n) {} } """) } fun `test do not show hints on setters`() { check("""class Groo { public void test() { setTestNow(false); System.out.println(""); } public void setTestNow(boolean testNow) { System.out.println(""); System.out.println(""); } }""") } fun `test single varargs hint`() { check(""" public class VarArgTest { public void main() { System.out.println("AAA"); testBooleanVarargs(<hint text="test:"/>13, <hint text="...booleans:"/>false); } public boolean testBooleanVarargs(int test, Boolean... booleans) { int temp = test; return false; } } """) } fun `test no hint if varargs null`() { check(""" public class VarArgTest { public void main() { System.out.println("AAA"); testBooleanVarargs(<hint text="test:"/>13); } public boolean testBooleanVarargs(int test, Boolean... booleans) { int temp = test; return false; } } """) } fun `test multiple vararg hint`() { check(""" public class VarArgTest { public void main() { System.out.println("AAA"); testBooleanVarargs(<hint text="test:"/>13, <hint text="...booleans:"/>false, true, false); } public boolean testBooleanVarargs(int test, Boolean... booleans) { int temp = test; return false; } } """) } fun `test do not inline known subsequent parameter names`() { check(""" public class Test { public void main() { test1(1, 2); test2(1, 2); test3(1, 2); doTest("first", "second"); } public void test1(int first, int second) { int start = first; int end = second; } public void test2(int key, int value) { int start = key; int end = value; } public void test3(int key, int value) { int start = key; int end = value; } } """) } fun `test show if can be assigned`() { check(""" public class CharSymbol { public void main() { Object obj = new Object(); count(<hint text="test:"/>100, <hint text="boo:"/>false, <hint text="seq:"/>"Hi!"); } public void count(Integer test, Boolean boo, CharSequence seq) { int a = test; Object obj = new Object(); } } """) } fun `test inline positive and negative numbers`() { check(""" public class CharSymbol { public void main() { Object obj = new Object(); count(<hint text="test:"/>-1, obj); count(<hint text="test:"/>+1, obj); } public void count(int test, Object obj) { Object tmp = obj; boolean isFast = false; } } """) } fun `test inline literal arguments with crazy settings`() { check(""" public class Test { public void main(boolean isActive, boolean requestFocus, int xoo) { System.out.println("AAA"); main(<hint text="isActive:"/>true,<hint text="requestFocus:"/>false, /*comment*/<hint text="xoo:"/>2); } } """) } fun `test suppress for erroneous parameters`() { JavaInlayParameterHintsProvider.getInstance().isShowForParamsWithSameType.set(false) check(""" public class Test { void foo(String foo) {} void foo(String foo, String bar) {} void foo(String foo, String bar, String baz) {} void test() { foo("a"++"b"); // no hint } } """) JavaInlayParameterHintsProvider.getInstance().isShowForParamsWithSameType.set(true) check(""" public class Test { void foo(String foo) {} void foo(String foo, String bar) {} void foo(String foo, String bar, String baz) {} void test() { foo(<hint text="foo:"/>"a"++"b"); } } """) } fun `test ignored methods`() { check(""" public class Test { List<String> list = new ArrayList<>(); StringBuilder builder = new StringBuilder(); public void main() { System.out.println("A"); System.out.print("A"); list.add("sss"); list.get(1); list.set(1, "sss"); setNewIndex(10); "sss".contains("s"); builder.append("sdfsdf"); "sfsdf".startWith("s"); "sss".charAt(3); clearStatus(<hint text="updatedRecently:"/>false); } void print(String s) {} void println(String s) {} void get(int index) {} void set(int index, Object object) {} void append(String s) {} void clearStatus(boolean updatedRecently) {} } """) } fun `test hints for generic arguments`() { check(""" class QList<E> { void add(int query, E obj) {} } class QCmp<E> { void cmpre(E oe1, E oq2) {} } public class Test { public void main(QCmp<Integer> c, QList<String> l) { c.cmpre(<hint text="oe1:"/>0, /** ddd */<hint text="oq2:"/>3); l.add(<hint text="query:"/>1, <hint text="obj:"/>"uuu"); } } """) } fun `test inline constructor literal arguments names`() { check(""" public class Test { public void main() { System.out.println("AAA"); Checker r = new Checker(<hint text="isActive:"/>true, <hint text="requestFocus:"/>false) { @Override void test() { } }; } abstract class Checker { Checker(boolean isActive, boolean requestFocus) {} abstract void test(); } } """) } fun `test inline anonymous class constructor parameters`() { check(""" public class Test { Test(int counter, boolean shouldTest) { System.out.println(); System.out.println(); } public static void main() { System.out.println(); Test t = new Test(<hint text="counter:"/>10, <hint text="shouldTest:"/>false); } } """) } fun `test inline if one of vararg params is literal`() { check(""" public class VarArgTest { public void main() { System.out.println("AAA"); int test = 13; boolean isCheck = false; boolean isOk = true; testBooleanVarargs(test, <hint text="...booleans:"/>isCheck, true, isOk); } public boolean testBooleanVarargs(int test, Boolean... booleans) { int temp = test; return false; } } """) } fun `test if any param matches inline all`() { check(""" public class VarArgTest { public void main() { check(<hint text="x:"/>10, <hint text="paramNameLength:"/>1000); } public void check(int x, int paramNameLength) { } } """) } fun `test inline common name pair if more that 2 args`() { check(""" public class VarArgTest { public void main() { String s = "su"; check(<hint text="beginIndex:"/>10, <hint text="endIndex:"/>1000, s); } public void check(int beginIndex, int endIndex, String params) { } } """) } fun `test ignore String methods`() { check(""" class Test { public void main() { String.format("line", "eee", "www"); } } """) } fun `test inline common name pair if more that 2 args xxx`() { check(""" public class VarArgTest { public void main() { check(<hint text="beginIndex:"/>10, <hint text="endIndex:"/>1000, <hint text="x:"/>"su"); } public void check(int beginIndex, int endIndex, String x) { } } """) } fun `test inline this`() { check(""" public class VarArgTest { public void main() { check(<hint text="test:"/>this, <hint text="endIndex:"/>1000); } public void check(VarArgTest test, int endIndex) { } } """) } fun `test inline strange methods`() { check(""" public class Test { void main() { createContent(<hint text="manager:"/>null); createNewContent(<hint text="test:"/>this); } Content createContent(DockManager manager) {} Content createNewContent(Test test) {} } interface DockManager {} interface Content {} """) } fun `test do not inline builder pattern`() { check(""" class Builder { void await(boolean value) {} Builder bwait(boolean xvalue) {} Builder timeWait(int time) {} } class Test { public void test() { Builder builder = new Builder(); builder.await(<hint text="value:"/>true); builder.bwait(false).timeWait(100); } } """) JavaInlayParameterHintsProvider.getInstance().isDoNotShowForBuilderLikeMethods.set(false) check(""" class Builder { void await(boolean value) {} Builder bwait(boolean xvalue) {} Builder timeWait(int millis) {} } class Test { public void test() { Builder builder = new Builder(); builder.await(<hint text="value:"/>true); builder.bwait(<hint text="xvalue:"/>false).timeWait(<hint text="millis:"/>100); } } """) } fun `test builder method only method with one param`() { check(""" class Builder { Builder qwit(boolean value, String sValue) {} Builder trew(boolean value) {} } class Test { public void test() { Builder builder = new Builder(); builder .trew(false) .qwit(<hint text="value:"/>true, <hint text="sValue:"/>"value"); } } """) JavaInlayParameterHintsProvider.getInstance().isDoNotShowForBuilderLikeMethods.set(false) check(""" class Builder { Builder qwit(boolean value, String sValue) {} Builder trew(boolean value) {} } class Test { public void test() { Builder builder = new Builder(); builder .trew(<hint text="value:"/>false) .qwit(<hint text="value:"/>true, <hint text="sValue:"/>"value"); } } """) } fun `test do not show single parameter hint if it is string literal`() { check(""" public class Test { public void test() { debug("Error message"); info("Error message", new Object()); } void debug(String message) {} void info(String message, Object error) {} } """) } fun `test show single`() { check(""" class Test { void main() { blah(<hint text="a:"/>1, <hint text="b:"/>2); int z = 2; draw(<hint text="x:"/>10, <hint text="y:"/>20, z); int x = 10; int y = 12; drawRect(x, y, <hint text="w:"/>10, <hint text="h:"/>12); } void blah(int a, int b) {} void draw(int x, int y, int z) {} void drawRect(int x, int y, int w, int h) {} } """) } fun `test do not show for setters`() { check(""" class Test { void main() { set(10); setWindow(100); setWindow(<hint text="height:"/>100, <hint text="weight:">); } void set(int newValue) {} void setWindow(int newValue) {} void setWindow(int height, int weight) {} } """) } fun `test do not show for equals and min`() { check(""" class Test { void test() { "xxx".equals(name); Math.min(10, 20); } } """) } fun `test more blacklisted items`() { check(""" class Test { void test() { System.getProperty("aaa"); System.setProperty("aaa", "bbb"); new Key().create(10); } } class Key { void create(int a) {} } """) } fun `test poly and binary expressions`() { check(""" class Test { void test() { xxx(<hint text="followTheSum:"/>100); check(<hint text="isShow:"/>1 + 1); check(<hint text="isShow:"/>1 + 1 + 1); yyy(<hint text="followTheSum:"/>200); } void check(int isShow) {} void xxx(int followTheSum) {} void yyy(int followTheSum) {} } """) } fun `test incorrect pattern`() { ParameterNameHintsSettings.getInstance().addIgnorePattern(JavaLanguage.INSTANCE, "") check(""" class Test { void test() { check(<hint text="isShow:"/>1000); } void check(int isShow) {} } """) } fun `test do not show hint for name contained in method`() { JavaInlayParameterHintsProvider.getInstance().isDoNotShowIfMethodNameContainsParameterName.set(true) check(""" class Test { void main() { timeoutExecution(1000); createSpace(true); } void timeoutExecution(int timeout) {} void createSpace(boolean space) {} } """) } fun `test show if multiple params but name contained`() { JavaInlayParameterHintsProvider.getInstance().isDoNotShowIfMethodNameContainsParameterName.set(true) check(""" class Test { void main() { timeoutExecution(<hint text="timeout:"/>1000, <hint text="message:"/>"xxx"); createSpace(<hint text="space:"/>true, <hint text="a:"/>10); } void timeoutExecution(int timeout, String message) {} void createSpace(boolean space, int a) {} } """) } fun `test show same params`() { JavaInlayParameterHintsProvider.getInstance().isShowForParamsWithSameType.set(true) check(""" class Test { void main() { String c = "c"; String d = "d"; test(<hint text="parent:"/>c, <hint text="child:"/>d); } void test(String parent, String child) { } } """) } fun `test show triple`() { JavaInlayParameterHintsProvider.getInstance().isShowForParamsWithSameType.set(true) check(""" class Test { void main() { String c = "c"; test(<hint text="parent:"/>c, <hint text="child:"/>c, <hint text="grandParent:"/>c); } void test(String parent, String child, String grandParent) { } } """) } fun `test show couple of doubles`() { JavaInlayParameterHintsProvider.getInstance().isShowForParamsWithSameType.set(true) check(""" class Test { void main() { String c = "c"; String d = "d"; int v = 10; test(<hint text="parent:"/>c, <hint text="child:"/>d, <hint text="vx:"/>v, <hint text="vy:"/>v); } void test(String parent, String child, int vx, int vy) { } } """) } fun `test show ambigous`() { myFixture.configureByText(JavaFileType.INSTANCE, """ class Test { void main() { test(10<selection>, 100</selection>); } void test(int a, String bS) {} void test(int a, int bI) {} } """) myFixture.doHighlighting() val hints = getHints() assertThat(hints.size).isEqualTo(2) assertThat(hints[0]).isEqualTo("a:") assertThat(hints[1]).isEqualTo("bI:") myFixture.type('\b') myFixture.doHighlighting() assertSingleInlayWithText("a:") } fun `test show ambiguous constructor`() { myFixture.configureByText(JavaFileType.INSTANCE, """ class Test { void main() { new X(10<selection>, 100</selection>); } } class X { X(int a, int bI) {} X(int a, String bS) {} } """) myFixture.doHighlighting() val hints = getHints() assertThat(hints.size).isEqualTo(2) assertThat(hints[0]).isEqualTo("a:") assertThat(hints[1]).isEqualTo("bI:") myFixture.type('\b') myFixture.doHighlighting() assertSingleInlayWithText("a:") } fun `test preserved inlays`() { myFixture.configureByText(JavaFileType.INSTANCE, """ class Test { void main() { test(<caret>); } void test(int fooo) {} } """) myFixture.type("100") myFixture.doHighlighting() assertSingleInlayWithText("fooo:") myFixture.type("\b\b\b") myFixture.doHighlighting() assertSingleInlayWithText("fooo:") myFixture.type("yyy") myFixture.doHighlighting() assertSingleInlayWithText("fooo:") myFixture.checkResult( """ class Test { void main() { test(yyy); } void test(int fooo) {} } """) } fun `test do not show hints if method is unknown and one of them or both are blacklisted`() { ParameterNameHintsSettings.getInstance().addIgnorePattern(JavaLanguage.INSTANCE, "*kee") myFixture.configureByText(JavaFileType.INSTANCE, """ class Test { void main() { kee(100<caret>) } void kee(int a) {} void kee(String a) {} } """) myFixture.doHighlighting() var hints = getHints() assertThat(hints).hasSize(0) myFixture.type('+') myFixture.doHighlighting() hints = getHints() assertThat(hints).hasSize(0) } fun `test multiple hints on same offset lives without exception`() { myFixture.configureByText(JavaFileType.INSTANCE, """ class Test { void main() { check(<selection>0, </selection>200); } void check(int qas, int b) { } } """) myFixture.doHighlighting() var inlays = getHints() assert(inlays.size == 2) myFixture.type('\b') myFixture.doHighlighting() inlays = getHints() assert(inlays.size == 1 && inlays.first() == "qas:", { "Real inlays ${inlays.size}" }) } fun `test params with same type`() { JavaInlayParameterHintsProvider.getInstance().isShowForParamsWithSameType.set(true) check(""" class Test { void test() { String parent, child, element; check(<hint text="a:"/>10, parent, child); check(<hint text="a:"/>10, <hint text="parent:">element, child); } void check(int a, String parent, String child) {} } """) } fun `test if resolved but no hints just return no hints`() { myFixture.configureByText(JavaFileType.INSTANCE, """ public class Test { public void main() { foo(1<caret>); } void foo(int a) {} void foo() {} } """) myFixture.doHighlighting() var inlays = getHints() assert(inlays.size == 1) myFixture.type('\b') myFixture.performEditorAction("EditorLeft") myFixture.doHighlighting() inlays = getHints() assert(inlays.isEmpty()) } fun `test one-char one-digit hints enabled`() { JavaInlayParameterHintsProvider.getInstance().ignoreOneCharOneDigitHints.set(false) check(""" class Test { void main() { timeoutExecution(<hint text="t1:"/>1, <hint text="t2:"/>2, <hint text="t3:"/>3, <hint text="t4:"/>4, <hint text="t5:"/>5, <hint text="t6:"/>6, <hint text="t7:"/>7, <hint text="t8:"/>8, <hint text="t9:"/>9, <hint text="t10:"/>10); } void timeoutExecution(int t1, int t2, int t3, int t4, int t5, int t6, int t7, int t8, int t9, int t10) {} } """) } fun `test ordered sequential`() { JavaInlayParameterHintsProvider.getInstance().ignoreOneCharOneDigitHints.set(true) check(""" class Test { void main() { rect(<hint text="x1:"/>1, <hint text="y1:"/>2, <hint text="x2:"/>3, <hint text="y2:"/>4); fromZero(1, 2); fromOne(1, 2); fromX(<hint text="x86:"/>1, <hint text="x87:"/>2); fromX(<hint text="x86:"/>1); } void rect(int x1, int y1, int x2, int y2) {} void fromZero(int x0, int x1) {} void fromOne(int x1, int x2) {} void fromX(int x86, int x87) {} void fromX(int x86) {} } """) } fun `test unordered sequential`() { JavaInlayParameterHintsProvider.getInstance().ignoreOneCharOneDigitHints.set(true) check(""" class Test { void test() { unordered(<hint text="x1:"/>100, <hint text="x3:"/>200); unordered2(<hint text="x0:"/>100, <hint text="x3:"/>200); } void unordered(int x1, int x3) {} void unordered2(int x0, int x3) {} } """) } fun `test ordered with varargs`() { JavaInlayParameterHintsProvider.getInstance().ignoreOneCharOneDigitHints.set(true) check(""" class Test { void test() { ord(100, 200); ord2(100, 200); } void ord(int x1, int x2, int... others) {} void ord2(int x0, int x1, int... others) {} } """) } fun `test one-char one-digit hints disabled`() { JavaInlayParameterHintsProvider.getInstance().ignoreOneCharOneDigitHints.set(true) check(""" class Test { void main() { timeoutExecution(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); } void timeoutExecution(int t1, int t2, int t3, int t4, int t5, int t6, int t7, int t8, int t9, int t10) {} } """) } fun `test just some unparsable parameter name`() { JavaInlayParameterHintsProvider.getInstance().ignoreOneCharOneDigitHints.set(true) check(""" class Test { void main() { check(<hint text="main2toMain:"/>100); www(<hint text="x86:"/>100); } void check(int main2toMain) {} void www(int x86) {} } """) } fun `test unclear expression type setting true`() { JavaInlayParameterHintsProvider.getInstance().isShowHintWhenExpressionTypeIsClear.set(true) check(""" class Test { void main() { String data = "asdad"; foo(<hint text="info:"/>data); } void foo(String info) {} } """) } fun `test unclear expression type setting false`() { JavaInlayParameterHintsProvider.getInstance().isShowHintWhenExpressionTypeIsClear.set(false) check(""" class Test { void main() { String data = "asdad"; foo(data); } void foo(String info) {} } """) } fun `test enum parameter names`() { check(""" public enum Thingy { ONE(<hint text="green:"/>false, <hint text="striped:"/>true), TWO(<hint text="green:"/>false, <hint text="striped:"/>false), THREE(<hint text="...x:"/>12,32,3,2,32,3,2,3,23); private boolean green; private boolean striped; Thingy(final boolean green, final boolean striped) { this.green = green; this.striped = striped; } Thingy(int... x) { } }""") } fun `test enum parameter names disabled`() { JavaInlayParameterHintsProvider.getInstance().isShowHintsForEnumConstants.set(false) check(""" public enum Thingy { ONE(false, true), TWO(false, false), THREE(12,32,3,2,32,3,2,3,23); private boolean green; private boolean striped; Thingy(final boolean green, final boolean striped) { this.green = green; this.striped = striped; } Thingy(int... x) { } }""") } fun `test constructor call`() { JavaInlayParameterHintsProvider.getInstance().isShowHintsForNewExpressions.set(true) check(""" public class Test { static class A { A(boolean hardName){} } void foo() { new A(<hint text="hardName:"/>true); } }""") } fun `test constructor call disabled`() { JavaInlayParameterHintsProvider.getInstance().isShowHintsForNewExpressions.set(false) check(""" public class Test { static class A { A(boolean hardName){} } void foo() { new A(true); } }""") } fun `test constructor call with other features`() { JavaInlayParameterHintsProvider.getInstance().isShowHintsForNewExpressions.set(true) JavaInlayParameterHintsProvider.getInstance().ignoreOneCharOneDigitHints.set(true) check(""" public class Test { static class A { A(boolean a1, boolean a2){} } void foo() { new A(true, false); } }""") } fun getHints(): List<String> { val document = myFixture.getDocument(myFixture.file) val manager = ParameterHintsPresentationManager.getInstance() return myFixture.editor .inlayModel .getInlineElementsInRange(0, document.textLength) .mapNotNull { manager.getHintText(it) } } fun assertSingleInlayWithText(expectedText: String) { val inlays = myFixture.editor.inlayModel.getInlineElementsInRange(0, editor.document.textLength) assertThat(inlays).hasSize(1) val realText = getHintText(inlays[0]) assertThat(realText).isEqualTo(expectedText) } fun getHintText(inlay: Inlay<*>): String { return ParameterHintsPresentationManager.getInstance().getHintText(inlay) } }
apache-2.0
4ed75333da61db171f9b001226382b3d
20.847789
233
0.628795
3.724558
false
true
false
false
google/intellij-community
plugins/kotlin/base/plugin/src/org/jetbrains/kotlin/idea/compiler/configuration/KotlinIdePlugin.kt
5
2504
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.compiler.configuration import com.intellij.ide.plugins.IdeaPluginDescriptor import com.intellij.ide.plugins.PluginManagerCore import com.intellij.internal.statistic.utils.PluginInfo import com.intellij.internal.statistic.utils.getPluginInfoById import com.intellij.openapi.extensions.PluginId object KotlinIdePlugin { val id: PluginId /** * If `true`, the installed Kotlin IDE plugin is post-processed to be included in some other IDE, such as AppCode. */ val isPostProcessed: Boolean /** * If `true`, the plugin version was patched in runtime, using the `kotlin.plugin.version` Java system property. */ val hasPatchedVersion: Boolean /** * An original (non-patched) plugin version from the plugin descriptor. */ val originalVersion: String /** * Kotlin IDE plugin version (the patched version if provided, the version from the plugin descriptor otherwise). */ val version: String val isSnapshot: Boolean val isRelease: Boolean get() = !isSnapshot && KotlinPluginLayout.standaloneCompilerVersion.isRelease val isPreRelease: Boolean get() = !isRelease val isDev: Boolean get() = !isSnapshot && KotlinPluginLayout.standaloneCompilerVersion.isDev fun getPluginDescriptor(): IdeaPluginDescriptor = PluginManagerCore.getPlugin(id) ?: error("Kotlin IDE plugin ($id) disappeared") fun getPluginInfo(): PluginInfo = getPluginInfoById(id) init { val mainPluginId = "org.jetbrains.kotlin" val allPluginIds = listOf( mainPluginId, "com.intellij.appcode.kmm", "org.jetbrains.kotlin.native.appcode" ) val pluginDescriptor = PluginManagerCore.getPlugins().firstOrNull { it.pluginId.idString in allPluginIds } ?: error("Kotlin IDE plugin not found above the active plugins: " + PluginManagerCore.getPlugins().contentToString()) val patchedVersion = System.getProperty("kotlin.plugin.version", null) id = pluginDescriptor.pluginId isPostProcessed = id.idString == mainPluginId hasPatchedVersion = patchedVersion != null originalVersion = pluginDescriptor.version version = patchedVersion ?: originalVersion isSnapshot = version == "@snapshot@" || version.contains("-SNAPSHOT") } }
apache-2.0
e67a0183beef46d1b23051125f4f751f
35.304348
133
0.70607
5.018036
false
false
false
false
google/intellij-community
platform/platform-impl/src/com/intellij/openapi/wm/impl/headertoolbar/ProjectToolbarWidgetAction.kt
1
2481
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.openapi.wm.impl.headertoolbar import com.intellij.ide.ui.UISettings import com.intellij.openapi.actionSystem.ActionUpdateThread import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.Presentation import com.intellij.openapi.actionSystem.ex.CustomComponentAction import com.intellij.openapi.fileEditor.FileEditorManager import com.intellij.openapi.util.NlsSafe import com.intellij.openapi.util.registry.Registry import javax.swing.JComponent class ProjectToolbarWidgetAction : AnAction(), CustomComponentAction { override fun actionPerformed(e: AnActionEvent) {} override fun getActionUpdateThread(): ActionUpdateThread = ActionUpdateThread.EDT override fun createCustomComponent(presentation: Presentation, place: String): JComponent = ProjectWidget(presentation) override fun update(e: AnActionEvent) { val project = e.project val file = project?.let { FileEditorManager.getInstance(it).selectedFiles.firstOrNull() } val settings = UISettings.getInstance() val showFileName = Registry.`is`("ide.experimental.ui.project.widget.show.file") && settings.editorTabPlacement == UISettings.TABS_NONE && file != null val maxLength = if (showFileName) 12 else 24 val projName = project?.name ?: "" @NlsSafe val fullName = StringBuilder(projName) @NlsSafe val cutName = StringBuilder(cutProject(projName, maxLength)) if (showFileName) { fullName.append(" — ").append(file!!.name) cutName.append(" — ").append(cutFile(file.name, maxLength)) } e.presentation.text = cutName.toString() e.presentation.description = if (cutName.toString() == fullName.toString()) null else fullName.toString() e.presentation.putClientProperty(projectKey, project) } private fun cutFile(value: String, maxLength: Int): String { if (value.length <= maxLength) return value val extension = value.substringAfterLast(".", "") val name = value.substringBeforeLast(".") if (name.length + extension.length <= maxLength) return value return name.substring(0, maxLength - extension.length) + "..." + extension } private fun cutProject(value: String, maxLength: Int): String { return if (value.length <= maxLength) value else value.substring(0, maxLength) + "..." } }
apache-2.0
c2e77154d5d7e8e8612e1d1c117c31d8
44.054545
155
0.755349
4.495463
false
false
false
false
apache/isis
incubator/clients/kroviz/src/main/kotlin/org/apache/causeway/client/kroviz/ui/dialog/DownloadDialog.kt
2
1543
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.causeway.client.kroviz.ui.dialog import org.apache.causeway.client.kroviz.to.ValueType import org.apache.causeway.client.kroviz.ui.core.FormItem import org.apache.causeway.client.kroviz.ui.core.RoDialog import org.apache.causeway.client.kroviz.utils.DomUtil class DownloadDialog(val fileName:String, val content:String) : Controller() { val formItems = mutableListOf<FormItem>() override fun open() { formItems.add(FormItem("Preview", ValueType.TEXT_AREA, content, 15)) dialog = RoDialog(caption = "Download: $fileName", items = formItems, controller = this) super.open() } override fun execute(action:String?) { DomUtil.download(fileName, content) } }
apache-2.0
da3a1da8e27e2cff0bdd236d5e9d20cd
36.634146
96
0.738172
4.136729
false
false
false
false
google/intellij-community
tools/ideTestingFramework/intellij.tools.ide.metricsCollector/src/com/intellij/metricsCollector/publishing/utils.kt
3
1166
package com.intellij.metricsCollector.publishing import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper import com.intellij.metricsCollector.collector.PerformanceMetricsDto import com.intellij.metricsCollector.metrics.IndexingMetrics import com.intellij.openapi.util.BuildNumber import kotlin.io.path.div const val reportName = "metrics.performance.json" @Suppress("unused") fun IndexingMetrics.publishIndexingMetrics(): IndexingMetrics { val performanceMetricsJson = this.toPerformanceMetricsJson() val jsonWithIndexingMetrics = "indexing.$reportName" val jsonReport = this.ideStartResult.context.paths.reportsDir / jsonWithIndexingMetrics jacksonObjectMapper().writerWithDefaultPrettyPrinter().writeValue(jsonReport.toFile(), performanceMetricsJson) return this } fun IndexingMetrics.toPerformanceMetricsJson(): PerformanceMetricsDto { val metrics = getListOfIndexingMetrics() return PerformanceMetricsDto.create( projectName = this.ideStartResult.runContext.contextName, buildNumber = BuildNumber.fromStringWithProductCode(ideStartResult.context.ide.build, ideStartResult.context.ide.productCode)!!, metrics = metrics ) }
apache-2.0
382f61437fe52f9d58d62bcfbdf62447
40.642857
132
0.833619
4.682731
false
false
false
false
nielsutrecht/adventofcode
src/main/kotlin/com/nibado/projects/advent/y2018/Day07.kt
1
1817
package com.nibado.projects.advent.y2018 import com.nibado.projects.advent.Day import com.nibado.projects.advent.resourceRegex object Day07 : Day { private val regex = "Step ([A-Z]) must be finished before step ([A-Z]) can begin\\.".toRegex() private val input = resourceRegex(2018, 7, regex).map { it.drop(1) }.map { (a, b) -> a.first() to b.first() } private val characters = input.flatMap { listOf(it.first, it.second) }.toSet().sorted().toList() private val preReqs = input.groupBy { it.second }.map { it.key to it.value.map { it.first }.toSet() }.toMap() override fun part1(): String { val result = mutableListOf<Char>() while (result.size < characters.size) { result += characters .filterNot { result.contains(it) } .first { a -> !preReqs.containsKey(a) || preReqs[a]!!.all { b -> result.contains(b) } } } return result.joinToString("") } override fun part2(): Int { val result = mutableListOf<Char>() var workers = 0 var second = 0 var until = mutableMapOf<Char, Int>() while (result.size < characters.size) { with(until.filter { it.value == second }.keys.sorted()) { forEach { until.remove(it) } workers -= size result += this } characters.filterNot { result.contains(it) || until.keys.contains(it) } .filter { a -> !preReqs.containsKey(a) || preReqs[a]!!.all { b -> result.contains(b) } } .sorted() .take(5 - workers) .also { workers += it.size } .forEach { until[it] = second + (it - 'A' + 61) } second++ } return second - 1 } }
mit
d9775f9f7d0a8ac4177dbf890858eaf3
35.36
113
0.5377
3.958606
false
false
false
false
JetBrains/intellij-community
python/python-terminal/src/com/jetbrains/python/sdk/PyVirtualEnvTerminalCustomizer.kt
1
6932
// 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.jetbrains.python.sdk import com.intellij.openapi.application.runReadAction import com.intellij.openapi.components.PersistentStateComponent import com.intellij.openapi.components.State import com.intellij.openapi.components.Storage import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.options.UnnamedConfigurable import com.intellij.openapi.project.Project import com.intellij.openapi.projectRoots.Sdk import com.intellij.openapi.util.SystemInfo import com.intellij.openapi.vfs.VirtualFile import com.jetbrains.python.packaging.PyCondaPackageService import com.jetbrains.python.run.findActivateScript import com.jetbrains.python.sdk.flavors.conda.CondaEnvSdkFlavor import org.jetbrains.plugins.terminal.LocalTerminalCustomizer import org.jetbrains.plugins.terminal.TerminalOptionsProvider import java.io.File import java.nio.file.Path import java.nio.file.Paths import javax.swing.JCheckBox import kotlin.io.path.Path import kotlin.io.path.exists import kotlin.io.path.isExecutable import kotlin.io.path.name class PyVirtualEnvTerminalCustomizer : LocalTerminalCustomizer() { private fun generateCommandForPowerShell(sdk: Sdk, sdkHomePath: VirtualFile): Array<out String>? { // TODO: This should be migrated to Targets API: each target provides terminal if ((sdk.sdkAdditionalData as? PythonSdkAdditionalData)?.flavor is CondaEnvSdkFlavor) { // Activate conda val condaPath = PyCondaPackageService.getCondaExecutable(sdk.homePath)?.let { Path(it) } val condaActivationCommand: String if (condaPath != null && condaPath.exists() && condaPath.isExecutable()) { condaActivationCommand = getCondaActivationCommand(condaPath, sdkHomePath) } else { logger<PyVirtualEnvTerminalCustomizer>().warn("Can't find $condaPath, will not activate conda") condaActivationCommand = PyTerminalBundle.message("powershell.conda.not.activated", "conda") } return arrayOf("powershell.exe", "-NoExit", "-Command", condaActivationCommand) } // Activate convenient virtualenv val virtualEnvProfile = sdkHomePath.parent.findChild("activate.ps1") ?: return null return if (virtualEnvProfile.exists()) arrayOf("powershell.exe", "-NoExit", "-File", virtualEnvProfile.path) else null } /** *``conda init`` installs conda activation hook into user profile * We run this hook manually because we can't ask user to install hook and restart terminal * In case of failure we ask user to run "conda init" manually */ private fun getCondaActivationCommand(condaPath: Path, sdkHomePath: VirtualFile): String { // ' are in "Write-Host" val errorMessage = PyTerminalBundle.message("powershell.conda.not.activated", condaPath).replace('\'', '"') // No need to escape path: conda can't have spaces return """ $condaPath shell.powershell hook | Out-String | Invoke-Expression ; try { conda activate ${sdkHomePath.parent.path} } catch { Write-Host('$errorMessage') } """.trim() } override fun customizeCommandAndEnvironment(project: Project, workingDirectory: String?, command: Array<out String>, envs: MutableMap<String, String>): Array<out String> { var sdkByDirectory: Sdk? = null if (workingDirectory != null) { runReadAction { sdkByDirectory = PySdkUtil.findSdkForDirectory(project, Paths.get(workingDirectory), false) } } val sdk = sdkByDirectory if (sdk != null && (PythonSdkUtil.isVirtualEnv(sdk) || PythonSdkUtil.isConda(sdk)) && PyVirtualEnvTerminalSettings.getInstance(project).virtualEnvActivate) { // in case of virtualenv sdk on unix we activate virtualenv val sdkHomePath = sdk.homeDirectory if (sdkHomePath != null && command.isNotEmpty()) { val shellPath = command[0] if (Path(shellPath).name == "powershell.exe") { return generateCommandForPowerShell(sdk, sdkHomePath) ?: command } if (isShellIntegrationAvailable(shellPath)) { //fish shell works only for virtualenv and not for conda //for bash we pass activate script to jediterm shell integration (see jediterm-bash.in) to source it there //TODO: fix conda for fish findActivateScript(sdkHomePath.path, shellPath)?.let { activate -> envs.put("JEDITERM_SOURCE", activate.first) envs.put("JEDITERM_SOURCE_ARGS", activate.second ?: "") } } else { //for other shells we read envs from activate script by the default shell and pass them to the process val envVars = PySdkUtil.activateVirtualEnv(sdk) if (envVars.isEmpty()) { Logger.getInstance(PyVirtualEnvTerminalCustomizer::class.java).warn("No vars found to activate in ${sdk.homePath}") } envs.putAll(envVars) } } } return command } private fun isShellIntegrationAvailable(shellPath: String): Boolean { if (TerminalOptionsProvider.instance.shellIntegration) { val shellName = File(shellPath).name return shellName == "bash" || (SystemInfo.isMac && shellName == "sh") || shellName == "zsh" || shellName == "fish" } return false } override fun getConfigurable(project: Project): UnnamedConfigurable = object : UnnamedConfigurable { val settings = PyVirtualEnvTerminalSettings.getInstance(project) var myCheckbox: JCheckBox = JCheckBox(PyTerminalBundle.message("activate.virtualenv.checkbox.text")) override fun createComponent() = myCheckbox override fun isModified() = myCheckbox.isSelected != settings.virtualEnvActivate override fun apply() { settings.virtualEnvActivate = myCheckbox.isSelected } override fun reset() { myCheckbox.isSelected = settings.virtualEnvActivate } } } class SettingsState { var virtualEnvActivate: Boolean = true } @State(name = "PyVirtualEnvTerminalCustomizer", storages = [(Storage("python-terminal.xml"))]) class PyVirtualEnvTerminalSettings : PersistentStateComponent<SettingsState> { private var myState: SettingsState = SettingsState() var virtualEnvActivate: Boolean get() = myState.virtualEnvActivate set(value) { myState.virtualEnvActivate = value } override fun getState(): SettingsState = myState override fun loadState(state: SettingsState) { myState.virtualEnvActivate = state.virtualEnvActivate } companion object { fun getInstance(project: Project): PyVirtualEnvTerminalSettings { return project.getService(PyVirtualEnvTerminalSettings::class.java) } } }
apache-2.0
67d477eaf2dd3cc3824620e6e4e8b7df
39.302326
140
0.71206
4.712441
false
false
false
false
JetBrains/intellij-community
plugins/kotlin/code-insight/intentions-k2/src/org/jetbrains/kotlin/idea/k2/codeinsight/intentions/RemoveAllArgumentNamesIntention.kt
1
6232
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.k2.codeinsight.intentions import com.intellij.openapi.util.TextRange import com.intellij.refactoring.suggested.startOffset import org.jetbrains.kotlin.analysis.api.KtAnalysisSession import org.jetbrains.kotlin.analysis.api.calls.singleFunctionCallOrNull import org.jetbrains.kotlin.config.LanguageFeature import org.jetbrains.kotlin.idea.base.analysis.api.utils.CallParameterInfoProvider import org.jetbrains.kotlin.idea.base.projectStructure.languageVersionSettings import org.jetbrains.kotlin.idea.base.psi.relativeTo import org.jetbrains.kotlin.idea.codeinsight.api.applicators.* import org.jetbrains.kotlin.idea.codeinsights.impl.base.applicators.ApplicabilityRanges import org.jetbrains.kotlin.idea.codeinsights.impl.base.applicators.RemoveArgumentNamesApplicators import org.jetbrains.kotlin.idea.parameterInfo.isArrayOfCall import org.jetbrains.kotlin.psi.KtCallElement import org.jetbrains.kotlin.psi.KtValueArgument import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType class RemoveAllArgumentNamesIntention : AbstractKotlinApplicatorBasedIntention<KtCallElement, RemoveArgumentNamesApplicators.MultipleArgumentsInput>(KtCallElement::class) { override fun getApplicator(): KotlinApplicator<KtCallElement, RemoveArgumentNamesApplicators.MultipleArgumentsInput> = RemoveArgumentNamesApplicators.multipleArgumentsApplicator override fun getApplicabilityRange() = ApplicabilityRanges.SELF override fun getInputProvider(): KotlinApplicatorInputProvider<KtCallElement, RemoveArgumentNamesApplicators.MultipleArgumentsInput> = inputProvider { callElement -> val (sortedArguments, vararg, varargIsArrayOfCall) = collectSortedArgumentsThatCanBeUnnamed(callElement) ?: return@inputProvider null if (sortedArguments.isEmpty()) return@inputProvider null RemoveArgumentNamesApplicators.MultipleArgumentsInput(sortedArguments, vararg, varargIsArrayOfCall) } } class RemoveArgumentNameIntention : AbstractKotlinApplicatorBasedIntention<KtValueArgument, RemoveArgumentNamesApplicators.SingleArgumentInput>(KtValueArgument::class) { override fun getApplicator(): KotlinApplicator<KtValueArgument, RemoveArgumentNamesApplicators.SingleArgumentInput> = RemoveArgumentNamesApplicators.singleArgumentsApplicator override fun getApplicabilityRange(): KotlinApplicabilityRange<KtValueArgument> = applicabilityRange { valueArgument -> val argumentExpression = valueArgument.getArgumentExpression() ?: return@applicabilityRange null TextRange(valueArgument.startOffset, argumentExpression.startOffset).relativeTo(valueArgument) } override fun getInputProvider(): KotlinApplicatorInputProvider<KtValueArgument, RemoveArgumentNamesApplicators.SingleArgumentInput> = inputProvider { computeInput(it) } private fun KtAnalysisSession.computeInput(valueArgument: KtValueArgument): RemoveArgumentNamesApplicators.SingleArgumentInput? { val callElement = valueArgument.getStrictParentOfType<KtCallElement>() ?: return null val (sortedArguments, vararg, varargIsArrayOfCall) = collectSortedArgumentsThatCanBeUnnamed(callElement) ?: return null if (valueArgument !in sortedArguments) return null val allArguments = callElement.valueArgumentList?.arguments ?: return null val sortedArgumentsBeforeCurrent = sortedArguments.takeWhile { it != valueArgument } val supportsMixed = valueArgument.languageVersionSettings.supportsFeature(LanguageFeature.MixedNamedArgumentsInTheirOwnPosition) val nameCannotBeRemoved = if (supportsMixed) { sortedArgumentsBeforeCurrent.withIndex().any { (parameterIndex, argument) -> parameterIndex != allArguments.indexOf(argument) } } else { sortedArgumentsBeforeCurrent.any { it.isNamed() } } if (nameCannotBeRemoved) return null return RemoveArgumentNamesApplicators.SingleArgumentInput( anchorArgument = sortedArgumentsBeforeCurrent.lastOrNull(), isVararg = valueArgument == vararg, isArrayOfCall = valueArgument == vararg && varargIsArrayOfCall ) } } private data class ArgumentsData(val arguments: List<KtValueArgument>, val vararg: KtValueArgument?, val varargIsArrayOfCall: Boolean) /** * Returns arguments that are not named or can be unnamed, placed on their correct positions. * No arguments following vararg argument are returned. */ private fun KtAnalysisSession.collectSortedArgumentsThatCanBeUnnamed(callElement: KtCallElement): ArgumentsData? { val resolvedCall = callElement.resolveCall().singleFunctionCallOrNull() ?: return null val valueArguments = callElement.valueArgumentList?.arguments ?: return null val argumentToParameterIndex = CallParameterInfoProvider.mapArgumentsToParameterIndices( callElement, resolvedCall.partiallyAppliedSymbol.signature, resolvedCall.argumentMapping ) val argumentsOnCorrectPositions = valueArguments .sortedBy { argumentToParameterIndex[it.getArgumentExpression()] ?: Int.MAX_VALUE } .filterIndexed { index, argument -> index == argumentToParameterIndex[argument.getArgumentExpression()] } val vararg = argumentsOnCorrectPositions.firstOrNull { resolvedCall.argumentMapping[it.getArgumentExpression()]?.symbol?.isVararg == true } val varargIsArrayOfCall = (vararg?.getArgumentExpression() as? KtCallElement)?.let { isArrayOfCall(it) } == true val argumentsThatCanBeUnnamed = if (vararg != null) { val varargIndex = valueArguments.indexOf(vararg) // if an argument is vararg, it can only be unnamed if all arguments following it are named val takeVararg = valueArguments.drop(varargIndex + 1).all { it.isNamed() } argumentsOnCorrectPositions.take(if (takeVararg) varargIndex + 1 else varargIndex) } else { argumentsOnCorrectPositions } return ArgumentsData(argumentsThatCanBeUnnamed, vararg, varargIsArrayOfCall) }
apache-2.0
40bec43cd21dc17f49f4490647d87c57
57.252336
158
0.787869
5.515044
false
false
false
false
Atsky/haskell-idea-plugin
plugin/src/org/jetbrains/grammar/analysis/Main.kt
1
1786
package org.jetbrains.grammar.analysis import org.jetbrains.grammar.HaskellParser import org.jetbrains.grammar.dumb.Rule import java.util.HashSet import com.intellij.psi.tree.IElementType import org.jetbrains.grammar.dumb.Term import org.jetbrains.grammar.dumb.Variant import java.util.HashMap import java.util.ArrayList import org.jetbrains.grammar.dumb.NonTerminal import org.jetbrains.grammar.dumb.Terminal /** * Created by atsky on 11/20/14. */ fun main(args: Array<String>) { val grammar = HaskellParser(null).getGrammar() for ((name, rule) in grammar) { rule.makeAnalysis(grammar) println("rule ${name} {") println(" can be empty: " + rule.canBeEmpty) println(" first: " + rule.first) println("}") } } /* fun hasConflict(rule: Rule, variants: List<Variant>, index: Int): Boolean { var conflict = false; val terms = HashMap<Term, MutableList<Variant>>() for (variant in variants) { if (variant.terms.size == 0) { continue } val term = variant.terms[index] if (!terms.containsKey(term)) { terms[term] = ArrayList<Variant>() } terms[term].add(variant) } val allFirst = HashSet<List<IElementType>>() for ((term, variants) in terms) { val firsts = HashSet<List<IElementType>>() for (variant in variants) { firsts.addAll(variant.first!!) } for (f in firsts) { if (allFirst.contains(f)) { println("conflict: ${rule.name} - '${f}'") conflict = true } } allFirst.addAll(firsts) } return conflict } fun hasConflicts(rule: Rule): Boolean { return hasConflict(rule, rule.variants, 0) } */
apache-2.0
d7a264ae7a8d8c3ff412b2f57ea16b53
24.528571
75
0.611982
3.899563
false
false
false
false
JetBrains/intellij-community
plugins/kotlin/j2k/new/src/org/jetbrains/kotlin/nj2k/symbols/JKFieldSymbol.kt
1
2239
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.nj2k.symbols import com.intellij.psi.PsiVariable import org.jetbrains.kotlin.j2k.ast.Nullability.NotNull import org.jetbrains.kotlin.nj2k.tree.JKVariable import org.jetbrains.kotlin.nj2k.types.JKClassType import org.jetbrains.kotlin.nj2k.types.JKType import org.jetbrains.kotlin.nj2k.types.JKTypeFactory import org.jetbrains.kotlin.nj2k.types.toJK import org.jetbrains.kotlin.psi.KtCallableDeclaration import org.jetbrains.kotlin.psi.KtEnumEntry import org.jetbrains.kotlin.psi.psiUtil.containingClass sealed class JKFieldSymbol : JKSymbol { abstract val fieldType: JKType? } class JKUniverseFieldSymbol(override val typeFactory: JKTypeFactory) : JKFieldSymbol(), JKUniverseSymbol<JKVariable> { override val fieldType: JKType get() = target.type.type override lateinit var target: JKVariable } class JKMultiverseFieldSymbol( override val target: PsiVariable, override val typeFactory: JKTypeFactory ) : JKFieldSymbol(), JKMultiverseSymbol<PsiVariable> { override val fieldType: JKType get() = typeFactory.fromPsiType(target.type) } class JKMultiversePropertySymbol( override val target: KtCallableDeclaration, override val typeFactory: JKTypeFactory ) : JKFieldSymbol(), JKMultiverseKtSymbol<KtCallableDeclaration> { override val fieldType: JKType? get() = target.typeReference?.toJK(typeFactory) } class JKMultiverseKtEnumEntrySymbol( override val target: KtEnumEntry, override val typeFactory: JKTypeFactory ) : JKFieldSymbol(), JKMultiverseKtSymbol<KtEnumEntry> { override val fieldType: JKType? get() = target.containingClass()?.let { klass -> JKClassType( symbolProvider.provideDirectSymbol(klass) as? JKClassSymbol ?: return@let null, nullability = NotNull ) } } class JKUnresolvedField( override val target: String, override val typeFactory: JKTypeFactory ) : JKFieldSymbol(), JKUnresolvedSymbol { override val fieldType: JKType get() = typeFactory.types.nullableAny }
apache-2.0
c19e618caf4d3f0ffa0ea7ac32c359b6
33.984375
158
0.756141
4.424901
false
false
false
false
Homes-MinecraftServerMod/Homes
src/main/kotlin/com/masahirosaito/spigot/homes/strings/commands/ListCommandStrings.kt
1
3072
package com.masahirosaito.spigot.homes.strings.commands import com.masahirosaito.spigot.homes.Configs import com.masahirosaito.spigot.homes.PlayerDataManager import com.masahirosaito.spigot.homes.datas.PlayerData import com.masahirosaito.spigot.homes.datas.strings.commands.ListCommandStringData import com.masahirosaito.spigot.homes.exceptions.NoHomeException import com.masahirosaito.spigot.homes.load import com.masahirosaito.spigot.homes.loadData import com.masahirosaito.spigot.homes.nms.HomesEntity import java.io.File object ListCommandStrings { lateinit private var data: ListCommandStringData fun load(folderPath: String) { data = loadData(File(folderPath, "list-command.json").load(), ListCommandStringData::class.java) } fun DESCRIPTION_PLAYER_COMMAND() = data.DESCRIPTION_PLAYER_COMMAND fun DESCRIPTION_CONSOLE_COMMAND() = data.DESCRIPTION_CONSOLE_COMMAND fun USAGE_CONSOLE_COMMAND_LIST() = data.USAGE_CONSOLE_COMMAND_LIST fun USAGE_PLAYER_COMMAND_LIST() = data.USAGE_PLAYER_COMMAND_LIST fun USAGE_LIST_PLAYER() = data.USAGE_LIST_PLAYER fun PLAYER_LIST() = buildString { append("Player List") PlayerDataManager.getPlayerDataList().forEach { (offlinePlayer, defaultHome, namedHomes) -> append("\n &d${offlinePlayer.name}&r : ") if (defaultHome != null) append("default, ") append("named(&b${namedHomes.size}&r)") } } fun HOME_LIST(playerData: PlayerData, isPlayerHomeList: Boolean) = buildString { val offlinePlayer = playerData.offlinePlayer val defaultHome = playerData.defaultHome val namedHomes = playerData.namedHomes if (defaultHome == null && namedHomes.isEmpty()) { throw NoHomeException(offlinePlayer) } if (isPlayerHomeList .and(defaultHome != null && defaultHome.isPrivate) .and(namedHomes.all { it.isPrivate })) { throw NoHomeException(offlinePlayer) } append("${offlinePlayer.name}'s Home List") defaultHome?.let { if (!isPlayerHomeList || !it.isPrivate) { append("\n [&6Default&r] ${getText(it)}") } } if (Configs.onNamedHome) { namedHomes.filter { !isPlayerHomeList || !it.isPrivate }.apply { if (isNotEmpty()) { append("\n [&6Named Home&r]\n") this.forEach { append(" &d${it.homeName}&r") append(" : ${getText(it)}\n") } } } } } private fun getText(homesEntity: HomesEntity): String { val loc = homesEntity.location return buildString { append("&a${loc.world.name}&r, ") append("{&b${loc.x.toInt()}&r, &b${loc.y.toInt()}&r, &b${loc.z.toInt()}&r}, ") append(if (homesEntity.isPrivate) "&ePRIVATE&r" else "&9PUBLIC&r") } } }
apache-2.0
f5ccbb5fe119e97ee283a572bcd53943
33.909091
104
0.608724
4.237241
false
false
false
false
allotria/intellij-community
java/java-impl/src/com/intellij/refactoring/extractMethod/newImpl/inplace/CodeFragmentPopup.kt
3
2657
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.refactoring.extractMethod.newImpl.inplace import com.intellij.codeInsight.hint.EditorFragmentComponent import com.intellij.openapi.Disposable import com.intellij.openapi.editor.Editor import com.intellij.openapi.ui.popup.JBPopup import com.intellij.openapi.ui.popup.JBPopupFactory import com.intellij.ui.popup.PopupComponent import java.awt.GridBagLayout import java.awt.Window import java.awt.event.MouseAdapter import java.awt.event.MouseEvent import javax.swing.JPanel import java.awt.GridBagConstraints class CodeFragmentPopup(val editor: Editor, val lines: IntRange, private val onClick: Runnable): Disposable { private val fillConstraints = GridBagConstraints().apply { fill = GridBagConstraints.BOTH weightx = 1.0 weighty = 1.0 gridx = 0 gridy = 0 } private val content = JPanel(GridBagLayout()).apply { add(createEditorFragment(editor, lines), fillConstraints) addMouseListener(object : MouseAdapter() { override fun mouseClicked(e: MouseEvent) { onClick.run() } }) } private val popupWrapper = PopupComponent.DialogPopupWrapper(editor.component, content, 0, 0, createFragmentPopup(content)) private fun createFragmentPopup(content: JPanel): JBPopup { return JBPopupFactory.getInstance().createComponentPopupBuilder(content, null) .setCancelOnClickOutside(false) .setRequestFocus(false) .setFocusable(false) .setMovable(false) .setResizable(false) .setShowBorder(false) .setCancelKeyEnabled(false) .setCancelOnWindowDeactivation(false) .setCancelOnOtherWindowOpen(false) .createPopup() } private fun createEditorFragment(editor: Editor, lines: IntRange): EditorFragmentComponent { return EditorFragmentComponent.createEditorFragmentComponent(editor, lines.first, lines.last + 1, true, true) } fun updateCodePreview() { if (lines.last > editor.document.lineCount) return val editorFragmentComponent = createEditorFragment(editor, lines) content.removeAll() content.add(editorFragmentComponent, fillConstraints) window.preferredSize = editorFragmentComponent.preferredSize window.validate() } fun show() { if (! window.isVisible) { popupWrapper.setRequestFocus(false) popupWrapper.show() } } fun hide() { popupWrapper.hide(false) } override fun dispose() { popupWrapper.hide(true) popupWrapper.window.dispose() } val window: Window get() = popupWrapper.window }
apache-2.0
f7e6b0c5ca65988fb27995c6da4b03bb
31.024096
140
0.745954
4.518707
false
false
false
false
allotria/intellij-community
platform/platform-impl/src/com/intellij/ide/plugins/marketplace/PluginSignatureChecker.kt
1
3946
// 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.ide.plugins.marketplace import com.intellij.ide.IdeBundle import com.intellij.ide.plugins.certificates.PluginCertificateStore import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.ModalityState import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.ui.Messages import org.jetbrains.annotations.ApiStatus import org.jetbrains.zip.signer.verifier.InvalidSignatureResult import org.jetbrains.zip.signer.verifier.MissingSignatureResult import org.jetbrains.zip.signer.verifier.SuccessfulVerificationResult import org.jetbrains.zip.signer.verifier.ZipVerifier import java.io.File import java.security.cert.Certificate import java.security.cert.CertificateFactory @ApiStatus.Internal internal object PluginSignatureChecker { private val LOG = logger<PluginSignatureChecker>() private val jetbrainsCertificate: Certificate? by lazy { val cert = PluginSignatureChecker.javaClass.classLoader.getResourceAsStream("ca.crt") if (cert == null) { LOG.warn(IdeBundle.message("jetbrains.certificate.not.found")) null } else { CertificateFactory.getInstance("X.509").generateCertificate(cert) } } @JvmStatic fun isSignedByAnyCertificates(pluginName: String, pluginFile: File): Boolean { val jbCert = jetbrainsCertificate ?: return processSignatureWarning(pluginName, IdeBundle.message("jetbrains.certificate.not.found")) val certificates = PluginCertificateStore.getInstance().customTrustManager.certificates.orEmpty() + jbCert return isSignedBy(pluginName, pluginFile, *certificates.toTypedArray()) } @JvmStatic fun isSignedByCustomCertificates(pluginName: String, pluginFile: File): Boolean { val certificates = PluginCertificateStore.getInstance().customTrustManager.certificates if (certificates.isEmpty()) return true return isSignedBy(pluginName, pluginFile, *certificates.toTypedArray()) } @JvmStatic fun isSignedByJetBrains(pluginName: String, pluginFile: File): Boolean { val jbCert = jetbrainsCertificate ?: return processSignatureWarning(pluginName, IdeBundle.message("jetbrains.certificate.not.found")) return isSignedBy(pluginName, pluginFile, jbCert) } private fun isSignedBy(pluginName: String, pluginFile: File, vararg certificate: Certificate): Boolean { val errorMessage = verifyPluginAndGetErrorMessage(pluginFile, *certificate) if (errorMessage != null) { return processSignatureWarning(pluginName, errorMessage) } return true } private fun verifyPluginAndGetErrorMessage(file: File, vararg certificates: Certificate): String? { return when (val verificationResult = ZipVerifier.verify(file)) { is InvalidSignatureResult -> verificationResult.errorMessage is MissingSignatureResult -> IdeBundle.message("plugin.signature.not.signed") is SuccessfulVerificationResult -> { val isSigned = certificates.any { certificate -> verificationResult.isSignedBy(certificate) } if (!isSigned) { IdeBundle.message("plugin.signature.not.signed.by") } else null } } } private fun processSignatureWarning(pluginName: String, errorMessage: String): Boolean { val title = IdeBundle.message("plugin.signature.checker.title") val message = IdeBundle.message("plugin.signature.checker.untrusted.message", pluginName, errorMessage) val yesText = IdeBundle.message("plugin.signature.checker.yes") val noText = IdeBundle.message("plugin.signature.checker.no") var result: Int = -1 ApplicationManager.getApplication().invokeAndWait( { result = Messages.showYesNoDialog(message, title, yesText, noText, Messages.getWarningIcon()) }, ModalityState.any() ) return result == Messages.YES } }
apache-2.0
414b70b7f993102973a4b051b3b8ae5e
43.348315
140
0.770147
4.636898
false
false
false
false
JetBrains/teamcity-dnx-plugin
plugin-dotnet-agent/src/main/kotlin/jetbrains/buildServer/agent/runner/LoggerServiceImpl.kt
1
3130
package jetbrains.buildServer.agent.runner import jetbrains.buildServer.BuildProblemData import jetbrains.buildServer.agent.BuildProgressLogger import jetbrains.buildServer.messages.DefaultMessagesInfo import jetbrains.buildServer.messages.serviceMessages.BlockClosed import jetbrains.buildServer.messages.serviceMessages.BlockOpened import jetbrains.buildServer.messages.serviceMessages.ServiceMessage import jetbrains.buildServer.rx.Disposable import jetbrains.buildServer.rx.disposableOf class LoggerServiceImpl( private val _buildStepContext: BuildStepContext, private val _colorTheme: ColorTheme) : LoggerService { private val listener: LoggingProcessListener get() = LoggingProcessListener(_buildLogger) private val _buildLogger: BuildProgressLogger get() = _buildStepContext.runnerContext.build.buildLogger override fun writeMessage(serviceMessage: ServiceMessage) = _buildLogger.message(serviceMessage.toString()) override fun writeBuildProblem(identity: String, type: String, description: String) = _buildLogger.logBuildProblem(BuildProblemData.createBuildProblem(identity.substring(0 .. Integer.min(identity.length, 60) - 1), type, description)) override fun writeStandardOutput(text: String, color: Color) = listener.onStandardOutput(applyColor(text, color)) override fun writeStandardOutput(vararg text: StdOutText) = listener.onStandardOutput(applyColor(*text)) override fun writeErrorOutput(text: String) = _buildLogger.error(text) override fun writeWarning(text: String) = _buildLogger.warning(text) override fun writeBlock(blockName: String, description: String) = writeBlock(blockName, description, false) override fun writeTrace(text: String) = _buildLogger.logMessage(DefaultMessagesInfo.internalize(DefaultMessagesInfo.createTextMessage(text))) override fun writeTraceBlock(blockName: String, description: String) = writeBlock(blockName, description, true) private fun writeBlock(blockName: String, description: String, trace: Boolean): Disposable { val blockOpened = BlockOpened(blockName, if (description.isBlank()) null else description) if (trace) { blockOpened.addTag(DefaultMessagesInfo.TAG_INTERNAL) } _buildLogger.message(blockOpened.toString()) return disposableOf { _buildLogger.message(BlockClosed(blockName).toString()) } } private fun applyColor(text: String, color: Color, prevColor: Color = Color.Default): String = if (color == prevColor) { text } else { if (color == Color.Default) { "\u001B[0m$text" } else { "\u001B[${_colorTheme.getAnsiColor(color)}m$text" } } private fun applyColor(vararg text: StdOutText): String = text.fold(DefaultStdOutText) { acc, (text, color) -> StdOutText(acc.text + applyColor(text, color, acc.color), color) }.text companion object { private val DefaultStdOutText = StdOutText("") } }
apache-2.0
325f82b0c4e6b7fc5b8bbbaa539dbb65
41.310811
159
0.717891
4.582723
false
false
false
false
F43nd1r/acra-backend
acrarium/src/main/kotlin/com/faendir/acra/ui/component/dialog/AcrariumDialog.kt
1
2925
package com.faendir.acra.ui.component.dialog import com.faendir.acra.i18n.Messages import com.faendir.acra.ui.component.Translatable import com.faendir.acra.ui.ext.content import com.vaadin.flow.component.ClickEvent import com.vaadin.flow.component.Component import com.vaadin.flow.component.Composite import com.vaadin.flow.component.HasComponents import com.vaadin.flow.component.button.Button import com.vaadin.flow.component.button.ButtonVariant import com.vaadin.flow.component.dialog.Dialog import com.vaadin.flow.dom.Element open class AcrariumDialog : Composite<Dialog>(), HasComponents { private val dialogContent: DialogContent = DialogContent() init { content.add(dialogContent) } var isOpened: Boolean get() = content.isOpened set(value) { content.isOpened = value } fun open() { content.open() } fun close() { content.close() } fun header(captionId: String, vararg params: Any) { dialogContent.add(DialogContent.Slot.HEADER, Translatable.createH3(captionId, *params)) } fun positiveAction(captionId: String, vararg params: Any, clickListener: (ClickEvent<Button>) -> Unit = {}) { dialogContent.add(DialogContent.Slot.POSITIVE, Translatable.createButton(captionId, *params) { close() clickListener(it) }) } val positive: Translatable<Button>? get() = dialogContent.get(DialogContent.Slot.POSITIVE) .filterIsInstance<Translatable<Button>>() .firstOrNull() fun negativeAction(captionId: String, vararg params: Any, clickListener: (ClickEvent<Button>) -> Unit = {}) { dialogContent.add(DialogContent.Slot.NEGATIVE, Translatable.createButton(captionId, *params, theme = ButtonVariant.LUMO_TERTIARY) { close() clickListener(it) }) } override fun add(vararg components: Component?) { dialogContent.add(*components) } override fun add(text: String?) { dialogContent.add(text) } override fun remove(vararg components: Component?) { dialogContent.remove(*components) } override fun removeAll() { dialogContent.removeAll() } override fun addComponentAtIndex(index: Int, component: Component?) { dialogContent.addComponentAtIndex(index, component) } override fun addComponentAsFirst(component: Component?) { dialogContent.addComponentAsFirst(component) } } fun AcrariumDialog.createButton(onCreateAction: AcrariumDialog.() -> Unit) { positiveAction(Messages.CREATE) { onCreateAction() } negativeAction(Messages.CANCEL) } fun AcrariumDialog.closeButton() { positiveAction(Messages.CLOSE) } fun AcrariumDialog.confirmButtons(onYesAction: AcrariumDialog.() -> Unit) { positiveAction(Messages.CONFIRM) { onYesAction() } negativeAction(Messages.CANCEL) }
apache-2.0
5f2c1ff242dcd6e3229f698d91d9ad20
29.479167
139
0.694359
4.190544
false
false
false
false
JuliusKunze/kotlin-native
backend.native/tests/external/codegen/box/reflection/mapping/extensionProperty.kt
2
838
// TODO: muted automatically, investigate should it be ran for JS or not // IGNORE_BACKEND: JS, NATIVE // WITH_REFLECT import kotlin.reflect.jvm.* import kotlin.test.assertEquals class K(var value: Long) var K.ext: Double get() = value.toDouble() set(value) { this.value = value.toLong() } fun box(): String { val p = K::ext val getter = p.javaGetter!! val setter = p.javaSetter!! assertEquals(getter, Class.forName("ExtensionPropertyKt").getMethod("getExt", K::class.java)) assertEquals(setter, Class.forName("ExtensionPropertyKt").getMethod("setExt", K::class.java, Double::class.java)) val k = K(42L) assert(getter.invoke(null, k) == 42.0) { "Fail k getter" } setter.invoke(null, k, -239.0) assert(getter.invoke(null, k) == -239.0) { "Fail k setter" } return "OK" }
apache-2.0
c3f602b4b982451f628c666924d44889
25.1875
117
0.653938
3.325397
false
false
false
false
JuliusKunze/kotlin-native
backend.native/tests/external/codegen/box/bridges/methodFromTrait.kt
5
317
interface A<T, U> { fun foo(t: T, u: U) = "A" } class Z<T> : A<T, Int> { override fun foo(t: T, u: Int) = "Z" } fun box(): String { val z = Z<Int>() val a: A<Int, Int> = z return when { z.foo(0, 0) != "Z" -> "Fail #1" a.foo(0, 0) != "Z" -> "Fail #2" else -> "OK" } }
apache-2.0
485efedb9ea5c14f25dad8ede1038331
17.647059
40
0.403785
2.264286
false
false
false
false
JuliusKunze/kotlin-native
backend.native/tests/external/codegen/box/classes/kt2485.kt
5
186
fun f1(a : Any?) {} fun f2(a : Boolean?) {} fun f3(a : Any) {} fun f4(a : Boolean) {} fun box() : String { f1(1 == 1) f2(1 == 1) f3(1 == 1) f4(1 == 1) return "OK" }
apache-2.0
764c54f64a338dba3a7ecfa47516df59
14.5
23
0.430108
2.137931
false
false
false
false
Flank/flank
flank-scripts/src/main/kotlin/flank/scripts/ops/common/GenerateChangeLog.kt
1
3181
package flank.scripts.ops.common import com.github.kittinunf.result.Result import com.github.kittinunf.result.getOrElse import com.github.kittinunf.result.map import flank.scripts.data.github.getLatestReleaseTag import flank.scripts.data.github.getPrDetailsByCommit import flank.scripts.data.github.objects.GithubPullRequest import flank.scripts.data.github.objects.GithubUser import flank.scripts.utils.markdownLink import flank.scripts.utils.runCommand import kotlinx.coroutines.async import kotlinx.coroutines.awaitAll import kotlinx.coroutines.runBlocking import java.io.File fun generateReleaseNotes(githubToken: String) = runBlocking { generateReleaseNotes( latestReleaseTag = getLatestReleaseTag(githubToken).map { it.tag }.getOrElse { "" }, githubToken = githubToken ) } fun generateReleaseNotes( latestReleaseTag: String, githubToken: String ) = getCommitsSha(latestReleaseTag).getNewReleaseNotes(githubToken) internal fun getCommitsSha(fromTag: String): List<String> { val outputFile = File.createTempFile("sha", ".log") "git log --pretty=%H $fromTag..HEAD".runCommand(fileForOutput = outputFile) return outputFile.readLines() } private fun List<String>.getNewReleaseNotes(githubToken: String) = runBlocking { map { sha -> async { getPrDetailsByCommit(sha, githubToken) } } .awaitAll() .filterIsInstance<Result.Success<List<GithubPullRequest>>>() .mapNotNull { it.value.firstOrNull()?.toReleaseNoteMessage() } .fold(mutableMapOf<String, MutableList<String>>()) { grouped, pr -> grouped.apply { val (type, message) = pr appendToType(type, message) } } } private fun MutableMap<String, MutableList<String>>.appendToType( type: String, message: String ) = apply { (getOrPut(type) { mutableListOf() }).add(message) } private fun GithubPullRequest.toReleaseNoteMessage() = title.mapPrTitleWithType()?.let { (type, title) -> type to "- ${markdownLink("#$number", htmlUrl)} $title ${assignees.format()}" } internal fun String.mapPrTitleWithType() = when { startsWith("feat") -> "Features" to skipConventionalCommitPrefix().replaceFirstChar { it.uppercase() } startsWith("fix") -> "Bug Fixes" to skipConventionalCommitPrefix().replaceFirstChar { it.uppercase() } startsWith("docs") -> "Documentation" to skipConventionalCommitPrefix().replaceFirstChar { it.uppercase() } startsWith("refactor") -> "Refactor" to skipConventionalCommitPrefix().replaceFirstChar { it.uppercase() } startsWith("ci") -> "CI Changes" to skipConventionalCommitPrefix().replaceFirstChar { it.uppercase() } startsWith("test") -> "Tests update" to skipConventionalCommitPrefix().replaceFirstChar { it.uppercase() } startsWith("perf") -> "Performance upgrade" to skipConventionalCommitPrefix().replaceFirstChar { it.uppercase() } else -> null // we do not accept other prefix to have update in release notes } private fun String.skipConventionalCommitPrefix() = substring(indexOf(':') + 2) private fun List<GithubUser>.format() = "(${joinToString { (login, url) -> markdownLink(login, url) }})"
apache-2.0
91fd32edd928b8dbbddb4ca39bc820aa
42.575342
117
0.727759
4.3397
false
true
false
false
remkop/picocli
picocli-examples/src/main/kotlin/picocli/examples/kotlin/Checksum.kt
1
1676
package picocli.examples.kotlin import picocli.CommandLine import picocli.CommandLine.HelpCommand import picocli.CommandLine.Command import picocli.CommandLine.Option import picocli.CommandLine.Parameters import java.util.ArrayList import java.io.File import java.math.BigInteger import java.nio.file.Files import java.security.MessageDigest import java.util.concurrent.Callable import kotlin.system.exitProcess @Command(name = "checksum", mixinStandardHelpOptions = true, subcommands = [ HelpCommand::class ], version = ["checksum 4.1.4"], description = ["Prints the checksum (SHA-1 by default) of file(s) to STDOUT."]) class Checksum : Callable<Int> { @Parameters(index = "0..*", description = ["The file(s) whose checksum to calculate."], arity = "1..*", paramLabel = "<file 1> <file 2>") val files: ArrayList<File> = arrayListOf() @Option(names = ["-a", "--algorithm"], description = ["MD5, SHA-1, SHA-256, ..."]) var algorithm = "SHA-1" override fun call(): Int { for (file in files) { val fileContents = Files.readAllBytes(file.toPath()) val digest = MessageDigest.getInstance(algorithm).digest(fileContents) println(("%s: %0" + digest.size * 2 + "x").format(file.name, BigInteger(1, digest))) } return 0 } companion object { @JvmStatic fun main(args: Array<String>) { CommandLine(Checksum()).execute(*args) } } } // NOTE: below is an alternative to defining a @JvmStatic main function in a companion object: // fun main(args: Array<String>) : Unit = exitProcess(CommandLine(Checksum()).execute(*args))
apache-2.0
63d4d166ce72db21626ba881fb0e0e18
35.434783
96
0.667661
4.138272
false
false
false
false
kohesive/kohesive-iac
aws-examples/lambdas/src/main/kotlin/uy/kohesive/iac/examples/aws/lambdas/S3TriggeredEventProcessDigestToSes.kt
1
6963
package uy.kohesive.iac.examples.aws.lambdas import com.amazonaws.auth.EnvironmentVariableCredentialsProvider import com.amazonaws.auth.profile.ProfileCredentialsProvider import com.amazonaws.services.lambda.runtime.Context import com.amazonaws.services.lambda.runtime.RequestHandler import com.amazonaws.services.lambda.runtime.events.S3Event import com.amazonaws.services.s3.AmazonS3Client import com.amazonaws.services.s3.model.GetObjectRequest import com.amazonaws.services.simpleemail.AmazonSimpleEmailServiceClient import com.fasterxml.jackson.annotation.JsonIgnore import com.fasterxml.jackson.annotation.JsonProperty import com.fasterxml.jackson.core.type.TypeReference import com.fasterxml.jackson.databind.ObjectMapper import nl.komponents.kovenant.all import nl.komponents.kovenant.task import nl.komponents.kovenant.then import org.apache.commons.csv.CSVFormat import org.apache.commons.csv.CSVParser import uy.klutter.core.collections.lazyBatch import java.io.File import java.time.Instant import java.time.ZoneOffset import java.time.format.DateTimeFormatter import java.util.* // TODO: have this push to SQS queue, which then sends each person. Too high of chance of failures here processing within the Lambda class S3TriggeredEventProcessDigestToSes(val overrideCredentialsProviderWithProfile: String? = null, val overrideSesAwsRegion: String? = null, val overrideAthenaAwsRegion: String? = null, val overrideSenderEmail: String? = null) : RequestHandler<S3Event, Unit> { companion object { val ENV_SETTING_SES_REGION = "SES_AWS_REGION" val ENV_SETTING_ATHENA_REGION = "ATHENA_AWS_REGION" val ENV_SETTING_SENDER_EMAIL = "SENDER_EMAIL" val templateBaseName = "social-notifications-digest" val templateLanguage = "en" // TODO: from each user's settings val JSON = ObjectMapper() val sesService = SesTemplatedEmailService() } val sesAwsRegion = overrideSesAwsRegion ?: System.getenv(ENV_SETTING_SES_REGION) ?: throw IllegalStateException("Missing environment variable ${ENV_SETTING_SES_REGION} defining the SES region for sending email") val athenaAwsRegion = overrideAthenaAwsRegion ?: System.getenv(ENV_SETTING_ATHENA_REGION) ?: throw IllegalStateException("Missing environment variable ${ENV_SETTING_ATHENA_REGION} defining the Athena region") val awsCredentials = overrideCredentialsProviderWithProfile?.let { ProfileCredentialsProvider(it) } ?: EnvironmentVariableCredentialsProvider() val senderEmail = overrideSenderEmail ?: System.getenv(ENV_SETTING_SENDER_EMAIL) ?: throw IllegalStateException("Missing environment variable ${ENV_SETTING_SENDER_EMAIL} defining the sender email") val sesClient = AmazonSimpleEmailServiceClient.builder().apply { credentials = awsCredentials region = sesAwsRegion }.build() val s3Client = AmazonS3Client.builder().apply { credentials = awsCredentials region = athenaAwsRegion }.build() override fun handleRequest(input: S3Event, context: Context) { input.records.forEach { event -> val s3Bucket = event.s3.bucket.name val objKey = event.s3.`object`.key processOneS3File(s3Bucket, objKey) } } fun processOneS3File(s3Bucket: String, objKey: String) { var lastSuccessfulLine = 0 // in case of failure, we need to know try { // always download S3 objects fast, never put anything in the way val tempFile = File.createTempFile("social-digest-${UUID.randomUUID()}-", ".csv").apply { deleteOnExit() } try { // TODO: add retry, sometimes S3 has temporary problems s3Client.getObject(GetObjectRequest(s3Bucket, objKey), tempFile) // file is one of: // "eventHour","email","name","eventCount","_col4" // "eventHour","email","name","eventCount","events" CSVParser.parse(tempFile, Charsets.UTF_8, CSVFormat.DEFAULT).use { parser -> val eventEmailField = 0 val eventNameField = 1 val eventEventCountField = 2 val eventEventsField = 3 parser.asSequence().drop(1).map { record -> val events = JSON.readValue<List<SocialEvent>>(record[eventEventsField], object : TypeReference<List<SocialEvent>>() {}) EmailModel(email = record[eventEmailField], name = record[eventNameField], events = events.sortedBy { it.eventTime }) }.lazyBatch(10) { batch -> val sendTasks = batch.map { item -> task { // TODO: configure send Name, subject line /* sesService.sendEmail(sesClient, item.name, item.email, "Xyz", senderEmail, "Hi ${item.name}, your friends are active on Xyz", "$templateBaseName.$templateLanguage", item) */ } }.toList() all(sendTasks, cancelOthersOnError = false).then { // noop, all emails sent! }.fail { // TODO: on error, we need to put the file and lastSuccessfulLine into SQS queue to try continuing from there later // we don't want a retry causing this to send duplicate emails }.get() // force wait } } } finally { tempFile.delete() } } catch (ex: Exception) { // TODO: on error, we need to put the file and lastSuccessfulLine into SQS queue to try continuing from there later // we don't want a retry causing this to send duplicate emails throw ex } } class EmailModel(val email: String, val name: String, val events: List<SocialEvent>) class SocialEvent() { lateinit @get:JsonProperty("eventTime") var eventTimeStr: String lateinit var message: String @get:JsonIgnore val eventTime: Instant get() = Instant.from(DateTimeFormatter.ISO_INSTANT.withZone(ZoneOffset.UTC).parse("${eventTimeStr}Z")) // TODO: this should be formatted according to the receiving user's local settings, not the servers @get:JsonIgnore val eventTimeFormatted: String get() = DateTimeFormatter.ofPattern("EEEE, hh:mm").withZone(ZoneOffset.UTC).format(eventTime) } }
mit
065398f4353aace9dceacd5522613650
47.692308
149
0.623869
4.838777
false
false
false
false
serssp/reakt
todo/src/main/kotlin/todo/components/Footer.kt
3
1336
package todo.components import com.github.andrewoma.react.* import todo.actions.TodoActions import todo.stores.Todo import todo.stores.completedCount data class FooterProperties(val todos: Collection<Todo>) class Footer : ComponentSpec<FooterProperties, Unit>() { companion object { val factory = react.createFactory(Footer()) } override fun Component.render() { log.debug("Footer.render", props) if (props.todos.isEmpty()) return val completed = props.todos.completedCount() val itemsLeft = props.todos.size - completed val itemsLeftPhrase = (if (itemsLeft == 1) " item " else " items ") + "left" footer({ id = "footer" }) { span({ id = "todo-count" }) { strong { text("$itemsLeft") }.text(itemsLeftPhrase) } if (completed != 0) { button({ id = "clear-completed" onClick = { onClearCompletedClick() } }) { text("Clear completed ($completed)") } } } } fun onClearCompletedClick() { TodoActions.destroyCompleted(null) } } fun Component.todoFooter(props: FooterProperties): Component { return constructAndInsert(Component({ Footer.factory(Ref(props)) })) }
mit
faa04abfc2f8f668dac8d60463a84fe1
28.043478
84
0.583084
4.483221
false
false
false
false
ingokegel/intellij-community
plugins/gradle/java/src/codeInspection/BintrayPublishingPluginInspection.kt
5
1962
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.plugins.gradle.codeInspection import com.intellij.codeInspection.ProblemHighlightType import com.intellij.codeInspection.ProblemsHolder import com.intellij.openapi.util.io.FileUtilRt import com.intellij.psi.PsiFile import org.jetbrains.plugins.gradle.util.GradleConstants import org.jetbrains.plugins.groovy.lang.psi.GroovyElementVisitor import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrCall import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.literals.GrLiteral class BintrayPublishingPluginInspection: GradleBaseInspection() { override fun buildGroovyVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): GroovyElementVisitor = object : GroovyElementVisitor() { override fun visitLiteralExpression(literal: GrLiteral) { val file: PsiFile = literal.containingFile if (!FileUtilRt.extensionEquals(file.name, GradleConstants.EXTENSION)) return super.visitLiteralExpression(literal) if (!literal.isString) return if ("com.jfrog.bintray" == literal.value) { if (isPluginDSL(literal) || isApplyPlugin(literal)) { holder.registerProblem(literal, GradleInspectionBundle.message("bintray.publishing.plugin"), ProblemHighlightType.WARNING) } } } private fun isApplyPlugin(literal: GrLiteral): Boolean { return (literal.parent?.parent?.parent as? GrCall)?.resolveMethod()?.let { "org.gradle.api.plugins.PluginAware" == it.containingClass?.qualifiedName && "apply" == it.name } ?: false } private fun isPluginDSL(literal: GrLiteral): Boolean { return (literal.parent?.parent as? GrCall)?.resolveMethod()?.let { "org.gradle.plugin.use.PluginDependenciesSpec" == it.containingClass?.qualifiedName && "id" == it.name } ?: false } } }
apache-2.0
56d481264655d5b57bddea2696ed3122
44.651163
138
0.745158
4.584112
false
false
false
false
Raizlabs/DBFlow
processor/src/main/kotlin/com/dbflow5/processor/definition/TypeConverterDefinition.kt
1
2052
package com.dbflow5.processor.definition import com.dbflow5.annotation.TypeConverter import com.dbflow5.processor.ClassNames import com.dbflow5.processor.ProcessorManager import com.squareup.javapoet.ClassName import com.squareup.javapoet.TypeName import javax.lang.model.type.DeclaredType import javax.lang.model.type.MirroredTypesException import javax.lang.model.type.TypeMirror /** * Description: Holds data about type converters in order to write them. */ class TypeConverterDefinition( typeConverter: TypeConverter?, val className: ClassName, typeMirror: TypeMirror, manager: ProcessorManager, val isDefaultConverter: Boolean) { val modelTypeName: TypeName? val dbTypeName: TypeName? val allowedSubTypes: List<TypeName> init { val allowedSubTypes: MutableList<TypeName> = mutableListOf() typeConverter?.let { converter -> try { converter.allowedSubtypes } catch (e: MirroredTypesException) { val types = e.typeMirrors types.forEach { allowedSubTypes.add(TypeName.get(it)) } } } this.allowedSubTypes = allowedSubTypes val types = manager.typeUtils var typeConverterSuper: DeclaredType? = null val typeConverterType = manager.typeUtils.getDeclaredType(manager.elements .getTypeElement(ClassNames.TYPE_CONVERTER.toString())) for (superType in types.directSupertypes(typeMirror)) { val erasure = types.erasure(superType) if (types.isAssignable(erasure, typeConverterType) || erasure.toString() == typeConverterType.toString()) { typeConverterSuper = superType as DeclaredType } } if (typeConverterSuper != null) { val typeArgs = typeConverterSuper.typeArguments dbTypeName = ClassName.get(typeArgs[0]) modelTypeName = ClassName.get(typeArgs[1]) } else { dbTypeName = null modelTypeName = null } } }
mit
af4645182efe3ea25604a46d641a81d2
33.2
119
0.673002
4.944578
false
false
false
false
code-helix/slatekit
src/lib/kotlin/slatekit-cache/src/main/kotlin/slatekit/cache/CacheCommand.kt
1
2443
package slatekit.cache import kotlinx.coroutines.CompletableDeferred import slatekit.results.Outcome /** * Cache commands are sent via channels to update/manage shared state ( cache values ) * @see * 1. https://kotlinlang.org/docs/reference/coroutines/shared-mutable-state-and-concurrency.html * 2. https://kotlinlang.org/docs/reference/coroutines/shared-mutable-state-and-concurrency.html#actors * */ sealed class CacheCommand { abstract val action: CacheAction class Exists(val key:String, val response: CompletableDeferred<Boolean>) : CacheCommand() { override val action = CacheAction.Exists } class Put(val key: String, val desc: String, val expiryInSeconds: Int, val fetcher: suspend () -> Any?, val response: CompletableDeferred<Boolean>) : CacheCommand() { override val action = CacheAction.Create } class Set(val key: String, val value: Any?, val response: CompletableDeferred<Boolean>) : CacheCommand() { override val action = CacheAction.Update } class Get(val key: String, val response: CompletableDeferred<Any?>, val load:Boolean = false) : CacheCommand() { override val action = CacheAction.Fetch } class GetFresh(val key: String, val response: CompletableDeferred<Any?>) : CacheCommand() { override val action = CacheAction.Fetch } class Refresh(val key: String, val response: CompletableDeferred<Outcome<Boolean>>) : CacheCommand() { override val action = CacheAction.Refresh } class Expire(val key: String, val response: CompletableDeferred<Outcome<Boolean>>) : CacheCommand() { override val action = CacheAction.Expire } class ExpireAll(val response: CompletableDeferred<Outcome<Boolean>>) : CacheCommand() { override val action = CacheAction.ExpireAll } class Delete(val key: String, val response: CompletableDeferred<Outcome<Boolean>>) : CacheCommand() { override val action = CacheAction.Delete } class DeleteAll(val response: CompletableDeferred<Outcome<Boolean>>) : CacheCommand() { override val action = CacheAction.DeleteAll } class SimpleStats(val response: CompletableDeferred<Pair<Int, List<String>>>) : CacheCommand() { override val action = CacheAction.Stats } class CompleteStats(val response: CompletableDeferred<List<CacheStats>>) : CacheCommand() { override val action = CacheAction.Stats } }
apache-2.0
214c191320a54e002cde32c7e8751cac
37.777778
170
0.712239
4.524074
false
false
false
false
jwren/intellij-community
platform/build-scripts/groovy/org/jetbrains/intellij/build/impl/JarPackager.kt
1
21999
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. @file:Suppress("ReplaceGetOrSet", "ReplacePutWithAssignment") package org.jetbrains.intellij.build.impl import com.intellij.openapi.util.io.FileUtil import com.intellij.util.PathUtilRt import com.intellij.util.io.URLUtil import io.opentelemetry.api.common.AttributeKey import io.opentelemetry.api.common.Attributes import io.opentelemetry.api.trace.Span import org.jetbrains.intellij.build.BuildContext import org.jetbrains.intellij.build.BuildOptions import org.jetbrains.intellij.build.impl.BaseLayout.Companion.APP_JAR import org.jetbrains.intellij.build.impl.projectStructureMapping.DistributionFileEntry import org.jetbrains.intellij.build.impl.projectStructureMapping.ModuleLibraryFileEntry import org.jetbrains.intellij.build.impl.projectStructureMapping.ModuleOutputEntry import org.jetbrains.intellij.build.impl.projectStructureMapping.ProjectLibraryEntry import org.jetbrains.intellij.build.tasks.Source import org.jetbrains.intellij.build.tasks.ZipSource import org.jetbrains.intellij.build.tasks.addModuleSources import org.jetbrains.intellij.build.tasks.buildJars import org.jetbrains.jps.model.java.JpsJavaClasspathKind import org.jetbrains.jps.model.java.JpsJavaExtensionService import org.jetbrains.jps.model.library.JpsLibrary import org.jetbrains.jps.model.library.JpsOrderRootType import org.jetbrains.jps.model.module.JpsLibraryDependency import org.jetbrains.jps.model.module.JpsModule import org.jetbrains.jps.model.module.JpsModuleReference import org.jetbrains.jps.util.JpsPathUtil import java.io.File import java.nio.file.Path import java.util.* import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.ConcurrentLinkedQueue @Suppress("ReplaceJavaStaticMethodWithKotlinAnalog") private val libsThatUsedInJps = java.util.Set.of( "ASM", "aalto-xml", "netty-buffer", "netty-codec-http", "netty-handler-proxy", "fastutil-min", "gson", "Log4J", "Slf4j", "slf4j-jdk14", // see getBuildProcessApplicationClasspath - used in JPS "lz4-java", "maven-resolver-provider", "OroMatcher", "jgoodies-forms", "jgoodies-common", "NanoXML", // see ArtifactRepositoryManager.getClassesFromDependencies "plexus-utils", "Guava", "http-client", "commons-codec", "commons-logging", "commons-lang3", "kotlin-stdlib-jdk8" ) class JarPackager private constructor(private val context: BuildContext) { private val jarDescriptors = LinkedHashMap<Path, JarDescriptor>() private val projectStructureMapping = ConcurrentLinkedQueue<DistributionFileEntry>() private val libToMetadata = HashMap<JpsLibrary, ProjectLibraryData>() companion object { private val extraMergeRules = LinkedHashMap<String, (String) -> Boolean>() init { extraMergeRules.put("groovy.jar") { it.startsWith("org.codehaus.groovy:") } extraMergeRules.put("jsch-agent.jar") { it.startsWith("jsch-agent") } // see ClassPathUtil.getUtilClassPath extraMergeRules.put("3rd-party-rt.jar") { libsThatUsedInJps.contains(it) || it.startsWith("kotlinx-") || it == "kotlin-reflect" } } @JvmStatic fun getLibraryName(lib: JpsLibrary): String { val name = lib.name if (!name.startsWith("#")) { return name } val roots = lib.getRoots(JpsOrderRootType.COMPILED) if (roots.size != 1) { throw IllegalStateException("Non-single entry module library $name: ${roots.joinToString { it.url }}") } return PathUtilRt.getFileName(roots.first().url.removeSuffix(URLUtil.JAR_SEPARATOR)) } @JvmStatic fun pack(actualModuleJars: Map<String, List<String>>, outputDir: Path, context: BuildContext) { pack(actualModuleJars = actualModuleJars, outputDir = outputDir, layout = object : BaseLayout() {}, moduleOutputPatcher = ModuleOutputPatcher(), dryRun = false, context = context) } @JvmStatic fun pack(actualModuleJars: Map<String, List<String>>, outputDir: Path, layout: BaseLayout, moduleOutputPatcher: ModuleOutputPatcher, dryRun: Boolean, context: BuildContext): Collection<DistributionFileEntry> { val copiedFiles = HashMap<Path, JpsLibrary>() val packager = JarPackager(context) for (data in layout.includedModuleLibraries) { val library = context.findRequiredModule(data.moduleName).libraryCollection.libraries .find { getLibraryName(it) == data.libraryName } ?: throw IllegalArgumentException("Cannot find library ${data.libraryName} in \'${data.moduleName}\' module") var fileName = libNameToMergedJarFileName(data.libraryName) var relativePath = data.relativeOutputPath var targetFile: Path? = null if (relativePath.endsWith(".jar")) { val index = relativePath.lastIndexOf('/') if (index == -1) { fileName = relativePath relativePath = "" } else { fileName = relativePath.substring(index + 1) relativePath = relativePath.substring(0, index) } } if (!relativePath.isEmpty()) { targetFile = outputDir.resolve(relativePath).resolve(fileName) } if (targetFile == null) { targetFile = outputDir.resolve(fileName) } packager.addLibrary(library = library, targetFile = targetFile!!, files = getLibraryFiles(library = library, copiedFiles = copiedFiles, isModuleLevel = true)) } val extraLibSources = HashMap<String, MutableList<Source>>() val libraryToMerge = packager.packProjectLibraries(jarToModuleNames = actualModuleJars, outputDir = outputDir, layout = layout, copiedFiles = copiedFiles, extraLibSources = extraLibSources) val isRootDir = context.paths.distAllDir == outputDir.parent if (isRootDir) { for ((key, value) in extraMergeRules) { packager.mergeLibsByPredicate(key, libraryToMerge, outputDir, value) } if (!libraryToMerge.isEmpty()) { packager.filesToSourceWithMappings(outputDir.resolve(APP_JAR), libraryToMerge) } } else if (!libraryToMerge.isEmpty()) { val mainJarName = (layout as PluginLayout).getMainJarName() assert(actualModuleJars.containsKey(mainJarName)) packager.filesToSourceWithMappings(outputDir.resolve(mainJarName), libraryToMerge) } // must be concurrent - buildJars executed in parallel val moduleNameToSize = ConcurrentHashMap<String, Int>() for ((jarPath, modules) in actualModuleJars) { val jarFile = outputDir.resolve(jarPath) val descriptor = packager.jarDescriptors.computeIfAbsent(jarFile) { JarDescriptor(jarFile = it) } val includedModules = descriptor.includedModules if (includedModules == null) { descriptor.includedModules = modules.toMutableList() } else { includedModules.addAll(modules) } val sourceList = descriptor.sources extraLibSources.get(jarPath)?.let(sourceList::addAll) packager.packModuleOutputAndUnpackedProjectLibraries(modules = modules, jarPath = jarPath, jarFile = jarFile, moduleOutputPatcher = moduleOutputPatcher, layout = layout, moduleNameToSize = moduleNameToSize, sourceList = sourceList) } val entries = ArrayList<Triple<Path, String, List<Source>>>(packager.jarDescriptors.size) val isReorderingEnabled = !context.options.buildStepsToSkip.contains(BuildOptions.GENERATE_JAR_ORDER_STEP) for (descriptor in packager.jarDescriptors.values) { var pathInClassLog = "" if (isReorderingEnabled) { if (isRootDir) { pathInClassLog = outputDir.parent.relativize(descriptor.jarFile).toString().replace(File.separatorChar, '/') } else if (outputDir.startsWith(context.paths.distAllDir)) { pathInClassLog = context.paths.distAllDir.relativize(descriptor.jarFile).toString().replace(File.separatorChar, '/') } else { val parent = outputDir.parent if (parent?.fileName.toString() == "plugins") { pathInClassLog = outputDir.parent.parent.relativize(descriptor.jarFile).toString().replace(File.separatorChar, '/') } } } entries.add(Triple(descriptor.jarFile, pathInClassLog, descriptor.sources)) } buildJars(entries, dryRun) for (item in packager.jarDescriptors.values) { for (moduleName in (item.includedModules ?: emptyList())) { val size = moduleNameToSize.get(moduleName) ?: throw IllegalStateException("Size is not set for $moduleName (moduleNameToSize=$moduleNameToSize)") packager.projectStructureMapping.add(ModuleOutputEntry(path = item.jarFile, moduleName, size)) } } return packager.projectStructureMapping } @JvmStatic fun getSearchableOptionsDir(buildContext: BuildContext): Path = buildContext.paths.tempDir.resolve("searchableOptionsResult") } private fun mergeLibsByPredicate(jarName: String, libraryToMerge: MutableMap<JpsLibrary, List<Path>>, outputDir: Path, predicate: (String) -> Boolean) { val result = LinkedHashMap<JpsLibrary, List<Path>>() val iterator = libraryToMerge.entries.iterator() while (iterator.hasNext()) { val (key, value) = iterator.next() if (predicate(key.name)) { iterator.remove() result.put(key, value) } } if (result.isEmpty()) { return } filesToSourceWithMappings(outputDir.resolve(jarName), result) } private fun filesToSourceWithMappings(uberJarFile: Path, libraryToMerge: Map<JpsLibrary, List<Path>>) { val sources = getJarDescriptorSources(uberJarFile) for ((key, value) in libraryToMerge) { filesToSourceWithMapping(sources, value, key, uberJarFile) } } private fun packModuleOutputAndUnpackedProjectLibraries(modules: Collection<String>, jarPath: String, jarFile: Path, moduleOutputPatcher: ModuleOutputPatcher, layout: BaseLayout, moduleNameToSize: MutableMap<String, Int>, sourceList: MutableList<Source>) { val searchableOptionsDir = getSearchableOptionsDir(context) Span.current().addEvent("include module outputs", Attributes.of(AttributeKey.stringArrayKey("modules"), java.util.List.copyOf(modules))) for (moduleName in modules) { addModuleSources(moduleName, moduleNameToSize, context.getModuleOutputDir(context.findRequiredModule(moduleName)), moduleOutputPatcher.getPatchedDir(moduleName), moduleOutputPatcher.getPatchedContent(moduleName), searchableOptionsDir, layout.moduleExcludes[moduleName], sourceList) } for (libraryName in layout.projectLibrariesToUnpack.get(jarPath)) { val library = context.project.libraryCollection.findLibrary(libraryName) if (library == null) { context.messages.error("Project library \'$libraryName\' from $jarPath should be unpacked but it isn\'t found") continue } for (ioFile in library.getFiles(JpsOrderRootType.COMPILED)) { val file = ioFile.toPath() sourceList.add(ZipSource(file = file) { size: Int -> val libraryData = ProjectLibraryData(libraryName = library.name, outPath = null, packMode = LibraryPackMode.MERGED, reason = "explicitUnpack") projectStructureMapping.add(ProjectLibraryEntry(jarFile, libraryData, file, size)) }) } } } private fun packProjectLibraries(jarToModuleNames: Map<String, List<String>>, outputDir: Path, layout: BaseLayout, copiedFiles: MutableMap<Path, JpsLibrary>, extraLibSources: MutableMap<String, MutableList<Source>>): MutableMap<JpsLibrary, List<Path>> { val toMerge = LinkedHashMap<JpsLibrary, List<Path>>() val projectLibs = if (layout.includedProjectLibraries.isEmpty()) { emptyList() } else { layout.includedProjectLibraries.sortedBy { it.libraryName } } for (libraryData in projectLibs) { val library = context.project.libraryCollection.findLibrary(libraryData.libraryName) ?: throw IllegalArgumentException("Cannot find library ${libraryData.libraryName} in the project") libToMetadata.put(library, libraryData) val libName = library.name val files = getLibraryFiles(library = library, copiedFiles = copiedFiles, isModuleLevel = false) var packMode = libraryData.packMode if (packMode == LibraryPackMode.MERGED && !extraMergeRules.values.any { it(libName) } && !isLibraryMergeable(libName)) { packMode = LibraryPackMode.STANDALONE_MERGED } val outPath = libraryData.outPath if (packMode == LibraryPackMode.MERGED && outPath == null) { toMerge.put(library, files) } else { var libOutputDir = outputDir if (outPath != null) { libOutputDir = if (outPath.endsWith(".jar")) { addLibrary(library, outputDir.resolve(outPath), files) continue } else { outputDir.resolve(outPath) } } if (packMode == LibraryPackMode.STANDALONE_MERGED) { addLibrary(library, libOutputDir.resolve(libNameToMergedJarFileName(libName)), files) } else { for (file in files) { var fileName = file.fileName.toString() if (packMode == LibraryPackMode.STANDALONE_SEPARATE_WITHOUT_VERSION_NAME) { fileName = removeVersionFromJar(fileName) } addLibrary(library, libOutputDir.resolve(fileName), listOf(file)) } } } } for ((targetFilename, value) in jarToModuleNames) { if (targetFilename.contains("/")) { continue } for (moduleName in value) { if (layout.modulesWithExcludedModuleLibraries.contains(moduleName)) { continue } val excluded = layout.excludedModuleLibraries.get(moduleName) for (element in context.findRequiredModule(moduleName).dependenciesList.dependencies) { if (element !is JpsLibraryDependency) { continue } packModuleLibs(moduleName = moduleName, targetFilename = targetFilename, libraryDependency = element, excluded = excluded, layout = layout, outputDir = outputDir, copiedFiles = copiedFiles, extraLibSources = extraLibSources) } } } return toMerge } private fun packModuleLibs(moduleName: String, targetFilename: String, libraryDependency: JpsLibraryDependency, excluded: Collection<String>, layout: BaseLayout, outputDir: Path, copiedFiles: MutableMap<Path, JpsLibrary>, extraLibSources: MutableMap<String, MutableList<Source>>) { if (libraryDependency.libraryReference.parentReference!!.resolve() !is JpsModule) { return } if (JpsJavaExtensionService.getInstance().getDependencyExtension(libraryDependency)?.scope ?.isIncludedIn(JpsJavaClasspathKind.PRODUCTION_RUNTIME) != true) { return } val library = libraryDependency.library!! val libraryName = getLibraryName(library) if (excluded.contains(libraryName) || layout.includedModuleLibraries.any { it.libraryName == libraryName }) { return } val files = getLibraryFiles(library = library, copiedFiles = copiedFiles, isModuleLevel = true) if (library.name == "async-profiler-windows") { // custom name, removeVersionFromJar doesn't support strings like `2.1-ea-4` addLibrary(library, outputDir.resolve("async-profiler-windows.jar"), files) return } for (i in (files.size - 1) downTo 0) { val file = files.get(i) val fileName = file.fileName.toString() if (fileName.endsWith("-rt.jar") || fileName.contains("-agent") || fileName == "yjp-controller-api-redist.jar") { files.removeAt(i) addLibrary(library, outputDir.resolve(removeVersionFromJar(fileName)), listOf(file)) } } if (!files.isEmpty()) { val sources = extraLibSources.computeIfAbsent(targetFilename) { mutableListOf() } val targetFile = outputDir.resolve(targetFilename) for (file in files) { sources.add(ZipSource(file = file) { size -> projectStructureMapping.add(ModuleLibraryFileEntry(targetFile, moduleName, file, size)) }) } } } private fun filesToSourceWithMapping(to: MutableList<Source>, files: List<Path>, library: JpsLibrary, targetFile: Path) { val moduleReference = library.createReference().parentReference as? JpsModuleReference for (file in files) { to.add(ZipSource(file) { size -> if (moduleReference == null) { projectStructureMapping.add(ProjectLibraryEntry(path = targetFile, data = libToMetadata.get(library)!!, libraryFile = file, size = size)) } else { projectStructureMapping.add(ModuleLibraryFileEntry(path = targetFile, moduleName = moduleReference.moduleName, libraryFile = file, size = size)) } }) } } private fun addLibrary(library: JpsLibrary, targetFile: Path, files: List<Path>) { filesToSourceWithMapping(getJarDescriptorSources(targetFile), files, library, targetFile) } private fun getJarDescriptorSources(targetFile: Path): MutableList<Source> { return jarDescriptors.computeIfAbsent(targetFile) { JarDescriptor(targetFile) }.sources } } private data class JarDescriptor(val jarFile: Path) { val sources: MutableList<Source> = mutableListOf() var includedModules: MutableList<String>? = null } private fun removeVersionFromJar(fileName: String): String { val matcher = LayoutBuilder.JAR_NAME_WITH_VERSION_PATTERN.matcher(fileName) return if (matcher.matches()) "${matcher.group(1)}.jar" else fileName } private fun getLibraryFiles(library: JpsLibrary, copiedFiles: MutableMap<Path, JpsLibrary>, isModuleLevel: Boolean): MutableList<Path> { val urls = library.getRootUrls(JpsOrderRootType.COMPILED) val result = ArrayList<Path>(urls.size) val libName = library.name for (url in urls) { if (JpsPathUtil.isJrtUrl(url)) { continue } val file = Path.of(JpsPathUtil.urlToPath(url)) val alreadyCopiedFor = copiedFiles.putIfAbsent(file, library) if (alreadyCopiedFor != null) { // check name - we allow to have same named module level library name if (isModuleLevel && alreadyCopiedFor.name == libName) { continue } throw IllegalStateException("File $file from $libName is already provided by ${alreadyCopiedFor.name} library") } result.add(file) } return result } private fun libNameToMergedJarFileName(libName: String): String { return "${FileUtil.sanitizeFileName(libName.lowercase(Locale.getDefault()), false)}.jar" } @Suppress("SpellCheckingInspection") private val excludedFromMergeLibs = java.util.Set.of( "sqlite", "async-profiler", "dexlib2", // android-only lib "intellij-test-discovery", // used as an agent "winp", "junixsocket-core", "pty4j", "grpc-netty-shaded", // these contain a native library "protobuf", // https://youtrack.jetbrains.com/issue/IDEA-268753 ) private fun isLibraryMergeable(libName: String): Boolean { return !excludedFromMergeLibs.contains(libName) && !libName.startsWith("kotlin-") && !libName.startsWith("kotlinc.") && !libName.startsWith("projector-") && !libName.contains("-agent-") && !libName.startsWith("rd-") && !libName.contains("annotations", ignoreCase = true) && !libName.startsWith("junit", ignoreCase = true) && !libName.startsWith("cucumber-", ignoreCase = true) && !libName.contains("groovy", ignoreCase = true) }
apache-2.0
5c75710aa0a6bbc73af96e9db0ad76a4
42.564356
140
0.628301
5.043329
false
false
false
false
ninjahoahong/unstoppable
app/src/main/java/com/ninjahoahong/unstoppable/AppModule.kt
1
1909
package com.ninjahoahong.unstoppable import android.content.Context import com.google.gson.Gson import com.google.gson.GsonBuilder import com.jakewharton.retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory import com.ninjahoahong.unstoppable.api.AppService import com.ninjahoahong.unstoppable.utils.SchedulerProvider import com.ninjahoahong.unstoppable.utils.SchedulerProviderImpl import dagger.Module import dagger.Provides import io.reactivex.disposables.CompositeDisposable import okhttp3.Cache import okhttp3.OkHttpClient import okhttp3.logging.HttpLoggingInterceptor import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory import java.util.concurrent.TimeUnit import javax.inject.Singleton @Module class AppModule(private val context: Context) { @Provides @Singleton fun applicationContext(): Context = context @Provides fun scheduler(): SchedulerProvider = SchedulerProviderImpl() @Provides fun compositeDisposable(): CompositeDisposable = CompositeDisposable() @Provides @Singleton fun appService(gson: Gson, okHttpClient: OkHttpClient): AppService = Retrofit.Builder().apply { baseUrl(BuildConfig.API_BASE_URL) addConverterFactory(GsonConverterFactory.create(gson)) addCallAdapterFactory(RxJava2CallAdapterFactory.create()) client(okHttpClient) }.build().create(AppService::class.java) @Provides @Singleton fun gson(): Gson = GsonBuilder().create() @Provides @Singleton fun httpCache(context: Context): Cache = Cache(context.cacheDir, 10000) @Provides @Singleton fun okhttpClient(cache: Cache): OkHttpClient = OkHttpClient.Builder().apply { cache(cache) connectTimeout(10, TimeUnit.DAYS) readTimeout(10, TimeUnit.DAYS) addInterceptor(HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.HEADERS)) }.build() }
mit
8972fa54a500d0d375f1298f0e0c7e9c
30.295082
99
0.770037
4.644769
false
false
false
false
dahlstrom-g/intellij-community
plugins/ide-features-trainer/src/training/statistic/StatisticBase.kt
3
17959
// 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 training.statistic import com.intellij.ide.TipsOfTheDayUsagesCollector.TipInfoValidationRule import com.intellij.ide.plugins.PluginManager import com.intellij.internal.statistic.eventLog.EventLogGroup import com.intellij.internal.statistic.eventLog.FeatureUsageData import com.intellij.internal.statistic.eventLog.events.* import com.intellij.internal.statistic.service.fus.collectors.CounterUsagesCollector import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.keymap.Keymap import com.intellij.openapi.keymap.KeymapManager import com.intellij.openapi.keymap.impl.DefaultKeymapImpl import com.intellij.openapi.util.BuildNumber import com.intellij.util.TimeoutUtil import training.lang.LangManager import training.learn.CourseManager import training.learn.course.IftModule import training.learn.course.Lesson import training.learn.lesson.LessonManager import training.statistic.FeatureUsageStatisticConsts.ACTION_ID import training.statistic.FeatureUsageStatisticConsts.COMPLETED_COUNT import training.statistic.FeatureUsageStatisticConsts.COURSE_SIZE import training.statistic.FeatureUsageStatisticConsts.DURATION import training.statistic.FeatureUsageStatisticConsts.EXPAND_WELCOME_PANEL import training.statistic.FeatureUsageStatisticConsts.FEEDBACK_ENTRY_PLACE import training.statistic.FeatureUsageStatisticConsts.FEEDBACK_EXPERIENCED_USER import training.statistic.FeatureUsageStatisticConsts.FEEDBACK_HAS_BEEN_SENT import training.statistic.FeatureUsageStatisticConsts.FEEDBACK_LIKENESS_ANSWER import training.statistic.FeatureUsageStatisticConsts.FEEDBACK_OPENED_VIA_NOTIFICATION import training.statistic.FeatureUsageStatisticConsts.HELP_LINK_CLICKED import training.statistic.FeatureUsageStatisticConsts.INTERNAL_PROBLEM import training.statistic.FeatureUsageStatisticConsts.KEYMAP_SCHEME import training.statistic.FeatureUsageStatisticConsts.LANGUAGE import training.statistic.FeatureUsageStatisticConsts.LAST_BUILD_LEARNING_OPENED import training.statistic.FeatureUsageStatisticConsts.LEARN_PROJECT_OPENED_FIRST_TIME import training.statistic.FeatureUsageStatisticConsts.LEARN_PROJECT_OPENING_WAY import training.statistic.FeatureUsageStatisticConsts.LESSON_ID import training.statistic.FeatureUsageStatisticConsts.LESSON_LINK_CLICKED_FROM_TIP import training.statistic.FeatureUsageStatisticConsts.LESSON_STARTING_WAY import training.statistic.FeatureUsageStatisticConsts.MODULE_NAME import training.statistic.FeatureUsageStatisticConsts.NEED_SHOW_NEW_LESSONS_NOTIFICATIONS import training.statistic.FeatureUsageStatisticConsts.NEW_LESSONS_COUNT import training.statistic.FeatureUsageStatisticConsts.NEW_LESSONS_NOTIFICATION_SHOWN import training.statistic.FeatureUsageStatisticConsts.NON_LEARNING_PROJECT_OPENED import training.statistic.FeatureUsageStatisticConsts.ONBOARDING_FEEDBACK_DIALOG_RESULT import training.statistic.FeatureUsageStatisticConsts.ONBOARDING_FEEDBACK_NOTIFICATION_SHOWN import training.statistic.FeatureUsageStatisticConsts.PASSED import training.statistic.FeatureUsageStatisticConsts.PROBLEM import training.statistic.FeatureUsageStatisticConsts.PROGRESS import training.statistic.FeatureUsageStatisticConsts.REASON import training.statistic.FeatureUsageStatisticConsts.RESTORE import training.statistic.FeatureUsageStatisticConsts.SHORTCUT_CLICKED import training.statistic.FeatureUsageStatisticConsts.SHOULD_SHOW_NEW_LESSONS import training.statistic.FeatureUsageStatisticConsts.SHOW_NEW_LESSONS import training.statistic.FeatureUsageStatisticConsts.START import training.statistic.FeatureUsageStatisticConsts.START_MODULE_ACTION import training.statistic.FeatureUsageStatisticConsts.STOPPED import training.statistic.FeatureUsageStatisticConsts.TASK_ID import training.statistic.FeatureUsageStatisticConsts.TIP_FILENAME import training.util.KeymapUtil import java.awt.event.KeyEvent import java.util.concurrent.ConcurrentHashMap import javax.swing.JOptionPane enum class LessonStartingWay { NEXT_BUTTON, PREV_BUTTON, RESTART_BUTTON, RESTORE_LINK, ONBOARDING_PROMOTER, LEARN_TAB, TIP_AND_TRICK_PROMOTER, NO_SDK_RESTART } internal enum class FeedbackEntryPlace { WELCOME_SCREEN, LEARNING_PROJECT, ANOTHER_PROJECT } internal enum class FeedbackLikenessAnswer { NO_ANSWER, LIKE, DISLIKE } enum class LearningInternalProblems { NO_SDK_CONFIGURED, // Before learning start we are trying to autoconfigure SDK or at least ask about location } internal class StatisticBase : CounterUsagesCollector() { override fun getGroup() = GROUP private data class LessonProgress(val lessonId: String, val taskId: Int) enum class LearnProjectOpeningWay { LEARN_IDE, ONBOARDING_PROMOTER } enum class LessonStopReason { CLOSE_PROJECT, RESTART, CLOSE_FILE, OPEN_MODULES, OPEN_NEXT_OR_PREV_LESSON, EXIT_LINK } companion object { private val LOG = logger<StatisticBase>() private val sessionLessonTimestamp: ConcurrentHashMap<String, Long> = ConcurrentHashMap() private var prevRestoreLessonProgress: LessonProgress = LessonProgress("", 0) private val GROUP: EventLogGroup = EventLogGroup("ideFeaturesTrainer", 18) var isLearnProjectCloseLogged = false // FIELDS private val lessonIdField = EventFields.StringValidatedByCustomRule(LESSON_ID, IdeFeaturesTrainerRuleValidator::class.java) private val languageField = EventFields.StringValidatedByCustomRule(LANGUAGE, SupportedLanguageRuleValidator::class.java) private val completedCountField = EventFields.Int(COMPLETED_COUNT) private val courseSizeField = EventFields.Int(COURSE_SIZE) private val moduleNameField = EventFields.StringValidatedByCustomRule(MODULE_NAME, IdeFeaturesTrainerModuleRuleValidator::class.java) private val taskIdField = EventFields.StringValidatedByCustomRule(TASK_ID, TaskIdRuleValidator::class.java) private val actionIdField = EventFields.StringValidatedByCustomRule(ACTION_ID, ActionIdRuleValidator::class.java) private val keymapSchemeField = EventFields.StringValidatedByCustomRule(KEYMAP_SCHEME, KeymapSchemeRuleValidator::class.java) private val versionField = EventFields.Version private val inputEventField = EventFields.InputEvent private val learnProjectOpeningWayField = EventFields.Enum<LearnProjectOpeningWay>(LEARN_PROJECT_OPENING_WAY) private val reasonField = EventFields.Enum<LessonStopReason>(REASON) private val newLessonsCount = EventFields.Int(NEW_LESSONS_COUNT) private val showNewLessonsState = EventFields.Boolean(SHOULD_SHOW_NEW_LESSONS) private val tipFilenameField = EventFields.StringValidatedByCustomRule(TIP_FILENAME, TipInfoValidationRule::class.java) private val lessonStartingWayField = EventFields.Enum<LessonStartingWay>(LESSON_STARTING_WAY) private val feedbackEntryPlace = EventFields.Enum<FeedbackEntryPlace>(FEEDBACK_ENTRY_PLACE) private val feedbackHasBeenSent = EventFields.Boolean(FEEDBACK_HAS_BEEN_SENT) private val feedbackOpenedViaNotification = EventFields.Boolean(FEEDBACK_OPENED_VIA_NOTIFICATION) private val feedbackLikenessAnswer = EventFields.Enum<FeedbackLikenessAnswer>(FEEDBACK_LIKENESS_ANSWER) private val feedbackExperiencedUser = EventFields.Boolean(FEEDBACK_EXPERIENCED_USER) private val internalProblemField = EventFields.Enum<LearningInternalProblems>(PROBLEM) private val lastBuildLearningOpened = object : PrimitiveEventField<String?>() { override val name: String = LAST_BUILD_LEARNING_OPENED override val validationRule: List<String> get() = listOf("{regexp#version}") override fun addData(fuData: FeatureUsageData, value: String?) { if (value != null) { fuData.addData(name, value) } } } // EVENTS private val lessonStartedEvent: EventId3<String?, String?, LessonStartingWay> = GROUP.registerEvent(START, lessonIdField, languageField, lessonStartingWayField) private val lessonPassedEvent: EventId3<String?, String?, Long> = GROUP.registerEvent(PASSED, lessonIdField, languageField, EventFields.Long(DURATION)) private val lessonStoppedEvent = GROUP.registerVarargEvent(STOPPED, lessonIdField, taskIdField, languageField, reasonField) private val progressUpdatedEvent = GROUP.registerVarargEvent(PROGRESS, lessonIdField, completedCountField, courseSizeField, languageField) private val moduleStartedEvent: EventId2<String?, String?> = GROUP.registerEvent(START_MODULE_ACTION, moduleNameField, languageField) private val welcomeScreenPanelExpandedEvent: EventId1<String?> = GROUP.registerEvent(EXPAND_WELCOME_PANEL, languageField) private val shortcutClickedEvent = GROUP.registerVarargEvent(SHORTCUT_CLICKED, inputEventField, keymapSchemeField, lessonIdField, taskIdField, actionIdField, versionField) private val restorePerformedEvent = GROUP.registerVarargEvent(RESTORE, lessonIdField, taskIdField, versionField) private val learnProjectOpenedFirstTimeEvent: EventId2<LearnProjectOpeningWay, String?> = GROUP.registerEvent(LEARN_PROJECT_OPENED_FIRST_TIME, learnProjectOpeningWayField, languageField) private val nonLearningProjectOpened: EventId1<LearnProjectOpeningWay> = GROUP.registerEvent(NON_LEARNING_PROJECT_OPENED, learnProjectOpeningWayField) private val newLessonsNotificationShown = GROUP.registerEvent(NEW_LESSONS_NOTIFICATION_SHOWN, newLessonsCount, lastBuildLearningOpened) private val showNewLessonsEvent = GROUP.registerEvent(SHOW_NEW_LESSONS, newLessonsCount, lastBuildLearningOpened) private val needShowNewLessonsNotifications = GROUP.registerEvent(NEED_SHOW_NEW_LESSONS_NOTIFICATIONS, newLessonsCount, lastBuildLearningOpened, showNewLessonsState) private val internalProblem = GROUP.registerEvent(INTERNAL_PROBLEM, internalProblemField, lessonIdField, languageField) private val lessonLinkClickedFromTip = GROUP.registerEvent(LESSON_LINK_CLICKED_FROM_TIP, lessonIdField, languageField, tipFilenameField) private val helpLinkClicked = GROUP.registerEvent(HELP_LINK_CLICKED, lessonIdField, languageField) private val onboardingFeedbackNotificationShown = GROUP.registerEvent(ONBOARDING_FEEDBACK_NOTIFICATION_SHOWN, feedbackEntryPlace) private val onboardingFeedbackDialogResult = GROUP.registerVarargEvent(ONBOARDING_FEEDBACK_DIALOG_RESULT, feedbackEntryPlace, feedbackHasBeenSent, feedbackOpenedViaNotification, feedbackLikenessAnswer, feedbackExperiencedUser, ) // LOGGING fun logLessonStarted(lesson: Lesson, startingWay: LessonStartingWay) { sessionLessonTimestamp[lesson.id] = System.nanoTime() lessonStartedEvent.log(lesson.id, courseLanguage(), startingWay) } fun logLessonPassed(lesson: Lesson) { val timestamp = sessionLessonTimestamp[lesson.id] if (timestamp == null) { LOG.warn("Unable to find timestamp for a lesson: ${lesson.name}") return } val delta = TimeoutUtil.getDurationMillis(timestamp) lessonPassedEvent.log(lesson.id, courseLanguage(), delta) progressUpdatedEvent.log(lessonIdField with lesson.id, completedCountField with completedCount(), courseSizeField with CourseManager.instance.lessonsForModules.size, languageField with courseLanguage()) } fun logLessonStopped(reason: LessonStopReason) { val lessonManager = LessonManager.instance if (lessonManager.lessonIsRunning()) { val lessonId = lessonManager.currentLesson!!.id val taskId = lessonManager.currentLessonExecutor!!.currentTaskIndex lessonStoppedEvent.log(lessonIdField with lessonId, taskIdField with taskId.toString(), languageField with courseLanguage(), reasonField with reason ) if (reason == LessonStopReason.CLOSE_PROJECT || reason == LessonStopReason.EXIT_LINK) { isLearnProjectCloseLogged = true } } } fun logModuleStarted(module: IftModule) { moduleStartedEvent.log(module.id, courseLanguage()) } fun logWelcomeScreenPanelExpanded() { welcomeScreenPanelExpandedEvent.log(courseLanguage()) } fun logShortcutClicked(actionId: String) { val lessonManager = LessonManager.instance if (lessonManager.lessonIsRunning()) { val lesson = lessonManager.currentLesson!! val keymap = getDefaultKeymap() ?: return shortcutClickedEvent.log(inputEventField with createInputEvent(actionId), keymapSchemeField with keymap.name, lessonIdField with lesson.id, taskIdField with lessonManager.currentLessonExecutor?.currentTaskIndex.toString(), actionIdField with actionId, versionField with getPluginVersion(lesson)) } } fun logRestorePerformed(lesson: Lesson, taskId: Int) { val curLessonProgress = LessonProgress(lesson.id, taskId) if (curLessonProgress != prevRestoreLessonProgress) { prevRestoreLessonProgress = curLessonProgress restorePerformedEvent.log(lessonIdField with lesson.id, taskIdField with taskId.toString(), versionField with getPluginVersion(lesson)) } } fun logLearnProjectOpenedForTheFirstTime(way: LearnProjectOpeningWay) { val langManager = LangManager.getInstance() val langSupport = langManager.getLangSupport() ?: return if (langManager.getLearningProjectPath(langSupport) == null) { LearnProjectState.instance.firstTimeOpenedWay = way learnProjectOpenedFirstTimeEvent.log(way, courseLanguage()) } } fun logNonLearningProjectOpened(way: LearnProjectOpeningWay) { nonLearningProjectOpened.log(way) } fun logNewLessonsNotification(newLessonsCount: Int, previousOpenedVersion: BuildNumber?) { newLessonsNotificationShown.log(newLessonsCount, previousOpenedVersion?.asString()) } fun logShowNewLessonsEvent(newLessonsCount: Int, previousOpenedVersion: BuildNumber?) { showNewLessonsEvent.log(newLessonsCount, previousOpenedVersion?.asString()) } fun logShowNewLessonsNotificationState(newLessonsCount: Int, previousOpenedVersion: BuildNumber?, showNewLessons: Boolean) { needShowNewLessonsNotifications.log(newLessonsCount, previousOpenedVersion?.asString(), showNewLessons) } fun logLessonLinkClickedFromTip(lessonId: String, tipFilename: String) { lessonLinkClickedFromTip.log(lessonId, courseLanguage(), tipFilename) } fun logHelpLinkClicked(lessonId: String) { helpLinkClicked.log(lessonId, courseLanguage()) } fun logOnboardingFeedbackNotification(place: FeedbackEntryPlace) { onboardingFeedbackNotificationShown.log(place) } fun logOnboardingFeedbackDialogResult(place: FeedbackEntryPlace, hasBeenSent: Boolean, openedViaNotification: Boolean, likenessAnswer: FeedbackLikenessAnswer, experiencedUser: Boolean) { onboardingFeedbackDialogResult.log( feedbackEntryPlace with place, feedbackHasBeenSent with hasBeenSent, feedbackOpenedViaNotification with openedViaNotification, feedbackLikenessAnswer with likenessAnswer, feedbackExperiencedUser with experiencedUser ) } fun logLearningProblem(problem: LearningInternalProblems, lesson: Lesson) { internalProblem.log(problem, lesson.id, courseLanguage()) } private fun courseLanguage() = LangManager.getInstance().getLangSupport()?.primaryLanguage?.toLowerCase() ?: "" private fun completedCount(): Int = CourseManager.instance.lessonsForModules.count { it.passed } private fun createInputEvent(actionId: String): FusInputEvent? { val keyStroke = KeymapUtil.getShortcutByActionId(actionId) ?: return null val inputEvent = KeyEvent(JOptionPane.getRootFrame(), KeyEvent.KEY_PRESSED, System.currentTimeMillis(), keyStroke.modifiers, keyStroke.keyCode, keyStroke.keyChar, KeyEvent.KEY_LOCATION_STANDARD) return FusInputEvent(inputEvent, "") } private fun getPluginVersion(lesson: Lesson): String? { return PluginManager.getPluginByClass(lesson::class.java)?.version } private fun getDefaultKeymap(): Keymap? { val keymap = KeymapManager.getInstance().activeKeymap if (keymap is DefaultKeymapImpl) { return keymap } return keymap.parent as? DefaultKeymapImpl } } }
apache-2.0
72fc94e160a99fa7a4ff6f23e0ddccd7
53.096386
158
0.731889
5.202491
false
false
false
false
google/playhvz
Android/ghvzApp/app/src/main/java/com/app/playhvz/screens/quiz/editablequestions/BooleanAnswerViewHolder.kt
1
3399
/* * Copyright 2020 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.app.playhvz.screens.quiz.editablequestions import android.content.Context import android.view.MenuInflater import android.view.MenuItem import android.view.View import android.widget.ImageButton import android.widget.TextView import androidx.appcompat.widget.PopupMenu import androidx.recyclerview.widget.RecyclerView import com.app.playhvz.R import com.app.playhvz.common.ui.MarkdownTextView import com.app.playhvz.firebase.classmodels.QuizQuestion class BooleanAnswerViewHolder( val context: Context, val view: View, val onEdit: (position: Int) -> Unit? ) : RecyclerView.ViewHolder(view) { private val answerButton = view.findViewById<MarkdownTextView>(R.id.answer_button)!! private val overflowButton = view.findViewById<ImageButton>(R.id.overflow_button)!! private val orderView = view.findViewById<TextView>(R.id.answer_order)!! private val correctnessView = view.findViewById<MarkdownTextView>(R.id.answer_correctness)!! private var answer: QuizQuestion.Answer? = null init { overflowButton.setOnClickListener { triggerOverflowPopup() } } fun onBind(position: Int, answer: QuizQuestion.Answer) { this.answer = answer val res = orderView.resources answerButton.text = if (answer.text.isEmpty()) { res.getString(R.string.quiz_answer_empty_text) } else { answer.text } answerButton.setOnClickListener { onEdit.invoke(position) } if (answer.order == -1) { orderView.text = res.getString(R.string.quiz_answer_order_text, "Ø") } else { orderView.text = res.getString(R.string.quiz_answer_order_text, answer.order.toString()) } val correctness = if (answer.isCorrect) R.string.quiz_answer_correct_text else R.string.quiz_answer_incorrect_text correctnessView.text = res.getString(correctness) } private fun triggerOverflowPopup() { val popup = PopupMenu(overflowButton.context, overflowButton) val inflater: MenuInflater = popup.menuInflater inflater.inflate(R.menu.menu_edit_quiz_answer, popup.menu) popup.menu.findItem(R.id.move_up_option).isVisible = false popup.menu.findItem(R.id.remove_order_option).isVisible = false popup.menu.findItem(R.id.move_down_option).isVisible = false popup.menu.findItem(R.id.delete_option).isVisible = false popup.setOnMenuItemClickListener { item -> handleOverflowPopupSelection(item) } popup.show() } private fun handleOverflowPopupSelection(item: MenuItem): Boolean { if (item.itemId == R.id.edit_option) { onEdit.invoke(adapterPosition) return true } return false } }
apache-2.0
fce642e3f08c7eb79cda885ee23836ce
36.351648
108
0.698352
4.169325
false
false
false
false