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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
AoEiuV020/PaNovel | app/src/main/java/cc/aoeiuv020/panovel/booklist/BookListFragmentAdapter.kt | 1 | 2136 | package cc.aoeiuv020.panovel.booklist
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import cc.aoeiuv020.panovel.R
import cc.aoeiuv020.panovel.data.entity.BookList
import kotlinx.android.synthetic.main.book_list_item.view.*
/**
*
* Created by AoEiuV020 on 2017.11.22-14:33:36.
*/
class BookListFragmentAdapter(
private val itemListener: ItemListener
) : androidx.recyclerview.widget.RecyclerView.Adapter<BookListFragmentAdapter.ViewHolder>() {
private var _data: MutableList<BookList> = mutableListOf()
var data: List<BookList>
get() = _data
set(value) {
_data = value.toMutableList()
notifyDataSetChanged()
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val itemView = LayoutInflater.from(parent.context).inflate(R.layout.book_list_item, parent, false)
return ViewHolder(itemView, itemListener)
}
override fun getItemCount(): Int = data.size
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val item = data[position]
holder.apply(item)
}
class ViewHolder(itemView: View, itemListener: ItemListener) : androidx.recyclerview.widget.RecyclerView.ViewHolder(itemView) {
private val name = itemView.ivName
private val count = itemView.ivCount
// 提供外面的加调方法使用,
lateinit var bookList: BookList
private set
val ctx: Context = itemView.context
init {
itemView.setOnClickListener {
itemListener.onClick(this)
}
itemView.setOnLongClickListener {
itemListener.onLongClick(this)
}
}
fun apply(bookList: BookList) {
this.bookList = bookList
name.text = bookList.name
// TODO: 改改,顺便要查到数量,
count.text = ""
}
}
interface ItemListener {
fun onClick(vh: ViewHolder)
fun onLongClick(vh: ViewHolder): Boolean
}
} | gpl-3.0 | d5ea8ea8b00710b908e27520dd90ea05 | 30.208955 | 131 | 0.65311 | 4.427966 | false | false | false | false |
free5ty1e/primestationone-control-android | app/src/main/java/com/chrisprime/primestationonecontrol/views/FoundPrimestationsRecyclerViewAdapter.kt | 1 | 2608 | package com.chrisprime.primestationonecontrol.views
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import com.chrisprime.primestationonecontrol.PrimeStationOneControlApplication
import com.chrisprime.primestationonecontrol.R
import com.chrisprime.primestationonecontrol.model.PrimeStationOne
import com.chrisprime.primestationonecontrol.utilities.FileUtilities
import kotlinx.android.synthetic.main.recyclerview_found_primestations_item.view.*
/**
* Created by cpaian on 7/18/15.
*/
class FoundPrimestationsRecyclerViewAdapter(private val mPrimeStationOneList: List<PrimeStationOne>?) : RecyclerView.Adapter<FoundPrimestationsRecyclerViewAdapter.FoundPrimeStationsRecyclerViewHolder>() {
override fun onCreateViewHolder(viewGroup: ViewGroup, i: Int): FoundPrimeStationsRecyclerViewHolder {
val view = LayoutInflater.from(viewGroup.context).inflate(R.layout.recyclerview_found_primestations_item, viewGroup, false)
return FoundPrimeStationsRecyclerViewHolder(view)
}
override fun onBindViewHolder(foundPrimeStationsRecyclerViewHolder: FoundPrimeStationsRecyclerViewHolder, i: Int) {
val primeStationOne = mPrimeStationOneList!![i]
foundPrimeStationsRecyclerViewHolder.primeStationOne = primeStationOne
//Setting text view title
foundPrimeStationsRecyclerViewHolder.itemView.found_primestation_title.text = primeStationOne.ipAddress +
"\n" + primeStationOne.hostname + "\n" + primeStationOne.version + "\n" +
primeStationOne.piUser + ":" + primeStationOne.piPassword + "\n" +
primeStationOne.mac
}
override fun getItemCount(): Int {
return if (null != mPrimeStationOneList) mPrimeStationOneList.size else 0
}
override fun getItemId(position: Int): Long {
return position.toLong()
}
class FoundPrimeStationsRecyclerViewHolder(view: View) : RecyclerView.ViewHolder(view), View.OnClickListener {
var primeStationOne: PrimeStationOne? = null
init {
itemView.isClickable = true
itemView.setOnClickListener(this)
}
override fun onClick(v: View) {
PrimeStationOneControlApplication.instance.currentPrimeStationOne = primeStationOne
Toast.makeText(v.context, "Current PrimeStation One set to: " + primeStationOne!!.toString(), Toast.LENGTH_LONG).show()
FileUtilities.storeCurrentPrimeStationToJson(v.context, primeStationOne!!)
}
}
}
| mit | 23da4cf8003409f9ccedf0b57e045bad | 42.466667 | 204 | 0.752684 | 5.025048 | false | false | false | false |
Light-Team/ModPE-IDE-Source | app/src/main/kotlin/com/brackeys/ui/feature/explorer/dialogs/ProgressDialog.kt | 1 | 7168 | /*
* Copyright 2021 Brackeys IDE contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.brackeys.ui.feature.explorer.dialogs
import android.app.Dialog
import android.os.Bundle
import android.widget.TextView
import androidx.fragment.app.DialogFragment
import androidx.fragment.app.activityViewModels
import androidx.lifecycle.Observer
import androidx.lifecycle.lifecycleScope
import androidx.navigation.fragment.navArgs
import com.afollestad.materialdialogs.MaterialDialog
import com.afollestad.materialdialogs.customview.customView
import com.afollestad.materialdialogs.customview.getCustomView
import com.brackeys.ui.R
import com.brackeys.ui.databinding.DialogProgressBinding
import com.brackeys.ui.feature.explorer.utils.Operation
import com.brackeys.ui.feature.explorer.viewmodel.ExplorerViewModel
import com.brackeys.ui.filesystem.base.model.FileModel
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.delay
import java.text.SimpleDateFormat
import java.util.*
@AndroidEntryPoint
class ProgressDialog : DialogFragment() {
private val viewModel: ExplorerViewModel by activityViewModels()
private val navArgs: ProgressDialogArgs by navArgs()
private lateinit var binding: DialogProgressBinding
private var dialogTitle: Int = -1
private var dialogMessage: Int = -1
private var dialogAction: () -> Unit = {} // Действие, которое запустится при открытии диалога
private var onCloseAction: () -> Unit = {} // Действие, которое выполнится при закрытии диалога
private var indeterminate: Boolean = false // Загрузка без отображения реального прогресса
private var tempFiles: List<FileModel> = emptyList() // Список файлов для отображения информации
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
collectData()
}
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
return MaterialDialog(requireContext()).show {
title(dialogTitle)
customView(R.layout.dialog_progress)
cancelOnTouchOutside(false)
positiveButton(R.string.action_run_in_background) {
onCloseAction.invoke()
}
negativeButton(R.string.action_cancel) {
viewModel.currentJob?.cancel()
onCloseAction.invoke()
}
binding = DialogProgressBinding.bind(getCustomView())
formatElapsedTime(binding.textElapsedTime, 0L) // 00:00
val then = System.currentTimeMillis()
lifecycleScope.launchWhenStarted {
repeat(1000) {
val difference = System.currentTimeMillis() - then
formatElapsedTime(binding.textElapsedTime, difference)
delay(1000)
}
}
val totalProgress = tempFiles.size
binding.progressIndicator.max = totalProgress
binding.progressIndicator.isIndeterminate = indeterminate
val progressObserver = Observer<Int> { currentProgress ->
if (currentProgress < tempFiles.size) {
val fileModel = tempFiles[currentProgress]
binding.textDetails.text = getString(dialogMessage, fileModel.path)
binding.textOfTotal.text = getString(
R.string.message_of_total,
currentProgress + 1,
totalProgress
)
binding.progressIndicator.progress = currentProgress + 1
}
if (currentProgress >= totalProgress) {
onCloseAction.invoke()
dismiss()
}
}
setOnShowListener {
viewModel.progressEvent.observe(this@ProgressDialog, progressObserver)
dialogAction.invoke()
}
setOnDismissListener {
viewModel.progressEvent.removeObservers(this@ProgressDialog)
}
}
}
private fun formatElapsedTime(textView: TextView, timeInMillis: Long) {
val formatter = SimpleDateFormat("mm:ss", Locale.getDefault())
val elapsedTime = getString(
R.string.message_elapsed_time,
formatter.format(timeInMillis)
)
textView.text = elapsedTime
}
private fun collectData() {
tempFiles = viewModel.tempFiles.toList()
viewModel.tempFiles.clear() // Clear immediately
when (viewModel.operation) {
Operation.DELETE -> {
dialogTitle = R.string.dialog_title_deleting
dialogMessage = R.string.message_deleting
dialogAction = {
viewModel.deleteFiles(tempFiles)
}
}
Operation.COPY -> {
dialogTitle = R.string.dialog_title_copying
dialogMessage = R.string.message_copying
dialogAction = {
viewModel.copyFiles(tempFiles, navArgs.parentPath)
}
onCloseAction = {
viewModel.allowPasteFiles.value = false
}
}
Operation.CUT -> {
dialogTitle = R.string.dialog_title_copying
dialogMessage = R.string.message_copying
dialogAction = {
viewModel.cutFiles(tempFiles, navArgs.parentPath)
}
onCloseAction = {
viewModel.allowPasteFiles.value = false
}
}
Operation.COMPRESS -> {
dialogTitle = R.string.dialog_title_compressing
dialogMessage = R.string.message_compressing
dialogAction = {
viewModel.compressFiles(
source = tempFiles,
destPath = navArgs.parentPath,
archiveName = navArgs.archiveName ?: tempFiles.first().name + ".zip"
)
}
}
Operation.EXTRACT -> {
dialogTitle = R.string.dialog_title_extracting
dialogMessage = R.string.message_extracting
dialogAction = {
viewModel.extractAll(tempFiles.first(), navArgs.parentPath)
}
indeterminate = true
}
}
}
} | apache-2.0 | d095c24e3789fc7b8e9c59f375881a9c | 38.145251 | 100 | 0.612475 | 5.17048 | false | false | false | false |
Light-Team/ModPE-IDE-Source | app/src/main/kotlin/com/brackeys/ui/feature/editor/fragments/EditorFragment.kt | 1 | 26941 | /*
* Copyright 2021 Brackeys IDE contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.brackeys.ui.feature.editor.fragments
import android.content.Intent
import android.os.Bundle
import android.view.KeyEvent
import android.view.View
import androidx.core.view.isInvisible
import androidx.core.view.isVisible
import androidx.core.widget.TextViewCompat
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import com.afollestad.materialdialogs.MaterialDialog
import com.afollestad.materialdialogs.color.ColorPalette
import com.afollestad.materialdialogs.color.colorChooser
import com.afollestad.materialdialogs.customview.customView
import com.afollestad.materialdialogs.customview.getCustomView
import com.brackeys.ui.R
import com.brackeys.ui.data.converter.DocumentConverter
import com.brackeys.ui.data.utils.toHexString
import com.brackeys.ui.databinding.FragmentEditorBinding
import com.brackeys.ui.domain.model.documents.DocumentParams
import com.brackeys.ui.domain.model.editor.DocumentContent
import com.brackeys.ui.editorkit.exception.LineException
import com.brackeys.ui.editorkit.listener.OnChangeListener
import com.brackeys.ui.editorkit.listener.OnShortcutListener
import com.brackeys.ui.editorkit.listener.OnUndoRedoChangedListener
import com.brackeys.ui.editorkit.widget.TextScroller
import com.brackeys.ui.feature.editor.adapters.AutoCompleteAdapter
import com.brackeys.ui.feature.editor.adapters.DocumentAdapter
import com.brackeys.ui.feature.editor.utils.Panel
import com.brackeys.ui.feature.editor.utils.TabController
import com.brackeys.ui.feature.editor.utils.ToolbarManager
import com.brackeys.ui.feature.editor.viewmodel.EditorViewModel
import com.brackeys.ui.feature.main.adapters.TabAdapter
import com.brackeys.ui.feature.main.utils.OnBackPressedHandler
import com.brackeys.ui.feature.main.viewmodel.MainViewModel
import com.brackeys.ui.feature.settings.activities.SettingsActivity
import com.brackeys.ui.utils.event.SettingsEvent
import com.brackeys.ui.utils.extensions.*
import com.google.android.material.textfield.TextInputEditText
import dagger.hilt.android.AndroidEntryPoint
import net.yslibrary.android.keyboardvisibilityevent.KeyboardVisibilityEvent
@AndroidEntryPoint
class EditorFragment : Fragment(R.layout.fragment_editor), OnBackPressedHandler,
ToolbarManager.OnPanelClickListener, DocumentAdapter.TabInteractor {
companion object {
private const val ALPHA_FULL = 255
private const val ALPHA_SEMI = 90
private const val TAB_LIMIT = 10
}
private val sharedViewModel: MainViewModel by activityViewModels()
private val viewModel: EditorViewModel by viewModels()
private val toolbarManager: ToolbarManager by lazy { ToolbarManager(this) }
private val tabController: TabController by lazy { TabController() }
private lateinit var binding: FragmentEditorBinding
private lateinit var adapter: DocumentAdapter
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding = FragmentEditorBinding.bind(view)
observeViewModel()
toolbarManager.bind(binding)
binding.tabLayout.setHasFixedSize(true)
binding.tabLayout.adapter = DocumentAdapter(this).also { adapter ->
adapter.setOnTabSelectedListener(object : TabAdapter.OnTabSelectedListener {
override fun onTabUnselected(position: Int) = saveDocument(position)
override fun onTabSelected(position: Int) = loadDocument(position)
})
adapter.setOnDataRefreshListener(object : TabAdapter.OnDataRefreshListener {
override fun onDataRefresh() {
viewModel.emptyView.value = adapter.currentList.isEmpty()
}
})
this.adapter = adapter
}
tabController.attachToRecyclerView(binding.tabLayout)
binding.extendedKeyboard.setKeyListener { char -> binding.editor.insert(char) }
binding.extendedKeyboard.setHasFixedSize(true)
binding.scroller.attachTo(binding.editor)
binding.editor.suggestionAdapter = AutoCompleteAdapter(requireContext())
binding.editor.onUndoRedoChangedListener = OnUndoRedoChangedListener {
val canUndo = binding.editor.canUndo()
val canRedo = binding.editor.canRedo()
binding.actionUndo.isClickable = canUndo
binding.actionRedo.isClickable = canRedo
binding.actionUndo.imageAlpha = if (canUndo) ALPHA_FULL else ALPHA_SEMI
binding.actionRedo.imageAlpha = if (canRedo) ALPHA_FULL else ALPHA_SEMI
}
binding.editor.clearText()
binding.editor.onChangeListener = OnChangeListener {
val position = adapter.selectedPosition
if (position > -1) {
val isModified = adapter.currentList[position].modified
if (!isModified) {
adapter.currentList[position].modified = true
adapter.notifyItemChanged(position)
}
}
}
binding.actionTab.setOnClickListener {
binding.editor.insert(binding.editor.tab())
}
// region SHORTCUTS
binding.editor.onShortcutListener = OnShortcutListener { (ctrl, shift, alt, keyCode) ->
when {
ctrl && shift && keyCode == KeyEvent.KEYCODE_Z -> onUndoButton()
ctrl && shift && keyCode == KeyEvent.KEYCODE_S -> onSaveAsButton()
ctrl && keyCode == KeyEvent.KEYCODE_X -> onCutButton()
ctrl && keyCode == KeyEvent.KEYCODE_C -> onCopyButton()
ctrl && keyCode == KeyEvent.KEYCODE_V -> onPasteButton()
ctrl && keyCode == KeyEvent.KEYCODE_A -> onSelectAllButton()
ctrl && keyCode == KeyEvent.KEYCODE_DEL -> onDeleteLineButton()
ctrl && keyCode == KeyEvent.KEYCODE_D -> onDuplicateLineButton()
ctrl && keyCode == KeyEvent.KEYCODE_Z -> onUndoButton()
ctrl && keyCode == KeyEvent.KEYCODE_Y -> onRedoButton()
ctrl && keyCode == KeyEvent.KEYCODE_S -> onSaveButton()
ctrl && keyCode == KeyEvent.KEYCODE_P -> onPropertiesButton()
ctrl && keyCode == KeyEvent.KEYCODE_W -> onCloseButton()
ctrl && keyCode == KeyEvent.KEYCODE_F -> onOpenFindButton()
ctrl && keyCode == KeyEvent.KEYCODE_R -> onOpenReplaceButton()
ctrl && keyCode == KeyEvent.KEYCODE_G -> onGoToLineButton()
ctrl && keyCode == KeyEvent.KEYCODE_DPAD_LEFT -> binding.editor.moveCaretToStartOfLine()
ctrl && keyCode == KeyEvent.KEYCODE_DPAD_RIGHT -> binding.editor.moveCaretToEndOfLine()
alt && keyCode == KeyEvent.KEYCODE_DPAD_LEFT -> binding.editor.moveCaretToPrevWord()
alt && keyCode == KeyEvent.KEYCODE_DPAD_RIGHT -> binding.editor.moveCaretToNextWord()
alt && keyCode == KeyEvent.KEYCODE_A -> onSelectLineButton()
alt && keyCode == KeyEvent.KEYCODE_S -> onSettingsButton()
keyCode == KeyEvent.KEYCODE_TAB -> { binding.editor.insert(binding.editor.tab()); true }
else -> false
}
}
// endregion SHORTCUTS
viewModel.loadFiles()
}
override fun onPause() {
super.onPause()
saveDocument(adapter.selectedPosition)
}
override fun onResume() {
super.onResume()
loadDocument(adapter.selectedPosition)
viewModel.fetchSettings()
}
override fun handleOnBackPressed(): Boolean {
if (toolbarManager.panel != Panel.DEFAULT) {
onCloseFindButton()
return true
}
return false
}
private fun observeViewModel() {
viewModel.toastEvent.observe(viewLifecycleOwner) {
context?.showToast(it)
}
viewModel.loadFilesEvent.observe(viewLifecycleOwner) { documents ->
adapter.submitList(documents)
val position = viewModel.findRecentTab(documents)
if (position > -1) {
adapter.select(position)
}
}
viewModel.loadingBar.observe(viewLifecycleOwner) { isVisible ->
binding.loadingBar.isVisible = isVisible
if (isVisible) {
binding.editor.isInvisible = isVisible
} else {
if (!binding.emptyViewImage.isVisible) {
binding.editor.isInvisible = isVisible
}
}
}
viewModel.emptyView.observe(viewLifecycleOwner) { isVisible ->
binding.emptyViewImage.isVisible = isVisible
binding.emptyViewText.isVisible = isVisible
binding.editor.isInvisible = isVisible
}
viewModel.parseEvent.observe(viewLifecycleOwner) { model ->
model.exception?.let {
binding.editor.setErrorLine(it.lineNumber)
}
}
viewModel.contentEvent.observe(viewLifecycleOwner) { (content, textParams) ->
binding.scroller.state = TextScroller.STATE_HIDDEN
binding.editor.language = content.language
binding.editor.undoStack = content.undoStack
binding.editor.redoStack = content.redoStack
binding.editor.setTextContent(textParams)
binding.editor.scrollX = content.documentModel.scrollX
binding.editor.scrollY = content.documentModel.scrollY
binding.editor.setSelection(
content.documentModel.selectionStart,
content.documentModel.selectionEnd
)
binding.editor.requestFocus()
}
sharedViewModel.openEvent.observe(viewLifecycleOwner) { documentModel ->
if (!adapter.currentList.contains(documentModel)) {
if (adapter.currentList.size < TAB_LIMIT) {
viewModel.openFile(adapter.currentList + documentModel)
} else {
context?.showToast(R.string.message_tab_limit_achieved)
}
} else {
val position = adapter.currentList.indexOf(documentModel)
adapter.select(position)
}
}
// region PREFERENCES
viewModel.settingsEvent.observe(viewLifecycleOwner) { queue ->
val config = binding.editor.editorConfig
while (!queue.isNullOrEmpty()) {
when (val event = queue.poll()) {
is SettingsEvent.ThemePref -> {
binding.editor.colorScheme = event.value.colorScheme
}
is SettingsEvent.FontSize -> config.fontSize = event.value
is SettingsEvent.FontType -> {
config.fontType = requireContext().createTypefaceFromPath(event.value)
}
is SettingsEvent.WordWrap -> config.wordWrap = event.value
is SettingsEvent.CodeCompletion -> config.codeCompletion = event.value
is SettingsEvent.ErrorHighlight -> {
if (event.value) {
binding.editor.debounce(
coroutineScope = viewLifecycleOwner.lifecycleScope,
waitMs = 1500
) { text ->
if (text.isNotEmpty()) {
val position = adapter.selectedPosition
if (position > -1) {
viewModel.parse(
adapter.currentList[position],
binding.editor.language,
binding.editor.text.toString()
)
}
}
}
}
}
is SettingsEvent.PinchZoom -> config.pinchZoom = event.value
is SettingsEvent.CurrentLine -> config.highlightCurrentLine = event.value
is SettingsEvent.Delimiters -> config.highlightDelimiters = event.value
is SettingsEvent.ExtendedKeys -> {
KeyboardVisibilityEvent.setEventListener(requireActivity(), viewLifecycleOwner) { isOpen ->
binding.keyboardContainer.isVisible = event.value && isOpen
}
}
is SettingsEvent.KeyboardPreset -> {
binding.extendedKeyboard.submitList(event.value)
}
is SettingsEvent.SoftKeys -> config.softKeyboard = event.value
is SettingsEvent.AutoIndent -> config.autoIndentation = event.value
is SettingsEvent.AutoBrackets -> config.autoCloseBrackets = event.value
is SettingsEvent.AutoQuotes -> config.autoCloseQuotes = event.value
is SettingsEvent.UseSpacesNotTabs -> config.useSpacesInsteadOfTabs = event.value
is SettingsEvent.TabWidth -> config.tabWidth = event.value
}
}
binding.editor.editorConfig = config
}
// endregion PREFERENCES
}
// region TABS
override fun close(position: Int) {
val isModified = adapter.currentList[position].modified
if (isModified) {
MaterialDialog(requireContext()).show {
title(text = adapter.currentList[position].name)
message(R.string.dialog_message_close_tab)
negativeButton(R.string.action_cancel)
positiveButton(R.string.action_close) {
closeTabImpl(position)
}
}
} else {
closeTabImpl(position)
}
}
override fun closeOthers(position: Int) {
val tabCount = adapter.itemCount - 1
for (index in tabCount downTo 0) {
if (index != position) {
closeTabImpl(index)
}
}
}
override fun closeAll(position: Int) {
closeOthers(position)
closeTabImpl(adapter.selectedPosition)
}
private fun closeTabImpl(position: Int) {
if (position == adapter.selectedPosition) {
binding.scroller.state = TextScroller.STATE_HIDDEN
binding.editor.clearText() // TTL Exception bypass
if (adapter.itemCount == 1) {
activity?.closeKeyboard()
}
}
removeDocument(position)
adapter.close(position)
}
private fun loadDocument(position: Int) {
if (position > -1) {
val document = adapter.currentList[position]
viewModel.loadFile(document, TextViewCompat.getTextMetricsParams(binding.editor))
}
}
private fun saveDocument(position: Int) {
if (position > -1) {
viewModel.loadingBar.value = true // show loading indicator
val document = adapter.currentList[position].apply {
scrollX = binding.editor.scrollX
scrollY = binding.editor.scrollY
selectionStart = binding.editor.selectionStart
selectionEnd = binding.editor.selectionEnd
}
val text = binding.editor.text.toString()
if (text.isNotEmpty()) {
val documentContent = DocumentContent(
documentModel = document,
language = binding.editor.language,
undoStack = binding.editor.undoStack.clone(),
redoStack = binding.editor.redoStack.clone(),
text = text
)
val params = DocumentParams(
local = viewModel.autoSaveFiles,
cache = true
)
viewModel.saveFile(documentContent, params)
}
binding.editor.clearText() // TTL Exception bypass
adapter.currentList.forEachIndexed { index, model ->
viewModel.updateDocument(model.copy(position = index))
}
}
}
private fun removeDocument(position: Int) {
if (position > -1) {
val documentModel = adapter.currentList[position]
viewModel.deleteDocument(documentModel)
}
}
// endregion TABS
// region TOOLBAR
override fun onDrawerButton() {
sharedViewModel.openDrawerEvent.call()
}
override fun onNewButton() {
onDrawerButton() // TODO 27/02/21 Add Dialog
}
override fun onOpenButton() {
onDrawerButton()
context?.showToast(R.string.message_select_file)
}
override fun onSaveButton(): Boolean {
val position = adapter.selectedPosition
if (position > -1) {
val isModified = adapter.currentList[position].modified
if (isModified) {
adapter.currentList[position].modified = false
adapter.notifyItemChanged(position)
}
val documentContent = DocumentContent(
documentModel = adapter.currentList[position],
language = binding.editor.language,
undoStack = binding.editor.undoStack.clone(),
redoStack = binding.editor.redoStack.clone(),
text = binding.editor.text.toString()
)
val params = DocumentParams(
local = true,
cache = true
)
viewModel.saveFile(documentContent, params)
} else {
context?.showToast(R.string.message_no_open_files)
}
return true
}
override fun onSaveAsButton(): Boolean {
val position = adapter.selectedPosition
if (position > -1) {
val document = adapter.currentList[position]
MaterialDialog(requireContext()).show {
title(R.string.dialog_title_save_as)
customView(R.layout.dialog_save_as, scrollable = true)
negativeButton(R.string.action_cancel)
positiveButton(R.string.action_save) {
val enterFilePath = findViewById<TextInputEditText>(R.id.input)
val filePath = enterFilePath.text?.toString()?.trim()
if (!filePath.isNullOrBlank()) {
val updateDocument = document.copy(
uuid = "whatever",
path = filePath
)
val documentContent = DocumentContent(
documentModel = updateDocument,
language = binding.editor.language,
undoStack = binding.editor.undoStack.clone(),
redoStack = binding.editor.redoStack.clone(),
text = binding.editor.text.toString()
)
val params = DocumentParams(
local = true,
cache = false
)
viewModel.saveFile(documentContent, params)
} else {
context.showToast(R.string.message_invalid_file_path)
}
}
val enterFilePath = findViewById<TextInputEditText>(R.id.input)
enterFilePath.setText(document.path)
}
} else {
context?.showToast(R.string.message_no_open_files)
}
return true
}
override fun onPropertiesButton(): Boolean {
val position = adapter.selectedPosition
if (position > -1) {
val document = adapter.currentList[position]
sharedViewModel.propertiesEvent.value = DocumentConverter.toModel(document)
} else {
context?.showToast(R.string.message_no_open_files)
}
return true
}
override fun onCloseButton(): Boolean {
val position = adapter.selectedPosition
if (position > -1) {
close(position)
} else {
context?.showToast(R.string.message_no_open_files)
}
return true
}
override fun onCutButton(): Boolean {
if (binding.editor.hasSelection()) {
binding.editor.cut()
} else {
context?.showToast(R.string.message_nothing_to_cut)
}
return true
}
override fun onCopyButton(): Boolean {
if (binding.editor.hasSelection()) {
binding.editor.copy()
} else {
context?.showToast(R.string.message_nothing_to_copy)
}
return true
}
override fun onPasteButton(): Boolean {
val position = adapter.selectedPosition
if (binding.editor.hasPrimaryClip() && position > -1) {
binding.editor.paste()
} else {
context?.showToast(R.string.message_nothing_to_paste)
}
return true
}
override fun onSelectAllButton(): Boolean {
binding.editor.selectAll()
return true
}
override fun onSelectLineButton(): Boolean {
binding.editor.selectLine()
return true
}
override fun onDeleteLineButton(): Boolean {
binding.editor.deleteLine()
return true
}
override fun onDuplicateLineButton(): Boolean {
binding.editor.duplicateLine()
return true
}
override fun onOpenFindButton(): Boolean {
val position = adapter.selectedPosition
if (position > -1) {
toolbarManager.panel = Panel.FIND
} else {
context?.showToast(R.string.message_no_open_files)
}
return true
}
override fun onCloseFindButton() {
toolbarManager.panel = Panel.DEFAULT
binding.inputFind.setText("")
binding.editor.clearFindResultSpans()
}
override fun onOpenReplaceButton(): Boolean {
val position = adapter.selectedPosition
if (position > -1) {
toolbarManager.panel = Panel.FIND_REPLACE
} else {
context?.showToast(R.string.message_no_open_files)
}
return true
}
override fun onCloseReplaceButton() {
toolbarManager.panel = Panel.FIND
binding.inputReplace.setText("")
}
override fun onGoToLineButton(): Boolean {
val position = adapter.selectedPosition
if (position > -1) {
MaterialDialog(requireContext()).show {
title(R.string.dialog_title_goto_line)
customView(R.layout.dialog_goto_line)
negativeButton(R.string.action_cancel)
positiveButton(R.string.action_go_to) {
val input = getCustomView().findViewById<TextInputEditText>(R.id.input)
val inputNumber = input.text.toString()
try {
val lineNumber = inputNumber.toIntOrNull() ?: 0
binding.editor.gotoLine(lineNumber)
} catch (e: LineException) {
context.showToast(R.string.message_line_not_exists)
}
}
}
} else {
context?.showToast(R.string.message_no_open_files)
}
return true
}
override fun onReplaceButton(replaceText: String) {
binding.editor.replaceFindResult(replaceText)
}
override fun onReplaceAllButton(replaceText: String) {
binding.editor.replaceAllFindResults(replaceText)
}
override fun onNextResultButton() {
binding.editor.findNext()
}
override fun onPreviousResultButton() {
binding.editor.findPrevious()
}
override fun onFindInputChanged(findText: String) {
binding.editor.clearFindResultSpans()
binding.editor.find(findText, toolbarManager.findParams())
}
override fun onErrorCheckingButton() {
val position = adapter.selectedPosition
if (position > -1) {
MaterialDialog(requireContext()).show {
title(R.string.dialog_title_result)
message(R.string.message_no_errors_detected)
viewModel.parseEvent.value?.let { model ->
model.exception?.let {
message(text = it.message)
binding.editor.setErrorLine(it.lineNumber)
}
}
positiveButton(R.string.action_ok)
}
} else {
context?.showToast(R.string.message_no_open_files)
}
}
override fun onInsertColorButton() {
val position = adapter.selectedPosition
if (position > -1) {
MaterialDialog(requireContext()).show {
title(R.string.dialog_title_color_picker)
colorChooser(
colors = ColorPalette.Primary,
subColors = ColorPalette.PrimarySub,
allowCustomArgb = true,
showAlphaSelector = true
) { _, color ->
binding.editor.insert(color.toHexString())
}
positiveButton(R.string.action_insert)
negativeButton(R.string.action_cancel)
}
} else {
context?.showToast(R.string.message_no_open_files)
}
}
override fun onUndoButton(): Boolean {
if (binding.editor.canUndo()) {
binding.editor.undo()
}
return true
}
override fun onRedoButton(): Boolean {
if (binding.editor.canRedo()) {
binding.editor.redo()
}
return true
}
override fun onSettingsButton(): Boolean {
val intent = Intent(context, SettingsActivity::class.java)
startActivity(intent)
return true
}
// endregion TOOLBAR
} | apache-2.0 | 85b53c506abc3f2db535c15ef880d7d3 | 38.103048 | 115 | 0.589548 | 5.222136 | false | false | false | false |
nemerosa/ontrack | ontrack-service/src/main/java/net/nemerosa/ontrack/service/metrics/MetricsReexportJob.kt | 1 | 1763 | package net.nemerosa.ontrack.service.metrics
import net.nemerosa.ontrack.extension.api.ExtensionManager
import net.nemerosa.ontrack.extension.api.MetricsExportExtension
import net.nemerosa.ontrack.job.*
import net.nemerosa.ontrack.model.metrics.MetricsReexportJobProvider
import net.nemerosa.ontrack.model.support.JobProvider
import org.springframework.stereotype.Component
/**
* Job which re-exports all existing metrics.
*/
@Component
class MetricsReexportJob(
private val extensionManager: ExtensionManager,
private val metricsReexportJobProviders: List<MetricsReexportJobProvider>,
private val jobScheduler: JobScheduler,
) : JobProvider, Job {
override fun getStartingJobs() = listOf(
JobRegistration(
this,
Schedule.NONE
)
)
override fun getKey(): JobKey =
JobCategory.CORE.getType("metrics").withName("Metrics jobs").getKey("restoration")
override fun getTask() = JobRun { listener ->
listener.message("Preparing all the metrics extensions...")
extensionManager.getExtensions(MetricsExportExtension::class.java).forEach { extension ->
listener.message("Preparing ${extension::class.java.name}...")
extension.prepareReexport()
}
listener.message("Launching all the re-exportations...")
metricsReexportJobProviders.forEach { metricsReexportJobProvider ->
val key = metricsReexportJobProvider.getReexportJobKey()
listener.message("Launching (asynchronously) the re-exportation for $key...")
jobScheduler.fireImmediately(key).orElse(null)
}
}
override fun getDescription(): String = "Re-export of all metrics"
override fun isDisabled(): Boolean = false
} | mit | 0494a77d29573d985a2e7d330feaffe0 | 35.75 | 97 | 0.717527 | 4.790761 | false | false | false | false |
rsiebert/TVHClient | data/src/main/java/org/tvheadend/data/entity/Input.kt | 1 | 693 | package org.tvheadend.data.entity
data class Input(
var uuid: String = "",
var input: String = "",
var username: String = "",
var stream: String = "",
var numberOfSubscriptions: Int = 0,
var weight: Int = 0,
var signalStrength: Int = 0, // Shown as percentage from a range between 0 to 65535)
var bitErrorRate: Int = 0,
var uncorrectedBlocks: Int = 0,
var signalNoiseRatio: Int = 0, // Shown as percentage from a range between 0 to 65535)
var bandWidth: Int = 0, // bits/second
var continuityErrors: Int = 0,
var transportErrors: Int = 0,
var connectionId: Int = 0
)
| gpl-3.0 | e317d5e0a45e4bb06dc8e5075f8afa52 | 35.473684 | 95 | 0.582973 | 4.100592 | false | false | false | false |
LarsKrogJensen/graphql-kotlin | src/main/kotlin/graphql/validation/rules/FieldsOnCorrectType.kt | 1 | 834 | package graphql.validation.rules
import graphql.language.Field
import graphql.validation.IValidationContext
import graphql.validation.ValidationError
import graphql.validation.ValidationErrorType
import graphql.validation.*
class FieldsOnCorrectType(validationContext: IValidationContext,
validationErrorCollector: ValidationErrorCollector)
: AbstractRule(validationContext, validationErrorCollector) {
override fun checkField(field: Field) {
if (validationContext.parentType == null)
return
val fieldDef = validationContext.fieldDef
if (fieldDef == null) {
val message = String.format("Field %s is undefined", field.name)
addError(ValidationError(ValidationErrorType.FieldUndefined, field.sourceLocation, message))
}
}
}
| mit | 9ea3bcdd086f919bcdf059e8399922d2 | 32.36 | 104 | 0.730216 | 5.2125 | false | false | false | false |
nickbutcher/plaid | designernews/src/main/java/io/plaidapp/designernews/domain/GetCommentsWithRepliesUseCase.kt | 1 | 3945 | /*
* 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.designernews.domain
import io.plaidapp.core.data.Result
import io.plaidapp.core.designernews.domain.model.CommentWithReplies
import io.plaidapp.designernews.data.comments.CommentsRepository
import io.plaidapp.designernews.data.comments.model.CommentResponse
import io.plaidapp.designernews.data.comments.model.toCommentsWithReplies
import java.io.IOException
import javax.inject.Inject
/**
* Use case that constructs the entire comments and replies tree for a list of comments. Works
* with the [CommentsRepository] to get the data.
*/
class GetCommentsWithRepliesUseCase @Inject constructor(
private val commentsRepository: CommentsRepository
) {
/**
* Get all comments and their replies. If we get an error on any reply depth level, ignore it
* and just use the comments retrieved until that point.
*/
suspend operator fun invoke(parentIds: List<Long>): Result<List<CommentWithReplies>> {
val replies = mutableListOf<List<CommentResponse>>()
// get the first level of comments
var parentComments = commentsRepository.getComments(parentIds)
// as long as we could get comments or replies to comments
while (parentComments is Result.Success) {
val parents = parentComments.data
// add the replies
replies.add(parents)
// check if we have another level of replies
val replyIds = parents.flatMap { comment -> comment.links.comments }
if (!replyIds.isEmpty()) {
parentComments = commentsRepository.getComments(replyIds)
} else {
// we don't have any other level of replies match the replies to the comments
// they belong to and return the first level of comments.
if (replies.isNotEmpty()) {
return Result.Success(matchComments(replies))
}
}
}
// the last request was unsuccessful
// if we already got some comments and replies, then use that data and ignore the error
return when {
replies.isNotEmpty() -> Result.Success(matchComments(replies))
parentComments is Result.Error -> parentComments
else -> Result.Error(IOException("Unable to get comments"))
}
}
/**
* Build up the replies tree, by matching the replies from lower levels to the level above they
* belong to
*/
private fun matchComments(comments: List<List<CommentResponse>>): List<CommentWithReplies> {
var commentsWithReplies = emptyList<CommentWithReplies>()
for (index in comments.size - 1 downTo 0) {
commentsWithReplies = matchCommentsWithReplies(comments[index], commentsWithReplies)
}
return commentsWithReplies
}
private fun matchCommentsWithReplies(
comments: List<CommentResponse>,
replies: List<CommentWithReplies>
): List<CommentWithReplies> {
val commentReplyMapping = replies.groupBy { it.parentId }
// for every comment construct the CommentWithReplies based on the comment properties and
// the list of replies
return comments.map {
val commentReplies = commentReplyMapping[it.id].orEmpty()
it.toCommentsWithReplies(commentReplies)
}
}
}
| apache-2.0 | 75b856083f69ee80530082069d0461db | 41.419355 | 99 | 0.683904 | 4.764493 | false | false | false | false |
d9n/intellij-rust | src/test/kotlin/org/rust/ide/annotator/RsHighlightingAnnotatorTest.kt | 1 | 4095 | package org.rust.ide.annotator
import com.intellij.testFramework.fixtures.impl.CodeInsightTestFixtureImpl
class RsHighlightingAnnotatorTest : RsAnnotatorTestBase() {
fun testAttributes() = checkInfo("""
<info>#[cfg_attr(foo)]</info>
fn <info>main</info>() {
<info>#![crate_type = <info>"lib"</info>]</info>
}
""")
fun testFieldsAndMethods() = checkInfo("""
struct <info>T</info>(<info>i32</info>);
struct <info>S</info>{ <info>field</info>: <info>T</info>}
fn <info>main</info>() {
let s = <info>S</info>{ <info>field</info>: <info>T</info>(92) };
s.<info>field</info>.0;
}
""")
fun testFunctions() = checkInfo("""
fn <info>main</info>() {}
struct <info>S</info>;
impl <info>S</info> {
fn <info>foo</info>() {}
}
trait <info>T</info> {
fn <info>foo</info>();
fn <info>bar</info>() {}
}
impl <info>T</info> for <info>S</info> {
fn <info>foo</info>() {}
}
""")
private val `$` = '$'
fun testMacro() = checkInfo("""
fn <info>main</info>() {
<info>println!</info>["Hello, World!"];
<info>unreachable!</info>();
}
<info>macro_rules!</info> foo {
(x => $`$`<info>e</info>:expr) => (println!("mode X: {}", $`$`<info>e</info>));
(y => $`$`<info>e</info>:expr) => (println!("mode Y: {}", $`$`<info>e</info>));
}
impl T {
<info>foo!</info>();
}
""")
fun testMutBinding() = checkInfo("""
fn <info>main</info>() {
let mut <info>a</info> = 1;
let b = <info>a</info>;
let Some(ref mut <info>c</info>) = Some(10);
let d = <info>c</info>;
}
""")
fun testTypeParameters() = checkInfo("""
trait <info>MyTrait</info> {
type <info>AssocType</info>;
fn <info>some_fn</info>(&<info>self</info>);
}
struct <info>MyStruct</info><<info>N</info>: ?<info>Sized</info>+<info>Debug</info>+<info><info>MyTrait</info></info>> {
<info>N</info>: my_field
}
""")
fun testFunctionArguments() = checkInfo("""
struct <info>Foo</info> {}
impl <info>Foo</info> {
fn <info>bar</info>(&<info>self</info>, (<info>i</info>, <info>j</info>): (<info>i32</info>, <info>i32</info>)) {}
}
fn <info>baz</info>(<info>u</info>: <info>u32</info>) {}
""")
fun testContextualKeywords() = checkInfo("""
trait <info>T</info> {
fn <info>foo</info>();
}
<info>union</info> <info>U</info> { }
impl <info>T</info> for <info>U</info> {
<info>default</info> fn <info>foo</info>() {}
}
""")
fun testQOperator() = checkInfo("""
fn <info>foo</info>() -> Result<<info>i32</info>, ()>{
Ok(Ok(1)<info>?</info> * 2)
}
""")
fun testTypeAlias() = checkInfo("""
type <info>Bar</info> = <info>u32</info>;
fn <info>main</info>() {
let a: <info>Bar</info> = 10;
}
""")
fun testSelfIsNotOverAnnotated() = checkInfo("""
pub use self::<info>foo</info>;
mod <info>foo</info> {
pub use self::<info>bar</info>;
pub mod <info>bar</info> {}
}
""")
fun testDontTouchAstInOtherFiles() {
val files = ProjectFile.parseFileCollection("""
//- main.rs
mod aux;
fn <info>main</info>() {
let _ = aux::<info>S</info>;
}
//- aux.rs
pub struct S;
""")
for ((path, text) in files) {
myFixture.tempDirFixture.createFile(path, text)
}
(myFixture as CodeInsightTestFixtureImpl) // meh
.setVirtualFileFilter { !it.path.endsWith(files[0].path) }
myFixture.configureFromTempProjectFile(files[0].path)
myFixture.testHighlighting(false, true, false)
}
}
| mit | 0e8ff4bddd1bc456fb66d7ab2f35423a | 29.110294 | 128 | 0.480098 | 3.617491 | false | true | false | false |
genobis/tornadofx | src/main/java/tornadofx/Validation.kt | 1 | 7076 | @file:Suppress("unused")
package tornadofx
import javafx.beans.binding.BooleanExpression
import javafx.beans.property.BooleanProperty
import javafx.beans.property.ReadOnlyBooleanProperty
import javafx.beans.property.SimpleBooleanProperty
import javafx.beans.value.ObservableValue
import javafx.collections.FXCollections
import javafx.scene.Node
import javafx.scene.control.TextInputControl
import kotlin.concurrent.thread
enum class ValidationSeverity { Error, Warning, Info, Success }
sealed class ValidationTrigger {
object OnBlur : ValidationTrigger()
class OnChange(val delay: Long = 0) : ValidationTrigger()
object None : ValidationTrigger()
}
class ValidationMessage(val message: String?, val severity: ValidationSeverity)
class ValidationContext {
val validators = FXCollections.observableArrayList<Validator<*>>()
/**
* The decoration provider decides what kind of decoration should be applied to
* a control when validation fails. The default decorator will paint a small triangle
* in the top left corner and display a Tooltip with the error message.
*/
var decorationProvider: (ValidationMessage) -> Decorator? = { SimpleMessageDecorator(it.message, it.severity) }
/**
* Add the given validator to the given property. The supplied node will be decorated by
* the current decorationProvider for this context if validation fails.
*
* The validator function is executed in the scope of this ValidationContex to give
* access to other fields and shortcuts like the error and warning functions.
*
* The validation trigger decides when the validation is applied. ValidationTrigger.OnBlur
* tracks focus on the supplied node while OnChange tracks changes to the property itself.
*/
inline fun <reified T> addValidator(
node: Node,
property: ObservableValue<T>,
trigger: ValidationTrigger = ValidationTrigger.OnChange(),
noinline validator: ValidationContext.(T?) -> ValidationMessage?) = addValidator(Validator(node, property, trigger, validator))
fun <T> addValidator(validator: Validator<T>, decorateErrors: Boolean = true): Validator<T> {
when (validator.trigger) {
is ValidationTrigger.OnChange -> {
var delayActive = false
validator.property.onChange {
if (validator.trigger.delay == 0L) {
validator.validate(decorateErrors)
} else {
if (!delayActive) {
delayActive = true
thread(true) {
Thread.sleep(validator.trigger.delay)
FX.runAndWait {
validator.validate(decorateErrors)
}
delayActive = false
}
}
}
}
}
is ValidationTrigger.OnBlur -> {
validator.node.focusedProperty().onChange {
if (!it) validator.validate(decorateErrors)
}
}
}
validators.add(validator)
return validator
}
/**
* A boolean indicating the current validation status.
*/
val valid: ReadOnlyBooleanProperty = SimpleBooleanProperty(true)
val isValid by valid
/**
* Rerun all validators (or just the ones passed in) and return a boolean indicating if validation passed.
*/
fun validate(vararg fields: ObservableValue<*>) = validate(true, true, fields = *fields)
/**
* Rerun all validators (or just the ones passed in) and return a boolean indicating if validation passed.
* It is allowed to pass inn fields that has no corresponding validator. They will register as validated.
*/
fun validate(focusFirstError: Boolean = true, decorateErrors: Boolean = true, vararg fields: ObservableValue<*>): Boolean {
var firstErrorFocused = false
var validationSucceeded = true
val validateThese = if (fields.isEmpty()) validators else validators.filter {
val facade = it.property.viewModelFacade
facade != null && facade in fields
}
for (validator in validateThese) {
if (!validator.validate(decorateErrors)) {
validationSucceeded = false
if (focusFirstError && !firstErrorFocused) {
firstErrorFocused = true
validator.node.requestFocus()
}
}
}
return validationSucceeded
}
/**
* Add validator for a TextInputControl and validate the control's textProperty. Useful when
* you don't bind against a ViewModel or other backing property.
*/
fun addValidator(node: TextInputControl, trigger: ValidationTrigger = ValidationTrigger.OnChange(), validator: ValidationContext.(String?) -> ValidationMessage?) =
addValidator<String>(node, node.textProperty(), trigger, validator)
fun error(message: String? = null) = ValidationMessage(message, ValidationSeverity.Error)
fun info(message: String? = null) = ValidationMessage(message, ValidationSeverity.Info)
fun warning(message: String? = null) = ValidationMessage(message, ValidationSeverity.Warning)
fun success(message: String? = null) = ValidationMessage(message, ValidationSeverity.Success)
/**
* Update the valid property state. If the calling validator was valid we need to see if any of the other properties are invalid.
* If the calling validator is invalid, we know the state is invalid so no need to check the other validators.
*/
internal fun updateValidState(callingValidatorState: Boolean) {
(valid as BooleanProperty).value = if (callingValidatorState) validators.find { !it.isValid } == null else false
}
inner class Validator<T>(
val node: Node,
val property: ObservableValue<T>,
val trigger: ValidationTrigger = ValidationTrigger.OnChange(),
val validator: ValidationContext.(T?) -> ValidationMessage?) {
var result: ValidationMessage? = null
var decorator: Decorator? = null
val valid: BooleanExpression = SimpleBooleanProperty(true)
val isValid: Boolean get() = valid.value
fun validate(decorateErrors: Boolean = true): Boolean {
decorator?.apply { undecorate(node) }
decorator = null
result = validator(this@ValidationContext, property.value)
(valid as BooleanProperty).value = result == null || result!!.severity != ValidationSeverity.Error
if (decorateErrors) {
result?.apply {
decorator = decorationProvider(this)
decorator!!.decorate(node)
}
}
updateValidState(isValid)
return isValid
}
}
} | apache-2.0 | 24c15d5c6604386ec429dcf16d7244cd | 40.385965 | 167 | 0.637366 | 5.300375 | false | false | false | false |
goodwinnk/intellij-community | platform/testGuiFramework/src/com/intellij/testGuiFramework/generators/Generators.kt | 1 | 35309 | /*
* 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.
*/
@file:Suppress("unused")
package com.intellij.testGuiFramework.generators
import com.intellij.icons.AllIcons
import com.intellij.ide.plugins.PluginTable
import com.intellij.ide.projectView.impl.ProjectViewTree
import com.intellij.openapi.actionSystem.impl.ActionButton
import com.intellij.openapi.actionSystem.impl.ActionMenu
import com.intellij.openapi.actionSystem.impl.ActionMenuItem
import com.intellij.openapi.actionSystem.impl.ActionToolbarImpl
import com.intellij.openapi.editor.impl.EditorComponentImpl
import com.intellij.openapi.ui.*
import com.intellij.openapi.util.Ref
import com.intellij.openapi.util.text.StringUtil
import com.intellij.openapi.wm.impl.IdeFrameImpl
import com.intellij.openapi.wm.impl.ToolWindowImpl
import com.intellij.openapi.wm.impl.ToolWindowManagerImpl
import com.intellij.openapi.wm.impl.WindowManagerImpl
import com.intellij.openapi.wm.impl.welcomeScreen.FlatWelcomeFrame
import com.intellij.testGuiFramework.cellReader.ExtendedJListCellReader
import com.intellij.testGuiFramework.cellReader.ExtendedJTableCellReader
import com.intellij.testGuiFramework.driver.CheckboxTreeDriver
import com.intellij.testGuiFramework.fixtures.MainToolbarFixture
import com.intellij.testGuiFramework.fixtures.MessagesFixture
import com.intellij.testGuiFramework.fixtures.NavigationBarFixture
import com.intellij.testGuiFramework.fixtures.SettingsTreeFixture
import com.intellij.testGuiFramework.fixtures.extended.getPathStrings
import com.intellij.testGuiFramework.framework.GuiTestUtil
import com.intellij.testGuiFramework.generators.Utils.clicks
import com.intellij.testGuiFramework.generators.Utils.convertSimpleTreeItemToPath
import com.intellij.testGuiFramework.generators.Utils.findBoundedText
import com.intellij.testGuiFramework.generators.Utils.getCellText
import com.intellij.testGuiFramework.generators.Utils.getJTreePath
import com.intellij.testGuiFramework.generators.Utils.getJTreePathItemsString
import com.intellij.testGuiFramework.generators.Utils.withRobot
import com.intellij.testGuiFramework.impl.GuiTestUtilKt.getComponentText
import com.intellij.testGuiFramework.impl.GuiTestUtilKt.isTextComponent
import com.intellij.testGuiFramework.impl.GuiTestUtilKt.onHeightCenter
import com.intellij.ui.CheckboxTree
import com.intellij.ui.EditorNotificationPanel
import com.intellij.ui.HyperlinkLabel
import com.intellij.ui.InplaceButton
import com.intellij.ui.components.JBCheckBox
import com.intellij.ui.components.JBList
import com.intellij.ui.components.JBTabbedPane
import com.intellij.ui.components.labels.ActionLink
import com.intellij.ui.components.labels.LinkLabel
import com.intellij.ui.messages.SheetController
import com.intellij.ui.tabs.impl.TabLabel
import com.intellij.ui.treeStructure.SimpleTree
import com.intellij.ui.treeStructure.treetable.TreeTable
import com.intellij.util.ui.tree.TreeUtil
import org.fest.reflect.core.Reflection.field
import org.fest.swing.core.BasicRobot
import org.fest.swing.core.ComponentMatcher
import org.fest.swing.core.GenericTypeMatcher
import org.fest.swing.core.Robot
import org.fest.swing.exception.ComponentLookupException
import java.awt.*
import java.awt.event.MouseEvent
import java.io.File
import java.net.URI
import java.nio.file.Paths
import java.util.*
import java.util.jar.JarFile
import javax.swing.*
import javax.swing.plaf.basic.BasicArrowButton
import javax.swing.tree.TreeNode
import javax.swing.tree.TreePath
//**********COMPONENT GENERATORS**********
private val leftButton = MouseEvent.BUTTON1
private val rightButton = MouseEvent.BUTTON3
private fun MouseEvent.isLeftButton() = (this.button == leftButton)
private fun MouseEvent.isRightButton() = (this.button == rightButton)
class JButtonGenerator : ComponentCodeGenerator<JButton> {
override fun accept(cmp: Component): Boolean = cmp is JButton
override fun generate(cmp: JButton, me: MouseEvent, cp: Point): String = """button("${cmp.text}").click()"""
}
class InplaceButtonGenerator : ComponentCodeGenerator<InplaceButton> {
override fun accept(cmp: Component): Boolean = cmp is InplaceButton
override fun generate(cmp: InplaceButton, me: MouseEvent, cp: Point): String = """inplaceButton(${getIconClassName(cmp)}).click()"""
private fun getIconClassName(inplaceButton: InplaceButton): String {
val icon = inplaceButton.icon
val iconField = AllIcons::class.java.classes.flatMap { it.fields.filter { it.type == Icon::class.java } }.firstOrNull {
it.get(null) is Icon && (it.get(null) as Icon) == icon
} ?: return "REPLACE IT WITH ICON $icon"
return "${iconField.declaringClass?.canonicalName}.${iconField.name}"
}
}
class JSpinnerGenerator : ComponentCodeGenerator<JButton> {
override fun accept(cmp: Component): Boolean = cmp.parent is JSpinner
override fun priority(): Int = 1
override fun generate(cmp: JButton, me: MouseEvent, cp: Point): String {
val labelText = Utils.getBoundedLabel(cmp.parent).text
return if (cmp.name.contains("nextButton"))
"""spinner("$labelText").increment()"""
else
"""spinner("$labelText").decrement()"""
}
}
class TreeTableGenerator : ComponentCodeGenerator<TreeTable> {
override fun accept(cmp: Component): Boolean = cmp is TreeTable
override fun generate(cmp: TreeTable, me: MouseEvent, cp: Point): String {
val path = cmp.tree.getClosestPathForLocation(cp.x, cp.y)
val treeStringPath = getJTreePath(cmp.tree, path)
val column = cmp.columnAtPoint(cp)
return """treeTable().clickColumn($column, $treeStringPath)"""
}
override fun priority(): Int = 10
}
class ComponentWithBrowseButtonGenerator : ComponentCodeGenerator<FixedSizeButton> {
override fun accept(cmp: Component): Boolean {
return cmp.parent.parent is ComponentWithBrowseButton<*>
}
override fun generate(cmp: FixedSizeButton, me: MouseEvent, cp: Point): String {
val componentWithBrowseButton = cmp.parent.parent
val labelText = Utils.getBoundedLabel(componentWithBrowseButton).text
return """componentWithBrowseButton("$labelText").clickButton()"""
}
}
class ActionButtonGenerator : ComponentCodeGenerator<ActionButton> {
override fun accept(cmp: Component): Boolean = cmp is ActionButton
override fun generate(cmp: ActionButton, me: MouseEvent, cp: Point): String {
val text = cmp.action.templatePresentation.text
val simpleClassName = cmp.action.javaClass.simpleName
val result: String = if (text.isNullOrEmpty())
"""actionButtonByClass("$simpleClassName").click()"""
else
"""actionButton("$text").click()"""
return result
}
}
class ActionLinkGenerator : ComponentCodeGenerator<ActionLink> {
override fun priority(): Int = 1
override fun accept(cmp: Component): Boolean = cmp is ActionLink
override fun generate(cmp: ActionLink, me: MouseEvent, cp: Point): String = """actionLink("${cmp.text}").click()"""
}
class JTextFieldGenerator : ComponentCodeGenerator<JTextField> {
override fun accept(cmp: Component): Boolean = cmp is JTextField
override fun generate(cmp: JTextField, me: MouseEvent, cp: Point): String = """textfield("${findBoundedText(cmp).orEmpty()}").${clicks(
me)}"""
}
class JBListGenerator : ComponentCodeGenerator<JBList<*>> {
override fun priority(): Int = 1
override fun accept(cmp: Component): Boolean = cmp is JBList<*>
private fun JBList<*>.isPopupList() = this.javaClass.name.toLowerCase().contains("listpopup")
private fun JBList<*>.isFrameworksTree() = this.javaClass.name.toLowerCase().contains("AddSupportForFrameworksPanel".toLowerCase())
override fun generate(cmp: JBList<*>, me: MouseEvent, cp: Point): String {
val cellText = getCellText(cmp, cp).orEmpty()
if (cmp.isPopupList()) return """popupMenu("$cellText").clickSearchedItem()"""
if (me.button == MouseEvent.BUTTON2) return """jList("$cellText").item("$cellText").rightClick()"""
if (me.clickCount == 2) return """jList("$cellText").doubleClickItem("$cellText")"""
return """jList("$cellText").clickItem("$cellText")"""
}
}
class BasicComboPopupGenerator : ComponentCodeGenerator<JList<*>> {
override fun accept(cmp: Component): Boolean = cmp is JList<*> && cmp.javaClass.name.contains("BasicComboPopup")
override fun generate(cmp: JList<*>, me: MouseEvent, cp: Point): String {
val cellText = getCellText(cmp, cp).orEmpty()
return """.selectItem("$cellText")""" // check that combobox is open
}
}
class CheckboxTreeGenerator : ComponentCodeGenerator<CheckboxTree> {
override fun accept(cmp: Component): Boolean = cmp is CheckboxTree
private fun JTree.getPath(cp: Point): TreePath = this.getClosestPathForLocation(cp.x, cp.y)
private fun wasClickOnCheckBox(cmp: CheckboxTree, cp: Point): Boolean {
val treePath = cmp.getPath(cp)
println("CheckboxTreeGenerator.wasClickOnCheckBox: treePath = ${treePath.path.joinToString()}")
return withRobot {
val checkboxComponent = CheckboxTreeDriver(it).getCheckboxComponent(cmp, treePath) ?: throw Exception(
"Checkbox component from cell renderer is null")
val pathBounds = cmp.getPathBounds(treePath)
val checkboxTreeBounds = Rectangle(pathBounds.x + checkboxComponent.x, pathBounds.y + checkboxComponent.y, checkboxComponent.width,
checkboxComponent.height)
checkboxTreeBounds.contains(cp)
}
}
override fun generate(cmp: CheckboxTree, me: MouseEvent, cp: Point): String {
val path = getJTreePath(cmp, cmp.getPath(cp))
return if (wasClickOnCheckBox(cmp, cp))
"checkboxTree($path).clickCheckbox()"
else
"checkboxTree($path).clickPath()"
}
}
class SimpleTreeGenerator : ComponentCodeGenerator<SimpleTree> {
override fun accept(cmp: Component): Boolean = cmp is SimpleTree
private fun SimpleTree.getPath(cp: Point) = convertSimpleTreeItemToPath(this, this.getDeepestRendererComponentAt(cp.x, cp.y).toString())
override fun generate(cmp: SimpleTree, me: MouseEvent, cp: Point): String {
val path = cmp.getPath(cp)
if (me.isRightButton()) return """jTree("$path").rightClickPath("$path")"""
return """jTree("$path").selectPath("$path")"""
}
}
class JTableGenerator : ComponentCodeGenerator<JTable> {
override fun accept(cmp: Component): Boolean = cmp is JTable
override fun generate(cmp: JTable, me: MouseEvent, cp: Point): String {
val row = cmp.rowAtPoint(cp)
val col = cmp.columnAtPoint(cp)
val cellText = ExtendedJTableCellReader().valueAt(cmp, row, col)
return """table("$cellText").cell("$cellText")""".addClick(me)
}
}
class JBCheckBoxGenerator : ComponentCodeGenerator<JBCheckBox> {
override fun priority(): Int = 1
override fun accept(cmp: Component): Boolean = cmp is JBCheckBox
override fun generate(cmp: JBCheckBox, me: MouseEvent, cp: Point): String = """checkbox("${cmp.text}").click()"""
}
class JCheckBoxGenerator : ComponentCodeGenerator<JCheckBox> {
override fun accept(cmp: Component): Boolean = cmp is JCheckBox
override fun generate(cmp: JCheckBox, me: MouseEvent, cp: Point): String = """checkbox("${cmp.text}").click()"""
}
class JComboBoxGenerator : ComponentCodeGenerator<JComboBox<*>> {
override fun accept(cmp: Component): Boolean = cmp is JComboBox<*>
override fun generate(cmp: JComboBox<*>, me: MouseEvent, cp: Point): String = """combobox("${findBoundedText(cmp).orEmpty()}")"""
}
class BasicArrowButtonDelegatedGenerator : ComponentCodeGenerator<BasicArrowButton> {
override fun priority(): Int = 1 //make sense if we challenge with simple jbutton
override fun accept(cmp: Component): Boolean = (cmp is BasicArrowButton) && (cmp.parent is JComboBox<*>)
override fun generate(cmp: BasicArrowButton, me: MouseEvent, cp: Point): String =
JComboBoxGenerator().generate(cmp.parent as JComboBox<*>, me, cp)
}
class JRadioButtonGenerator : ComponentCodeGenerator<JRadioButton> {
override fun accept(cmp: Component): Boolean = cmp is JRadioButton
override fun generate(cmp: JRadioButton, me: MouseEvent, cp: Point): String = """radioButton("${cmp.text}").select()"""
}
class LinkLabelGenerator : ComponentCodeGenerator<LinkLabel<*>> {
override fun accept(cmp: Component): Boolean = cmp is LinkLabel<*>
override fun generate(cmp: LinkLabel<*>, me: MouseEvent, cp: Point): String = """linkLabel("${cmp.text}").click()"""
}
class HyperlinkLabelGenerator : ComponentCodeGenerator<HyperlinkLabel> {
override fun accept(cmp: Component): Boolean = cmp is HyperlinkLabel
override fun generate(cmp: HyperlinkLabel, me: MouseEvent, cp: Point): String {
//we assume, that hyperlink label has only one highlighted region
val linkText = cmp.highlightedRegionsBoundsMap.keys.toList().firstOrNull() ?: "null"
return """hyperlinkLabel("${cmp.text}").clickLink("$linkText")"""
}
}
class HyperlinkLabelInNotificationPanelGenerator : ComponentCodeGenerator<HyperlinkLabel> {
override fun accept(cmp: Component): Boolean = cmp is HyperlinkLabel && cmp.hasInParents(EditorNotificationPanel::class.java)
override fun priority(): Int = 1
override fun generate(cmp: HyperlinkLabel, me: MouseEvent, cp: Point): String {
//we assume, that hyperlink label has only one highlighted region
val linkText = cmp.highlightedRegionsBoundsMap.keys.toList().firstOrNull() ?: "null"
return """editor { notificationPanel().clickLink("$linkText") }"""
}
}
class JTreeGenerator : ComponentCodeGenerator<JTree> {
override fun accept(cmp: Component): Boolean = cmp is JTree
private fun JTree.getPath(cp: Point) = this.getClosestPathForLocation(cp.x, cp.y)
override fun generate(cmp: JTree, me: MouseEvent, cp: Point): String {
val path = getJTreePath(cmp, cmp.getPath(cp))
if (me.isRightButton()) return "jTree($path).rightClickPath()"
return "jTree($path).clickPath()"
}
}
class ProjectViewTreeGenerator : ComponentCodeGenerator<ProjectViewTree> {
override fun priority(): Int = 1
override fun accept(cmp: Component): Boolean = cmp is ProjectViewTree
private fun JTree.getPath(cp: Point) = this.getClosestPathForLocation(cp.x, cp.y)
override fun generate(cmp: ProjectViewTree, me: MouseEvent, cp: Point): String {
val path = if(cmp.getPath(cp) != null) getJTreePathItemsString(cmp, cmp.getPath(cp)) else ""
if (me.isRightButton()) return "path($path).rightClick()"
if (me.clickCount == 2) return "path($path).doubleClick()"
return "path($path).click()"
}
}
class PluginTableGenerator : ComponentCodeGenerator<PluginTable> {
override fun accept(cmp: Component): Boolean = cmp is PluginTable
override fun generate(cmp: PluginTable, me: MouseEvent, cp: Point): String {
val row = cmp.rowAtPoint(cp)
val ideaPluginDescriptor = cmp.getObjectAt(row)
return """pluginTable().selectPlugin("${ideaPluginDescriptor.name}")"""
}
}
class EditorComponentGenerator : ComponentSelectionCodeGenerator<EditorComponentImpl> {
override fun generateSelection(cmp: EditorComponentImpl, firstPoint: Point, lastPoint: Point): String {
val editor = cmp.editor
val firstOffset = editor.logicalPositionToOffset(editor.xyToLogicalPosition(firstPoint))
val lastOffset = editor.logicalPositionToOffset(editor.xyToLogicalPosition(lastPoint))
return "select($firstOffset, $lastOffset)"
}
override fun accept(cmp: Component): Boolean = cmp is EditorComponentImpl
override fun generate(cmp: EditorComponentImpl, me: MouseEvent, cp: Point): String {
val editor = cmp.editor
val logicalPos = editor.xyToLogicalPosition(cp)
val offset = editor.logicalPositionToOffset(logicalPos)
return when (me.button) {
leftButton -> "moveTo($offset)"
rightButton -> "rightClick($offset)"
else -> "//not implemented editor action"
}
}
}
class ActionMenuItemGenerator : ComponentCodeGenerator<ActionMenuItem> {
override fun accept(cmp: Component): Boolean = cmp is ActionMenuItem
override fun generate(cmp: ActionMenuItem, me: MouseEvent, cp: Point): String =
"menu(${buildPath(activatedActionMenuItem = cmp).joinToString(separator = ", ") { str -> "\"$str\"" }}).click()"
//for buildnig a path of actionMenus and actionMenuItem we need to scan all JBPopup and find a consequence of actions from a tail. Each discovered JBPopupMenu added to hashSet to avoid double sacnning and multiple component finding results
private fun buildPath(activatedActionMenuItem: ActionMenuItem): List<String> {
val jbPopupMenuSet = HashSet<Int>()
jbPopupMenuSet.add(activatedActionMenuItem.parent.hashCode())
val path = ArrayList<String>()
var actionItemName = activatedActionMenuItem.text
path.add(actionItemName)
var window = activatedActionMenuItem.getNextPopupSHeavyWeightWindow()
while (window?.getNextPopupSHeavyWeightWindow() != null) {
window = window.getNextPopupSHeavyWeightWindow()
actionItemName = window!!.findJBPopupMenu(jbPopupMenuSet).findParentActionMenu(jbPopupMenuSet)
path.add(0, actionItemName)
}
return path
}
private fun Component.getNextPopupSHeavyWeightWindow(): JWindow? {
if (this.parent == null) return null
var cmp = this.parent
while (cmp != null && !cmp.javaClass.name.endsWith("Popup\$HeavyWeightWindow")) cmp = cmp.parent
if (cmp == null) return null
return cmp as JWindow
}
private fun JWindow.findJBPopupMenu(jbPopupHashSet: MutableSet<Int>): JBPopupMenu {
return withRobot { robot ->
val resultJBPopupMenu = robot.finder().find(this, ComponentMatcher { component ->
(component is JBPopupMenu)
&& component.isShowing
&& component.isVisible
&& !jbPopupHashSet.contains(component.hashCode())
}) as JBPopupMenu
jbPopupHashSet.add(resultJBPopupMenu.hashCode())
resultJBPopupMenu
}
}
private fun JBPopupMenu.findParentActionMenu(jbPopupHashSet: MutableSet<Int>): String {
val actionMenu = this.subElements
.filterIsInstance(ActionMenu::class.java)
.find { actionMenu ->
actionMenu.subElements != null && actionMenu.subElements.isNotEmpty() && actionMenu.subElements.any { menuElement ->
menuElement is JBPopupMenu && jbPopupHashSet.contains(menuElement.hashCode())
}
} ?: throw Exception("Unable to find a proper ActionMenu")
return actionMenu.text
}
}
//**********GLOBAL CONTEXT GENERATORS**********
class WelcomeFrameGenerator : GlobalContextCodeGenerator<FlatWelcomeFrame>() {
override fun priority(): Int = 1
override fun accept(cmp: Component): Boolean = cmp is JComponent && cmp.rootPane?.parent is FlatWelcomeFrame
override fun generate(cmp: FlatWelcomeFrame): String {
return "welcomeFrame {"
}
}
class JDialogGenerator : GlobalContextCodeGenerator<JDialog>() {
override fun accept(cmp: Component): Boolean {
if (cmp !is JComponent || cmp.rootPane == null || cmp.rootPane.parent == null || cmp.rootPane.parent !is JDialog) return false
val dialog = cmp.rootPane.parent as JDialog
if (dialog.title == "This should not be shown") return false //do not add context for a SheetMessages on Mac
return true
}
override fun generate(cmp: JDialog): String = """dialog("${cmp.title}") {"""
}
class IdeFrameGenerator : GlobalContextCodeGenerator<JFrame>() {
override fun accept(cmp: Component): Boolean {
if (cmp !is JComponent) return false
val parent = cmp.rootPane.parent
return (parent is JFrame) && parent.title != "GUI Script Editor"
}
override fun generate(cmp: JFrame): String = "ideFrame {"
}
class TabbedPaneGenerator : ComponentCodeGenerator<Component> {
override fun priority(): Int = 2
override fun generate(cmp: Component, me: MouseEvent, cp: Point): String {
val tabbedPane = when {
cmp.parent.parent is JBTabbedPane -> cmp.parent.parent as JTabbedPane
else -> cmp.parent as JTabbedPane
}
val selectedTabIndex = tabbedPane.indexAtLocation(me.locationOnScreen.x - tabbedPane.locationOnScreen.x,
me.locationOnScreen.y - tabbedPane.locationOnScreen.y)
val title = tabbedPane.getTitleAt(selectedTabIndex)
return """tab("${title}").selectTab()"""
}
override fun accept(cmp: Component): Boolean = cmp.parent.parent is JBTabbedPane || cmp.parent is JBTabbedPane
}
//**********LOCAL CONTEXT GENERATORS**********
class ProjectViewGenerator : LocalContextCodeGenerator<JPanel>() {
override fun priority(): Int = 0
override fun isLastContext(): Boolean = true
override fun acceptor(): (Component) -> Boolean = { component -> component.javaClass.name.endsWith("ProjectViewImpl\$MyPanel") }
override fun generate(cmp: JPanel): String = "projectView {"
}
class ToolWindowGenerator : LocalContextCodeGenerator<Component>() {
override fun priority(): Int = 0
private fun Component.containsLocationOnScreen(locationOnScreen: Point): Boolean {
val rectangle = this.bounds
rectangle.location = this.locationOnScreen
return rectangle.contains(locationOnScreen)
}
private fun Component.centerOnScreen(): Point? {
val rectangle = this.bounds
rectangle.location = try {
this.locationOnScreen
}
catch (e: IllegalComponentStateException) {
return null
}
return Point(rectangle.centerX.toInt(), rectangle.centerY.toInt())
}
private fun getToolWindow(pointOnScreen: Point): ToolWindowImpl? {
if (WindowManagerImpl.getInstance().findVisibleFrame() !is IdeFrameImpl) return null
val ideFrame = WindowManagerImpl.getInstance().findVisibleFrame() as IdeFrameImpl
ideFrame.project ?: return null
val toolWindowManager = ToolWindowManagerImpl.getInstance(ideFrame.project!!)
val visibleToolWindows = toolWindowManager.toolWindowIds
.map { toolWindowId -> toolWindowManager.getToolWindow(toolWindowId) }
.filter { toolwindow -> toolwindow.isVisible }
return visibleToolWindows.filterIsInstance<ToolWindowImpl>().find { it.component.containsLocationOnScreen(pointOnScreen) }
}
override fun acceptor(): (Component) -> Boolean = { component ->
val centerOnScreen = component.centerOnScreen()
if (centerOnScreen != null) {
val tw = getToolWindow(centerOnScreen)
tw != null && component == tw.component
}
else false
}
override fun generate(cmp: Component): String {
val pointOnScreen = cmp.centerOnScreen() ?: throw IllegalComponentStateException("Unable to get center on screen for component: $cmp")
val toolWindow: ToolWindowImpl = getToolWindow(pointOnScreen)!!
return """toolwindow(id = "${toolWindow.id}") {"""
}
}
class ToolWindowContextGenerator : LocalContextCodeGenerator<Component>() {
override fun priority(): Int = 2
private fun Component.containsLocationOnScreen(locationOnScreen: Point): Boolean {
val rectangle = this.bounds
rectangle.location = this.locationOnScreen
return rectangle.contains(locationOnScreen)
}
private fun Component.centerOnScreen(): Point? {
val rectangle = this.bounds
rectangle.location = try {
this.locationOnScreen
}
catch (e: IllegalComponentStateException) {
return null
}
return Point(rectangle.centerX.toInt(), rectangle.centerY.toInt())
}
private fun Component.contains(component: Component): Boolean {
return this.contains(Point(component.bounds.x, component.bounds.y)) &&
this.contains(Point(component.bounds.x + component.width, component.bounds.y + component.height))
}
private fun getToolWindow(pointOnScreen: Point): ToolWindowImpl? {
if (WindowManagerImpl.getInstance().findVisibleFrame() !is IdeFrameImpl) return null
val ideFrame = WindowManagerImpl.getInstance().findVisibleFrame() as IdeFrameImpl
ideFrame.project ?: return null
val toolWindowManager = ToolWindowManagerImpl.getInstance(ideFrame.project!!)
val visibleToolWindows = toolWindowManager.toolWindowIds
.map { toolWindowId -> toolWindowManager.getToolWindow(toolWindowId) }
.filter { toolwindow -> toolwindow.isVisible }
return visibleToolWindows.filterIsInstance<ToolWindowImpl>().find { it.component.containsLocationOnScreen(pointOnScreen) }
}
override fun acceptor(): (Component) -> Boolean = { component ->
val pointOnScreen = component.centerOnScreen()
if (pointOnScreen != null) {
val tw = getToolWindow(pointOnScreen)
tw != null && tw.contentManager.selectedContent!!.component == component
}
else false
}
override fun generate(cmp: Component): String {
val toolWindow: ToolWindowImpl = getToolWindow(cmp.centerOnScreen()!!)!!
val tabName = toolWindow.contentManager.selectedContent?.tabName
return if (tabName != null) """content(tabName = "${tabName}") {"""
else "content {"
}
}
class MacMessageGenerator : LocalContextCodeGenerator<JButton>() {
override fun priority(): Int = 2
private fun acceptMacSheetPanel(cmp: Component): Boolean {
if (cmp !is JComponent) return false
if (!(Messages.canShowMacSheetPanel() && cmp.rootPane.parent is JDialog)) return false
val panel = cmp.rootPane.contentPane as JPanel
if (panel.javaClass.name.startsWith(SheetController::class.java.name) && panel.isShowing) {
val controller = MessagesFixture.findSheetController(panel)
val sheetPanel = field("mySheetPanel").ofType(JPanel::class.java).`in`(controller).get()
if (sheetPanel === panel) {
return true
}
}
return false
}
override fun acceptor(): (Component) -> Boolean = { component -> acceptMacSheetPanel(component) }
override fun generate(cmp: JButton): String {
val panel = cmp.rootPane.contentPane as JPanel
val title = withRobot { robot -> MessagesFixture.getTitle(panel, robot) }
return """message("$title") {"""
}
}
class MessageGenerator : LocalContextCodeGenerator<JDialog>() {
override fun priority(): Int = 2
override fun acceptor(): (Component) -> Boolean = { cmp ->
cmp is JDialog && MessagesFixture.isMessageDialog(cmp)
}
override fun generate(cmp: JDialog): String {
return """message("${cmp.title}") {"""
}
}
class EditorGenerator : LocalContextCodeGenerator<EditorComponentImpl>() {
override fun priority(): Int = 3
override fun acceptor(): (Component) -> Boolean = { component -> component is EditorComponentImpl }
override fun generate(cmp: EditorComponentImpl): String = "editor {"
}
class MainToolbarGenerator : LocalContextCodeGenerator<ActionToolbarImpl>() {
override fun acceptor(): (Component) -> Boolean = { component ->
component is ActionToolbarImpl
&& MainToolbarFixture.isMainToolbar(component)
}
override fun generate(cmp: ActionToolbarImpl): String = "toolbar {"
}
class NavigationBarGenerator : LocalContextCodeGenerator<JPanel>() {
override fun acceptor(): (Component) -> Boolean = { component ->
component is JPanel
&& NavigationBarFixture.isNavBar(component)
}
override fun generate(cmp: JPanel): String = "navigationBar {"
}
class TabGenerator : LocalContextCodeGenerator<TabLabel>() {
override fun acceptor(): (Component) -> Boolean = { component ->
component is TabLabel
}
override fun generate(cmp: TabLabel): String = "editor(\"" + cmp.info.text + "\") {"
}
//class JBPopupMenuGenerator: LocalContextCodeGenerator<JBPopupMenu>() {
//
// override fun acceptor(): (Component) -> Boolean = { component -> component is JBPopupMenu}
// override fun generate(cmp: JBPopupMenu, me: MouseEvent, cp: Point) = "popupMenu {"
//}
object Generators {
fun getGenerators(): List<ComponentCodeGenerator<*>> {
val generatorClassPaths = getSiblingsList().filter { path -> path.endsWith("Generator.class") }
val classLoader = Generators.javaClass.classLoader
return generatorClassPaths
.map { clzPath -> classLoader.loadClass("${Generators.javaClass.`package`.name}.${File(clzPath).nameWithoutExtension}") }
.filter { clz -> ComponentCodeGenerator::class.java.isAssignableFrom(clz) && !clz.isInterface }
.map(Class<*>::newInstance)
.filterIsInstance(ComponentCodeGenerator::class.java)
}
fun getGlobalContextGenerators(): List<GlobalContextCodeGenerator<*>> {
val generatorClassPaths = getSiblingsList().filter { path -> path.endsWith("Generator.class") }
val classLoader = Generators.javaClass.classLoader
return generatorClassPaths
.map { clzPath -> classLoader.loadClass("${Generators.javaClass.`package`.name}.${File(clzPath).nameWithoutExtension}") }
.filter { clz -> clz.superclass == GlobalContextCodeGenerator::class.java }
.map(Class<*>::newInstance)
.filterIsInstance(GlobalContextCodeGenerator::class.java)
}
fun getLocalContextCodeGenerator(): List<LocalContextCodeGenerator<*>> {
val generatorClassPaths = getSiblingsList().filter { path -> path.endsWith("Generator.class") }
val classLoader = Generators.javaClass.classLoader
return generatorClassPaths
.map { clzPath -> classLoader.loadClass("${Generators.javaClass.`package`.name}.${File(clzPath).nameWithoutExtension}") }
.filter { clz -> clz.superclass == LocalContextCodeGenerator::class.java }
.map(Class<*>::newInstance)
.filterIsInstance(LocalContextCodeGenerator::class.java)
}
private fun getSiblingsList(): List<String> {
val path = "/${Generators.javaClass.`package`.name.replace(".", "/")}"
val url = Generators.javaClass.getResource(path)
if (url.path.contains(".jar!")) {
val jarFile = JarFile(Paths.get(URI(url.file.substringBefore(".jar!").plus(".jar"))).toString())
val entries = jarFile.entries()
val genPath = url.path.substringAfter(".jar!").removePrefix("/")
return entries.toList().filter { entry -> entry.name.contains(genPath) }.map { entry -> entry.name }
}
else return File(url.toURI()).listFiles().map { file -> file.toURI().path }
}
}
object Utils {
fun getLabel(container: Container, jTextField: JTextField): JLabel? {
return withRobot { robot -> GuiTestUtil.findBoundedLabel(container, jTextField, robot) }
}
fun getLabel(jTextField: JTextField): JLabel? {
val parentContainer = jTextField.rootPane.parent
return withRobot { robot -> GuiTestUtil.findBoundedLabel(parentContainer, jTextField, robot) }
}
fun clicks(me: MouseEvent): String {
if (me.clickCount == 1) return "click()"
if (me.clickCount == 2) return "doubleClick()"
return ""
}
fun getCellText(jList: JList<*>, pointOnList: Point): String? {
return withRobot { robot ->
val extCellReader = ExtendedJListCellReader()
val index = jList.locationToIndex(pointOnList)
extCellReader.valueAt(jList, index)
}
}
fun convertSimpleTreeItemToPath(tree: SimpleTree, itemName: String): String {
val searchableNodeRef = Ref.create<TreeNode>()
val searchableNode: TreeNode?
TreeUtil.traverse(tree.model.root as TreeNode) { node ->
val valueFromNode = SettingsTreeFixture.getValueFromNode(tree, node)
if (valueFromNode != null && valueFromNode == itemName) {
assert(node is TreeNode)
searchableNodeRef.set(node as TreeNode)
}
true
}
searchableNode = searchableNodeRef.get()
val path = TreeUtil.getPathFromRoot(searchableNode!!)
return (0 until path.pathCount).map { path.getPathComponent(it).toString() }.filter(String::isNotEmpty).joinToString("/")
}
fun getBoundedLabel(component: Component): JLabel {
return getBoundedLabelRecursive(component, component.parent)
}
private fun getBoundedLabelRecursive(component: Component, parent: Component): JLabel {
val boundedLabel = findBoundedLabel(component, parent)
if (boundedLabel != null) return boundedLabel
else {
if (parent.parent == null) throw ComponentLookupException("Unable to find bounded label")
return getBoundedLabelRecursive(component, parent.parent)
}
}
private fun findBoundedLabel(component: Component, componentParent: Component): JLabel? {
return withRobot { robot ->
var resultLabel: JLabel?
if (componentParent is LabeledComponent<*>) resultLabel = componentParent.label
else {
try {
resultLabel = robot.finder().find(componentParent as Container, object : GenericTypeMatcher<JLabel>(JLabel::class.java) {
override fun isMatching(label: JLabel) = (label.labelFor != null && label.labelFor == component)
})
}
catch (e: ComponentLookupException) {
resultLabel = null
}
}
resultLabel
}
}
fun findBoundedText(target: Component): String? {
//let's try to find bounded label firstly
try {
return getBoundedLabel(target).text
}
catch (_: ComponentLookupException) {
}
return findBoundedTextRecursive(target, target.parent)
}
private fun findBoundedTextRecursive(target: Component, parent: Component): String? {
val boundedText = findBoundedText(target, parent)
if (boundedText != null)
return boundedText
else
if (parent.parent != null) return findBoundedTextRecursive(target, parent.parent)
else return null
}
private fun findBoundedText(target: Component, container: Component): String? {
val textComponents = withRobot { robot ->
robot.finder().findAll(container as Container, ComponentMatcher { component ->
component!!.isShowing && component.isTextComponent() && target.onHeightCenter(component, true)
})
}
if (textComponents.isEmpty()) return null
//if more than one component is found let's take the righter one
return textComponents.sortedBy { it.bounds.x + it.bounds.width }.last().getComponentText()
}
fun getJTreePath(cmp: JTree, path: TreePath): String {
val pathArray = path.getPathStrings(cmp)
return pathArray.joinToString(separator = ", ", transform = { str -> "\"$str\"" })
}
fun getJTreePathItemsString(cmp: JTree, path: TreePath): String {
return path.getPathStrings(cmp)
.map { StringUtil.wrapWithDoubleQuote(it) }
.reduceRight { s, s1 -> "$s, $s1" }
}
fun <ReturnType> withRobot(robotFunction: (Robot) -> ReturnType): ReturnType {
val robot = BasicRobot.robotWithCurrentAwtHierarchyWithoutScreenLock()
return robotFunction(robot)
}
}
private fun String.addClick(me: MouseEvent): String {
return when {
me.isLeftButton() && me.clickCount == 2 -> "$this.doubleClick()"
me.isRightButton() -> "$this.rightClick()"
else -> "$this.click()"
}
}
private fun Component.hasInParents(componentType: Class<out Component>): Boolean {
var component = this
while (component.parent != null) {
if (componentType.isInstance(component)) return true
component = component.parent
}
return false
}
| apache-2.0 | f4ac6c09fadc79d8b8398d8d2dfae577 | 41.134845 | 241 | 0.728115 | 4.741372 | false | false | false | false |
bozaro/git-as-svn | src/main/kotlin/svnserver/VersionInfo.kt | 1 | 1807 | /*
* This file is part of git-as-svn. It is subject to the license terms
* in the LICENSE file found in the top-level directory of this distribution
* and at http://www.gnu.org/licenses/gpl-2.0.html. No part of git-as-svn,
* including this file, may be copied, modified, propagated, or distributed
* except according to the terms contained in the LICENSE file.
*/
package svnserver
import java.io.IOException
import java.util.*
/**
* Version information.
*
* @author Artem V. Navrotskiy <[email protected]>
*/
class VersionInfo private constructor() {
private var revision: String? = null
private var tag: String? = null
companion object {
private val s_instance: VersionInfo = VersionInfo()
val versionInfo: String
get() {
if (s_instance.revision == null) return "none version info"
if (s_instance.tag == null) return s_instance.revision!!
return s_instance.tag + ", " + s_instance.revision
}
private fun getProperty(props: Properties, name: String, defaultValue: String?): String {
val value: String? = props.getProperty(name)
return if (value != null && !value.startsWith("\${")) value else (defaultValue)!!
}
}
init {
try {
javaClass.getResourceAsStream("VersionInfo.properties").use { stream ->
if (stream == null) {
throw IllegalStateException()
}
val props = Properties()
props.load(stream)
revision = getProperty(props, "revision", null)
tag = getProperty(props, "tag", null)
}
} catch (e: IOException) {
throw IllegalStateException(e)
}
}
}
| gpl-2.0 | af3e66c1319dee4dfd5fe452071c67e5 | 33.75 | 97 | 0.595462 | 4.506234 | false | false | false | false |
arturbosch/TiNBo | tinbo-finance/src/main/kotlin/io/gitlab/arturbosch/tinbo/finance/FinanceCommands.kt | 1 | 6058 | package io.gitlab.arturbosch.tinbo.finance
import io.gitlab.arturbosch.tinbo.api.TinboTerminal
import io.gitlab.arturbosch.tinbo.api.commands.EditableCommands
import io.gitlab.arturbosch.tinbo.api.config.Defaults
import io.gitlab.arturbosch.tinbo.api.config.ModeManager
import io.gitlab.arturbosch.tinbo.api.marker.Summarizable
import io.gitlab.arturbosch.tinbo.api.nullIfEmpty
import io.gitlab.arturbosch.tinbo.api.orDefaultMonth
import io.gitlab.arturbosch.tinbo.api.orThrow
import io.gitlab.arturbosch.tinbo.api.orValue
import io.gitlab.arturbosch.tinbo.api.utils.dateFormatter
import io.gitlab.arturbosch.tinbo.api.utils.dateTimeFormatter
import org.joda.money.Money
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.shell.core.annotation.CliAvailabilityIndicator
import org.springframework.shell.core.annotation.CliCommand
import org.springframework.shell.core.annotation.CliOption
import org.springframework.stereotype.Component
import java.time.LocalDate
import java.time.LocalDateTime
import java.time.Month
import java.time.format.DateTimeParseException
/**
* @author artur
*/
@Component
class FinanceCommands @Autowired constructor(private val financeExecutor: FinanceExecutor,
private val configProvider: ConfigProvider,
terminal: TinboTerminal) :
EditableCommands<FinanceEntry, FinanceData, DummyFinance>(financeExecutor, terminal), Summarizable {
override val id: String = FinanceMode.id
private val successMessage = "Successfully added a finance entry."
@CliAvailabilityIndicator("year", "mean", "deviation", "loadFinance")
fun isAvailable(): Boolean {
return ModeManager.isCurrentMode(FinanceMode)
}
@CliCommand("loadFinance", help = "Loads/Creates an other data set. Finance data sets are stored under ~/tinbo/finance/*.")
fun loadTasks(@CliOption(key = ["", "name"], mandatory = true,
specifiedDefaultValue = Defaults.FINANCE_NAME,
unspecifiedDefaultValue = Defaults.FINANCE_NAME) name: String) {
executor.loadData(name)
}
@CliCommand("year", "yearSummary", help = "Sums up the year by providing expenditure per month.")
fun yearSummary(@CliOption(key = ["last"], mandatory = false,
specifiedDefaultValue = "true", unspecifiedDefaultValue = "false") lastYear: Boolean,
@CliOption(key = [""], mandatory = false,
specifiedDefaultValue = "-1", unspecifiedDefaultValue = "-1") year: Int): String {
return withValidDate(year, lastYear) {
financeExecutor.yearSummary(it)
}
}
@CliCommand("mean", help = "Provides the mean expenditure per month for current or specified year.")
fun means(@CliOption(key = ["last"], mandatory = false,
specifiedDefaultValue = "true", unspecifiedDefaultValue = "false") lastYear: Boolean,
@CliOption(key = [""], mandatory = false,
specifiedDefaultValue = "-1", unspecifiedDefaultValue = "-1") year: Int): String {
return withValidDate(year, lastYear) {
financeExecutor.yearSummaryMean(it)
}
}
@CliCommand("deviation", help = "Provides the expenditure deviation per month for current or specified year.")
fun deviation(@CliOption(key = ["last"], mandatory = false,
specifiedDefaultValue = "true", unspecifiedDefaultValue = "false") lastYear: Boolean,
@CliOption(key = [""], mandatory = false,
specifiedDefaultValue = "-1", unspecifiedDefaultValue = "-1") year: Int): String {
return withValidDate(year, lastYear) {
financeExecutor.yearSummaryDeviation(it)
}
}
private fun withValidDate(year: Int, lastYear: Boolean, block: (LocalDate) -> String): String {
val now = LocalDate.now()
if (year != -1 && (year < 2000 || year > now.year + 20)) {
return "Entered date must be not too far in the past (> 2000) or in the future ( < now + 20)!"
}
val date = if (lastYear) now.minusYears(1) else if (year == -1) now else LocalDate.of(year, 1, 1)
return block.invoke(date)
}
override fun sum(categories: Set<String>, categoryFilters: Set<String>): String =
financeExecutor.sumCategories(categories, categoryFilters)
override fun add(): String {
return whileNotInEditMode {
val month = Month.of(console.readLine("Enter a month as number from 1-12 (empty if this month): ").orDefaultMonth())
val category = console.readLine("Enter a category: ").orValue(configProvider.categoryName)
val message = console.readLine("Enter a message: ")
val money = Money.of(configProvider.currencyUnit, console.readLine("Enter a money value: ").orThrow().toDouble())
val dateString = console.readLine("Enter a end time (yyyy-MM-dd HH:mm): ")
val dateTime = parseDateTime(dateString)
executor.addEntry(FinanceEntry(month, category, message, money, dateTime))
successMessage
}
}
private fun parseDateTime(dateString: String): LocalDateTime {
return if (dateString.isEmpty()) {
LocalDateTime.now()
} else {
try {
LocalDateTime.parse(dateString, dateTimeFormatter)
} catch (ex: DateTimeParseException) {
LocalDate.parse(dateString, dateFormatter).atTime(0, 0)
}
}
}
override fun edit(index: Int): String {
return withinListMode {
val i = index - 1
enterEditModeWithIndex(i) {
val monthString = console.readLine("Enter a month as number from 1-12 (empty if this month) (leave empty if unchanged): ")
val month = if (monthString.isEmpty()) null else Month.of(monthString.orDefaultMonth())
val category = console.readLine("Enter a category (leave empty if unchanged): ").nullIfEmpty()
val message = console.readLine("Enter a message (leave empty if unchanged): ").nullIfEmpty()
val moneyString = console.readLine("Enter a money value (leave empty if unchanged): ")
val money = if (moneyString.isEmpty()) null else Money.of(configProvider.currencyUnit, moneyString.toDouble())
val dateString = console.readLine("Enter a end time (yyyy-MM-dd HH:mm) (leave empty if unchanged): ")
val dateTime = parseDateTime(dateString)
executor.editEntry(i, DummyFinance(category, message, month, money, dateTime))
"Successfully edited a finance entry."
}
}
}
}
| apache-2.0 | d5fc65cee933b97827390db639e7482e | 42.898551 | 126 | 0.741004 | 3.856143 | false | true | false | false |
synyx/calenope | modules/organizer/src/main/kotlin/de/synyx/calenope/organizer/component/Layouts.kt | 1 | 6608 | package de.synyx.calenope.organizer.component
import android.support.design.widget.AppBarLayout
import android.support.design.widget.AppBarLayout.Behavior
import android.support.design.widget.CollapsingToolbarLayout
import android.support.design.widget.CoordinatorLayout
import android.support.design.widget.FloatingActionButton
import android.support.v4.widget.SwipeRefreshLayout
import android.support.v7.widget.Toolbar
import android.view.Gravity
import android.widget.LinearLayout
import de.synyx.calenope.organizer.R
import trikita.anvil.DSL.MATCH
import trikita.anvil.DSL.WRAP
import trikita.anvil.DSL.dip
import trikita.anvil.DSL.id
import trikita.anvil.DSL.layoutParams
import trikita.anvil.DSL.margin
import trikita.anvil.DSL.onClick
import trikita.anvil.DSL.onLongClick
import trikita.anvil.DSL.orientation
import trikita.anvil.DSL.size
import trikita.anvil.DSL.visibility
import trikita.anvil.appcompat.v7.AppCompatv7DSL.popupTheme
import trikita.anvil.appcompat.v7.AppCompatv7DSL.toolbar
import trikita.anvil.design.DesignDSL.appBarLayout
import trikita.anvil.design.DesignDSL.collapsingToolbarLayout
import trikita.anvil.design.DesignDSL.coordinatorLayout
import trikita.anvil.design.DesignDSL.expanded
import trikita.anvil.design.DesignDSL.floatingActionButton
import trikita.anvil.design.DesignDSL.title
import trikita.anvil.design.DesignDSL.titleEnabled
import trikita.anvil.support.v4.Supportv4DSL.onRefresh
import trikita.anvil.support.v4.Supportv4DSL.swipeRefreshLayout
/**
* @author clausen - [email protected]
*/
object Layouts {
private val scrolling by lazy {
val params = CoordinatorLayout.LayoutParams (MATCH, MATCH)
params.behavior = AppBarLayout.ScrollingViewBehavior ()
params
}
class Regular (
private val fab : Element<FloatingActionButton>.() -> Unit = {},
private val content : Element<SwipeRefreshLayout>.() -> Unit = {},
private val toolbar : Element<Toolbar>.() -> Unit = {}
) : Component () {
override fun view () = pin ("layout") {
Collapsible (
fab = fab,
content = content,
toolbar = toolbar,
collapsible = {
always += {
title ("")
titleEnabled (false)
}
}
)
}
}
class Collapsible (
private val draggable : Boolean = false,
private val fab : Element<FloatingActionButton>.() -> Unit = {},
private val content : Element<SwipeRefreshLayout>.() -> Unit = {},
private val appbar : Element<AppBarLayout>.() -> Unit = {},
private val toolbar : Element<Toolbar>.() -> Unit = {},
private val collapsible : Element<CollapsingToolbarLayout>.() -> Unit = {}
) : Component () {
override fun view () {
coordinatorLayout {
size (MATCH, MATCH)
orientation (LinearLayout.VERTICAL)
appBarLayout {
configure<AppBarLayout> {
once += {
val behavior = Behavior ()
behavior.setDragCallback (drag (draggable))
val params = layoutParams as CoordinatorLayout.LayoutParams
params.behavior = behavior
}
always += {
size (MATCH, WRAP)
expanded (false)
}
appbar (this)
}
collapsingToolbarLayout {
configure<CollapsingToolbarLayout> {
once += {
val params = layoutParams as AppBarLayout.LayoutParams
params.scrollFlags = params.scrollFlags or AppBarLayout.LayoutParams.SCROLL_FLAG_EXIT_UNTIL_COLLAPSED
}
always += {
size (MATCH, MATCH)
titleEnabled (true)
}
collapsible (this)
}
toolbar {
configure<Toolbar> {
once += {
val params = layoutParams as CollapsingToolbarLayout.LayoutParams
params.collapseMode = CollapsingToolbarLayout.LayoutParams.COLLAPSE_MODE_PIN
elevation = -1.0f
}
always += {
size (MATCH, dip (56))
popupTheme (R.style.AppTheme_PopupOverlay)
}
toolbar (this)
}
}
}
}
swipeRefreshLayout {
configure<SwipeRefreshLayout> {
always += {
id ("content".viewID ())
layoutParams (scrolling)
size (MATCH, MATCH)
onRefresh {}
}
content (this)
}
}
floatingActionButton {
configure<FloatingActionButton> {
once += {
val params = layoutParams as CoordinatorLayout.LayoutParams
params.anchorId = "content".viewID ()
params.anchorGravity = Gravity.BOTTOM or Gravity.END
}
always += {
visibility (false)
size (WRAP, WRAP)
margin (dip (16))
onClick {}
onLongClick { false }
}
fab (this)
}
}
}
}
}
private fun drag (draggable : Boolean) : Behavior.DragCallback {
return object : Behavior.DragCallback () {
override fun canDrag (layout : AppBarLayout) : Boolean = draggable
}
}
} | apache-2.0 | d78866cf70452e5ccca1a78a56fb72fc | 35.114754 | 137 | 0.493795 | 6.141264 | false | false | false | false |
soywiz/korge | korge/src/commonMain/kotlin/com/soywiz/korge/bitmapfont/BitmapFontExt.kt | 1 | 2934 | package com.soywiz.korge.bitmapfont
import com.soywiz.korge.html.*
import com.soywiz.korge.internal.*
import com.soywiz.korge.render.*
import com.soywiz.korge.view.*
import com.soywiz.korim.color.*
import com.soywiz.korim.font.*
import com.soywiz.korma.geom.*
import kotlin.math.*
fun Font.getBounds(text: String, format: Html.Format, out: Rectangle = Rectangle()): Rectangle {
//val font = getBitmapFont(format.computedFace, format.computedSize)
val font = this
val textSize = format.computedSize.toDouble()
var width = 0.0
var height = 0.0
var dy = 0.0
var dx = 0.0
val glyph = GlyphMetrics()
val fmetrics = font.getFontMetrics(textSize)
for (n in 0 until text.length) {
val c1 = text[n].toInt()
if (c1 == '\n'.toInt()) {
dx = 0.0
dy += fmetrics.lineHeight
height = max(height, dy)
continue
}
var c2: Int = ' '.toInt()
if (n + 1 < text.length) c2 = text[n + 1].toInt()
val kerningOffset = font.getKerning(textSize, c1, c2)
val glyph = font.getGlyphMetrics(textSize, c1, glyph)
dx += glyph.xadvance + kerningOffset
width = max(width, dx)
}
height += fmetrics.lineHeight
//val scale = textSize / font.fontSize.toDouble()
//out.setTo(0.0, 0.0, width * scale, height * scale)
out.setTo(0.0, 0.0, width, height)
return out
}
fun BitmapFont.drawText(
ctx: RenderContext,
textSize: Double,
str: String,
x: Int,
y: Int,
m: Matrix = Matrix(),
colMul: RGBA = Colors.WHITE,
colAdd: ColorAdd = ColorAdd.NEUTRAL,
blendMode: BlendMode = BlendMode.INHERIT,
filtering: Boolean = true
) {
val m2 = m.clone()
val scale = textSize / fontSize.toDouble()
m2.pretranslate(x.toDouble(), y.toDouble())
m2.prescale(scale, scale)
var dx = 0.0
var dy = 0.0
ctx.useBatcher { batch ->
for (n in str.indices) {
val c1 = str[n].toInt()
if (c1 == '\n'.toInt()) {
dx = 0.0
dy += fontSize
continue
}
val c2 = str.getOrElse(n + 1) { ' ' }.toInt()
val glyph = this[c1]
val tex = glyph.texture
batch.drawQuad(
ctx.getTex(tex),
(dx + glyph.xoffset).toFloat(),
(dy + glyph.yoffset).toFloat(),
m = m2,
colorMul = colMul,
colorAdd = colAdd,
blendFactors = blendMode.factors,
filtering = filtering
)
val kerningOffset = kernings[BitmapFont.Kerning.buildKey(c1, c2)]?.amount ?: 0
dx += glyph.xadvance + kerningOffset
}
}
}
fun RenderContext.drawText(
font: BitmapFont,
textSize: Double,
str: String,
x: Int,
y: Int,
m: Matrix = Matrix(),
colMul: RGBA = Colors.WHITE,
colAdd: ColorAdd = ColorAdd.NEUTRAL,
blendMode: BlendMode = BlendMode.INHERIT,
filtering: Boolean = true
) {
font.drawText(this, textSize, str, x, y, m, colMul, colAdd, blendMode, filtering)
}
| apache-2.0 | 4025a73635695a2af2e98788bf1ab4ab | 27.764706 | 96 | 0.608725 | 3.217105 | false | false | false | false |
StoneMain/Shortranks | ShortranksBukkit/src/main/kotlin/eu/mikroskeem/shortranks/bukkit/hooks/LibsDisguisesHook.kt | 1 | 6385 | /*
* This file is part of project Shortranks, licensed under the MIT License (MIT).
*
* Copyright (c) 2017-2019 Mark Vainomaa <[email protected]>
* Copyright (c) Contributors
*
* 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 eu.mikroskeem.shortranks.bukkit.hooks
import eu.mikroskeem.shortranks.api.ScoreboardHook
import eu.mikroskeem.shortranks.api.ScoreboardTeam
import eu.mikroskeem.shortranks.api.ScoreboardTeamProcessor
import eu.mikroskeem.shortranks.bukkit.Shortranks
import eu.mikroskeem.shortranks.bukkit.common.asPlayer
import eu.mikroskeem.shortranks.bukkit.common.sbStrip
import eu.mikroskeem.shortranks.common.debug
import eu.mikroskeem.shortranks.common.warning
import me.libraryaddict.disguise.DisguiseAPI
import me.libraryaddict.disguise.LibsDisguises
import me.libraryaddict.disguise.events.DisguiseEvent
import me.libraryaddict.disguise.events.UndisguiseEvent
import org.bukkit.entity.Player
import org.bukkit.event.EventHandler
import org.bukkit.event.EventPriority
import org.bukkit.event.Listener
import java.util.WeakHashMap
/**
* LibsDisguises plugin hook
*
* @author Mark Vainomaa
*/
class LibsDisguisesHook(private val plugin: Shortranks): ScoreboardHook, ScoreboardTeamProcessor, Listener {
private val disguisedPlayers = WeakHashMap<Player, Boolean>()
override fun hook() {
plugin.server.pluginManager.registerEvents(this, plugin)
checkLibsDisguisesSettings {
warning("** LibsDisguises's 'SelfDisguisesScoreboard' was not 'IGNORE_SCOREBOARD'!")
warning("Changing it to 'IGNORE_SCOREBOARD' to avoid Shortranks breakage, as " +
"Shortranks has proper workaround for LibsDisguises")
warning("Don't forget to change that setting by hand in plugin configuration, as " +
"altering configuration file by Shortranks gets rid of comments and LibsDisguises reload " +
"causes modified setting to reset.")
}
}
override fun unhook() {
DisguiseEvent.getHandlerList().unregister(this)
UndisguiseEvent.getHandlerList().unregister(this)
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
fun on(event: DisguiseEvent) {
checkLibsDisguisesSettings {}
if(event.entity is Player && !event.entity.hasMetadata("NPC")) {
val player = event.entity as Player
val team = plugin.scoreboardManager.getTeam(player.uniqueId)
if(DisguiseAPI.isDisguised(player)) {
// UndisguiseEvent is not fired when player tries to disguise itself if already disguised.
// So clean up old entity id
DisguiseAPI.getDisguise(player)!!.run {
debug("Cleaning up old disguise ${entity.entityId} from team $team")
team.removeMember("${entity.entityId}")
}
}
// Mark player disguised
disguisedPlayers.compute(player) { _, _ -> true }
// Add disguised entity's id to team
val disguiseId = event.disguise.entity.entityId
debug("Adding disguised entity id $disguiseId to team $team, as player disguised")
team.addMember("$disguiseId")
plugin.sbManager.updateTeam(team)
}
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
fun on(event: UndisguiseEvent) {
checkLibsDisguisesSettings {}
if(event.entity is Player && !event.entity.hasMetadata("NPC")) {
val player = event.entity as Player
if(!player.isOnline) return // Can be fired after player disconnects
val team = plugin.scoreboardManager.getTeam(player.uniqueId)
// Mark player undisguised
disguisedPlayers.compute(player) { _, _ -> false }
// Remove disguised entity's id from team
val disguiseId = event.disguise.entity.entityId
debug("Removing disguised entity id $disguiseId from team $team, as player undisguised")
team.removeMember("$disguiseId")
plugin.sbManager.updateTeam(team)
}
}
// Does not actually process teams, listens for changes instead
override fun accept(team: ScoreboardTeam) {
val player = team.teamOwnerPlayer.asPlayer
disguisedPlayers.computeIfPresent(player) compute@ { _, value ->
player.setPlayerListName(if(value) formatPlayerListName(team, player) else null)
return@compute value
}
}
override fun getName(): String = "LibsDisguises hook"
override fun getDescription(): String = "Built in LibsDisguises hook"
override fun getAuthors(): List<String> = listOf("mikroskeem")
override fun getScoreboardTeamProcessors()= listOf(this)
override fun getProcessorPriority(): Int = 1000
private inline fun checkLibsDisguisesSettings(callback: () -> Unit) {
LibsDisguises.getInstance().run {
if(config.get("SelfDisguisesScoreboard", "MODIFY_SCOREBOARD") != "IGNORE_SCOREBOARD") {
config.set("SelfDisguisesScoreboard", "IGNORE_SCOREBOARD")
callback()
}
}
}
private fun formatPlayerListName(team: ScoreboardTeam, player: Player) = (team.prefix + player.name + team.suffix).sbStrip()
} | mit | 751cbab01cb2c48a1e35584bc3cfed3f | 43.971831 | 128 | 0.695693 | 4.328814 | false | false | false | false |
cashapp/sqldelight | dialects/mysql/src/main/kotlin/app/cash/sqldelight/dialects/mysql/grammar/mixins/AlterTableAddColumnMixin.kt | 1 | 934 | package app.cash.sqldelight.dialects.mysql.grammar.mixins
import app.cash.sqldelight.dialects.mysql.grammar.psi.MySqlAlterTableAddColumn
import com.alecstrong.sql.psi.core.psi.AlterTableApplier
import com.alecstrong.sql.psi.core.psi.LazyQuery
import com.alecstrong.sql.psi.core.psi.QueryElement
import com.alecstrong.sql.psi.core.psi.impl.SqlAlterTableAddColumnImpl
import com.intellij.lang.ASTNode
internal abstract class AlterTableAddColumnMixin(
node: ASTNode,
) : SqlAlterTableAddColumnImpl(node),
MySqlAlterTableAddColumn,
AlterTableApplier {
override fun applyTo(lazyQuery: LazyQuery): LazyQuery {
return LazyQuery(
tableName = lazyQuery.tableName,
query = {
val columns = placementClause.placeInQuery(
columns = lazyQuery.query.columns,
column = QueryElement.QueryColumn(columnDef.columnName),
)
lazyQuery.query.copy(columns = columns)
},
)
}
}
| apache-2.0 | f926a3d44471cf9c2199ba5bb508fcf3 | 33.592593 | 78 | 0.75803 | 3.827869 | false | false | false | false |
karollewandowski/aem-intellij-plugin | src/test/kotlin/co/nums/intellij/aem/htl/completion/HtlBlocksCompletionTest.kt | 1 | 861 | package co.nums.intellij.aem.htl.completion
import co.nums.intellij.aem.htl.definitions.HtlBlock
class HtlBlocksCompletionTest : HtlCompletionTestBase() {
private val allBlocks = HtlBlock.values().map { it.type }.toTypedArray()
fun testAllHtlBlocksWhenDataTyped() = checkContainsAll(
"""<div data<caret>""",
*allBlocks)
fun testAllHtlBlocksWhenSlyTyped() = checkContainsAll(
"""<div sly<caret>""",
*allBlocks)
fun testHtlBlocksFilteredByNamePart() = checkContainsAll(
"""<div te<caret>""",
"data-sly-template", "data-sly-test", "data-sly-text", "data-sly-attribute")
fun testShouldNotCompleteAlreadyTypedBlocks() = checkContainsAll(
"""<div data-sly-text="any" te<caret>""",
"data-sly-template", "data-sly-test", "data-sly-attribute")
}
| gpl-3.0 | 9f53d75304b4614de0b63a0545dac978 | 33.44 | 88 | 0.648084 | 4.042254 | false | true | false | false |
wikimedia/apps-android-wikipedia | app/src/main/java/org/wikipedia/dataclient/mwapi/UserContribution.kt | 1 | 999 | package org.wikipedia.dataclient.mwapi
import kotlinx.serialization.Serializable
import kotlinx.serialization.Transient
import org.wikipedia.util.DateUtil
import java.text.ParseException
import java.util.*
@Serializable
class UserContribution {
val userid: Int = 0
val user: String = ""
val pageid: Int = 0
val revid: Long = 0
val parentid: Long = 0
val ns: Int = 0
val title: String = ""
private val timestamp: String = ""
@Transient private var parsedDate: Date? = null
val comment: String = ""
val new: Boolean = false
val minor: Boolean = false
val top: Boolean = false
val size: Int = 0
val sizediff: Int = 0
val tags: List<String> = Collections.emptyList()
fun date(): Date {
if (parsedDate == null) {
try {
parsedDate = DateUtil.iso8601DateParse(timestamp)
} catch (e: ParseException) {
// ignore
}
}
return parsedDate!!
}
}
| apache-2.0 | a10c7714f20f72d303c97c5ba4c844c7 | 25.289474 | 65 | 0.615616 | 4.251064 | false | false | false | false |
vanita5/twittnuker | twittnuker/src/main/kotlin/de/vanita5/twittnuker/fragment/AddStatusFilterDialogFragment.kt | 1 | 9705 | /*
* Twittnuker - Twitter client for Android
*
* Copyright (C) 2013-2017 vanita5 <[email protected]>
*
* This program incorporates a modified version of Twidere.
* Copyright (C) 2012-2017 Mariotaku Lee <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.vanita5.twittnuker.fragment
import android.app.Dialog
import android.content.ContentValues
import android.os.Bundle
import android.support.v4.app.FragmentManager
import android.support.v7.app.AlertDialog
import com.twitter.Extractor
import org.mariotaku.kpreferences.get
import de.vanita5.twittnuker.R
import de.vanita5.twittnuker.constant.IntentConstants.EXTRA_STATUS
import de.vanita5.twittnuker.constant.nameFirstKey
import de.vanita5.twittnuker.extension.applyTheme
import de.vanita5.twittnuker.extension.onShow
import de.vanita5.twittnuker.model.ParcelableStatus
import de.vanita5.twittnuker.model.ParcelableUserMention
import de.vanita5.twittnuker.model.UserKey
import de.vanita5.twittnuker.provider.TwidereDataStore.Filters
import de.vanita5.twittnuker.util.ContentValuesCreator
import de.vanita5.twittnuker.util.HtmlEscapeHelper
import de.vanita5.twittnuker.util.ParseUtils
import de.vanita5.twittnuker.util.UserColorNameManager
import de.vanita5.twittnuker.util.content.ContentResolverUtils
import java.util.*
class AddStatusFilterDialogFragment : BaseDialogFragment() {
private val extractor = Extractor()
private var filterItems: Array<FilterItemInfo>? = null
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val builder = AlertDialog.Builder(context)
filterItems = filterItemsInfo
val entries = arrayOfNulls<String>(filterItems!!.size)
val nameFirst = preferences[nameFirstKey]
for (i in 0 until entries.size) {
val info = filterItems!![i]
when (info.type) {
FilterItemInfo.FILTER_TYPE_USER -> {
entries[i] = getString(R.string.user_filter_name, getName(userColorNameManager,
info.value, nameFirst))
}
FilterItemInfo.FILTER_TYPE_KEYWORD -> {
entries[i] = getString(R.string.keyword_filter_name, getName(userColorNameManager,
info.value, nameFirst))
}
FilterItemInfo.FILTER_TYPE_SOURCE -> {
entries[i] = getString(R.string.source_filter_name, getName(userColorNameManager,
info.value, nameFirst))
}
}
}
builder.setTitle(R.string.action_add_to_filter)
builder.setMultiChoiceItems(entries, null, null)
builder.setPositiveButton(android.R.string.ok) { dialog, _ ->
val alertDialog = dialog as AlertDialog
val checkPositions = alertDialog.listView.checkedItemPositions
val userKeys = HashSet<UserKey>()
val keywords = HashSet<String>()
val sources = HashSet<String>()
val userValues = ArrayList<ContentValues>()
val keywordValues = ArrayList<ContentValues>()
val sourceValues = ArrayList<ContentValues>()
loop@ for (i in 0 until checkPositions.size()) {
if (!checkPositions.valueAt(i)) {
continue@loop
}
val info = filterItems!![checkPositions.keyAt(i)]
val value = info.value
if (value is ParcelableUserMention) {
userKeys.add(value.key)
userValues.add(ContentValuesCreator.createFilteredUser(value))
} else if (value is UserItem) {
userKeys.add(value.key)
userValues.add(createFilteredUser(value))
} else if (info.type == FilterItemInfo.FILTER_TYPE_KEYWORD) {
val keyword = ParseUtils.parseString(value)
keywords.add(keyword)
val values = ContentValues()
values.put(Filters.Keywords.VALUE, "#$keyword")
keywordValues.add(values)
} else if (info.type == FilterItemInfo.FILTER_TYPE_SOURCE) {
val source = ParseUtils.parseString(value)
sources.add(source)
val values = ContentValues()
values.put(Filters.Sources.VALUE, source)
sourceValues.add(values)
}
}
val resolver = context.contentResolver
ContentResolverUtils.bulkDelete(resolver, Filters.Users.CONTENT_URI,
Filters.Users.USER_KEY, false, userKeys, null, null)
ContentResolverUtils.bulkDelete(resolver, Filters.Keywords.CONTENT_URI,
Filters.Keywords.VALUE, false, keywords, null, null)
ContentResolverUtils.bulkDelete(resolver, Filters.Sources.CONTENT_URI,
Filters.Sources.VALUE, false, sources, null, null)
ContentResolverUtils.bulkInsert(resolver, Filters.Users.CONTENT_URI, userValues)
ContentResolverUtils.bulkInsert(resolver, Filters.Keywords.CONTENT_URI, keywordValues)
ContentResolverUtils.bulkInsert(resolver, Filters.Sources.CONTENT_URI, sourceValues)
}
builder.setNegativeButton(android.R.string.cancel, null)
val dialog = builder.create()
dialog.onShow { it.applyTheme() }
return dialog
}
private val filterItemsInfo: Array<FilterItemInfo>
get() {
val args = arguments
if (args == null || !args.containsKey(EXTRA_STATUS)) return emptyArray()
val status = args.getParcelable<ParcelableStatus>(EXTRA_STATUS) ?: return emptyArray()
val list = ArrayList<FilterItemInfo>()
if (status.is_retweet && status.retweeted_by_user_key != null) {
list.add(FilterItemInfo(FilterItemInfo.FILTER_TYPE_USER,
UserItem(status.retweeted_by_user_key!!, status.retweeted_by_user_name,
status.retweeted_by_user_screen_name)))
}
if (status.is_quote && status.quoted_user_key != null) {
list.add(FilterItemInfo(FilterItemInfo.FILTER_TYPE_USER,
UserItem(status.quoted_user_key!!, status.quoted_user_name,
status.quoted_user_screen_name)))
}
list.add(FilterItemInfo(FilterItemInfo.FILTER_TYPE_USER, UserItem(status.user_key,
status.user_name, status.user_screen_name)))
val mentions = status.mentions
if (mentions != null) {
for (mention in mentions) {
if (mention.key != status.user_key) {
list.add(FilterItemInfo(FilterItemInfo.FILTER_TYPE_USER, mention))
}
}
}
val hashtags = HashSet<String>()
hashtags.addAll(extractor.extractHashtags(status.text_plain))
for (hashtag in hashtags) {
list.add(FilterItemInfo(FilterItemInfo.FILTER_TYPE_KEYWORD, hashtag))
}
val source = status.source?.let(HtmlEscapeHelper::toPlainText)
if (source != null) {
list.add(FilterItemInfo(FilterItemInfo.FILTER_TYPE_SOURCE, source))
}
return list.toTypedArray()
}
private fun getName(manager: UserColorNameManager, value: Any, nameFirst: Boolean): String {
if (value is ParcelableUserMention) {
return manager.getDisplayName(value.key, value.name, value.screen_name, nameFirst)
} else if (value is UserItem) {
return manager.getDisplayName(value.key, value.name, value.screen_name, nameFirst)
} else
return ParseUtils.parseString(value)
}
internal data class FilterItemInfo(
val type: Int,
val value: Any
) {
companion object {
internal const val FILTER_TYPE_USER = 1
internal const val FILTER_TYPE_KEYWORD = 2
internal const val FILTER_TYPE_SOURCE = 3
}
}
internal data class UserItem(
val key: UserKey,
val name: String,
val screen_name: String
)
companion object {
val FRAGMENT_TAG = "add_status_filter"
private fun createFilteredUser(item: UserItem): ContentValues {
val values = ContentValues()
values.put(Filters.Users.USER_KEY, item.key.toString())
values.put(Filters.Users.NAME, item.name)
values.put(Filters.Users.SCREEN_NAME, item.screen_name)
return values
}
fun show(fm: FragmentManager, status: ParcelableStatus): AddStatusFilterDialogFragment {
val args = Bundle()
args.putParcelable(EXTRA_STATUS, status)
val f = AddStatusFilterDialogFragment()
f.arguments = args
f.show(fm, FRAGMENT_TAG)
return f
}
}
} | gpl-3.0 | fa3b2492b8ebea93156b138d9984b4a3 | 43.118182 | 102 | 0.624626 | 4.711165 | false | false | false | false |
BilledTrain380/sporttag-psa | app/shared/src/main/kotlin/ch/schulealtendorf/psa/shared/rulebook/SkippingRuleSet.kt | 1 | 2677 | /*
* Copyright (c) 2019 by Nicolas Märchy
*
* This file is part of Sporttag PSA.
*
* Sporttag PSA is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Sporttag PSA is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Sporttag PSA. If not, see <http://www.gnu.org/licenses/>.
*
* Diese Datei ist Teil von Sporttag PSA.
*
* Sporttag PSA ist Freie Software: Sie können es unter den Bedingungen
* der GNU General Public License, wie von der Free Software Foundation,
* Version 3 der Lizenz oder (nach Ihrer Wahl) jeder späteren
* veröffentlichten Version, weiterverbreiten und/oder modifizieren.
*
* Sporttag PSA wird in der Hoffnung, dass es nützlich sein wird, aber
* OHNE JEDE GEWÄHRLEISTUNG, bereitgestellt; sogar ohne die implizite
* Gewährleistung der MARKTFÄHIGKEIT oder EIGNUNG FÜR EINEN BESTIMMTEN ZWECK.
* Siehe die GNU General Public License für weitere Details.
*
* Sie sollten eine Kopie der GNU General Public License zusammen mit diesem
* Programm erhalten haben. Wenn nicht, siehe <http://www.gnu.org/licenses/>.
*
*
*/
package ch.schulealtendorf.psa.shared.rulebook
import ch.schulealtendorf.psa.dto.participation.GenderDto
import ch.schulealtendorf.psa.dto.participation.athletics.SEILSPRINGEN
import ch.schulealtendorf.psa.shared.rulebook.rules.RuleSet
/**
* Defines all the rules that can be applied to a skipping.
*
* @author nmaerchy
* @version 1.0.0
*/
class SkippingRuleSet : RuleSet<FormulaModel, Int>() {
/**
* @return true if the rules of this rule set can be used, otherwise false
*/
override val whenever: (FormulaModel) -> Boolean = { it.discipline == SEILSPRINGEN }
init {
addRule(
object : FormulaRule() {
override val formula: (Double) -> Int = { (1 * ((it - 0) pow 1.245)).toInt() }
override val whenever: (FormulaModel) -> Boolean = { it.gender == GenderDto.FEMALE }
}
)
addRule(
object : FormulaRule() {
override val formula: (Double) -> Int = { (1.4 * ((it - 0) pow 1.18)).toInt() }
override val whenever: (FormulaModel) -> Boolean = { it.gender == GenderDto.MALE }
}
)
}
}
| gpl-3.0 | e6bbdea658d0d7c33beee71f6cbffaa9 | 35.040541 | 100 | 0.685414 | 4.2672 | false | false | false | false |
vanita5/twittnuker | twittnuker/src/main/kotlin/de/vanita5/twittnuker/task/AbsAccountRequestTask.kt | 1 | 4082 | /*
* Twittnuker - Twitter client for Android
*
* Copyright (C) 2013-2017 vanita5 <[email protected]>
*
* This program incorporates a modified version of Twidere.
* Copyright (C) 2012-2017 Mariotaku Lee <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.vanita5.twittnuker.task
import android.accounts.AccountManager
import android.content.Context
import android.widget.Toast
import org.mariotaku.ktextension.toLongOr
import de.vanita5.microblog.library.MicroBlogException
import de.vanita5.twittnuker.exception.AccountNotFoundException
import de.vanita5.twittnuker.extension.getErrorMessage
import de.vanita5.twittnuker.extension.insert
import de.vanita5.twittnuker.model.AccountDetails
import de.vanita5.twittnuker.model.Draft
import de.vanita5.twittnuker.model.UserKey
import de.vanita5.twittnuker.model.util.AccountUtils
import de.vanita5.twittnuker.provider.TwidereDataStore.Drafts
import de.vanita5.twittnuker.task.twitter.UpdateStatusTask
abstract class AbsAccountRequestTask<Params, Result, Callback>(context: Context, val accountKey: UserKey?) :
ExceptionHandlingAbstractTask<Params, Result, MicroBlogException, Callback>(context) {
override final val exceptionClass = MicroBlogException::class.java
override final fun onExecute(params: Params): Result {
val am = AccountManager.get(context)
val account = accountKey?.let { AccountUtils.getAccountDetails(am, it, true) } ?:
throw AccountNotFoundException()
val draft = createDraft()
var draftId = -1L
if (draft != null) {
val uri = context.contentResolver.insert(Drafts.CONTENT_URI, draft)
draftId = uri?.lastPathSegment.toLongOr(-1)
}
if (draftId != -1L) {
microBlogWrapper.addSendingDraftId(draftId)
}
try {
val result = onExecute(account, params)
onCleanup(account, params, result, null)
if (draftId != -1L) {
UpdateStatusTask.deleteDraft(context, draftId)
}
return result
} catch (e: MicroBlogException) {
onCleanup(account, params, null, e)
if (draftId != 1L && deleteDraftOnException(account, params, e)) {
UpdateStatusTask.deleteDraft(context, draftId)
}
throw e
} finally {
if (draftId != -1L) {
microBlogWrapper.removeSendingDraftId(draftId)
}
}
}
protected abstract fun onExecute(account: AccountDetails, params: Params): Result
protected open fun onCleanup(account: AccountDetails, params: Params, result: Result?, exception: MicroBlogException?) {
if (result != null) {
onCleanup(account, params, result)
} else if (exception != null) {
onCleanup(account, params, exception)
}
}
protected open fun onCleanup(account: AccountDetails, params: Params, result: Result) {}
protected open fun onCleanup(account: AccountDetails, params: Params, exception: MicroBlogException) {}
protected open fun createDraft(): Draft? = null
protected open fun deleteDraftOnException(account: AccountDetails, params: Params, exception: MicroBlogException): Boolean = false
override fun onException(callback: Callback?, exception: MicroBlogException) {
Toast.makeText(context, exception.getErrorMessage(context), Toast.LENGTH_SHORT).show()
}
} | gpl-3.0 | c2dae25411c18a692dbea4e69561c34e | 40.663265 | 134 | 0.700882 | 4.515487 | false | false | false | false |
vimeo/vimeo-networking-java | models/src/main/java/com/vimeo/networking2/PlatformConstraint.kt | 1 | 545 | package com.vimeo.networking2
import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass
/**
* Constraints put in place by a social media platform on uploading videos.
*
* @param duration The max length in seconds of a video for the corresponding platform.
* @param size The max file size in gigabytes of a video for the corresponding platform.
*/
@JsonClass(generateAdapter = true)
data class PlatformConstraint(
@Json(name = "duration")
val duration: Int? = null,
@Json(name = "size")
val size: Long? = null
)
| mit | de17304f30e72f17abb924c648c50a7d | 26.25 | 88 | 0.72844 | 3.920863 | false | false | false | false |
Nunnery/MythicDrops | src/main/kotlin/com/tealcube/minecraft/bukkit/mythicdrops/settings/language/command/MythicGiveTomeMessages.kt | 1 | 2238 | /*
* This file is part of MythicDrops, licensed under the MIT License.
*
* Copyright (C) 2019 Richard Harrah
*
* Permission is hereby granted, free of charge,
* to any person obtaining a copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,
* and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or
* substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
* OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.tealcube.minecraft.bukkit.mythicdrops.settings.language.command
import com.squareup.moshi.JsonClass
import com.tealcube.minecraft.bukkit.mythicdrops.api.settings.language.command.GiveTomeMessages
import com.tealcube.minecraft.bukkit.mythicdrops.getNonNullString
import org.bukkit.configuration.ConfigurationSection
@JsonClass(generateAdapter = true)
data class MythicGiveTomeMessages internal constructor(
override val receiverSuccess: String = "",
override val receiverFailure: String = "",
override val senderSuccess: String = "",
override val senderFailure: String = ""
) : GiveTomeMessages {
companion object {
fun fromConfigurationSection(configurationSection: ConfigurationSection) = MythicGiveTomeMessages(
configurationSection.getNonNullString("receiver-success"),
configurationSection.getNonNullString("receiver-failure"),
configurationSection.getNonNullString("sender-success"),
configurationSection.getNonNullString("sender-failure")
)
}
}
| mit | 885c7ac53c8cc159978ca6cb1eec2eca | 49.863636 | 106 | 0.76765 | 4.962306 | false | true | false | false |
visiolink-android-dev/visiolink-app-plugin | src/main/kotlin/com/visiolink/app/VisiolinkAppPlugin.kt | 1 | 5197 | package com.visiolink.app
import com.android.build.gradle.AppExtension
import com.android.build.gradle.api.ApkVariantOutput
import com.android.build.gradle.api.ApplicationVariant
import com.visiolink.app.task.*
import org.gradle.api.GradleException
import org.gradle.api.Project
import org.gradle.api.Plugin
import org.gradle.api.internal.plugins.DefaultExtraPropertiesExtension
import java.io.FileInputStream
import java.util.*
open class VisiolinkAppPlugin : Plugin<Project> {
override fun apply(project: Project) {
with(project.tasks) {
val verifyVersionControl = create("verifyVersionControl", VerifyVersionControlTask::class.java)
val verifyBuildServer = create("verifyBuildServer", VerifyBuildServerTask::class.java)
val verifyNoStageUrl = create("verifyNoStageUrl", VerifyNoStageUrlTask::class.java)
val verifiers = listOf(verifyVersionControl, verifyBuildServer, verifyNoStageUrl)
val generateProjectChangeLog = create("generateProjectChangeLog", GenerateProjectChangeLogTask::class.java).setMustRunAfter(verifiers)
create("generateGenericChangeLog", GenerateGenericChangeLogTask::class.java).setMustRunAfter(verifiers)
create("increaseMajorVersionName", IncreaseMajorVersionNameTask::class.java)
create("increaseMinorVersionName", IncreaseMinorVersionNameTask::class.java)
create("increaseBuildVersionName", IncreaseBuildVersionNameTask::class.java)
create("getFlavors", GetFlavorsTask::class.java)
create("addAdtechModule", AddAdtechModuleTask::class.java)
create("addAndroidTvModule", AddAndroidTvModuleTask::class.java)
create("addCxenseModule", AddCxenseModuleTask::class.java)
create("addDfpModule", AddDfpModuleTask::class.java)
create("addInfosoftModule", AddInfosoftModuleTask::class.java)
create("addKindleModule", AddKindleModuleTask::class.java)
create("addSpidModule", AddSpidModuleTask::class.java)
create("addTnsDkModule", AddTnsGallupDkModuleTask::class.java)
create("addTnsNoModule", AddTnsGallupNoModuleTask::class.java)
create("addComScoreModule", AddComScoreModuleTask::class.java)
create("tagProject", TagProjectTask::class.java).setMustRunAfter(verifiers + generateProjectChangeLog)
whenTaskAdded { task ->
if (task.name.startsWith("generate")
&& task.name.endsWith("ReleaseBuildConfig")
&& !project.hasProperty("ignoreChecks")) {
//println("Task name: ${task.name}")
task.dependsOn("tagProject")
task.dependsOn("generateProjectChangeLog")
task.dependsOn("verifyBuildServer")
task.dependsOn("verifyVersionControl")
task.dependsOn("verifyNoStageUrl")
}
if (task.name == "preDevReleaseBuild") {
//println("Task name: ${task.name}")
task.dependsOn("generateGenericChangeLog")
}
}
}
//Set output file name for release builds
val android = project.extensions.getByName("android") as AppExtension
android.applicationVariants.all { variant ->
if (variant.buildType.name == "release") {
//If apkPath has been defined in ~/.gradle/gradle.properties or local.properties
if (project.hasProperty("apkPath")) {
//TODO:
//releaseDir = apkPath + "/" + rootProject.name
}
variant.outputs.filterIsInstance(ApkVariantOutput::class.java).forEach {
it.outputFileName = with(variant) { "${flavorName}_${versionNameNoDots}_$versionCode.apk" }
}
}
}
val ext = project.extensions.getByName("ext") as DefaultExtraPropertiesExtension
//Equivalent to project.ext.getVersionCodeTimestamp = { -> }
ext.set("getVersionCodeTimestamp", closure {
if (project.hasProperty("devBuild")) {
1
} else {
dateFormat("yyMMddHHmm").format(Date()).toInt()
}
})
//Equivalent to project.ext.getVersionNameFromFile = { -> }
ext.set("getVersionNameFromFile", closure {
val versionPropsFile = project.file("version.properties")
if (versionPropsFile.canRead()) {
val versionProps = Properties()
versionProps.load(FileInputStream(versionPropsFile))
val versionMajor = versionProps.getProperty("versionMajor").trim()
val versionMinor = versionProps.getProperty("versionMinor").trim()
val versionBuild = versionProps.getProperty("versionBuild").trim()
"$versionMajor.$versionMinor.$versionBuild"
} else {
throw GradleException("Could not read version.properties!")
}
})
}
}
val ApplicationVariant.versionNameNoDots
get() = versionName.replace(".", "") | apache-2.0 | 5f23f7d72f8403351a35bd28e1b7de5b | 48.037736 | 146 | 0.639023 | 4.84343 | false | false | false | false |
AndroidX/androidx | compose/animation/animation/integration-tests/animation-demos/src/main/java/androidx/compose/animation/demos/statetransition/MultiDimensionalAnimationDemo.kt | 3 | 3299 | /*
* 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.animation.demos.statetransition
import androidx.compose.animation.animateColor
import androidx.compose.animation.core.animateRect
import androidx.compose.animation.core.spring
import androidx.compose.animation.core.tween
import androidx.compose.animation.core.updateTransition
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Rect
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.tooling.preview.Preview
@Preview
@Composable
fun MultiDimensionalAnimationDemo() {
var currentState by remember { mutableStateOf(AnimState.Collapsed) }
val onClick = {
// Cycle through states when clicked.
currentState = when (currentState) {
AnimState.Collapsed -> AnimState.Expanded
AnimState.Expanded -> AnimState.PutAway
AnimState.PutAway -> AnimState.Collapsed
}
}
var width by remember { mutableStateOf(0f) }
var height by remember { mutableStateOf(0f) }
val transition = updateTransition(currentState)
val rect by transition.animateRect(transitionSpec = { spring(stiffness = 100f) }) {
when (it) {
AnimState.Collapsed -> Rect(600f, 600f, 900f, 900f)
AnimState.Expanded -> Rect(0f, 400f, width, height - 400f)
AnimState.PutAway -> Rect(width - 300f, height - 300f, width, height)
}
}
val color by transition.animateColor(transitionSpec = { tween(durationMillis = 500) }) {
when (it) {
AnimState.Collapsed -> Color.LightGray
AnimState.Expanded -> Color(0xFFd0fff8)
AnimState.PutAway -> Color(0xFFe3ffd9)
}
}
Canvas(
modifier = Modifier.fillMaxSize().clickable(
onClick = onClick,
indication = null,
interactionSource = remember { MutableInteractionSource() }
)
) {
width = size.width
height = size.height
drawRect(
color,
topLeft = Offset(rect.left, rect.top),
size = Size(rect.width, rect.height)
)
}
}
private enum class AnimState {
Collapsed,
Expanded,
PutAway
} | apache-2.0 | b085ef79c5987565e86469392bf8c493 | 34.483871 | 92 | 0.709003 | 4.375332 | false | false | false | false |
satamas/fortran-plugin | src/main/kotlin/org/jetbrains/fortran/ide/completion/KeywordCompletionContributor.kt | 1 | 3283 | package org.jetbrains.fortran.ide.completion
import com.intellij.codeInsight.completion.CompletionContributor
import com.intellij.codeInsight.completion.CompletionType
import com.intellij.patterns.PlatformPatterns.psiElement
import org.jetbrains.fortran.lang.FortranTypes
import org.jetbrains.fortran.lang.psi.FortranBlock
import org.jetbrains.fortran.lang.psi.FortranBlockData
class KeywordCompletionContributor : CompletionContributor() {
private val typeStatementsBeginning = setOf(
"byte", "character", "complex", "double", "integer", "logical", "real"
)
private val blockDataStatementsBeginning = setOf(
"common", "data", "dimension", "equivalence", "implicit", "parameter", "record", "save", "structure"
) + typeStatementsBeginning
private val allKeywords = blockDataStatementsBeginning + setOf("abstract", "accept", "all", "allocate",
"allocatable", "assign",
"assignment", "associate", "asynchronous", "backspace", "bind", "block", "blockdata",
"call", "case", "class", "close", "codimension", "concurrent", "contains", "contiguous", "continue",
"critical", "cycle", "deallocate", "decode", "default", "deferred", "do",
"doubleprecision", "doublecomplex", "elemental", "else", "elseif", "elsewhere", "encode",
"end", "endassociate", "endblock", "endblockdata", "endcritical", "enddo", "endenum",
"endfile", "endforall", "endfunction", "endif", "endinterface", "endmodule", "endprocedure",
"endprogram", "endselect", "endsubmodule", "endsubroutine", "endtype", "endwhere", "entry",
"enum", "enumerator", "error", "exit", "extends", "external", "final", "flush",
"forall", "format", "formatted", "function", "generic", "go", "goto", "if", "images",
"import", "impure", "in", "include", "inout", "intent", "interface", "intrinsic",
"inquire", "iolength", "is", "kind", "len", "lock", "memory", "module", "name",
"namelist", "none", "nonintrinsic", "nonoverridable", "nopass", "nullify", "only", "open",
"operator", "optional", "out", "pass", "pause", "pointer", "precision", "print",
"private", "procedure", "program", "protected", "public", "pure", "read", "recursive",
"result", "return", "rewind", "select", "sequence", "stop", "sync", "syncall",
"syncimages", "syncmemory", "subroutine", "submodule", "target", "then", "to", "type",
"unformatted", "unlock", "use", "value", "volatile", "wait", "where", "while", "write", "unit")
init {
extend(CompletionType.BASIC, blockDataStatementStart(), KeywordCompletionProvider(blockDataStatementsBeginning))
extend(CompletionType.BASIC, defaultStatementStart(), KeywordCompletionProvider(allKeywords))
}
private fun defaultStatementStart() = statementStart()
.andNot(psiElement()
.inside(FortranBlockData::class.java))
private fun blockDataStatementStart() = statementStart()
.inside(psiElement(FortranBlock::class.java))
.inside(psiElement(FortranBlockData::class.java))
private fun statementStart() = psiElement(FortranTypes.IDENTIFIER).afterLeaf(psiElement(FortranTypes.EOL))
} | apache-2.0 | 24f0db2240fde1d2c322b6a03192915b | 59.814815 | 120 | 0.646665 | 4.098627 | false | false | false | false |
DemonWav/StatCraft | src/main/kotlin/com/demonwav/statcraft/commands/sc/SCToolsBroken.kt | 1 | 1980 | /*
* StatCraft Bukkit Plugin
*
* Copyright (c) 2016 Kyle Wood (DemonWav)
* https://www.demonwav.com
*
* MIT License
*/
package com.demonwav.statcraft.commands.sc
import com.demonwav.statcraft.StatCraft
import com.demonwav.statcraft.commands.ResponseBuilder
import com.demonwav.statcraft.querydsl.QPlayers
import com.demonwav.statcraft.querydsl.QToolsBroken
import org.bukkit.command.CommandSender
import java.sql.Connection
class SCToolsBroken(plugin: StatCraft) : SCTemplate(plugin) {
init {
plugin.baseCommand.registerCommand("toolsbroken", this)
}
override fun hasPermission(sender: CommandSender, args: Array<out String>?) = sender.hasPermission("statcraft.user.toolsbroken")
override fun playerStatResponse(name: String, args: List<String>, connection: Connection): String {
val id = getId(name) ?: return ResponseBuilder.build(plugin) {
playerName { name }
statName { "Tools Broken" }
stats["Total"] = "0"
}
val query = plugin.databaseManager.getNewQuery(connection) ?: return databaseError
val t = QToolsBroken.toolsBroken
val result = query.from(t).where(t.id.eq(id)).uniqueResult(t.amount.sum())
return ResponseBuilder.build(plugin) {
playerName { name }
statName { "Tools Broken" }
stats["Total"] = df.format(result)
}
}
override fun serverStatListResponse(num: Long, args: List<String>, connection: Connection): String {
val query = plugin.databaseManager.getNewQuery(connection) ?: return databaseError
val t = QToolsBroken.toolsBroken
val p = QPlayers.players
val list = query
.from(t)
.innerJoin(p)
.on(t.id.eq(p.id))
.groupBy(p.name)
.orderBy(t.amount.sum().desc())
.limit(num)
.list(p.name, t.amount.sum())
return topListResponse("Tools Broken", list)
}
}
| mit | bbd4d2c35d51611513513b7c0426f498 | 30.428571 | 132 | 0.649495 | 4.203822 | false | false | false | false |
robohorse/RoboPOJOGenerator | generator/src/main/kotlin/com/robohorse/robopojogenerator/properties/templates/ClassTemplate.kt | 1 | 3316 | package com.robohorse.robopojogenerator.properties.templates
internal object ClassTemplate {
const val KOTLIN_DATA_CLASS = "data"
const val NEW_LINE = "\n"
const val TAB = "\t"
const val CLASS_BODY = "public class %1\$s" +
"{" + NEW_LINE +
"%2\$s" + NEW_LINE +
"}"
const val CLASS_BODY_ABSTRACT = "public abstract class %1\$s" +
"{" + NEW_LINE +
"%2\$s" + NEW_LINE +
"}"
const val CLASS_BODY_RECORDS = "public record %1\$s(\n%2\$s\n)" + " {\n}"
const val CLASS_BODY_KOTLIN_DTO = "$KOTLIN_DATA_CLASS class %1\$s" +
"(" + NEW_LINE +
"%2\$s" + NEW_LINE +
")"
const val CLASS_BODY_KOTLIN_DTO_PARCELABLE = "@Parcelize\n$KOTLIN_DATA_CLASS class %1\$s" +
"(" + NEW_LINE +
"%2\$s" + NEW_LINE +
") : Parcelable"
const val CLASS_BODY_ANNOTATED = "%1\$s" + NEW_LINE +
"%2\$s"
const val CLASS_ROOT_IMPORTS = (
"package %1\$s;" + NEW_LINE + NEW_LINE +
"%2\$s" + NEW_LINE +
"%3\$s"
)
const val CLASS_ROOT_IMPORTS_WITHOUT_SEMICOLON = (
"package %1\$s" + NEW_LINE + NEW_LINE +
"%2\$s" + NEW_LINE +
"%3\$s"
)
const val CLASS_ROOT = "package %1\$s;" + NEW_LINE + NEW_LINE +
"%2\$s" + NEW_LINE
const val CLASS_ROOT_WITHOUT_SEMICOLON = "package %1\$s" + NEW_LINE + NEW_LINE +
"%2\$s" + NEW_LINE
const val CLASS_ROOT_NO_PACKAGE = "%1\$s" + NEW_LINE
const val FIELD = "$TAB%1\$s %2\$s;$NEW_LINE"
const val FIELD_WITH_VISIBILITY = "$TAB%1\$s %2\$s %3\$s;$NEW_LINE"
const val FIELD_AUTO_VALUE = TAB + "public abstract %1\$s %2\$s();" + NEW_LINE
const val FIELD_KOTLIN_DTO = TAB + "val %1\$s: %2\$s? = null" + "," + NEW_LINE
const val FIELD_KOTLIN_DTO_NON_NULL = TAB + "val %1\$s: %2\$s" + "," + NEW_LINE
const val FIELD_JAVA_RECORD = "$TAB%1\$s %2\$s,$NEW_LINE"
const val FIELD_KOTLIN_DOT_DEFAULT = TAB + "val any: Any? = null"
const val FIELD_ANNOTATED = "$NEW_LINE$TAB%1\$s$NEW_LINE%2\$s"
const val TYPE_ADAPTER = (
TAB + "public static TypeAdapter<%1\$s> typeAdapter(Gson gson) {" +
NEW_LINE +
TAB + TAB + "return new AutoValue_%1\$s.GsonTypeAdapter(gson);" + NEW_LINE +
TAB + "}" + NEW_LINE
)
const val SETTER = (
TAB + "public void set%1\$s(%2\$s %3\$s){" + NEW_LINE +
TAB + TAB + "this.%3\$s = %3\$s;" + NEW_LINE +
TAB + "}" + NEW_LINE
)
const val GETTER = (
TAB + "public %3\$s get%1\$s(){" + NEW_LINE +
TAB + TAB + "return %2\$s;" + NEW_LINE +
TAB + "}" + NEW_LINE
)
const val GETTER_BOOLEAN = (
TAB + "public %3\$s is%1\$s(){" + NEW_LINE +
TAB + TAB + "return %2\$s;" + NEW_LINE +
TAB + "}" + NEW_LINE
)
const val TO_STRING = (
TAB + "@Override" + NEW_LINE + " " + TAB +
"public String toString(){" + NEW_LINE +
TAB + TAB + "return " + NEW_LINE +
TAB + TAB + TAB + "\"%1\$s{\" + " + NEW_LINE +
"%2\$s" +
TAB + TAB + TAB + "\"}\";" + NEW_LINE +
TAB + TAB + "}"
)
const val TO_STRING_LINE = "$TAB$TAB$TAB\"%3\$s%1\$s = \'\" + %2\$s + \'\\\'\' + $NEW_LINE"
}
| mit | 7b95812d87fd7e8b2a5ff3d1872e5adb | 39.439024 | 95 | 0.487334 | 3.125353 | false | false | false | false |
saschpe/PlanningPoker | mobile/src/main/java/saschpe/poker/activity/HelpActivity.kt | 1 | 4447 | /*
* Copyright 2016 Sascha Peilicke
*
* 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 saschpe.poker.activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentPagerAdapter
import com.google.android.gms.oss.licenses.OssLicensesMenuActivity
import com.google.android.material.tabs.TabLayout
import kotlinx.android.synthetic.main.activity_help.*
import saschpe.android.socialfragment.app.SocialFragment
import saschpe.android.versioninfo.widget.VersionInfoDialogFragment
import saschpe.poker.BuildConfig
import saschpe.poker.R
import saschpe.poker.application.Application
import saschpe.poker.customtabs.CustomTabs
class HelpActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (intent != null) {
if (intent?.scheme == Application.INTENT_SCHEME) {
if (intent?.data?.host == "about") {
when (intent?.data?.path) {
"/privacy" -> {
CustomTabs.startPrivacyPolicy(this)
finish()
}
}
}
}
}
setContentView(R.layout.activity_help)
// Set up toolbar
setSupportActionBar(toolbar)
supportActionBar?.title = null
supportActionBar?.setDisplayHomeAsUpEnabled(true)
// Set up nested scrollview
nested_scroll.isFillViewport = true
// Set up view pager
view_pager.adapter = MyFragmentPagerAdapter(this, supportFragmentManager)
// Set up tab layout
tab_layout.tabMode = TabLayout.MODE_FIXED
tab_layout.setupWithViewPager(view_pager)
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.help, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
android.R.id.home -> {
finish()
return true
}
R.id.privacy_policy -> CustomTabs.startPrivacyPolicy(this)
R.id.open_source_licenses -> startActivity(Intent(this, OssLicensesMenuActivity::class.java))
R.id.version_info -> {
VersionInfoDialogFragment
.newInstance(
getString(R.string.app_name),
BuildConfig.VERSION_NAME,
"Sascha Peilicke",
R.mipmap.ic_launcher
)
.show(supportFragmentManager, "version_info")
return true
}
}
return super.onOptionsItemSelected(item)
}
private class MyFragmentPagerAdapter(context: Context, fm: FragmentManager) : FragmentPagerAdapter(fm) {
private val pageTitles = arrayOf(context.getString(R.string.social))
private val applicationName = context.getString(R.string.app_name)
override fun getItem(position: Int): Fragment = SocialFragment.Builder()
// Mandatory
.setApplicationId(BuildConfig.APPLICATION_ID)
// Optional
.setApplicationName(applicationName)
.setContactEmailAddress("[email protected]")
.setGithubProject("saschpe/PlanningPoker")
.setTwitterProfile("saschpe")
// Visual customization
.setHeaderTextColor(R.color.accent)
.setIconTint(android.R.color.white)
.build()
override fun getPageTitle(position: Int): String = pageTitles[position]
override fun getCount() = 1
}
}
| apache-2.0 | e5168621f5a911c28781231d01db516b | 35.45082 | 108 | 0.641781 | 4.812771 | false | false | false | false |
wordpress-mobile/AztecEditor-Android | aztec/src/main/kotlin/org/wordpress/aztec/formatting/BlockFormatter.kt | 1 | 58755 | package org.wordpress.aztec.formatting
import android.text.Editable
import android.text.Layout
import android.text.Spanned
import android.text.TextUtils
import androidx.core.text.TextDirectionHeuristicsCompat
import org.wordpress.android.util.AppLog
import org.wordpress.aztec.AlignmentRendering
import org.wordpress.aztec.AztecAttributes
import org.wordpress.aztec.AztecText
import org.wordpress.aztec.AztecTextFormat
import org.wordpress.aztec.Constants
import org.wordpress.aztec.ITextFormat
import org.wordpress.aztec.handlers.BlockHandler
import org.wordpress.aztec.handlers.HeadingHandler
import org.wordpress.aztec.handlers.ListItemHandler
import org.wordpress.aztec.spans.AztecHeadingSpan
import org.wordpress.aztec.spans.AztecHorizontalRuleSpan
import org.wordpress.aztec.spans.AztecListItemSpan
import org.wordpress.aztec.spans.AztecListSpan
import org.wordpress.aztec.spans.AztecMediaSpan
import org.wordpress.aztec.spans.AztecOrderedListSpan
import org.wordpress.aztec.spans.AztecPreformatSpan
import org.wordpress.aztec.spans.AztecQuoteSpan
import org.wordpress.aztec.spans.AztecTaskListSpan
import org.wordpress.aztec.spans.AztecUnorderedListSpan
import org.wordpress.aztec.spans.IAztecAlignmentSpan
import org.wordpress.aztec.spans.IAztecBlockSpan
import org.wordpress.aztec.spans.IAztecCompositeBlockSpan
import org.wordpress.aztec.spans.IAztecLineBlockSpan
import org.wordpress.aztec.spans.IAztecNestable
import org.wordpress.aztec.spans.ParagraphSpan
import org.wordpress.aztec.spans.createAztecQuoteSpan
import org.wordpress.aztec.spans.createHeadingSpan
import org.wordpress.aztec.spans.createListItemSpan
import org.wordpress.aztec.spans.createOrderedListSpan
import org.wordpress.aztec.spans.createParagraphSpan
import org.wordpress.aztec.spans.createPreformatSpan
import org.wordpress.aztec.spans.createTaskListSpan
import org.wordpress.aztec.spans.createUnorderedListSpan
import org.wordpress.aztec.util.SpanWrapper
import kotlin.reflect.KClass
class BlockFormatter(editor: AztecText,
private val listStyle: ListStyle,
private val listItemStyle: ListItemStyle,
private val quoteStyle: QuoteStyle,
private val headerStyle: HeaderStyles,
private val preformatStyle: PreformatStyle,
private val alignmentRendering: AlignmentRendering,
private val exclusiveBlockStyles: ExclusiveBlockStyles,
private val paragraphStyle: ParagraphStyle
) : AztecFormatter(editor) {
private val listFormatter = ListFormatter(editor)
private val indentFormatter = IndentFormatter(editor)
data class ListStyle(val indicatorColor: Int, val indicatorMargin: Int, val indicatorPadding: Int, val indicatorWidth: Int, val verticalPadding: Int) {
fun leadingMargin(): Int {
return indicatorMargin + 2 * indicatorWidth + indicatorPadding
}
}
data class QuoteStyle(val quoteBackground: Int, val quoteColor: Int, val quoteTextColor: Int, val quoteBackgroundAlpha: Float, val quoteMargin: Int, val quotePadding: Int, val quoteWidth: Int, val verticalPadding: Int)
data class PreformatStyle(val preformatBackground: Int, val preformatBackgroundAlpha: Float, val preformatColor: Int, val verticalPadding: Int, val leadingMargin: Int, val preformatBorderColor: Int, val preformatBorderRadius: Int, val preformatBorderThickness: Int, val preformatTextSize: Int)
data class ListItemStyle(val strikeThroughCheckedItems: Boolean, val checkedItemsTextColor: Int)
data class HeaderStyles(val verticalPadding: Int, val styles: Map<AztecHeadingSpan.Heading, HeadingStyle>) {
data class HeadingStyle(val fontSize: Int, val fontColor: Int)
}
data class ExclusiveBlockStyles(val enabled: Boolean = false, val verticalParagraphMargin: Int)
data class ParagraphStyle(val verticalMargin: Int)
fun indent() {
listFormatter.indentList()
indentFormatter.indent()
}
fun outdent() {
listFormatter.outdentList()
indentFormatter.outdent()
}
fun isIndentAvailable(): Boolean {
if (listFormatter.isIndentAvailable()) return true
return indentFormatter.isIndentAvailable()
}
fun isOutdentAvailable(): Boolean {
if (listFormatter.isOutdentAvailable()) return true
return indentFormatter.isOutdentAvailable()
}
fun toggleOrderedList() {
toggleList(AztecTextFormat.FORMAT_ORDERED_LIST)
}
fun toggleUnorderedList() {
toggleList(AztecTextFormat.FORMAT_UNORDERED_LIST)
}
fun toggleTaskList() {
toggleList(AztecTextFormat.FORMAT_TASK_LIST)
}
private val availableLists = setOf(AztecTextFormat.FORMAT_TASK_LIST, AztecTextFormat.FORMAT_ORDERED_LIST, AztecTextFormat.FORMAT_UNORDERED_LIST)
private fun toggleList(toggledList: AztecTextFormat) {
val otherLists = availableLists.filter { it != toggledList }
if (!containsList(toggledList)) {
if (otherLists.any { containsList(it) }) {
switchListType(toggledList)
editor.addRefreshListenersToTaskLists(editableText, selectionStart, selectionEnd)
} else {
applyBlockStyle(toggledList)
editor.addRefreshListenersToTaskLists(editableText, selectionStart, selectionEnd)
}
} else {
if (otherLists.any { containsList(it) }) {
switchListType(toggledList)
editor.addRefreshListenersToTaskLists(editableText, selectionStart, selectionEnd)
} else {
removeBlockStyle(toggledList)
}
}
}
fun toggleQuote() {
if (!containsQuote()) {
applyBlockStyle(AztecTextFormat.FORMAT_QUOTE)
} else {
removeEntireBlock(AztecQuoteSpan::class.java)
}
}
fun togglePreformat() {
if (!containsPreformat()) {
if (containsOtherHeadings(AztecTextFormat.FORMAT_PREFORMAT) && !exclusiveBlockStyles.enabled) {
switchHeadingToPreformat()
} else {
applyBlockStyle(AztecTextFormat.FORMAT_PREFORMAT)
}
} else {
removeEntireBlock(AztecPreformatSpan::class.java)
}
}
fun toggleHeading(textFormat: ITextFormat) {
when (textFormat) {
AztecTextFormat.FORMAT_HEADING_1,
AztecTextFormat.FORMAT_HEADING_2,
AztecTextFormat.FORMAT_HEADING_3,
AztecTextFormat.FORMAT_HEADING_4,
AztecTextFormat.FORMAT_HEADING_5,
AztecTextFormat.FORMAT_HEADING_6 -> {
if (!containsHeadingOnly(textFormat)) {
if (containsPreformat() && !exclusiveBlockStyles.enabled) {
switchPreformatToHeading(textFormat)
} else if (containsOtherHeadings(textFormat)) {
switchHeaderType(textFormat)
} else {
applyBlockStyle(textFormat)
}
}
}
AztecTextFormat.FORMAT_PARAGRAPH -> {
val span = editableText.getSpans(selectionStart, selectionEnd, AztecHeadingSpan::class.java).firstOrNull()
if (span != null) {
removeBlockStyle(span.textFormat)
}
removeBlockStyle(AztecTextFormat.FORMAT_PREFORMAT)
}
else -> {
}
}
}
fun toggleTextAlignment(textFormat: ITextFormat) {
when (alignmentRendering) {
AlignmentRendering.VIEW_LEVEL -> {
val message = "cannot toggle text alignment when ${AlignmentRendering.VIEW_LEVEL} is being used"
AppLog.d(AppLog.T.EDITOR, message)
}
AlignmentRendering.SPAN_LEVEL -> {
when (textFormat) {
AztecTextFormat.FORMAT_ALIGN_LEFT,
AztecTextFormat.FORMAT_ALIGN_CENTER,
AztecTextFormat.FORMAT_ALIGN_RIGHT ->
if (containsAlignment(textFormat)) {
removeTextAlignment(textFormat)
} else {
applyTextAlignment(textFormat)
}
}
}
}
}
fun removeTextAlignment(textFormat: ITextFormat) {
getAlignedSpans(textFormat).forEach { changeAlignment(it, null) }
}
fun tryRemoveBlockStyleFromFirstLine(): Boolean {
val selectionStart = editor.selectionStart
if (selectionStart != 0) {
// only handle the edge case of start of text
return false
}
var changed = false
// try to remove block styling when pressing backspace at the beginning of the text
editableText.getSpans(0, 0, IAztecBlockSpan::class.java).forEach { it ->
val spanEnd = editableText.getSpanEnd(it)
val indexOfNewline = editableText.indexOf('\n').let { if (it != -1) it else editableText.length }
if (spanEnd <= indexOfNewline + 1) {
// block will collapse so, just remove it
editableText.removeSpan(it)
changed = true
return@forEach
}
editableText.setSpan(it, indexOfNewline + 1, spanEnd, editableText.getSpanFlags(it))
changed = true
}
return changed
}
/**
* This method makes sure only one block style is ever applied to part of the text. The following block styles are
* made exclusive if the option is enabled:
* - all the lists
* - all the headings
* - quote
* - preformat
*/
private fun removeBlockStylesFromSelectedLine(appliedClass: IAztecBlockSpan) {
// We only want to remove the previous block styles if this option is enabled
if (!exclusiveBlockStyles.enabled) {
return
}
val selectionStart = editor.selectionStart
var newSelStart = if (selectionStart > selectionEnd) selectionEnd else selectionStart
var newSelEnd = selectionEnd
if (newSelStart == 0 && newSelEnd == 0) {
newSelEnd++
} else if (newSelStart == newSelEnd && editableText.length > selectionStart && editableText[selectionStart - 1] == Constants.NEWLINE) {
newSelEnd++
} else if (newSelStart > 0 && !editor.isTextSelected()) {
newSelStart--
}
// try to remove block styling when pressing backspace at the beginning of the text
editableText.getSpans(newSelStart, newSelEnd, IAztecBlockSpan::class.java).forEach {
// We want to remove any list item span that's being converted to another block
if (it is AztecListItemSpan) {
editableText.removeSpan(it)
return@forEach
}
// We don't mind the paragraph blocks which wrap everything
if (it is ParagraphSpan) {
return@forEach
}
// Only these supported blocks will be split/removed on block change
val format = it.textFormat ?: return@forEach
// We do not want to handle cases where the applied style is already existing on a span
if (it.javaClass == appliedClass.javaClass) {
return@forEach
}
val spanStart = editableText.getSpanStart(it)
val spanEnd = editableText.getSpanEnd(it)
val spanFlags = editableText.getSpanFlags(it)
val nextLineLength = "\n".length
// Defines end of a line in a block
val previousLineBreak = editableText.indexOf("\n", newSelEnd)
val lineEnd = if (previousLineBreak > -1) {
previousLineBreak + nextLineLength
} else spanEnd
// Defines start of a line in a block
val nextLineBreak = if (lineEnd == newSelStart + nextLineLength) {
editableText.lastIndexOf("\n", newSelStart - 1)
} else {
editableText.lastIndexOf("\n", newSelStart)
}
val lineStart = if (nextLineBreak > -1) {
nextLineBreak + nextLineLength
} else spanStart
val spanStartsBeforeLineStart = spanStart < lineStart
val spanEndsAfterLineEnd = spanEnd > lineEnd
if (spanStartsBeforeLineStart && spanEndsAfterLineEnd) {
// The line is fully inside of the span so we want to split span in two around the selected line
val copy = makeBlock(format, it.nestingLevel, it.attributes).first()
editableText.removeSpan(it)
editableText.setSpan(it, spanStart, lineStart, spanFlags)
editableText.setSpan(copy, lineEnd, spanEnd, spanFlags)
} else if (!spanStartsBeforeLineStart && spanEndsAfterLineEnd) {
// If the selected line is at the beginning of a span, move the span start to the end of the line
editableText.removeSpan(it)
editableText.setSpan(it, lineEnd, spanEnd, spanFlags)
} else if (spanStartsBeforeLineStart && !spanEndsAfterLineEnd) {
// If the selected line is at the end of a span, move the span end to the start of the line
editableText.removeSpan(it)
editableText.setSpan(it, spanStart, lineStart, spanFlags)
} else {
// In this case the line fully covers the span so we just want to remove the span
editableText.removeSpan(it)
}
}
}
fun moveSelectionIfImageSelected() {
if (selectionStart == selectionEnd && selectionStart > 0 &&
(hasImageRightAfterSelection() || hasHorizontalRuleRightAfterSelection())) {
editor.setSelection(selectionStart - 1)
}
}
private fun hasImageRightAfterSelection() =
editableText.getSpans(selectionStart, selectionEnd, AztecMediaSpan::class.java).any {
editableText.getSpanStart(it) == selectionStart
}
private fun hasHorizontalRuleRightAfterSelection() =
editableText.getSpans(selectionStart, selectionEnd, AztecHorizontalRuleSpan::class.java).any {
editableText.getSpanStart(it) == selectionStart
}
fun removeBlockStyle(textFormat: ITextFormat) {
removeBlockStyle(textFormat, selectionStart, selectionEnd, makeBlock(textFormat, 0).map { it.javaClass })
}
fun <T : IAztecBlockSpan> removeEntireBlock(type: Class<T>) {
editableText.getSpans(selectionStart, selectionEnd, type).forEach {
IAztecNestable.pullUp(editableText, selectionStart, selectionEnd, it.nestingLevel)
editableText.removeSpan(it)
}
}
fun removeBlockStyle(textFormat: ITextFormat, originalStart: Int, originalEnd: Int,
spanTypes: List<Class<IAztecBlockSpan>> = listOf(IAztecBlockSpan::class.java),
ignoreLineBounds: Boolean = false) {
var start = originalStart
var end = originalEnd
// if splitting block set a range that would be excluded from it
val boundsOfSelectedText = if (ignoreLineBounds) {
IntRange(start, end)
} else {
getBoundsOfText(editableText, start, end)
}
var startOfBounds = boundsOfSelectedText.first
var endOfBounds = boundsOfSelectedText.last
if (ignoreLineBounds) {
val hasPrecedingSpans = spanTypes.any { spanType ->
editableText.getSpans(start, end, spanType)
.any { span -> editableText.getSpanStart(span) < startOfBounds }
}
if (hasPrecedingSpans) {
// let's make sure there's a newline before bounds start
if (editableText[startOfBounds - 1] != Constants.NEWLINE) {
// insert a newline in the start of (inside) the bounds
editableText.insert(startOfBounds, "" + Constants.NEWLINE)
// the insertion will have pushed everything forward so, adjust indices
start++
end++
startOfBounds++
endOfBounds++
}
}
val hasExtendingBeyondSpans = spanTypes.any { spanType ->
editableText.getSpans(start, end, spanType)
.any { span -> endOfBounds < editableText.getSpanEnd(span) }
}
if (hasExtendingBeyondSpans) {
// let's make sure there's a newline before bounds end
if (editableText[endOfBounds] != Constants.NEWLINE) {
// insert a newline before the bounds
editableText.insert(endOfBounds, "" + Constants.NEWLINE)
// the insertion will have pushed the end forward so, adjust the indices
end++
endOfBounds++
if (selectionEnd == endOfBounds) {
// apparently selection end moved along when we inserted the newline but we need it to stay
// back in order to save the newline from potential removal
editor.setSelection(if (selectionStart != selectionEnd) selectionStart else selectionEnd - 1,
selectionEnd - 1)
}
}
}
}
spanTypes.forEach { spanType ->
// when removing style from multiple selected lines, if the last selected line is empty
// or at the end of editor the selection wont include the trailing newline/EOB marker
// that will leave us with orphan <li> tag, so we need to shift index to the right
val hasLingeringEmptyListItem = AztecListItemSpan::class.java.isAssignableFrom(spanType)
&& editableText.length > end
&& (editableText[end] == '\n' || editableText[end] == Constants.END_OF_BUFFER_MARKER)
val endModifier = if (hasLingeringEmptyListItem) 1 else 0
val spans = editableText.getSpans(start, end + endModifier, spanType)
spans.forEach { span ->
val spanStart = editableText.getSpanStart(span)
val spanEnd = editableText.getSpanEnd(span)
val spanPrecedesLine = spanStart < startOfBounds
val spanExtendsBeyondLine = endOfBounds < spanEnd
if (spanPrecedesLine && !spanExtendsBeyondLine) {
// pull back the end of the block span
BlockHandler.set(editableText, span, spanStart, startOfBounds)
} else if (spanExtendsBeyondLine && !spanPrecedesLine) {
// push the start of the block span
BlockHandler.set(editableText, span, endOfBounds, spanEnd)
} else if (spanPrecedesLine && spanExtendsBeyondLine) {
// we need to split the span into two parts
// first, let's pull back the end of the existing span
BlockHandler.set(editableText, span, spanStart, startOfBounds)
// now, let's "clone" the span and set it
BlockHandler.set(editableText, makeBlockSpan(span::class, textFormat, span.nestingLevel, span.attributes), endOfBounds, spanEnd)
} else {
// tough luck. The span is fully inside the line so it gets axed.
IAztecNestable.pullUp(editableText, editableText.getSpanStart(span), editableText.getSpanEnd(span), span.nestingLevel)
editableText.removeSpan(span)
}
}
}
}
// TODO: Come up with a better way to init spans and get their classes (all the "make" methods)
fun makeBlock(textFormat: ITextFormat, nestingLevel: Int, attrs: AztecAttributes = AztecAttributes()): List<IAztecBlockSpan> {
return when (textFormat) {
AztecTextFormat.FORMAT_ORDERED_LIST -> listOf(createOrderedListSpan(nestingLevel, alignmentRendering, attrs, listStyle), createListItemSpan(nestingLevel + 1, alignmentRendering))
AztecTextFormat.FORMAT_UNORDERED_LIST -> listOf(createUnorderedListSpan(nestingLevel, alignmentRendering, attrs, listStyle), createListItemSpan(nestingLevel + 1, alignmentRendering))
AztecTextFormat.FORMAT_TASK_LIST -> listOf(createTaskListSpan(nestingLevel, alignmentRendering, attrs, editor.context, listStyle), createListItemSpan(nestingLevel + 1, alignmentRendering, listItemStyle = listItemStyle))
AztecTextFormat.FORMAT_QUOTE -> listOf(createAztecQuoteSpan(nestingLevel, attrs, alignmentRendering, quoteStyle))
AztecTextFormat.FORMAT_HEADING_1,
AztecTextFormat.FORMAT_HEADING_2,
AztecTextFormat.FORMAT_HEADING_3,
AztecTextFormat.FORMAT_HEADING_4,
AztecTextFormat.FORMAT_HEADING_5,
AztecTextFormat.FORMAT_HEADING_6 -> listOf(createHeadingSpan(nestingLevel, textFormat, attrs, alignmentRendering, headerStyle))
AztecTextFormat.FORMAT_PREFORMAT -> listOf(createPreformatSpan(nestingLevel, alignmentRendering, attrs, preformatStyle))
else -> listOf(createParagraphSpan(nestingLevel, alignmentRendering, attrs, paragraphStyle))
}
}
fun getAlignment(textFormat: ITextFormat?, text: CharSequence): Layout.Alignment? {
val direction = TextDirectionHeuristicsCompat.FIRSTSTRONG_LTR
val isRtl = direction.isRtl(text, 0, text.length)
return when (textFormat) {
AztecTextFormat.FORMAT_ALIGN_LEFT -> if (!isRtl) Layout.Alignment.ALIGN_NORMAL else Layout.Alignment.ALIGN_OPPOSITE
AztecTextFormat.FORMAT_ALIGN_CENTER -> Layout.Alignment.ALIGN_CENTER
AztecTextFormat.FORMAT_ALIGN_RIGHT -> if (isRtl) Layout.Alignment.ALIGN_NORMAL else Layout.Alignment.ALIGN_OPPOSITE
else -> null
}
}
fun makeBlockSpan(textFormat: ITextFormat, nestingLevel: Int, attrs: AztecAttributes = AztecAttributes()): IAztecBlockSpan {
return when (textFormat) {
AztecTextFormat.FORMAT_ORDERED_LIST -> makeBlockSpan(AztecOrderedListSpan::class, textFormat, nestingLevel, attrs)
AztecTextFormat.FORMAT_UNORDERED_LIST -> makeBlockSpan(AztecUnorderedListSpan::class, textFormat, nestingLevel, attrs)
AztecTextFormat.FORMAT_TASK_LIST -> makeBlockSpan(AztecTaskListSpan::class, textFormat, nestingLevel, attrs)
AztecTextFormat.FORMAT_QUOTE -> makeBlockSpan(AztecQuoteSpan::class, textFormat, nestingLevel, attrs)
AztecTextFormat.FORMAT_HEADING_1,
AztecTextFormat.FORMAT_HEADING_2,
AztecTextFormat.FORMAT_HEADING_3,
AztecTextFormat.FORMAT_HEADING_4,
AztecTextFormat.FORMAT_HEADING_5,
AztecTextFormat.FORMAT_HEADING_6 -> makeBlockSpan(AztecHeadingSpan::class, textFormat, nestingLevel, attrs)
AztecTextFormat.FORMAT_PREFORMAT -> makeBlockSpan(AztecPreformatSpan::class, textFormat, nestingLevel, attrs)
else -> createParagraphSpan(nestingLevel, alignmentRendering, attrs, paragraphStyle)
}
}
private fun <T : KClass<out IAztecBlockSpan>> makeBlockSpan(type: T, textFormat: ITextFormat, nestingLevel: Int, attrs: AztecAttributes = AztecAttributes()): IAztecBlockSpan {
val typeIsAssignableTo = { clazz: KClass<out Any> -> clazz.java.isAssignableFrom(type.java) }
return when {
typeIsAssignableTo(AztecOrderedListSpan::class) -> createOrderedListSpan(nestingLevel, alignmentRendering, attrs, listStyle)
typeIsAssignableTo(AztecUnorderedListSpan::class) -> createUnorderedListSpan(nestingLevel, alignmentRendering, attrs, listStyle)
typeIsAssignableTo(AztecTaskListSpan::class) -> createTaskListSpan(nestingLevel, alignmentRendering, attrs, editor.context, listStyle)
typeIsAssignableTo(AztecListItemSpan::class) -> createListItemSpan(nestingLevel, alignmentRendering, attrs, listItemStyle)
typeIsAssignableTo(AztecQuoteSpan::class) -> createAztecQuoteSpan(nestingLevel, attrs, alignmentRendering, quoteStyle)
typeIsAssignableTo(AztecHeadingSpan::class) -> createHeadingSpan(nestingLevel, textFormat, attrs, alignmentRendering, headerStyle)
typeIsAssignableTo(AztecPreformatSpan::class) -> createPreformatSpan(nestingLevel, alignmentRendering, attrs, preformatStyle)
else -> createParagraphSpan(nestingLevel, alignmentRendering, attrs, paragraphStyle)
}
}
fun setBlockStyle(blockElement: IAztecBlockSpan) {
when (blockElement) {
is AztecOrderedListSpan -> blockElement.listStyle = listStyle
is AztecUnorderedListSpan -> blockElement.listStyle = listStyle
is AztecTaskListSpan -> blockElement.listStyle = listStyle
is AztecQuoteSpan -> blockElement.quoteStyle = quoteStyle
is ParagraphSpan -> blockElement.paragraphStyle = paragraphStyle
is AztecPreformatSpan -> blockElement.preformatStyle = preformatStyle
is AztecHeadingSpan -> blockElement.headerStyle = headerStyle
}
}
fun getTopBlockDelimiters(start: Int, end: Int): List<Int> {
val delimiters = arrayListOf(start, end)
val bounds = hashMapOf<Int, Int>()
val startNesting = IAztecNestable.getMinNestingLevelAt(editableText, start)
bounds[start] = startNesting
val endNesting = IAztecNestable.getMinNestingLevelAt(editableText, end)
bounds[end] = endNesting
val blockSpans = editableText.getSpans(start, end, IAztecBlockSpan::class.java)
.filter { editableText.getSpanStart(it) >= start && editableText.getSpanEnd(it) <= end }
.sortedBy { editableText.getSpanStart(it) }
blockSpans.forEach {
var spanIndex = editableText.getSpanStart(it)
var nesting = IAztecNestable.getMinNestingLevelAt(editableText, spanIndex)
bounds[spanIndex] = nesting
spanIndex = editableText.getSpanEnd(it)
nesting = IAztecNestable.getMinNestingLevelAt(editableText, spanIndex)
bounds[spanIndex] = nesting
if (it is IAztecCompositeBlockSpan) {
val wrapper = SpanWrapper(editableText, it)
val parent = IAztecNestable.getParent(editableText, wrapper)
parent?.let {
if (parent.start < start || parent.end > end) {
delimiters.add(wrapper.start)
delimiters.add(wrapper.end)
}
}
}
}
if (bounds.isNotEmpty()) {
var lastIndex: Int = bounds.keys.first()
bounds.keys.forEach { key ->
val last = checkBound(bounds, key, delimiters, lastIndex)
if (last > -1) {
lastIndex = last
}
}
lastIndex = bounds.keys.last()
bounds.keys.reversed().forEach { key ->
val last = checkBound(bounds, key, delimiters, lastIndex)
if (last > -1) {
lastIndex = last
}
}
}
return delimiters.distinct().sorted()
}
private fun checkBound(bounds: HashMap<Int, Int>, key: Int, delimiters: ArrayList<Int>, lastIndex: Int): Int {
if (bounds[key]!! != bounds[lastIndex]!!) {
if (bounds[key]!! < bounds[lastIndex]!!) {
delimiters.add(key)
return key
}
}
return -1
}
/**
* Returns paragraph bounds (\n) to the left and to the right of selection.
*/
fun getBoundsOfText(editable: Editable, selectionStart: Int, selectionEnd: Int): IntRange {
val startOfBlock: Int
val endOfBlock: Int
val selectionStartIsOnTheNewLine = selectionStart != selectionEnd && selectionStart > 0
&& selectionStart < editableText.length
&& editable[selectionStart] == '\n'
val selectionStartIsBetweenNewlines = selectionStartIsOnTheNewLine
&& selectionStart > 0
&& selectionStart < editableText.length
&& editable[selectionStart - 1] == '\n'
val isTrailingNewlineAtTheEndOfSelection = selectionStart != selectionEnd
&& selectionEnd > 0
&& editableText.length > selectionEnd
&& editableText[selectionEnd] != Constants.END_OF_BUFFER_MARKER
&& editableText[selectionEnd] != '\n'
&& editableText[selectionEnd - 1] == '\n'
val indexOfFirstLineBreak: Int
var indexOfLastLineBreak = editable.indexOf("\n", selectionEnd)
if (selectionStartIsBetweenNewlines) {
indexOfFirstLineBreak = selectionStart
} else if (selectionStartIsOnTheNewLine) {
val isSingleCharacterLine = (selectionStart > 1 && editableText[selectionStart - 1] != '\n' && editableText[selectionStart - 2] == '\n') || selectionStart == 1
indexOfFirstLineBreak = if (isSingleCharacterLine) {
selectionStart - 1
} else {
editable.lastIndexOf("\n", selectionStart - 1) + 1
}
if (isTrailingNewlineAtTheEndOfSelection) {
indexOfLastLineBreak = editable.indexOf("\n", selectionEnd - 1)
}
} else if (isTrailingNewlineAtTheEndOfSelection) {
indexOfFirstLineBreak = editable.lastIndexOf("\n", selectionStart - 1) + 1
indexOfLastLineBreak = editable.indexOf("\n", selectionEnd - 1)
} else if (indexOfLastLineBreak > 0) {
indexOfFirstLineBreak = editable.lastIndexOf("\n", selectionStart - 1) + 1
} else if (indexOfLastLineBreak == -1) {
indexOfFirstLineBreak = if (selectionStart == 0) 0 else {
editable.lastIndexOf("\n", selectionStart) + 1
}
} else {
indexOfFirstLineBreak = editable.lastIndexOf("\n", selectionStart)
}
startOfBlock = if (indexOfFirstLineBreak != -1) indexOfFirstLineBreak else 0
endOfBlock = if (indexOfLastLineBreak != -1) (indexOfLastLineBreak + 1) else editable.length
return IntRange(startOfBlock, endOfBlock)
}
fun applyTextAlignment(textFormat: ITextFormat, start: Int = selectionStart, end: Int = selectionEnd) {
if (editableText.isEmpty()) {
editableText.append("" + Constants.END_OF_BUFFER_MARKER)
}
val boundsOfSelectedText = getBoundsOfText(editableText, start, end)
var spans = getAlignedSpans(null, boundsOfSelectedText.first, boundsOfSelectedText.last)
if (start == end) {
if (start == boundsOfSelectedText.first && spans.size > 1) {
spans = spans.filter { editableText.getSpanEnd(it) != start }
} else if (start == boundsOfSelectedText.last && spans.size > 1) {
spans = spans.filter { editableText.getSpanStart(it) != start }
}
}
if (spans.isNotEmpty()) {
spans.filter { it !is AztecListSpan }.forEach { changeAlignment(it, textFormat) }
} else {
val nestingLevel = IAztecNestable.getNestingLevelAt(editableText, boundsOfSelectedText.first)
val alignment = getAlignment(textFormat,
editableText.subSequence(boundsOfSelectedText.first until boundsOfSelectedText.last))
editableText.setSpan(createParagraphSpan(nestingLevel, alignment, paragraphStyle = paragraphStyle),
boundsOfSelectedText.first, boundsOfSelectedText.last, Spanned.SPAN_PARAGRAPH)
}
}
private fun changeAlignment(it: IAztecAlignmentSpan, blockElementType: ITextFormat?) {
val wrapper = SpanWrapper(editableText, it)
it.align = getAlignment(blockElementType, editableText.substring(wrapper.start until wrapper.end))
editableText.setSpan(it, wrapper.start, wrapper.end, wrapper.flags)
}
fun applyBlockStyle(blockElementType: ITextFormat, start: Int = selectionStart, end: Int = selectionEnd) {
if (editableText.isEmpty()) {
editableText.append("" + Constants.END_OF_BUFFER_MARKER)
}
val boundsOfSelectedText = getBoundsOfText(editableText, start, end)
val nestingLevel = IAztecNestable.getNestingLevelAt(editableText, start) + 1
val spanToApply = makeBlockSpan(blockElementType, nestingLevel)
removeBlockStylesFromSelectedLine(spanToApply)
if (start != end) {
// we want to push line blocks as deep as possible, because they can't contain other block elements (e.g. headings)
if (spanToApply is IAztecLineBlockSpan) {
applyLineBlock(blockElementType, boundsOfSelectedText.first, boundsOfSelectedText.last)
} else {
val delimiters = getTopBlockDelimiters(boundsOfSelectedText.first, boundsOfSelectedText.last)
for (i in 0 until delimiters.size - 1) {
pushNewBlock(delimiters[i], delimiters[i + 1], blockElementType)
}
}
editor.setSelection(editor.selectionStart)
} else {
val startOfLine = boundsOfSelectedText.first
val endOfLine = boundsOfSelectedText.last
// we can't add blocks around partial block elements (i.e. list items), everything must go inside
val isWithinPartialBlock = editableText.getSpans(boundsOfSelectedText.first,
boundsOfSelectedText.last, IAztecCompositeBlockSpan::class.java)
.any { it.nestingLevel == nestingLevel - 1 }
val startOfBlock = mergeWithBlockAbove(startOfLine, endOfLine, spanToApply, nestingLevel, isWithinPartialBlock, blockElementType)
val endOfBlock = mergeWithBlockBelow(endOfLine, startOfBlock, spanToApply, nestingLevel, isWithinPartialBlock, blockElementType)
if (spanToApply is IAztecLineBlockSpan) {
applyBlock(spanToApply, startOfBlock, endOfBlock)
} else {
pushNewBlock(startOfBlock, endOfBlock, blockElementType)
}
}
editor.setSelection(editor.selectionStart, editor.selectionEnd)
}
private fun pushNewBlock(start: Int, end: Int, blockElementType: ITextFormat) {
var nesting = IAztecNestable.getMinNestingLevelAt(editableText, start, end) + 1
// we can't add blocks around composite block elements (i.e. list items), everything must go inside
val isListItem = editableText.getSpans(start, end, IAztecCompositeBlockSpan::class.java)
.any { it.nestingLevel == nesting }
if (isListItem) {
nesting++
}
val newBlock = makeBlockSpan(blockElementType, nesting)
val pushBy = if (newBlock is AztecListSpan) 2 else 1
val spans = IAztecNestable.pushDeeper(editableText, start, end, nesting, pushBy)
spans.forEach {
it.remove()
}
applyBlock(newBlock, start, end)
spans.forEach {
it.reapply()
}
}
private fun mergeWithBlockAbove(startOfLine: Int, endOfLine: Int, spanToApply: IAztecBlockSpan, nestingLevel: Int, isWithinList: Boolean, blockElementType: ITextFormat): Int {
var startOfBlock = startOfLine
if (startOfLine != 0) {
val spansOnPreviousLine = editableText.getSpans(startOfLine - 1, startOfLine - 1, spanToApply.javaClass)
.firstOrNull()
if (spansOnPreviousLine == null) {
// no similar blocks before us so, don't expand
} else if (spansOnPreviousLine.nestingLevel != nestingLevel) {
// other block is at a different nesting level so, don't expand
} else if (spansOnPreviousLine is AztecHeadingSpan && spanToApply is AztecHeadingSpan) {
// Heading span is of different style so, don't expand
} else if (!isWithinList) {
// expand the start
startOfBlock = editableText.getSpanStart(spansOnPreviousLine)
liftBlock(blockElementType, startOfBlock, endOfLine)
}
}
return startOfBlock
}
private fun mergeWithBlockBelow(endOfLine: Int, startOfBlock: Int, spanToApply: IAztecBlockSpan, nestingLevel: Int, isWithinList: Boolean, blockElementType: ITextFormat): Int {
var endOfBlock = endOfLine
if (endOfLine != editableText.length) {
val spanOnNextLine = editableText.getSpans(endOfLine + 1, endOfLine + 1, spanToApply.javaClass)
.firstOrNull()
if (spanOnNextLine == null) {
// no similar blocks after us so, don't expand
} else if (spanOnNextLine.nestingLevel != nestingLevel) {
// other block is at a different nesting level so, don't expand
} else if (spanOnNextLine is AztecHeadingSpan && spanToApply is AztecHeadingSpan) {
// Heading span is of different style so, don't expand
} else if (!isWithinList) {
// expand the end
endOfBlock = editableText.getSpanEnd(spanOnNextLine)
liftBlock(blockElementType, startOfBlock, endOfBlock)
}
}
return endOfBlock
}
private fun applyBlock(blockSpan: IAztecBlockSpan, start: Int, end: Int) {
when (blockSpan) {
is AztecOrderedListSpan -> applyListBlock(blockSpan, start, end)
is AztecUnorderedListSpan -> applyListBlock(blockSpan, start, end)
is AztecTaskListSpan -> applyListBlock(blockSpan, start, end)
is AztecQuoteSpan -> applyQuote(blockSpan, start, end)
is AztecHeadingSpan -> applyHeadingBlock(blockSpan, start, end)
is AztecPreformatSpan -> BlockHandler.set(editableText, blockSpan, start, end)
else -> editableText.setSpan(blockSpan, start, end, Spanned.SPAN_PARAGRAPH)
}
}
private fun applyQuote(blockSpan: AztecQuoteSpan, start: Int, end: Int) {
BlockHandler.set(editableText, blockSpan, start, end)
}
private fun applyListBlock(listSpan: AztecListSpan, start: Int, end: Int) {
BlockHandler.set(editableText, listSpan, start, end)
// special case for styling single empty lines
if (end - start == 1 && (editableText[end - 1] == '\n' || editableText[end - 1] == Constants.END_OF_BUFFER_MARKER)) {
ListItemHandler.newListItem(editableText, start, end, listSpan.nestingLevel + 1, alignmentRendering, listItemStyle)
} else {
val listEnd = if (end == editableText.length) end else end - 1
val listContent = editableText.substring(start, listEnd)
val lines = TextUtils.split(listContent, "\n")
for (i in lines.indices) {
val lineLength = lines[i].length
val lineStart = (0 until i).sumOf { lines[it].length + 1 }
val lineEnd = (lineStart + lineLength).let {
if ((start + it) != editableText.length) it + 1 else it // include the newline or not
}
ListItemHandler.newListItem(
editableText,
start + lineStart,
start + lineEnd,
listSpan.nestingLevel + 1,
alignmentRendering, listItemStyle)
}
}
}
private fun applyLineBlock(format: ITextFormat, start: Int, end: Int) {
val lines = TextUtils.split(editableText.substring(start, end), "\n")
for (i in lines.indices) {
val splitLength = lines[i].length
val lineStart = start + (0 until i).sumOf { lines[it].length + 1 }
val lineEnd = (lineStart + splitLength + 1).coerceAtMost(end) // +1 to include the newline
val lineLength = lineEnd - lineStart
if (lineLength == 0) continue
val nesting = IAztecNestable.getNestingLevelAt(editableText, lineStart) + 1
val block = makeBlockSpan(format, nesting)
applyBlock(block, lineStart, lineEnd)
}
}
private fun applyHeadingBlock(headingSpan: AztecHeadingSpan, start: Int, end: Int) {
val lines = TextUtils.split(editableText.substring(start, end), "\n")
for (i in lines.indices) {
val splitLength = lines[i].length
val lineStart = start + (0 until i).sumOf { lines[it].length + 1 }
val lineEnd = (lineStart + splitLength + 1).coerceAtMost(end) // +1 to include the newline
val lineLength = lineEnd - lineStart
if (lineLength == 0) continue
HeadingHandler.cloneHeading(editableText, headingSpan, alignmentRendering, lineStart, lineEnd)
}
}
private fun liftBlock(textFormat: ITextFormat, start: Int, end: Int) {
when (textFormat) {
AztecTextFormat.FORMAT_ORDERED_LIST -> liftListBlock(AztecOrderedListSpan::class.java, start, end)
AztecTextFormat.FORMAT_UNORDERED_LIST -> liftListBlock(AztecUnorderedListSpan::class.java, start, end)
AztecTextFormat.FORMAT_TASK_LIST -> liftListBlock(AztecTaskListSpan::class.java, start, end)
AztecTextFormat.FORMAT_QUOTE -> editableText.getSpans(start, end, AztecQuoteSpan::class.java).forEach {
IAztecNestable.pullUp(editableText, start, end, it.nestingLevel)
editableText.removeSpan(it)
}
else -> editableText.getSpans(start, end, ParagraphSpan::class.java).forEach {
IAztecNestable.pullUp(editableText, start, end, it.nestingLevel)
editableText.removeSpan(it)
}
}
}
private fun liftListBlock(listSpan: Class<out AztecListSpan>, start: Int, end: Int) {
editableText.getSpans(start, end, listSpan).forEach { it ->
val wrapper = SpanWrapper(editableText, it)
editableText.getSpans(wrapper.start, wrapper.end, AztecListItemSpan::class.java).forEach { editableText.removeSpan(it) }
IAztecNestable.pullUp(editableText, start, end, wrapper.span.nestingLevel)
wrapper.remove()
}
}
fun containsList(format: ITextFormat, selStart: Int = selectionStart, selEnd: Int = selectionEnd): Boolean {
val lines = TextUtils.split(editableText.toString(), "\n")
val list = ArrayList<Int>()
for (i in lines.indices) {
val lineStart = (0 until i).sumOf { lines[it].length + 1 }
val lineEnd = lineStart + lines[i].length
if (lineStart > lineEnd) {
continue
}
/**
* lineStart >= selStart && selEnd >= lineEnd // single line, current entirely selected OR
* multiple lines (before and/or after), current entirely selected
* lineStart <= selEnd && selEnd <= lineEnd // single line, current partially or entirely selected OR
* multiple lines (after), current partially or entirely selected
* lineStart <= selStart && selStart <= lineEnd // single line, current partially or entirely selected OR
* multiple lines (before), current partially or entirely selected
*/
if ((lineStart >= selStart && selEnd >= lineEnd)
|| (selEnd in lineStart..lineEnd)
|| (selStart in lineStart..lineEnd)) {
list.add(i)
}
}
if (list.isEmpty()) return false
return list.any { index ->
val listSpans = getBlockElement(index, editableText, AztecListSpan::class.java)
val maxNestingLevel = listSpans.maxByOrNull { span -> span.nestingLevel }?.nestingLevel
listSpans.filter { it.nestingLevel == maxNestingLevel }.any { listSpan ->
when (listSpan) {
is AztecUnorderedListSpan -> format == AztecTextFormat.FORMAT_UNORDERED_LIST
is AztecOrderedListSpan -> format == AztecTextFormat.FORMAT_ORDERED_LIST
is AztecTaskListSpan -> format == AztecTextFormat.FORMAT_TASK_LIST
else -> {
false
}
}
}
}
}
private fun <T> getBlockElement(index: Int, text: Editable, blockClass: Class<T>): List<T> {
val lines = TextUtils.split(text.toString(), "\n")
if (index < 0 || index >= lines.size) {
return emptyList()
}
val start = (0 until index).sumOf { lines[it].length + 1 }
val end = start + lines[index].length
if (start > end) {
return emptyList()
}
return editableText.getSpans(start, end, blockClass).toList()
}
fun containsQuote(selStart: Int = selectionStart, selEnd: Int = selectionEnd): Boolean {
if (selStart < 0 || selEnd < 0) return false
return editableText.getSpans(selStart, selEnd, AztecQuoteSpan::class.java)
.any {
val spanStart = editableText.getSpanStart(it)
val spanEnd = editableText.getSpanEnd(it)
if (selStart == selEnd) {
if (editableText.length == selStart) {
selStart in spanStart..spanEnd
} else {
(spanEnd != selStart) && selStart in spanStart..spanEnd
}
} else {
(selStart in spanStart..spanEnd || selEnd in spanStart..spanEnd) ||
(spanStart in selStart..selEnd || spanEnd in spanStart..spanEnd)
}
}
}
fun containsHeading(textFormat: ITextFormat, selStart: Int = selectionStart, selEnd: Int = selectionEnd): Boolean {
val lines = TextUtils.split(editableText.toString(), "\n")
val list = ArrayList<Int>()
for (i in lines.indices) {
val lineStart = (0 until i).sumOf { lines[it].length + 1 }
val lineEnd = lineStart + lines[i].length
if (lineStart >= lineEnd) {
continue
}
/**
* lineStart >= selStart && selEnd >= lineEnd // single line, current entirely selected OR
* multiple lines (before and/or after), current entirely selected
* lineStart <= selEnd && selEnd <= lineEnd // single line, current partially or entirely selected OR
* multiple lines (after), current partially or entirely selected
* lineStart <= selStart && selStart <= lineEnd // single line, current partially or entirely selected OR
* multiple lines (before), current partially or entirely selected
*/
if ((lineStart >= selStart && selEnd >= lineEnd)
|| (selEnd in lineStart..lineEnd)
|| (selStart in lineStart..lineEnd)) {
list.add(i)
}
}
if (list.isEmpty()) return false
return list.any { containHeadingType(textFormat, it) }
}
private fun containHeadingType(textFormat: ITextFormat, index: Int): Boolean {
val lines = TextUtils.split(editableText.toString(), "\n")
if (index < 0 || index >= lines.size) {
return false
}
val start = (0 until index).sumOf { lines[it].length + 1 }
val end = start + lines[index].length
if (start >= end) {
return false
}
val spans = editableText.getSpans(start, end, AztecHeadingSpan::class.java)
for (span in spans) {
return when (textFormat) {
AztecTextFormat.FORMAT_HEADING_1 ->
span.heading == AztecHeadingSpan.Heading.H1
AztecTextFormat.FORMAT_HEADING_2 ->
span.heading == AztecHeadingSpan.Heading.H2
AztecTextFormat.FORMAT_HEADING_3 ->
span.heading == AztecHeadingSpan.Heading.H3
AztecTextFormat.FORMAT_HEADING_4 ->
span.heading == AztecHeadingSpan.Heading.H4
AztecTextFormat.FORMAT_HEADING_5 ->
span.heading == AztecHeadingSpan.Heading.H5
AztecTextFormat.FORMAT_HEADING_6 ->
span.heading == AztecHeadingSpan.Heading.H6
else -> false
}
}
return false
}
fun containsOtherHeadings(textFormat: ITextFormat, selStart: Int = selectionStart, selEnd: Int = selectionEnd): Boolean {
arrayOf(AztecTextFormat.FORMAT_HEADING_1,
AztecTextFormat.FORMAT_HEADING_2,
AztecTextFormat.FORMAT_HEADING_3,
AztecTextFormat.FORMAT_HEADING_4,
AztecTextFormat.FORMAT_HEADING_5,
AztecTextFormat.FORMAT_HEADING_6,
AztecTextFormat.FORMAT_PREFORMAT)
.filter { it != textFormat }
.forEach {
if (containsHeading(it, selStart, selEnd)) {
return true
}
}
return false
}
fun containsHeadingOnly(textFormat: ITextFormat, selStart: Int = selectionStart, selEnd: Int = selectionEnd): Boolean {
val otherHeadings = arrayOf(
AztecTextFormat.FORMAT_HEADING_1,
AztecTextFormat.FORMAT_HEADING_2,
AztecTextFormat.FORMAT_HEADING_3,
AztecTextFormat.FORMAT_HEADING_4,
AztecTextFormat.FORMAT_HEADING_5,
AztecTextFormat.FORMAT_HEADING_6,
AztecTextFormat.FORMAT_PREFORMAT)
.filter { it != textFormat }
return containsHeading(textFormat, selStart, selEnd) && otherHeadings.none { containsHeading(it, selStart, selEnd) }
}
fun containsAlignment(textFormat: ITextFormat, selStart: Int = selectionStart, selEnd: Int = selectionEnd): Boolean {
return getAlignedSpans(textFormat, selStart, selEnd).isNotEmpty()
}
private fun getAlignedSpans(textFormat: ITextFormat?, selStart: Int = selectionStart, selEnd: Int = selectionEnd): List<IAztecAlignmentSpan> {
if (selStart < 0 || selEnd < 0) return emptyList()
return editableText.getSpans(selStart, selEnd, IAztecAlignmentSpan::class.java)
.filter {
textFormat == null || it.align == getAlignment(textFormat,
editableText.substring(editableText.getSpanStart(it) until editableText.getSpanEnd(it)))
}
.filter {
val spanStart = editableText.getSpanStart(it)
val spanEnd = editableText.getSpanEnd(it)
if (selStart == selEnd) {
if (editableText.length == selStart) {
selStart in spanStart..spanEnd
} else {
(spanEnd != selStart) && selStart in spanStart..spanEnd
}
} else {
(selStart in spanStart..spanEnd || selEnd in spanStart..spanEnd) ||
(spanStart in selStart..selEnd || spanEnd in selStart..selEnd)
}
}
}
fun containsPreformat(selStart: Int = selectionStart, selEnd: Int = selectionEnd): Boolean {
val lines = TextUtils.split(editableText.toString(), "\n")
val list = ArrayList<Int>()
for (i in lines.indices) {
val lineStart = (0 until i).sumOf { lines[it].length + 1 }
val lineEnd = lineStart + lines[i].length
if (lineStart > lineEnd) {
continue
}
if (lineStart <= selectionEnd && lineEnd >= selectionStart) {
list.add(i)
}
}
if (list.isEmpty()) return false
return list.any { containsPreformat(it) }
}
fun containsPreformat(index: Int): Boolean {
val lines = TextUtils.split(editableText.toString(), "\n")
if (index < 0 || index >= lines.size) {
return false
}
val start = (0 until index).sumOf { lines[it].length + 1 }
val end = start + lines[index].length
if (start > end) {
return false
}
val spans = editableText.getSpans(start, end, AztecPreformatSpan::class.java)
return spans.any {
val spanEnd = editableText.getSpanEnd(it)
spanEnd != start || editableText[spanEnd] != '\n'
}
}
private fun switchListType(listTypeToSwitchTo: ITextFormat, start: Int = selectionStart, end: Int = selectionEnd, attrs: AztecAttributes = AztecAttributes()) {
var spans = editableText.getSpans(start, end, AztecListSpan::class.java)
val maxNestingLevel = spans.maxByOrNull { it.nestingLevel }?.nestingLevel
if (start == end && spans.filter { it.nestingLevel == maxNestingLevel }.size > 1) {
spans = spans.filter { editableText.getSpanStart(it) == start }.toTypedArray()
}
val maxSpanStart = spans.map { editableText.getSpanStart(it) }.filter {
it <= selectionStart
}.maxByOrNull { it } ?: selectionStart
spans.filter { editableText.getSpanStart(it) >= maxSpanStart }.forEach { existingListSpan ->
if (existingListSpan != null) {
val spanStart = editableText.getSpanStart(existingListSpan)
val spanEnd = editableText.getSpanEnd(existingListSpan)
val spanFlags = editableText.getSpanFlags(existingListSpan)
editableText.removeSpan(existingListSpan)
cleanupTaskItems(existingListSpan, listTypeToSwitchTo, spanStart, spanEnd)
editableText.setSpan(makeBlockSpan(listTypeToSwitchTo, existingListSpan.nestingLevel, attrs), spanStart, spanEnd, spanFlags)
editor.onSelectionChanged(start, end)
}
}
}
private fun cleanupTaskItems(existingListSpan: AztecListSpan?, listTypeToSwitchTo: ITextFormat, spanStart: Int, spanEnd: Int) {
val isTaskListSpan = existingListSpan is AztecTaskListSpan
val isSwitchingToTaskListSpan = listTypeToSwitchTo == AztecTextFormat.FORMAT_TASK_LIST
editableText.getSpans(spanStart, spanEnd, AztecListItemSpan::class.java).forEach {
if (isTaskListSpan) {
it.attributes.removeAttribute(AztecListItemSpan.CHECKED)
} else if (isSwitchingToTaskListSpan) {
it.attributes.setValue(AztecListItemSpan.CHECKED, "false")
}
}
}
fun switchHeaderType(headerTypeToSwitchTo: ITextFormat, start: Int = selectionStart, end: Int = selectionEnd) {
var spans = editableText.getSpans(start, end, AztecHeadingSpan::class.java)
if (start == end && spans.size > 1) {
spans = spans.filter { editableText.getSpanStart(it) == start }.toTypedArray()
}
spans.forEach { existingHeaderSpan ->
if (existingHeaderSpan != null) {
val spanStart = editableText.getSpanStart(existingHeaderSpan)
val spanEnd = editableText.getSpanEnd(existingHeaderSpan)
val spanFlags = editableText.getSpanFlags(existingHeaderSpan)
existingHeaderSpan.textFormat = headerTypeToSwitchTo
editableText.setSpan(existingHeaderSpan, spanStart, spanEnd, spanFlags)
editor.onSelectionChanged(start, end)
}
}
}
fun switchHeadingToPreformat(start: Int = selectionStart, end: Int = selectionEnd) {
var spans = editableText.getSpans(start, end, AztecHeadingSpan::class.java)
if (start == end && spans.size > 1) {
spans = spans.filter { editableText.getSpanStart(it) == start }.toTypedArray()
}
spans.forEach { heading ->
if (heading != null) {
val spanStart = editableText.getSpanStart(heading)
val spanEnd = editableText.getSpanEnd(heading)
val spanFlags = editableText.getSpanFlags(heading)
val spanType = makeBlock(heading.textFormat, 0).map { it.javaClass }
removeBlockStyle(heading.textFormat, spanStart, spanEnd, spanType)
editableText.setSpan(AztecPreformatSpan(heading.nestingLevel, heading.attributes, preformatStyle), spanStart, spanEnd, spanFlags)
editor.onSelectionChanged(start, end)
}
}
}
fun switchPreformatToHeading(headingTextFormat: ITextFormat, start: Int = selectionStart, end: Int = selectionEnd) {
var spans = editableText.getSpans(start, end, AztecPreformatSpan::class.java)
if (start == end && spans.size > 1) {
spans = spans.filter { editableText.getSpanStart(it) == start }.toTypedArray()
}
spans.forEach { preformat ->
if (preformat != null) {
val spanStart = editableText.getSpanStart(preformat)
val spanEnd = editableText.getSpanEnd(preformat)
val spanFlags = editableText.getSpanFlags(preformat)
val spanType = makeBlock(AztecTextFormat.FORMAT_PREFORMAT, 0).map { it.javaClass }
removeBlockStyle(AztecTextFormat.FORMAT_PREFORMAT, spanStart, spanEnd, spanType)
val headingSpan = createHeadingSpan(
preformat.nestingLevel,
headingTextFormat,
preformat.attributes,
alignmentRendering)
editableText.setSpan(headingSpan, spanStart, spanEnd, spanFlags)
editor.onSelectionChanged(start, end)
}
}
}
}
| mpl-2.0 | b0dea28df04983877ff9fda2b69596e3 | 45.89146 | 297 | 0.617547 | 4.916325 | false | false | false | false |
revbingo/SPIFF | src/main/java/com/revbingo/spiff/events/EventListeners.kt | 1 | 2980 | package com.revbingo.spiff.events
import com.revbingo.spiff.ExecutionException
import com.revbingo.spiff.datatypes.Datatype
import java.util.*
interface EventListener {
fun notifyData(ins: Datatype)
fun notifyGroup(groupName: String, start: Boolean)
}
class ClassBindingEventListener<T>(val clazz:Class<T>): EventListener {
private val rootBinding: T
private var currentBinding: Any
private val bindingStack: Stack<Any> = Stack()
private val bindingFactory = BindingFactory()
private var skipCount = 0
var skipUnboundGroups = false
var isStrict = true
init {
try {
rootBinding = clazz.newInstance()
currentBinding = rootBinding as Any
} catch (e: InstantiationException) {
throw ExecutionException("Could not instantiate ${clazz.getCanonicalName()}", e);
} catch (e: IllegalAccessException) {
throw ExecutionException("Could not access ${clazz.getCanonicalName()}", e);
}
}
override fun notifyData(ins: Datatype) {
if(skipUnboundGroups && skipCount > 0) return
val binder = bindingFactory.getBindingFor(ins.name, currentBinding.javaClass)
if(binder != null) {
binder.bind(currentBinding, ins.value)
} else {
if(isStrict) throw ExecutionException("Could not get binding for instruction ${ins.name}")
}
}
override fun notifyGroup(groupName: String, start: Boolean) {
if(start) {
bindingStack.push(currentBinding)
val binder = bindingFactory.getBindingFor(groupName, currentBinding.javaClass)
if(binder != null) {
currentBinding = binder.createAndBind(currentBinding)
} else {
if(isStrict) {
throw ExecutionException("Cound not get binding for group ${groupName}")
} else {
if(skipUnboundGroups) skipCount++
}
}
} else {
if(skipUnboundGroups && skipCount > 0) skipCount--
currentBinding = bindingStack.pop()
}
}
fun getResult(): T = rootBinding
}
class DebugEventListener(val wrappedListener: EventListener): EventListener {
var tabCount = 0
constructor(): this(object: EventListener {
override fun notifyData(ins: Datatype) { }
override fun notifyGroup(groupName: String, start: Boolean) {}
})
override fun notifyData(ins: Datatype) {
repeat(tabCount, { print("\t") })
println("[${ins.name}] ${ins.value}")
wrappedListener.notifyData(ins)
}
override fun notifyGroup(groupName: String, start: Boolean) {
if(!start) {
tabCount--
}
repeat(tabCount, { print("\t") })
val leader = if(start) ">>" else "<<"
println("${leader} [$groupName]")
if(start) tabCount++
wrappedListener.notifyGroup(groupName, start)
}
} | mit | f3b073dc70dcc3c6790c64c18c433290 | 29.418367 | 102 | 0.615436 | 4.71519 | false | false | false | false |
Zeyad-37/GenericUseCase | sampleApp/src/main/java/com/zeyad/usecases/app/components/VerticalDividerItemDecoration.kt | 2 | 1630 | package com.zeyad.usecases.app.components
import android.content.Context
import android.graphics.Canvas
import android.graphics.Rect
import android.graphics.drawable.Drawable
import android.support.v4.content.ContextCompat
import android.support.v7.widget.RecyclerView
import android.view.View
class VerticalDividerItemDecoration : RecyclerView.ItemDecoration {
private val mDivider: Drawable?
/**
* Default divider will be used
*/
constructor(context: Context) {
val styledAttributes = context.obtainStyledAttributes(ATTRS)
mDivider = styledAttributes.getDrawable(0)
styledAttributes.recycle()
}
/**
* Custom divider will be used
*/
constructor(context: Context, resId: Int) {
mDivider = ContextCompat.getDrawable(context, resId)
}
override fun onDraw(c: Canvas, parent: RecyclerView, state: RecyclerView.State) {
val childCount = parent.childCount
for (i in 0 until childCount) {
val child = parent.getChildAt(i)
val params = child.layoutParams as RecyclerView.LayoutParams
val top = child.bottom + params.bottomMargin
val bottom = top + mDivider!!.intrinsicHeight
mDivider.setBounds(parent.paddingLeft, top, parent.width - parent.paddingRight,
bottom)
mDivider.draw(c)
}
}
override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) {
outRect.bottom = 1
}
companion object {
private val ATTRS = intArrayOf(android.R.attr.listDivider)
}
}
| apache-2.0 | bf23c1aef7f944e887b5598bd9df61a0 | 30.346154 | 109 | 0.680982 | 4.836795 | false | false | false | false |
jakubveverka/SportApp | app/src/main/java/com/example/jakubveverka/sportapp/Models/DataManager.kt | 1 | 6201 | package com.example.jakubveverka.sportapp.Models
import android.content.Context
import com.example.jakubveverka.sportapp.Adapters.EventsRecyclerViewAdapter
import com.example.jakubveverka.sportapp.Entities.Event
import java.util.*
import android.widget.Toast
import com.example.jakubveverka.sportapp.Utils.MyLog
import com.google.firebase.database.*
/**
* Created by jakubveverka on 14.06.17.
* Class for data managment (Firebase and local SQL db)
*/
object DataManager {
var context: Context? = null
var userUid: String? = null
val childEventListener: ChildEventListener by lazy {
object : ChildEventListener {
override fun onChildAdded(dataSnapshot: DataSnapshot, previousChildName: String?) {
MyLog.d("onChildAdded:" + dataSnapshot.key)
val newEvent = dataSnapshot.getValue(Event::class.java) ?: return
newEvent.firebaseKey = dataSnapshot.key
addNewEventToOrderedList(newEvent)
}
override fun onChildChanged(dataSnapshot: DataSnapshot, previousChildName: String?) {
MyLog.d("onChildChanged:" + dataSnapshot.key)
val changedEvent = dataSnapshot.getValue(Event::class.java) ?: return
changedEvent.firebaseKey = dataSnapshot.key
updateEventInList(changedEvent)
}
override fun onChildRemoved(dataSnapshot: DataSnapshot) {
MyLog.d("onChildRemoved:" + dataSnapshot.key)
val eventKey = dataSnapshot.key
removeEventInListWithKey(eventKey)
}
override fun onChildMoved(dataSnapshot: DataSnapshot, previousChildName: String?) {
MyLog.d("onChildMoved:" + dataSnapshot.key)
val movedEvent = dataSnapshot.getValue(Event::class.java) ?: return
movedEvent.firebaseKey = dataSnapshot.key
removeEventInListWithKey(movedEvent.firebaseKey!!)
addNewEventToOrderedList(movedEvent)
}
override fun onCancelled(databaseError: DatabaseError) {
MyLog.d("onCancelled " + databaseError.toException().toString())
Toast.makeText(context, "Failed to load events.", Toast.LENGTH_SHORT).show()
}
}
}
var eventsRef: Query? = null
fun init(context: Context, userUid: String): DataManager {
this.context = context
this.userUid = userUid
return this
}
private val mEventsAdapter: EventsRecyclerViewAdapter by lazy {
EventsRecyclerViewAdapter(context!!)
}
private val mEvents: LinkedList<Event> = LinkedList()
/**
* Method decides where to save event and saves it
*/
fun saveEvent(event: Event): Boolean {
when (event.storage) {
Event.EventStorage.LOCAL -> return saveEventToDb(event)
Event.EventStorage.FIREBASE -> return saveEventToFirebase(event)
else -> throw Exception("Not supported EventStorage type")
}
}
private fun saveEventToDb(event: Event): Boolean {
return EventsDbHelper.getInstance(context!!).saveEvent(event)
}
private fun saveEventToFirebase(event: Event): Boolean {
val database = FirebaseDatabase.getInstance().reference
val eventsRef = database.child("users").child(event.userUid).child("events").push()
eventsRef.setValue(event)
return true
}
fun getAllEventsAdapterOfUserWithUid(): EventsRecyclerViewAdapter {
mEvents.clear()
getAllEventsOfUserWithUid()
mEventsAdapter.mValues = mEvents
return mEventsAdapter
}
private fun getAllEventsOfUserWithUid() {
getLocalDbEventsOfUserWithUid()
getFirebaseDbEventsOfUserWithUid()
}
fun getLocalDbEventsOfUserWithUid() {
mEvents.addAll(EventsDbHelper.getInstance(context!!).getAllEventsOfUserWithUid(userUid!!))
}
/*private fun getFirebaseDbEventsOfUserWithUid(userUid: String) {
startListeningForEvents(userUid)
}*/
private fun addNewEventToOrderedList(newEvent: Event) {
var inserted = false
var insertedIndex = 0
MyLog.d("mEventsSize in addNewEventToOrderedList: ${mEvents.size}")
val iterator = mEvents.listIterator(mEvents.size)
while(iterator.hasPrevious()) {
val event = iterator.previous()
if(newEvent.startTime >= event.startTime) {
if(iterator.hasNext()) iterator.next()
iterator.add(newEvent)
inserted = true
insertedIndex = iterator.nextIndex() - 1
MyLog.d("inserting at index: $insertedIndex")
break
}
}
if(!inserted) iterator.add(newEvent)
mEventsAdapter.notifyItemInserted(insertedIndex)
}
private fun updateEventInList(changedEvent: Event) {
val iterator = mEvents.listIterator(mEvents.size)
while(iterator.hasPrevious()) {
val event = iterator.previous()
if(event.firebaseKey == changedEvent.firebaseKey) {
iterator.set(changedEvent)
mEventsAdapter.notifyItemChanged(iterator.nextIndex())
break
}
}
}
private fun removeEventInListWithKey(key: String) {
val iterator = mEvents.listIterator(mEvents.size)
while(iterator.hasPrevious()) {
val event = iterator.previous()
if(event.firebaseKey == key) {
val removedIndex = iterator.nextIndex()
iterator.remove()
mEventsAdapter.notifyItemRemoved(removedIndex)
break
}
}
}
fun getFirebaseDbEventsOfUserWithUid() {
eventsRef?.removeEventListener(childEventListener)
val database = FirebaseDatabase.getInstance().reference
eventsRef = database.child("users").child(userUid!!).child("events").orderByChild("startTime")
eventsRef?.addChildEventListener(childEventListener)
}
fun stopListeningOnFirebaseDb() {
eventsRef?.removeEventListener(childEventListener)
}
} | mit | c612d417abd5bdde5f7c496df2d7be02 | 35.916667 | 102 | 0.642316 | 4.964772 | false | false | false | false |
robfletcher/orca | orca-queue/src/main/kotlin/com/netflix/spinnaker/orca/q/handler/RunTaskHandler.kt | 2 | 17767 | /*
* Copyright 2017 Netflix, 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.netflix.spinnaker.orca.q.handler
import com.netflix.spectator.api.BasicTag
import com.netflix.spectator.api.Registry
import com.netflix.spinnaker.kork.dynamicconfig.DynamicConfigService
import com.netflix.spinnaker.kork.exceptions.UserException
import com.netflix.spinnaker.orca.TaskExecutionInterceptor
import com.netflix.spinnaker.orca.TaskResolver
import com.netflix.spinnaker.orca.api.pipeline.OverridableTimeoutRetryableTask
import com.netflix.spinnaker.orca.api.pipeline.RetryableTask
import com.netflix.spinnaker.orca.api.pipeline.Task
import com.netflix.spinnaker.orca.api.pipeline.TaskResult
import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionStatus
import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionStatus.CANCELED
import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionStatus.FAILED_CONTINUE
import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionStatus.PAUSED
import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionStatus.REDIRECT
import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionStatus.RUNNING
import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionStatus.SKIPPED
import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionStatus.STOPPED
import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionStatus.SUCCEEDED
import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionStatus.TERMINAL
import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionType
import com.netflix.spinnaker.orca.api.pipeline.models.PipelineExecution
import com.netflix.spinnaker.orca.api.pipeline.models.StageExecution
import com.netflix.spinnaker.orca.api.pipeline.models.TaskExecution
import com.netflix.spinnaker.orca.clouddriver.utils.CloudProviderAware
import com.netflix.spinnaker.orca.exceptions.ExceptionHandler
import com.netflix.spinnaker.orca.exceptions.TimeoutException
import com.netflix.spinnaker.orca.ext.beforeStages
import com.netflix.spinnaker.orca.ext.failureStatus
import com.netflix.spinnaker.orca.ext.isManuallySkipped
import com.netflix.spinnaker.orca.pipeline.RestrictExecutionDuringTimeWindow
import com.netflix.spinnaker.orca.pipeline.StageDefinitionBuilderFactory
import com.netflix.spinnaker.orca.pipeline.persistence.ExecutionRepository
import com.netflix.spinnaker.orca.pipeline.util.ContextParameterProcessor
import com.netflix.spinnaker.orca.pipeline.util.StageNavigator
import com.netflix.spinnaker.orca.q.CompleteTask
import com.netflix.spinnaker.orca.q.InvalidTaskType
import com.netflix.spinnaker.orca.q.PauseTask
import com.netflix.spinnaker.orca.q.RunTask
import com.netflix.spinnaker.orca.q.metrics.MetricsTagHelper
import com.netflix.spinnaker.orca.time.toDuration
import com.netflix.spinnaker.orca.time.toInstant
import com.netflix.spinnaker.q.Message
import com.netflix.spinnaker.q.Queue
import java.time.Clock
import java.time.Duration
import java.time.Duration.ZERO
import java.time.Instant
import java.time.temporal.TemporalAmount
import java.util.concurrent.TimeUnit
import kotlin.collections.set
import org.apache.commons.lang3.time.DurationFormatUtils
import org.slf4j.MDC
import org.springframework.stereotype.Component
@Component
class RunTaskHandler(
override val queue: Queue,
override val repository: ExecutionRepository,
override val stageNavigator: StageNavigator,
override val stageDefinitionBuilderFactory: StageDefinitionBuilderFactory,
override val contextParameterProcessor: ContextParameterProcessor,
private val taskResolver: TaskResolver,
private val clock: Clock,
private val exceptionHandlers: List<ExceptionHandler>,
private val taskExecutionInterceptors: List<TaskExecutionInterceptor>,
private val registry: Registry,
private val dynamicConfigService: DynamicConfigService
) : OrcaMessageHandler<RunTask>, ExpressionAware, AuthenticationAware {
/**
* If a task takes longer than this number of ms to run, we will print a warning.
* This is an indication that the task might eventually hit the dreaded message ack timeout and might end
* running multiple times cause unintended side-effects.
*/
private val warningInvocationTimeMs: Int = dynamicConfigService.getConfig(
Int::class.java,
"tasks.warningInvocationTimeMs",
30000
)
override fun handle(message: RunTask) {
message.withTask { origStage, taskModel, task ->
var stage = origStage
stage.withAuth {
stage.withLoggingContext(taskModel) {
val thisInvocationStartTimeMs = clock.millis()
val execution = stage.execution
var taskResult: TaskResult? = null
try {
taskExecutionInterceptors.forEach { t -> stage = t.beforeTaskExecution(task, stage) }
if (execution.isCanceled) {
task.onCancel(stage)
queue.push(CompleteTask(message, CANCELED))
} else if (execution.status.isComplete) {
queue.push(CompleteTask(message, CANCELED))
} else if (execution.status == PAUSED) {
queue.push(PauseTask(message))
} else if (stage.isManuallySkipped()) {
queue.push(CompleteTask(message, SKIPPED))
} else {
try {
task.checkForTimeout(stage, taskModel, message)
} catch (e: TimeoutException) {
registry
.timeoutCounter(stage.execution.type, stage.execution.application, stage.type, taskModel.name)
.increment()
taskResult = task.onTimeout(stage)
if (taskResult == null) {
// This means this task doesn't care to alter the timeout flow, just throw
throw e
}
if (!setOf(TERMINAL, FAILED_CONTINUE).contains(taskResult.status)) {
log.error("Task ${task.javaClass.name} returned invalid status (${taskResult.status}) for onTimeout")
throw e
}
}
if (taskResult == null) {
taskResult = task.execute(stage.withMergedContext())
taskExecutionInterceptors.forEach { t -> taskResult = t.afterTaskExecution(task, stage, taskResult) }
}
taskResult!!.let { result: TaskResult ->
// TODO: rather send this data with CompleteTask message
stage.processTaskOutput(result)
when (result.status) {
RUNNING -> {
queue.push(message, task.backoffPeriod(taskModel, stage))
trackResult(stage, thisInvocationStartTimeMs, taskModel, result.status)
}
SUCCEEDED, REDIRECT, SKIPPED, FAILED_CONTINUE, STOPPED -> {
queue.push(CompleteTask(message, result.status))
trackResult(stage, thisInvocationStartTimeMs, taskModel, result.status)
}
CANCELED -> {
task.onCancel(stage)
val status = stage.failureStatus(default = result.status)
queue.push(CompleteTask(message, status, result.status))
trackResult(stage, thisInvocationStartTimeMs, taskModel, status)
}
TERMINAL -> {
val status = stage.failureStatus(default = result.status)
queue.push(CompleteTask(message, status, result.status))
trackResult(stage, thisInvocationStartTimeMs, taskModel, status)
}
else ->
TODO("Unhandled task status ${result.status}")
}
}
}
} catch (e: Exception) {
val exceptionDetails = exceptionHandlers.shouldRetry(e, taskModel.name)
if (exceptionDetails?.shouldRetry == true) {
log.warn("Error running ${message.taskType.simpleName} for ${message.executionType}[${message.executionId}]")
queue.push(message, task.backoffPeriod(taskModel, stage))
trackResult(stage, thisInvocationStartTimeMs, taskModel, RUNNING)
} else if (e is TimeoutException && stage.context["markSuccessfulOnTimeout"] == true) {
trackResult(stage, thisInvocationStartTimeMs, taskModel, SUCCEEDED)
queue.push(CompleteTask(message, SUCCEEDED))
} else {
if (e !is TimeoutException) {
if (e is UserException) {
log.warn("${message.taskType.simpleName} for ${message.executionType}[${message.executionId}] failed, likely due to user error", e)
} else {
log.error("Error running ${message.taskType.simpleName} for ${message.executionType}[${message.executionId}]", e)
}
}
val status = stage.failureStatus(default = TERMINAL)
stage.context["exception"] = exceptionDetails
repository.storeStage(stage)
queue.push(CompleteTask(message, status, TERMINAL))
trackResult(stage, thisInvocationStartTimeMs, taskModel, status)
}
}
}
}
}
}
private fun trackResult(stage: StageExecution, thisInvocationStartTimeMs: Long, taskModel: TaskExecution, status: ExecutionStatus) {
try {
val commonTags = MetricsTagHelper.commonTags(stage, taskModel, status)
val detailedTags = MetricsTagHelper.detailedTaskTags(stage, taskModel, status)
val elapsedMillis = clock.millis() - thisInvocationStartTimeMs
hashMapOf(
"task.invocations.duration" to commonTags + BasicTag("application", stage.execution.application),
"task.invocations.duration.withType" to commonTags + detailedTags
).forEach { name, tags ->
registry.timer(name, tags).record(elapsedMillis, TimeUnit.MILLISECONDS)
}
if (elapsedMillis >= warningInvocationTimeMs) {
log.info(
"Task invocation took over ${warningInvocationTimeMs}ms " +
"(taskType: ${taskModel.implementingClass}, stageType: ${stage.type}, stageId: ${stage.id})"
)
}
} catch (e: java.lang.Exception) {
log.warn("Failed to track result for stage: ${stage.id}, task: ${taskModel.id}", e)
}
}
override val messageType = RunTask::class.java
private fun RunTask.withTask(block: (StageExecution, TaskExecution, Task) -> Unit) =
withTask { stage, taskModel ->
try {
taskResolver.getTask(taskModel.implementingClass)
} catch (e: TaskResolver.NoSuchTaskException) {
try {
taskResolver.getTask(taskType)
} catch (e: TaskResolver.NoSuchTaskException) {
queue.push(InvalidTaskType(this, taskType.name))
null
}
}?.let {
block.invoke(stage, taskModel, it)
}
}
private fun Task.backoffPeriod(taskModel: TaskExecution, stage: StageExecution): TemporalAmount =
when (this) {
is RetryableTask -> Duration.ofMillis(
retryableBackOffPeriod(taskModel, stage).coerceAtMost(taskExecutionInterceptors.maxBackoff())
)
else -> Duration.ofMillis(1000)
}
/**
* The max back off value always wins. For example, given the following dynamic configs:
* `tasks.global.backOffPeriod = 5000`
* `tasks.aws.backOffPeriod = 80000`
* `tasks.aws.someAccount.backoffPeriod = 60000`
* `tasks.aws.backoffPeriod` will be used (given the criteria matches and unless the default dynamicBackOffPeriod is greater).
*/
private fun RetryableTask.retryableBackOffPeriod(
taskModel: TaskExecution,
stage: StageExecution
): Long {
val dynamicBackOffPeriod = getDynamicBackoffPeriod(
stage, Duration.ofMillis(System.currentTimeMillis() - (taskModel.startTime ?: 0))
)
val backOffs: MutableList<Long> = mutableListOf(
dynamicBackOffPeriod,
dynamicConfigService.getConfig(
Long::class.java,
"tasks.global.backOffPeriod",
dynamicBackOffPeriod
)
)
if (this is CloudProviderAware && hasCloudProvider(stage)) {
backOffs.add(
dynamicConfigService.getConfig(
Long::class.java,
"tasks.${getCloudProvider(stage)}.backOffPeriod",
dynamicBackOffPeriod
)
)
if (hasCredentials(stage)) {
backOffs.add(
dynamicConfigService.getConfig(
Long::class.java,
"tasks.${getCloudProvider(stage)}.${getCredentials(stage)}.backOffPeriod",
dynamicBackOffPeriod
)
)
}
}
return backOffs.max() ?: dynamicBackOffPeriod
}
private fun List<TaskExecutionInterceptor>.maxBackoff(): Long =
this.fold(Long.MAX_VALUE) { backoff, interceptor ->
backoff.coerceAtMost(interceptor.maxTaskBackoff())
}
private fun formatTimeout(timeout: Long): String {
return DurationFormatUtils.formatDurationWords(timeout, true, true)
}
private fun Task.checkForTimeout(stage: StageExecution, taskModel: TaskExecution, message: Message) {
if (stage.type == RestrictExecutionDuringTimeWindow.TYPE) {
return
} else {
checkForStageTimeout(stage)
checkForTaskTimeout(taskModel, stage, message)
}
}
private fun Task.checkForTaskTimeout(taskModel: TaskExecution, stage: StageExecution, message: Message) {
if (this is RetryableTask) {
val startTime = taskModel.startTime.toInstant()
if (startTime != null) {
val pausedDuration = stage.execution.pausedDurationRelativeTo(startTime)
val elapsedTime = Duration.between(startTime, clock.instant())
val actualTimeout = (
if (this is OverridableTimeoutRetryableTask && stage.parentWithTimeout.isPresent)
stage.parentWithTimeout.get().timeout.get().toDuration()
else
getDynamicTimeout(stage).toDuration()
)
if (elapsedTime.minus(pausedDuration) > actualTimeout) {
val durationString = formatTimeout(elapsedTime.toMillis())
val msg = StringBuilder("${javaClass.simpleName} of stage ${stage.name} timed out after $durationString. ")
msg.append("pausedDuration: ${formatTimeout(pausedDuration.toMillis())}, ")
msg.append("elapsedTime: ${formatTimeout(elapsedTime.toMillis())}, ")
msg.append("timeoutValue: ${formatTimeout(actualTimeout.toMillis())}")
log.info(msg.toString())
throw TimeoutException(msg.toString())
}
}
}
}
private fun checkForStageTimeout(stage: StageExecution) {
stage.parentWithTimeout.ifPresent {
val startTime = it.startTime.toInstant()
if (startTime != null) {
val elapsedTime = Duration.between(startTime, clock.instant())
val pausedDuration = stage.execution.pausedDurationRelativeTo(startTime)
val executionWindowDuration = stage.executionWindow?.duration ?: ZERO
val timeout = Duration.ofMillis(it.timeout.get())
if (elapsedTime.minus(pausedDuration).minus(executionWindowDuration) > timeout) {
throw TimeoutException("Stage ${stage.name} timed out after ${formatTimeout(elapsedTime.toMillis())}")
}
}
}
}
private val StageExecution.executionWindow: StageExecution?
get() = beforeStages()
.firstOrNull { it.type == RestrictExecutionDuringTimeWindow.TYPE }
private val StageExecution.duration: Duration
get() = run {
if (startTime == null || endTime == null) {
throw IllegalStateException("Only valid on completed stages")
}
Duration.between(startTime.toInstant(), endTime.toInstant())
}
private fun Registry.timeoutCounter(
executionType: ExecutionType,
application: String,
stageType: String,
taskType: String
) =
counter(
createId("queue.task.timeouts")
.withTags(
mapOf(
"executionType" to executionType.toString(),
"application" to application,
"stageType" to stageType,
"taskType" to taskType
)
)
)
private fun PipelineExecution.pausedDurationRelativeTo(instant: Instant?): Duration {
val pausedDetails = paused
return if (pausedDetails != null) {
if (pausedDetails.pauseTime.toInstant()?.isAfter(instant) == true) {
Duration.ofMillis(pausedDetails.pausedMs)
} else ZERO
} else ZERO
}
private fun StageExecution.processTaskOutput(result: TaskResult) {
val filteredOutputs = result.outputs.filterKeys { it != "stageTimeoutMs" }
if (result.context.isNotEmpty() || filteredOutputs.isNotEmpty()) {
context.putAll(result.context)
outputs.putAll(filteredOutputs)
repository.storeStage(this)
}
}
private fun StageExecution.withLoggingContext(taskModel: TaskExecution, block: () -> Unit) {
try {
MDC.put("stageType", type)
MDC.put("taskType", taskModel.implementingClass)
if (taskModel.startTime != null) {
MDC.put("taskStartTime", taskModel.startTime.toString())
}
block.invoke()
} finally {
MDC.remove("stageType")
MDC.remove("taskType")
MDC.remove("taskStartTime")
}
}
}
| apache-2.0 | 36e9fec7cdc2da74855ff90a433afbb5 | 41.002364 | 149 | 0.681995 | 4.879703 | false | false | false | false |
jiaminglu/kotlin-native | backend.native/compiler/ir/backend.native/src/org/jetbrains/kotlin/ir/util/IrUnboundSymbolReplacer.kt | 1 | 14575 | package org.jetbrains.kotlin.ir.util
import org.jetbrains.kotlin.backend.common.pop
import org.jetbrains.kotlin.backend.common.push
import org.jetbrains.kotlin.backend.konan.Context
import org.jetbrains.kotlin.descriptors.DeclarationDescriptor
import org.jetbrains.kotlin.descriptors.FunctionDescriptor
import org.jetbrains.kotlin.ir.IrElement
import org.jetbrains.kotlin.ir.IrStatement
import org.jetbrains.kotlin.ir.declarations.IrAnonymousInitializer
import org.jetbrains.kotlin.ir.declarations.IrFunction
import org.jetbrains.kotlin.ir.declarations.IrModuleFragment
import org.jetbrains.kotlin.ir.declarations.IrSymbolOwner
import org.jetbrains.kotlin.ir.expressions.*
import org.jetbrains.kotlin.ir.expressions.impl.*
import org.jetbrains.kotlin.ir.symbols.IrBindableSymbol
import org.jetbrains.kotlin.ir.symbols.IrClassifierSymbol
import org.jetbrains.kotlin.ir.symbols.IrFunctionSymbol
import org.jetbrains.kotlin.ir.symbols.IrSymbol
import org.jetbrains.kotlin.ir.visitors.*
@Deprecated("")
internal fun IrModuleFragment.replaceUnboundSymbols(context: Context) {
val collector = DeclarationSymbolCollector()
with(collector) {
with(irBuiltins) {
for (op in arrayOf(eqeqeqFun, eqeqFun, lt0Fun, lteq0Fun, gt0Fun, gteq0Fun, throwNpeFun, booleanNotFun,
noWhenBranchMatchedExceptionFun)) {
register(op.symbol)
}
}
}
this.acceptVoid(collector)
val symbolTable = context.ir.symbols.symbolTable
this.transformChildrenVoid(IrUnboundSymbolReplacer(symbolTable, collector.descriptorToSymbol))
// Generate missing external stubs:
// TODO: ModuleGenerator::generateUnboundSymbolsAsDependencies(IRModuleFragment) is private function :/
ExternalDependenciesGenerator(symbolTable = context.psi2IrGeneratorContext.symbolTable, irBuiltIns = context.irBuiltIns).generateUnboundSymbolsAsDependencies(this)
// Merge duplicated module and package declarations:
this.acceptVoid(object : IrElementVisitorVoid {
override fun visitElement(element: IrElement) {}
override fun visitModuleFragment(declaration: IrModuleFragment) {
declaration.dependencyModules.forEach { it.acceptVoid(this) }
val dependencyModules = declaration.dependencyModules.groupBy { it.descriptor }.map { (_, fragments) ->
fragments.reduce { firstModule, nextModule ->
firstModule.apply {
mergeFrom(nextModule)
}
}
}
declaration.dependencyModules.clear()
declaration.dependencyModules.addAll(dependencyModules)
}
})
}
private fun IrModuleFragment.mergeFrom(other: IrModuleFragment): Unit {
assert(this.files.isEmpty())
assert(other.files.isEmpty())
val thisPackages = this.externalPackageFragments.groupBy { it.packageFragmentDescriptor }
other.externalPackageFragments.forEach {
val thisPackage = thisPackages[it.packageFragmentDescriptor]?.single()
if (thisPackage == null) {
this.externalPackageFragments.add(it)
} else {
thisPackage.declarations.addAll(it.declarations)
}
}
}
private class DeclarationSymbolCollector : IrElementVisitorVoid {
val descriptorToSymbol = mutableMapOf<DeclarationDescriptor, IrSymbol>()
fun register(symbol: IrSymbol) {
descriptorToSymbol[symbol.descriptor] = symbol
}
override fun visitElement(element: IrElement) {
element.acceptChildrenVoid(this)
if (element is IrSymbolOwner && element !is IrAnonymousInitializer) {
register(element.symbol)
}
}
}
private class IrUnboundSymbolReplacer(
val symbolTable: SymbolTable,
val descriptorToSymbol: Map<DeclarationDescriptor, IrSymbol>
) : IrElementTransformerVoid() {
private inline fun <D : DeclarationDescriptor, reified S : IrBindableSymbol<D, *>> S.replace(
referenceSymbol: (SymbolTable, D) -> S): S? {
if (this.isBound) {
return null
}
descriptorToSymbol[this.descriptor]?.let {
return it as S
}
return referenceSymbol(symbolTable, this.descriptor)
}
private inline fun <D : DeclarationDescriptor, reified S : IrBindableSymbol<D, *>> S.replaceOrSame(
referenceSymbol: (SymbolTable, D) -> S): S = this.replace(referenceSymbol) ?: this
private fun IrFunctionSymbol.replace(
referenceSymbol: (SymbolTable, FunctionDescriptor) -> IrFunctionSymbol): IrFunctionSymbol? {
if (this.isBound) {
return null
}
descriptorToSymbol[this.descriptor]?.let {
return it as IrFunctionSymbol
}
return referenceSymbol(symbolTable, this.descriptor)
}
private inline fun <reified S : IrSymbol> S.replaceLocal(): S? {
return if (this.isBound) {
null
} else {
descriptorToSymbol[this.descriptor] as S
}
}
override fun visitGetValue(expression: IrGetValue): IrExpression {
val symbol = expression.symbol.replaceLocal() ?: return super.visitGetValue(expression)
expression.transformChildrenVoid(this)
return with(expression) {
IrGetValueImpl(startOffset, endOffset, symbol, origin)
}
}
override fun visitSetVariable(expression: IrSetVariable): IrExpression {
val symbol = expression.symbol.replaceLocal() ?: return super.visitSetVariable(expression)
expression.transformChildrenVoid(this)
return with(expression) {
IrSetVariableImpl(startOffset, endOffset, symbol, value, origin)
}
}
override fun visitGetObjectValue(expression: IrGetObjectValue): IrExpression {
val symbol = expression.symbol.replace(SymbolTable::referenceClass) ?:
return super.visitGetObjectValue(expression)
expression.transformChildrenVoid(this)
return with(expression) {
IrGetObjectValueImpl(startOffset, endOffset, type, symbol)
}
}
override fun visitGetEnumValue(expression: IrGetEnumValue): IrExpression {
val symbol = expression.symbol.replace(SymbolTable::referenceEnumEntry) ?:
return super.visitGetEnumValue(expression)
expression.transformChildrenVoid(this)
return with(expression) {
IrGetEnumValueImpl(startOffset, endOffset, type, symbol)
}
}
override fun visitClassReference(expression: IrClassReference): IrExpression {
val symbol = expression.symbol.let {
if (it.isBound) {
return super.visitClassReference(expression)
}
descriptorToSymbol[it.descriptor]?.let {
it as IrClassifierSymbol
}
symbolTable.referenceClassifier(it.descriptor)
}
expression.transformChildrenVoid(this)
return with(expression) {
IrClassReferenceImpl(startOffset, endOffset, type, symbol)
}
}
override fun visitGetField(expression: IrGetField): IrExpression {
val symbol = expression.symbol.replaceOrSame(SymbolTable::referenceField)
val superQualifierSymbol = expression.superQualifierSymbol?.replaceOrSame(SymbolTable::referenceClass)
if (symbol == expression.symbol && superQualifierSymbol == expression.superQualifierSymbol) {
return super.visitGetField(expression)
}
expression.transformChildrenVoid(this)
return with(expression) {
IrGetFieldImpl(startOffset, endOffset, symbol, receiver, origin, superQualifierSymbol)
}
}
override fun visitSetField(expression: IrSetField): IrExpression {
val symbol = expression.symbol.replaceOrSame(SymbolTable::referenceField)
val superQualifierSymbol = expression.superQualifierSymbol?.replaceOrSame(SymbolTable::referenceClass)
if (symbol == expression.symbol && superQualifierSymbol == expression.superQualifierSymbol) {
return super.visitSetField(expression)
}
expression.transformChildrenVoid(this)
return with(expression) {
IrSetFieldImpl(startOffset, endOffset, symbol, receiver, value, origin, superQualifierSymbol)
}
}
override fun visitCall(expression: IrCall): IrExpression {
val symbol = expression.symbol.replace(SymbolTable::referenceFunction) ?: expression.symbol
val superQualifierSymbol = expression.superQualifierSymbol?.replaceOrSame(SymbolTable::referenceClass)
if (symbol == expression.symbol && superQualifierSymbol == expression.superQualifierSymbol) {
return super.visitCall(expression)
}
expression.transformChildrenVoid()
return with(expression) {
IrCallImpl(startOffset, endOffset, symbol, descriptor,
getTypeArgumentsMap(),
origin, superQualifierSymbol).also {
it.copyArgumentsFrom(this)
}
}
}
private fun IrMemberAccessExpression.getTypeArgumentsMap() =
descriptor.original.typeParameters.associate { it to getTypeArgumentOrDefault(it) }
private fun IrMemberAccessExpressionBase.copyArgumentsFrom(original: IrMemberAccessExpression) {
dispatchReceiver = original.dispatchReceiver
extensionReceiver = original.extensionReceiver
original.descriptor.valueParameters.forEachIndexed { index, _ ->
putValueArgument(index, original.getValueArgument(index))
}
}
override fun visitEnumConstructorCall(expression: IrEnumConstructorCall): IrExpression {
val symbol = expression.symbol.replace(SymbolTable::referenceConstructor) ?:
return super.visitEnumConstructorCall(expression)
return with(expression) {
IrEnumConstructorCallImpl(startOffset, endOffset, symbol).also {
it.copyArgumentsFrom(this)
}
}
}
override fun visitDelegatingConstructorCall(expression: IrDelegatingConstructorCall): IrExpression {
val symbol = expression.symbol.replace(SymbolTable::referenceConstructor) ?:
return super.visitDelegatingConstructorCall(expression)
expression.transformChildrenVoid()
return with(expression) {
IrDelegatingConstructorCallImpl(startOffset, endOffset, symbol, descriptor, getTypeArgumentsMap()).also {
it.copyArgumentsFrom(this)
}
}
}
override fun visitFunctionReference(expression: IrFunctionReference): IrExpression {
val symbol = expression.symbol.replace(SymbolTable::referenceFunction) ?:
return super.visitFunctionReference(expression)
expression.transformChildrenVoid(this)
return with(expression) {
IrFunctionReferenceImpl(startOffset, endOffset, type, symbol, descriptor, getTypeArgumentsMap()).also {
it.copyArgumentsFrom(this)
}
}
}
override fun visitPropertyReference(expression: IrPropertyReference): IrExpression {
val field = expression.field?.replaceOrSame(SymbolTable::referenceField)
val getter = expression.getter?.replace(SymbolTable::referenceFunction) ?: expression.getter
val setter = expression.setter?.replace(SymbolTable::referenceFunction) ?: expression.setter
if (field == expression.field && getter == expression.getter && setter == expression.setter) {
return super.visitPropertyReference(expression)
}
expression.transformChildrenVoid(this)
return with(expression) {
IrPropertyReferenceImpl(startOffset, endOffset, type, descriptor,
field,
getter,
setter,
getTypeArgumentsMap(), origin).also {
it.copyArgumentsFrom(this)
}
}
}
override fun visitLocalDelegatedPropertyReference(expression: IrLocalDelegatedPropertyReference): IrExpression {
val delegate = expression.delegate.replaceOrSame(SymbolTable::referenceVariable)
val getter = expression.getter.replace(SymbolTable::referenceFunction) ?: expression.getter
val setter = expression.setter?.replace(SymbolTable::referenceFunction) ?: expression.setter
if (delegate == expression.delegate && getter == expression.getter && setter == expression.setter) {
return super.visitLocalDelegatedPropertyReference(expression)
}
expression.transformChildrenVoid(this)
return with(expression) {
IrLocalDelegatedPropertyReferenceImpl(startOffset, endOffset, type, descriptor,
delegate, getter, setter, origin).also {
it.copyArgumentsFrom(this)
}
}
}
private val returnTargetStack = mutableListOf<IrFunctionSymbol>()
override fun visitFunction(declaration: IrFunction): IrStatement {
returnTargetStack.push(declaration.symbol)
try {
return super.visitFunction(declaration)
} finally {
returnTargetStack.pop()
}
}
override fun visitBlock(expression: IrBlock): IrExpression {
if (expression is IrReturnableBlock) {
returnTargetStack.push(expression.symbol)
try {
return super.visitBlock(expression)
} finally {
returnTargetStack.pop()
}
} else {
return super.visitBlock(expression)
}
}
override fun visitReturn(expression: IrReturn): IrExpression {
if (expression.returnTargetSymbol.isBound) {
return super.visitReturn(expression)
}
val returnTargetSymbol = returnTargetStack.last { it.descriptor == expression.returnTarget }
expression.transformChildrenVoid(this)
return with(expression) {
IrReturnImpl(startOffset, endOffset, type, returnTargetSymbol, value)
}
}
override fun visitInstanceInitializerCall(expression: IrInstanceInitializerCall): IrExpression {
val classSymbol = expression.classSymbol.replace(SymbolTable::referenceClass) ?:
return super.visitInstanceInitializerCall(expression)
expression.transformChildrenVoid(this)
return with(expression) {
IrInstanceInitializerCallImpl(startOffset, endOffset, classSymbol)
}
}
}
| apache-2.0 | f390e6e64879cd57a103c50569fb99cc | 36.955729 | 167 | 0.681372 | 5.292302 | false | false | false | false |
Lucas-Lu/KotlinWorld | KT10/src/main/kotlin/net/println/kt10/LazyThreadSafeDoubleCheck.kt | 1 | 655 | package net.println.kt10.kotlin
/**
* Created by luliju on 2017/7/8.
*/
class LazyThreadSafeDoubleCheck private constructor(){
companion object{
val instance by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED){
LazyThreadSafeDoubleCheck()
}
private @Volatile var instance2: LazyThreadSafeDoubleCheck? = null
fun get(): LazyThreadSafeDoubleCheck {
if(instance2 == null){
synchronized(this){
if(instance2 == null)
instance2 = LazyThreadSafeDoubleCheck()
}
}
return instance2!!
}
}
} | mit | d642616071acd687cffafade3be62491 | 26.333333 | 74 | 0.569466 | 5 | false | false | false | false |
farmerbb/Notepad | app/src/main/java/com/farmerbb/notepad/ui/routes/AppSettings.kt | 1 | 5461 | /* Copyright 2021 Braden Farmer
*
* 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:OptIn(
ExperimentalComposeUiApi::class,
ExperimentalMaterialApi::class
)
package com.farmerbb.notepad.ui.routes
import androidx.annotation.ArrayRes
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.material.ExperimentalMaterialApi
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Surface
import androidx.compose.runtime.Composable
import androidx.compose.runtime.ReadOnlyComposable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.res.stringArrayResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.Dialog
import com.farmerbb.notepad.R
import com.farmerbb.notepad.model.Prefs
import com.farmerbb.notepad.viewmodel.NotepadViewModel
import de.schnettler.datastore.compose.material.PreferenceScreen
import de.schnettler.datastore.compose.material.model.Preference.PreferenceItem.ListPreference
import de.schnettler.datastore.compose.material.model.Preference.PreferenceItem.SwitchPreference
import org.koin.androidx.compose.getViewModel
@Composable
fun SettingsDialog(onDismiss: () -> Unit) {
Dialog(onDismissRequest = onDismiss) {
Surface(shape = MaterialTheme.shapes.medium) {
NotepadPreferenceScreen()
}
}
}
@Composable
fun NotepadPreferenceScreen(
vm: NotepadViewModel = getViewModel()
) {
val markdown by vm.prefs.markdown.collectAsState()
val directEdit by vm.prefs.directEdit.collectAsState()
PreferenceScreen(
items = listOf(
ListPreference(
request = Prefs.Theme,
title = stringResource(id = R.string.action_theme),
singleLineTitle = false,
entries = listPrefEntries(
keyRes = R.array.theme_list_values,
valueRes = R.array.theme_list
),
),
ListPreference(
request = Prefs.FontSize,
title = stringResource(id = R.string.action_font_size),
singleLineTitle = false,
entries = listPrefEntries(
keyRes = R.array.font_size_list_values,
valueRes = R.array.font_size_list
),
),
ListPreference(
request = Prefs.SortBy,
title = stringResource(id = R.string.action_sort_by),
singleLineTitle = false,
entries = listPrefEntries(
keyRes = R.array.sort_by_list_values,
valueRes = R.array.sort_by_list
),
),
ListPreference(
request = Prefs.ExportFilename,
title = stringResource(id = R.string.action_export_filename),
singleLineTitle = false,
entries = listPrefEntries(
keyRes = R.array.exported_filename_list_values,
valueRes = R.array.exported_filename_list
),
),
SwitchPreference(
request = Prefs.ShowDialogs,
title = stringResource(id = R.string.pref_title_show_dialogs),
singleLineTitle = false
),
SwitchPreference(
request = Prefs.ShowDate,
title = stringResource(id = R.string.pref_title_show_date),
singleLineTitle = false
),
SwitchPreference(
request = Prefs.DirectEdit,
title = stringResource(id = R.string.pref_title_direct_edit),
singleLineTitle = false,
enabled = !markdown
),
SwitchPreference(
request = Prefs.Markdown,
title = stringResource(id = R.string.pref_title_markdown),
singleLineTitle = false,
enabled = !directEdit
),
SwitchPreference(
request = Prefs.RtlSupport,
title = stringResource(id = R.string.rtl_layout),
singleLineTitle = false
)
),
contentPadding = PaddingValues(8.dp),
dataStoreManager = vm.dataStoreManager
)
}
@ReadOnlyComposable
@Composable
private fun listPrefEntries(
@ArrayRes keyRes: Int,
@ArrayRes valueRes: Int
): Map<String, String> {
val keys = stringArrayResource(id = keyRes)
val values = stringArrayResource(id = valueRes)
if(keys.size != values.size) {
throw RuntimeException("Keys and values are not the same size")
}
val map = mutableMapOf<String, String>()
for(i in keys.indices) {
map[keys[i]] = values[i]
}
return map.toMutableMap()
} | apache-2.0 | bf3a18dc5c5ce52d56b8e6446c16ec5f | 35.172185 | 96 | 0.629738 | 4.765271 | false | false | false | false |
exponentjs/exponent | packages/expo-image-picker/android/src/main/java/expo/modules/imagepicker/ImagePickerConstants.kt | 2 | 9500 | package expo.modules.imagepicker
import androidx.exifinterface.media.ExifInterface
object ImagePickerConstants {
const val TAG = "ExponentImagePicker"
const val REQUEST_LAUNCH_CAMERA = 1
const val REQUEST_LAUNCH_IMAGE_LIBRARY = 2
const val DEFAULT_QUALITY = 100
const val CACHE_DIR_NAME = "ImagePicker"
const val PENDING_RESULT_EVENT = "ExpoImagePicker.onPendingResult"
const val ERR_MISSING_ACTIVITY = "ERR_MISSING_ACTIVITY"
const val MISSING_ACTIVITY_MESSAGE = "Activity which was provided during module initialization is no longer available"
const val ERR_CAN_NOT_DEDUCE_TYPE = "ERR_CAN_NOT_DEDUCE_TYPE"
const val CAN_NOT_DEDUCE_TYPE_MESSAGE = "Can not deduce type of the returned file."
const val ERR_CAN_NOT_SAVE_RESULT = "ERR_CAN_NOT_SAVE_RESULT"
const val CAN_NOT_SAVE_RESULT_MESSAGE = "Can not save result to the file."
const val ERR_CAN_NOT_EXTRACT_METADATA = "ERR_CAN_NOT_EXTRACT_METADATA"
const val CAN_NOT_EXTRACT_METADATA_MESSAGE = "Can not extract metadata."
const val ERR_INVALID_OPTION = "ERR_INVALID_OPTION"
const val ERR_MISSING_URL = "ERR_MISSING_URL"
const val MISSING_URL_MESSAGE = "Intent doesn't contain `url`."
const val ERR_CAN_NOT_OPEN_CROP = "ERR_CAN_NOT_OPEN_CROP"
const val CAN_NOT_OPEN_CROP_MESSAGE = "Can not open the crop tool."
const val COROUTINE_CANCELED = "Coroutine canceled by module destruction."
const val PROMISES_CANCELED = "Module destroyed, all promises canceled."
const val UNKNOWN_EXCEPTION = "Unknown exception."
const val OPTION_QUALITY = "quality"
const val OPTION_ALLOWS_EDITING = "allowsEditing"
const val OPTION_MEDIA_TYPES = "mediaTypes"
const val OPTION_ASPECT = "aspect"
const val OPTION_BASE64 = "base64"
const val OPTION_EXIF = "exif"
const val OPTION_VIDEO_MAX_DURATION = "videoMaxDuration"
val exifTags = arrayOf(
arrayOf("string", ExifInterface.TAG_ARTIST),
arrayOf("int", ExifInterface.TAG_BITS_PER_SAMPLE),
arrayOf("int", ExifInterface.TAG_COMPRESSION),
arrayOf("string", ExifInterface.TAG_COPYRIGHT),
arrayOf("string", ExifInterface.TAG_DATETIME),
arrayOf("string", ExifInterface.TAG_IMAGE_DESCRIPTION),
arrayOf("int", ExifInterface.TAG_IMAGE_LENGTH),
arrayOf("int", ExifInterface.TAG_IMAGE_WIDTH),
arrayOf("int", ExifInterface.TAG_JPEG_INTERCHANGE_FORMAT),
arrayOf("int", ExifInterface.TAG_JPEG_INTERCHANGE_FORMAT_LENGTH),
arrayOf("string", ExifInterface.TAG_MAKE),
arrayOf("string", ExifInterface.TAG_MODEL),
arrayOf("int", ExifInterface.TAG_ORIENTATION),
arrayOf("int", ExifInterface.TAG_PHOTOMETRIC_INTERPRETATION),
arrayOf("int", ExifInterface.TAG_PLANAR_CONFIGURATION),
arrayOf("double", ExifInterface.TAG_PRIMARY_CHROMATICITIES),
arrayOf("double", ExifInterface.TAG_REFERENCE_BLACK_WHITE),
arrayOf("int", ExifInterface.TAG_RESOLUTION_UNIT),
arrayOf("int", ExifInterface.TAG_ROWS_PER_STRIP),
arrayOf("int", ExifInterface.TAG_SAMPLES_PER_PIXEL),
arrayOf("string", ExifInterface.TAG_SOFTWARE),
arrayOf("int", ExifInterface.TAG_STRIP_BYTE_COUNTS),
arrayOf("int", ExifInterface.TAG_STRIP_OFFSETS),
arrayOf("int", ExifInterface.TAG_TRANSFER_FUNCTION),
arrayOf("double", ExifInterface.TAG_WHITE_POINT),
arrayOf("double", ExifInterface.TAG_X_RESOLUTION),
arrayOf("double", ExifInterface.TAG_Y_CB_CR_COEFFICIENTS),
arrayOf("int", ExifInterface.TAG_Y_CB_CR_POSITIONING),
arrayOf("int", ExifInterface.TAG_Y_CB_CR_SUB_SAMPLING),
arrayOf("double", ExifInterface.TAG_Y_RESOLUTION),
arrayOf("double", ExifInterface.TAG_APERTURE_VALUE),
arrayOf("double", ExifInterface.TAG_BRIGHTNESS_VALUE),
arrayOf("string", ExifInterface.TAG_CFA_PATTERN),
arrayOf("int", ExifInterface.TAG_COLOR_SPACE),
arrayOf("string", ExifInterface.TAG_COMPONENTS_CONFIGURATION),
arrayOf("double", ExifInterface.TAG_COMPRESSED_BITS_PER_PIXEL),
arrayOf("int", ExifInterface.TAG_CONTRAST),
arrayOf("int", ExifInterface.TAG_CUSTOM_RENDERED),
arrayOf("string", ExifInterface.TAG_DATETIME_DIGITIZED),
arrayOf("string", ExifInterface.TAG_DATETIME_ORIGINAL),
arrayOf("string", ExifInterface.TAG_DEVICE_SETTING_DESCRIPTION),
arrayOf("double", ExifInterface.TAG_DIGITAL_ZOOM_RATIO),
arrayOf("string", ExifInterface.TAG_EXIF_VERSION),
arrayOf("double", ExifInterface.TAG_EXPOSURE_BIAS_VALUE),
arrayOf("double", ExifInterface.TAG_EXPOSURE_INDEX),
arrayOf("int", ExifInterface.TAG_EXPOSURE_MODE),
arrayOf("int", ExifInterface.TAG_EXPOSURE_PROGRAM),
arrayOf("double", ExifInterface.TAG_EXPOSURE_TIME),
arrayOf("double", ExifInterface.TAG_F_NUMBER),
arrayOf("string", ExifInterface.TAG_FILE_SOURCE),
arrayOf("int", ExifInterface.TAG_FLASH),
arrayOf("double", ExifInterface.TAG_FLASH_ENERGY),
arrayOf("string", ExifInterface.TAG_FLASHPIX_VERSION),
arrayOf("double", ExifInterface.TAG_FOCAL_LENGTH),
arrayOf("int", ExifInterface.TAG_FOCAL_LENGTH_IN_35MM_FILM),
arrayOf("int", ExifInterface.TAG_FOCAL_PLANE_RESOLUTION_UNIT),
arrayOf("double", ExifInterface.TAG_FOCAL_PLANE_X_RESOLUTION),
arrayOf("double", ExifInterface.TAG_FOCAL_PLANE_Y_RESOLUTION),
arrayOf("int", ExifInterface.TAG_GAIN_CONTROL),
arrayOf("int", ExifInterface.TAG_ISO_SPEED_RATINGS),
arrayOf("string", ExifInterface.TAG_IMAGE_UNIQUE_ID),
arrayOf("int", ExifInterface.TAG_LIGHT_SOURCE),
arrayOf("string", ExifInterface.TAG_MAKER_NOTE),
arrayOf("double", ExifInterface.TAG_MAX_APERTURE_VALUE),
arrayOf("int", ExifInterface.TAG_METERING_MODE),
arrayOf("int", ExifInterface.TAG_NEW_SUBFILE_TYPE),
arrayOf("string", ExifInterface.TAG_OECF),
arrayOf("int", ExifInterface.TAG_PIXEL_X_DIMENSION),
arrayOf("int", ExifInterface.TAG_PIXEL_Y_DIMENSION),
arrayOf("string", ExifInterface.TAG_RELATED_SOUND_FILE),
arrayOf("int", ExifInterface.TAG_SATURATION),
arrayOf("int", ExifInterface.TAG_SCENE_CAPTURE_TYPE),
arrayOf("string", ExifInterface.TAG_SCENE_TYPE),
arrayOf("int", ExifInterface.TAG_SENSING_METHOD),
arrayOf("int", ExifInterface.TAG_SHARPNESS),
arrayOf("double", ExifInterface.TAG_SHUTTER_SPEED_VALUE),
arrayOf("string", ExifInterface.TAG_SPATIAL_FREQUENCY_RESPONSE),
arrayOf("string", ExifInterface.TAG_SPECTRAL_SENSITIVITY),
arrayOf("int", ExifInterface.TAG_SUBFILE_TYPE),
arrayOf("string", ExifInterface.TAG_SUBSEC_TIME),
arrayOf("string", ExifInterface.TAG_SUBSEC_TIME_DIGITIZED),
arrayOf("string", ExifInterface.TAG_SUBSEC_TIME_ORIGINAL),
arrayOf("int", ExifInterface.TAG_SUBJECT_AREA),
arrayOf("double", ExifInterface.TAG_SUBJECT_DISTANCE),
arrayOf("int", ExifInterface.TAG_SUBJECT_DISTANCE_RANGE),
arrayOf("int", ExifInterface.TAG_SUBJECT_LOCATION),
arrayOf("string", ExifInterface.TAG_USER_COMMENT),
arrayOf("int", ExifInterface.TAG_WHITE_BALANCE),
arrayOf("double", ExifInterface.TAG_GPS_ALTITUDE),
arrayOf("int", ExifInterface.TAG_GPS_ALTITUDE_REF),
arrayOf("string", ExifInterface.TAG_GPS_AREA_INFORMATION),
arrayOf("double", ExifInterface.TAG_GPS_DOP),
arrayOf("string", ExifInterface.TAG_GPS_DATESTAMP),
arrayOf("double", ExifInterface.TAG_GPS_DEST_BEARING),
arrayOf("string", ExifInterface.TAG_GPS_DEST_BEARING_REF),
arrayOf("double", ExifInterface.TAG_GPS_DEST_DISTANCE),
arrayOf("string", ExifInterface.TAG_GPS_DEST_DISTANCE_REF),
arrayOf("double", ExifInterface.TAG_GPS_DEST_LATITUDE),
arrayOf("string", ExifInterface.TAG_GPS_DEST_LATITUDE_REF),
arrayOf("double", ExifInterface.TAG_GPS_DEST_LONGITUDE),
arrayOf("string", ExifInterface.TAG_GPS_DEST_LONGITUDE_REF),
arrayOf("int", ExifInterface.TAG_GPS_DIFFERENTIAL),
arrayOf("string", ExifInterface.TAG_GPS_H_POSITIONING_ERROR),
arrayOf("double", ExifInterface.TAG_GPS_IMG_DIRECTION),
arrayOf("string", ExifInterface.TAG_GPS_IMG_DIRECTION_REF),
arrayOf("double", ExifInterface.TAG_GPS_LATITUDE),
arrayOf("string", ExifInterface.TAG_GPS_LATITUDE_REF),
arrayOf("double", ExifInterface.TAG_GPS_LONGITUDE),
arrayOf("string", ExifInterface.TAG_GPS_LONGITUDE_REF),
arrayOf("string", ExifInterface.TAG_GPS_MAP_DATUM),
arrayOf("string", ExifInterface.TAG_GPS_MEASURE_MODE),
arrayOf("string", ExifInterface.TAG_GPS_PROCESSING_METHOD),
arrayOf("string", ExifInterface.TAG_GPS_SATELLITES),
arrayOf("double", ExifInterface.TAG_GPS_SPEED),
arrayOf("string", ExifInterface.TAG_GPS_SPEED_REF),
arrayOf("string", ExifInterface.TAG_GPS_STATUS),
arrayOf("string", ExifInterface.TAG_GPS_TIMESTAMP),
arrayOf("double", ExifInterface.TAG_GPS_TRACK),
arrayOf("string", ExifInterface.TAG_GPS_TRACK_REF),
arrayOf("string", ExifInterface.TAG_GPS_VERSION_ID),
arrayOf("string", ExifInterface.TAG_INTEROPERABILITY_INDEX),
arrayOf("int", ExifInterface.TAG_THUMBNAIL_IMAGE_LENGTH),
arrayOf("int", ExifInterface.TAG_THUMBNAIL_IMAGE_WIDTH),
arrayOf("int", ExifInterface.TAG_DNG_VERSION),
arrayOf("int", ExifInterface.TAG_DEFAULT_CROP_SIZE),
arrayOf("int", ExifInterface.TAG_ORF_PREVIEW_IMAGE_START),
arrayOf("int", ExifInterface.TAG_ORF_PREVIEW_IMAGE_LENGTH),
arrayOf("int", ExifInterface.TAG_ORF_ASPECT_FRAME),
arrayOf("int", ExifInterface.TAG_RW2_SENSOR_BOTTOM_BORDER),
arrayOf("int", ExifInterface.TAG_RW2_SENSOR_LEFT_BORDER),
arrayOf("int", ExifInterface.TAG_RW2_SENSOR_RIGHT_BORDER),
arrayOf("int", ExifInterface.TAG_RW2_SENSOR_TOP_BORDER),
arrayOf("int", ExifInterface.TAG_RW2_ISO)
)
}
| bsd-3-clause | d5b7d4623be655e49763e3833a107ef4 | 53.913295 | 120 | 0.734105 | 3.883892 | false | false | false | false |
Heiner1/AndroidAPS | database/src/main/java/info/nightscout/androidaps/database/transactions/CutCarbsTransaction.kt | 1 | 1222 | package info.nightscout.androidaps.database.transactions
import info.nightscout.androidaps.database.entities.Carbs
import info.nightscout.androidaps.database.interfaces.end
import kotlin.math.roundToInt
class CutCarbsTransaction(val id: Long, val end: Long) : Transaction<CutCarbsTransaction.TransactionResult>() {
override fun run(): TransactionResult {
val result = TransactionResult()
val carbs = database.carbsDao.findById(id)
?: throw IllegalArgumentException("There is no such Carbs with the specified ID.")
if (carbs.timestamp == end) {
carbs.isValid = false
database.carbsDao.updateExistingEntry(carbs)
result.invalidated.add(carbs)
} else if (end in carbs.timestamp..carbs.end) {
val pctRun = (end - carbs.timestamp) / carbs.duration.toDouble()
carbs.amount = (carbs.amount * pctRun).roundToInt().toDouble()
carbs.end = end
database.carbsDao.updateExistingEntry(carbs)
result.updated.add(carbs)
}
return result
}
class TransactionResult {
val invalidated = mutableListOf<Carbs>()
val updated = mutableListOf<Carbs>()
}
} | agpl-3.0 | 152cd6fb9d50ef1fc1292b1dd9a295d6 | 37.21875 | 111 | 0.669394 | 4.849206 | false | false | false | false |
Heiner1/AndroidAPS | database/src/main/java/info/nightscout/androidaps/database/entities/Carbs.kt | 1 | 1880 | package info.nightscout.androidaps.database.entities
import androidx.room.Embedded
import androidx.room.Entity
import androidx.room.ForeignKey
import androidx.room.Index
import androidx.room.PrimaryKey
import info.nightscout.androidaps.database.TABLE_CARBS
import info.nightscout.androidaps.database.embedments.InterfaceIDs
import info.nightscout.androidaps.database.interfaces.DBEntryWithTimeAndDuration
import info.nightscout.androidaps.database.interfaces.TraceableDBEntry
import java.util.*
@Entity(tableName = TABLE_CARBS,
foreignKeys = [ForeignKey(
entity = Carbs::class,
parentColumns = ["id"],
childColumns = ["referenceId"])],
indices = [
Index("id"),
Index("isValid"),
Index("nightscoutId"),
Index("referenceId"),
Index("timestamp")
])
data class Carbs(
@PrimaryKey(autoGenerate = true)
override var id: Long = 0,
override var version: Int = 0,
override var dateCreated: Long = -1,
override var isValid: Boolean = true,
override var referenceId: Long? = null,
@Embedded
override var interfaceIDs_backing: InterfaceIDs? = null,
override var timestamp: Long,
override var utcOffset: Long = TimeZone.getDefault().getOffset(timestamp).toLong(),
override var duration: Long, // in milliseconds
var amount: Double
) : TraceableDBEntry, DBEntryWithTimeAndDuration {
private fun contentEqualsTo(other: Carbs): Boolean =
isValid == other.isValid &&
timestamp == other.timestamp &&
utcOffset == other.utcOffset &&
amount == other.amount &&
duration == other.duration
fun onlyNsIdAdded(previous: Carbs): Boolean =
previous.id != id &&
contentEqualsTo(previous) &&
previous.interfaceIDs.nightscoutId == null &&
interfaceIDs.nightscoutId != null
} | agpl-3.0 | 6aec5e7d07beca6f7937d0f637c42d27 | 34.490566 | 87 | 0.687766 | 4.688279 | false | false | false | false |
JStege1206/AdventOfCode | aoc-2015/src/main/kotlin/nl/jstege/adventofcode/aoc2015/days/Day15.kt | 1 | 4418 | package nl.jstege.adventofcode.aoc2015.days
import nl.jstege.adventofcode.aoccommon.days.Day
import nl.jstege.adventofcode.aoccommon.utils.extensions.component6
import nl.jstege.adventofcode.aoccommon.utils.extensions.component7
import nl.jstege.adventofcode.aoccommon.utils.extensions.extractValues
import kotlin.math.max
import kotlin.reflect.KProperty1
/**
*
* @author Jelle Stege
*/
class Day15 : Day(title = "Science for Hungry People") {
private companion object Configuration {
private const val TEA_SPOONS_AMOUNT = 100
private const val NEEDED_CALORIES = 500
private const val SPRINKLES = "Sprinkles"
private const val BUTTERSCOTCH = "Butterscotch"
private const val CHOCOLATE = "Chocolate"
private const val CANDY = "Candy"
}
override fun first(input: Sequence<String>) = input
.map(Ingredient.Parser::parse)
.associate { it.name to it }
.calculateMaxScore()
override fun second(input: Sequence<String>) = input
.map(Ingredient.Parser::parse)
.associate { it.name to it }
.calculateMaxScore(true)
private fun Map<String, Ingredient>.calculateMaxScore(useCalories: Boolean = false): Int {
var score = 0
(0 until TEA_SPOONS_AMOUNT).forEach { sprinkle ->
(0 until TEA_SPOONS_AMOUNT - sprinkle).forEach { butterscotch ->
(0 until TEA_SPOONS_AMOUNT - butterscotch - sprinkle).forEach { chocolate ->
val candy = TEA_SPOONS_AMOUNT - chocolate - butterscotch - sprinkle
score = max(
score,
calculateScore(
sprinkle to this[SPRINKLES]!!,
butterscotch to this[BUTTERSCOTCH]!!,
chocolate to this[CHOCOLATE]!!,
candy to this[CANDY]!!,
useCalories = useCalories
)
)
}
}
}
return score
}
private fun calculateScore(vararg recipe: Pair<Int, Ingredient>, useCalories: Boolean): Int {
fun calculateScore(
recipe: Array<out Pair<Int, Ingredient>>,
property: KProperty1<Ingredient, Int>
) = recipe.sumBy { (amount, ingredient) -> amount * ingredient.run(property) }
return if (useCalories && calculateScore(recipe, Ingredient::calories) != NEEDED_CALORIES) 0
else setOf(
Ingredient::capacity,
Ingredient::durability,
Ingredient::flavor,
Ingredient::texture
).let {
it.fold(1) { acc, property -> acc * Math.max(calculateScore(recipe, property), 0) }
}
}
private data class Ingredient(
val name: String,
val capacity: Int,
val durability: Int,
val flavor: Int,
val texture: Int,
val calories: Int
) {
companion object Parser {
private val INPUT_REGEX = ("(\\w+): " +
"capacity (-?\\d+), " +
"durability (-?\\d+), flavor (-?\\d+), " +
"texture (-?\\d+), " +
"calories (-?\\d+)").toRegex()
private const val NAME_INDEX = 1
private const val CAPACITY_INDEX = 2
private const val DURABILITY_INDEX = 3
private const val FLAVOR_INDEX = 4
private const val TEXTURE_INDEX = 5
private const val CALORIES_INDEX = 6
private val PARAM_INDICES = intArrayOf(
NAME_INDEX,
CAPACITY_INDEX,
DURABILITY_INDEX,
FLAVOR_INDEX,
TEXTURE_INDEX,
CALORIES_INDEX
)
@JvmStatic
fun parse(input: String): Ingredient {
return input.extractValues(INPUT_REGEX, *PARAM_INDICES)
.let { (name, capacity, durability, flavor, texture, calories) ->
Ingredient(
name,
capacity.toInt(),
durability.toInt(),
flavor.toInt(),
texture.toInt(),
calories.toInt()
)
}
}
}
}
}
| mit | e9040e5d6fa652241731609d8f136fe0 | 35.512397 | 100 | 0.527614 | 4.568769 | false | false | false | false |
wordpress-mobile/WordPress-Android | WordPress/src/main/java/org/wordpress/android/ui/activitylog/list/ActivityLogDiffCallback.kt | 1 | 2047 | package org.wordpress.android.ui.activitylog.list
import android.os.Bundle
import androidx.recyclerview.widget.DiffUtil
import org.wordpress.android.ui.activitylog.list.ActivityLogListItem.Event
import org.wordpress.android.ui.activitylog.list.ActivityLogListItem.IActionableItem
import org.wordpress.android.ui.activitylog.list.ActivityLogListItem.Notice
import org.wordpress.android.ui.activitylog.list.ActivityLogListItem.Progress
class ActivityLogDiffCallback(
private val oldList: List<ActivityLogListItem>,
private val newList: List<ActivityLogListItem>
) : DiffUtil.Callback() {
companion object {
const val LIST_ITEM_BUTTON_VISIBILITY_KEY = "list_item_button_visibility_key"
}
override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
val oldItem = oldList[oldItemPosition]
val newItem = newList[newItemPosition]
return when {
oldItem is Event && newItem is Event -> oldItem.activityId == newItem.activityId
oldItem is Progress && newItem is Progress -> oldItem == newItem
oldItem is Notice && newItem is Notice -> oldItem == newItem
else -> false
}
}
override fun getOldListSize(): Int {
return oldList.size
}
override fun getNewListSize(): Int {
return newList.size
}
override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
return oldList[oldItemPosition] == newList[newItemPosition]
}
override fun getChangePayload(oldItemPosition: Int, newItemPosition: Int): Any? {
val oldItem = oldList[oldItemPosition]
val newItem = newList[newItemPosition]
val bundle = Bundle()
if (oldItem is IActionableItem && newItem is IActionableItem &&
oldItem.isButtonVisible != newItem.isButtonVisible) {
bundle.putBoolean(LIST_ITEM_BUTTON_VISIBILITY_KEY, newItem.isButtonVisible)
}
if (bundle.size() == 0) return null
return bundle
}
}
| gpl-2.0 | 763e9487eeceae9e4e80b4ac8c190633 | 36.218182 | 92 | 0.703468 | 5.054321 | false | false | false | false |
ingokegel/intellij-community | plugins/gradle/src/org/jetbrains/plugins/gradle/GradleContentRootContributor.kt | 9 | 2318 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.gradle
import com.intellij.openapi.externalSystem.model.DataNode
import com.intellij.openapi.externalSystem.model.ProjectKeys
import com.intellij.openapi.externalSystem.model.project.ContentRootData
import com.intellij.openapi.externalSystem.model.project.ExternalSystemSourceType
import com.intellij.openapi.externalSystem.model.project.ModuleData
import com.intellij.openapi.externalSystem.util.ExternalSystemApiUtil
import com.intellij.openapi.externalSystem.util.ExternalSystemContentRootContributor
import com.intellij.openapi.module.Module
import org.jetbrains.plugins.gradle.model.data.GradleSourceSetData
import org.jetbrains.plugins.gradle.util.GradleConstants
import org.jetbrains.plugins.gradle.util.GradleUtil.findGradleModuleData
import kotlin.io.path.Path
class GradleContentRootContributor : ExternalSystemContentRootContributor {
override fun isApplicable(systemId: String): Boolean = systemId == GradleConstants.SYSTEM_ID.id
override fun findContentRoots(
module: Module,
sourceTypes: Collection<ExternalSystemSourceType>,
): Collection<ExternalSystemContentRootContributor.ExternalContentRoot> = mutableListOf<ExternalSystemContentRootContributor.ExternalContentRoot>().apply {
processContentRoots(module) { rootData ->
for (sourceType in sourceTypes) {
rootData.getPaths(sourceType).mapTo(this) {
ExternalSystemContentRootContributor.ExternalContentRoot(Path(it.path), sourceType)
}
}
}
}.toList()
companion object {
internal fun processContentRoots(
module: Module,
processor: (ContentRootData) -> Unit,
) {
val moduleData = findGradleModuleData(module) ?: return
moduleData.processModule(processor)
for (eachSourceSetNode in ExternalSystemApiUtil.getChildren(moduleData, GradleSourceSetData.KEY)) {
eachSourceSetNode.processModule(processor)
}
}
}
}
private fun DataNode<out ModuleData>.processModule(processor: (ContentRootData) -> Unit) {
for (eachContentRootNode in ExternalSystemApiUtil.findAll(this, ProjectKeys.CONTENT_ROOT)) {
processor(eachContentRootNode.data)
}
} | apache-2.0 | 38550ca5c886867eccd42ccf1bec40a9 | 44.470588 | 158 | 0.795513 | 4.859539 | false | false | false | false |
mdaniel/intellij-community | platform/core-impl/src/com/intellij/ide/plugins/PluginDescriptorLoader.kt | 1 | 37561 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
@file:Suppress("ReplaceNegatedIsEmptyWithIsNotEmpty", "ReplacePutWithAssignment")
@file:JvmName("PluginDescriptorLoader")
@file:Internal
package com.intellij.ide.plugins
import com.intellij.diagnostic.StartUpMeasurer
import com.intellij.openapi.application.PathManager
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.extensions.PluginId
import com.intellij.openapi.util.BuildNumber
import com.intellij.openapi.util.io.NioFiles
import com.intellij.util.PlatformUtils
import com.intellij.util.io.Decompressor
import com.intellij.util.io.URLUtil
import com.intellij.util.lang.UrlClassLoader
import com.intellij.util.lang.ZipFilePool
import com.intellij.util.xml.dom.createNonCoalescingXmlStreamReader
import kotlinx.coroutines.*
import org.codehaus.stax2.XMLStreamReader2
import org.jetbrains.annotations.ApiStatus.Internal
import org.jetbrains.annotations.TestOnly
import org.jetbrains.annotations.VisibleForTesting
import java.io.Closeable
import java.io.File
import java.io.IOException
import java.io.InputStream
import java.net.URL
import java.nio.charset.StandardCharsets
import java.nio.file.Files
import java.nio.file.NoSuchFileException
import java.nio.file.Path
import java.nio.file.Paths
import java.util.*
import java.util.concurrent.CancellationException
import java.util.concurrent.ExecutionException
import java.util.zip.ZipFile
import javax.xml.stream.XMLStreamException
import kotlin.io.path.name
private val LOG: Logger
get() = PluginManagerCore.getLogger()
@TestOnly
fun loadDescriptor(file: Path, parentContext: DescriptorListLoadingContext): IdeaPluginDescriptorImpl? {
return loadDescriptorFromFileOrDir(file = file,
context = parentContext,
pathResolver = PluginXmlPathResolver.DEFAULT_PATH_RESOLVER,
isBundled = false,
isEssential = false,
isDirectory = Files.isDirectory(file),
useCoreClassLoader = false,
pool = null)
}
internal fun loadForCoreEnv(pluginRoot: Path, fileName: String): IdeaPluginDescriptorImpl? {
val pathResolver = PluginXmlPathResolver.DEFAULT_PATH_RESOLVER
val parentContext = DescriptorListLoadingContext(disabledPlugins = DisabledPluginsState.getDisabledIds())
if (Files.isDirectory(pluginRoot)) {
return loadDescriptorFromDir(file = pluginRoot,
descriptorRelativePath = "${PluginManagerCore.META_INF}$fileName",
pluginPath = null,
context = parentContext,
isBundled = true,
isEssential = true,
pathResolver = pathResolver,
useCoreClassLoader = false)
}
else {
return runBlocking {
loadDescriptorFromJar(file = pluginRoot,
fileName = fileName,
pathResolver = pathResolver,
parentContext = parentContext,
isBundled = true,
isEssential = true,
pluginPath = null,
useCoreClassLoader = false,
pool = null)
}
}
}
private fun loadDescriptorFromDir(file: Path,
descriptorRelativePath: String,
pluginPath: Path?,
context: DescriptorListLoadingContext,
isBundled: Boolean,
isEssential: Boolean,
useCoreClassLoader: Boolean,
pathResolver: PathResolver): IdeaPluginDescriptorImpl? {
try {
val input = Files.readAllBytes(file.resolve(descriptorRelativePath))
val dataLoader = LocalFsDataLoader(file)
val raw = readModuleDescriptor(input = input,
readContext = context,
pathResolver = pathResolver,
dataLoader = dataLoader,
includeBase = null,
readInto = null,
locationSource = file.toString())
val descriptor = IdeaPluginDescriptorImpl(raw = raw, path = pluginPath ?: file, isBundled = isBundled, id = null, moduleName = null,
useCoreClassLoader = useCoreClassLoader)
descriptor.readExternal(raw = raw, pathResolver = pathResolver, context = context, isSub = false, dataLoader = dataLoader)
descriptor.jarFiles = Collections.singletonList(file)
return descriptor
}
catch (e: NoSuchFileException) {
return null
}
catch (e: Throwable) {
if (isEssential) {
throw e
}
LOG.warn("Cannot load ${file.resolve(descriptorRelativePath)}", e)
return null
}
}
private fun loadDescriptorFromJar(file: Path,
fileName: String,
pathResolver: PathResolver,
parentContext: DescriptorListLoadingContext,
isBundled: Boolean,
isEssential: Boolean,
useCoreClassLoader: Boolean,
pluginPath: Path?,
pool: ZipFilePool?): IdeaPluginDescriptorImpl? {
var closeable: Closeable? = null
try {
val dataLoader = if (pool == null) {
val zipFile = ZipFile(file.toFile(), StandardCharsets.UTF_8)
closeable = zipFile
JavaZipFileDataLoader(zipFile)
}
else {
ImmutableZipFileDataLoader(pool.load(file), file, pool)
}
val raw = readModuleDescriptor(input = dataLoader.load("META-INF/$fileName") ?: return null,
readContext = parentContext,
pathResolver = pathResolver,
dataLoader = dataLoader,
includeBase = null,
readInto = null,
locationSource = file.toString())
val descriptor = IdeaPluginDescriptorImpl(raw = raw, path = pluginPath ?: file, isBundled = isBundled, id = null, moduleName = null,
useCoreClassLoader = useCoreClassLoader)
descriptor.readExternal(raw = raw, pathResolver = pathResolver, context = parentContext, isSub = false, dataLoader = dataLoader)
descriptor.jarFiles = Collections.singletonList(descriptor.pluginPath)
return descriptor
}
catch (e: Throwable) {
if (isEssential) {
throw if (e is XMLStreamException) RuntimeException("Cannot read $file", e) else e
}
parentContext.reportCannotLoad(file, e)
}
finally {
closeable?.close()
}
return null
}
private class JavaZipFileDataLoader(private val file: ZipFile) : DataLoader {
override val pool: ZipFilePool?
get() = null
override fun load(path: String): InputStream? {
val entry = file.getEntry(if (path[0] == '/') path.substring(1) else path) ?: return null
return file.getInputStream(entry)
}
override fun toString() = file.toString()
}
@VisibleForTesting
fun loadDescriptorFromFileOrDir(
file: Path,
context: DescriptorListLoadingContext,
pathResolver: PathResolver,
isBundled: Boolean,
isEssential: Boolean,
isDirectory: Boolean,
useCoreClassLoader: Boolean,
isUnitTestMode: Boolean = false,
pool: ZipFilePool?,
): IdeaPluginDescriptorImpl? {
return when {
isDirectory -> {
loadFromPluginDir(
file = file,
parentContext = context,
isBundled = isBundled,
isEssential = isEssential,
useCoreClassLoader = useCoreClassLoader,
pathResolver = pathResolver,
isUnitTestMode = isUnitTestMode,
pool = pool,
)
}
file.fileName.toString().endsWith(".jar", ignoreCase = true) -> {
loadDescriptorFromJar(file = file,
fileName = PluginManagerCore.PLUGIN_XML,
pathResolver = pathResolver,
parentContext = context,
isBundled = isBundled,
isEssential = isEssential,
pluginPath = null,
useCoreClassLoader = useCoreClassLoader,
pool = pool)
}
else -> null
}
}
// [META-INF] [classes] lib/*.jar
private fun loadFromPluginDir(
file: Path,
parentContext: DescriptorListLoadingContext,
isBundled: Boolean,
isEssential: Boolean,
useCoreClassLoader: Boolean,
pathResolver: PathResolver,
isUnitTestMode: Boolean = false,
pool: ZipFilePool?,
): IdeaPluginDescriptorImpl? {
val pluginJarFiles = resolveArchives(file)
if (!pluginJarFiles.isNullOrEmpty()) {
putMoreLikelyPluginJarsFirst(file, pluginJarFiles)
val pluginPathResolver = PluginXmlPathResolver(pluginJarFiles)
for (jarFile in pluginJarFiles) {
loadDescriptorFromJar(file = jarFile,
fileName = PluginManagerCore.PLUGIN_XML,
pathResolver = pluginPathResolver,
parentContext = parentContext,
isBundled = isBundled,
isEssential = isEssential,
pluginPath = file,
useCoreClassLoader = useCoreClassLoader,
pool = pool)?.let {
it.jarFiles = pluginJarFiles
return it
}
}
}
// not found, ok, let's check classes (but only for unbundled plugins)
if (!isBundled || isUnitTestMode) {
val classesDir = file.resolve("classes")
sequenceOf(classesDir, file)
.firstNotNullOfOrNull {
loadDescriptorFromDir(
file = it,
descriptorRelativePath = PluginManagerCore.PLUGIN_XML_PATH,
pluginPath = file,
context = parentContext,
isBundled = isBundled,
isEssential = isEssential,
pathResolver = pathResolver,
useCoreClassLoader = useCoreClassLoader,
)
}?.let {
if (pluginJarFiles.isNullOrEmpty()) {
it.jarFiles = Collections.singletonList(classesDir)
}
else {
val classPath = ArrayList<Path>(pluginJarFiles.size + 1)
classPath.add(classesDir)
classPath.addAll(pluginJarFiles)
it.jarFiles = classPath
}
return it
}
}
return null
}
private fun resolveArchives(path: Path): MutableList<Path>? {
try {
return Files.newDirectoryStream(path.resolve("lib")).use { stream ->
stream.filterTo(ArrayList()) {
val childPath = it.toString()
childPath.endsWith(".jar", ignoreCase = true) || childPath.endsWith(".zip", ignoreCase = true)
}
}
}
catch (e: NoSuchFileException) {
return null
}
}
/*
* Sort the files heuristically to load the plugin jar containing plugin descriptors without extra ZipFile accesses.
* File name preference:
* a) last order for files with resources in name, like resources_en.jar
* b) last order for files that have `-digit` suffix is the name e.g., completion-ranking.jar is before `gson-2.8.0.jar` or `junit-m5.jar`
* c) jar with name close to plugin's directory name, e.g., kotlin-XXX.jar is before all-open-XXX.jar
* d) shorter name, e.g., android.jar is before android-base-common.jar
*/
private fun putMoreLikelyPluginJarsFirst(pluginDir: Path, filesInLibUnderPluginDir: MutableList<Path>) {
val pluginDirName = pluginDir.fileName.toString()
// don't use kotlin sortWith to avoid loading of CollectionsKt
Collections.sort(filesInLibUnderPluginDir, Comparator { o1: Path, o2: Path ->
val o2Name = o2.fileName.toString()
val o1Name = o1.fileName.toString()
val o2StartsWithResources = o2Name.startsWith("resources")
val o1StartsWithResources = o1Name.startsWith("resources")
if (o2StartsWithResources != o1StartsWithResources) {
return@Comparator if (o2StartsWithResources) -1 else 1
}
val o2IsVersioned = fileNameIsLikeVersionedLibraryName(o2Name)
val o1IsVersioned = fileNameIsLikeVersionedLibraryName(o1Name)
if (o2IsVersioned != o1IsVersioned) {
return@Comparator if (o2IsVersioned) -1 else 1
}
val o2StartsWithNeededName = o2Name.startsWith(pluginDirName, ignoreCase = true)
val o1StartsWithNeededName = o1Name.startsWith(pluginDirName, ignoreCase = true)
if (o2StartsWithNeededName != o1StartsWithNeededName) {
return@Comparator if (o2StartsWithNeededName) 1 else -1
}
val o2EndsWithIdea = o2Name.endsWith("-idea.jar")
val o1EndsWithIdea = o1Name.endsWith("-idea.jar")
if (o2EndsWithIdea != o1EndsWithIdea) {
return@Comparator if (o2EndsWithIdea) 1 else -1
}
o1Name.length - o2Name.length
})
}
private fun fileNameIsLikeVersionedLibraryName(name: String): Boolean {
val i = name.lastIndexOf('-')
if (i == -1) {
return false
}
if (i + 1 < name.length) {
val c = name[i + 1]
return Character.isDigit(c) || ((c == 'm' || c == 'M') && i + 2 < name.length && Character.isDigit(name[i + 2]))
}
return false
}
private fun CoroutineScope.loadDescriptorsFromProperty(context: DescriptorListLoadingContext,
pool: ZipFilePool?): List<Deferred<IdeaPluginDescriptorImpl?>> {
val pathProperty = System.getProperty("plugin.path") ?: return emptyList()
// gradle-intellij-plugin heavily depends on this property in order to have core class loader plugins during tests
val useCoreClassLoaderForPluginsFromProperty = java.lang.Boolean.getBoolean("idea.use.core.classloader.for.plugin.path")
val t = StringTokenizer(pathProperty, File.pathSeparatorChar + ",")
val list = mutableListOf<Deferred<IdeaPluginDescriptorImpl?>>()
while (t.hasMoreTokens()) {
val file = Paths.get(t.nextToken())
list.add(async {
loadDescriptorFromFileOrDir(
file = file,
context = context,
pathResolver = PluginXmlPathResolver.DEFAULT_PATH_RESOLVER,
isBundled = false,
isEssential = false,
isDirectory = Files.isDirectory(file),
useCoreClassLoader = useCoreClassLoaderForPluginsFromProperty,
pool = pool,
)
})
}
return list
}
@Suppress("DeferredIsResult")
internal fun CoroutineScope.scheduleLoading(zipFilePoolDeferred: Deferred<ZipFilePool>?): Deferred<PluginSet> {
val resultDeferred = async {
val activity = StartUpMeasurer.startActivity("plugin descriptor loading")
val isUnitTestMode = PluginManagerCore.isUnitTestMode
val isRunningFromSources = PluginManagerCore.isRunningFromSources()
val result = DescriptorListLoadingContext(
isMissingSubDescriptorIgnored = true,
isMissingIncludeIgnored = isUnitTestMode,
checkOptionalConfigFileUniqueness = isUnitTestMode || isRunningFromSources,
disabledPlugins = DisabledPluginsState.getDisabledIds(),
).use { context ->
context to loadDescriptors(
context = context,
isUnitTestMode = isUnitTestMode,
isRunningFromSources = isRunningFromSources,
zipFilePoolDeferred = zipFilePoolDeferred,
)
}
activity.end()
result
}
val pluginSetDeferred = async {
val pair = resultDeferred.await()
PluginManagerCore.initializeAndSetPlugins(pair.first, pair.second, PluginManagerCore::class.java.classLoader)
}
// logging is no not as a part of plugin set job for performance reasons
launch {
val pair = resultDeferred.await()
logPlugins(plugins = pluginSetDeferred.await().allPlugins, context = pair.first, loadingResult = pair.second)
}
return pluginSetDeferred
}
private fun logPlugins(plugins: Collection<IdeaPluginDescriptorImpl>,
context: DescriptorListLoadingContext,
loadingResult: PluginLoadingResult) {
if (IdeaPluginDescriptorImpl.disableNonBundledPlugins) {
LOG.info("Running with disableThirdPartyPlugins argument, third-party plugins will be disabled")
}
val bundled = StringBuilder()
val disabled = StringBuilder()
val custom = StringBuilder()
val disabledPlugins = HashSet<PluginId>()
for (descriptor in plugins) {
var target: StringBuilder
val pluginId = descriptor.pluginId
target = if (!descriptor.isEnabled) {
if (!context.isPluginDisabled(pluginId)) {
// plugin will be logged as part of "Problems found loading plugins"
continue
}
disabledPlugins.add(pluginId)
disabled
}
else if (descriptor.isBundled || PluginManagerCore.SPECIAL_IDEA_PLUGIN_ID == pluginId) {
bundled
}
else {
custom
}
appendPlugin(descriptor, target)
}
for ((pluginId, descriptor) in loadingResult.getIncompleteIdMap()) {
// log only explicitly disabled plugins
if (context.isPluginDisabled(pluginId) && !disabledPlugins.contains(pluginId)) {
appendPlugin(descriptor, disabled)
}
}
val log = LOG
log.info("Loaded bundled plugins: $bundled")
if (custom.isNotEmpty()) {
log.info("Loaded custom plugins: $custom")
}
if (disabled.isNotEmpty()) {
log.info("Disabled plugins: $disabled")
}
}
private fun appendPlugin(descriptor: IdeaPluginDescriptor, target: StringBuilder) {
if (target.isNotEmpty()) {
target.append(", ")
}
target.append(descriptor.name)
val version = descriptor.version
if (version != null) {
target.append(" (").append(version).append(')')
}
}
// used and must be used only by Rider
@Suppress("unused")
@Internal
suspend fun getLoadedPluginsForRider(): List<IdeaPluginDescriptorImpl?> {
PluginManagerCore.getNullablePluginSet()?.enabledPlugins?.let {
return it
}
val isUnitTestMode = PluginManagerCore.isUnitTestMode
val isRunningFromSources = PluginManagerCore.isRunningFromSources()
return DescriptorListLoadingContext(
isMissingSubDescriptorIgnored = true,
isMissingIncludeIgnored = isUnitTestMode,
checkOptionalConfigFileUniqueness = isUnitTestMode || isRunningFromSources,
disabledPlugins = DisabledPluginsState.getDisabledIds(),
).use { context ->
val result = loadDescriptors(context = context, isUnitTestMode = isUnitTestMode, isRunningFromSources = isRunningFromSources)
PluginManagerCore.initializeAndSetPlugins(context, result, PluginManagerCore::class.java.classLoader).enabledPlugins
}
}
@Internal
@Deprecated("do not use")
fun loadDescriptorsForDeprecatedWizard(): PluginLoadingResult {
return runBlocking {
val isUnitTestMode = PluginManagerCore.isUnitTestMode
val isRunningFromSources = PluginManagerCore.isRunningFromSources()
DescriptorListLoadingContext(
isMissingSubDescriptorIgnored = true,
isMissingIncludeIgnored = isUnitTestMode,
checkOptionalConfigFileUniqueness = isUnitTestMode || isRunningFromSources,
disabledPlugins = DisabledPluginsState.getDisabledIds(),
).use { context ->
loadDescriptors(context = context, isUnitTestMode = isUnitTestMode, isRunningFromSources = isRunningFromSources)
}
}
}
/**
* Think twice before use and get approve from core team.
*
* Returns enabled plugins only.
*/
@Internal
suspend fun loadDescriptors(
context: DescriptorListLoadingContext,
isUnitTestMode: Boolean = PluginManagerCore.isUnitTestMode,
isRunningFromSources: Boolean,
zipFilePoolDeferred: Deferred<ZipFilePool>? = null,
): PluginLoadingResult {
val list: List<IdeaPluginDescriptorImpl?>
val extraList: List<IdeaPluginDescriptorImpl?>
coroutineScope {
withContext(Dispatchers.IO) {
val zipFilePool = if (context.transient) null else zipFilePoolDeferred?.await()
val listDeferred = loadDescriptorsFromDirs(
context = context,
customPluginDir = Paths.get(PathManager.getPluginsPath()),
isUnitTestMode = isUnitTestMode,
isRunningFromSources = isRunningFromSources,
zipFilePool = zipFilePool,
)
val extraListDeferred = loadDescriptorsFromProperty(context, zipFilePool)
list = listDeferred.awaitAll()
extraList = extraListDeferred.awaitAll()
}
}
val buildNumber = context.productBuildNumber()
val loadingResult = PluginLoadingResult()
loadingResult.addAll(descriptors = list, overrideUseIfCompatible = false, productBuildNumber = buildNumber)
if (!extraList.isEmpty()) {
// plugins added via property shouldn't be overridden to avoid plugin root detection issues when running external plugin tests
loadingResult.addAll(descriptors = extraList, overrideUseIfCompatible = true, productBuildNumber = buildNumber)
}
if (isUnitTestMode && loadingResult.enabledPluginsById.size <= 1) {
// we're running in unit test mode, but the classpath doesn't contain any plugins; try to load bundled plugins anyway
loadingResult.addAll(
descriptors = coroutineScope {
loadDescriptorsFromDir(
dir = Paths.get(PathManager.getPreInstalledPluginsPath()),
context = context,
isBundled = true,
pool = if (context.transient) null else zipFilePoolDeferred?.await()
).awaitAll()
},
overrideUseIfCompatible = false,
productBuildNumber = buildNumber
)
}
return loadingResult
}
private suspend fun loadDescriptorsFromDirs(
context: DescriptorListLoadingContext,
customPluginDir: Path,
bundledPluginDir: Path? = null,
isUnitTestMode: Boolean = PluginManagerCore.isUnitTestMode,
isRunningFromSources: Boolean = PluginManagerCore.isRunningFromSources(),
zipFilePool: ZipFilePool?,
): List<Deferred<IdeaPluginDescriptorImpl?>> {
val isInDevServerMode = java.lang.Boolean.getBoolean("idea.use.dev.build.server")
val platformPrefixProperty = PlatformUtils.getPlatformPrefix()
val platformPrefix = if (platformPrefixProperty == PlatformUtils.QODANA_PREFIX) {
System.getProperty("idea.parent.prefix", PlatformUtils.IDEA_PREFIX)
}
else {
platformPrefixProperty
}
return coroutineScope {
val root = loadCoreModules(context = context,
platformPrefix = platformPrefix,
isUnitTestMode = isUnitTestMode,
isInDevServerMode = isInDevServerMode,
isRunningFromSources = isRunningFromSources,
pool = zipFilePool)
val custom = loadDescriptorsFromDir(dir = customPluginDir, context = context, isBundled = false, pool = zipFilePool)
val effectiveBundledPluginDir = bundledPluginDir ?: if (isUnitTestMode) {
null
}
else if (isInDevServerMode) {
Paths.get(PathManager.getHomePath(), "out/dev-run", platformPrefix, "plugins")
}
else {
Paths.get(PathManager.getPreInstalledPluginsPath())
}
val bundled = if (effectiveBundledPluginDir == null) {
emptyList()
}
else {
loadDescriptorsFromDir(dir = effectiveBundledPluginDir, context = context, isBundled = true, pool = zipFilePool)
}
(root + custom + bundled)
}
}
private fun CoroutineScope.loadCoreModules(context: DescriptorListLoadingContext,
platformPrefix: String,
isUnitTestMode: Boolean,
isInDevServerMode: Boolean,
isRunningFromSources: Boolean,
pool: ZipFilePool?): List<Deferred<IdeaPluginDescriptorImpl?>> {
val classLoader = DescriptorListLoadingContext::class.java.classLoader
val pathResolver = ClassPathXmlPathResolver(classLoader = classLoader, isRunningFromSources = isRunningFromSources && !isInDevServerMode)
val useCoreClassLoader = pathResolver.isRunningFromSources ||
platformPrefix.startsWith("CodeServer") ||
java.lang.Boolean.getBoolean("idea.force.use.core.classloader")
// should be the only plugin in lib (only for Ultimate and WebStorm for now)
val rootModuleDescriptors = if ((platformPrefix == PlatformUtils.IDEA_PREFIX || platformPrefix == PlatformUtils.WEB_PREFIX) &&
(isInDevServerMode || (!isUnitTestMode && !isRunningFromSources))) {
Collections.singletonList(async {
loadCoreProductPlugin(getResourceReader(PluginManagerCore.PLUGIN_XML_PATH, classLoader)!!,
context = context,
pathResolver = pathResolver,
useCoreClassLoader = useCoreClassLoader)
})
}
else {
val fileName = "${platformPrefix}Plugin.xml"
var result = listOf(async {
getResourceReader("${PluginManagerCore.META_INF}$fileName", classLoader)?.let {
loadCoreProductPlugin(it, context, pathResolver, useCoreClassLoader)
}
})
val urlToFilename = collectPluginFilesInClassPath(classLoader)
if (!urlToFilename.isEmpty()) {
@Suppress("SuspiciousCollectionReassignment")
result += loadDescriptorsFromClassPath(urlToFilename = urlToFilename,
context = context,
pathResolver = pathResolver,
useCoreClassLoader = useCoreClassLoader,
pool = pool)
}
result
}
return rootModuleDescriptors
}
private fun getResourceReader(path: String, classLoader: ClassLoader): XMLStreamReader2? {
if (classLoader is UrlClassLoader) {
return createNonCoalescingXmlStreamReader(classLoader.getResourceAsBytes(path, false) ?: return null, path)
}
else {
return createNonCoalescingXmlStreamReader(classLoader.getResourceAsStream(path) ?: return null, path)
}
}
private fun loadCoreProductPlugin(reader: XMLStreamReader2,
context: DescriptorListLoadingContext,
pathResolver: ClassPathXmlPathResolver,
useCoreClassLoader: Boolean): IdeaPluginDescriptorImpl {
val dataLoader = object : DataLoader {
override val pool: ZipFilePool
get() = throw IllegalStateException("must be not called")
override val emptyDescriptorIfCannotResolve: Boolean
get() = true
override fun load(path: String) = throw IllegalStateException("must be not called")
override fun toString() = "product classpath"
}
val raw = readModuleDescriptor(reader,
readContext = context,
pathResolver = pathResolver,
dataLoader = dataLoader,
includeBase = null,
readInto = null)
val descriptor = IdeaPluginDescriptorImpl(raw = raw,
path = Paths.get(PathManager.getLibPath()),
isBundled = true,
id = null,
moduleName = null,
useCoreClassLoader = useCoreClassLoader)
descriptor.readExternal(raw = raw, pathResolver = pathResolver, context = context, isSub = false, dataLoader = dataLoader)
return descriptor
}
private fun collectPluginFilesInClassPath(loader: ClassLoader): Map<URL, String> {
val urlToFilename = LinkedHashMap<URL, String>()
try {
val enumeration = loader.getResources(PluginManagerCore.PLUGIN_XML_PATH)
while (enumeration.hasMoreElements()) {
urlToFilename.put(enumeration.nextElement(), PluginManagerCore.PLUGIN_XML)
}
}
catch (e: IOException) {
LOG.warn(e)
}
return urlToFilename
}
@Throws(IOException::class)
fun loadDescriptorFromArtifact(file: Path, buildNumber: BuildNumber?): IdeaPluginDescriptorImpl? {
val context = DescriptorListLoadingContext(isMissingSubDescriptorIgnored = true,
disabledPlugins = DisabledPluginsState.getDisabledIds(),
productBuildNumber = { buildNumber ?: PluginManagerCore.getBuildNumber() },
transient = true)
val descriptor = runBlocking {
loadDescriptorFromFileOrDir(file = file,
context = context,
pathResolver = PluginXmlPathResolver.DEFAULT_PATH_RESOLVER,
isBundled = false,
isEssential = false,
isDirectory = false,
useCoreClassLoader = false,
pool = null)
}
if (descriptor != null || !file.toString().endsWith(".zip")) {
return descriptor
}
val outputDir = Files.createTempDirectory("plugin")!!
try {
Decompressor.Zip(file).extract(outputDir)
try {
//org.jetbrains.intellij.build.io.ZipArchiveOutputStream may add __index__ entry to the plugin zip, we need to ignore it here
val rootDir = NioFiles.list(outputDir).firstOrNull { it.name != "__index__" }
if (rootDir != null) {
return runBlocking {
loadDescriptorFromFileOrDir(file = rootDir,
context = context,
pathResolver = PluginXmlPathResolver.DEFAULT_PATH_RESOLVER,
isBundled = false,
isEssential = false,
isDirectory = true,
useCoreClassLoader = false,
pool = null)
}
}
}
catch (ignore: NoSuchFileException) {
}
}
finally {
NioFiles.deleteRecursively(outputDir)
}
return null
}
fun loadDescriptor(file: Path,
disabledPlugins: Set<PluginId>,
isBundled: Boolean,
pathResolver: PathResolver): IdeaPluginDescriptorImpl? {
DescriptorListLoadingContext(disabledPlugins = disabledPlugins).use { context ->
return runBlocking {
loadDescriptorFromFileOrDir(file = file,
context = context,
pathResolver = pathResolver,
isBundled = isBundled,
isEssential = false,
isDirectory = Files.isDirectory(file),
useCoreClassLoader = false,
pool = null)
}
}
}
@Throws(ExecutionException::class, InterruptedException::class)
fun loadDescriptors(
customPluginDir: Path,
bundledPluginDir: Path?,
brokenPluginVersions: Map<PluginId, Set<String?>>?,
productBuildNumber: BuildNumber?,
): PluginLoadingResult {
return DescriptorListLoadingContext(
disabledPlugins = emptySet(),
brokenPluginVersions = brokenPluginVersions ?: PluginManagerCore.getBrokenPluginVersions(),
productBuildNumber = { productBuildNumber ?: PluginManagerCore.getBuildNumber() },
isMissingIncludeIgnored = true,
isMissingSubDescriptorIgnored = true,
).use { context ->
runBlocking {
val result = PluginLoadingResult()
result.addAll(
descriptors = loadDescriptorsFromDirs(context = context,
customPluginDir = customPluginDir,
bundledPluginDir = bundledPluginDir,
zipFilePool = null).awaitAll(),
overrideUseIfCompatible = false,
productBuildNumber = context.productBuildNumber()
)
result
}
}
}
@TestOnly
fun testLoadDescriptorsFromClassPath(loader: ClassLoader): List<IdeaPluginDescriptor> {
val urlToFilename = collectPluginFilesInClassPath(loader)
val buildNumber = BuildNumber.fromString("2042.42")!!
val context = DescriptorListLoadingContext(disabledPlugins = Collections.emptySet(),
brokenPluginVersions = emptyMap(),
productBuildNumber = { buildNumber })
return runBlocking {
val result = PluginLoadingResult(checkModuleDependencies = false)
result.addAll(loadDescriptorsFromClassPath(
urlToFilename = urlToFilename,
context = context,
pathResolver = ClassPathXmlPathResolver(loader, isRunningFromSources = false),
useCoreClassLoader = true,
pool = if (context.transient) null else ZipFilePool.POOL,
).awaitAll(), overrideUseIfCompatible = false, productBuildNumber = buildNumber)
result.enabledPlugins
}
}
private fun CoroutineScope.loadDescriptorsFromDir(dir: Path,
context: DescriptorListLoadingContext,
isBundled: Boolean,
pool: ZipFilePool?): List<Deferred<IdeaPluginDescriptorImpl?>> {
if (!Files.isDirectory(dir)) {
return emptyList()
}
return Files.newDirectoryStream(dir).use { dirStream ->
dirStream.map { file ->
async {
loadDescriptorFromFileOrDir(
file = file,
context = context,
pathResolver = PluginXmlPathResolver.DEFAULT_PATH_RESOLVER,
isBundled = isBundled,
isDirectory = Files.isDirectory(file),
isEssential = false,
useCoreClassLoader = false,
pool = pool,
)
}
}
}
}
// urls here expected to be a file urls to plugin.xml
private fun CoroutineScope.loadDescriptorsFromClassPath(
urlToFilename: Map<URL, String>,
context: DescriptorListLoadingContext,
pathResolver: ClassPathXmlPathResolver,
useCoreClassLoader: Boolean,
pool: ZipFilePool?,
): List<Deferred<IdeaPluginDescriptorImpl?>> {
return urlToFilename.map { (url, filename) ->
async {
loadDescriptorFromResource(resource = url,
filename = filename,
context = context,
pathResolver = pathResolver,
useCoreClassLoader = useCoreClassLoader,
pool = pool)
}
}
}
// filename - plugin.xml or ${platformPrefix}Plugin.xml
private fun loadDescriptorFromResource(
resource: URL,
filename: String,
context: DescriptorListLoadingContext,
pathResolver: ClassPathXmlPathResolver,
useCoreClassLoader: Boolean,
pool: ZipFilePool?,
): IdeaPluginDescriptorImpl? {
val file = Paths.get(UrlClassLoader.urlToFilePath(resource.path))
var closeable: Closeable? = null
val dataLoader: DataLoader
val basePath: Path
try {
val input: InputStream
when {
URLUtil.FILE_PROTOCOL == resource.protocol -> {
basePath = file.parent.parent
dataLoader = LocalFsDataLoader(basePath)
input = Files.newInputStream(file)
}
URLUtil.JAR_PROTOCOL == resource.protocol -> {
// support for unpacked plugins in classpath, e.g. .../community/build/dependencies/build/kotlin/Kotlin/lib/kotlin-plugin.jar
basePath = file.parent?.takeIf { !it.endsWith("lib") }?.parent ?: file
if (pool == null) {
val zipFile = ZipFile(file.toFile(), StandardCharsets.UTF_8)
closeable = zipFile
dataLoader = JavaZipFileDataLoader(zipFile)
}
else {
dataLoader = ImmutableZipFileDataLoader(pool.load(file), file, pool)
}
input = dataLoader.load("META-INF/$filename") ?: return null
}
else -> return null
}
val raw = readModuleDescriptor(input = input,
readContext = context,
pathResolver = pathResolver,
dataLoader = dataLoader,
includeBase = null,
readInto = null,
locationSource = file.toString())
// it is very important to not set useCoreClassLoader = true blindly
// - product modules must uses own class loader if not running from sources
val descriptor = IdeaPluginDescriptorImpl(raw = raw,
path = basePath,
isBundled = true,
id = null,
moduleName = null,
useCoreClassLoader = useCoreClassLoader)
descriptor.readExternal(raw = raw, pathResolver = pathResolver, context = context, isSub = false, dataLoader = dataLoader)
// do not set jarFiles by intention - doesn't make sense
return descriptor
}
catch (e: CancellationException) {
throw e
}
catch (e: Throwable) {
LOG.info("Cannot load $resource", e)
return null
}
finally {
closeable?.close()
}
} | apache-2.0 | 7b7c6d7b4c7da5a52190d73d22653bd7 | 38.83245 | 139 | 0.629722 | 5.442834 | false | false | false | false |
GunoH/intellij-community | platform/platform-impl/src/com/intellij/openapi/actionSystem/impl/segmentedActionBar/SegmentedActionToolbarComponent.kt | 2 | 7130 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.openapi.actionSystem.impl.segmentedActionBar
import com.intellij.openapi.actionSystem.*
import com.intellij.openapi.actionSystem.ex.ActionButtonLook
import com.intellij.openapi.actionSystem.ex.ComboBoxAction
import com.intellij.openapi.actionSystem.ex.ComboBoxAction.ComboBoxButton
import com.intellij.openapi.actionSystem.ex.CustomComponentAction
import com.intellij.openapi.actionSystem.impl.ActionButton
import com.intellij.openapi.actionSystem.impl.ActionToolbarImpl
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.diagnostic.Logger
import com.intellij.util.ui.JBInsets
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.UIUtil
import java.awt.*
import javax.swing.JComponent
import javax.swing.border.Border
open class SegmentedActionToolbarComponent(place: String,
group: ActionGroup,
private val paintBorderForSingleItem: Boolean = true) : ActionToolbarImpl(place, group, true) {
companion object {
internal const val CONTROL_BAR_PROPERTY = "CONTROL_BAR_PROPERTY"
internal const val CONTROL_BAR_FIRST = "CONTROL_BAR_PROPERTY_FIRST"
internal const val CONTROL_BAR_LAST = "CONTROL_BAR_PROPERTY_LAST"
internal const val CONTROL_BAR_MIDDLE = "CONTROL_BAR_PROPERTY_MIDDLE"
internal const val CONTROL_BAR_SINGLE = "CONTROL_BAR_PROPERTY_SINGLE"
const val RUN_TOOLBAR_COMPONENT_ACTION = "RUN_TOOLBAR_COMPONENT_ACTION"
private val LOG = Logger.getInstance(SegmentedActionToolbarComponent::class.java)
val segmentedButtonLook = object : ActionButtonLook() {
override fun paintBorder(g: Graphics, c: JComponent, state: Int) {
}
override fun paintBackground(g: Graphics, component: JComponent, state: Int) {
SegmentedBarPainter.paintActionButtonBackground(g, component, state)
}
}
fun isCustomBar(component: Component): Boolean {
if (component !is JComponent) return false
return component.getClientProperty(CONTROL_BAR_PROPERTY)?.let {
it != CONTROL_BAR_SINGLE
} ?: false
}
fun paintButtonDecorations(g: Graphics2D, c: JComponent, paint: Paint): Boolean {
return SegmentedBarPainter.paintButtonDecorations(g, c, paint)
}
}
init {
layoutPolicy = NOWRAP_LAYOUT_POLICY
setActionButtonBorder(JBUI.Borders.empty(0, 3))
setCustomButtonLook(segmentedButtonLook)
}
private var isActive = false
private var visibleActions: List<AnAction>? = null
override fun getInsets(): Insets {
return JBInsets.emptyInsets()
}
override fun setBorder(border: Border?) {
}
override fun createCustomComponent(action: CustomComponentAction, presentation: Presentation): JComponent {
var component = super.createCustomComponent(action, presentation)
if (!isActive) {
return component
}
if (action is ComboBoxAction) {
UIUtil.uiTraverser(component).filter(ComboBoxButton::class.java).firstOrNull()?.let {
component.remove(it)
component = it
}
}
if (component !is ActionButton) {
component.border = JBUI.Borders.empty()
}
return component
}
override fun fillToolBar(actions: List<AnAction>, layoutSecondaries: Boolean) {
if (!isActive) {
super.fillToolBar(actions, layoutSecondaries)
return
}
val rightAligned: MutableList<AnAction> = ArrayList()
for (i in actions.indices) {
val action = actions[i]
if (action is RightAlignedToolbarAction) {
rightAligned.add(action)
continue
}
if (action is CustomComponentAction) {
val component = getCustomComponent(action)
addMetadata(component, i, actions.size)
add(CUSTOM_COMPONENT_CONSTRAINT, component)
component.putClientProperty(RUN_TOOLBAR_COMPONENT_ACTION, action)
}
else {
val component = createToolbarButton(action)
addMetadata(component, i, actions.size)
add(ACTION_BUTTON_CONSTRAINT, component)
component.putClientProperty(RUN_TOOLBAR_COMPONENT_ACTION, action)
}
}
}
protected open fun isSuitableAction(action: AnAction): Boolean {
return true
}
override fun paintComponent(g: Graphics) {
super.paintComponent(g)
paintActiveBorder(g)
}
private fun paintActiveBorder(g: Graphics) {
if ((isActive || paintBorderForSingleItem) && visibleActions != null) {
SegmentedBarPainter.paintActionBarBorder(this, g)
}
}
override fun paintBorder(g: Graphics) {
super.paintBorder(g)
paintActiveBorder(g)
}
override fun paint(g: Graphics) {
super.paint(g)
paintActiveBorder(g)
}
private fun addMetadata(component: JComponent, index: Int, count: Int) {
if (count == 1) {
component.putClientProperty(CONTROL_BAR_PROPERTY, CONTROL_BAR_SINGLE)
return
}
val property = when (index) {
0 -> CONTROL_BAR_FIRST
count - 1 -> CONTROL_BAR_LAST
else -> CONTROL_BAR_MIDDLE
}
component.putClientProperty(CONTROL_BAR_PROPERTY, property)
}
protected open fun logNeeded() = false
protected fun forceUpdate() {
if (logNeeded()) LOG.info("RunToolbar MAIN SLOT forceUpdate")
visibleActions?.let {
update(true, it)
revalidate()
repaint()
}
}
override fun actionsUpdated(forced: Boolean, newVisibleActions: List<AnAction>) {
visibleActions = newVisibleActions
update(forced, newVisibleActions)
}
private var lastIds: List<String> = emptyList()
private var lastActions: List<AnAction> = emptyList()
private fun update(forced: Boolean, newVisibleActions: List<AnAction>) {
val filtered = newVisibleActions.filter { isSuitableAction(it) }
val ides = newVisibleActions.map { ActionManager.getInstance().getId(it) }.toList()
val filteredIds = filtered.map { ActionManager.getInstance().getId(it) }.toList()
traceState(lastIds, filteredIds, ides)
isActive = newVisibleActions.size > 1
super.actionsUpdated(forced, if (filtered.size > 1) filtered else if(lastActions.isEmpty()) newVisibleActions else lastActions)
lastIds = filteredIds
lastActions = filtered
ApplicationManager.getApplication().messageBus.syncPublisher(ToolbarActionsUpdatedListener.TOPIC).actionsUpdated()
}
protected open fun traceState(lastIds: List<String>, filteredIds: List<String>, ides: List<String>) {
// if(logNeeded() && filteredIds != lastIds) LOG.info("MAIN SLOT new filtered: ${filteredIds}} visible: $ides RunToolbar")
}
override fun calculateBounds(size2Fit: Dimension, bounds: MutableList<Rectangle>) {
bounds.clear()
for (i in 0 until componentCount) {
bounds.add(Rectangle())
}
var offset = 0
for (i in 0 until componentCount) {
val d = getChildPreferredSize(i)
val r = bounds[i]
r.setBounds(insets.left + offset, insets.top, d.width, DEFAULT_MINIMUM_BUTTON_SIZE.height)
offset += d.width
}
}
} | apache-2.0 | 174a0bb2a8f52c8ce1412dff3e759957 | 31.861751 | 138 | 0.707293 | 4.521243 | false | false | false | false |
GunoH/intellij-community | platform/projectModel-impl/src/com/intellij/workspaceModel/ide/impl/legacyBridge/module/roots/ModifiableContentEntryBridge.kt | 2 | 13555 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.workspaceModel.ide.impl.legacyBridge.module.roots
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.roots.*
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.util.CachedValueProvider
import com.intellij.util.CachedValueImpl
import com.intellij.workspaceModel.ide.getInstance
import com.intellij.workspaceModel.ide.impl.toVirtualFileUrl
import com.intellij.workspaceModel.ide.isEqualOrParentOf
import com.intellij.workspaceModel.storage.EntitySource
import com.intellij.workspaceModel.storage.MutableEntityStorage
import com.intellij.workspaceModel.storage.bridgeEntities.addSourceRootEntity
import com.intellij.workspaceModel.storage.bridgeEntities.ContentRootEntity
import com.intellij.workspaceModel.storage.bridgeEntities.ExcludeUrlEntity
import com.intellij.workspaceModel.storage.bridgeEntities.modifyEntity
import com.intellij.workspaceModel.storage.bridgeEntities.asJavaResourceRoot
import com.intellij.workspaceModel.storage.bridgeEntities.asJavaSourceRoot
import com.intellij.workspaceModel.storage.url.VirtualFileUrl
import com.intellij.workspaceModel.storage.url.VirtualFileUrlManager
import org.jetbrains.jps.model.JpsElement
import org.jetbrains.jps.model.java.JavaResourceRootProperties
import org.jetbrains.jps.model.java.JavaSourceRootProperties
import org.jetbrains.jps.model.java.JavaSourceRootType
import org.jetbrains.jps.model.module.JpsModuleSourceRootType
import org.jetbrains.jps.model.serialization.module.JpsModuleSourceRootPropertiesSerializer
internal class ModifiableContentEntryBridge(
private val diff: MutableEntityStorage,
private val modifiableRootModel: ModifiableRootModelBridgeImpl,
val contentEntryUrl: VirtualFileUrl
) : ContentEntry {
companion object {
private val LOG = logger<ModifiableContentEntryBridge>()
}
private val virtualFileManager = VirtualFileUrlManager.getInstance(modifiableRootModel.project)
private val currentContentEntry = CachedValueImpl {
val contentEntry = modifiableRootModel.currentModel.contentEntries.firstOrNull { it.url == contentEntryUrl.url } as? ContentEntryBridge
?: error("Unable to find content entry in parent modifiable root model by url: $contentEntryUrl")
CachedValueProvider.Result.createSingleDependency(contentEntry, modifiableRootModel)
}
private fun <P : JpsElement> addSourceFolder(sourceFolderUrl: VirtualFileUrl,
type: JpsModuleSourceRootType<P>,
properties: P,
folderEntitySource: EntitySource): SourceFolder {
if (!contentEntryUrl.isEqualOrParentOf(sourceFolderUrl)) {
error("Source folder $sourceFolderUrl must be under content entry $contentEntryUrl")
}
val duplicate = findDuplicate(sourceFolderUrl, type, properties)
if (duplicate != null) {
LOG.debug("Source folder for '$sourceFolderUrl' and type '$type' already exist")
return duplicate
}
val serializer: JpsModuleSourceRootPropertiesSerializer<P> = SourceRootPropertiesHelper.findSerializer(type)
?: error("Module source root type $type is not registered as JpsModelSerializerExtension")
val contentRootEntity = currentContentEntry.value.entity
val sourceRootEntity = diff.addSourceRootEntity(
contentRoot = contentRootEntity,
url = sourceFolderUrl,
rootType = serializer.typeId,
source = folderEntitySource
)
SourceRootPropertiesHelper.addPropertiesEntity(diff, sourceRootEntity, properties, serializer)
return currentContentEntry.value.sourceFolders.firstOrNull {
it.url == sourceFolderUrl.url && it.rootType == type
} ?: error("Source folder for '$sourceFolderUrl' and type '$type' was not found after adding")
}
private fun <P : JpsElement?> findDuplicate(sourceFolderUrl: VirtualFileUrl, type: JpsModuleSourceRootType<P>,
properties: P): SourceFolder? {
val propertiesFilter: (SourceFolder) -> Boolean = when (properties) {
is JavaSourceRootProperties -> label@{ sourceFolder: SourceFolder ->
val javaSourceRoot = (sourceFolder as SourceFolderBridge).sourceRootEntity.asJavaSourceRoot()
return@label javaSourceRoot != null && javaSourceRoot.generated == properties.isForGeneratedSources
&& javaSourceRoot.packagePrefix == properties.packagePrefix
}
is JavaResourceRootProperties -> label@{ sourceFolder: SourceFolder ->
val javaResourceRoot = (sourceFolder as SourceFolderBridge).sourceRootEntity.asJavaResourceRoot()
return@label javaResourceRoot != null && javaResourceRoot.generated == properties.isForGeneratedSources
&& javaResourceRoot.relativeOutputPath == properties.relativeOutputPath
}
else -> { _ -> true }
}
return sourceFolders.filter { it.url == sourceFolderUrl.url && it.rootType == type }.find { propertiesFilter.invoke(it) }
}
override fun removeSourceFolder(sourceFolder: SourceFolder) {
val legacyBridgeSourceFolder = sourceFolder as SourceFolderBridge
val sourceRootEntity = currentContentEntry.value.sourceRootEntities.firstOrNull { it == legacyBridgeSourceFolder.sourceRootEntity }
if (sourceRootEntity == null) {
LOG.error("SourceFolder ${sourceFolder.url} is not present under content entry $contentEntryUrl")
return
}
modifiableRootModel.removeCachedJpsRootProperties(sourceRootEntity.url)
diff.removeEntity(sourceRootEntity)
}
override fun clearSourceFolders() {
currentContentEntry.value.sourceRootEntities.forEach { sourceRoot -> diff.removeEntity(sourceRoot) }
}
private fun addExcludeFolder(excludeUrl: VirtualFileUrl, projectSource: ProjectModelExternalSource?): ExcludeFolder {
if (!contentEntryUrl.isEqualOrParentOf(excludeUrl)) {
error("Exclude folder $excludeUrl must be under content entry $contentEntryUrl")
}
if (excludeUrl !in currentContentEntry.value.entity.excludedUrls.map { it.url }) {
updateContentEntry {
val source = if (projectSource == null) getInternalFileSource(entitySource) ?: entitySource else entitySource
excludedUrls = excludedUrls + ExcludeUrlEntity(excludeUrl, source)
}
}
return currentContentEntry.value.excludeFolders.firstOrNull {
it.url == excludeUrl.url
} ?: error("Exclude folder $excludeUrl must be present after adding it to content entry $contentEntryUrl")
}
override fun addExcludeFolder(file: VirtualFile): ExcludeFolder = addExcludeFolder(file.toVirtualFileUrl(virtualFileManager), null)
override fun addExcludeFolder(url: String): ExcludeFolder = addExcludeFolder(virtualFileManager.fromUrl(url), null)
override fun addExcludeFolder(url: String, source: ProjectModelExternalSource): ExcludeFolder {
return addExcludeFolder(virtualFileManager.fromUrl(url), source)
}
override fun removeExcludeFolder(excludeFolder: ExcludeFolder) {
val virtualFileUrl = (excludeFolder as ExcludeFolderBridge).excludeFolderUrl
val excludeUrlEntities = currentContentEntry.value.entity.excludedUrls.filter { it.url == virtualFileUrl }
if (excludeUrlEntities.isEmpty()) {
error("Exclude folder ${excludeFolder.url} is not under content entry $contentEntryUrl")
}
excludeUrlEntities.forEach {
diff.removeEntity(it)
}
}
private fun updateContentEntry(updater: ContentRootEntity.Builder.() -> Unit) {
diff.modifyEntity(currentContentEntry.value.entity, updater)
}
override fun removeExcludeFolder(url: String): Boolean {
val virtualFileUrl = virtualFileManager.fromUrl(url)
val excludedUrls = currentContentEntry.value.entity.excludedUrls.map { it.url }
if (!excludedUrls.contains(virtualFileUrl)) return false
val contentRootEntity = currentContentEntry.value.entity
val (new, toRemove) = contentRootEntity.excludedUrls.partition {excludedUrl -> excludedUrl.url != virtualFileUrl }
updateContentEntry {
this.excludedUrls = new
}
toRemove.forEach { diff.removeEntity(it) }
return true
}
override fun clearExcludeFolders() {
updateContentEntry {
excludedUrls = mutableListOf()
}
}
override fun addExcludePattern(pattern: String) {
updateContentEntry {
if (!excludedPatterns.contains(pattern)) excludedPatterns.add(pattern)
}
}
override fun removeExcludePattern(pattern: String) {
updateContentEntry {
excludedPatterns.remove(pattern)
}
}
override fun setExcludePatterns(patterns: MutableList<String>) {
updateContentEntry {
excludedPatterns = patterns.toMutableList()
}
}
override fun equals(other: Any?): Boolean {
return (other as? ContentEntry)?.url == url
}
override fun hashCode(): Int {
return url.hashCode()
}
override fun addSourceFolder(file: VirtualFile, isTestSource: Boolean) = addSourceFolder(file, isTestSource, "")
override fun addSourceFolder(file: VirtualFile, isTestSource: Boolean, packagePrefix: String): SourceFolder =
addSourceFolder(file, if (isTestSource) JavaSourceRootType.TEST_SOURCE else JavaSourceRootType.SOURCE,
JavaSourceRootProperties(packagePrefix, false))
override fun <P : JpsElement> addSourceFolder(file: VirtualFile, type: JpsModuleSourceRootType<P>): SourceFolder =
addSourceFolder(file, type, type.createDefaultProperties())
override fun addSourceFolder(url: String, isTestSource: Boolean): SourceFolder =
addSourceFolder(url, if (isTestSource) JavaSourceRootType.TEST_SOURCE else JavaSourceRootType.SOURCE)
override fun <P : JpsElement> addSourceFolder(url: String, type: JpsModuleSourceRootType<P>): SourceFolder {
return addSourceFolder(url, type, type.createDefaultProperties())
}
override fun <P : JpsElement> addSourceFolder(url: String,
type: JpsModuleSourceRootType<P>,
externalSource: ProjectModelExternalSource): SourceFolder {
return addSourceFolder(url, type, type.createDefaultProperties(), externalSource)
}
override fun <P : JpsElement> addSourceFolder(url: String,
type: JpsModuleSourceRootType<P>,
useSourceOfContentRoot: Boolean): SourceFolder {
val contentRootSource = currentContentEntry.value.entity.entitySource
val source = if (useSourceOfContentRoot) contentRootSource else getInternalFileSource(contentRootSource) ?: contentRootSource
return addSourceFolder(virtualFileManager.fromUrl(url), type, type.createDefaultProperties(), source)
}
override fun <P : JpsElement> addSourceFolder(file: VirtualFile, type: JpsModuleSourceRootType<P>, properties: P): SourceFolder {
val contentRootSource = currentContentEntry.value.entity.entitySource
val source: EntitySource = getInternalFileSource(contentRootSource) ?: contentRootSource
return addSourceFolder(file.toVirtualFileUrl(virtualFileManager), type, properties, source)
}
override fun <P : JpsElement> addSourceFolder(url: String, type: JpsModuleSourceRootType<P>, properties: P): SourceFolder {
val contentRootSource = currentContentEntry.value.entity.entitySource
val source: EntitySource = getInternalFileSource(contentRootSource) ?: contentRootSource
return addSourceFolder(virtualFileManager.fromUrl(url), type, properties, source)
}
override fun <P : JpsElement> addSourceFolder(url: String,
type: JpsModuleSourceRootType<P>,
properties: P,
externalSource: ProjectModelExternalSource?): SourceFolder {
val contentRootSource = currentContentEntry.value.entity.entitySource
val source = if (externalSource != null) contentRootSource else getInternalFileSource(contentRootSource) ?: contentRootSource
return addSourceFolder(virtualFileManager.fromUrl(url), type, properties, source)
}
override fun getFile(): VirtualFile? = currentContentEntry.value.file
override fun getUrl(): String = contentEntryUrl.url
override fun getSourceFolders(): Array<SourceFolder> = currentContentEntry.value.sourceFolders
override fun getSourceFolders(rootType: JpsModuleSourceRootType<*>): List<SourceFolder> =
currentContentEntry.value.getSourceFolders(rootType)
override fun getSourceFolders(rootTypes: MutableSet<out JpsModuleSourceRootType<*>>): List<SourceFolder> =
currentContentEntry.value.getSourceFolders(rootTypes)
override fun getSourceFolderFiles(): Array<VirtualFile> = currentContentEntry.value.sourceFolderFiles
override fun getExcludeFolders(): Array<ExcludeFolder> = currentContentEntry.value.excludeFolders
override fun getExcludeFolderUrls(): MutableList<String> = currentContentEntry.value.excludeFolderUrls
override fun getExcludeFolderFiles(): Array<VirtualFile> = currentContentEntry.value.excludeFolderFiles
override fun getExcludePatterns(): List<String> = currentContentEntry.value.excludePatterns
override fun getRootModel(): ModuleRootModel = modifiableRootModel
override fun isSynthetic(): Boolean = currentContentEntry.value.isSynthetic
}
| apache-2.0 | ccb510de8ac41629988cba154b9bf536 | 49.958647 | 155 | 0.745481 | 5.726658 | false | false | false | false |
GunoH/intellij-community | plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/ui/toolwindow/models/versions/PackageVersionNormalizer.kt | 2 | 8609 | /*******************************************************************************
* Copyright 2000-2022 JetBrains s.r.o. and contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.versions
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.PackageVersion
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.versions.NormalizedPackageVersion.Garbage
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.versions.NormalizedPackageVersion.Semantic
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.versions.NormalizedPackageVersion.TimestampLike
import com.jetbrains.packagesearch.intellij.plugin.util.CoroutineLRUCache
import com.jetbrains.packagesearch.intellij.plugin.util.nullIfBlank
import kotlinx.coroutines.runBlocking
internal class PackageVersionNormalizer(
private val versionsCache: CoroutineLRUCache<PackageVersion.Named, NormalizedPackageVersion<PackageVersion.Named>> = CoroutineLRUCache(2_000)
) {
private val HEX_STRING_LETTER_CHARS = 'a'..'f'
/**
* Matches a whole string starting with a semantic version. A valid semantic version
* has [1, 5] numeric components, each up to 5 digits long. Between each component
* there is a period character.
*
* Examples of valid semver: 1, 1.0-whatever, 1.2.3, 2.3.3.0-beta02, 21.4.0.0.1
* Examples of invalid semver: 1.0.0.0.0.1 (too many components), 123456 (component too long)
*
* Group 0 matches the whole string, group 1 is the semver minus any suffixes.
*/
private val SEMVER_REGEX = "^((?:\\d{1,5}\\.){0,4}\\d{1,5}(?!\\.?\\d)).*\$".toRegex(option = RegexOption.IGNORE_CASE)
/**
* Extracts stability markers. Must be used on the string that follows a valid semver (see [SEMVER_REGEX]).
*
* Stability markers are made up by a separator character (one of: . _ - +), then one of the stability tokens (see the list below), followed by an
* optional separator (one of: . _ -), AND [0, 5] numeric digits. After the digits, there must be a word boundary (most punctuation, except for
* underscores, qualifies as such).
*
* We only support up to two stability markers (arguably, having two already qualifies for the [Garbage] tier, but we have well-known libraries
* out there that do the two-markers game, now and then, and we need to support those shenanigans).
*
* ### Stability tokens
* We support the following stability tokens:
* * `snapshots`*, `snapshot`, `snap`, `s`*
* * `preview`, `eap`, `pre`, `p`*
* * `develop`*, `dev`*
* * `milestone`*, `m`, `build`*
* * `alpha`, `a`
* * `betta` (yes, there are Bettas out there), `beta`, `b`
* * `candidate`*, `rc`
* * `sp`
* * `release`, `final`, `stable`*, `rel`, `r`
*
* Tokens denoted by a `*` are considered as meaningless words by [com.intellij.util.text.VersionComparatorUtil] when comparing without a custom
* token priority provider, so sorting may be funky when they appear.
*/
private val STABILITY_MARKER_REGEX =
("^((?:[._\\-+]" +
"(?:snapshots?|preview|milestone|candidate|release|develop|stable|build|alpha|betta|final|snap|beta|dev|pre|eap|rel|sp|rc|m|r|b|a|p)" +
"(?:[._\\-]?\\d{1,5})?){1,2})(?:\\b|_)")
.toRegex(option = RegexOption.IGNORE_CASE)
suspend fun <T : PackageVersion> parse(version: T): NormalizedPackageVersion<*> =
when (version) {
is PackageVersion.Missing -> NormalizedPackageVersion.Missing
is PackageVersion.Named -> parse(version)
else -> error("Unknown version type: ${version.javaClass.simpleName}")
}
suspend fun parse(version: PackageVersion.Named): NormalizedPackageVersion<PackageVersion.Named> {
val cachedValue = versionsCache.get(version)
if (cachedValue != null) return cachedValue
// Before parsing, we rule out git commit hashes — those are garbage as far as we're concerned.
// The initial step attempts to parse the version as a date(time) string starting at 0; if that fails,
// and the version is not one uninterrupted alphanumeric blob (trying to catch more garbage), it
// tries parsing it as a semver; if that fails too, the version name is considered "garbage"
// (that is, it realistically can't be sorted if not by timestamp, and by hoping for the best).
val garbage = Garbage(version)
if (version.looksLikeGitCommitOrOtherHash()) {
versionsCache.put(version, garbage)
return garbage
}
val timestampPrefix = VeryLenientDateTimeExtractor.extractTimestampLookingPrefixOrNull(version.versionName)
if (timestampPrefix != null) {
val normalized = parseTimestampVersion(version, timestampPrefix)
versionsCache.put(version, normalized)
return normalized
}
if (version.isOneBigHexadecimalBlob()) {
versionsCache.put(version, garbage)
return garbage
}
val semanticVersionPrefix = version.semanticVersionPrefixOrNull()
if (semanticVersionPrefix != null) {
val normalized = parseSemanticVersion(version, semanticVersionPrefix)
versionsCache.put(version, normalized)
return normalized
}
versionsCache.put(version, garbage)
return garbage
}
fun parseBlocking(version: PackageVersion.Named) = runBlocking { parse(version) }
private fun PackageVersion.Named.looksLikeGitCommitOrOtherHash(): Boolean {
val hexLookingPrefix = versionName.takeWhile { it.isDigit() || HEX_STRING_LETTER_CHARS.contains(it) }
return when (hexLookingPrefix.length) {
7, 40 -> true
else -> false
}
}
private fun parseTimestampVersion(version: PackageVersion.Named, timestampPrefix: String): NormalizedPackageVersion<PackageVersion.Named> =
TimestampLike(
original = version,
timestampPrefix = timestampPrefix,
stabilityMarker = version.stabilitySuffixComponentOrNull(timestampPrefix),
nonSemanticSuffix = version.nonSemanticSuffix(timestampPrefix)
)
private fun PackageVersion.Named.isOneBigHexadecimalBlob(): Boolean {
var hasHexChars = false
for (char in versionName.lowercase()) {
when {
char in HEX_STRING_LETTER_CHARS -> hasHexChars = true
!char.isDigit() -> return false
}
}
return hasHexChars
}
private fun parseSemanticVersion(version: PackageVersion.Named, semanticVersionPrefix: String): NormalizedPackageVersion<PackageVersion.Named> =
Semantic(
original = version,
semanticPart = semanticVersionPrefix,
stabilityMarker = version.stabilitySuffixComponentOrNull(semanticVersionPrefix),
nonSemanticSuffix = version.nonSemanticSuffix(semanticVersionPrefix)
)
private fun PackageVersion.Named.semanticVersionPrefixOrNull(): String? {
val groupValues = SEMVER_REGEX.find(versionName)?.groupValues ?: return null
if (groupValues.size <= 1) return null
return groupValues[1]
}
private fun PackageVersion.Named.stabilitySuffixComponentOrNull(ignoredPrefix: String): String? {
val groupValues = STABILITY_MARKER_REGEX.find(versionName.substringAfter(ignoredPrefix))
?.groupValues ?: return null
if (groupValues.size <= 1) return null
return groupValues[1].takeIf { it.isNotBlank() }
}
private fun PackageVersion.Named.nonSemanticSuffix(ignoredPrefix: String?): String? {
val semanticPart = stabilitySuffixComponentOrNull(ignoredPrefix ?: return null)
?: ignoredPrefix
return versionName.substringAfter(semanticPart).nullIfBlank()
}
}
| apache-2.0 | fb10272f84efd565d092e3aa512df3a7 | 47.627119 | 150 | 0.670036 | 4.573326 | false | false | false | false |
google/accompanist | insets/src/main/java/com/google/accompanist/insets/WindowInsets.kt | 1 | 20258 | /*
* 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
*
* 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.
*/
@file:Suppress("DEPRECATION")
package com.google.accompanist.insets
import android.view.View
import android.view.WindowInsetsAnimation
import androidx.annotation.FloatRange
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.ProvidableCompositionLocal
import androidx.compose.runtime.Stable
import androidx.compose.runtime.remember
import androidx.compose.runtime.staticCompositionLocalOf
import androidx.compose.ui.platform.LocalView
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsAnimationCompat
import androidx.core.view.WindowInsetsCompat
/**
* The main insets holder, containing instances of [WindowInsets.Type] which each refer to different
* types of system display insets.
*/
@Stable
@Deprecated(
"""
accompanist/insets is deprecated.
For more migration information, please visit https://google.github.io/accompanist/insets/#migration
""",
replaceWith = ReplaceWith(
"WindowInsets",
"androidx.compose.foundation.layout.WindowInsets"
)
)
interface WindowInsets {
/**
* Inset values which match [WindowInsetsCompat.Type.navigationBars]
*/
val navigationBars: Type
/**
* Inset values which match [WindowInsetsCompat.Type.statusBars]
*/
val statusBars: Type
/**
* Inset values which match [WindowInsetsCompat.Type.ime]
*/
val ime: Type
/**
* Inset values which match [WindowInsetsCompat.Type.systemGestures]
*/
val systemGestures: Type
/**
* Inset values which match [WindowInsetsCompat.Type.systemBars]
*/
val systemBars: Type
/**
* Inset values which match [WindowInsetsCompat.Type.displayCutout]
*/
val displayCutout: Type
/**
* Returns a copy of this instance with the given values.
*/
fun copy(
navigationBars: Type = this.navigationBars,
statusBars: Type = this.statusBars,
systemGestures: Type = this.systemGestures,
ime: Type = this.ime,
displayCutout: Type = this.displayCutout,
): WindowInsets = ImmutableWindowInsets(
systemGestures = systemGestures,
navigationBars = navigationBars,
statusBars = statusBars,
ime = ime,
displayCutout = displayCutout
)
companion object {
/**
* Empty and immutable instance of [WindowInsets].
*/
val Empty: WindowInsets = ImmutableWindowInsets()
}
/**
* Represents the values for a type of insets, and stores information about the layout insets,
* animating insets, and visibility of the insets.
*
* [WindowInsets.Type] instances are commonly stored in a [WindowInsets] instance.
*/
@Stable
@Deprecated(
"accompanist/insets is deprecated",
replaceWith = ReplaceWith(
"WindowInsets",
"androidx.compose.foundation.layout.WindowInsets"
)
)
interface Type : Insets {
/**
* The layout insets for this [WindowInsets.Type]. These are the insets which are defined from the
* current window layout.
*
* You should not normally need to use this directly, and instead use [left], [top],
* [right], and [bottom] to return the correct value for the current state.
*/
val layoutInsets: Insets
/**
* The animated insets for this [WindowInsets.Type]. These are the insets which are updated from
* any on-going animations. If there are no animations in progress, the returned [Insets] will
* be empty.
*
* You should not normally need to use this directly, and instead use [left], [top],
* [right], and [bottom] to return the correct value for the current state.
*/
val animatedInsets: Insets
/**
* Whether the insets are currently visible.
*/
val isVisible: Boolean
/**
* Whether this insets type is being animated at this moment.
*/
val animationInProgress: Boolean
/**
* The left dimension of the insets in pixels.
*/
override val left: Int
get() = (if (animationInProgress) animatedInsets else layoutInsets).left
/**
* The top dimension of the insets in pixels.
*/
override val top: Int
get() = (if (animationInProgress) animatedInsets else layoutInsets).top
/**
* The right dimension of the insets in pixels.
*/
override val right: Int
get() = (if (animationInProgress) animatedInsets else layoutInsets).right
/**
* The bottom dimension of the insets in pixels.
*/
override val bottom: Int
get() = (if (animationInProgress) animatedInsets else layoutInsets).bottom
/**
* The progress of any ongoing animations, in the range of 0 to 1.
* If there is no animation in progress, this will return 0.
*/
@get:FloatRange(from = 0.0, to = 1.0)
val animationFraction: Float
companion object {
/**
* Empty and immutable instance of [WindowInsets.Type].
*/
val Empty: Type = ImmutableWindowInsetsType()
}
}
}
/**
* This class sets up the necessary listeners on the given [view] to be able to observe
* [WindowInsetsCompat] instances dispatched by the system.
*
* This class is useful for when you prefer to handle the ownership of the [WindowInsets]
* yourself. One example of this is if you find yourself using [ProvideWindowInsets] in fragments.
*
* It is convenient to use [ProvideWindowInsets] in fragments, but that can result in a
* delay in the initial inset update, which results in a visual flicker.
* See [this issue](https://github.com/google/accompanist/issues/155) for more information.
*
* The alternative is for fragments to manage the [WindowInsets] themselves, like so:
*
* ```
* override fun onCreateView(
* inflater: LayoutInflater,
* container: ViewGroup?,
* savedInstanceState: Bundle?
* ): View = ComposeView(requireContext()).apply {
* layoutParams = LayoutParams(MATCH_PARENT, MATCH_PARENT)
*
* // Create an ViewWindowInsetObserver using this view
* val observer = ViewWindowInsetObserver(this)
*
* // Call start() to start listening now.
* // The WindowInsets instance is returned to us.
* val windowInsets = observer.start()
*
* setContent {
* // Instead of calling ProvideWindowInsets, we use CompositionLocalProvider to provide
* // the WindowInsets instance from above to LocalWindowInsets
* CompositionLocalProvider(LocalWindowInsets provides windowInsets) {
* /* Content */
* }
* }
* }
* ```
*
* @param view The view to observe [WindowInsetsCompat]s from.
*/
@Deprecated(
"""
accompanist/insets is deprecated.
ViewWindowInsetObserver is not necessary in androidx.compose and can be removed.
For more migration information, please visit https://google.github.io/accompanist/insets/#migration
"""
)
class ViewWindowInsetObserver(private val view: View) {
private val attachListener = object : View.OnAttachStateChangeListener {
override fun onViewAttachedToWindow(v: View) = v.requestApplyInsets()
override fun onViewDetachedFromWindow(v: View) = Unit
}
/**
* Whether this [ViewWindowInsetObserver] is currently observing.
*/
@Suppress("MemberVisibilityCanBePrivate")
var isObserving: Boolean = false
private set
/**
* Start observing window insets from [view]. Make sure to call [stop] if required.
*
* @param windowInsetsAnimationsEnabled Whether to listen for [WindowInsetsAnimation]s, such as
* IME animations.
* @param consumeWindowInsets Whether to consume any [WindowInsetsCompat]s which are
* dispatched to the host view. Defaults to `true`.
*/
fun start(
consumeWindowInsets: Boolean = true,
windowInsetsAnimationsEnabled: Boolean = true,
): WindowInsets = RootWindowInsets().also {
observeInto(
windowInsets = it,
consumeWindowInsets = consumeWindowInsets,
windowInsetsAnimationsEnabled = windowInsetsAnimationsEnabled
)
}
internal fun observeInto(
windowInsets: RootWindowInsets,
consumeWindowInsets: Boolean,
windowInsetsAnimationsEnabled: Boolean,
) {
require(!isObserving) {
"start() called, but this ViewWindowInsetObserver is already observing"
}
ViewCompat.setOnApplyWindowInsetsListener(view) { _, wic ->
// Go through each inset type and update its layoutInsets from the
// WindowInsetsCompat values
windowInsets.statusBars.run {
layoutInsets.updateFrom(wic.getInsets(WindowInsetsCompat.Type.statusBars()))
isVisible = wic.isVisible(WindowInsetsCompat.Type.statusBars())
}
windowInsets.navigationBars.run {
layoutInsets.updateFrom(wic.getInsets(WindowInsetsCompat.Type.navigationBars()))
isVisible = wic.isVisible(WindowInsetsCompat.Type.navigationBars())
}
windowInsets.systemGestures.run {
layoutInsets.updateFrom(wic.getInsets(WindowInsetsCompat.Type.systemGestures()))
isVisible = wic.isVisible(WindowInsetsCompat.Type.systemGestures())
}
windowInsets.ime.run {
layoutInsets.updateFrom(wic.getInsets(WindowInsetsCompat.Type.ime()))
isVisible = wic.isVisible(WindowInsetsCompat.Type.ime())
}
windowInsets.displayCutout.run {
layoutInsets.updateFrom(wic.getInsets(WindowInsetsCompat.Type.displayCutout()))
isVisible = wic.isVisible(WindowInsetsCompat.Type.displayCutout())
}
if (consumeWindowInsets) WindowInsetsCompat.CONSUMED else wic
}
// Add an OnAttachStateChangeListener to request an inset pass each time we're attached
// to the window
view.addOnAttachStateChangeListener(attachListener)
if (windowInsetsAnimationsEnabled) {
ViewCompat.setWindowInsetsAnimationCallback(
view,
InnerWindowInsetsAnimationCallback(windowInsets)
)
} else {
ViewCompat.setWindowInsetsAnimationCallback(view, null)
}
if (view.isAttachedToWindow) {
// If the view is already attached, we can request an inset pass now
view.requestApplyInsets()
}
isObserving = true
}
/**
* Removes any listeners from the [view] so that we no longer observe inset changes.
*
* This is only required to be called from hosts which have a shorter lifetime than the [view].
* For example, if you're using [ViewWindowInsetObserver] from a `@Composable` function,
* you should call [stop] from an `onDispose` block, like so:
*
* ```
* DisposableEffect(view) {
* val observer = ViewWindowInsetObserver(view)
* // ...
* onDispose {
* observer.stop()
* }
* }
* ```
*
* Whereas if you're using this class from a fragment (or similar), it is not required to
* call this function since it will live as least as longer as the view.
*/
fun stop() {
require(isObserving) {
"stop() called, but this ViewWindowInsetObserver is not currently observing"
}
view.removeOnAttachStateChangeListener(attachListener)
ViewCompat.setOnApplyWindowInsetsListener(view, null)
isObserving = false
}
}
/**
* Applies any [WindowInsetsCompat] values to [LocalWindowInsets], which are then available
* within [content].
*
* If you're using this in fragments, you may wish to take a look at
* [ViewWindowInsetObserver] for a more optimal solution.
*
* @param windowInsetsAnimationsEnabled Whether to listen for [WindowInsetsAnimation]s, such as
* IME animations.
* @param consumeWindowInsets Whether to consume any [WindowInsetsCompat]s which are dispatched to
* the host view. Defaults to `true`.
*/
@Deprecated(
"""
accompanist/insets is deprecated.
For more migration information, please visit https://google.github.io/accompanist/insets/#migration
""",
replaceWith = ReplaceWith("content")
)
@Composable
fun ProvideWindowInsets(
consumeWindowInsets: Boolean = true,
windowInsetsAnimationsEnabled: Boolean = true,
content: @Composable () -> Unit
) {
val view = LocalView.current
val windowInsets = remember { RootWindowInsets() }
DisposableEffect(view) {
val observer = ViewWindowInsetObserver(view)
observer.observeInto(
windowInsets = windowInsets,
consumeWindowInsets = consumeWindowInsets,
windowInsetsAnimationsEnabled = windowInsetsAnimationsEnabled
)
onDispose { observer.stop() }
}
CompositionLocalProvider(LocalWindowInsets provides windowInsets) {
content()
}
}
private class InnerWindowInsetsAnimationCallback(
private val windowInsets: RootWindowInsets,
) : WindowInsetsAnimationCompat.Callback(DISPATCH_MODE_STOP) {
override fun onPrepare(animation: WindowInsetsAnimationCompat) {
// Go through each type and flag that an animation has started
if (animation.typeMask and WindowInsetsCompat.Type.ime() != 0) {
windowInsets.ime.onAnimationStart()
}
if (animation.typeMask and WindowInsetsCompat.Type.statusBars() != 0) {
windowInsets.statusBars.onAnimationStart()
}
if (animation.typeMask and WindowInsetsCompat.Type.navigationBars() != 0) {
windowInsets.navigationBars.onAnimationStart()
}
if (animation.typeMask and WindowInsetsCompat.Type.systemGestures() != 0) {
windowInsets.systemGestures.onAnimationStart()
}
if (animation.typeMask and WindowInsetsCompat.Type.displayCutout() != 0) {
windowInsets.displayCutout.onAnimationStart()
}
}
override fun onProgress(
platformInsets: WindowInsetsCompat,
runningAnimations: List<WindowInsetsAnimationCompat>
): WindowInsetsCompat {
// Update each inset type with the given parameters
windowInsets.ime.updateAnimation(
platformInsets = platformInsets,
runningAnimations = runningAnimations,
type = WindowInsetsCompat.Type.ime()
)
windowInsets.statusBars.updateAnimation(
platformInsets = platformInsets,
runningAnimations = runningAnimations,
type = WindowInsetsCompat.Type.statusBars()
)
windowInsets.navigationBars.updateAnimation(
platformInsets = platformInsets,
runningAnimations = runningAnimations,
type = WindowInsetsCompat.Type.navigationBars()
)
windowInsets.systemGestures.updateAnimation(
platformInsets = platformInsets,
runningAnimations = runningAnimations,
type = WindowInsetsCompat.Type.systemGestures()
)
windowInsets.displayCutout.updateAnimation(
platformInsets = platformInsets,
runningAnimations = runningAnimations,
type = WindowInsetsCompat.Type.displayCutout()
)
return platformInsets
}
private fun MutableWindowInsetsType.updateAnimation(
platformInsets: WindowInsetsCompat,
runningAnimations: List<WindowInsetsAnimationCompat>,
type: Int,
) {
// If there are animations of the given type...
if (runningAnimations.any { it.typeMask or type != 0 }) {
// Update our animated inset values
animatedInsets.updateFrom(platformInsets.getInsets(type))
// And update the animation fraction. We use the maximum animation progress of any
// ongoing animations for this type.
animationFraction = runningAnimations.maxOf { it.fraction }
}
}
override fun onEnd(animation: WindowInsetsAnimationCompat) {
// Go through each type and flag that an animation has ended
if (animation.typeMask and WindowInsetsCompat.Type.ime() != 0) {
windowInsets.ime.onAnimationEnd()
}
if (animation.typeMask and WindowInsetsCompat.Type.statusBars() != 0) {
windowInsets.statusBars.onAnimationEnd()
}
if (animation.typeMask and WindowInsetsCompat.Type.navigationBars() != 0) {
windowInsets.navigationBars.onAnimationEnd()
}
if (animation.typeMask and WindowInsetsCompat.Type.systemGestures() != 0) {
windowInsets.systemGestures.onAnimationEnd()
}
if (animation.typeMask and WindowInsetsCompat.Type.displayCutout() != 0) {
windowInsets.displayCutout.onAnimationEnd()
}
}
}
/**
* Holder of our root inset values.
*/
internal class RootWindowInsets : WindowInsets {
/**
* Inset values which match [WindowInsetsCompat.Type.systemGestures]
*/
override val systemGestures: MutableWindowInsetsType = MutableWindowInsetsType()
/**
* Inset values which match [WindowInsetsCompat.Type.navigationBars]
*/
override val navigationBars: MutableWindowInsetsType = MutableWindowInsetsType()
/**
* Inset values which match [WindowInsetsCompat.Type.statusBars]
*/
override val statusBars: MutableWindowInsetsType = MutableWindowInsetsType()
/**
* Inset values which match [WindowInsetsCompat.Type.ime]
*/
override val ime: MutableWindowInsetsType = MutableWindowInsetsType()
/**
* Inset values which match [WindowInsetsCompat.Type.displayCutout]
*/
override val displayCutout: MutableWindowInsetsType = MutableWindowInsetsType()
/**
* Inset values which match [WindowInsetsCompat.Type.systemBars]
*/
override val systemBars: WindowInsets.Type = derivedWindowInsetsTypeOf(statusBars, navigationBars)
}
/**
* Shallow-immutable implementation of [WindowInsets].
*/
internal class ImmutableWindowInsets(
override val systemGestures: WindowInsets.Type = WindowInsets.Type.Empty,
override val navigationBars: WindowInsets.Type = WindowInsets.Type.Empty,
override val statusBars: WindowInsets.Type = WindowInsets.Type.Empty,
override val ime: WindowInsets.Type = WindowInsets.Type.Empty,
override val displayCutout: WindowInsets.Type = WindowInsets.Type.Empty,
) : WindowInsets {
override val systemBars: WindowInsets.Type = derivedWindowInsetsTypeOf(statusBars, navigationBars)
}
@RequiresOptIn(message = "Animated Insets support is experimental. The API may be changed in the future.")
@Retention(AnnotationRetention.BINARY)
@Target(AnnotationTarget.CLASS, AnnotationTarget.FUNCTION)
annotation class ExperimentalAnimatedInsets
/**
* Composition local containing the current [WindowInsets].
*/
@Deprecated(
"""
accompanist/insets is deprecated.
The androidx.compose equivalent of LocalWindowInsets is the extensions on WindowInsets.
For more migration information, please visit https://google.github.io/accompanist/insets/#migration
"""
)
val LocalWindowInsets: ProvidableCompositionLocal<WindowInsets> =
staticCompositionLocalOf { WindowInsets.Empty }
| apache-2.0 | f70800bd0ffd99038aef68c89f2f863f | 35.566787 | 106 | 0.674203 | 5.100201 | false | false | false | false |
chaojimiaomiao/colorful_wechat | src/main/kotlin/com/rarnu/tophighlight/api/LocalApi.kt | 1 | 754 | package com.rarnu.tophighlight.api
import android.content.Context
import android.preference.PreferenceManager
/**
* Created by rarnu on 2/25/17.
*/
object LocalApi {
var ctx: Context? = null
private val KEY_USER_PROFILE_ID = "user_profile_id"
var userId: Int
get() {
var r = 0
if (ctx != null) {
val pref = PreferenceManager.getDefaultSharedPreferences(ctx)
r = pref.getInt(KEY_USER_PROFILE_ID, 0)
}
return r
}
set(value) {
if (ctx != null) {
val pref = PreferenceManager.getDefaultSharedPreferences(ctx)
pref.edit().putInt(KEY_USER_PROFILE_ID, value).apply()
}
}
} | gpl-3.0 | 3582a9aac42a67a966c12472cfd2c1a9 | 22.59375 | 77 | 0.55305 | 4.188889 | false | false | false | false |
MichaelRocks/grip | library/src/main/java/io/michaelrocks/grip/FileRegistry.kt | 1 | 3662 | /*
* Copyright 2021 Michael Rozumyanskiy
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.michaelrocks.grip
import io.michaelrocks.grip.commons.closeQuietly
import io.michaelrocks.grip.commons.immutable
import io.michaelrocks.grip.io.FileSource
import io.michaelrocks.grip.mirrors.Type
import io.michaelrocks.grip.mirrors.getObjectTypeByInternalName
import java.io.Closeable
import java.io.File
import java.util.ArrayList
import java.util.HashMap
import java.util.LinkedHashMap
interface FileRegistry {
operator fun contains(file: File): Boolean
operator fun contains(type: Type.Object): Boolean
fun classpath(): Collection<File>
fun readClass(type: Type.Object): ByteArray
fun findTypesForFile(file: File): Collection<Type.Object>
fun findFileForType(type: Type.Object): File?
}
internal class FileRegistryImpl(
classpath: Iterable<File>,
private val fileSourceFactory: FileSource.Factory
) : FileRegistry, Closeable {
private val sources = LinkedHashMap<File, FileSource>()
private val filesByTypes = HashMap<Type.Object, File>()
private val typesByFiles = HashMap<File, MutableCollection<Type.Object>>()
init {
classpath.forEach {
it.canonicalFile.let { file ->
if (file !in sources) {
val fileSource = fileSourceFactory.createFileSource(file)
sources.put(file, fileSource)
fileSource.listFiles { path, fileType ->
if (fileType == FileSource.EntryType.CLASS) {
val name = path.replace('\\', '/').substringBeforeLast(".class")
val type = getObjectTypeByInternalName(name)
filesByTypes.put(type, file)
typesByFiles.getOrPut(file) { ArrayList() } += type
}
}
}
}
}
check(!sources.isEmpty()) { "Classpath is empty" }
}
override fun contains(file: File): Boolean {
checkNotClosed()
return file.canonicalFile in sources
}
override fun contains(type: Type.Object): Boolean {
checkNotClosed()
return type in filesByTypes
}
override fun classpath(): Collection<File> {
checkNotClosed()
return sources.keys.immutable()
}
override fun readClass(type: Type.Object): ByteArray {
checkNotClosed()
val file = filesByTypes.getOrElse(type) {
throw IllegalArgumentException("Unable to find a file for ${type.internalName}")
}
val fileSource = sources.getOrElse(file) {
throw IllegalArgumentException("Unable to find a source for ${type.internalName}")
}
return fileSource.readFile("${type.internalName}.class")
}
override fun findTypesForFile(file: File): Collection<Type.Object> {
require(contains(file)) { "File $file is not added to the registry" }
return typesByFiles[file.canonicalFile]?.immutable() ?: emptyList()
}
override fun findFileForType(type: Type.Object): File? {
return filesByTypes[type]
}
override fun close() {
sources.values.forEach { it.closeQuietly() }
sources.clear()
filesByTypes.clear()
typesByFiles.clear()
}
private fun checkNotClosed() {
check(!sources.isEmpty()) { "FileRegistry was closed" }
}
}
| apache-2.0 | 2ff9992414ce352a1d7af07058c892cf | 30.843478 | 88 | 0.704533 | 4.422705 | false | false | false | false |
code-disaster/lwjgl3 | modules/lwjgl/nanovg/src/templates/kotlin/nanovg/templates/nanovg_gles2.kt | 4 | 3291 | /*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
*/
package nanovg.templates
import org.lwjgl.generator.*
import nanovg.*
val nanovg_gles2 = "NanoVGGLES2".dependsOn(Module.OPENGLES)?.nativeClass(Module.NANOVG, prefix = "NVG") {
includeNanoVGAPI("""#define NANOVG_GLES2_IMPLEMENTATION
#include "nanovg.h"
#include "nanovg_gl.h"
#include "nanovg_gl_utils.h"""")
documentation = "Implementation of the NanoVG API using OpenGL ES 2.0."
val CreateFlags = EnumConstant(
"Create flags.",
"ANTIALIAS".enum("Flag indicating if geometry based anti-aliasing is used (may not be needed when using MSAA).", "1<<0"),
"STENCIL_STROKES".enum(
"""
Flag indicating if strokes should be drawn using stencil buffer. The rendering will be a little slower, but path overlaps (i.e. self-intersecting
or sharp turns) will be drawn just once.
""",
"1<<1"
),
"DEBUG".enum("Flag indicating that additional debug checks are done.", "1<<2")
).javaDocLinks
EnumConstant(
"These are additional flags on top of NVGimageFlags.",
"IMAGE_NODELETE".enum("Do not delete GL texture handle.", "1<<16")
)
val ctx = NVGcontext.p("ctx", "the NanoVG context")
NativeName("nvglCreateImageFromHandleGLES2")..int(
"lCreateImageFromHandle",
"Creates a NanoVG image from an OpenGL texture.",
ctx,
GLuint("textureId", "the OpenGL texture id"),
int("w", "the image width"),
int("h", "the image height"),
int("flags", "the image flags"),
returnDoc = "a handle to the image"
)
NativeName("nvglImageHandleGLES2")..GLuint(
"lImageHandle",
"Returns the OpenGL texture id associated with a NanoVG image.",
ctx,
int("image", "the image handle")
)
NativeName("nvgCreateGLES2")..NVGcontext.p(
"Create",
"""
Creates a NanoVG context with an OpenGL ES 2.0 rendering back-end.
An OpenGL ES 2.0+ context must be current in the current thread when this function is called and the returned NanoVG context may only be used in
the thread in which that OpenGL context is current.
""",
JNI_ENV,
int("flags", "the context flags", CreateFlags)
)
NativeName("nvgDeleteGLES2")..void(
"Delete",
"Deletes a NanoVG context created with #Create().",
ctx
)
NativeName("nvgluCreateFramebufferGLES2")..NVGLUframebuffer.p(
"luCreateFramebuffer",
"Creates a framebuffer object to render to.",
ctx,
int("w", "the framebuffer width"),
int("h", "the framebuffer height"),
int("imageFlags", "the image flags")
)
NativeName("nvgluBindFramebufferGLES2")..void(
"luBindFramebuffer",
"Binds the framebuffer object associated with the specified ##NVGLUFramebuffer.",
ctx,
Input..nullable..NVGLUframebuffer.p("fb", "the framebuffer to bind")
)
NativeName("nvgluDeleteFramebufferGLES2")..void(
"luDeleteFramebuffer",
"Deletes an ##NVGLUFramebuffer.",
ctx,
Input..NVGLUframebuffer.p("fb", "the framebuffer to delete")
)
} | bsd-3-clause | c9e756a0a78721d67468b30ac3c73138 | 30.056604 | 157 | 0.627773 | 4.192357 | false | false | false | false |
mdanielwork/intellij-community | plugins/git4idea/src/git4idea/ignore/GitIgnoredFileContentProvider.kt | 1 | 1737 | // 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 git4idea.ignore
import com.intellij.openapi.project.Project
import com.intellij.openapi.vcs.VcsKey
import com.intellij.openapi.vcs.changes.IgnoredFileContentProvider
import com.intellij.openapi.vcs.changes.IgnoredFileProvider
import com.intellij.openapi.vfs.VirtualFile
import git4idea.GitVcs
import git4idea.repo.GitRepositoryFiles.GITIGNORE
import java.lang.System.lineSeparator
open class GitIgnoredFileContentProvider(private val project: Project) : IgnoredFileContentProvider {
override fun getSupportedVcs(): VcsKey = GitVcs.getKey()
override fun getFileName() = GITIGNORE
override fun buildIgnoreFileContent(ignoreFileRoot: VirtualFile, ignoredFileProviders: Array<IgnoredFileProvider>): String {
val content = StringBuilder()
val lineSeparator = lineSeparator()
for (i in ignoredFileProviders.indices) {
val provider = ignoredFileProviders[i]
val ignoredFileMasks = provider.getIgnoredFilesMasks(project, ignoreFileRoot)
if (ignoredFileMasks.isEmpty()) continue
if (!content.isEmpty()) {
content.append(lineSeparator).append(lineSeparator)
}
val description = provider.masksGroupDescription
if (description.isNotBlank()) {
content.append(prependCommentHashCharacterIfNeeded(description))
content.append(lineSeparator)
}
content.append(ignoredFileMasks.joinToString(lineSeparator))
}
return content.toString()
}
private fun prependCommentHashCharacterIfNeeded(description: String): String =
if (description.startsWith("#")) description else "# $description"
}
| apache-2.0 | b01dec54060a40013826b5e394b8623c | 38.477273 | 140 | 0.772596 | 4.694595 | false | false | false | false |
dahlstrom-g/intellij-community | plugins/markdown/core/src/org/intellij/plugins/markdown/editor/lists/ListItemIndentUnindentHandlerBase.kt | 7 | 3912 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.intellij.plugins.markdown.editor.lists
import com.intellij.openapi.actionSystem.DataContext
import com.intellij.openapi.editor.Caret
import com.intellij.openapi.editor.Document
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.actionSystem.EditorActionHandler
import com.intellij.openapi.editor.actionSystem.EditorWriteActionHandler
import com.intellij.openapi.util.registry.Registry
import com.intellij.psi.PsiDocumentManager
import com.intellij.refactoring.suggested.endOffset
import org.intellij.plugins.markdown.editor.lists.ListUtils.getListItemAtLine
import org.intellij.plugins.markdown.lang.psi.impl.MarkdownFile
import org.intellij.plugins.markdown.lang.psi.impl.MarkdownListItem
import org.intellij.plugins.markdown.settings.MarkdownSettings
/**
* This is a base class for classes, handling indenting/unindenting of list items.
* It collects selected items (or the ones the carets are inside) and calls [doIndentUnindent] and [updateNumbering] on them one by one.
*/
internal abstract class ListItemIndentUnindentHandlerBase(private val baseHandler: EditorActionHandler?) : EditorWriteActionHandler.ForEachCaret() {
override fun isEnabledForCaret(editor: Editor, caret: Caret, dataContext: DataContext?): Boolean =
baseHandler?.isEnabled(editor, caret, dataContext) == true
override fun executeWriteAction(editor: Editor, caret: Caret?, dataContext: DataContext?) {
val enabled = editor.project?.let { MarkdownSettings.getInstance(it) }?.isEnhancedEditingEnabled == true
if (caret == null || !enabled || !doExecuteAction(editor, caret)) {
baseHandler?.execute(editor, caret, dataContext)
}
}
private fun doExecuteAction(editor: Editor, caret: Caret): Boolean {
val project = editor.project ?: return false
val psiDocumentManager = PsiDocumentManager.getInstance(project)
val document = editor.document
val file = psiDocumentManager.getPsiFile(document) as? MarkdownFile ?: return false
val firstLinesOfSelectedItems = getFirstLinesOfSelectedItems(caret, document, file)
// use lines instead of items, because items may become invalid before used
var indentPerformed = false
for (line in firstLinesOfSelectedItems) {
psiDocumentManager.commitDocument(document)
val item = file.getListItemAtLine(line, document)!!
if (!doIndentUnindent(item, file, document)) {
continue
}
indentPerformed = true
if (Registry.`is`("markdown.lists.renumber.on.type.enable")) {
psiDocumentManager.commitDocument(document)
@Suppress("name_shadowing") // item is not valid anymore, but line didn't change
val item = file.getListItemAtLine(line, document)!!
updateNumbering(item, file, document)
}
}
return firstLinesOfSelectedItems.isNotEmpty() && indentPerformed
}
private fun getFirstLinesOfSelectedItems(caret: Caret, document: Document, file: MarkdownFile): List<Int> {
var line = document.getLineNumber(caret.selectionStart)
val lastLine = if (caret.hasSelection()) document.getLineNumber(caret.selectionEnd - 1) else line
val lines = mutableListOf<Int>()
while (line <= lastLine) {
val item = file.getListItemAtLine(line, document)
if (item == null) {
line++
continue
}
lines.add(line)
line = document.getLineNumber(item.endOffset) + 1
}
return lines
}
/** If this method returns `true`, then the document is committed and [updateNumbering] is called */
protected abstract fun doIndentUnindent(item: MarkdownListItem, file: MarkdownFile, document: Document): Boolean
protected abstract fun updateNumbering(item: MarkdownListItem, file: MarkdownFile, document: Document)
}
| apache-2.0 | 70f39a04fc0e72c01de0fdbb8b08d20c | 45.571429 | 158 | 0.755879 | 4.679426 | false | false | false | false |
dahlstrom-g/intellij-community | platform/platform-impl/src/com/intellij/openapi/options/newEditor/CopySettingsPathAction.kt | 4 | 6112 | // 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.openapi.options.newEditor
import com.google.common.net.UrlEscapers
import com.intellij.CommonBundle
import com.intellij.ide.IdeBundle
import com.intellij.idea.ActionsBundle
import com.intellij.openapi.actionSystem.ActionManager
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.PlatformCoreDataKeys.CONTEXT_COMPONENT
import com.intellij.openapi.ide.CopyPasteManager
import com.intellij.openapi.project.DumbAware
import com.intellij.openapi.util.NlsActions
import com.intellij.openapi.util.SystemInfo.isMac
import com.intellij.ui.ComponentUtil
import com.intellij.ui.tabs.JBTabs
import com.intellij.util.PlatformUtils
import com.intellij.util.ui.TextTransferable
import org.jetbrains.ide.BuiltInServerManager
import java.awt.datatransfer.Transferable
import java.awt.event.ActionEvent
import java.util.*
import java.util.function.Supplier
import javax.swing.*
import javax.swing.border.TitledBorder
private val pathActionName: String
get() = ActionsBundle.message(if (isMac) "action.CopySettingsPath.mac.text" else "action.CopySettingsPath.text")
internal class CopySettingsPathAction : AnAction(pathActionName, ActionsBundle.message("action.CopySettingsPath.description"), null), DumbAware {
init {
isEnabledInModalContext = true
}
companion object {
@JvmStatic
fun createSwingActions(supplier: Supplier<Collection<String>>): List<Action> {
return listOf(
createSwingAction("CopySettingsPath", pathActionName) { copy(supplier.get()) },
// disable until REST API is not able to delegate to proper IDE
//createSwingAction(null, "Copy ${CommonBundle.settingsTitle()} Link") {
// copyLink(supplier, isHttp = true)
//},
createSwingAction(null, IdeBundle.message("action.copy.link.text", CommonBundle.settingsTitle())) {
copyLink(supplier, isHttp = false)
}
)
}
@JvmStatic
fun createTransferable(names: Collection<String>): Transferable? {
if (names.isEmpty()) {
return null
}
val prefix = if (isMac) CommonBundle.message("action.settings.path.mac") else CommonBundle.message("action.settings.path")
val sb = StringBuilder(prefix)
for (name in names) {
sb.append(" | ").append(name)
}
return TextTransferable(sb)
}
}
override fun update(event: AnActionEvent) {
val component = event.getData(CONTEXT_COMPONENT)
val editor = ComponentUtil.getParentOfType(SettingsEditor::class.java, component)
event.presentation.isEnabledAndVisible = editor != null
}
override fun actionPerformed(event: AnActionEvent) {
var component = event.getData(CONTEXT_COMPONENT)
if (component is JTree) {
ComponentUtil.getParentOfType(SettingsTreeView::class.java, component)?.let { settingsTreeView ->
settingsTreeView.createTransferable(event.inputEvent)?.let {
CopyPasteManager.getInstance().setContents(it)
}
return
}
}
val names = ComponentUtil.getParentOfType(SettingsEditor::class.java, component)?.pathNames ?: return
if (names.isEmpty()) {
return
}
val inner = ComponentUtil.getParentOfType(ConfigurableEditor::class.java, component)
if (inner != null) {
val label = getTextLabel(component)
val path = ArrayDeque<String>()
while (component != null && component !== inner) {
if (component is JBTabs) {
component.selectedInfo?.let {
path.addFirst(it.text)
}
}
if (component is JTabbedPane) {
path.addFirst(component.getTitleAt(component.selectedIndex))
}
if (component is JComponent) {
val border = component.border
if (border is TitledBorder) {
val title = border.title
if (!title.isNullOrEmpty()) {
path.addFirst(title)
}
}
}
component = component.parent
}
names.addAll(path)
if (label != null) {
names.add(label)
}
}
copy(names)
}
}
private fun copy(names: Collection<String>): Boolean {
val transferable = CopySettingsPathAction.createTransferable(names)
if (transferable == null) {
return false
}
CopyPasteManager.getInstance().setContents(transferable)
return true
}
private fun getTextLabel(component: Any?): String? {
if (component is JToggleButton) {
val text = component.text
if (!text.isNullOrEmpty()) {
return text
}
}
// find corresponding label
if (component is JLabel) {
val text = component.text
if (!text.isNullOrEmpty()) {
return text
}
}
else if (component is JComponent) {
return getTextLabel(component.getClientProperty("labeledBy"))
}
return null
}
private inline fun createSwingAction(id: String?, @NlsActions.ActionText name: String, crossinline performer: () -> Unit): Action {
val action = object : AbstractAction(name) {
override fun actionPerformed(event: ActionEvent) {
performer()
}
}
if (id != null) {
ActionManager.getInstance().getKeyboardShortcut(id)?.let {
action.putValue(Action.ACCELERATOR_KEY, it.firstKeyStroke)
}
}
return action
}
private fun copyLink(supplier: Supplier<Collection<String>>, isHttp: Boolean) {
val builder = StringBuilder()
if (isHttp) {
builder
.append("http://localhost:")
.append(BuiltInServerManager.getInstance().port)
.append("/api")
}
else {
builder.append("jetbrains://").append(PlatformUtils.getPlatformPrefix())
}
builder.append("/settings?name=")
// -- is used as separator to avoid ugly URL due to percent encoding (| encoded as %7C, but - encoded as is)
supplier.get().joinTo(builder, "--", transform = UrlEscapers.urlFormParameterEscaper()::escape)
CopyPasteManager.getInstance().setContents(TextTransferable(builder))
} | apache-2.0 | c7264a204acc83246ce23c7780f017eb | 31.68984 | 145 | 0.696171 | 4.422576 | false | false | false | false |
dahlstrom-g/intellij-community | plugins/kotlin/base/fe10/obsolete-compat/src/org/jetbrains/kotlin/idea/core/ModuleUtils.kt | 2 | 1384 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.core
import com.intellij.facet.FacetManager
import com.intellij.openapi.externalSystem.service.project.IdeModifiableModelsProvider
import com.intellij.openapi.module.Module
import org.jetbrains.kotlin.analyzer.ModuleInfo
import org.jetbrains.kotlin.idea.base.projectStructure.moduleInfo.ModuleSourceInfo
import org.jetbrains.kotlin.idea.base.projectStructure.moduleInfo.PlatformModuleInfo
@Deprecated("Use 'org.jetbrains.kotlin.idea.base.util.isAndroidModule' instead")
fun Module.isAndroidModule(modelsProvider: IdeModifiableModelsProvider? = null): Boolean {
val facetModel = modelsProvider?.getModifiableFacetModel(this) ?: FacetManager.getInstance(this)
val facets = facetModel.allFacets
return facets.any { it.javaClass.simpleName == "AndroidFacet" }
}
@Deprecated("Use 'org.jetbrains.kotlin.idea.base.projectStructure.unwrapModuleSourceInfo()' instead")
@Suppress("unused", "DEPRECATION", "DeprecatedCallableAddReplaceWith")
fun ModuleInfo.unwrapModuleSourceInfo(): org.jetbrains.kotlin.idea.caches.project.ModuleSourceInfo? {
return when (this) {
is ModuleSourceInfo -> this
is PlatformModuleInfo -> this.platformModule
else -> null
}
} | apache-2.0 | 037595300dc0fffe78fe28efcd480244 | 50.296296 | 158 | 0.797688 | 4.628763 | false | false | false | false |
dahlstrom-g/intellij-community | plugins/settings-sync/src/com/intellij/settingsSync/SettingsSyncEvents.kt | 5 | 1425 | package com.intellij.settingsSync
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.ApplicationManager
import com.intellij.util.EventDispatcher
internal class SettingsSyncEvents : Disposable {
private val settingsChangeDispatcher = EventDispatcher.create(SettingsChangeListener::class.java)
private val enabledStateChangeDispatcher = EventDispatcher.create(SettingsSyncEnabledStateListener::class.java)
fun addSettingsChangedListener(settingsChangeListener: SettingsChangeListener) {
settingsChangeDispatcher.addListener(settingsChangeListener)
}
fun fireSettingsChanged(event: SyncSettingsEvent) {
settingsChangeDispatcher.multicaster.settingChanged(event)
}
fun addEnabledStateChangeListener(listener: SettingsSyncEnabledStateListener, parentDisposable: Disposable? = null) {
if (parentDisposable != null) enabledStateChangeDispatcher.addListener(listener, parentDisposable)
else enabledStateChangeDispatcher.addListener(listener, this)
}
fun fireEnabledStateChanged(syncEnabled: Boolean) {
enabledStateChangeDispatcher.multicaster.enabledStateChanged(syncEnabled)
}
companion object {
fun getInstance(): SettingsSyncEvents = ApplicationManager.getApplication().getService(SettingsSyncEvents::class.java)
}
override fun dispose() {
settingsChangeDispatcher.listeners.clear()
enabledStateChangeDispatcher.listeners.clear()
}
} | apache-2.0 | faacf5ace3c71fcd17a020cb053ab5b9 | 37.540541 | 122 | 0.825965 | 5.523256 | false | false | false | false |
dahlstrom-g/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/actions/internal/FindImplicitNothingAction.kt | 2 | 7105 | // 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.actions.internal
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.progress.ProcessCanceledException
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.Messages
import com.intellij.openapi.vfs.VfsUtilCore
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.vfs.VirtualFileVisitor
import com.intellij.psi.PsiManager
import com.intellij.usageView.UsageInfo
import com.intellij.usages.UsageInfo2UsageAdapter
import com.intellij.usages.UsageTarget
import com.intellij.usages.UsageViewManager
import com.intellij.usages.UsageViewPresentation
import org.jetbrains.kotlin.builtins.KotlinBuiltIns
import org.jetbrains.kotlin.builtins.getReturnTypeFromFunctionType
import org.jetbrains.kotlin.builtins.isFunctionType
import org.jetbrains.kotlin.descriptors.CallableDescriptor
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.getResolutionFacade
import org.jetbrains.kotlin.idea.util.application.isApplicationInternalMode
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.DescriptorToSourceUtils
import org.jetbrains.kotlin.resolve.calls.util.getCalleeExpressionIfAny
import org.jetbrains.kotlin.types.KotlinType
import javax.swing.SwingUtilities
class FindImplicitNothingAction : AnAction() {
companion object {
private val LOG = Logger.getInstance("#org.jetbrains.kotlin.idea.actions.internal.FindImplicitNothingAction")
}
override fun actionPerformed(e: AnActionEvent) {
val selectedFiles = selectedKotlinFiles(e).toList()
val project = CommonDataKeys.PROJECT.getData(e.dataContext)!!
ProgressManager.getInstance().runProcessWithProgressSynchronously(
{ find(selectedFiles, project) },
KotlinBundle.message("progress.finding.implicit.nothing.s"),
true,
project
)
}
private fun find(files: Collection<KtFile>, project: Project) {
val progressIndicator = ProgressManager.getInstance().progressIndicator
val found = ArrayList<KtCallExpression>()
for ((i, file) in files.withIndex()) {
progressIndicator?.text = KotlinBundle.message("scanning.files.0.fo.1.file.2.occurrences.found", i, files.size, found.size)
progressIndicator?.text2 = file.virtualFile.path
val resolutionFacade = file.getResolutionFacade()
file.acceptChildren(object : KtVisitorVoid() {
override fun visitKtElement(element: KtElement) {
ProgressManager.checkCanceled()
element.acceptChildren(this)
}
override fun visitCallExpression(expression: KtCallExpression) {
expression.acceptChildren(this)
try {
val bindingContext = resolutionFacade.analyze(expression)
val type = bindingContext.getType(expression) ?: return
if (KotlinBuiltIns.isNothing(type) && !expression.hasExplicitNothing(bindingContext)) { //TODO: what about nullable Nothing?
found.add(expression)
}
} catch (e: ProcessCanceledException) {
throw e
} catch (t: Throwable) { // do not stop on internal error
LOG.error(t)
}
}
})
progressIndicator?.fraction = (i + 1) / files.size.toDouble()
}
SwingUtilities.invokeLater {
if (found.isNotEmpty()) {
val usages = found.map { UsageInfo2UsageAdapter(UsageInfo(it)) }.toTypedArray()
val presentation = UsageViewPresentation()
presentation.tabName = KotlinBundle.message("implicit.nothing.s")
UsageViewManager.getInstance(project).showUsages(arrayOf<UsageTarget>(), usages, presentation)
} else {
Messages.showInfoMessage(
project,
KotlinBundle.message("not.found.in.0.files", files.size),
KotlinBundle.message("titile.not.found")
)
}
}
}
private fun KtExpression.hasExplicitNothing(bindingContext: BindingContext): Boolean {
val callee = getCalleeExpressionIfAny() ?: return false
when (callee) {
is KtSimpleNameExpression -> {
val target = bindingContext[BindingContext.REFERENCE_TARGET, callee] ?: return false
val callableDescriptor = (target as? CallableDescriptor ?: return false).original
val declaration = DescriptorToSourceUtils.descriptorToDeclaration(callableDescriptor) as? KtCallableDeclaration
if (declaration != null && declaration.typeReference == null) return false // implicit type
val type = callableDescriptor.returnType ?: return false
return type.isNothingOrNothingFunctionType()
}
else -> {
return callee.hasExplicitNothing(bindingContext)
}
}
}
private fun KotlinType.isNothingOrNothingFunctionType(): Boolean {
return KotlinBuiltIns.isNothing(this) ||
(isFunctionType && this.getReturnTypeFromFunctionType().isNothingOrNothingFunctionType())
}
override fun update(e: AnActionEvent) {
val internalMode = isApplicationInternalMode()
e.presentation.isVisible = internalMode
e.presentation.isEnabled = internalMode
}
private fun selectedKotlinFiles(e: AnActionEvent): Sequence<KtFile> {
val virtualFiles = e.getData(CommonDataKeys.VIRTUAL_FILE_ARRAY) ?: return sequenceOf()
val project = CommonDataKeys.PROJECT.getData(e.dataContext) ?: return sequenceOf()
return allKotlinFiles(virtualFiles, project)
}
private fun allKotlinFiles(filesOrDirs: Array<VirtualFile>, project: Project): Sequence<KtFile> {
val manager = PsiManager.getInstance(project)
return allFiles(filesOrDirs)
.asSequence()
.mapNotNull { manager.findFile(it) as? KtFile }
}
private fun allFiles(filesOrDirs: Array<VirtualFile>): Collection<VirtualFile> {
val result = ArrayList<VirtualFile>()
for (file in filesOrDirs) {
VfsUtilCore.visitChildrenRecursively(file, object : VirtualFileVisitor<Unit>() {
override fun visitFile(file: VirtualFile): Boolean {
result.add(file)
return true
}
})
}
return result
}
}
| apache-2.0 | e331dae50820470630316539d6bbe014 | 44.254777 | 148 | 0.670514 | 5.419527 | false | false | false | false |
dkandalov/katas | kotlin/src/katas/kotlin/skiena/graphs/BFS.kt | 1 | 4504 | package katas.kotlin.skiena.graphs
import katas.kotlin.skiena.graphs.UnweightedGraphs.diamondGraph
import katas.kotlin.skiena.graphs.UnweightedGraphs.disconnectedGraph
import katas.kotlin.skiena.graphs.UnweightedGraphs.linearGraph
import katas.kotlin.skiena.graphs.UnweightedGraphs.meshGraph
import datsok.shouldEqual
import org.junit.Test
import java.util.*
import kotlin.collections.ArrayList
import kotlin.collections.HashMap
import kotlin.collections.HashSet
import kotlin.collections.LinkedHashSet
data class SearchResult<T>(
val prevVertex: Map<T, T>,
val vertices: LinkedHashSet<T>
)
// This implementation which roughly copies the one from the book
// is bloated with unnecessary complexity so I'll try to avoid it.
fun <T> Graph<T>.bfs_skiena(
fromVertex: T,
processVertexEarly: (T) -> Unit = {},
processVertexLate: (T) -> Unit = {},
processEdge: (Edge<T>) -> Unit = {}
): SearchResult<T> {
if (!vertices.contains(fromVertex)) error("Graph doesn't contain vertex '$fromVertex'")
val prevVertex = HashMap<T, T>()
val processed = LinkedHashSet<T>()
val discovered = LinkedHashSet<T>()
val queue = LinkedList<T>()
queue.add(fromVertex)
discovered.add(fromVertex)
while (queue.isNotEmpty()) {
val vertex = queue.removeFirst()
processVertexEarly(vertex)
processed.add(vertex)
(edgesByVertex[vertex] ?: emptyList<Edge<T>>())
.forEach { edge ->
if (!processed.contains(edge.to)) processEdge(edge)
if (!discovered.contains(edge.to)) {
queue.add(edge.to)
discovered.add(edge.to)
prevVertex[edge.to] = vertex
}
}
processVertexLate(vertex)
}
return SearchResult(prevVertex, processed)
}
fun <T> Graph<T>.bfs(fromVertex: T = vertices.first()): List<T> {
val result = ArrayList<T>()
val wasQueued = HashSet<T>().apply { add(fromVertex) }
val queue = LinkedList<T>().apply { add(fromVertex) }
while (queue.isNotEmpty()) {
val vertex = queue.removeFirst()
result.add(vertex)
edgesByVertex[vertex]?.map { it.to }
?.forEach {
val justAdded = wasQueued.add(it)
if (justAdded) queue.add(it)
}
}
return result
}
fun <T> Graph<T>.bfsEdges(fromVertex: T = vertices.first()): List<Edge<T>> {
val result = ArrayList<Edge<T>>()
val visited = HashSet<T>()
val queue = LinkedList<T>().apply { add(fromVertex) }
while (queue.isNotEmpty()) {
val vertex = queue.removeFirst()
visited.add(vertex)
edgesByVertex[vertex]?.forEach { edge ->
if (edge.to !in visited) {
result.add(edge)
if (edge.to !in queue) queue.add(edge.to)
}
}
}
return result
}
class BFSTests {
@Test fun `breadth-first search Skiena`() {
val earlyVertices = ArrayList<Int>()
val lateVertices = ArrayList<Int>()
val edges = ArrayList<Edge<Int>>()
val searchResult = diamondGraph.bfs_skiena(
fromVertex = 1,
processVertexEarly = { earlyVertices.add(it) },
processVertexLate = { lateVertices.add(it) },
processEdge = { edges.add(it) }
)
searchResult.vertices.toList() shouldEqual listOf(1, 2, 4, 3)
earlyVertices shouldEqual listOf(1, 2, 4, 3)
lateVertices shouldEqual listOf(1, 2, 4, 3)
edges shouldEqual listOf(Edge(1, 2), Edge(1, 4), Edge(2, 3), Edge(4, 3))
}
@Test fun `breadth-first vertex traversal`() {
linearGraph.bfs(fromVertex = 1) shouldEqual listOf(1, 2, 3)
disconnectedGraph.bfs(fromVertex = 1) shouldEqual listOf(1, 2)
diamondGraph.bfs(fromVertex = 1) shouldEqual listOf(1, 2, 4, 3)
meshGraph.bfs(fromVertex = 1) shouldEqual listOf(1, 2, 3, 4)
}
@Test fun `breadth-first edge traversal`() {
linearGraph.bfsEdges(fromVertex = 1) shouldEqual listOf(
Edge(1, 2), Edge(2, 3)
)
disconnectedGraph.bfsEdges(fromVertex = 1) shouldEqual listOf(
Edge(1, 2)
)
diamondGraph.bfsEdges(fromVertex = 1) shouldEqual listOf(
Edge(1, 2), Edge(1, 4), Edge(2, 3), Edge(4, 3)
)
meshGraph.bfsEdges(fromVertex = 1) shouldEqual listOf(
Edge(1, 2), Edge(1, 3), Edge(1, 4), Edge(2, 3), Edge(2, 4), Edge(3, 4)
)
}
} | unlicense | e0ebf6db70255e54391d3b6c8bbcadef | 32.37037 | 91 | 0.611901 | 3.859469 | false | false | false | false |
tateisu/SubwayTooter | app/src/main/java/jp/juggler/subwaytooter/action/Action_User.kt | 1 | 34218 | package jp.juggler.subwaytooter.action
import android.annotation.SuppressLint
import android.app.AlertDialog
import android.view.Gravity
import android.view.View
import android.widget.*
import androidx.appcompat.widget.AppCompatButton
import jp.juggler.subwaytooter.*
import jp.juggler.subwaytooter.actmain.addColumn
import jp.juggler.subwaytooter.api.*
import jp.juggler.subwaytooter.api.entity.*
import jp.juggler.subwaytooter.column.*
import jp.juggler.subwaytooter.dialog.ReportForm
import jp.juggler.subwaytooter.dialog.pickAccount
import jp.juggler.subwaytooter.table.AcctColor
import jp.juggler.subwaytooter.table.FavMute
import jp.juggler.subwaytooter.table.SavedAccount
import jp.juggler.subwaytooter.table.UserRelation
import jp.juggler.subwaytooter.util.matchHost
import jp.juggler.subwaytooter.util.openCustomTab
import jp.juggler.util.*
import kotlinx.coroutines.*
import okhttp3.Request
import java.util.*
// private val log = LogCategory("Action_User")
fun ActMain.clickMute(
accessInfo: SavedAccount,
who: TootAccount,
relation: UserRelation,
) = when {
relation.muting -> userUnmute(accessInfo, who, accessInfo)
else -> userMuteConfirm(accessInfo, who, accessInfo)
}
fun ActMain.clickBlock(
accessInfo: SavedAccount,
who: TootAccount,
relation: UserRelation,
) = when {
relation.blocking -> userBlock(accessInfo, who, accessInfo, false)
else -> userBlockConfirm(accessInfo, who, accessInfo)
}
fun ActMain.clickNicknameCustomize(
accessInfo: SavedAccount,
who: TootAccount,
) = arNickname.launch(ActNickname.createIntent(this, accessInfo.getFullAcct(who), true))
fun ActMain.openAvatarImage(who: TootAccount) {
openCustomTab(
when {
who.avatar.isNullOrEmpty() -> who.avatar_static
else -> who.avatar
}
)
}
fun ActMain.clickHideFavourite(
accessInfo: SavedAccount,
who: TootAccount,
) {
val acct = accessInfo.getFullAcct(who)
FavMute.save(acct)
showToast(false, R.string.changed)
for (column in appState.columnList) {
column.onHideFavouriteNotification(acct)
}
}
fun ActMain.clickShowFavourite(
accessInfo: SavedAccount,
who: TootAccount,
) {
FavMute.delete(accessInfo.getFullAcct(who))
showToast(false, R.string.changed)
}
fun ActMain.clickStatusNotification(
accessInfo: SavedAccount,
who: TootAccount,
relation: UserRelation,
) {
if (!accessInfo.isPseudo &&
accessInfo.isMastodon &&
relation.following
) {
userSetStatusNotification(accessInfo, who.id, enabled = !relation.notifying)
}
}
// ユーザをミュート/ミュート解除する
private fun ActMain.userMute(
accessInfo: SavedAccount,
whoArg: TootAccount,
whoAccessInfo: SavedAccount,
bMute: Boolean,
bMuteNotification: Boolean,
duration: Int?,
) {
val whoAcct = whoAccessInfo.getFullAcct(whoArg)
if (accessInfo.isMe(whoAcct)) {
showToast(false, R.string.it_is_you)
return
}
launchMain {
var resultRelation: UserRelation? = null
var resultWhoId: EntityId? = null
runApiTask(accessInfo) { client ->
val parser = TootParser(this, accessInfo)
if (accessInfo.isPseudo) {
if (!whoAcct.isValidFull) {
TootApiResult("can't mute pseudo acct ${whoAcct.pretty}")
} else {
val relation = UserRelation.loadPseudo(whoAcct)
relation.muting = bMute
relation.savePseudo(whoAcct.ascii)
resultRelation = relation
resultWhoId = whoArg.id
TootApiResult()
}
} else {
val whoId = if (accessInfo.matchHost(whoAccessInfo)) {
whoArg.id
} else {
val (result, accountRef) = client.syncAccountByAcct(accessInfo, whoAcct)
accountRef?.get()?.id ?: return@runApiTask result
}
resultWhoId = whoId
if (accessInfo.isMisskey) {
client.request(
when (bMute) {
true -> "/api/mute/create"
else -> "/api/mute/delete"
},
accessInfo.putMisskeyApiToken().apply {
put("userId", whoId.toString())
}.toPostRequestBuilder()
)?.apply {
if (jsonObject != null) {
// 204 no content
// update user relation
val ur = UserRelation.load(accessInfo.db_id, whoId)
ur.muting = bMute
accessInfo.saveUserRelationMisskey(
whoId,
parser
)
resultRelation = ur
}
}
} else {
client.request(
"/api/v1/accounts/$whoId/${if (bMute) "mute" else "unmute"}",
when {
!bMute -> "".toFormRequestBody()
else ->
jsonObject {
put("notifications", bMuteNotification)
if (duration != null) put("duration", duration)
}
.toRequestBody()
}.toPost()
)?.apply {
val jsonObject = jsonObject
if (jsonObject != null) {
resultRelation = accessInfo.saveUserRelation(
parseItem(::TootRelationShip, parser, jsonObject)
)
}
}
}
}
}?.let { result ->
val relation = resultRelation
val whoId = resultWhoId
if (relation == null || whoId == null) {
showToast(false, result.error)
} else {
// 未確認だが、自分をミュートしようとするとリクエストは成功するがレスポンス中のmutingはfalseになるはず
if (bMute && !relation.muting) {
showToast(false, R.string.not_muted)
return@launchMain
}
for (column in appState.columnList) {
if (column.accessInfo.isPseudo) {
if (relation.muting && column.type != ColumnType.PROFILE) {
// ミュートしたユーザの情報はTLから消える
column.removeAccountInTimelinePseudo(whoAcct)
}
// フォローアイコンの表示更新が走る
column.updateFollowIcons(accessInfo)
} else if (column.accessInfo == accessInfo) {
when {
!relation.muting -> {
if (column.type == ColumnType.MUTES) {
// ミュート解除したら「ミュートしたユーザ」カラムから消える
column.removeUser(accessInfo, ColumnType.MUTES, whoId)
} else {
// 他のカラムではフォローアイコンの表示更新が走る
column.updateFollowIcons(accessInfo)
}
}
column.type == ColumnType.PROFILE && column.profileId == whoId -> {
// 該当ユーザのプロフページのトゥートはミュートしてても見れる
// しかしフォローアイコンの表示更新は必要
column.updateFollowIcons(accessInfo)
}
else -> {
// ミュートしたユーザの情報はTLから消える
column.removeAccountInTimeline(accessInfo, whoId)
}
}
}
}
showToast(
false,
if (relation.muting) R.string.mute_succeeded else R.string.unmute_succeeded
)
}
}
}
}
fun ActMain.userUnmute(
accessInfo: SavedAccount,
whoArg: TootAccount,
whoAccessInfo: SavedAccount,
) = userMute(
accessInfo,
whoArg,
whoAccessInfo,
bMute = false,
bMuteNotification = false,
duration = null,
)
fun ActMain.userMuteConfirm(
accessInfo: SavedAccount,
who: TootAccount,
whoAccessInfo: SavedAccount,
) {
val activity = this@userMuteConfirm
// Mastodon 3.3から時限ミュート設定ができる
val choiceList = arrayOf(
Pair(0, getString(R.string.duration_indefinite)),
Pair(300, getString(R.string.duration_minutes_5)),
Pair(1800, getString(R.string.duration_minutes_30)),
Pair(3600, getString(R.string.duration_hours_1)),
Pair(21600, getString(R.string.duration_hours_6)),
Pair(86400, getString(R.string.duration_days_1)),
Pair(259200, getString(R.string.duration_days_3)),
Pair(604800, getString(R.string.duration_days_7)),
)
@SuppressLint("InflateParams")
val view = layoutInflater.inflate(R.layout.dlg_confirm, null, false)
val tvMessage = view.findViewById<TextView>(R.id.tvMessage)
tvMessage.text = getString(R.string.confirm_mute_user, who.username)
tvMessage.text = getString(R.string.confirm_mute_user, who.username)
// 「次回以降スキップ」のチェックボックスは「このユーザからの通知もミュート」に再利用する
// このオプションはMisskeyや疑似アカウントにはない
val cbMuteNotification = view.findViewById<CheckBox>(R.id.cbSkipNext)
val hasMuteNotification = !accessInfo.isMisskey && !accessInfo.isPseudo
cbMuteNotification.isChecked = hasMuteNotification
cbMuteNotification.vg(hasMuteNotification)
?.setText(R.string.confirm_mute_notification_for_user)
launchMain {
val spMuteDuration: Spinner = view.findViewById(R.id.spMuteDuration)
val hasMuteDuration = try {
when {
accessInfo.isMisskey || accessInfo.isPseudo -> false
else -> {
var resultBoolean = false
runApiTask(accessInfo) { client ->
val (ti, ri) = TootInstance.get(client)
resultBoolean = ti?.versionGE(TootInstance.VERSION_3_3_0_rc1) == true
ri
}
resultBoolean
}
}
} catch (ignored: CancellationException) {
// not show error
return@launchMain
} catch (ex: RuntimeException) {
showToast(true, ex.message)
return@launchMain
}
if (hasMuteDuration) {
view.findViewById<View>(R.id.llMuteDuration).vg(true)
spMuteDuration.apply {
adapter = ArrayAdapter(
activity,
android.R.layout.simple_spinner_item,
choiceList.map { it.second }.toTypedArray(),
).apply {
setDropDownViewResource(R.layout.lv_spinner_dropdown)
}
}
}
AlertDialog.Builder(activity)
.setView(view)
.setNegativeButton(R.string.cancel, null)
.setPositiveButton(R.string.ok) { _, _ ->
userMute(
accessInfo,
who,
whoAccessInfo,
bMute = true,
bMuteNotification = cbMuteNotification.isChecked,
duration = spMuteDuration.selectedItemPosition
.takeIf { hasMuteDuration && it in choiceList.indices }
?.let { choiceList[it].first }
)
}
.show()
}
}
fun ActMain.userMuteFromAnotherAccount(
who: TootAccount?,
whoAccessInfo: SavedAccount,
) {
who ?: return
launchMain {
pickAccount(
bAllowPseudo = false,
bAuto = false,
message = getString(R.string.account_picker_mute, who.acct.pretty),
accountListArg = accountListNonPseudo(who.apDomain)
)?.let {
userMuteConfirm(it, who, whoAccessInfo)
}
}
}
// ユーザをブロック/ブロック解除する
fun ActMain.userBlock(
accessInfo: SavedAccount,
whoArg: TootAccount,
whoAccessInfo: SavedAccount,
bBlock: Boolean,
) {
val whoAcct = whoArg.acct
if (accessInfo.isMe(whoAcct)) {
showToast(false, R.string.it_is_you)
return
}
launchMain {
var relationResult: UserRelation? = null
var whoIdResult: EntityId? = null
runApiTask(accessInfo) { client ->
if (accessInfo.isPseudo) {
if (whoAcct.ascii.contains('?')) {
TootApiResult("can't block pseudo account ${whoAcct.pretty}")
} else {
val relation = UserRelation.loadPseudo(whoAcct)
relation.blocking = bBlock
relation.savePseudo(whoAcct.ascii)
relationResult = relation
TootApiResult()
}
} else {
val whoId = if (accessInfo.matchHost(whoAccessInfo)) {
whoArg.id
} else {
val (result, accountRef) = client.syncAccountByAcct(accessInfo, whoAcct)
accountRef?.get()?.id ?: return@runApiTask result
}
whoIdResult = whoId
if (accessInfo.isMisskey) {
fun saveBlock(v: Boolean) {
val ur = UserRelation.load(accessInfo.db_id, whoId)
ur.blocking = v
UserRelation.save1Misskey(
System.currentTimeMillis(),
accessInfo.db_id,
whoId.toString(),
ur
)
relationResult = ur
}
client.request(
"/api/blocking/${if (bBlock) "create" else "delete"}",
accessInfo.putMisskeyApiToken().apply {
put("userId", whoId.toString())
}.toPostRequestBuilder()
)?.apply {
val error = this.error
when {
// success
error == null -> saveBlock(bBlock)
// already
error.contains("already blocking") -> saveBlock(bBlock)
error.contains("already not blocking") -> saveBlock(bBlock)
// else something error
}
}
} else {
client.request(
"/api/v1/accounts/$whoId/${if (bBlock) "block" else "unblock"}",
"".toFormRequestBody().toPost()
)?.also { result ->
val parser = TootParser(this, accessInfo)
relationResult = accessInfo.saveUserRelation(
parseItem(::TootRelationShip, parser, result.jsonObject)
)
}
}
}
}?.let { result ->
val relation = relationResult
val whoId = whoIdResult
when {
relation == null || whoId == null ->
showToast(false, result.error)
else -> {
// 自分をブロックしようとすると、blocking==falseで帰ってくる
if (bBlock && !relation.blocking) {
showToast(false, R.string.not_blocked)
return@launchMain
}
for (column in appState.columnList) {
if (column.accessInfo.isPseudo) {
if (relation.blocking) {
// ミュートしたユーザの情報はTLから消える
column.removeAccountInTimelinePseudo(whoAcct)
}
// フォローアイコンの表示更新が走る
column.updateFollowIcons(accessInfo)
} else if (column.accessInfo == accessInfo) {
when {
!relation.blocking -> {
if (column.type == ColumnType.BLOCKS) {
// ブロック解除したら「ブロックしたユーザ」カラムのリストから消える
column.removeUser(accessInfo, ColumnType.BLOCKS, whoId)
} else {
// 他のカラムではフォローアイコンの更新を行う
column.updateFollowIcons(accessInfo)
}
}
accessInfo.isMisskey -> {
// Misskeyのブロックはフォロー解除とフォロー拒否だけなので
// カラム中の投稿を消すなどの効果はない
// しかしカラム中のフォローアイコン表示の更新は必要
column.updateFollowIcons(accessInfo)
}
// 該当ユーザのプロフカラムではブロックしててもトゥートを見れる
// しかしカラム中のフォローアイコン表示の更新は必要
column.type == ColumnType.PROFILE && whoId == column.profileId -> {
column.updateFollowIcons(accessInfo)
}
// MastodonではブロックしたらTLからそのアカウントの投稿が消える
else -> column.removeAccountInTimeline(accessInfo, whoId)
}
}
}
showToast(
false,
when {
relation.blocking -> R.string.block_succeeded
else -> R.string.unblock_succeeded
}
)
}
}
}
}
}
fun ActMain.userBlockConfirm(
accessInfo: SavedAccount,
who: TootAccount,
whoAccessInfo: SavedAccount,
) {
AlertDialog.Builder(this)
.setMessage(getString(R.string.confirm_block_user, who.username))
.setNegativeButton(R.string.cancel, null)
.setPositiveButton(R.string.ok) { _, _ ->
userBlock(
accessInfo,
who,
whoAccessInfo,
bBlock = true
)
}
.show()
}
fun ActMain.userBlockFromAnotherAccount(
who: TootAccount?,
whoAccessInfo: SavedAccount,
) {
who ?: return
launchMain {
pickAccount(
bAllowPseudo = false,
bAuto = false,
message = getString(R.string.account_picker_block, who.acct.pretty),
accountListArg = accountListNonPseudo(who.apDomain)
)?.let { ai ->
userBlockConfirm(ai, who, whoAccessInfo)
}
}
}
//////////////////////////////////////////////////////////////////////////////////////
// ユーザURLを同期してプロフカラムを開く
private fun ActMain.userProfileFromUrlOrAcct(
pos: Int,
accessInfo: SavedAccount,
acct: Acct,
whoUrl: String,
) {
launchMain {
var resultWho: TootAccount? = null
runApiTask(accessInfo) { client ->
val (result, ar) = client.syncAccountByUrl(accessInfo, whoUrl)
if (result == null) {
null
} else {
resultWho = ar?.get()
if (resultWho != null) {
result
} else {
val (r2, ar2) = client.syncAccountByAcct(accessInfo, acct)
resultWho = ar2?.get()
r2
}
}
}?.let { result ->
when (val who = resultWho) {
null -> {
showToast(true, result.error)
// 仕方ないのでchrome tab で開く
openCustomTab(whoUrl)
}
else -> addColumn(pos, accessInfo, ColumnType.PROFILE, who.id)
}
}
}
}
// アカウントを選んでユーザプロフを開く
fun ActMain.userProfileFromAnotherAccount(
pos: Int,
accessInfo: SavedAccount,
who: TootAccount?,
) {
who?.url ?: return
launchMain {
pickAccount(
bAllowPseudo = false,
bAuto = false,
message = getString(
R.string.account_picker_open_user_who,
AcctColor.getNickname(accessInfo, who)
),
accountListArg = accountListNonPseudo(who.apDomain)
)?.let { ai ->
if (ai.matchHost(accessInfo)) {
addColumn(pos, ai, ColumnType.PROFILE, who.id)
} else {
userProfileFromUrlOrAcct(pos, ai, accessInfo.getFullAcct(who), who.url)
}
}
}
}
// 今のアカウントでユーザプロフを開く
fun ActMain.userProfileLocal(
pos: Int,
accessInfo: SavedAccount,
who: TootAccount,
) {
when {
accessInfo.isNA -> userProfileFromAnotherAccount(pos, accessInfo, who)
else -> addColumn(pos, accessInfo, ColumnType.PROFILE, who.id)
}
}
// user@host で指定されたユーザのプロフを開く
// Intent-Filter や openChromeTabから 呼ばれる
fun ActMain.userProfile(
pos: Int,
accessInfo: SavedAccount?,
acct: Acct,
userUrl: String,
originalUrl: String = userUrl,
) {
if (accessInfo?.isPseudo == false) {
// 文脈のアカウントがあり、疑似アカウントではない
if (!accessInfo.matchHost(acct.host)) {
// 文脈のアカウントと異なるインスタンスなら、別アカウントで開く
userProfileFromUrlOrAcct(pos, accessInfo, acct, userUrl)
} else {
// 文脈のアカウントと同じインスタンスなら、アカウントIDを探して開いてしまう
launchMain {
var resultWho: TootAccount? = null
runApiTask(accessInfo) { client ->
val (result, ar) = client.syncAccountByAcct(accessInfo, acct)
resultWho = ar?.get()
result
}?.let {
when (val who = resultWho) {
// ダメならchromeで開く
null -> openCustomTab(userUrl)
// 変換できたアカウント情報で開く
else -> userProfileLocal(pos, accessInfo, who)
}
}
}
}
return
}
// 文脈がない、もしくは疑似アカウントだった
// 疑似アカウントでは検索APIを使えないため、IDが分からない
if (!SavedAccount.hasRealAccount()) {
// 疑似アカウントしか登録されていない
// chrome tab で開く
openCustomTab(originalUrl)
return
}
launchMain {
val activity = this@userProfile
pickAccount(
bAllowPseudo = false,
bAuto = false,
message = getString(
R.string.account_picker_open_user_who,
AcctColor.getNickname(acct)
),
accountListArg = accountListNonPseudo(acct.host),
extraCallback = { ll, pad_se, pad_tb ->
// chrome tab で開くアクションを追加
val lp = LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT
)
val b = AppCompatButton(activity)
b.setPaddingRelative(pad_se, pad_tb, pad_se, pad_tb)
b.gravity = Gravity.START or Gravity.CENTER_VERTICAL
b.isAllCaps = false
b.layoutParams = lp
b.minHeight = (0.5f + 32f * activity.density).toInt()
b.text = getString(R.string.open_in_browser)
b.setBackgroundResource(R.drawable.btn_bg_transparent_round6dp)
b.setOnClickListener {
openCustomTab(originalUrl)
}
ll.addView(b, 0)
}
)?.let {
userProfileFromUrlOrAcct(pos, it, acct, userUrl)
}
}
}
//////////////////////////////////////////////////////////////////////////////////////
// 通報フォームを開く
fun ActMain.userReportForm(
accessInfo: SavedAccount,
who: TootAccount,
status: TootStatus? = null,
) {
ReportForm.showReportForm(this, accessInfo, who, status) { dialog, comment, forward ->
userReport(accessInfo, who, status, comment, forward) {
dialog.dismissSafe()
}
}
}
// 通報する
private fun ActMain.userReport(
accessInfo: SavedAccount,
who: TootAccount,
status: TootStatus?,
comment: String,
forward: Boolean,
onReportComplete: (result: TootApiResult) -> Unit,
) {
if (accessInfo.isMe(who)) {
showToast(false, R.string.it_is_you)
return
}
launchMain {
runApiTask(accessInfo) { client ->
if (accessInfo.isMisskey) {
client.request(
"/api/users/report-abuse",
accessInfo.putMisskeyApiToken().apply {
put("userId", who.id.toString())
put(
"comment",
StringBuilder().apply {
status?.let {
append(it.url)
append("\n")
}
append(comment)
}.toString()
)
}.toPostRequestBuilder()
)
} else {
client.request(
"/api/v1/reports",
JsonObject().apply {
put("account_id", who.id.toString())
put("comment", comment)
put("forward", forward)
if (status != null) {
put("status_ids", jsonArray {
add(status.id.toString())
})
}
}.toPostRequestBuilder()
)
}
}?.let { result ->
when (result.jsonObject) {
null -> showToast(true, result.error)
else -> {
onReportComplete(result)
showToast(false, R.string.report_completed)
}
}
}
}
}
// show/hide boosts from (following) user
fun ActMain.userSetShowBoosts(
accessInfo: SavedAccount,
who: TootAccount,
bShow: Boolean,
) {
if (accessInfo.isMe(who)) {
showToast(false, R.string.it_is_you)
return
}
launchMain {
var resultRelation: UserRelation? = null
runApiTask(accessInfo) { client ->
client.request(
"/api/v1/accounts/${who.id}/follow",
jsonObjectOf("reblogs" to bShow).toPostRequestBuilder()
)?.also { result ->
val parser = TootParser(this, accessInfo)
resultRelation = accessInfo.saveUserRelation(
parseItem(
::TootRelationShip,
parser,
result.jsonObject
)
)
}
}?.let { result ->
when (resultRelation) {
null -> showToast(true, result.error)
else -> showToast(true, R.string.operation_succeeded)
}
}
}
}
fun ActMain.userSuggestionDelete(
accessInfo: SavedAccount,
who: TootAccount,
bConfirmed: Boolean = false,
) {
if (!bConfirmed) {
val name = who.decodeDisplayName(applicationContext)
AlertDialog.Builder(this)
.setMessage(
name.intoStringResource(
applicationContext,
R.string.delete_succeeded_confirm
)
)
.setNegativeButton(R.string.cancel, null)
.setPositiveButton(R.string.ok) { _, _ ->
userSuggestionDelete(accessInfo, who, bConfirmed = true)
}
.show()
return
}
launchMain {
runApiTask(accessInfo) { client ->
client.request("/api/v1/suggestions/${who.id}", Request.Builder().delete())
}?.let { result ->
when (result.error) {
null -> {
showToast(false, R.string.delete_succeeded)
// update suggestion column
for (column in appState.columnList) {
column.removeUser(accessInfo, ColumnType.FOLLOW_SUGGESTION, who.id)
}
}
else -> showToast(true, result.error)
}
}
}
}
fun ActMain.userSetStatusNotification(
accessInfo: SavedAccount,
whoId: EntityId,
enabled: Boolean,
) {
launchMain {
runApiTask(accessInfo) { client ->
client.request(
"/api/v1/accounts/$whoId/follow",
jsonObject {
put("notify", enabled)
}.toPostRequestBuilder()
)?.also { result ->
val relation = parseItem(
::TootRelationShip,
TootParser(this, accessInfo),
result.jsonObject
)
if (relation != null) {
UserRelation.save1Mastodon(
System.currentTimeMillis(),
accessInfo.db_id,
relation
)
}
}
}?.let { result ->
when (val error = result.error) {
null -> showToast(false, R.string.operation_succeeded)
else -> showToast(true, error)
}
}
}
}
fun ActMain.userEndorsement(
accessInfo: SavedAccount,
who: TootAccount,
bSet: Boolean,
) {
if (accessInfo.isMisskey) {
showToast(false, "This feature is not provided on Misskey account.")
return
}
launchMain {
@Suppress("ASSIGNED_BUT_NEVER_ACCESSED_VARIABLE")
var resultRelation: UserRelation? = null
runApiTask(accessInfo) { client ->
client.request(
"/api/v1/accounts/${who.id}/" + when (bSet) {
true -> "pin"
false -> "unpin"
},
"".toFormRequestBody().toPost()
)
?.also { result ->
val parser = TootParser(this, accessInfo)
resultRelation = accessInfo.saveUserRelation(
parseItem(::TootRelationShip, parser, result.jsonObject)
)
}
}?.let { result ->
when (val error = result.error) {
null -> showToast(
false, when (bSet) {
true -> R.string.endorse_succeeded
else -> R.string.remove_endorse_succeeded
}
)
else -> showToast(true, error)
}
}
}
}
| apache-2.0 | e913bc01039a6402d69ad39556abbe77 | 33.214286 | 99 | 0.470527 | 4.964602 | false | false | false | false |
DreierF/MyTargets | app/src/main/java/de/dreier/mytargets/base/db/dao/TrainingDAO.kt | 1 | 1936 | /*
* Copyright (C) 2018 Florian Dreier
*
* This file is part of MyTargets.
*
* MyTargets 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.
*
* MyTargets is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
package de.dreier.mytargets.base.db.dao
import androidx.lifecycle.LiveData
import androidx.room.*
import de.dreier.mytargets.shared.models.db.Round
import de.dreier.mytargets.shared.models.db.Training
@Dao
abstract class TrainingDAO {
@Query("SELECT * FROM `Training`")
abstract fun loadTrainings(): List<Training>
@Query("SELECT * FROM `Training`")
abstract fun loadTrainingsLive(): LiveData<List<Training>>
@Query("SELECT * FROM `Training` WHERE `id` = :id")
abstract fun loadTraining(id: Long): Training
@Query("SELECT * FROM `Training` WHERE `id` = :id")
abstract fun loadTrainingLive(id: Long): LiveData<Training>
@Insert(onConflict = OnConflictStrategy.REPLACE)
abstract fun insertTraining(training: Training): Long
@Update
abstract fun updateTraining(training: Training)
@Query("UPDATE `Training` SET `comment`=:comment WHERE `id` = :trainingId")
abstract fun updateComment(trainingId: Long, comment: String)
@Transaction
open fun insertTraining(training: Training, rounds: List<Round>) {
training.id = insertTraining(training)
for (round in rounds) {
round.trainingId = training.id
round.id = insertRound(round)
}
}
@Insert(onConflict = OnConflictStrategy.REPLACE)
abstract fun insertRound(round: Round): Long
@Delete
abstract fun deleteTraining(training: Training)
}
| gpl-2.0 | 3d8a2f9c757866bdd399f568b6269281 | 31.266667 | 79 | 0.71281 | 4.208696 | false | false | false | false |
cxpqwvtj/himawari | web/src/main/kotlin/app/himawari/interceptor/AccessContextInterceptor.kt | 1 | 2030 | package app.himawari.interceptor
import app.himawari.model.AppDate
import org.aspectj.lang.ProceedingJoinPoint
import org.aspectj.lang.annotation.Around
import org.aspectj.lang.annotation.Aspect
import org.dbflute.hook.AccessContext
import org.springframework.security.core.context.SecurityContextHolder
import org.springframework.security.core.userdetails.UserDetails
import org.springframework.stereotype.Component
/**
* DBFluteのアクセスコンテキストを設定するためのインターセプタクラスです。
* Created by cxpqwvtj on 2017/02/11.
*/
@Component
@Aspect
class AccessContextInterceptor(
private val appDate: AppDate
) {
@Around("execution(* app.himawari.controller..*.*(..))")
fun around(point: ProceedingJoinPoint): Any? {
if (AccessContext.isExistAccessContextOnThread()) {
// 既に設定されていたら何もしないで次へ
// (二度呼び出しされたときのために念のため)
return point.proceed()
}
// [アクセスユーザ]
// 例えば、セッション上のログインユーザを利用。
// ログインしていない場合のことも考慮すること。
val authentication = SecurityContextHolder.getContext().authentication
val accessUser = if (authentication == null) {
"anonymous"
} else {
val principal = authentication.principal
if (principal is UserDetails) {
principal.username
} else {
principal.toString()
}
}
val context = AccessContext()
context.accessLocalDateTime = appDate.systemDate().toLocalDateTime()
context.accessUser = accessUser
AccessContext.setAccessContextOnThread(context)
try {
return point.proceed()
} finally {
// 最後はしっかりクリアすること (必須)
AccessContext.clearAccessContextOnThread()
}
}
} | mit | 22745b4011e2fd7c881269391afe1f04 | 29.327586 | 78 | 0.658703 | 3.924107 | false | false | false | false |
paplorinc/intellij-community | platform/projectModel-impl/src/com/intellij/openapi/module/impl/ModulePointerImpl.kt | 7 | 2183 | /*
* 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.openapi.module.impl
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.module.Module
import com.intellij.openapi.module.ModulePointer
import java.util.concurrent.locks.ReentrantReadWriteLock
import kotlin.concurrent.read
private val LOG = Logger.getInstance(ModulePointerImpl::class.java)
class ModulePointerImpl : ModulePointer {
private var module: Module? = null
private var moduleName: String? = null
private val lock: ReentrantReadWriteLock
internal constructor(module: Module, lock: ReentrantReadWriteLock) {
this.module = module
this.lock = lock
}
internal constructor(moduleName: String, lock: ReentrantReadWriteLock) {
this.moduleName = moduleName
this.lock = lock
}
override fun getModule(): Module? = lock.read { module }
override fun getModuleName(): String = lock.read { module?.name ?: moduleName!! }
// must be called under lock, so, explicit lock using is not required
internal fun moduleAdded(module: Module) {
LOG.assertTrue(moduleName == module.name)
moduleName = null
this.module = module
}
// must be called under lock, so, explicit lock using is not required
internal fun moduleRemoved(module: Module) {
val resolvedModule = this.module
LOG.assertTrue(resolvedModule === module)
moduleName = resolvedModule!!.name
this.module = null
}
internal fun renameUnresolved(newName: String) {
LOG.assertTrue(module == null)
moduleName = newName
}
override fun toString(): String = "moduleName: $moduleName, module: $module"
}
| apache-2.0 | 229c0f9968fe8de477167d2bc6560827 | 32.075758 | 83 | 0.740724 | 4.322772 | false | false | false | false |
peruukki/SimpleCurrencyConverter | app/src/main/java/com/peruukki/simplecurrencyconverter/network/FetchConversionRatesTask.kt | 1 | 4529 | package com.peruukki.simplecurrencyconverter.network
import android.content.Context
import android.net.Uri
import android.os.AsyncTask
import android.util.Log
import com.peruukki.simplecurrencyconverter.R
import com.peruukki.simplecurrencyconverter.models.ConversionRate
import com.squareup.okhttp.OkHttpClient
import com.squareup.okhttp.Request
import org.json.JSONException
import org.json.JSONObject
import java.io.IOException
import java.net.URL
import java.util.*
/**
* The background task to use for fetching updated conversion rates. Updates the rates in the
* database after fetching.
*/
class FetchConversionRatesTask
/**
* Creates a new background task for fetching updated conversion rates.
*
* @param context application context
* @param updateListener listener to notify after successful fetching
*/
(private val mContext: Context, private val mUpdateListener: OnConversionRatesFetchedListener) : AsyncTask<Void, Void, String>() {
private var mConversionRates: List<ConversionRate> = ArrayList()
private val currencyPairsForApiQuery = ConversionRate.allRates
.map { conversionRateToApiKeyName(it) }
.joinToString(",")
override fun doInBackground(vararg params: Void): String? {
val client = OkHttpClient()
val uri = Uri.parse("https://free.currencyconverterapi.com/api/v5/convert").buildUpon()
.appendQueryParameter("q", currencyPairsForApiQuery)
.build()
try {
val url = URL(uri.toString())
Log.i(LOG_TAG, "Fetching conversion rates from $url")
val request = Request.Builder()
.url(url)
.build()
val responseBody = client.newCall(request)
.execute()
.body()
val response = responseBody.string()
Log.i(LOG_TAG, "Conversion rates response: '$response'")
val conversionRates = parseConversionRates(response)
for (conversionRate in conversionRates) {
Log.d(LOG_TAG, "Parsed conversion rate: " + conversionRate.fixedCurrencyRateString +
" <-> " + conversionRate.variableCurrencyRateString)
}
storeConversionRates(conversionRates)
mConversionRates = conversionRates
responseBody.close()
return null
} catch (e: IOException) {
Log.e(LOG_TAG, "Error fetching conversion rates", e)
return mContext.getString(R.string.failed_to_fetch_conversion_rates)
} catch (e: JSONException) {
Log.e(LOG_TAG, "Error parsing conversion rates to JSON", e)
return mContext.getString(R.string.unexpected_conversion_rate_data)
} catch (e: NumberFormatException) {
Log.e(LOG_TAG, "Error converting JSON string to number", e)
return mContext.getString(R.string.invalid_conversion_rates)
}
}
private fun conversionRateToApiKeyName(conversionRate: ConversionRate): String {
return conversionRate.fixedCurrency + "_" + conversionRate.variableCurrency
}
@Throws(JSONException::class)
private fun parseConversionRates(responseBody: String): List<ConversionRate> {
val responseJson = JSONObject(responseBody)
val results = responseJson.getJSONObject("results")
return ConversionRate.allRates.map { conversionRate ->
val rate = results.getJSONObject(conversionRateToApiKeyName(conversionRate))
val rateValue = java.lang.Float.valueOf(rate.getString("val"))
ConversionRate(conversionRate.fixedCurrency, conversionRate.variableCurrency, rateValue)
}
}
private fun storeConversionRates(conversionRates: List<ConversionRate>) {
for (conversionRate in conversionRates) {
conversionRate.writeToDb(mContext.contentResolver)
}
}
override fun onPostExecute(errorMessage: String?) {
super.onPostExecute(errorMessage)
if (errorMessage == null) {
mUpdateListener.onConversionRatesUpdated(mConversionRates)
} else {
mUpdateListener.onUpdateFailed(errorMessage)
}
}
interface OnConversionRatesFetchedListener {
fun onConversionRatesUpdated(conversionRates: List<ConversionRate>)
fun onUpdateFailed(errorMessage: String)
}
companion object {
private val LOG_TAG = FetchConversionRatesTask::class.java.simpleName
}
}
| mit | fad318b105e4d1ed0e38fdfab48b45e2 | 36.429752 | 130 | 0.674763 | 4.833511 | false | false | false | false |
paplorinc/intellij-community | platform/diff-impl/src/com/intellij/openapi/vcs/ex/LineStatusTrackerBase.kt | 2 | 12215 | /*
* 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.openapi.vcs.ex
import com.intellij.diff.util.DiffUtil
import com.intellij.diff.util.Side
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.Application
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.command.CommandProcessor
import com.intellij.openapi.command.undo.UndoConstants
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.editor.Document
import com.intellij.openapi.editor.impl.DocumentImpl
import com.intellij.openapi.localVcs.UpToDateLineNumberProvider.ABSENT_LINE_NUMBER
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.vcs.VcsBundle
import com.intellij.openapi.vcs.ex.DocumentTracker.Block
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.containers.nullize
import org.jetbrains.annotations.CalledInAwt
import org.jetbrains.annotations.TestOnly
import java.util.*
abstract class LineStatusTrackerBase<R : Range> : LineStatusTrackerI<R> {
protected val application: Application = ApplicationManager.getApplication()
open val project: Project?
final override val document: Document
final override val vcsDocument: Document
protected val disposable: Disposable = Disposer.newDisposable()
protected val documentTracker: DocumentTracker
protected abstract val renderer: LineStatusMarkerRenderer
final override var isReleased: Boolean = false
private set
protected var isInitialized: Boolean = false
private set
protected val blocks: List<Block> get() = documentTracker.blocks
internal val LOCK: DocumentTracker.Lock get() = documentTracker.LOCK
constructor(project: Project?, document: Document) {
this.project = project
this.document = document
vcsDocument = DocumentImpl(this.document.immutableCharSequence, true)
vcsDocument.putUserData(UndoConstants.DONT_RECORD_UNDO, true)
vcsDocument.setReadOnly(true)
documentTracker = DocumentTracker(vcsDocument, this.document, createDocumentTrackerHandler())
Disposer.register(disposable, documentTracker)
}
@CalledInAwt
protected open fun isDetectWhitespaceChangedLines(): Boolean = false
@CalledInAwt
protected open fun fireFileUnchanged() {}
protected open fun fireLinesUnchanged(startLine: Int, endLine: Int) {}
override val virtualFile: VirtualFile? get() = null
protected abstract fun Block.toRange(): R
protected open fun createDocumentTrackerHandler(): DocumentTracker.Handler = MyDocumentTrackerHandler()
override fun getRanges(): List<R>? {
application.assertReadAccessAllowed()
LOCK.read {
if (!isValid()) return null
return blocks.filter { !it.range.isEmpty }.map { it.toRange() }
}
}
@CalledInAwt
open fun setBaseRevision(vcsContent: CharSequence) {
setBaseRevision(vcsContent, null)
}
@CalledInAwt
protected fun setBaseRevision(vcsContent: CharSequence, beforeUnfreeze: (() -> Unit)?) {
application.assertIsDispatchThread()
if (isReleased) return
documentTracker.doFrozen(Side.LEFT) {
updateDocument(Side.LEFT) {
vcsDocument.setText(vcsContent)
}
beforeUnfreeze?.invoke()
}
if (!isInitialized) {
isInitialized = true
updateHighlighters()
}
}
@CalledInAwt
fun dropBaseRevision() {
application.assertIsDispatchThread()
if (isReleased) return
isInitialized = false
updateHighlighters()
}
@CalledInAwt
protected fun updateDocument(side: Side, task: (Document) -> Unit): Boolean {
return updateDocument(side, null, task)
}
@CalledInAwt
protected fun updateDocument(side: Side, commandName: String?, task: (Document) -> Unit): Boolean {
if (side.isLeft) {
vcsDocument.setReadOnly(false)
try {
CommandProcessor.getInstance().runUndoTransparentAction {
task(vcsDocument)
}
return true
}
finally {
vcsDocument.setReadOnly(true)
}
}
else {
return DiffUtil.executeWriteCommand(document, project, commandName, { task(document) })
}
}
@CalledInAwt
override fun doFrozen(task: Runnable) {
documentTracker.doFrozen({ task.run() })
}
fun release() {
val runnable = Runnable {
if (isReleased) return@Runnable
isReleased = true
Disposer.dispose(disposable)
}
if (!application.isDispatchThread || LOCK.isHeldByCurrentThread) {
application.invokeLater(runnable)
}
else {
runnable.run()
}
}
protected open inner class MyDocumentTrackerHandler : DocumentTracker.Handler {
override fun onRangeShifted(before: Block, after: Block) {
after.ourData.innerRanges = before.ourData.innerRanges
}
override fun afterRangeChange() {
updateHighlighters()
}
override fun afterBulkRangeChange() {
checkIfFileUnchanged()
calcInnerRanges()
updateHighlighters()
}
override fun onUnfreeze(side: Side) {
calcInnerRanges()
updateHighlighters()
}
private fun checkIfFileUnchanged() {
if (blocks.isEmpty()) {
fireFileUnchanged()
}
}
private fun calcInnerRanges() {
if (isDetectWhitespaceChangedLines() &&
!documentTracker.isFrozen()) {
for (block in blocks) {
if (block.ourData.innerRanges == null) {
block.ourData.innerRanges = calcInnerRanges(block)
}
}
}
}
}
private fun calcInnerRanges(block: Block): List<Range.InnerRange> {
if (block.start == block.end || block.vcsStart == block.vcsEnd) return emptyList()
return createInnerRanges(block.range,
vcsDocument.immutableCharSequence, document.immutableCharSequence,
vcsDocument.lineOffsets, document.lineOffsets)
}
protected fun updateHighlighters() {
renderer.scheduleUpdate()
}
@CalledInAwt
protected fun updateInnerRanges() {
LOCK.write {
if (isDetectWhitespaceChangedLines()) {
for (block in blocks) {
block.ourData.innerRanges = calcInnerRanges(block)
}
}
else {
for (block in blocks) {
block.ourData.innerRanges = null
}
}
updateHighlighters()
}
}
override fun isOperational(): Boolean = LOCK.read {
return isInitialized && !isReleased
}
override fun isValid(): Boolean = LOCK.read {
return isOperational() && !documentTracker.isFrozen()
}
override fun findRange(range: Range): R? = findBlock(range)?.toRange()
protected fun findBlock(range: Range): Block? {
LOCK.read {
if (!isValid()) return null
for (block in blocks) {
if (block.start == range.line1 &&
block.end == range.line2 &&
block.vcsStart == range.vcsLine1 &&
block.vcsEnd == range.vcsLine2) {
return block
}
}
return null
}
}
override fun getNextRange(line: Int): R? {
LOCK.read {
if (!isValid()) return null
for (block in blocks) {
if (line < block.end && !block.isSelectedByLine(line)) {
return block.toRange()
}
}
return null
}
}
override fun getPrevRange(line: Int): R? {
LOCK.read {
if (!isValid()) return null
for (block in blocks.reversed()) {
if (line > block.start && !block.isSelectedByLine(line)) {
return block.toRange()
}
}
return null
}
}
override fun getRangesForLines(lines: BitSet): List<R>? {
LOCK.read {
if (!isValid()) return null
val result = ArrayList<R>()
for (block in blocks) {
if (block.isSelectedByLine(lines)) {
result.add(block.toRange())
}
}
return result
}
}
override fun getRangeForLine(line: Int): R? {
LOCK.read {
if (!isValid()) return null
for (block in blocks) {
if (block.isSelectedByLine(line)) {
return block.toRange()
}
}
return null
}
}
@CalledInAwt
override fun rollbackChanges(range: Range) {
val newRange = findBlock(range)
if (newRange != null) {
runBulkRollback { it == newRange }
}
}
@CalledInAwt
override fun rollbackChanges(lines: BitSet) {
runBulkRollback { it.isSelectedByLine(lines) }
}
@CalledInAwt
protected fun runBulkRollback(condition: (Block) -> Boolean) {
if (!isValid()) return
updateDocument(Side.RIGHT, VcsBundle.message("command.name.rollback.change")) {
documentTracker.partiallyApplyBlocks(Side.RIGHT, condition) { block, shift ->
fireLinesUnchanged(block.start + shift, block.start + shift + (block.vcsEnd - block.vcsStart))
}
}
}
override fun isLineModified(line: Int): Boolean {
return isRangeModified(line, line + 1)
}
override fun isRangeModified(startLine: Int, endLine: Int): Boolean {
if (startLine == endLine) return false
assert(startLine < endLine)
LOCK.read {
if (!isValid()) return false
for (block in blocks) {
if (block.start >= endLine) return false
if (block.end > startLine) return true
}
return false
}
}
override fun transferLineFromVcs(line: Int, approximate: Boolean): Int {
return transferLine(line, approximate, true)
}
override fun transferLineToVcs(line: Int, approximate: Boolean): Int {
return transferLine(line, approximate, false)
}
private fun transferLine(line: Int, approximate: Boolean, fromVcs: Boolean): Int {
LOCK.read {
if (!isValid()) return if (approximate) line else ABSENT_LINE_NUMBER
var result = line
for (block in blocks) {
val startLine1 = if (fromVcs) block.vcsStart else block.start
val endLine1 = if (fromVcs) block.vcsEnd else block.end
val startLine2 = if (fromVcs) block.start else block.vcsStart
val endLine2 = if (fromVcs) block.end else block.vcsEnd
if (line in startLine1 until endLine1) {
return if (approximate) startLine2 else ABSENT_LINE_NUMBER
}
if (endLine1 > line) return result
val length1 = endLine1 - startLine1
val length2 = endLine2 - startLine2
result += length2 - length1
}
return result
}
}
protected open class BlockData(internal var innerRanges: List<Range.InnerRange>? = null)
protected open fun createBlockData(): BlockData = BlockData()
protected open val Block.ourData: BlockData get() = getBlockData(this)
protected fun getBlockData(block: Block): BlockData {
if (block.data == null) block.data = createBlockData()
return block.data as BlockData
}
protected val Block.innerRanges: List<Range.InnerRange>? get() = this.ourData.innerRanges.nullize()
companion object {
@JvmStatic protected val LOG: Logger = Logger.getInstance("#com.intellij.openapi.vcs.ex.LineStatusTracker")
@JvmStatic protected val Block.start: Int get() = range.start2
@JvmStatic protected val Block.end: Int get() = range.end2
@JvmStatic protected val Block.vcsStart: Int get() = range.start1
@JvmStatic protected val Block.vcsEnd: Int get() = range.end1
@JvmStatic protected fun Block.isSelectedByLine(line: Int): Boolean = DiffUtil.isSelectedByLine(line, this.range.start2, this.range.end2)
@JvmStatic protected fun Block.isSelectedByLine(lines: BitSet): Boolean = DiffUtil.isSelectedByLine(lines, this.range.start2, this.range.end2)
}
@TestOnly
fun getDocumentTrackerInTestMode(): DocumentTracker = documentTracker
}
| apache-2.0 | 578727571c8f4cb1331eedb4f9cc237a | 27.808962 | 146 | 0.680065 | 4.449909 | false | false | false | false |
paplorinc/intellij-community | platform/vcs-impl/src/com/intellij/openapi/vcs/changes/actions/SelectChangesGroupingActionGroup.kt | 6 | 1837 | // 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.openapi.vcs.changes.actions
import com.intellij.openapi.actionSystem.*
import com.intellij.openapi.project.DumbAware
import com.intellij.openapi.vcs.changes.ui.ChangesGroupingSupport
import com.intellij.ui.JBColor
import com.intellij.ui.SeparatorWithText
import com.intellij.ui.popup.PopupFactoryImpl
import com.intellij.ui.popup.list.PopupListElementRenderer
import java.awt.Graphics
class SelectChangesGroupingActionGroup : DefaultActionGroup(), DumbAware {
override fun canBePerformed(context: DataContext): Boolean = true
override fun update(e: AnActionEvent) {
e.presentation.isEnabled = e.getData(ChangesGroupingSupport.KEY) != null
}
override fun actionPerformed(e: AnActionEvent) {
val group = DefaultActionGroup().apply {
addSeparator(e.presentation.text)
addAll(this@SelectChangesGroupingActionGroup)
}
val popup = SelectChangesGroupingActionPopup(group, e.dataContext)
val component = e.inputEvent?.component
when (component) {
is ActionButtonComponent -> popup.showUnderneathOf(component)
else -> popup.showInBestPositionFor(e.dataContext)
}
}
}
private class SelectChangesGroupingActionPopup(group: ActionGroup, dataContext: DataContext) : PopupFactoryImpl.ActionGroupPopup(
null, group, dataContext, false, false, false, true, null, -1, null, null) {
override fun getListElementRenderer() = object : PopupListElementRenderer<Any>(this) {
override fun createSeparator() = object : SeparatorWithText() {
init {
textForeground = JBColor.BLACK
setCaptionCentered(false)
}
override fun paintLine(g: Graphics, x: Int, y: Int, width: Int) = Unit
}
}
} | apache-2.0 | d17196440676642628c13d85d92e32c7 | 38.106383 | 140 | 0.758302 | 4.458738 | false | false | false | false |
georocket/georocket | src/main/kotlin/io/georocket/output/xml/AllSameStrategy.kt | 1 | 473 | package io.georocket.output.xml
import io.georocket.storage.XmlChunkMeta
/**
* Merge chunks whose root XML elements are all equal
* @author Michel Kraemer
*/
class AllSameStrategy : AbstractMergeStrategy() {
override fun canMerge(metadata: XmlChunkMeta): Boolean {
return (parents == null || parents == metadata.parents)
}
override fun mergeParents(chunkMetadata: XmlChunkMeta) {
if (parents == null) {
parents = chunkMetadata.parents
}
}
}
| apache-2.0 | da47759aba1dc1a5369c7dd1713d001d | 23.894737 | 59 | 0.714588 | 4.185841 | false | false | false | false |
google/intellij-community | platform/lang-impl/src/com/intellij/openapi/projectRoots/impl/jdkDownloader/RuntimeChooserDialog.kt | 4 | 8827 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.projectRoots.impl.jdkDownloader
import com.intellij.icons.AllIcons
import com.intellij.lang.LangBundle
import com.intellij.openapi.actionSystem.DataProvider
import com.intellij.openapi.application.ApplicationInfo
import com.intellij.openapi.application.ModalityState
import com.intellij.openapi.application.invokeLater
import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory
import com.intellij.openapi.ide.CopyPasteManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.ComboBox
import com.intellij.openapi.ui.DialogWrapper
import com.intellij.openapi.ui.TextFieldWithBrowseButton
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.SystemInfo
import com.intellij.openapi.util.io.FileUtil
import com.intellij.ui.ExperimentalUI
import com.intellij.ui.JBColor
import com.intellij.ui.SimpleColoredComponent
import com.intellij.ui.dsl.builder.*
import com.intellij.ui.dsl.gridLayout.Gaps
import com.intellij.ui.dsl.gridLayout.HorizontalAlign
import com.intellij.ui.dsl.gridLayout.VerticalAlign
import com.intellij.ui.dsl.gridLayout.toJBEmptyBorder
import com.intellij.util.castSafelyTo
import com.intellij.util.io.isDirectory
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.components.BorderLayoutPanel
import java.awt.datatransfer.DataFlavor
import java.awt.event.WindowAdapter
import java.awt.event.WindowEvent
import java.nio.file.Path
import java.nio.file.Paths
import javax.swing.JComponent
import javax.swing.JPanel
sealed class RuntimeChooserDialogResult {
object Cancel : RuntimeChooserDialogResult()
object UseDefault: RuntimeChooserDialogResult()
data class DownloadAndUse(val item: JdkItem, val path: Path) : RuntimeChooserDialogResult()
data class UseCustomJdk(val name: String, val path: Path) : RuntimeChooserDialogResult()
}
class RuntimeChooserDialog(
private val project: Project?,
private val model: RuntimeChooserModel,
) : DialogWrapper(project), DataProvider {
private val USE_DEFAULT_RUNTIME_CODE = NEXT_USER_EXIT_CODE + 42
private lateinit var jdkInstallDirSelector: TextFieldWithBrowseButton
private lateinit var jdkCombobox: ComboBox<RuntimeChooserItem>
init {
title = LangBundle.message("dialog.title.choose.ide.runtime")
isResizable = false
init()
initClipboardListener()
}
private fun initClipboardListener() {
val knownPaths = mutableSetOf<String>()
val clipboardUpdateAction = {
val newPath = runCatching {
CopyPasteManager.getInstance().contents?.getTransferData(DataFlavor.stringFlavor) as? String
}.getOrNull()
if (!newPath.isNullOrBlank() && knownPaths.add(newPath)) {
RuntimeChooserCustom.importDetectedItem(newPath.trim(), model)
}
}
val windowListener = object: WindowAdapter() {
override fun windowActivated(e: WindowEvent?) {
invokeLater(ModalityState.any()) {
clipboardUpdateAction()
}
}
}
window?.let { window ->
window.addWindowListener(windowListener)
Disposer.register(disposable) { window.removeWindowListener(windowListener) }
}
clipboardUpdateAction()
}
override fun getData(dataId: String): Any? {
return RuntimeChooserCustom.jdkDownloaderExtensionProvider.getData(dataId)
}
override fun createSouthAdditionalPanel(): JPanel {
return BorderLayoutPanel().apply {
addToCenter(
createJButtonForAction(
DialogWrapperExitAction(
LangBundle.message("dialog.button.choose.ide.runtime.useDefault"),
USE_DEFAULT_RUNTIME_CODE)
)
)
}
}
fun showDialogAndGetResult() : RuntimeChooserDialogResult {
show()
if (exitCode == USE_DEFAULT_RUNTIME_CODE) {
return RuntimeChooserDialogResult.UseDefault
}
if (isOK) run {
val jdkItem = jdkCombobox.selectedItem.castSafelyTo<RuntimeChooserDownloadableItem>()?.item ?: return@run
val path = model.getInstallPathFromText(jdkItem, jdkInstallDirSelector.text)
return RuntimeChooserDialogResult.DownloadAndUse(jdkItem, path)
}
if (isOK) run {
val jdkItem = jdkCombobox.selectedItem.castSafelyTo<RuntimeChooserCustomItem>() ?: return@run
val home = Paths.get(jdkItem.homeDir)
if (home.isDirectory()) {
return RuntimeChooserDialogResult.UseCustomJdk(listOfNotNull(jdkItem.displayName, jdkItem.version).joinToString(" "), home)
}
}
return RuntimeChooserDialogResult.Cancel
}
override fun createTitlePane(): JComponent {
return panel {
row {
icon(AllIcons.General.Warning)
.verticalAlign(VerticalAlign.TOP)
.gap(RightGap.SMALL)
text(LangBundle.message("dialog.label.choose.ide.runtime.warn", ApplicationInfo.getInstance().shortCompanyName),
maxLineLength = DEFAULT_COMMENT_WIDTH)
}
}.apply {
val customLine = when {
SystemInfo.isWindows -> JBUI.Borders.customLine(JBColor.border(), 1, 0, 1, 0)
else -> JBUI.Borders.customLineBottom(JBColor.border())
}
border = JBUI.Borders.merge(JBUI.Borders.empty(10), customLine, true)
background = if (ExperimentalUI.isNewUI()) JBUI.CurrentTheme.Banner.WARNING_BACKGROUND else JBUI.CurrentTheme.Notification.BACKGROUND
foreground = JBUI.CurrentTheme.Notification.FOREGROUND
putClientProperty(DslComponentProperty.VISUAL_PADDINGS, Gaps.EMPTY)
}
}
override fun createCenterPanel(): JComponent {
jdkCombobox = object : ComboBox<RuntimeChooserItem>(model.mainComboBoxModel) {
init {
isSwingPopup = false
setRenderer(RuntimeChooserPresenter())
}
override fun setSelectedItem(anObject: Any?) {
if (anObject !is RuntimeChooserItem) return
if (anObject is RuntimeChooserAddCustomItem) {
RuntimeChooserCustom
.createSdkChooserPopup(jdkCombobox, [email protected])
?.showUnderneathOf(jdkCombobox)
return
}
if (anObject is RuntimeChooserDownloadableItem || anObject is RuntimeChooserCustomItem || anObject is RuntimeChooserCurrentItem) {
super.setSelectedItem(anObject)
}
}
}
return panel {
row(LangBundle.message("dialog.label.choose.ide.runtime.current")) {
val control = SimpleColoredComponent()
cell(control).horizontalAlign(HorizontalAlign.FILL)
model.currentRuntime.getAndSubscribe(disposable) {
control.clear()
if (it != null) {
RuntimeChooserPresenter.run {
control.presetCurrentRuntime(it)
}
}
}
}
row(LangBundle.message("dialog.label.choose.ide.runtime.combo")) {
cell(jdkCombobox).horizontalAlign(HorizontalAlign.FILL)
}
//download row
row(LangBundle.message("dialog.label.choose.ide.runtime.location")) {
jdkInstallDirSelector = textFieldWithBrowseButton(
project = project,
browseDialogTitle = LangBundle.message("dialog.title.choose.ide.runtime.select.path.to.install.jdk"),
fileChooserDescriptor = FileChooserDescriptorFactory.createSingleFolderDescriptor()
).horizontalAlign(HorizontalAlign.FILL)
.comment(LangBundle.message("dialog.message.choose.ide.runtime.select.path.to.install.jdk"))
.component
val updateLocation = {
when(val item = jdkCombobox.selectedItem){
is RuntimeChooserDownloadableItem -> {
jdkInstallDirSelector.text = model.getDefaultInstallPathFor(item.item)
jdkInstallDirSelector.setButtonEnabled(true)
jdkInstallDirSelector.isEditable = true
jdkInstallDirSelector.setButtonVisible(true)
}
is RuntimeChooserItemWithFixedLocation -> {
jdkInstallDirSelector.text = FileUtil.getLocationRelativeToUserHome(item.homeDir, false)
jdkInstallDirSelector.setButtonEnabled(false)
jdkInstallDirSelector.isEditable = false
jdkInstallDirSelector.setButtonVisible(false)
}
else -> {
jdkInstallDirSelector.text = ""
jdkInstallDirSelector.setButtonEnabled(false)
jdkInstallDirSelector.isEditable = false
jdkInstallDirSelector.setButtonVisible(false)
}
}
}
updateLocation()
jdkCombobox.addItemListener { updateLocation() }
}
}.apply {
border = IntelliJSpacingConfiguration().dialogGap.toJBEmptyBorder()
putClientProperty(IS_VISUAL_PADDING_COMPENSATED_ON_COMPONENT_LEVEL_KEY, false)
}
}
}
| apache-2.0 | d482a5bba4a34e16db10a8ee85aac735 | 36.722222 | 140 | 0.715419 | 4.792074 | false | false | false | false |
google/intellij-community | plugins/gitlab/src/org/jetbrains/plugins/gitlab/GitLabSettingsConfigurable.kt | 5 | 2040 | // 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.gitlab
import com.intellij.collaboration.auth.ui.AccountsPanelFactory
import com.intellij.openapi.components.service
import com.intellij.openapi.options.BoundConfigurable
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.DialogPanel
import com.intellij.openapi.util.Disposer
import com.intellij.ui.dsl.builder.panel
import com.intellij.ui.dsl.gridLayout.HorizontalAlign
import com.intellij.ui.dsl.gridLayout.VerticalAlign
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancel
import org.jetbrains.plugins.gitlab.authentication.accounts.GitLabAccountManager
import org.jetbrains.plugins.gitlab.authentication.accounts.GitLabProjectDefaultAccountHolder
import org.jetbrains.plugins.gitlab.authentication.ui.GitLabAccountsDetailsLoader
import org.jetbrains.plugins.gitlab.authentication.ui.GitLabAccountsListModel
import org.jetbrains.plugins.gitlab.util.GitLabUtil
internal class GitLabSettingsConfigurable(private val project: Project)
: BoundConfigurable(GitLabUtil.SERVICE_DISPLAY_NAME, "settings.gitlab") {
override fun createPanel(): DialogPanel {
val accountManager = service<GitLabAccountManager>()
val defaultAccountHolder = project.service<GitLabProjectDefaultAccountHolder>()
val accountsModel = GitLabAccountsListModel(project)
val scope = CoroutineScope(SupervisorJob()).also { Disposer.register(disposable!!) { it.cancel() } }
val detailsLoader = GitLabAccountsDetailsLoader(scope, accountManager, accountsModel)
val accountsPanelFactory = AccountsPanelFactory(accountManager, defaultAccountHolder, accountsModel, detailsLoader, disposable!!)
return panel {
row {
accountsPanelFactory.accountsPanelCell(this, true)
.horizontalAlign(HorizontalAlign.FILL)
.verticalAlign(VerticalAlign.FILL)
}.resizableRow()
}
}
} | apache-2.0 | 67f9bdd1a089c927e2f2345deef5c02d | 48.780488 | 133 | 0.817647 | 4.777518 | false | true | false | false |
google/iosched | mobile/src/main/java/com/google/samples/apps/iosched/util/UiUtils.kt | 1 | 3485 | /*
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.samples.apps.iosched.util
import android.content.Context
import android.graphics.drawable.Drawable
import android.view.View
import androidx.appcompat.content.res.AppCompatResources
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.graphics.drawable.DrawableCompat
import androidx.fragment.app.Fragment
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import com.google.samples.apps.iosched.R
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch
fun navigationItemBackground(context: Context): Drawable? {
// Need to inflate the drawable and CSL via AppCompatResources to work on Lollipop
var background =
AppCompatResources.getDrawable(context, R.drawable.navigation_item_background)
if (background != null) {
val tint = AppCompatResources.getColorStateList(
context, R.color.navigation_item_background_tint
)
background = DrawableCompat.wrap(background.mutate())
background.setTintList(tint)
}
return background
}
/**
* Map a slideOffset (in the range `[-1, 1]`) to an alpha value based on the desired range.
* For example, `slideOffsetToAlpha(0.5, 0.25, 1) = 0.33` because 0.5 is 1/3 of the way between
* 0.25 and 1. The result value is additionally clamped to the range `[0, 1]`.
*/
fun slideOffsetToAlpha(value: Float, rangeMin: Float, rangeMax: Float): Float {
return ((value - rangeMin) / (rangeMax - rangeMin)).coerceIn(0f, 1f)
}
/**
* Launches a new coroutine and repeats `block` every time the Fragment's viewLifecycleOwner
* is in and out of `minActiveState` lifecycle state.
*/
inline fun Fragment.launchAndRepeatWithViewLifecycle(
minActiveState: Lifecycle.State = Lifecycle.State.STARTED,
crossinline block: suspend CoroutineScope.() -> Unit
) {
viewLifecycleOwner.lifecycleScope.launch {
viewLifecycleOwner.lifecycle.repeatOnLifecycle(minActiveState) {
block()
}
}
}
/**
* Set the maximum width the view should take as a percent of its parent. The view must a direct
* child of a ConstraintLayout.
*/
fun setContentMaxWidth(view: View) {
val parent = view.parent as? ConstraintLayout ?: return
val layoutParams = view.layoutParams as ConstraintLayout.LayoutParams
val screenDensity = view.resources.displayMetrics.density
val widthDp = parent.width / screenDensity
val widthPercent = getContextMaxWidthPercent(widthDp.toInt())
layoutParams.matchConstraintPercentWidth = widthPercent
view.requestLayout()
}
private fun getContextMaxWidthPercent(maxWidthDp: Int): Float {
// These match @dimen/content_max_width_percent.
return when {
maxWidthDp >= 1024 -> 0.6f
maxWidthDp >= 840 -> 0.7f
maxWidthDp >= 600 -> 0.8f
else -> 1f
}
}
| apache-2.0 | 61798688c176a6c3afea776816f1869c | 36.473118 | 96 | 0.738307 | 4.35625 | false | false | false | false |
allotria/intellij-community | platform/testFramework/src/com/intellij/util/io/impl/DirectoryContentSpecImpl.kt | 1 | 7410 | // 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.util.io.impl
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.vfs.CharsetToolkit
import com.intellij.util.io.*
import org.junit.Assert.*
import java.io.File
import java.io.IOException
import java.nio.file.Files
import java.nio.file.Path
import java.util.*
import kotlin.collections.LinkedHashMap
sealed class DirectoryContentSpecImpl : DirectoryContentSpec {
abstract override fun mergeWith(other: DirectoryContentSpec): DirectoryContentSpecImpl
}
abstract class DirectorySpecBase : DirectoryContentSpecImpl() {
protected val children: LinkedHashMap<String, DirectoryContentSpecImpl> = LinkedHashMap()
fun addChild(name: String, spec: DirectoryContentSpecImpl) {
if (name in children) {
val existing = children[name]
if (spec is DirectorySpecBase && existing is DirectorySpecBase) {
existing.children += spec.children
return
}
throw IllegalArgumentException("'$name' already exists")
}
children[name] = spec
}
protected fun generateInDirectory(target: File) {
for ((name, child) in children) {
child.generate(File(target, name))
}
}
override fun generateInTempDir(): Path {
val target = FileUtil.createTempDirectory("directory-by-spec", null, true)
generate(target)
return target.toPath()
}
fun getChildren() : Map<String, DirectoryContentSpecImpl> = Collections.unmodifiableMap(children)
override fun mergeWith(other: DirectoryContentSpec): DirectoryContentSpecImpl {
require(other.javaClass == javaClass)
other as DirectorySpecBase
val result = when (other) {
is DirectorySpec -> DirectorySpec()
is ZipSpec -> ZipSpec()
else -> error(other)
}
result.children.putAll(children)
for ((name, child) in other.children) {
val oldChild = children[name]
result.children[name] = oldChild?.mergeWith(child) ?: child
}
return result
}
}
class DirectorySpec : DirectorySpecBase() {
override fun generate(target: File) {
if (!FileUtil.createDirectory(target)) {
throw IOException("Cannot create directory $target")
}
generateInDirectory(target)
}
}
class ZipSpec : DirectorySpecBase() {
override fun generate(target: File) {
val contentDir = FileUtil.createTempDirectory("zip-content", null, false)
try {
generateInDirectory(contentDir)
Compressor.Zip(target).use { it.addDirectory(contentDir) }
}
finally {
FileUtil.delete(contentDir)
}
}
override fun generateInTempDir(): Path {
val target = FileUtil.createTempFile("zip-by-spec", ".zip", true)
generate(target)
return target.toPath()
}
}
class FileSpec(val content: ByteArray?) : DirectoryContentSpecImpl() {
override fun generate(target: File) {
FileUtil.writeToFile(target, content ?: ByteArray(0))
}
override fun generateInTempDir(): Path {
val target = FileUtil.createTempFile("file-by-spec", null, true)
generate(target)
return target.toPath()
}
override fun mergeWith(other: DirectoryContentSpec): DirectoryContentSpecImpl {
return other as DirectoryContentSpecImpl
}
}
class DirectoryContentBuilderImpl(val result: DirectorySpecBase) : DirectoryContentBuilder() {
override fun addChild(name: String, spec: DirectoryContentSpecImpl) {
result.addChild(name, spec)
}
override fun file(name: String) {
addChild(name, FileSpec(null))
}
override fun file(name: String, text: String) {
file(name, text.toByteArray())
}
override fun file(name: String, content: ByteArray) {
addChild(name, FileSpec(content))
}
}
fun assertDirectoryContentMatches(file: File,
spec: DirectoryContentSpecImpl,
relativePath: String,
fileTextMatcher: FileTextMatcher,
filePathFilter: (String) -> Boolean) {
assertTrue("$file doesn't exist", file.exists())
when (spec) {
is DirectorySpec -> {
assertDirectoryMatches(file, spec, relativePath, fileTextMatcher, filePathFilter)
}
is ZipSpec -> {
assertTrue("$file is not a file", file.isFile)
val dirForExtracted = FileUtil.createTempDirectory("extracted-${file.name}", null, false)
ZipUtil.extract(file, dirForExtracted, null)
assertDirectoryMatches(dirForExtracted, spec, relativePath, fileTextMatcher, filePathFilter)
FileUtil.delete(dirForExtracted)
}
is FileSpec -> {
assertTrue("$file is not a file", file.isFile)
if (spec.content != null) {
val actualBytes = FileUtil.loadFileBytes(file)
if (!Arrays.equals(actualBytes, spec.content)) {
val actualString = actualBytes.convertToText()
val expectedString = spec.content.convertToText()
val place = if (relativePath != ".") " at $relativePath" else ""
if (actualString != null && expectedString != null) {
if (!fileTextMatcher.matches(actualString, expectedString)) {
assertEquals("File content mismatch$place:", expectedString, actualString)
}
}
else {
fail("Binary file content mismatch$place")
}
}
}
}
}
}
private fun ByteArray.convertToText(): String? {
val encoding = CharsetToolkit(this, Charsets.UTF_8, false).guessFromContent(size)
val charset = when (encoding) {
CharsetToolkit.GuessedEncoding.SEVEN_BIT -> Charsets.US_ASCII
CharsetToolkit.GuessedEncoding.VALID_UTF8 -> Charsets.UTF_8
else -> return null
}
return String(this, charset)
}
private fun assertDirectoryMatches(file: File,
spec: DirectorySpecBase,
relativePath: String,
fileTextMatcher: FileTextMatcher,
filePathFilter: (String) -> Boolean) {
assertTrue("$file is not a directory", file.isDirectory)
fun childNameFilter(name: String) = filePathFilter("$relativePath/$name")
val actualChildrenNames = file.listFiles()!!.filter { it.isDirectory || childNameFilter(it.name) }
.map { it.name }.sortedWith(String.CASE_INSENSITIVE_ORDER)
val children = spec.getChildren()
val expectedChildrenNames = children.entries.filter { it.value !is FileSpec || childNameFilter(it.key) }
.map { it.key }.sortedWith(String.CASE_INSENSITIVE_ORDER)
assertEquals("Directory content mismatch${if (relativePath != "") " at $relativePath" else ""}:",
expectedChildrenNames.joinToString("\n"), actualChildrenNames.joinToString("\n"))
for (child in actualChildrenNames) {
assertDirectoryContentMatches(File(file, child), children.get(child)!!, "$relativePath/$child", fileTextMatcher, filePathFilter)
}
}
internal fun createSpecByDirectory(dir: Path): DirectorySpec {
val spec = DirectorySpec()
dir.directoryStreamIfExists { children ->
children.forEach {
spec.addChild(it.fileName.toString(), createSpecByPath(it))
}
}
return spec
}
private fun createSpecByPath(path: Path): DirectoryContentSpecImpl {
if (path.isFile()) {
return FileSpec(Files.readAllBytes(path))
}
//todo support zip files
return createSpecByDirectory(path)
}
| apache-2.0 | 02e009b492ae71a0503181ecd231e63b | 34.118483 | 140 | 0.681377 | 4.704762 | false | false | false | false |
F43nd1r/acra-backend | acrarium/src/main/kotlin/com/faendir/acra/ui/view/SettingsView.kt | 1 | 3138 | /*
* (C) Copyright 2019 Lukas Morawietz (https://github.com/F43nd1r)
*
* 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.faendir.acra.ui.view
import com.faendir.acra.i18n.Messages
import com.faendir.acra.navigation.View
import com.faendir.acra.settings.LocalSettings
import com.faendir.acra.ui.component.HasAcrariumTitle
import com.faendir.acra.i18n.TranslatableText
import com.faendir.acra.ui.ext.Align
import com.faendir.acra.ui.ext.content
import com.faendir.acra.ui.ext.formLayout
import com.faendir.acra.ui.ext.setAlignSelf
import com.faendir.acra.ui.ext.translatableCheckbox
import com.faendir.acra.ui.ext.translatableSelect
import com.faendir.acra.ui.view.main.MainView
import com.vaadin.flow.component.Composite
import com.vaadin.flow.component.formlayout.FormLayout.ResponsiveStep
import com.vaadin.flow.component.orderedlayout.FlexComponent
import com.vaadin.flow.component.orderedlayout.FlexComponent.JustifyContentMode
import com.vaadin.flow.component.orderedlayout.FlexLayout
import com.vaadin.flow.router.Route
import com.vaadin.flow.server.VaadinService
import com.vaadin.flow.server.VaadinSession
import com.vaadin.flow.theme.lumo.Lumo
/**
* @author lukas
* @since 10.09.19
*/
@View
@Route(value = "settings", layout = MainView::class)
class SettingsView(localSettings: LocalSettings) : Composite<FlexLayout>(), HasAcrariumTitle {
init {
content {
setSizeFull()
justifyContentMode = JustifyContentMode.CENTER
alignItems = FlexComponent.Alignment.CENTER
formLayout {
setResponsiveSteps(ResponsiveStep("0px", 1))
setAlignSelf(Align.AUTO)
translatableCheckbox(Messages.DARK_THEME) {
value = localSettings.darkTheme
addValueChangeListener {
localSettings.darkTheme = it.value
VaadinSession.getCurrent().uIs.forEach { ui -> ui.element.setAttribute("theme", if (it.value) Lumo.DARK else Lumo.LIGHT) }
}
}
translatableSelect(VaadinService.getCurrent().instantiator.i18NProvider.providedLocales, Messages.LOCALE) {
setItemLabelGenerator { it.getDisplayName(localSettings.locale) }
value = localSettings.locale
addValueChangeListener {
localSettings.locale = it.value
VaadinSession.getCurrent().locale = it.value
}
}
}
}
}
override val title = TranslatableText(Messages.SETTINGS)
} | apache-2.0 | a57a968c26167dc30eac2062869ebb2b | 40.302632 | 146 | 0.695347 | 4.257802 | false | false | false | false |
genonbeta/TrebleShot | app/src/main/java/org/monora/uprotocol/client/android/viewmodel/FilesViewModel.kt | 1 | 7682 | /*
* Copyright (C) 2021 Veli Tasalı
*
* 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, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.monora.uprotocol.client.android.viewmodel
import android.annotation.TargetApi
import android.content.Context
import android.content.Intent
import android.database.sqlite.SQLiteConstraintException
import android.net.Uri
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Transformations
import androidx.lifecycle.ViewModel
import androidx.lifecycle.liveData
import androidx.lifecycle.viewModelScope
import com.genonbeta.android.framework.io.DocumentFile
import dagger.hilt.android.lifecycle.HiltViewModel
import dagger.hilt.android.qualifiers.ApplicationContext
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import org.monora.uprotocol.client.android.R
import org.monora.uprotocol.client.android.data.FileRepository
import org.monora.uprotocol.client.android.data.SelectionRepository
import org.monora.uprotocol.client.android.database.model.SafFolder
import org.monora.uprotocol.client.android.lifecycle.SingleLiveEvent
import org.monora.uprotocol.client.android.model.FileModel
import org.monora.uprotocol.client.android.model.ListItem
import org.monora.uprotocol.client.android.model.TitleSectionContentModel
import java.lang.ref.WeakReference
import java.text.Collator
import javax.inject.Inject
@HiltViewModel
class FilesViewModel @Inject internal constructor(
@ApplicationContext context: Context,
private val fileRepository: FileRepository,
private val selectionRepository: SelectionRepository,
) : ViewModel() {
private val context = WeakReference(context)
private val textFolder = context.getString(R.string.folder)
private val textFile = context.getString(R.string.file)
private val _files = MutableLiveData<List<ListItem>>()
val files = Transformations.map(
liveData {
requestPath(fileRepository.appDirectory)
emitSource(_files)
}
) {
selectionRepository.whenContains(it) { item, selected ->
if (item is FileModel) item.isSelected = selected
}
it
}
val isCustomStorageFolder: Boolean
get() = Uri.fromFile(fileRepository.defaultAppDirectory) != fileRepository.appDirectory.getUri()
private val _path = MutableLiveData<FileModel>()
val path = liveData {
emitSource(_path)
}
private val _pathTree = MutableLiveData<List<FileModel>>()
val pathTree = liveData {
emitSource(_pathTree)
}
val safAdded = SingleLiveEvent<SafFolder>()
val safFolders = fileRepository.getSafFolders()
var appDirectory
get() = fileRepository.appDirectory
set(value) {
fileRepository.appDirectory = value
}
fun clearStorageList() {
viewModelScope.launch(Dispatchers.IO) {
fileRepository.clearStorageList()
}
}
fun createFolder(displayName: String): Boolean {
val currentFolder = path.value ?: return false
val context = context.get() ?: return false
if (currentFolder.file.createDirectory(context, displayName) != null) {
requestPath(currentFolder.file)
return true
}
return false
}
private fun createOrderedFileList(file: DocumentFile): List<ListItem> {
val pathTree = mutableListOf<FileModel>()
var pathChild = file
do {
pathTree.add(FileModel(pathChild))
} while (pathChild.parent?.also { pathChild = it } != null)
pathTree.reverse()
_pathTree.postValue(pathTree)
val list = fileRepository.getFileList(file)
if (list.isEmpty()) return list
val collator = Collator.getInstance()
collator.strength = Collator.TERTIARY
val sortedList = list.sortedWith(compareBy(collator) {
it.file.getName()
})
val contents = ArrayList<ListItem>(0)
val files = ArrayList<FileModel>(0)
sortedList.forEach {
if (it.file.isDirectory()) contents.add(it)
else if (it.file.isFile()) files.add(it)
}
if (contents.isNotEmpty()) {
contents.add(0, TitleSectionContentModel(textFolder))
}
if (files.isNotEmpty()) {
contents.add(TitleSectionContentModel(textFile))
contents.addAll(files)
}
return contents
}
fun goUp(): Boolean {
val paths = pathTree.value ?: return false
if (paths.size < 2) {
return false
}
val iterator = paths.asReversed().listIterator()
if (iterator.hasNext()) {
iterator.next() // skip the first one that is already visible
do {
val next = iterator.next()
if (next.file.canRead()) {
requestPath(next.file)
return true
}
} while (iterator.hasNext())
}
return false
}
@TargetApi(19)
fun insertSafFolder(uri: Uri) {
viewModelScope.launch(Dispatchers.IO) {
try {
val context = context.get() ?: return@launch
context.contentResolver.takePersistableUriPermission(
uri, Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION
)
val document = DocumentFile.fromUri(context, uri, true)
val safFolder = SafFolder(uri, document.getName())
try {
fileRepository.insertFolder(safFolder)
} catch (ignored: SQLiteConstraintException) {
// The selected path may already exist!
}
safAdded.postValue(safFolder)
} catch (e: Exception) {
e.printStackTrace()
}
}
}
fun requestDefaultStorageFolder() {
viewModelScope.launch(Dispatchers.IO) {
context.get()?.let {
requestPathInternal(DocumentFile.fromFile(fileRepository.defaultAppDirectory))
}
}
}
fun requestStorageFolder() {
viewModelScope.launch(Dispatchers.IO) {
context.get()?.let {
requestPathInternal(fileRepository.appDirectory)
}
}
}
fun requestPath(file: DocumentFile) {
viewModelScope.launch(Dispatchers.IO) {
requestPathInternal(file)
}
}
fun requestPath(folder: SafFolder) {
viewModelScope.launch(Dispatchers.IO) {
try {
context.get()?.let {
requestPathInternal(DocumentFile.fromUri(it, folder.uri, true))
}
} catch (e: Exception) {
e.printStackTrace()
}
}
}
private fun requestPathInternal(file: DocumentFile) {
_path.postValue(FileModel(file))
_files.postValue(createOrderedFileList(file))
}
}
| gpl-2.0 | f09ad4f9e4b2b5c6c683b6f622cbedfe | 30.35102 | 104 | 0.644838 | 4.735512 | false | false | false | false |
Kotlin/kotlinx.coroutines | kotlinx-coroutines-test/jvm/src/migration/TestCoroutineScope.kt | 1 | 15824 | /*
* Copyright 2016-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
@file:Suppress("DEPRECATION")
package kotlinx.coroutines.test
import kotlinx.coroutines.*
import kotlinx.coroutines.internal.*
import kotlin.coroutines.*
/**
* A scope which provides detailed control over the execution of coroutines for tests.
*
* This scope is deprecated in favor of [TestScope].
* Please see the
* [migration guide](https://github.com/Kotlin/kotlinx.coroutines/blob/master/kotlinx-coroutines-test/MIGRATION.md)
* for an instruction on how to update the code for the new API.
*/
@ExperimentalCoroutinesApi
@Deprecated("Use `TestScope` in combination with `runTest` instead." +
"Please see the migration guide for details: " +
"https://github.com/Kotlin/kotlinx.coroutines/blob/master/kotlinx-coroutines-test/MIGRATION.md",
level = DeprecationLevel.WARNING)
// Since 1.6.0, ERROR in 1.7.0 and removed as experimental in 1.8.0
public interface TestCoroutineScope : CoroutineScope {
/**
* Called after the test completes.
*
* * It checks that there were no uncaught exceptions caught by its [CoroutineExceptionHandler].
* If there were any, then the first one is thrown, whereas the rest are suppressed by it.
* * It runs the tasks pending in the scheduler at the current time. If there are any uncompleted tasks afterwards,
* it fails with [UncompletedCoroutinesError].
* * It checks whether some new child [Job]s were created but not completed since this [TestCoroutineScope] was
* created. If so, it fails with [UncompletedCoroutinesError].
*
* For backward compatibility, if the [CoroutineExceptionHandler] is an [UncaughtExceptionCaptor], its
* [TestCoroutineExceptionHandler.cleanupTestCoroutines] behavior is performed.
* Likewise, if the [ContinuationInterceptor] is a [DelayController], its [DelayController.cleanupTestCoroutines]
* is called.
*
* @throws Throwable the first uncaught exception, if there are any uncaught exceptions.
* @throws AssertionError if any pending tasks are active.
* @throws IllegalStateException if called more than once.
*/
@ExperimentalCoroutinesApi
@Deprecated("Please call `runTest`, which automatically performs the cleanup, instead of using this function.")
// Since 1.6.0, ERROR in 1.7.0 and removed as experimental in 1.8.0
public fun cleanupTestCoroutines()
/**
* The delay-skipping scheduler used by the test dispatchers running the code in this scope.
*/
@ExperimentalCoroutinesApi
public val testScheduler: TestCoroutineScheduler
}
private class TestCoroutineScopeImpl(
override val coroutineContext: CoroutineContext
) : TestCoroutineScope {
private val lock = SynchronizedObject()
private var exceptions = mutableListOf<Throwable>()
private var cleanedUp = false
/**
* Reports an exception so that it is thrown on [cleanupTestCoroutines].
*
* If several exceptions are reported, only the first one will be thrown, and the other ones will be suppressed by
* it.
*
* Returns `false` if [cleanupTestCoroutines] was already called.
*/
fun reportException(throwable: Throwable): Boolean =
synchronized(lock) {
if (cleanedUp) {
false
} else {
exceptions.add(throwable)
true
}
}
override val testScheduler: TestCoroutineScheduler
get() = coroutineContext[TestCoroutineScheduler]!!
/** These jobs existed before the coroutine scope was used, so it's alright if they don't get cancelled. */
private val initialJobs = coroutineContext.activeJobs()
override fun cleanupTestCoroutines() {
val delayController = coroutineContext.delayController
val hasUnfinishedJobs = if (delayController != null) {
try {
delayController.cleanupTestCoroutines()
false
} catch (e: UncompletedCoroutinesError) {
true
}
} else {
testScheduler.runCurrent()
!testScheduler.isIdle(strict = false)
}
(coroutineContext[CoroutineExceptionHandler] as? UncaughtExceptionCaptor)?.cleanupTestCoroutines()
synchronized(lock) {
if (cleanedUp)
throw IllegalStateException("Attempting to clean up a test coroutine scope more than once.")
cleanedUp = true
}
exceptions.firstOrNull()?.let { toThrow ->
exceptions.drop(1).forEach { toThrow.addSuppressed(it) }
throw toThrow
}
if (hasUnfinishedJobs)
throw UncompletedCoroutinesError(
"Unfinished coroutines during teardown. Ensure all coroutines are" +
" completed or cancelled by your test."
)
val jobs = coroutineContext.activeJobs()
if ((jobs - initialJobs).isNotEmpty())
throw UncompletedCoroutinesError("Test finished with active jobs: $jobs")
}
}
internal fun CoroutineContext.activeJobs(): Set<Job> {
return checkNotNull(this[Job]).children.filter { it.isActive }.toSet()
}
/**
* A coroutine scope for launching test coroutines using [TestCoroutineDispatcher].
*
* [createTestCoroutineScope] is a similar function that defaults to [StandardTestDispatcher].
*/
@Deprecated(
"This constructs a `TestCoroutineScope` with a deprecated `CoroutineDispatcher` by default. " +
"Please use `createTestCoroutineScope` instead.",
ReplaceWith(
"createTestCoroutineScope(TestCoroutineDispatcher() + TestCoroutineExceptionHandler() + context)",
"kotlin.coroutines.EmptyCoroutineContext"
),
level = DeprecationLevel.WARNING
)
// Since 1.6.0, ERROR in 1.7.0 and removed as experimental in 1.8.0
public fun TestCoroutineScope(context: CoroutineContext = EmptyCoroutineContext): TestCoroutineScope {
val scheduler = context[TestCoroutineScheduler] ?: TestCoroutineScheduler()
return createTestCoroutineScope(TestCoroutineDispatcher(scheduler) + TestCoroutineExceptionHandler() + context)
}
/**
* A coroutine scope for launching test coroutines.
*
* This is a function for aiding in migration from [TestCoroutineScope] to [TestScope].
* Please see the
* [migration guide](https://github.com/Kotlin/kotlinx.coroutines/blob/master/kotlinx-coroutines-test/MIGRATION.md)
* for an instruction on how to update the code for the new API.
*
* It ensures that all the test module machinery is properly initialized.
* * If [context] doesn't define a [TestCoroutineScheduler] for orchestrating the virtual time used for delay-skipping,
* a new one is created, unless either
* - a [TestDispatcher] is provided, in which case [TestDispatcher.scheduler] is used;
* - at the moment of the creation of the scope, [Dispatchers.Main] is delegated to a [TestDispatcher], in which case
* its [TestCoroutineScheduler] is used.
* * If [context] doesn't have a [ContinuationInterceptor], a [StandardTestDispatcher] is created.
* * A [CoroutineExceptionHandler] is created that makes [TestCoroutineScope.cleanupTestCoroutines] throw if there were
* any uncaught exceptions, or forwards the exceptions further in a platform-specific manner if the cleanup was
* already performed when an exception happened. Passing a [CoroutineExceptionHandler] is illegal, unless it's an
* [UncaughtExceptionCaptor], in which case the behavior is preserved for the time being for backward compatibility.
* If you need to have a specific [CoroutineExceptionHandler], please pass it to [launch] on an already-created
* [TestCoroutineScope] and share your use case at
* [our issue tracker](https://github.com/Kotlin/kotlinx.coroutines/issues).
* * If [context] provides a [Job], that job is used for the new scope; otherwise, a [CompletableJob] is created.
*
* @throws IllegalArgumentException if [context] has both [TestCoroutineScheduler] and a [TestDispatcher] linked to a
* different scheduler.
* @throws IllegalArgumentException if [context] has a [ContinuationInterceptor] that is not a [TestDispatcher].
* @throws IllegalArgumentException if [context] has an [CoroutineExceptionHandler] that is not an
* [UncaughtExceptionCaptor].
*/
@ExperimentalCoroutinesApi
@Deprecated(
"This function was introduced in order to help migrate from TestCoroutineScope to TestScope. " +
"Please use TestScope() construction instead, or just runTest(), without creating a scope.",
level = DeprecationLevel.WARNING
)
// Since 1.6.0, ERROR in 1.7.0 and removed as experimental in 1.8.0
public fun createTestCoroutineScope(context: CoroutineContext = EmptyCoroutineContext): TestCoroutineScope {
val ctxWithDispatcher = context.withDelaySkipping()
var scope: TestCoroutineScopeImpl? = null
val ownExceptionHandler =
object : AbstractCoroutineContextElement(CoroutineExceptionHandler), TestCoroutineScopeExceptionHandler {
override fun handleException(context: CoroutineContext, exception: Throwable) {
if (!scope!!.reportException(exception))
throw exception // let this exception crash everything
}
}
val exceptionHandler = when (val exceptionHandler = ctxWithDispatcher[CoroutineExceptionHandler]) {
is UncaughtExceptionCaptor -> exceptionHandler
null -> ownExceptionHandler
is TestCoroutineScopeExceptionHandler -> ownExceptionHandler
else -> throw IllegalArgumentException(
"A CoroutineExceptionHandler was passed to TestCoroutineScope. " +
"Please pass it as an argument to a `launch` or `async` block on an already-created scope " +
"if uncaught exceptions require special treatment."
)
}
val job: Job = ctxWithDispatcher[Job] ?: Job()
return TestCoroutineScopeImpl(ctxWithDispatcher + exceptionHandler + job).also {
scope = it
}
}
/** A marker that shows that this [CoroutineExceptionHandler] was created for [TestCoroutineScope]. With this,
* constructing a new [TestCoroutineScope] with the [CoroutineScope.coroutineContext] of an existing one will override
* the exception handler, instead of failing. */
private interface TestCoroutineScopeExceptionHandler : CoroutineExceptionHandler
private inline val CoroutineContext.delayController: DelayController?
get() {
val handler = this[ContinuationInterceptor]
return handler as? DelayController
}
/**
* The current virtual time on [testScheduler][TestCoroutineScope.testScheduler].
* @see TestCoroutineScheduler.currentTime
*/
@ExperimentalCoroutinesApi
public val TestCoroutineScope.currentTime: Long
get() = coroutineContext.delayController?.currentTime ?: testScheduler.currentTime
/**
* Advances the [testScheduler][TestCoroutineScope.testScheduler] by [delayTimeMillis] and runs the tasks up to that
* moment (inclusive).
*
* @see TestCoroutineScheduler.advanceTimeBy
*/
@ExperimentalCoroutinesApi
@Deprecated(
"The name of this function is misleading: it not only advances the time, but also runs the tasks " +
"scheduled *at* the ending moment.",
ReplaceWith("this.testScheduler.apply { advanceTimeBy(delayTimeMillis); runCurrent() }"),
DeprecationLevel.WARNING
)
// Since 1.6.0, ERROR in 1.7.0 and removed as experimental in 1.8.0
public fun TestCoroutineScope.advanceTimeBy(delayTimeMillis: Long): Unit =
when (val controller = coroutineContext.delayController) {
null -> {
testScheduler.advanceTimeBy(delayTimeMillis)
testScheduler.runCurrent()
}
else -> {
controller.advanceTimeBy(delayTimeMillis)
Unit
}
}
/**
* Advances the [testScheduler][TestCoroutineScope.testScheduler] to the point where there are no tasks remaining.
* @see TestCoroutineScheduler.advanceUntilIdle
*/
@ExperimentalCoroutinesApi
public fun TestCoroutineScope.advanceUntilIdle() {
coroutineContext.delayController?.advanceUntilIdle() ?: testScheduler.advanceUntilIdle()
}
/**
* Run any tasks that are pending at the current virtual time, according to
* the [testScheduler][TestCoroutineScope.testScheduler].
*
* @see TestCoroutineScheduler.runCurrent
*/
@ExperimentalCoroutinesApi
public fun TestCoroutineScope.runCurrent() {
coroutineContext.delayController?.runCurrent() ?: testScheduler.runCurrent()
}
@ExperimentalCoroutinesApi
@Deprecated(
"The test coroutine scope isn't able to pause its dispatchers in the general case. " +
"Only `TestCoroutineDispatcher` supports pausing; pause it directly, or use a dispatcher that is always " +
"\"paused\", like `StandardTestDispatcher`.",
ReplaceWith(
"(this.coroutineContext[ContinuationInterceptor]!! as DelayController).pauseDispatcher(block)",
"kotlin.coroutines.ContinuationInterceptor"
),
DeprecationLevel.WARNING
)
// Since 1.6.0, ERROR in 1.7.0 and removed as experimental in 1.8.0
public suspend fun TestCoroutineScope.pauseDispatcher(block: suspend () -> Unit) {
delayControllerForPausing.pauseDispatcher(block)
}
@ExperimentalCoroutinesApi
@Deprecated(
"The test coroutine scope isn't able to pause its dispatchers in the general case. " +
"Only `TestCoroutineDispatcher` supports pausing; pause it directly, or use a dispatcher that is always " +
"\"paused\", like `StandardTestDispatcher`.",
ReplaceWith(
"(this.coroutineContext[ContinuationInterceptor]!! as DelayController).pauseDispatcher()",
"kotlin.coroutines.ContinuationInterceptor"
),
level = DeprecationLevel.WARNING
)
// Since 1.6.0, ERROR in 1.7.0 and removed as experimental in 1.8.0
public fun TestCoroutineScope.pauseDispatcher() {
delayControllerForPausing.pauseDispatcher()
}
@ExperimentalCoroutinesApi
@Deprecated(
"The test coroutine scope isn't able to pause its dispatchers in the general case. " +
"Only `TestCoroutineDispatcher` supports pausing; pause it directly, or use a dispatcher that is always " +
"\"paused\", like `StandardTestDispatcher`.",
ReplaceWith(
"(this.coroutineContext[ContinuationInterceptor]!! as DelayController).resumeDispatcher()",
"kotlin.coroutines.ContinuationInterceptor"
),
level = DeprecationLevel.WARNING
)
// Since 1.6.0, ERROR in 1.7.0 and removed as experimental in 1.8.0
public fun TestCoroutineScope.resumeDispatcher() {
delayControllerForPausing.resumeDispatcher()
}
/**
* List of uncaught coroutine exceptions, for backward compatibility.
*
* The returned list is a copy of the exceptions caught during execution.
* During [TestCoroutineScope.cleanupTestCoroutines] the first element of this list is rethrown if it is not empty.
*
* Exceptions are only collected in this list if the [UncaughtExceptionCaptor] is in the test context.
*/
@Deprecated(
"This list is only populated if `UncaughtExceptionCaptor` is in the test context, and so can be " +
"easily misused. It is only present for backward compatibility and will be removed in the subsequent " +
"releases. If you need to check the list of exceptions, please consider creating your own " +
"`CoroutineExceptionHandler`.",
level = DeprecationLevel.WARNING
)
public val TestCoroutineScope.uncaughtExceptions: List<Throwable>
get() = (coroutineContext[CoroutineExceptionHandler] as? UncaughtExceptionCaptor)?.uncaughtExceptions
?: emptyList()
private val TestCoroutineScope.delayControllerForPausing: DelayController
get() = coroutineContext.delayController
?: throw IllegalStateException("This scope isn't able to pause its dispatchers")
| apache-2.0 | a837d263bf9893688fae8f37a4dc7ddb | 44.866667 | 119 | 0.724469 | 4.945 | false | true | false | false |
leafclick/intellij-community | platform/diff-impl/tests/testSrc/com/intellij/diff/util/DiffUtilTest.kt | 2 | 7105 | /*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.diff.util
import com.intellij.diff.DiffRequestFactoryImpl
import com.intellij.diff.DiffTestCase
import com.intellij.diff.comparison.ComparisonPolicy
import com.intellij.diff.tools.util.text.LineOffsetsUtil
import com.intellij.openapi.diff.DiffBundle
import com.intellij.openapi.editor.impl.DocumentImpl
import com.intellij.util.containers.ContainerUtil
import java.io.File
class DiffUtilTest : DiffTestCase() {
fun `test getSortedIndexes`() {
fun <T> doTest(vararg values: T, comparator: (T, T) -> Int) {
val list = values.toList()
val sortedIndexes = DiffUtil.getSortedIndexes(list, comparator)
val expected = ContainerUtil.sorted(list, comparator)
val actual = (0..values.size - 1).map { values[sortedIndexes[it]] }
assertOrderedEquals(expected, actual)
assertEquals(sortedIndexes.toSet().size, list.size)
}
doTest(1, 2, 3, 4, 5, 6, 7, 8) { v1, v2 -> v1 - v2 }
doTest(8, 7, 6, 5, 4, 3, 2, 1) { v1, v2 -> v1 - v2 }
doTest(1, 3, 5, 7, 8, 6, 4, 2) { v1, v2 -> v1 - v2 }
doTest(1, 2, 3, 4, 5, 6, 7, 8) { v1, v2 -> v2 - v1 }
doTest(8, 7, 6, 5, 4, 3, 2, 1) { v1, v2 -> v2 - v1 }
doTest(1, 3, 5, 7, 8, 6, 4, 2) { v1, v2 -> v2 - v1 }
}
fun `test merge conflict partially resolved confirmation message`() {
fun doTest(changes: Int, conflicts: Int, expected: String) {
val actual = DiffBundle.message("merge.dialog.apply.partially.resolved.changes.confirmation.message", changes, conflicts)
assertTrue(actual.startsWith(expected), actual)
}
doTest(1, 0, "There is one change left")
doTest(0, 1, "There is one conflict left")
doTest(1, 1, "There is one change and one conflict left")
doTest(2, 0, "There are 2 changes left")
doTest(0, 2, "There are 2 conflicts left")
doTest(2, 2, "There are 2 changes and 2 conflicts left")
doTest(1, 2, "There is one change and 2 conflicts left")
doTest(2, 1, "There are 2 changes and one conflict left")
doTest(2, 3, "There are 2 changes and 3 conflicts left")
}
fun `test diff content titles`() {
fun doTest(path: String, expected: String) {
val filePath = createFilePath(path)
val actual1 = DiffRequestFactoryImpl.getContentTitle(filePath)
val actual2 = DiffRequestFactoryImpl.getTitle(filePath, null, " <-> ")
val actual3 = DiffRequestFactoryImpl.getTitle(null, filePath, " <-> ")
val expectedNative = expected.replace('/', File.separatorChar)
assertEquals(expectedNative, actual1)
assertEquals(expectedNative, actual2)
assertEquals(expectedNative, actual3)
}
doTest("file.txt", "file.txt")
doTest("/path/to/file.txt", "file.txt (/path/to)")
doTest("/path/to/dir/", "/path/to/dir")
}
fun `test diff request titles`() {
fun doTest(path1: String, path2: String, expected: String) {
val filePath1 = createFilePath(path1)
val filePath2 = createFilePath(path2)
val actual = DiffRequestFactoryImpl.getTitle(filePath1, filePath2, " <-> ")
assertEquals(expected.replace('/', File.separatorChar), actual)
}
doTest("file1.txt", "file1.txt", "file1.txt")
doTest("/path/to/file1.txt", "/path/to/file1.txt", "file1.txt (/path/to)")
doTest("/path/to/dir1/", "/path/to/dir1/", "/path/to/dir1")
doTest("file1.txt", "file2.txt", "file1.txt <-> file2.txt")
doTest("/path/to/file1.txt", "/path/to/file2.txt", "file1.txt <-> file2.txt (/path/to)")
doTest("/path/to/dir1/", "/path/to/dir2/", "dir1 <-> dir2 (/path/to)")
doTest("/path/to/file1.txt", "/path/to_another/file1.txt", "file1.txt (/path/to <-> /path/to_another)")
doTest("/path/to/file1.txt", "/path/to_another/file2.txt", "file1.txt <-> file2.txt (/path/to <-> /path/to_another)")
doTest("/path/to/dir1/", "/path/to_another/dir2/", "dir1 <-> dir2 (/path/to <-> /path/to_another)")
doTest("file1.txt", "/path/to/file1.txt", "file1.txt <-> /path/to/file1.txt")
doTest("file1.txt", "/path/to/file2.txt", "file1.txt <-> /path/to/file2.txt")
doTest("/path/to/dir1/", "/path/to/file2.txt", "dir1/ <-> file2.txt (/path/to)")
doTest("/path/to/file1.txt", "/path/to/dir2/", "file1.txt <-> dir2/ (/path/to)")
doTest("/path/to/dir1/", "/path/to_another/file2.txt", "dir1/ <-> file2.txt (/path/to <-> /path/to_another)")
}
fun `test applyModification`() {
val runs = 10000
val textLength = 30
doAutoTest(System.currentTimeMillis(), runs) {
val text1 = generateText(textLength)
val text2 = generateText(textLength)
val lineOffsets1 = LineOffsetsUtil.create(text1)
val lineOffsets2 = LineOffsetsUtil.create(text2)
val fragments = MANAGER.compareLines(text1, text2, ComparisonPolicy.DEFAULT, INDICATOR)
val ranges = fragments.map {
Range(it.startLine1, it.endLine1, it.startLine2, it.endLine2)
}
val patched = DiffUtil.applyModification(text1, lineOffsets1, text2, lineOffsets2, ranges)
val base = textToReadableFormat(text1)
val expected = textToReadableFormat(text2)
val actual = textToReadableFormat(patched)
assertEquals(expected, actual, "$base\n$expected\n$actual")
}
}
fun `test getLines`() {
fun doTest(text: String, expectedLines: List<String>) {
val document = DocumentImpl(text)
assertEquals(expectedLines, DiffUtil.getLines(document))
val lineOffsets = LineOffsetsUtil.create(text)
assertEquals(expectedLines, DiffUtil.getLines(text, lineOffsets))
}
doTest("", listOf(""))
doTest(" ", listOf(" "))
doTest("\n", listOf("", ""))
doTest("\na\n", listOf("", "a", ""))
doTest("\na", listOf("", "a"))
doTest("a\n\nb", listOf("a", "", "b"))
doTest("ab\ncd", listOf("ab", "cd"))
doTest("ab\ncd\n", listOf("ab", "cd", ""))
doTest("\nab\ncd", listOf("", "ab", "cd"))
doTest("\nab\ncd\n", listOf("", "ab", "cd", ""))
}
}
| apache-2.0 | 3697192c507ec9a22694719876c75ed0 | 38.692737 | 127 | 0.65855 | 3.476027 | false | true | false | false |
io53/Android_RuuvitagScanner | app/src/main/java/com/ruuvi/station/settings/ui/AppSettingsGraphFragment.kt | 1 | 2605 | package com.ruuvi.station.settings.ui
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.lifecycleScope
import com.flexsentlabs.extensions.viewModel
import com.ruuvi.station.R
import kotlinx.android.synthetic.main.fragment_app_settings_graph.*
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.collect
import org.kodein.di.Kodein
import org.kodein.di.KodeinAware
import org.kodein.di.android.support.closestKodein
class AppSettingsGraphFragment : Fragment(), KodeinAware {
override val kodein: Kodein by closestKodein()
private val viewModel: AppSettingsGraphViewModel by viewModel()
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.fragment_app_settings_graph, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
setupViews()
observeInterval()
observePeriod()
observeShowAllPoints()
}
private fun setupViews() {
graphIntervalNumberPicker.minValue = 1
graphIntervalNumberPicker.maxValue = 60
viewPeriodNumberPicker.minValue = 1
viewPeriodNumberPicker.maxValue = 72
graphIntervalNumberPicker.setOnValueChangedListener { _, _, new ->
viewModel.setPointInterval(new)
}
viewPeriodNumberPicker.setOnValueChangedListener { _, _, new ->
viewModel.setViewPeriod(new)
}
graphAllPointsSwitch.setOnCheckedChangeListener { _, isChecked ->
viewModel.setShowAllPoints(isChecked)
}
}
private fun observeInterval() {
lifecycleScope.launch {
viewModel.observePointInterval().collect {
graphIntervalNumberPicker.value = it
}
}
}
private fun observePeriod() {
lifecycleScope.launch {
viewModel.observeViewPeriod().collect {
viewPeriodNumberPicker.value = it
}
}
}
private fun observeShowAllPoints() {
lifecycleScope.launch {
viewModel.showAllPointsFlow.collect{
graphAllPointsSwitch.isChecked = it
graphIntervalNumberPicker.isEnabled = !graphAllPointsSwitch.isChecked
}
}
}
companion object {
fun newInstance() = AppSettingsGraphFragment()
}
} | mit | 840be88433b7910bf70dda9ff2455f85 | 30.39759 | 87 | 0.679079 | 5.148221 | false | false | false | false |
leafclick/intellij-community | plugins/settings-repository/src/autoSync.kt | 1 | 6012 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.settingsRepository
import com.intellij.configurationStore.ComponentStoreImpl
import com.intellij.notification.Notification
import com.intellij.notification.Notifications
import com.intellij.openapi.application.AppUIExecutor
import com.intellij.openapi.application.Application
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.ModalityState
import com.intellij.openapi.application.impl.coroutineDispatchingContext
import com.intellij.openapi.components.stateStore
import com.intellij.openapi.progress.ProcessCanceledException
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.ShutDownTracker
import com.intellij.openapi.vcs.VcsBundle
import com.intellij.openapi.vcs.VcsNotifier
import com.intellij.openapi.vcs.ui.VcsBalloonProblemNotifier
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withContext
import java.util.concurrent.Future
internal class AutoSyncManager(private val icsManager: IcsManager) {
@Volatile
private var autoSyncFuture: Future<*>? = null
@Volatile var enabled = true
fun waitAutoSync(indicator: ProgressIndicator) {
val autoFuture = autoSyncFuture
if (autoFuture != null) {
if (autoFuture.isDone) {
autoSyncFuture = null
}
else if (autoSyncFuture != null) {
LOG.info("Wait for auto sync future")
indicator.text = "Wait for auto sync completion"
while (!autoFuture.isDone) {
if (indicator.isCanceled) {
return
}
Thread.sleep(5)
}
}
}
}
fun registerListeners(project: Project) {
project.messageBus.connect().subscribe(Notifications.TOPIC, object : Notifications {
override fun notify(notification: Notification) {
if (!icsManager.isActive) {
return
}
if (when {
notification.groupId == VcsBalloonProblemNotifier.NOTIFICATION_GROUP.displayId -> {
val message = notification.content
message.startsWith("VCS Update Finished") ||
message == VcsBundle.message("message.text.file.is.up.to.date") ||
message == VcsBundle.message("message.text.all.files.are.up.to.date")
}
notification.groupId == VcsNotifier.NOTIFICATION_GROUP_ID.displayId && notification.title == "Push successful" -> true
else -> false
}) {
autoSync()
}
}
})
}
fun autoSync(onAppExit: Boolean = false, force: Boolean = false) {
if (!enabled || !icsManager.isActive || (!force && !icsManager.settings.autoSync)) {
return
}
autoSyncFuture?.let {
if (!it.isDone) {
return
}
}
val app = ApplicationManager.getApplication()
if (onAppExit) {
runBlocking {
sync(app, onAppExit)
}
return
}
else if (app.isDisposed) {
// will be handled by applicationExiting listener
return
}
autoSyncFuture = app.executeOnPooledThread {
try {
// to ensure that repository will not be in uncompleted state and changes will be pushed
ShutDownTracker.getInstance().registerStopperThread(Thread.currentThread())
runBlocking {
sync(app, onAppExit)
}
}
finally {
autoSyncFuture = null
ShutDownTracker.getInstance().unregisterStopperThread(Thread.currentThread())
}
}
}
private suspend fun sync(app: Application, onAppExit: Boolean) {
catchAndLog {
icsManager.runInAutoCommitDisabledMode {
doSync(app, onAppExit)
}
}
}
private suspend fun doSync(app: Application, onAppExit: Boolean) {
val repositoryManager = icsManager.repositoryManager
val hasUpstream = repositoryManager.hasUpstream()
if (hasUpstream && !repositoryManager.canCommit()) {
LOG.warn("Auto sync skipped: repository is not committable")
return
}
// on app exit fetch and push only if there are commits to push
if (onAppExit) {
// if no upstream - just update cloud schemes
if (hasUpstream && !repositoryManager.commit() && repositoryManager.getAheadCommitsCount() == 0 && icsManager.readOnlySourcesManager.repositories.isEmpty()) {
return
}
// use explicit progress task to sync on app exit to make it clear why app is not exited immediately
icsManager.syncManager.sync(SyncType.MERGE, onAppExit = true)
return
}
// update read-only sources at first (because contain scheme - to ensure that some scheme will exist when it will be set as current by some setting)
updateCloudSchemes(icsManager)
if (hasUpstream) {
val updater = repositoryManager.fetch()
// we merge in EDT non-modal to ensure that new settings will be properly applied
withContext(AppUIExecutor.onUiThread(ModalityState.NON_MODAL).coroutineDispatchingContext()) {
catchAndLog {
val updateResult = updater.merge()
if (!onAppExit &&
!app.isDisposed &&
updateResult != null &&
updateStoragesFromStreamProvider(icsManager, app.stateStore as ComponentStoreImpl, updateResult,
app.messageBus)) {
// force to avoid saveAll & confirmation
app.exit(true, true, true)
}
}
}
if (!updater.definitelySkipPush) {
repositoryManager.push()
}
}
}
}
internal inline fun catchAndLog(asWarning: Boolean = false, runnable: () -> Unit) {
try {
runnable()
}
catch (e: ProcessCanceledException) { }
catch (e: Throwable) {
if (asWarning || e is AuthenticationException || e is NoRemoteRepositoryException) {
LOG.warn(e)
}
else {
LOG.error(e)
}
}
} | apache-2.0 | efed2dc998b2cc024d7b3d2b43196fc6 | 32.220994 | 164 | 0.670492 | 4.8523 | false | false | false | false |
JuliusKunze/kotlin-native | backend.native/tests/external/codegen/box/super/traitproperty.kt | 4 | 540 | interface M {
var backingB : Int
var b : Int
get() = backingB
set(value: Int) {
backingB = value
}
}
class N() : M {
public override var backingB : Int = 0
val a : Int
get() {
super.b = super.b + 1
return super.b + 1
}
override var b: Int = a + 1
val superb : Int
get() = super.b
}
fun box(): String {
val n = N()
n.a
n.b
n.superb
if (n.b == 3 && n.a == 4 && n.superb == 3) return "OK";
return "fail";
}
| apache-2.0 | a3a224584923714db6e83c8388cdf22c | 16.419355 | 59 | 0.440741 | 3.214286 | false | false | false | false |
mrbublos/vkm | app/src/main/java/vkm/vkm/SearchFragment.kt | 1 | 5729 | package vkm.vkm
import android.text.InputType.TYPE_CLASS_TEXT
import android.text.InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD
import android.view.View
import android.view.View.GONE
import android.view.View.VISIBLE
import android.widget.AbsListView
import android.widget.AbsListView.OnScrollListener.SCROLL_STATE_IDLE
import kotlinx.android.synthetic.main.activity_search.*
import kotlinx.android.synthetic.main.composition_list_element.view.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import vkm.vkm.R.layout.*
import vkm.vkm.adapters.AlbumListAdapter
import vkm.vkm.adapters.ArtistListAdapter
import vkm.vkm.adapters.CompositionListAdapter
import vkm.vkm.utils.*
import vkm.vkm.utils.db.Db
class SearchFragment : VkmFragment() {
// private vars
private var filterText: String = ""
private var currentElement = 0
private var tabs: List<Tab<*>> = listOf()
private val currentTab: Tab<*>
get() = tabs[State.currentSearchTab]
init { layout = activity_search }
override fun init() {
tabs = listOf(TracksTab(::drawData),
// NewAlbumsTab(::drawData),
ChartTab(::drawData), ArtistTab(::drawData))
initializeElements()
initializeTabs()
initializeButton()
}
private fun initializeElements() {
showSpinner(false)
search.inputType = if (State.enableTextSuggestions) TYPE_CLASS_TEXT else TYPE_TEXT_VARIATION_VISIBLE_PASSWORD
resultList.setOnScrollListener(object : AbsListView.OnScrollListener {
private var resultVisibleIndex = 0
private var resultVisible = 0
override fun onScroll(view: AbsListView?, firstVisibleItem: Int, visibleItemCount: Int, totalItemCount: Int) {
resultVisibleIndex = firstVisibleItem
resultVisible = visibleItemCount
}
override fun onScrollStateChanged(view: AbsListView?, scrollState: Int) {
if (scrollState == SCROLL_STATE_IDLE && resultVisibleIndex + resultVisible >= currentTab.dataList.size) {
currentElement = resultVisibleIndex + resultVisible
currentTab.onBottomReached()
}
}
})
}
private fun initializeTabs() {
searchTabsSwiper.value = tabs.asSequence().map { it.name }.toMutableList()
searchTabsSwiper.setCurrentString(currentTab.name)
currentTab.activate(null)
searchTabsSwiper.onSwiped = { index, _, prev ->
State.currentSearchTab = index
tabs[index].activate(null)
lockScreen(true)
tabs[prev].deactivate()
searchPanel.visibility = if (currentTab.hideSearch) GONE else VISIBLE
}
}
private fun initializeButton() {
blockSearch(false)
searchButton.setOnClickListener {
filterText = search.text.toString()
if (currentTab.search(filterText)) { lockScreen(true) }
currentElement = 0
return@setOnClickListener
}
}
private fun drawData() {
val me = this
GlobalScope.launch(Dispatchers.Main) {
lockScreen(false)
val data = currentTab.dataList
resultList.adapter = when (currentTab.listType) {
ListType.Composition -> CompositionListAdapter(me, composition_list_element, data as MutableList<Composition>, compositionAction)
ListType.Album -> AlbumListAdapter(me, album_list_element, data as MutableList<Album>, ::compositionContainerAction)
ListType.Artist -> ArtistListAdapter(me, album_list_element, data as MutableList<Artist>, ::compositionContainerAction)
}
resultList.setSelection(currentElement)
// TODO see how slow it is
context?.let { HttpUtils.storeProxies(Db.instance(it).proxyDao()) }
}
}
// actions
private fun blockSearch(locked: Boolean) {
searchButton.isFocusable = !locked
searchButton.isClickable = !locked
}
private fun showSpinner(show: Boolean) {
resultList.visibility = if (!show) VISIBLE else GONE
loadingSpinner.visibility = if (show) VISIBLE else GONE
}
private fun lockScreen(locked: Boolean) {
GlobalScope.launch(Dispatchers.Main) {
blockSearch(currentTab.loading || locked)
showSpinner(currentTab.loading || locked)
}
}
private val compositionAction = { composition: Composition, view: View ->
if (!DownloadManager.getDownloaded().contains(composition)) {
DownloadManager.downloadComposition(composition)
val actionButton = view.imageView
actionButton.setImageDrawable(context!!.getDrawable(R.drawable.ic_downloading))
actionButton.setOnClickListener {}
}
}
private fun compositionContainerAction(item: CompositionContainer, view: View) {
lockScreen(true)
switchTo("tracks")
([email protected] as Tab<Composition>).activate(item.compositionFetcher)
}
private fun switchTo(name: String) {
searchTabsSwiper.setCurrentString(name)
switchTo(getTabIndex(name))
}
private fun switchTo(index: Int) {
State.currentSearchTab = index
searchPanel.visibility = if (currentTab.hideSearch) GONE else VISIBLE
}
private fun getTabIndex(name: String): Int {
return tabs.asSequence().map { it.name }.indexOf(name)
}
override fun onDestroyView() {
super.onDestroyView()
currentTab.deactivate()
tabs.forEach { it.destroy() }
}
}
| gpl-3.0 | a93a68330018170fbb731b713091360c | 35.259494 | 145 | 0.662768 | 4.850974 | false | false | false | false |
AndroidX/androidx | navigation/navigation-compose-lint/src/test/java/androidx/navigation/compose/lint/Stubs.kt | 3 | 7629 | /*
* 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.navigation.compose.lint
import androidx.compose.lint.test.compiledStub
internal val NAV_BACK_STACK_ENTRY = compiledStub(
filename = "NavBackStackEntry.kt",
filepath = "androidx/navigation",
checksum = 0x6920c3ac,
source = """
package androidx.navigation
public class NavBackStackEntry
""",
"""
META-INF/main.kotlin_module:
H4sIAAAAAAAAAGNgYGBmYGBgBGJWKM3AJcTFnZyfq5dakZhbkJMqxBzvXaLE
oMUAAMRK5d0sAAAA
""",
"""
androidx/navigation/NavBackStackEntry.class:
H4sIAAAAAAAAAI2Ru04CQRSG/zPAoisKKiqosTNeCleMncZEjCYkiIkYGqqB
3eBwmU12hw12PItvYGViYYilD2U8u9rZOMWX8/9nMucyn19v7wBOsU3YldoN
fOVOHC0j1ZNG+dppyKgqu4OmYVxrEzxlQYRCX0bSGUrdc+46fa9rskgRrHOl
lbkgpPYPWjlkYNlII0tIm0cVEvbq/6pwRliuD3wzVNq59Yx0pZHsiVGU4lYp
RoZAA7YmKlbHHLkVws5satuiJGxR4Gg2Lc2mJ+KYqpmPZ0sURHzrhPgFFP/U
PBoYbvPKdz1Cvq601xiPOl7wIDtDdlbqflcOWzJQsf417aY/DrrejYpF+X6s
jRp5LRUqzl5q7ZtkvBAVCN5CfLjpeCnMDVZOonmWw1fMvXAgUGJaiZlGmZn7
uYB52El+M+E6tpIvIyxwLtdGqobFGpaYyMco1LCMlTYoxCqKnA9hh1gLYX0D
+QLjIO8BAAA=
"""
)
internal val NAV_CONTROLLER = compiledStub(
filename = "NavController.kt",
filepath = "androidx/navigation",
checksum = 0xa6eda16e,
source = """
package androidx.navigation
public class NavController {
public fun getBackStackEntry(route: String) = NavBackStackEntry()
}
""",
"""
META-INF/main.kotlin_module:
H4sIAAAAAAAAAGNgYGBmYGBgBGJWKM3AJcTFnZyfq5dakZhbkJMqxBzvXaLE
oMUAAMRK5d0sAAAA
""",
"""
androidx/navigation/NavController.class:
H4sIAAAAAAAAAI1SW08TQRT+Ztru4oJlQbkrioDclAXikzVGIZqU1GrEkBie
pttJmXY7m+xOG3zjt/gL9AmjiSE++qOMZ8pGrGhkkz1nzjnf+WbO5fuPz18B
PMA6w5zQ9SRW9aNAi65qCKNiHVRFdyfWJomjSCYuGIPfFF0RREI3gpe1pgyN
ixyD80hpZR4z5JZX9odQgOMhD5chbw5VyjBf+S97iWGkIc22CFt7hsQzCrxj
KC1Xzm/cM4nSjdLKv9j6k0v23jhpBE1paolQOg2E1rHpwdOgGptqJ4oIVUji
jpEDKDLMtmITKR00u+1AaSMTLaKgrO29qQpTFz7DWHgow1aW/kokoi0JyLD0
+1PPmlP6y+OpP6O45mEE1xkWL1WJi3EPE7afoxcJqW+V7NUvpBF1YQT5eLub
o9EyKwoMrEWuI2WtDTrVNxkenh6Pe3ySe9w/Pfb4AO8Z9ugXJ0+Pt/gG2y58
e+9wn+8W/dw038hvOX6BtGMZthixY+nSo/D7pr3eMrQcO3FdMgxXlJbVTrsm
kzeiFklbZRyKaF8kytqZc+Z1RxvVlmXdVaki19PzYTIs/Bn9NZg+mLcXd5JQ
PleWcSrL2b/Ah01wWmD7caqS9tnWSlZAmtmWrp5g4GMvvEzS6TnzWCE5dAbA
FXikRzBInlwveZvQnHRxbXT4E8a+YOLtCSY/9LE4lGlZxs+QGYs9FTFF8dUM
d5X0Gv0uywyOez15F/dJPyHvNFHNHCBXxo0ybpLErBW3yriNuQOwFHcwfwA3
hZdiIYWTYjDFYooimT8B9qxp7xsEAAA=
"""
)
internal val NAV_GRAPH_BUILDER = compiledStub(
filename = "NavGraphBuilder.kt",
filepath = "androidx/navigation",
checksum = 0xf26bfe8b,
source = """
package androidx.navigation
public class NavGraphBuilder
""",
"""
META-INF/main.kotlin_module:
H4sIAAAAAAAAAGNgYGBmYGBgBGJWKM3AZc0lnZiXUpSfmVKhl5dYlpmeWJKZ
n6eXnJ9bkF+cKiTol1jmXpRYkOFUmpmTklrkXSLECRTyyC8u8S5RYtBiAAA0
5BaVVQAAAA==
""",
"""
androidx/navigation/NavGraphBuilder.class:
H4sIAAAAAAAAAI1RTUsCURQ996ljTVajfWlFmwiqRaPRrggqKAQzqHDT6ukM
+nJ8EzNPcelv6R+0ClqEtOxHRXemVq16i8M951zu1/v8ensHcIRNwrbUXhQq
b+xqOVJdaVSo3aYcXUXyqXc+VIHnR3kQwXmUI+kGUnfdm/aj3zF5ZAjWidLK
nBIyu3utAnKwbGSRJ2RNT8WEncY/6h8Tio1+aAKl3WvfSE8ayZoYjDI8JiWQ
I1CfpbFKWJUjr0bYmk5sW5SFLRyOppPydHIoqnSe+3i2hCOSrEPiCij96XjQ
NzziRej5hMWG0n5zOGj70b1sB6yUGmFHBi0ZqYT/ivZdOIw6/qVKSOV2qI0a
+C0VK3bPtA5NulqMGgRfIHk8cnIQxjVmbsp5k/1XzLxwIFBmtFIxiwpj4ScB
s7BTfz3FVWykn0WYY6/wgEwd83UsMGIxAaeOIkoPoBhLWGY/hh1jJYb1DRVj
VoXpAQAA
"""
)
internal val NAV_GRAPH_COMPOSABLE = compiledStub(
filename = "NavGraphBuilder.kt",
filepath = "androidx/navigation/compose",
checksum = 0x6920624a,
source = """
package androidx.navigation.compose
import androidx.compose.runtime.Composable
import androidx.navigation.NavBackStackEntry
import androidx.navigation.NavGraphBuilder
public fun NavGraphBuilder.composable(
route: String, content: @Composable (NavBackStackEntry) -> Unit
) { }
public fun NavGraphBuilder.navigation(route: String, builder: NavGraphBuilder.() -> Unit) { }
""",
"""
META-INF/main.kotlin_module:
H4sIAAAAAAAAAGNgYGBmYGBgBGJWKM3AZc0lnZiXUpSfmVKhl5dYlpmeWJKZ
n6eXnJ9bkF+cKiTol1jmXpRYkOFUmpmTklrkXSLECRTyyC8u8S7hEuXiBirU
S61IzC3ISRViC0kFCSsxaDEAAFP1RV1sAAAA
""",
"""
androidx/navigation/compose/NavGraphBuilderKt.class:
H4sIAAAAAAAAAL1VS1MTQRD+ZvMkoiYbBQKKqCgvcUN8XGJRJZRaKSM+ohzk
NNmsYfKYpXYmKbxx9WT5F/wH3iwPFuXRH2XZkwRIMBZcdFPb09PT/X090z2b
n7++fQdwF/cZlrmsBL6o7DqSt0WVa+FLx/WbO77ynA3efhLwne21lmhUvOCp
joExJGu8zZ0Gl1XnebnmuWQNMSS6Qbzc8BjezheH4R7DyxePkEo6ELKaL9Z9
3RDSqbWbzruWdE2Ych73tJX8wibDp38E/mD5b7hr3K2XNIlHUgfvD3HeSKHz
q52crhf9oOrUPF0OuCBQLqWveZdgw9cbrUYjzxB9oLeFWo1jhGG6LxkhtRdI
3nAK0mSqhKtiOMNw0d323Hov/gUPeNMjR4a5+eLxGgzZ7sLmKM7iXAKjOM8Q
CfyW9uJIMcRcnwiljiNN1Zw1Oc32V+/Gqc6Xwf6Tk2HmpBJSqxyhMnz879Uc
xP2zlrFydy2OqcPj6c84dRDzzNO8wjWnLVnNdoiuFDMiwsDqRrHIviuMliWt
ssLwYX/vZmJ/L2ElrYQ1YXXVc51hwjp6451xcim5vzdpZdmilbVy0WSI9HBu
PBmZTNth28rGOpJloz8+R614nNxHhngnet7WgPcZk1COUcZUxd52+ks0d8qr
MNAsB5+NoCW1aHrO+mFPkd/0Ac2jXeo9RXAHfK/f7xgH+1hpbtc1Q3jdr1BH
ni8K6W20mmUveN3tUbvou7yxyQNh5j3jSElUJdetgPTZV90sCrItlKDlw/vz
8OhuUi+W/Fbgeo+Fic/0Yja7EX2OWIGFMMxjIYMIogjBodlLmpsKpxftxFck
l2yb5C37AskvHecsyag5ZiQIBJjpuuMixjpwaaQwTutGS2OCInKduBjuGFuI
luKms/pkhn4n8F8awj86wH95CP9UH//k3/kt+usw8jbu0ficrNN0Ile2ECpg
poCrJHGtgOuYLeAGbm6BKcxhfgujChGFBYUxhVRHSSssKiwp3FLIKEwpLP8G
Q1+Sp54GAAA=
"""
)
internal val NAV_HOST = compiledStub(
filename = "NavHost.kt",
filepath = "androidx/navigation/compose",
checksum = 0x72aa34d0,
source = """
package androidx.navigation.compose
import androidx.navigation.NavGraphBuilder
public fun NavHost(route: String, builder: NavGraphBuilder.() -> Unit) { }
""",
"""
META-INF/main.kotlin_module:
H4sIAAAAAAAAAGNgYGBmYGBgBGJWKM3AZc0lnZiXUpSfmVKhl5dYlpmeWJKZ
n6eXnJ9bkF+cKiTol1jmXpRYkOFUmpmTklrkXSLECRTyyC8u8S5RYtBiAAA0
5BaVVQAAAA==
""",
"""
androidx/navigation/compose/NavHostKt.class:
H4sIAAAAAAAAAJVSy24TMRQ9nrxDH0lKXwFKoS19AZNWsApCKhWFqCEgUrLp
ypmY1MnErmY8Udn1W/gDdogFqljyUYg7k6SNVCRgpDn3+vjch33989e37wCe
4CHDGlctT8vWma14X7a5kVrZju6dal/YNd5/rX1zaFJgDLkO73Pb5aptv212
hENsjCE1FDE83aheKerGk6pdrna1caWyO/2e/TFQTpjetw+G3k55s8HQ+f+4
Z4+qf+qbWnnl8dOTF4F0W8K7zPJBSVN+HhVbqWqvbXeEaXpcUkqulDZ8kL6m
TS1w3TJDwtOBEWlkGJbGOpHKCE9x166osE1fOn4KNxhmnRPhdIfh77jHe4KE
DOvjJxvcWfn6WTcbE5jEVBYTmKb7bA6aTyPPULiuZlj+26Uy5EeSN8LwFjec
OKvXj9HUWQgJBtYNHYv4Mxl6JfJaOwyHF+fF7MV51spZAzMVmQVr9BfXcySx
Smw3mbPIxnbnc/HiTCFesErJCFkp8eNz0kqnwpS7jGrSQYYNjXe59k9DpBGM
gl+eGUG3rtUoy9GnU0GC7PANPu7SM4zv65ZgmK5KJWpBrym8I950RdiDdrjb
4J4M10MyU5dtxU3gkb/6PlBG9kRF9aUvaftylHtXr4Sq1XXgOeJAhvGLw5jG
IGJMiB1YiCP8SIYEkohhjVZ7xFtkJ7cK2a/IbRcKhF/CYeABYZLkE4Tr5M8N
hMhgJko0iTxu0v5GpE5hM+QsItJRlXREb0W4im2y+8TOUu25Y8QqmK9ggRCL
FRRxq4LbuHMM5mMJd4+R9pHwsewjE2Hexz0f932s/AYz8VZoLwQAAA==
"""
)
| apache-2.0 | 957317b21cfe325d88eff33a816b9d71 | 38.528497 | 97 | 0.80679 | 2.119167 | false | false | false | false |
smmribeiro/intellij-community | platform/diff-impl/src/com/intellij/diff/actions/DiffCustomCommandHandler.kt | 12 | 2665 | // 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.diff.actions
import com.intellij.diff.DiffDialogHints
import com.intellij.diff.DiffManager
import com.intellij.execution.Executor
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.extensions.InternalIgnoreDependencyViolation
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.terminal.TerminalShellCommandHandler
import com.intellij.util.execution.ParametersListUtil
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.Paths
@InternalIgnoreDependencyViolation
private class DiffCustomCommandHandler : TerminalShellCommandHandler {
override fun execute(project: Project, workingDirectory: String?, localSession: Boolean, command: String, executor: Executor): Boolean {
val parameters = parse(workingDirectory, localSession, command)
if (parameters == null) {
LOG.warn("Command $command should be matched and properly parsed")
return false
}
val file1 = LocalFileSystem.getInstance().findFileByIoFile(parameters.first.toFile())
val file2 = LocalFileSystem.getInstance().findFileByIoFile(parameters.second.toFile())
if (file1 == null || file2 == null) {
LOG.warn("Cannot find virtual file for one of the paths: $file1, $file2")
return false
}
DiffManager.getInstance().showDiff(project,
BaseShowDiffAction.createMutableChainFromFiles(project, file1, file2),
DiffDialogHints.DEFAULT)
return true
}
override fun matches(project: Project, workingDirectory: String?, localSession: Boolean, command: String): Boolean {
return parse(workingDirectory, localSession, command) != null
}
private fun parse(workingDirectory: String?, localSession: Boolean, command: String): Pair<Path, Path>? {
if (!command.startsWith("diff ") || !localSession) {
return null
}
if (workingDirectory == null) {
return null
}
val commands = ParametersListUtil.parse(command)
if (commands.size < 3) {
return null
}
val path1 = Paths.get(workingDirectory, commands[1])
val path2 = Paths.get(workingDirectory, commands[2])
val file1Exists = Files.exists(path1)
val file2Exists = Files.exists(path2)
if (!file1Exists || !file2Exists) {
return null
}
return Pair(path1, path2)
}
companion object {
private val LOG = Logger.getInstance(DiffCustomCommandHandler::class.java)
}
} | apache-2.0 | fe28c21877fac7cf45f4e1edcd82c8b2 | 34.546667 | 140 | 0.723827 | 4.441667 | false | false | false | false |
smmribeiro/intellij-community | platform/projectModel-impl/src/com/intellij/workspaceModel/ide/WorkspaceModelTopics.kt | 1 | 4698 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.workspaceModel.ide
import com.intellij.diagnostic.ActivityCategory
import com.intellij.diagnostic.StartUpMeasurer
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.components.service
import com.intellij.openapi.project.Project
import com.intellij.util.containers.ContainerUtil
import com.intellij.util.messages.MessageBus
import com.intellij.util.messages.MessageBusConnection
import com.intellij.util.messages.Topic
import com.intellij.workspaceModel.storage.VersionedStorageChange
import java.util.*
interface WorkspaceModelChangeListener : EventListener {
fun beforeChanged(event: VersionedStorageChange) {}
fun changed(event: VersionedStorageChange) {}
}
/**
* Topics to subscribe to Workspace changes
*
* Please use [subscribeImmediately] and [subscribeAfterModuleLoading] to subscribe to changes
*/
class WorkspaceModelTopics : Disposable {
companion object {
/** Please use [subscribeImmediately] and [subscribeAfterModuleLoading] to subscribe to changes */
@Topic.ProjectLevel
private val CHANGED = Topic(WorkspaceModelChangeListener::class.java, Topic.BroadcastDirection.NONE)
@JvmStatic
fun getInstance(project: Project): WorkspaceModelTopics = project.service()
}
private val allEvents = ContainerUtil.createConcurrentList<EventsDispatcher>()
private var sendToQueue = true
var modulesAreLoaded = false
/**
* Subscribe to topic and start to receive changes immediately.
*
* Topic is project-level only without broadcasting - connection expected to be to project message bus only.
*/
fun subscribeImmediately(connection: MessageBusConnection, listener: WorkspaceModelChangeListener) {
connection.subscribe(CHANGED, listener)
}
/**
* Subscribe to the topic and start to receive changes only *after* all the modules get loaded.
* All the events that will be fired before the modules loading, will be collected to the queue. After the modules are loaded, all events
* from the queue will be dispatched to listener under the write action and the further events will be dispatched to listener
* without passing to event queue.
*
* Topic is project-level only without broadcasting - connection expected to be to project message bus only.
*/
fun subscribeAfterModuleLoading(connection: MessageBusConnection, listener: WorkspaceModelChangeListener) {
if (!sendToQueue) {
subscribeImmediately(connection, listener)
}
else {
val queue = EventsDispatcher(listener)
allEvents += queue
subscribeImmediately(connection, queue)
}
}
fun syncPublisher(messageBus: MessageBus): WorkspaceModelChangeListener = messageBus.syncPublisher(CHANGED)
fun notifyModulesAreLoaded() {
val activity = StartUpMeasurer.startActivity("postponed events sending", ActivityCategory.DEFAULT)
sendToQueue = false
if (allEvents.isNotEmpty() && allEvents.any { it.events.isNotEmpty() }) {
val activityInQueue = activity.startChild("events sending (in queue)")
val application = ApplicationManager.getApplication()
application.invokeAndWait {
application.runWriteAction {
val innerActivity = activityInQueue.endAndStart("events sending")
allEvents.forEach { queue ->
queue.collectToQueue = false
queue.events.forEach { (isBefore, event) ->
if (isBefore) queue.originalListener.beforeChanged(event)
else queue.originalListener.changed(event)
}
queue.events.clear()
}
innerActivity.end()
}
}
}
else {
allEvents.forEach { queue -> queue.collectToQueue = false }
}
allEvents.clear()
modulesAreLoaded = true
activity.end()
}
private class EventsDispatcher(val originalListener: WorkspaceModelChangeListener) : WorkspaceModelChangeListener {
val events = mutableListOf<Pair<Boolean, VersionedStorageChange>>()
var collectToQueue = true
override fun beforeChanged(event: VersionedStorageChange) {
if (collectToQueue) {
events += true to event
}
else {
originalListener.beforeChanged(event)
}
}
override fun changed(event: VersionedStorageChange) {
if (collectToQueue) {
events += false to event
}
else {
originalListener.changed(event)
}
}
}
override fun dispose() {
allEvents.forEach { it.events.clear() }
allEvents.clear()
}
}
| apache-2.0 | 712af933218c5dfaaf28ef846df6bb4e | 35.703125 | 140 | 0.729034 | 4.997872 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/multiFileIntentions/moveToCompanion/moveProperty/after/test.kt | 13 | 908 | package test
inline fun <T, R> with(receiver: T, block: T.() -> R): R = receiver.block()
class A {
class X {
}
inner class OuterY
fun outerFoo(n: Int) {}
val outerBar = 1
companion object {
class Y
fun foo(n: Int) {}
val bar = 1
fun Int.extFoo(n: Int) {}
val Int.extBar: Int get() = 1
var test: Int
get() = 1
set(value: Int) {
X()
Y()
foo(bar)
1.extFoo(1.extBar)
O.Y()
O.foo(O.bar)
with (O) {
Y()
foo(bar)
1.extFoo(1.extBar)
}
}
}
object O {
class Y
fun foo(n: Int) {}
val bar = 1
fun Int.extFoo(n: Int) {}
val Int.extBar: Int get() = 1
}
} | apache-2.0 | 8d9fc577261c401157203a137c427199 | 14.672414 | 75 | 0.365639 | 3.880342 | false | false | false | false |
smmribeiro/intellij-community | plugins/svn4idea/testSource/org/jetbrains/idea/svn/SvnMergeInfoTest.kt | 12 | 11780 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.idea.svn
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.vcs.VcsConfiguration
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.openapi.vfs.VirtualFile
import org.jetbrains.idea.svn.SvnPropertyKeys.MERGE_INFO
import org.jetbrains.idea.svn.SvnUtil.createUrl
import org.jetbrains.idea.svn.SvnUtil.parseUrl
import org.jetbrains.idea.svn.api.Depth
import org.jetbrains.idea.svn.api.Revision
import org.jetbrains.idea.svn.api.Target
import org.jetbrains.idea.svn.api.Url
import org.jetbrains.idea.svn.dialogs.WCInfo
import org.jetbrains.idea.svn.dialogs.WCInfoWithBranches
import org.jetbrains.idea.svn.history.SvnChangeList
import org.jetbrains.idea.svn.history.SvnRepositoryLocation
import org.jetbrains.idea.svn.integrate.MergeContext
import org.jetbrains.idea.svn.mergeinfo.BranchInfo
import org.jetbrains.idea.svn.mergeinfo.MergeCheckResult
import org.jetbrains.idea.svn.mergeinfo.OneShotMergeInfoHelper
import org.junit.Assert.*
import org.junit.Test
import java.io.File
private const val CONTENT1 = "123\n456\n123"
private const val CONTENT2 = "123\n456\n123\n4"
private fun assertRevisions(changeLists: List<SvnChangeList>, vararg expectedTopRevisions: Long) =
assertArrayEquals(expectedTopRevisions, changeLists.take(expectedTopRevisions.size).map { it.number }.toLongArray())
private fun newFile(parent: File, name: String) = File(parent, name).also { it.createNewFile() }
private fun newFolder(parent: String, name: String) = File(parent, name).also { it.mkdir() }
private fun newFolder(parent: File, name: String) = File(parent, name).also { it.mkdir() }
class SvnMergeInfoTest : SvnTestCase() {
private lateinit var myBranchVcsRoot: File
private lateinit var myOneShotMergeInfoHelper: OneShotMergeInfoHelper
private lateinit var myMergeChecker: BranchInfo
private lateinit var trunk: File
private lateinit var folder: File
private lateinit var f1: File
private lateinit var f2: File
private lateinit var myTrunkUrl: String
private lateinit var myBranchUrl: String
private val trunkChangeLists: List<SvnChangeList>
get() {
val provider = vcs.committedChangesProvider
return provider.getCommittedChanges(provider.createDefaultSettings(), SvnRepositoryLocation(parseUrl(myTrunkUrl, false)), 0)
}
override fun before() {
super.before()
myTrunkUrl = "$myRepoUrl/trunk"
myBranchUrl = "$myRepoUrl/branch"
myBranchVcsRoot = File(myTempDirFixture.tempDirPath, "branch")
myBranchVcsRoot.mkdir()
vcsManager.setDirectoryMapping(myBranchVcsRoot.absolutePath, SvnVcs.VCS_NAME)
val vcsRoot = LocalFileSystem.getInstance().findFileByIoFile(myBranchVcsRoot)
val node = Node(vcsRoot!!, createUrl(myBranchUrl), myRepositoryUrl)
val root = RootUrlInfo(node, WorkingCopyFormat.ONE_DOT_EIGHT, vcsRoot, null)
val wcInfo = WCInfo(root, true, Depth.INFINITY)
val mergeContext = MergeContext(vcs, parseUrl(myTrunkUrl, false), wcInfo, Url.tail(myTrunkUrl), vcsRoot)
myOneShotMergeInfoHelper = OneShotMergeInfoHelper(mergeContext)
vcs.svnConfiguration.isCheckNestedForQuickMerge = true
enableSilentOperation(VcsConfiguration.StandardConfirmation.ADD)
enableSilentOperation(VcsConfiguration.StandardConfirmation.REMOVE)
val wcInfoWithBranches = WCInfoWithBranches(wcInfo, emptyList<WCInfoWithBranches.Branch>(), vcsRoot,
WCInfoWithBranches.Branch(myRepositoryUrl.appendPath("trunk", false)))
myMergeChecker = BranchInfo(vcs, wcInfoWithBranches, WCInfoWithBranches.Branch(myRepositoryUrl.appendPath("branch", false)))
}
@Test
fun testSimpleNotMerged() {
createOneFolderStructure()
// rev 3
editAndCommit(trunk, f1)
assertMergeResult(trunkChangeLists, MergeCheckResult.NOT_MERGED)
}
@Test
fun testSimpleMerged() {
createOneFolderStructure()
// rev 3
editAndCommit(trunk, f1)
// rev 4: record as merged into branch
recordMerge(myBranchVcsRoot, myTrunkUrl, "-c", "3")
commitFile(myBranchVcsRoot)
updateFile(myBranchVcsRoot)
assertMergeInfo(myBranchVcsRoot, "/trunk:3")
assertMergeResult(trunkChangeLists, MergeCheckResult.MERGED)
}
@Test
fun testEmptyMergeinfoBlocks() {
createOneFolderStructure()
// rev 3
editAndCommit(trunk, f1)
// rev 4: record as merged into branch
merge(myBranchVcsRoot, myTrunkUrl, "-c", "3")
commitFile(myBranchVcsRoot)
updateFile(myBranchVcsRoot)
// rev5: put blocking empty mergeinfo
//runInAndVerifyIgnoreOutput("merge", "-c", "-3", myRepoUrl + "/trunk/folder", new File(myBranchVcsRoot, "folder").getAbsolutePath(), "--record-only"));
merge(File(myBranchVcsRoot, "folder"), "$myTrunkUrl/folder", "-r", "3:2")
commitFile(myBranchVcsRoot)
updateFile(myBranchVcsRoot)
assertMergeInfo(myBranchVcsRoot, "/trunk:3")
assertMergeInfo(File(myBranchVcsRoot, "folder"), "")
assertMergeResult(trunkChangeLists, MergeCheckResult.NOT_MERGED)
}
@Test
fun testNonInheritableMergeinfo() {
createOneFolderStructure()
// rev 3
editAndCommit(trunk, f1)
// rev 4: record non inheritable merge
setMergeInfo(myBranchVcsRoot, "/trunk:3*")
commitFile(myBranchVcsRoot)
updateFile(myBranchVcsRoot)
assertMergeInfo(myBranchVcsRoot, "/trunk:3*")
assertMergeResult(trunkChangeLists, MergeCheckResult.NOT_MERGED)
}
@Test
fun testOnlyImmediateInheritableMergeinfo() {
createOneFolderStructure()
// rev 3
editAndCommit(trunk, f1, CONTENT1)
// rev4
editAndCommit(trunk, f1, CONTENT2)
updateFile(myBranchVcsRoot)
// rev 4: record non inheritable merge
setMergeInfo(myBranchVcsRoot, "/trunk:3,4")
setMergeInfo(File(myBranchVcsRoot, "folder"), "/trunk:3")
commitFile(myBranchVcsRoot)
updateFile(myBranchVcsRoot)
assertMergeInfo(myBranchVcsRoot, "/trunk:3-4")
assertMergeInfo(File(myBranchVcsRoot, "folder"), "/trunk:3")
val changeLists = trunkChangeLists
assertRevisions(changeLists, 4, 3)
assertMergeResult(changeLists, MergeCheckResult.NOT_MERGED, MergeCheckResult.MERGED)
}
@Test
fun testTwoPaths() {
createTwoFolderStructure(myBranchVcsRoot)
// rev 3
editFile(f1)
editFile(f2)
commitFile(trunk)
updateFile(myBranchVcsRoot)
// rev 4: record non inheritable merge
setMergeInfo(myBranchVcsRoot, "/trunk:3")
// this makes not merged for f2 path
setMergeInfo(File(myBranchVcsRoot, "folder/folder1"), "/trunk:3*")
commitFile(myBranchVcsRoot)
updateFile(myBranchVcsRoot)
assertMergeInfo(myBranchVcsRoot, "/trunk:3")
assertMergeInfo(File(myBranchVcsRoot, "folder/folder1"), "/trunk:3*")
val changeListList = trunkChangeLists
assertRevisions(changeListList, 3)
assertMergeResult(changeListList, MergeCheckResult.NOT_MERGED)
}
@Test
fun testWhenInfoInRepo() {
val fullBranch = newFolder(myTempDirFixture.tempDirPath, "fullBranch")
createTwoFolderStructure(fullBranch)
// folder1 will be taken as branch wc root
checkOutFile("$myBranchUrl/folder/folder1", myBranchVcsRoot)
// rev 3 : f2 changed
editAndCommit(trunk, f2)
// rev 4: record as merged into branch using full branch WC
recordMerge(fullBranch, myTrunkUrl, "-c", "3")
commitFile(fullBranch)
updateFile(myBranchVcsRoot)
val changeListList = trunkChangeLists
assertRevisions(changeListList, 3)
assertMergeResult(changeListList[0], MergeCheckResult.MERGED)
}
@Test
fun testMixedWorkingRevisions() {
createOneFolderStructure()
// rev 3
editAndCommit(trunk, f1)
// rev 4: record non inheritable merge
setMergeInfo(myBranchVcsRoot, "/trunk:3")
commitFile(myBranchVcsRoot)
// ! no update!
assertMergeInfo(myBranchVcsRoot, "/trunk:3")
val f1info = vcs.getInfo(File(myBranchVcsRoot, "folder/f1.txt"))
assertEquals(2, f1info!!.revision.number)
val changeList = trunkChangeLists[0]
assertMergeResult(changeList, MergeCheckResult.NOT_MERGED)
// and after update
updateFile(myBranchVcsRoot)
myMergeChecker.clear()
assertMergeResult(changeList, MergeCheckResult.MERGED)
}
private fun createOneFolderStructure() {
trunk = newFolder(myTempDirFixture.tempDirPath, "trunk")
folder = newFolder(trunk, "folder")
f1 = newFile(folder, "f1.txt")
f2 = newFile(folder, "f2.txt")
importAndCheckOut(trunk)
}
private fun createTwoFolderStructure(branchFolder: File) {
trunk = newFolder(myTempDirFixture.tempDirPath, "trunk")
folder = newFolder(trunk, "folder")
f1 = newFile(folder, "f1.txt")
val folder1 = newFolder(folder, "folder1")
f2 = newFile(folder1, "f2.txt")
importAndCheckOut(trunk, branchFolder)
}
private fun importAndCheckOut(trunk: File, branch: File = myBranchVcsRoot) {
runInAndVerifyIgnoreOutput("import", "-m", "test", trunk.absolutePath, myTrunkUrl)
runInAndVerifyIgnoreOutput("copy", "-m", "test", myTrunkUrl, myBranchUrl)
FileUtil.delete(trunk)
checkOutFile(myTrunkUrl, trunk)
checkOutFile(myBranchUrl, branch)
}
private fun editAndCommit(trunk: File, file: File, content: String = CONTENT1) {
val vf = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(file)
editAndCommit(trunk, vf!!, content)
}
private fun editAndCommit(trunk: File, file: VirtualFile, content: String) {
editFileInCommand(file, content)
commitFile(trunk)
}
private fun editFile(file: File) {
val vf = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(file)
editFileInCommand(vf!!, CONTENT1)
}
private fun assertMergeInfo(file: File, expectedValue: String) {
val propertyValue = vcs.getFactory(file).createPropertyClient().getProperty(Target.on(file), MERGE_INFO, false, Revision.WORKING)
assertNotNull(propertyValue)
assertEquals(expectedValue, propertyValue!!.toString())
}
private fun assertMergeResult(changeLists: List<SvnChangeList>, vararg mergeResults: MergeCheckResult) {
myOneShotMergeInfoHelper.prepare()
for ((index, mergeResult) in mergeResults.withIndex()) {
assertMergeResult(changeLists[index], mergeResult)
assertMergeResultOneShot(changeLists[index], mergeResult)
}
}
private fun assertMergeResult(changeList: SvnChangeList, mergeResult: MergeCheckResult) =
assertEquals(mergeResult, myMergeChecker.checkList(changeList, myBranchVcsRoot.absolutePath))
private fun assertMergeResultOneShot(changeList: SvnChangeList, mergeResult: MergeCheckResult) =
assertEquals(mergeResult, myOneShotMergeInfoHelper.checkList(changeList))
private fun commitFile(file: File) = runInAndVerifyIgnoreOutput("ci", "-m", "test", file.absolutePath)
private fun updateFile(file: File) = runInAndVerifyIgnoreOutput("up", file.absolutePath)
private fun checkOutFile(url: String, directory: File) = runInAndVerifyIgnoreOutput("co", url, directory.absolutePath)
private fun setMergeInfo(file: File, value: String) = runInAndVerifyIgnoreOutput("propset", "svn:mergeinfo", value, file.absolutePath)
private fun merge(file: File, url: String, vararg revisions: String) = merge(file, url, false, *revisions)
private fun recordMerge(file: File, url: String, vararg revisions: String) = merge(file, url, true, *revisions)
private fun merge(file: File, url: String, recordOnly: Boolean, vararg revisions: String) {
val parameters = mutableListOf<String>("merge", *revisions, url, file.absolutePath)
if (recordOnly) {
parameters.add("--record-only")
}
runInAndVerifyIgnoreOutput(*parameters.toTypedArray())
}
}
| apache-2.0 | 375ac69a67647d74d098af87309a29f7 | 34.914634 | 156 | 0.746095 | 4.48591 | false | true | false | false |
smmribeiro/intellij-community | json/src/com/intellij/jsonpath/ui/JsonPathEvaluateIntentionAction.kt | 12 | 1687 | // 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.jsonpath.ui
import com.intellij.codeInsight.intention.AbstractIntentionAction
import com.intellij.codeInsight.intention.HighPriorityAction
import com.intellij.icons.AllIcons
import com.intellij.json.JsonBundle
import com.intellij.jsonpath.JsonPathLanguage
import com.intellij.jsonpath.ui.JsonPathEvaluateManager.Companion.JSON_PATH_EVALUATE_EXPRESSION_KEY
import com.intellij.lang.injection.InjectedLanguageManager
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Iconable
import com.intellij.psi.PsiFile
import javax.swing.Icon
internal class JsonPathEvaluateIntentionAction : AbstractIntentionAction(), HighPriorityAction, Iconable {
override fun getText(): String = JsonBundle.message("jsonpath.evaluate.intention")
override fun invoke(project: Project, editor: Editor?, file: PsiFile?) {
if (file == null) return
val manager = InjectedLanguageManager.getInstance(project)
val jsonPath = if (manager.isInjectedFragment(file)) {
manager.getUnescapedText(file)
}
else {
file.text
}
JsonPathEvaluateManager.getInstance(project).evaluateExpression(jsonPath)
}
override fun isAvailable(project: Project, editor: Editor?, file: PsiFile?): Boolean {
if (editor == null || file == null) return false
return file.language == JsonPathLanguage.INSTANCE
&& file.getUserData(JSON_PATH_EVALUATE_EXPRESSION_KEY) != true
}
override fun getIcon(flags: Int): Icon = AllIcons.FileTypes.Json
} | apache-2.0 | db34fb9b973aba84c731bc780aa0e020 | 39.190476 | 140 | 0.780676 | 4.474801 | false | false | false | false |
smmribeiro/intellij-community | plugins/github/src/org/jetbrains/plugins/github/pullrequest/data/GHPRFilesManagerImpl.kt | 3 | 3767 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.github.pullrequest.data
import com.intellij.diff.editor.DiffEditorTabFilesManager
import com.intellij.openapi.Disposable
import com.intellij.openapi.fileEditor.FileEditorManager
import com.intellij.openapi.fileEditor.ex.FileEditorManagerEx
import com.intellij.openapi.project.Project
import com.intellij.util.EventDispatcher
import com.intellij.util.containers.ContainerUtil
import org.jetbrains.plugins.github.api.GHRepositoryCoordinates
import org.jetbrains.plugins.github.api.data.pullrequest.GHPullRequestShort
import org.jetbrains.plugins.github.pullrequest.GHNewPRDiffVirtualFile
import org.jetbrains.plugins.github.pullrequest.GHPRDiffVirtualFile
import org.jetbrains.plugins.github.pullrequest.GHPRStatisticsCollector
import org.jetbrains.plugins.github.pullrequest.GHPRTimelineVirtualFile
import java.util.*
internal class GHPRFilesManagerImpl(private val project: Project,
private val repository: GHRepositoryCoordinates) : GHPRFilesManager {
// current time should be enough to distinguish the manager between launches
private val id = System.currentTimeMillis().toString()
private val filesEventDispatcher = EventDispatcher.create(FileListener::class.java)
private val files = ContainerUtil.createWeakValueMap<GHPRIdentifier, GHPRTimelineVirtualFile>()
private val diffFiles = ContainerUtil.createWeakValueMap<GHPRIdentifier, GHPRDiffVirtualFile>()
override val newPRDiffFile by lazy { GHNewPRDiffVirtualFile(id, project, repository) }
override fun createAndOpenTimelineFile(pullRequest: GHPRIdentifier, requestFocus: Boolean) {
files.getOrPut(SimpleGHPRIdentifier(pullRequest)) {
GHPRTimelineVirtualFile(id, project, repository, pullRequest)
}.let {
filesEventDispatcher.multicaster.onBeforeFileOpened(it)
FileEditorManager.getInstance(project).openFile(it, requestFocus)
GHPRStatisticsCollector.logTimelineOpened(project)
}
}
override fun createAndOpenDiffFile(pullRequest: GHPRIdentifier, requestFocus: Boolean) {
diffFiles.getOrPut(SimpleGHPRIdentifier(pullRequest)) {
GHPRDiffVirtualFile(id, project, repository, pullRequest)
}.let {
DiffEditorTabFilesManager.getInstance(project).showDiffFile(it, requestFocus)
GHPRStatisticsCollector.logDiffOpened(project)
}
}
override fun openNewPRDiffFile(requestFocus: Boolean) {
DiffEditorTabFilesManager.getInstance(project).showDiffFile(newPRDiffFile, requestFocus)
}
override fun findTimelineFile(pullRequest: GHPRIdentifier): GHPRTimelineVirtualFile? = files[SimpleGHPRIdentifier(pullRequest)]
override fun findDiffFile(pullRequest: GHPRIdentifier): GHPRDiffVirtualFile? = diffFiles[SimpleGHPRIdentifier(pullRequest)]
override fun updateTimelineFilePresentation(details: GHPullRequestShort) {
val file = findTimelineFile(details)
if (file != null) {
file.details = details
FileEditorManagerEx.getInstanceEx(project).updateFilePresentation(file)
}
}
override fun addBeforeTimelineFileOpenedListener(disposable: Disposable, listener: (file: GHPRTimelineVirtualFile) -> Unit) {
filesEventDispatcher.addListener(object : FileListener {
override fun onBeforeFileOpened(file: GHPRTimelineVirtualFile) = listener(file)
}, disposable)
}
override fun dispose() {
for (file in (files.values + diffFiles.values)) {
FileEditorManager.getInstance(project).closeFile(file)
file.isValid = false
}
}
private interface FileListener : EventListener {
fun onBeforeFileOpened(file: GHPRTimelineVirtualFile)
}
}
| apache-2.0 | 1568d0e9abe67dcbd1689b07e49ce518 | 44.939024 | 158 | 0.796124 | 4.904948 | false | false | false | false |
smmribeiro/intellij-community | platform/platform-impl/src/com/intellij/openapi/util/registry/RegistryToAdvancedSettingsMigration.kt | 8 | 3011 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.util.registry
import com.intellij.ide.util.PropertiesComponent
import com.intellij.openapi.application.ApplicationInfo
import com.intellij.openapi.editor.impl.TabCharacterPaintMode
import com.intellij.openapi.options.advanced.AdvancedSettingBean
import com.intellij.openapi.options.advanced.AdvancedSettings
import com.intellij.openapi.project.Project
import com.intellij.openapi.startup.StartupActivity
private class RegistryToAdvancedSettingsMigration : StartupActivity.DumbAware {
override fun runActivity(project: Project) {
val propertyName = "registry.to.advanced.settings.migration.build"
val lastMigratedVersion = PropertiesComponent.getInstance().getValue(propertyName)
val currentVersion = ApplicationInfo.getInstance().build.asString()
if (currentVersion != lastMigratedVersion) {
val userProperties = Registry.getInstance().userProperties
for (setting in AdvancedSettingBean.EP_NAME.extensions) {
if (setting.id == "editor.tab.painting") {
migrateEditorTabPainting(userProperties, setting)
continue
}
if (setting.id == "vcs.process.ignored") {
migrateVcsIgnoreProcessing(userProperties, setting)
continue
}
val userProperty = userProperties[setting.id] ?: continue
try {
AdvancedSettings.getInstance().setSetting(setting.id, setting.valueFromString(userProperty), setting.type())
userProperties.remove(setting.id)
}
catch (e: IllegalArgumentException) {
continue
}
}
PropertiesComponent.getInstance().setValue(propertyName, currentVersion)
}
}
private fun migrateEditorTabPainting(userProperties: MutableMap<String, String>, setting: AdvancedSettingBean) {
val mode = if (userProperties["editor.old.tab.painting"] == "true") {
userProperties.remove("editor.old.tab.painting")
TabCharacterPaintMode.LONG_ARROW
}
else if (userProperties["editor.arrow.tab.painting"] == "true") {
userProperties.remove("editor.arrow.tab.painting")
TabCharacterPaintMode.ARROW
}
else {
return
}
AdvancedSettings.getInstance().setSetting(setting.id, mode, setting.type())
}
private fun migrateVcsIgnoreProcessing(userProperties: MutableMap<String, String>, setting: AdvancedSettingBean) {
if (userProperties["git.process.ignored"] == "false") {
userProperties.remove("git.process.ignored")
}
else if (userProperties["hg4idea.process.ignored"] == "false") {
userProperties.remove("hg4idea.process.ignored")
}
else if (userProperties["p4.process.ignored"] == "false") {
userProperties.remove("p4.process.ignored")
}
else {
return
}
AdvancedSettings.getInstance().setSetting(setting.id, false, setting.type())
}
}
| apache-2.0 | bcc424e4f7a065ed772a1f58ed59d24b | 40.246575 | 158 | 0.720359 | 4.618098 | false | false | false | false |
anitawoodruff/habitica-android | Habitica/src/main/java/com/habitrpg/android/habitica/ui/viewHolders/ChatRecyclerViewHolder.kt | 1 | 10229 | package com.habitrpg.android.habitica.ui.viewHolders
import android.annotation.SuppressLint
import android.content.Context
import android.content.res.Resources
import android.graphics.drawable.BitmapDrawable
import android.text.method.LinkMovementMethod
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.LinearLayout
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.RecyclerView
import com.habitrpg.android.habitica.R
import com.habitrpg.android.habitica.extensions.dpToPx
import com.habitrpg.android.habitica.extensions.getAgoString
import com.habitrpg.android.habitica.extensions.setScaledPadding
import com.habitrpg.android.habitica.models.social.ChatMessage
import com.habitrpg.android.habitica.models.user.User
import com.habitrpg.android.habitica.ui.AvatarView
import com.habitrpg.android.habitica.ui.helpers.DataBindingUtils
import com.habitrpg.android.habitica.ui.helpers.MarkdownParser
import com.habitrpg.android.habitica.ui.helpers.bindView
import com.habitrpg.android.habitica.ui.views.HabiticaEmojiTextView
import com.habitrpg.android.habitica.ui.views.HabiticaIconsHelper
import com.habitrpg.android.habitica.ui.views.social.UsernameLabel
import io.reactivex.Maybe
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
class ChatRecyclerViewHolder(itemView: View, private var userId: String, private val isTavern: Boolean) : RecyclerView.ViewHolder(itemView) {
private val messageWrapper: ViewGroup by bindView(R.id.message_wrapper)
private val avatarView: AvatarView by bindView(R.id.avatar_view)
private val userLabel: UsernameLabel by bindView(R.id.user_label)
private val messageText: HabiticaEmojiTextView by bindView(R.id.message_text)
private val sublineTextView: TextView by bindView(R.id.subline_textview)
private val likeBackground: LinearLayout by bindView(R.id.like_background_layout)
private val tvLikes: TextView by bindView(R.id.tvLikes)
private val buttonsWrapper: ViewGroup by bindView(R.id.buttons_wrapper)
private val replyButton: Button by bindView(R.id.reply_button)
private val copyButton: Button by bindView(R.id.copy_button)
private val reportButton: Button by bindView(R.id.report_button)
private val deleteButton: Button by bindView(R.id.delete_button)
private val modView: TextView by bindView(R.id.mod_view)
val context: Context = itemView.context
val res: Resources = itemView.resources
private var chatMessage: ChatMessage? = null
private var user: User? = null
var onShouldExpand: (() -> Unit)? = null
var onLikeMessage: ((ChatMessage) -> Unit)? = null
var onOpenProfile: ((String) -> Unit)? = null
var onReply: ((String) -> Unit)? = null
var onCopyMessage: ((ChatMessage) -> Unit)? = null
var onFlagMessage: ((ChatMessage) -> Unit)? = null
var onDeleteMessage: ((ChatMessage) -> Unit)? = null
init {
itemView.setOnClickListener {
onShouldExpand?.invoke()
}
tvLikes.setOnClickListener { chatMessage?.let { onLikeMessage?.invoke(it) } }
messageText.setOnClickListener { onShouldExpand?.invoke() }
messageText.movementMethod = LinkMovementMethod.getInstance()
userLabel.setOnClickListener { chatMessage?.uuid?.let { onOpenProfile?.invoke(it) } }
avatarView.setOnClickListener { chatMessage?.uuid?.let { onOpenProfile?.invoke(it) } }
replyButton.setOnClickListener {
if (chatMessage?.username != null) {
chatMessage?.username?.let { onReply?.invoke(it) }
} else {
chatMessage?.user?.let { onReply?.invoke(it) }
}
}
replyButton.setCompoundDrawablesWithIntrinsicBounds(BitmapDrawable(res, HabiticaIconsHelper.imageOfChatReplyIcon()),
null, null, null)
copyButton.setOnClickListener { chatMessage?.let { onCopyMessage?.invoke(it) } }
copyButton.setCompoundDrawablesWithIntrinsicBounds(BitmapDrawable(res, HabiticaIconsHelper.imageOfChatCopyIcon()),
null, null, null)
reportButton.setOnClickListener { chatMessage?.let { onFlagMessage?.invoke(it) } }
reportButton.setCompoundDrawablesWithIntrinsicBounds(BitmapDrawable(res, HabiticaIconsHelper.imageOfChatReportIcon()),
null, null, null)
deleteButton.setOnClickListener { chatMessage?.let { onDeleteMessage?.invoke(it) } }
deleteButton.setCompoundDrawablesWithIntrinsicBounds(BitmapDrawable(res, HabiticaIconsHelper.imageOfChatDeleteIcon()),
null, null, null)
}
fun bind(msg: ChatMessage, uuid: String, user: User?, isExpanded: Boolean) {
chatMessage = msg
this.user = user
userId = uuid
setLikeProperties()
val wasSent = messageWasSent()
val name = user?.profile?.name
if (wasSent) {
userLabel.isNPC = user?.backer?.npc != null
userLabel.tier = user?.contributor?.level ?: 0
userLabel.username = name
if (user?.username != null) {
@SuppressLint("SetTextI18n")
sublineTextView.text = "${user.formattedUsername} ∙ ${msg.timestamp?.getAgoString(res)}"
} else {
sublineTextView.text = msg.timestamp?.getAgoString(res)
}
} else {
userLabel.isNPC = msg.backer?.npc != null
userLabel.tier = msg.contributor?.level ?: 0
userLabel.username = msg.user
if (msg.username != null) {
@SuppressLint("SetTextI18n")
sublineTextView.text = "${msg.formattedUsername} ∙ ${msg.timestamp?.getAgoString(res)}"
} else {
sublineTextView.text = msg.timestamp?.getAgoString(res)
}
}
when {
userLabel.tier == 8 -> {
modView.visibility = View.VISIBLE
modView.text = context.getString(R.string.moderator)
modView.background = ContextCompat.getDrawable(context, R.drawable.pill_bg_blue)
modView.setScaledPadding(context, 12, 4, 12, 4)
}
userLabel.tier == 9 -> {
modView.visibility = View.VISIBLE
modView.text = context.getString(R.string.staff)
modView.background = ContextCompat.getDrawable(context, R.drawable.pill_bg_purple_300)
modView.setScaledPadding(context, 12, 4, 12, 4)
}
else -> modView.visibility = View.GONE
}
if (wasSent) {
avatarView.visibility = View.GONE
itemView.setPadding(64.dpToPx(context), itemView.paddingTop, itemView.paddingRight, itemView.paddingBottom)
} else {
val displayMetrics = res.displayMetrics
val dpWidth = displayMetrics.widthPixels / displayMetrics.density
if (dpWidth > 350) {
avatarView.visibility = View.VISIBLE
msg.userStyles?.let {
avatarView.setAvatar(it)
}
} else {
avatarView.visibility = View.GONE
}
itemView.setPadding(16.dpToPx(context), itemView.paddingTop, itemView.paddingRight, itemView.paddingBottom)
}
messageText.text = chatMessage?.parsedText
if (msg.parsedText == null) {
messageText.text = chatMessage?.text
Maybe.just(chatMessage?.text ?: "")
.map { MarkdownParser.parseMarkdown(it) }
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe({ parsedText ->
chatMessage?.parsedText = parsedText
messageText.text = chatMessage?.parsedText
}, { it.printStackTrace() })
}
val username = user?.formattedUsername
messageWrapper.background = if ((name != null && msg.text?.contains("@$name") == true) || (username != null && msg.text?.contains(username) == true)) {
ContextCompat.getDrawable(context, R.drawable.layout_rounded_bg_brand_700)
} else {
ContextCompat.getDrawable(context, R.drawable.layout_rounded_bg)
}
messageWrapper.setScaledPadding(context, 8, 8, 8, 8)
if (isExpanded) {
buttonsWrapper.visibility = View.VISIBLE
deleteButton.visibility = if (shouldShowDelete()) View.VISIBLE else View.GONE
replyButton.visibility = if (chatMessage?.isInboxMessage == true) View.GONE else View.VISIBLE
} else {
buttonsWrapper.visibility = View.GONE
}
}
private fun messageWasSent(): Boolean {
return chatMessage?.sent == true || chatMessage?.uuid == userId
}
private fun setLikeProperties() {
likeBackground.visibility = if (isTavern) View.VISIBLE else View.INVISIBLE
@SuppressLint("SetTextI18n")
tvLikes.text = "+" + chatMessage?.likeCount
val backgroundColorRes: Int
val foregroundColorRes: Int
if (chatMessage?.likeCount != 0) {
if (chatMessage?.userLikesMessage(userId) == true) {
backgroundColorRes = R.color.tavern_userliked_background
foregroundColorRes = R.color.tavern_userliked_foreground
} else {
backgroundColorRes = R.color.tavern_somelikes_background
foregroundColorRes = R.color.tavern_somelikes_foreground
}
} else {
backgroundColorRes = R.color.tavern_nolikes_background
foregroundColorRes = R.color.tavern_nolikes_foreground
}
DataBindingUtils.setRoundedBackground(likeBackground, ContextCompat.getColor(context, backgroundColorRes))
tvLikes.setTextColor(ContextCompat.getColor(context, foregroundColorRes))
}
private fun shouldShowDelete(): Boolean {
return chatMessage?.isSystemMessage != true && (chatMessage?.uuid == userId || user?.contributor?.admin == true || chatMessage?.isInboxMessage == true)
}
} | gpl-3.0 | 18a5a7a81f7046d57d89795c42d5ae1d | 46.342593 | 159 | 0.663178 | 4.662563 | false | false | false | false |
ozbek/quran_android | app/src/main/java/com/quran/labs/androidquran/worker/MissingPageDownloadWorker.kt | 2 | 3858 | package com.quran.labs.androidquran.worker
import android.content.Context
import androidx.work.CoroutineWorker
import androidx.work.ListenableWorker
import androidx.work.WorkerParameters
import com.quran.data.core.QuranInfo
import com.quran.labs.androidquran.core.worker.WorkerTaskFactory
import com.quran.labs.androidquran.util.QuranFileUtils
import com.quran.labs.androidquran.util.QuranScreenInfo
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.flow.asFlow
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.toList
import okhttp3.OkHttpClient
import timber.log.Timber
import java.io.File
import javax.inject.Inject
class MissingPageDownloadWorker(private val context: Context,
params: WorkerParameters,
private val okHttpClient: OkHttpClient,
private val quranInfo: QuranInfo,
private val quranScreenInfo: QuranScreenInfo,
private val quranFileUtils: QuranFileUtils
) : CoroutineWorker(context, params) {
override suspend fun doWork(): Result = coroutineScope {
Timber.d("MissingPageDownloadWorker")
val pagesToDownload = findMissingPagesToDownload()
Timber.d("MissingPageDownloadWorker found $pagesToDownload missing pages")
if (pagesToDownload.size < MISSING_PAGE_LIMIT) {
// attempt to download missing pages
val results = pagesToDownload.asFlow()
.map { downloadPage(it) }
.flowOn(Dispatchers.IO)
.toList()
val failures = results.count { !it }
if (failures > 0) {
Timber.d("MissingPageWorker failed with $failures from ${pagesToDownload.size}")
} else {
Timber.d("MissingPageWorker success with ${pagesToDownload.size}")
}
}
Result.success()
}
private fun findMissingPagesToDownload(): List<PageToDownload> {
val width = quranScreenInfo.widthParam
val result = findMissingPagesForWidth(width)
val tabletWidth = quranScreenInfo.tabletWidthParam
return if (width == tabletWidth) {
result
} else {
result + findMissingPagesForWidth(tabletWidth)
}
}
private fun findMissingPagesForWidth(width: String): List<PageToDownload> {
val result = mutableListOf<PageToDownload>()
val pagesDirectory = File(quranFileUtils.getQuranImagesDirectory(context, width))
for (page in 1..quranInfo.numberOfPages) {
val pageFile = QuranFileUtils.getPageFileName(page)
if (!File(pagesDirectory, pageFile).exists()) {
result.add(PageToDownload(width, page))
}
}
return result
}
data class PageToDownload(val width: String, val page: Int)
private fun downloadPage(pageToDownload: PageToDownload): Boolean {
Timber.d("downloading ${pageToDownload.page} for ${pageToDownload.width} - thread: %s",
Thread.currentThread().name)
val pageName = QuranFileUtils.getPageFileName(pageToDownload.page)
return try {
quranFileUtils.getImageFromWeb(okHttpClient, context, pageToDownload.width, pageName)
.isSuccessful
} catch (throwable: Throwable) {
false
}
}
class Factory @Inject constructor(
private val quranInfo: QuranInfo,
private val quranFileUtils: QuranFileUtils,
private val quranScreenInfo: QuranScreenInfo,
private val okHttpClient: OkHttpClient
) : WorkerTaskFactory {
override fun makeWorker(
appContext: Context,
workerParameters: WorkerParameters
): ListenableWorker {
return MissingPageDownloadWorker(
appContext, workerParameters, okHttpClient, quranInfo, quranScreenInfo, quranFileUtils
)
}
}
companion object {
private const val MISSING_PAGE_LIMIT = 50
}
}
| gpl-3.0 | e2376f7095309389a68b8d4af46937e4 | 34.394495 | 96 | 0.71099 | 4.722154 | false | false | false | false |
jotomo/AndroidAPS | danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Bolus_Set_Extended_Bolus.kt | 1 | 1436 | package info.nightscout.androidaps.danars.comm
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.logging.LTag
import info.nightscout.androidaps.danars.encryption.BleEncryption
class DanaRS_Packet_Bolus_Set_Extended_Bolus(
injector: HasAndroidInjector,
private var extendedAmount: Double = 0.0,
private var extendedBolusDurationInHalfHours: Int = 0
) : DanaRS_Packet(injector) {
init {
opCode = BleEncryption.DANAR_PACKET__OPCODE_BOLUS__SET_EXTENDED_BOLUS
aapsLogger.debug(LTag.PUMPCOMM, "Extended bolus start : $extendedAmount U halfhours: $extendedBolusDurationInHalfHours")
}
override fun getRequestParams(): ByteArray {
val extendedBolusRate = (extendedAmount * 100.0).toInt()
val request = ByteArray(3)
request[0] = (extendedBolusRate and 0xff).toByte()
request[1] = (extendedBolusRate ushr 8 and 0xff).toByte()
request[2] = (extendedBolusDurationInHalfHours and 0xff).toByte()
return request
}
override fun handleMessage(data: ByteArray) {
val result = intFromBuff(data, 0, 1)
if (result == 0) {
aapsLogger.debug(LTag.PUMPCOMM, "Result OK")
failed = false
} else {
aapsLogger.error("Result Error: $result")
failed = true
}
}
override fun getFriendlyName(): String {
return "BOLUS__SET_EXTENDED_BOLUS"
}
} | agpl-3.0 | 5707f8221c07fe2efac6017b774c43ca | 34.04878 | 128 | 0.676184 | 4.338369 | false | false | false | false |
jotomo/AndroidAPS | danars/src/main/java/info/nightscout/androidaps/danars/services/DanaRSService.kt | 1 | 24091 | package info.nightscout.androidaps.danars.services
import android.app.Service
import android.content.Context
import android.content.Intent
import android.os.Binder
import android.os.IBinder
import android.os.SystemClock
import dagger.android.DaggerService
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.Constants
import info.nightscout.androidaps.activities.ErrorHelperActivity
import info.nightscout.androidaps.dana.DanaPump
import info.nightscout.androidaps.dana.comm.RecordTypes
import info.nightscout.androidaps.dana.events.EventDanaRNewStatus
import info.nightscout.androidaps.danars.DanaRSPlugin
import info.nightscout.androidaps.danars.R
import info.nightscout.androidaps.danars.comm.*
import info.nightscout.androidaps.data.Profile
import info.nightscout.androidaps.data.PumpEnactResult
import info.nightscout.androidaps.db.Treatment
import info.nightscout.androidaps.dialogs.BolusProgressDialog
import info.nightscout.androidaps.events.EventAppExit
import info.nightscout.androidaps.events.EventInitializationChanged
import info.nightscout.androidaps.events.EventProfileNeedsUpdate
import info.nightscout.androidaps.events.EventPumpStatusChanged
import info.nightscout.androidaps.interfaces.ActivePluginProvider
import info.nightscout.androidaps.interfaces.CommandQueueProvider
import info.nightscout.androidaps.interfaces.ProfileFunction
import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.logging.LTag
import info.nightscout.androidaps.plugins.bus.RxBusWrapper
import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker
import info.nightscout.androidaps.plugins.general.nsclient.NSUpload
import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification
import info.nightscout.androidaps.plugins.general.overview.events.EventOverviewBolusProgress
import info.nightscout.androidaps.plugins.general.overview.notifications.Notification
import info.nightscout.androidaps.plugins.pump.common.bolusInfo.DetailedBolusInfoStorage
import info.nightscout.androidaps.queue.Callback
import info.nightscout.androidaps.queue.commands.Command
import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.utils.FabricPrivacy
import info.nightscout.androidaps.utils.T
import info.nightscout.androidaps.utils.resources.ResourceHelper
import info.nightscout.androidaps.utils.sharedPreferences.SP
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.schedulers.Schedulers
import org.joda.time.DateTime
import org.joda.time.DateTimeZone
import java.util.concurrent.TimeUnit
import javax.inject.Inject
import kotlin.math.abs
import kotlin.math.min
class DanaRSService : DaggerService() {
@Inject lateinit var injector: HasAndroidInjector
@Inject lateinit var aapsLogger: AAPSLogger
@Inject lateinit var rxBus: RxBusWrapper
@Inject lateinit var sp: SP
@Inject lateinit var resourceHelper: ResourceHelper
@Inject lateinit var profileFunction: ProfileFunction
@Inject lateinit var commandQueue: CommandQueueProvider
@Inject lateinit var context: Context
@Inject lateinit var danaRSPlugin: DanaRSPlugin
@Inject lateinit var danaPump: DanaPump
@Inject lateinit var danaRSMessageHashTable: DanaRSMessageHashTable
@Inject lateinit var activePlugin: ActivePluginProvider
@Inject lateinit var constraintChecker: ConstraintChecker
@Inject lateinit var detailedBolusInfoStorage: DetailedBolusInfoStorage
@Inject lateinit var bleComm: BLEComm
@Inject lateinit var fabricPrivacy: FabricPrivacy
@Inject lateinit var nsUpload: NSUpload
@Inject lateinit var dateUtil: DateUtil
private val disposable = CompositeDisposable()
private val mBinder: IBinder = LocalBinder()
private var lastHistoryFetched: Long = 0
private var lastApproachingDailyLimit: Long = 0
override fun onCreate() {
super.onCreate()
disposable.add(rxBus
.toObservable(EventAppExit::class.java)
.observeOn(Schedulers.io())
.subscribe({ stopSelf() }) { fabricPrivacy.logException(it) }
)
}
override fun onDestroy() {
disposable.clear()
super.onDestroy()
}
val isConnected: Boolean
get() = bleComm.isConnected
val isConnecting: Boolean
get() = bleComm.isConnecting
fun connect(from: String, address: String): Boolean {
return bleComm.connect(from, address)
}
fun stopConnecting() {
bleComm.stopConnecting()
}
fun disconnect(from: String) {
bleComm.disconnect(from)
}
fun sendMessage(message: DanaRS_Packet) {
bleComm.sendMessage(message)
}
fun readPumpStatus() {
try {
val pump = activePlugin.activePump
rxBus.send(EventPumpStatusChanged(resourceHelper.gs(R.string.gettingpumpsettings)))
sendMessage(DanaRS_Packet_Etc_Keep_Connection(injector)) // test encryption for v3
sendMessage(DanaRS_Packet_General_Get_Shipping_Information(injector)) // serial no
sendMessage(DanaRS_Packet_General_Get_Pump_Check(injector)) // firmware
sendMessage(DanaRS_Packet_Basal_Get_Profile_Number(injector))
sendMessage(DanaRS_Packet_Bolus_Get_Bolus_Option(injector)) // isExtendedEnabled
sendMessage(DanaRS_Packet_Basal_Get_Basal_Rate(injector)) // basal profile, basalStep, maxBasal
sendMessage(DanaRS_Packet_Bolus_Get_Calculation_Information(injector)) // target
if (danaPump.profile24) sendMessage(DanaRS_Packet_Bolus_Get_24_CIR_CF_Array(injector))
else sendMessage(DanaRS_Packet_Bolus_Get_CIR_CF_Array(injector))
sendMessage(DanaRS_Packet_Option_Get_User_Option(injector)) // Getting user options
rxBus.send(EventPumpStatusChanged(resourceHelper.gs(R.string.gettingpumpstatus)))
sendMessage(DanaRS_Packet_General_Initial_Screen_Information(injector))
rxBus.send(EventPumpStatusChanged(resourceHelper.gs(R.string.gettingextendedbolusstatus)))
sendMessage(DanaRS_Packet_Bolus_Get_Extended_Bolus_State(injector))
rxBus.send(EventPumpStatusChanged(resourceHelper.gs(R.string.gettingbolusstatus)))
sendMessage(DanaRS_Packet_Bolus_Get_Step_Bolus_Information(injector)) // last bolus, bolusStep, maxBolus
rxBus.send(EventPumpStatusChanged(resourceHelper.gs(R.string.gettingtempbasalstatus)))
sendMessage(DanaRS_Packet_Basal_Get_Temporary_Basal_State(injector))
danaPump.lastConnection = System.currentTimeMillis()
val profile = profileFunction.getProfile()
if (profile != null && abs(danaPump.currentBasal - profile.basal) >= pump.pumpDescription.basalStep) {
rxBus.send(EventPumpStatusChanged(resourceHelper.gs(R.string.gettingpumpsettings)))
sendMessage(DanaRS_Packet_Basal_Get_Basal_Rate(injector)) // basal profile, basalStep, maxBasal
if (!pump.isThisProfileSet(profile) && !commandQueue.isRunning(Command.CommandType.BASAL_PROFILE)) {
rxBus.send(EventProfileNeedsUpdate())
}
}
rxBus.send(EventPumpStatusChanged(resourceHelper.gs(R.string.gettingpumptime)))
if (danaPump.usingUTC) sendMessage(DanaRS_Packet_Option_Get_Pump_UTC_And_TimeZone(injector))
else sendMessage(DanaRS_Packet_Option_Get_Pump_Time(injector))
var timeDiff = (danaPump.getPumpTime() - System.currentTimeMillis()) / 1000L
if (danaPump.getPumpTime() == 0L) {
// initial handshake was not successful
// de-initialize pump
danaPump.reset()
rxBus.send(EventDanaRNewStatus())
rxBus.send(EventInitializationChanged())
return
}
aapsLogger.debug(LTag.PUMPCOMM, "Pump time difference: $timeDiff seconds")
// phone timezone
val tz = DateTimeZone.getDefault()
val instant = DateTime.now().millis
val offsetInMilliseconds = tz.getOffset(instant).toLong()
val offset = TimeUnit.MILLISECONDS.toHours(offsetInMilliseconds).toInt()
if (abs(timeDiff) > 3 || danaPump.usingUTC && offset != danaPump.zoneOffset) {
if (abs(timeDiff) > 60 * 60 * 1.5) {
aapsLogger.debug(LTag.PUMPCOMM, "Pump time difference: $timeDiff seconds - large difference")
//If time-diff is very large, warn user until we can synchronize history readings properly
val i = Intent(context, ErrorHelperActivity::class.java)
i.putExtra("soundid", R.raw.error)
i.putExtra("status", resourceHelper.gs(R.string.largetimediff))
i.putExtra("title", resourceHelper.gs(R.string.largetimedifftitle))
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
context.startActivity(i)
//de-initialize pump
danaPump.reset()
rxBus.send(EventDanaRNewStatus())
rxBus.send(EventInitializationChanged())
return
} else {
if (danaPump.usingUTC) {
sendMessage(DanaRS_Packet_Option_Set_Pump_UTC_And_TimeZone(injector, DateUtil.now(), offset))
} else if (danaPump.protocol >= 6) { // can set seconds
sendMessage(DanaRS_Packet_Option_Set_Pump_Time(injector, DateUtil.now()))
} else {
waitForWholeMinute() // Dana can set only whole minute
// add 10sec to be sure we are over minute (will be cut off anyway)
sendMessage(DanaRS_Packet_Option_Set_Pump_Time(injector, DateUtil.now() + T.secs(10).msecs()))
}
if (danaPump.usingUTC) sendMessage(DanaRS_Packet_Option_Get_Pump_UTC_And_TimeZone(injector))
else sendMessage(DanaRS_Packet_Option_Get_Pump_Time(injector))
timeDiff = (danaPump.getPumpTime() - System.currentTimeMillis()) / 1000L
aapsLogger.debug(LTag.PUMPCOMM, "Pump time difference: $timeDiff seconds")
}
}
loadEvents()
rxBus.send(EventDanaRNewStatus())
rxBus.send(EventInitializationChanged())
//NSUpload.uploadDeviceStatus();
if (danaPump.dailyTotalUnits > danaPump.maxDailyTotalUnits * Constants.dailyLimitWarning) {
aapsLogger.debug(LTag.PUMPCOMM, "Approaching daily limit: " + danaPump.dailyTotalUnits + "/" + danaPump.maxDailyTotalUnits)
if (System.currentTimeMillis() > lastApproachingDailyLimit + 30 * 60 * 1000) {
val reportFail = Notification(Notification.APPROACHING_DAILY_LIMIT, resourceHelper.gs(R.string.approachingdailylimit), Notification.URGENT)
rxBus.send(EventNewNotification(reportFail))
nsUpload.uploadError(resourceHelper.gs(R.string.approachingdailylimit) + ": " + danaPump.dailyTotalUnits + "/" + danaPump.maxDailyTotalUnits + "U")
lastApproachingDailyLimit = System.currentTimeMillis()
}
}
} catch (e: Exception) {
aapsLogger.error(LTag.PUMPCOMM, "Unhandled exception", e)
}
aapsLogger.debug(LTag.PUMPCOMM, "Pump status loaded")
}
fun loadEvents(): PumpEnactResult {
if (!danaRSPlugin.isInitialized) {
val result = PumpEnactResult(injector).success(false)
result.comment = "pump not initialized"
return result
}
SystemClock.sleep(1000)
val msg: DanaRS_Packet_APS_History_Events
if (lastHistoryFetched == 0L) {
msg = DanaRS_Packet_APS_History_Events(injector, 0)
aapsLogger.debug(LTag.PUMPCOMM, "Loading complete event history")
} else {
msg = DanaRS_Packet_APS_History_Events(injector, lastHistoryFetched)
aapsLogger.debug(LTag.PUMPCOMM, "Loading event history from: " + dateUtil.dateAndTimeString(lastHistoryFetched))
}
sendMessage(msg)
while (!danaPump.historyDoneReceived && bleComm.isConnected) {
SystemClock.sleep(100)
}
lastHistoryFetched = if (danaPump.lastEventTimeLoaded != 0L) danaPump.lastEventTimeLoaded - T.mins(1).msecs() else 0
aapsLogger.debug(LTag.PUMPCOMM, "Events loaded")
danaPump.lastConnection = System.currentTimeMillis()
return PumpEnactResult(injector).success(msg.success())
}
fun setUserSettings(): PumpEnactResult {
val message = DanaRS_Packet_Option_Set_User_Option(injector)
sendMessage(message)
return PumpEnactResult(injector).success(message.success())
}
fun bolus(insulin: Double, carbs: Int, carbTime: Long, t: Treatment): Boolean {
if (!isConnected) return false
if (BolusProgressDialog.stopPressed) return false
rxBus.send(EventPumpStatusChanged(resourceHelper.gs(R.string.startingbolus)))
val preferencesSpeed = sp.getInt(R.string.key_danars_bolusspeed, 0)
danaPump.bolusDone = false
danaPump.bolusingTreatment = t
danaPump.bolusAmountToBeDelivered = insulin
danaPump.bolusStopped = false
danaPump.bolusStopForced = false
danaPump.bolusProgressLastTimeStamp = DateUtil.now()
val start = DanaRS_Packet_Bolus_Set_Step_Bolus_Start(injector, insulin, preferencesSpeed)
if (carbs > 0) {
// MsgSetCarbsEntry msg = new MsgSetCarbsEntry(carbTime, carbs); ####
// sendMessage(msg);
val msgSetHistoryEntryV2 = DanaRS_Packet_APS_Set_Event_History(injector, DanaPump.CARBS, carbTime, carbs, 0)
sendMessage(msgSetHistoryEntryV2)
lastHistoryFetched = min(lastHistoryFetched, carbTime - T.mins(1).msecs())
}
val bolusStart = System.currentTimeMillis()
if (insulin > 0) {
if (!danaPump.bolusStopped) {
sendMessage(start)
} else {
t.insulin = 0.0
return false
}
while (!danaPump.bolusStopped && !start.failed && !danaPump.bolusDone) {
SystemClock.sleep(100)
if (System.currentTimeMillis() - danaPump.bolusProgressLastTimeStamp > 15 * 1000L) { // if i didn't receive status for more than 20 sec expecting broken comm
danaPump.bolusStopped = true
danaPump.bolusStopForced = true
aapsLogger.debug(LTag.PUMPCOMM, "Communication stopped")
bleComm.disconnect("Communication stopped")
}
}
}
val bolusingEvent = EventOverviewBolusProgress
bolusingEvent.t = t
bolusingEvent.percent = 99
danaPump.bolusingTreatment = null
var speed = 12
when (preferencesSpeed) {
0 -> speed = 12
1 -> speed = 30
2 -> speed = 60
}
val bolusDurationInMSec = (insulin * speed * 1000).toLong()
val expectedEnd = bolusStart + bolusDurationInMSec + 2000
while (System.currentTimeMillis() < expectedEnd) {
val waitTime = expectedEnd - System.currentTimeMillis()
bolusingEvent.status = String.format(resourceHelper.gs(R.string.waitingforestimatedbolusend), waitTime / 1000)
rxBus.send(bolusingEvent)
SystemClock.sleep(1000)
}
// do not call loadEvents() directly, reconnection may be needed
commandQueue.loadEvents(object : Callback() {
override fun run() {
// reread bolus status
rxBus.send(EventPumpStatusChanged(resourceHelper.gs(R.string.gettingbolusstatus)))
sendMessage(DanaRS_Packet_Bolus_Get_Step_Bolus_Information(injector)) // last bolus
bolusingEvent.percent = 100
rxBus.send(EventPumpStatusChanged(resourceHelper.gs(R.string.disconnecting)))
}
})
return !start.failed
}
fun bolusStop() {
aapsLogger.debug(LTag.PUMPCOMM, "bolusStop >>>>> @ " + if (danaPump.bolusingTreatment == null) "" else danaPump.bolusingTreatment?.insulin)
val stop = DanaRS_Packet_Bolus_Set_Step_Bolus_Stop(injector)
danaPump.bolusStopForced = true
if (isConnected) {
sendMessage(stop)
while (!danaPump.bolusStopped) {
sendMessage(stop)
SystemClock.sleep(200)
}
} else {
danaPump.bolusStopped = true
}
}
fun tempBasal(percent: Int, durationInHours: Int): Boolean {
if (!isConnected) return false
if (danaPump.isTempBasalInProgress) {
rxBus.send(EventPumpStatusChanged(resourceHelper.gs(R.string.stoppingtempbasal)))
sendMessage(DanaRS_Packet_Basal_Set_Cancel_Temporary_Basal(injector))
SystemClock.sleep(500)
}
rxBus.send(EventPumpStatusChanged(resourceHelper.gs(R.string.settingtempbasal)))
val msgTBR = DanaRS_Packet_Basal_Set_Temporary_Basal(injector, percent, durationInHours)
sendMessage(msgTBR)
SystemClock.sleep(200)
sendMessage(DanaRS_Packet_Basal_Get_Temporary_Basal_State(injector))
loadEvents()
rxBus.send(EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTING))
return msgTBR.success()
}
fun highTempBasal(percent: Int): Boolean {
if (danaPump.isTempBasalInProgress) {
rxBus.send(EventPumpStatusChanged(resourceHelper.gs(R.string.stoppingtempbasal)))
sendMessage(DanaRS_Packet_Basal_Set_Cancel_Temporary_Basal(injector))
SystemClock.sleep(500)
}
rxBus.send(EventPumpStatusChanged(resourceHelper.gs(R.string.settingtempbasal)))
val msgTBR = DanaRS_Packet_APS_Basal_Set_Temporary_Basal(injector, percent)
sendMessage(msgTBR)
sendMessage(DanaRS_Packet_Basal_Get_Temporary_Basal_State(injector))
loadEvents()
rxBus.send(EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTING))
return msgTBR.success()
}
fun tempBasalShortDuration(percent: Int, durationInMinutes: Int): Boolean {
if (durationInMinutes != 15 && durationInMinutes != 30) {
aapsLogger.error(LTag.PUMPCOMM, "Wrong duration param")
return false
}
if (danaPump.isTempBasalInProgress) {
rxBus.send(EventPumpStatusChanged(resourceHelper.gs(R.string.stoppingtempbasal)))
sendMessage(DanaRS_Packet_Basal_Set_Cancel_Temporary_Basal(injector))
SystemClock.sleep(500)
}
rxBus.send(EventPumpStatusChanged(resourceHelper.gs(R.string.settingtempbasal)))
val msgTBR = DanaRS_Packet_APS_Basal_Set_Temporary_Basal(injector, percent)
sendMessage(msgTBR)
sendMessage(DanaRS_Packet_Basal_Get_Temporary_Basal_State(injector))
loadEvents()
rxBus.send(EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTING))
return msgTBR.success()
}
fun tempBasalStop(): Boolean {
if (!isConnected) return false
rxBus.send(EventPumpStatusChanged(resourceHelper.gs(R.string.stoppingtempbasal)))
val msgCancel = DanaRS_Packet_Basal_Set_Cancel_Temporary_Basal(injector)
sendMessage(msgCancel)
sendMessage(DanaRS_Packet_Basal_Get_Temporary_Basal_State(injector))
loadEvents()
rxBus.send(EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTING))
return msgCancel.success()
}
fun extendedBolus(insulin: Double, durationInHalfHours: Int): Boolean {
if (!isConnected) return false
rxBus.send(EventPumpStatusChanged(resourceHelper.gs(R.string.settingextendedbolus)))
val msgExtended = DanaRS_Packet_Bolus_Set_Extended_Bolus(injector, insulin, durationInHalfHours)
sendMessage(msgExtended)
SystemClock.sleep(200)
sendMessage(DanaRS_Packet_Bolus_Get_Extended_Bolus_State(injector))
loadEvents()
rxBus.send(EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTING))
return msgExtended.success()
}
fun extendedBolusStop(): Boolean {
if (!isConnected) return false
rxBus.send(EventPumpStatusChanged(resourceHelper.gs(R.string.stoppingextendedbolus)))
val msgStop = DanaRS_Packet_Bolus_Set_Extended_Bolus_Cancel(injector)
sendMessage(msgStop)
sendMessage(DanaRS_Packet_Bolus_Get_Extended_Bolus_State(injector))
loadEvents()
rxBus.send(EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTING))
return msgStop.success()
}
fun updateBasalsInPump(profile: Profile): Boolean {
if (!isConnected) return false
rxBus.send(EventPumpStatusChanged(resourceHelper.gs(R.string.updatingbasalrates)))
val basal = danaPump.buildDanaRProfileRecord(profile)
val msgSet = DanaRS_Packet_Basal_Set_Profile_Basal_Rate(injector, 0, basal)
sendMessage(msgSet)
val msgActivate = DanaRS_Packet_Basal_Set_Profile_Number(injector, 0)
sendMessage(msgActivate)
if (danaPump.profile24) {
val msgProfile = DanaRS_Packet_Bolus_Set_24_CIR_CF_Array(injector, profile)
sendMessage(msgProfile)
}
readPumpStatus()
rxBus.send(EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTING))
return msgSet.success()
}
fun loadHistory(type: Byte): PumpEnactResult {
val result = PumpEnactResult(injector)
if (!isConnected) return result
var msg: DanaRS_Packet_History_? = null
when (type) {
RecordTypes.RECORD_TYPE_ALARM -> msg = DanaRS_Packet_History_Alarm(injector)
RecordTypes.RECORD_TYPE_PRIME -> msg = DanaRS_Packet_History_Prime(injector)
RecordTypes.RECORD_TYPE_BASALHOUR -> msg = DanaRS_Packet_History_Basal(injector)
RecordTypes.RECORD_TYPE_BOLUS -> msg = DanaRS_Packet_History_Bolus(injector)
RecordTypes.RECORD_TYPE_CARBO -> msg = DanaRS_Packet_History_Carbohydrate(injector)
RecordTypes.RECORD_TYPE_DAILY -> msg = DanaRS_Packet_History_Daily(injector)
RecordTypes.RECORD_TYPE_GLUCOSE -> msg = DanaRS_Packet_History_Blood_Glucose(injector)
RecordTypes.RECORD_TYPE_REFILL -> msg = DanaRS_Packet_History_Refill(injector)
RecordTypes.RECORD_TYPE_SUSPEND -> msg = DanaRS_Packet_History_Suspend(injector)
}
if (msg != null) {
sendMessage(DanaRS_Packet_General_Set_History_Upload_Mode(injector, 1))
SystemClock.sleep(200)
sendMessage(msg)
while (!msg.done && isConnected) {
SystemClock.sleep(100)
}
SystemClock.sleep(200)
sendMessage(DanaRS_Packet_General_Set_History_Upload_Mode(injector, 0))
}
result.success = msg?.success() ?: false
return result
}
inner class LocalBinder : Binder() {
val serviceInstance: DanaRSService
get() = this@DanaRSService
}
override fun onBind(intent: Intent): IBinder {
return mBinder
}
override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int {
return Service.START_STICKY
}
private fun waitForWholeMinute() {
while (true) {
val time = DateUtil.now()
val timeToWholeMinute = 60000 - time % 60000
if (timeToWholeMinute > 59800 || timeToWholeMinute < 300) break
rxBus.send(EventPumpStatusChanged(resourceHelper.gs(R.string.waitingfortimesynchronization, (timeToWholeMinute / 1000).toInt())))
SystemClock.sleep(min(timeToWholeMinute, 100))
}
}
} | agpl-3.0 | 2b24a24876aefe8f7e1a4ef1db2c13f6 | 48.879917 | 173 | 0.674982 | 4.693357 | false | false | false | false |
cout970/Modeler | src/main/kotlin/com/cout970/modeler/util/collections/FloatArrayList.kt | 1 | 6994 | package com.cout970.modeler.util.collections
import java.util.*
/**
* Created by cout970 on 2017/05/17.
*/
fun listOf(vararg values: Float) = FloatArrayList(values)
class FloatArrayList internal constructor(private var array: FloatArray) : MutableList<Float>, RandomAccess {
override var size: Int = 0
private set
private var modCount = 0
constructor(capacity: Int = 10) : this(FloatArray(capacity))
internal fun internalArray(): FloatArray = array
override fun contains(element: Float): Boolean {
repeat(size) {
if (array[it] == element) return true
}
return false
}
override fun containsAll(elements: Collection<Float>): Boolean {
return elements.all { contains(it) }
}
override fun get(index: Int): Float {
require(index in 0 until size) { "Index $index outside bounds (0, $size)" }
return array[index]
}
override fun indexOf(element: Float): Int {
repeat(size) {
if (array[it] == element) return it
}
return -1
}
override fun isEmpty(): Boolean = size == 0
override fun iterator(): MutableIterator<Float> = Itr()
override fun lastIndexOf(element: Float): Int {
repeat(size) { i ->
val index = (size - 1) - i
if (array[index] == element) return index
}
return -1
}
override fun add(element: Float): Boolean {
modCount++
if (array.size == size) {
growArray()
}
array[size] = element
size++
return true
}
private fun growArray() {
val newArray = FloatArray(array.size * 2)
System.arraycopy(array, 0, newArray, 0, array.size)
array = newArray
}
override fun add(index: Int, element: Float) {
require(index in 0 until size) { "Index $index outside bounds (0, $size)" }
modCount++
array[index] = element
}
override fun set(index: Int, element: Float): Float {
require(index in 0 until size) { "Index $index outside bounds (0, $size)" }
modCount++
val old = array[index]
array[index] = element
return old
}
override fun addAll(index: Int, elements: Collection<Float>): Boolean {
elements.forEachIndexed { pos, fl ->
if (pos + index in 0 until size) {
set(pos + index, fl)
} else {
add(fl)
}
}
return true
}
override fun addAll(elements: Collection<Float>): Boolean {
elements.forEach { add(it) }
return true
}
override fun clear() {
modCount++
size = 0
}
override fun listIterator(): MutableListIterator<Float> = listIterator(0)
override fun listIterator(index: Int): MutableListIterator<Float> = ListItr(index)
override fun remove(element: Float): Boolean {
val index = indexOf(element)
if (index != -1) {
removeAt(index)
return true
}
return false
}
override fun removeAll(elements: Collection<Float>): Boolean {
return elements.map { remove(it) }.any()
}
override fun removeAt(index: Int): Float {
modCount++
val oldValue = array[index]
val numMoved = size - index - 1
if (numMoved > 0)
System.arraycopy(array, index + 1, array, index, numMoved)
size--
return oldValue
}
override fun retainAll(elements: Collection<Float>): Boolean {
val oldSize = size
elements.forEach { remove(it) }
return oldSize != size
}
override fun subList(fromIndex: Int, toIndex: Int): MutableList<Float> {
require(fromIndex in 0 until size) { "FromIndex $fromIndex outside bounds [0, $size)" }
require(toIndex in 0 until size) { "ToIndex $toIndex outside bounds [0, $size)" }
return array.toMutableList().subList(fromIndex, toIndex)
}
private open inner class Itr : MutableIterator<Float>, FloatIterator() {
internal var cursor: Int = 0
internal var lastRet = -1
internal var expectedModCount = modCount
override fun hasNext(): Boolean {
return cursor != size
}
override fun nextFloat(): Float {
checkForComodification()
val i = cursor
if (i >= size)
throw NoSuchElementException()
val elementData = array
if (i >= elementData.size)
throw ConcurrentModificationException()
cursor = i + 1
lastRet = i
return elementData[i]
}
override fun remove() {
if (lastRet < 0)
throw IllegalStateException()
checkForComodification()
try {
[email protected](lastRet)
cursor = lastRet
lastRet = -1
expectedModCount = modCount
} catch (ex: IndexOutOfBoundsException) {
throw ConcurrentModificationException()
}
}
internal fun checkForComodification() {
if (modCount != expectedModCount)
throw ConcurrentModificationException()
}
}
private inner class ListItr internal constructor(index: Int) : Itr(), MutableListIterator<Float> {
init {
cursor = index
}
override fun hasPrevious(): Boolean {
return cursor != 0
}
override fun previous(): Float {
checkForComodification()
try {
val i = cursor - 1
val previous = get(i)
cursor = i
lastRet = cursor
return previous
} catch (e: IndexOutOfBoundsException) {
checkForComodification()
throw NoSuchElementException()
}
}
override fun nextIndex(): Int {
return cursor
}
override fun previousIndex(): Int {
return cursor - 1
}
override fun set(element: Float) {
if (lastRet < 0)
throw IllegalStateException()
checkForComodification()
try {
this@FloatArrayList[lastRet] = element
expectedModCount = modCount
} catch (ex: IndexOutOfBoundsException) {
throw ConcurrentModificationException()
}
}
override fun add(element: Float) {
checkForComodification()
try {
val i = cursor
[email protected](i, element)
lastRet = -1
cursor = i + 1
expectedModCount = modCount
} catch (ex: IndexOutOfBoundsException) {
throw ConcurrentModificationException()
}
}
}
} | gpl-3.0 | 3f538cfaa3e9557db3a35a3a511d1f27 | 27.092369 | 109 | 0.547755 | 4.97086 | false | false | false | false |
cout970/Modeler | src/main/kotlin/com/cout970/modeler/core/animation/Animation.kt | 1 | 4543 | package com.cout970.modeler.core.animation
import com.cout970.modeler.api.animation.*
import com.cout970.modeler.api.model.IModel
import com.cout970.modeler.api.model.ITransformation
import com.cout970.modeler.api.model.`object`.RootGroupRef
import com.cout970.modeler.core.model.TRTSTransformation
import java.util.*
/**
* Created by cout970 on 2017/08/20.
*/
data class AnimationRef(override val id: UUID) : IAnimationRef
object AnimationRefNone : IAnimationRef {
override val id: UUID = UUID.fromString("94ca9fb4-bf93-4423-b27a-6b7320b1727a")
}
data class Animation(
override val channels: Map<IChannelRef, IChannel>,
override val channelMapping: Map<IChannelRef, AnimationTarget>,
override val timeLength: Float,
override val name: String,
override val id: UUID = UUID.randomUUID()
) : IAnimation {
override fun withName(name: String): IAnimation = copy(name = name)
override fun withChannel(channel: IChannel): IAnimation {
return copy(channels = channels + (channel.ref to channel))
}
override fun withTimeLength(newLength: Float): IAnimation {
return copy(timeLength = newLength)
}
override fun withMapping(channel: IChannelRef, target: AnimationTarget): IAnimation {
require(target !is AnimationTargetGroup || target.ref != RootGroupRef) {
"Cannot apply animation to the root group"
}
return copy(channelMapping = channelMapping + Pair(channel, target))
}
override fun removeChannels(list: List<IChannelRef>): IAnimation {
return copy(channels = channels.filterKeys { it !in list })
}
override fun plus(other: IAnimation): IAnimation {
return copy(channels = channels + other.channels)
}
companion object {
fun of(
name: String = "Animation",
timeLength: Float = 1f,
channels: Map<IChannelRef, IChannel> = emptyMap(),
channelMapping: Map<IChannelRef, AnimationTarget> = emptyMap()
): IAnimation {
return Animation(
channels = channels,
channelMapping = channelMapping,
name = name,
timeLength = timeLength
)
}
}
}
data class ChannelRef(override val id: UUID) : IChannelRef
data class Channel(
override val name: String,
override val interpolation: InterpolationMethod,
override val keyframes: List<IKeyframe>,
override val enabled: Boolean = true,
override val type: ChannelType = ChannelType.TRANSLATION,
override val id: UUID = UUID.randomUUID()
) : IChannel {
override fun withName(name: String): IChannel = copy(name = name)
override fun withEnable(enabled: Boolean): IChannel = copy(enabled = enabled)
override fun withInterpolation(method: InterpolationMethod): IChannel = copy(interpolation = method)
override fun withKeyframes(keyframes: List<IKeyframe>): IChannel = copy(keyframes = keyframes)
override fun withType(type: ChannelType): IChannel = copy(type = type)
}
data class Keyframe(
override val time: Float,
override val value: TRTSTransformation
) : IKeyframe {
override fun withValue(trs: TRTSTransformation): IKeyframe = copy(value = trs)
override fun withTime(time: Float): IKeyframe = copy(time = time)
}
inline val IChannel.ref: IChannelRef get() = ChannelRef(id)
inline val IAnimation.ref: IAnimationRef get() = AnimationRef(id)
object AnimationNone : IAnimation {
override val id: UUID get() = AnimationRefNone.id
override val name: String get() = "None"
override val channels: Map<IChannelRef, IChannel> get() = emptyMap()
override val channelMapping: Map<IChannelRef, AnimationTarget> get() = emptyMap()
override val timeLength: Float get() = 1f
override fun withName(name: String): IAnimation = this
override fun withChannel(channel: IChannel): IAnimation = this
override fun withTimeLength(newLength: Float): IAnimation = this
override fun withMapping(channel: IChannelRef, target: AnimationTarget): IAnimation = this
override fun removeChannels(list: List<IChannelRef>): IAnimation = this
override fun plus(other: IAnimation): IAnimation = other
}
fun AnimationTarget.getTransformation(model: IModel): ITransformation {
return when (this) {
is AnimationTargetGroup -> model.getGroup(ref).transform
// TODO
is AnimationTargetObject -> model.getObject(refs.first()).transformation
}
} | gpl-3.0 | 32025ba0a9380bedcb66862476565b1c | 33.687023 | 104 | 0.691834 | 4.372474 | false | false | false | false |
kickstarter/android-oss | app/src/main/java/com/kickstarter/ui/ArgumentsKey.kt | 1 | 661 | package com.kickstarter.ui
object ArgumentsKey {
const val CANCEL_PLEDGE_PROJECT = "com.kickstarter.ui.fragments.CancelPledgeFragment.project"
const val DISCOVERY_SORT_POSITION = "argument_discovery_position"
const val NEW_CARD_MODAL = "com.kickstarter.ui.fragments.NewCardFragment.modal"
const val NEW_CARD_PROJECT = "com.kickstarter.ui.fragments.NewCardFragment.project"
const val PLEDGE_PLEDGE_DATA = "com.kickstarter.ui.fragments.PledgeFragment.pledge_data"
const val PLEDGE_PLEDGE_REASON = "com.kickstarter.ui.fragments.PledgeFragment.pledge_reason"
const val PROJECT_PAGER_POSITION = "com.kickstarter.ui.fragments.position"
}
| apache-2.0 | bfca8f5a67be6bd3edb0d868ab3f1331 | 59.090909 | 97 | 0.785174 | 3.865497 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/fir/src/org/jetbrains/kotlin/idea/fir/highlighter/HighlightingUtils.kt | 1 | 3117 | /*
* Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.idea.fir.highlighter
import com.intellij.lang.jvm.JvmModifier
import com.intellij.openapi.editor.colors.TextAttributesKey
import com.intellij.psi.*
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.isAbstract
import org.jetbrains.kotlin.psi.psiUtil.isExtensionDeclaration
import org.jetbrains.kotlin.idea.highlighter.KotlinHighlightingColors as Colors
internal fun textAttributesKeyForPropertyDeclaration(declaration: PsiElement): TextAttributesKey? = when (declaration) {
is KtProperty -> textAttributesForKtPropertyDeclaration(declaration)
is KtParameter -> textAttributesForKtParameterDeclaration(declaration)
is PsiLocalVariable -> Colors.LOCAL_VARIABLE
is PsiParameter -> Colors.PARAMETER
is PsiField -> Colors.INSTANCE_PROPERTY
else -> null
}
internal fun textAttributesForKtParameterDeclaration(parameter: KtParameter) =
if (parameter.valOrVarKeyword != null) Colors.INSTANCE_PROPERTY
else Colors.PARAMETER
internal fun textAttributesForKtPropertyDeclaration(property: KtProperty): TextAttributesKey? = when {
property.isExtensionDeclaration() -> Colors.EXTENSION_PROPERTY
property.isLocal -> Colors.LOCAL_VARIABLE
property.isTopLevel -> {
if (property.isCustomPropertyDeclaration()) Colors.PACKAGE_PROPERTY_CUSTOM_PROPERTY_DECLARATION
else Colors.PACKAGE_PROPERTY
}
else -> {
if (property.isCustomPropertyDeclaration()) Colors.INSTANCE_PROPERTY_CUSTOM_PROPERTY_DECLARATION
else Colors.INSTANCE_PROPERTY
}
}
private fun KtProperty.isCustomPropertyDeclaration() =
getter?.bodyExpression != null || setter?.bodyExpression != null
@Suppress("UnstableApiUsage")
internal fun textAttributesKeyForTypeDeclaration(declaration: PsiElement): TextAttributesKey? = when {
declaration is KtTypeParameter || declaration is PsiTypeParameter -> Colors.TYPE_PARAMETER
declaration is KtTypeAlias -> Colors.TYPE_ALIAS
declaration is KtClass -> textAttributesForClass(declaration)
declaration is PsiClass && declaration.isInterface && !declaration.isAnnotationType -> Colors.TRAIT
declaration.isAnnotationClass() -> Colors.ANNOTATION
declaration is KtObjectDeclaration -> Colors.OBJECT
declaration is PsiEnumConstant -> Colors.ENUM_ENTRY
declaration is PsiClass && declaration.hasModifier(JvmModifier.ABSTRACT) -> Colors.ABSTRACT_CLASS
declaration is PsiClass -> Colors.CLASS
else -> null
}
fun textAttributesForClass(klass: KtClass): TextAttributesKey = when {
klass.isInterface() -> Colors.TRAIT
klass.isAnnotation() -> Colors.ANNOTATION
klass.isEnum() -> Colors.ENUM
klass is KtEnumEntry -> Colors.ENUM_ENTRY
klass.isAbstract() -> Colors.ABSTRACT_CLASS
else -> Colors.CLASS
}
internal fun PsiElement.isAnnotationClass() =
this is KtClass && isAnnotation() || this is PsiClass && isAnnotationType | apache-2.0 | 93cf17b3e91054ee2d5a52afda29d8f3 | 44.188406 | 120 | 0.775746 | 5.084829 | false | false | false | false |
stefanmedack/cccTV | app/src/main/java/de/stefanmedack/ccctv/ui/detail/DetailViewModel.kt | 1 | 4503 | package de.stefanmedack.ccctv.ui.detail
import de.stefanmedack.ccctv.persistence.entities.Event
import de.stefanmedack.ccctv.repository.EventRepository
import de.stefanmedack.ccctv.ui.base.BaseDisposableViewModel
import de.stefanmedack.ccctv.ui.detail.uiModels.DetailUiModel
import de.stefanmedack.ccctv.ui.detail.uiModels.SpeakerUiModel
import de.stefanmedack.ccctv.ui.detail.uiModels.VideoPlaybackUiModel
import de.stefanmedack.ccctv.util.EMPTY_STRING
import de.stefanmedack.ccctv.util.getRelatedEventGuidsWeighted
import io.reactivex.Completable
import io.reactivex.Flowable
import io.reactivex.Single
import io.reactivex.rxkotlin.Singles
import io.reactivex.rxkotlin.subscribeBy
import io.reactivex.rxkotlin.withLatestFrom
import io.reactivex.subjects.PublishSubject
import timber.log.Timber
import javax.inject.Inject
import info.metadude.kotlin.library.c3media.models.Event as EventRemote
class DetailViewModel @Inject constructor(
private val repository: EventRepository
) : BaseDisposableViewModel(), Inputs, Outputs {
internal val inputs: Inputs = this
internal val outputs: Outputs = this
private var eventId: String = EMPTY_STRING
fun init(eventId: String) {
this.eventId = eventId
disposables.addAll(
doToggleBookmark.subscribeBy(onError = { Timber.w("DetailViewModel - doToggleBookmark - onError $it") }),
doSavePlayedSeconds.subscribeBy(onError = { Timber.w("DetailViewModel - doSavePlayedSeconds - onError $it") })
)
}
//<editor-fold desc="Inputs">
override fun toggleBookmark() {
bookmarkClickStream.onNext(0)
}
override fun savePlaybackPosition(playedSeconds: Int, totalDurationSeconds: Int) {
savePlayPositionStream.onNext(PlaybackData(playedSeconds, totalDurationSeconds))
}
//</editor-fold>
//<editor-fold desc="Outputs">
override val detailData: Single<DetailUiModel>
get() = Singles.zip(
eventWithRelated.firstOrError(),
wasPlayed,
{ first, wasPlayed -> first.copy(wasPlayed = wasPlayed) })
override val videoPlaybackData: Single<VideoPlaybackUiModel>
get() = Singles.zip(
repository.getEventWithRecordings(eventId),
repository.getPlayedSeconds(eventId),
::VideoPlaybackUiModel)
override val isBookmarked: Flowable<Boolean>
get() = repository.isBookmarked(eventId)
//</editor-fold>
private val bookmarkClickStream = PublishSubject.create<Int>()
private val savePlayPositionStream = PublishSubject.create<PlaybackData>()
private val doToggleBookmark
get() = bookmarkClickStream
.withLatestFrom(isBookmarked.toObservable(), { _, t2 -> t2 })
.flatMapCompletable { updateBookmarkState(it) }
private val doSavePlayedSeconds
get() = savePlayPositionStream
.flatMapCompletable {
if (it.hasPlayedMinimumToSave() && !it.hasAlmostFinished()) {
repository.savePlayedSeconds(eventId, it.playedSeconds)
} else {
repository.deletePlayedSeconds(eventId)
}
}
private val eventWithRelated: Flowable<DetailUiModel>
get() = repository.getEvent(eventId)
.flatMap { event ->
getRelatedEvents(event).map { DetailUiModel(event = event, speaker = event.persons.map { SpeakerUiModel(it) }, related = it) }
}
private fun getRelatedEvents(event: Event): Flowable<List<Event>> = repository.getEvents(event.getRelatedEventGuidsWeighted())
private val wasPlayed: Single<Boolean>
get() = repository.getPlayedSeconds(eventId).map { it > 0 }
private fun updateBookmarkState(isBookmarked: Boolean): Completable = repository.changeBookmarkState(eventId, !isBookmarked)
private data class PlaybackData(
val playedSeconds: Int,
val totalDurationSeconds: Int
) {
private val MINIMUM_PLAYBACK_SECONDS_TO_SAVE = 60
private val MAXIMUM_PLAYBACK_PERCENT_TO_SAVE = .9f
fun hasPlayedMinimumToSave(): Boolean = this.playedSeconds > MINIMUM_PLAYBACK_SECONDS_TO_SAVE
fun hasAlmostFinished(): Boolean = when {
totalDurationSeconds > 0 -> (playedSeconds.toFloat() / totalDurationSeconds.toFloat()) > MAXIMUM_PLAYBACK_PERCENT_TO_SAVE
else -> true
}
}
} | apache-2.0 | 166830549d161b0b8d9b1e572b4f5c38 | 37.169492 | 146 | 0.688652 | 4.770127 | false | false | false | false |
jwren/intellij-community | platform/statistics/src/com/intellij/internal/statistic/beans/MetricEventUtil.kt | 3 | 7276 | // 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.internal.statistic.beans
import com.intellij.internal.statistic.eventLog.FeatureUsageData
import com.intellij.internal.statistic.eventLog.events.EventField
import com.intellij.internal.statistic.eventLog.events.EventFields
import com.intellij.internal.statistic.eventLog.events.EventPair
import com.intellij.internal.statistic.eventLog.events.VarargEventId
import com.intellij.openapi.util.Comparing
import org.jetbrains.annotations.ApiStatus
/**
* Reports numerical or string value of the setting if it's not default.
*/
@ApiStatus.ScheduledForRemoval
@Deprecated("Use EventLogGroup#registerEvent and EventId#metric instead")
fun <T> addIfDiffers(set: MutableSet<in MetricEvent>, settingsBean: T, defaultSettingsBean: T,
valueFunction: Function1<T, Any>, eventId: String) {
addIfDiffers(set, settingsBean, defaultSettingsBean, valueFunction, eventId, null)
}
/**
* Reports numerical or string value of the setting if it's not default.
*/
@ApiStatus.ScheduledForRemoval
@Deprecated("Use EventLogGroup#registerEvent and EventId#metric instead")
fun <T> addIfDiffers(set: MutableSet<in MetricEvent>, settingsBean: T, defaultSettingsBean: T,
valueFunction: Function1<T, Any>, eventId: String, data: FeatureUsageData?) {
addMetricIfDiffers(set, settingsBean, defaultSettingsBean, valueFunction) {
when (it) {
is Int -> newMetric(eventId, it, data)
is Float -> newMetric(eventId, it, data)
else -> newMetric(eventId, it.toString(), data)
}
}
}
/**
* Reports the value of boolean setting (i.e. enabled or disabled) if it's not default.
*/
@ApiStatus.ScheduledForRemoval
@Deprecated("Use EventLogGroup#registerEvent and EventId#metric instead")
fun <T> addBoolIfDiffers(set: MutableSet<in MetricEvent>, settingsBean: T, defaultSettingsBean: T,
valueFunction: Function1<T, Boolean>, eventId: String) {
addBoolIfDiffers(set, settingsBean, defaultSettingsBean, valueFunction, eventId, null)
}
/**
* Reports the value of boolean setting (i.e. enabled or disabled) if it's not default.
*/
@ApiStatus.ScheduledForRemoval
@Deprecated("Use EventLogGroup#registerEvent and EventId#metric instead")
fun <T> addBoolIfDiffers(set: MutableSet<in MetricEvent>, settingsBean: T, defaultSettingsBean: T,
valueFunction: Function1<T, Boolean>, eventId: String, data: FeatureUsageData?) {
addMetricIfDiffers(set, settingsBean, defaultSettingsBean, valueFunction) { newBooleanMetric(eventId, it, data) }
}
/**
* Adds counter value if count is greater than 0
*/
@ApiStatus.ScheduledForRemoval
@Deprecated("Use EventLogGroup#registerEvent and EventId#metric instead")
fun <T> addCounterIfNotZero(set: MutableSet<in MetricEvent>, eventId: String, count: Int) {
if (count > 0) {
set.add(newCounterMetric(eventId, count))
}
}
/**
* Adds counter value if count is greater than 0
*/
@ApiStatus.ScheduledForRemoval
@Deprecated("Use EventLogGroup#registerEvent and EventId#metric instead")
fun <T> addCounterIfNotZero(set: MutableSet<in MetricEvent>, eventId: String, count: Int, data: FeatureUsageData?) {
if (count > 0) {
set.add(newCounterMetric(eventId, count, data))
}
}
@ApiStatus.ScheduledForRemoval
@Deprecated("Use EventLogGroup#registerEvent and EventId#metric instead")
fun <T> addCounterIfDiffers(set: MutableSet<in MetricEvent>, settingsBean: T, defaultSettingsBean: T,
valueFunction: Function1<T, Int>, eventId: String) {
addMetricIfDiffers(set, settingsBean, defaultSettingsBean, valueFunction) { newCounterMetric(eventId, it) }
}
@ApiStatus.ScheduledForRemoval
@Deprecated("Use EventLogGroup#registerEvent and EventId#metric instead")
fun <T> addCounterIfDiffers(set: MutableSet<in MetricEvent>, settingsBean: T, defaultSettingsBean: T,
valueFunction: Function1<T, Int>, eventId: String, data: FeatureUsageData?) {
addMetricIfDiffers(set, settingsBean, defaultSettingsBean, valueFunction) { newCounterMetric(eventId, it, data) }
}
@ApiStatus.ScheduledForRemoval
@Deprecated("Use EventLogGroup#registerEvent and EventId#metric instead")
fun <T, V : Enum<*>> addEnumIfDiffers(set: MutableSet<in MetricEvent>, settingsBean: T, defaultSettingsBean: T,
valueFunction: Function1<T, V>, eventId: String) {
addMetricIfDiffers(set, settingsBean, defaultSettingsBean, valueFunction) { newMetric(eventId, it, null) }
}
fun <T, V> addMetricIfDiffers(set: MutableSet<in MetricEvent>, settingsBean: T, defaultSettingsBean: T,
valueFunction: (T) -> V, eventIdFunc: (V) -> MetricEvent) {
val value = valueFunction(settingsBean)
val defaultValue = valueFunction(defaultSettingsBean)
if (!Comparing.equal(value, defaultValue)) {
set.add(eventIdFunc(value))
}
}
interface MetricDifferenceBuilder<T> {
fun add(eventId: String, valueFunction: (T) -> Any)
fun addBool(eventId: String, valueFunction: (T) -> Boolean)
}
@ApiStatus.ScheduledForRemoval
@Deprecated("Use EventLogGroup#registerEvent and EventId#metric instead")
fun <T> addMetricsIfDiffers(set: MutableSet<in MetricEvent>,
settingsBean: T,
defaultSettingsBean: T,
data: FeatureUsageData,
callback: MetricDifferenceBuilder<T>.() -> Unit) {
callback(object : MetricDifferenceBuilder<T> {
override fun add(eventId: String, valueFunction: (T) -> Any) {
addIfDiffers(set, settingsBean, defaultSettingsBean, valueFunction, eventId, data)
}
override fun addBool(eventId: String, valueFunction: (T) -> Boolean) {
addBoolIfDiffers(set, settingsBean, defaultSettingsBean, valueFunction, eventId, data)
}
})
}
@JvmOverloads
fun <T> addBoolIfDiffers(set: MutableSet<in MetricEvent>, settingsBean: T, defaultSettingsBean: T,
valueFunction: (T) -> Boolean, eventId: VarargEventId, data: MutableList<EventPair<*>>? = null) {
addIfDiffers(set, settingsBean, defaultSettingsBean, valueFunction, eventId, EventFields.Enabled, data)
}
@JvmOverloads
fun <T, V> addIfDiffers(set: MutableSet<in MetricEvent>, settingsBean: T, defaultSettingsBean: T,
valueFunction: (T) -> V, eventId: VarargEventId, field: EventField<V>, data: MutableList<EventPair<*>>? = null) {
addMetricIfDiffers(set, settingsBean, defaultSettingsBean, valueFunction) {
val fields = data ?: mutableListOf()
fields.add(field.with(it))
eventId.metric(fields)
}
}
/**
* Adds counter value if count is greater than 0
*/
fun <T> addCounterIfNotZero(set: MutableSet<in MetricEvent>, eventId: VarargEventId, count: Int) {
if (count > 0) {
set.add(eventId.metric(EventFields.Count.with(count)))
}
}
/**
* Adds counter value if count is greater than 0
*/
fun <T> addCounterIfNotZero(set: MutableSet<in MetricEvent>, eventId: VarargEventId, count: Int, data: MutableList<EventPair<*>>? = null) {
if (count > 0) {
val fields = data ?: mutableListOf()
fields.add(EventFields.Count.with(count))
eventId.metric(fields)
}
} | apache-2.0 | 25d537690cafc2023a0ad77b4f317b19 | 42.57485 | 139 | 0.7221 | 4.113058 | false | false | false | false |
jwren/intellij-community | plugins/search-everywhere-ml/src/com/intellij/ide/actions/searcheverywhere/ml/SearchEverywhereMlSearchState.kt | 1 | 3421 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ide.actions.searcheverywhere.ml
import com.intellij.ide.actions.searcheverywhere.SearchEverywhereContributor
import com.intellij.ide.actions.searcheverywhere.SearchRestartReason
import com.intellij.ide.actions.searcheverywhere.ml.features.SearchEverywhereElementFeaturesProvider
import com.intellij.ide.actions.searcheverywhere.ml.features.SearchEverywhereStateFeaturesProvider
import com.intellij.ide.actions.searcheverywhere.ml.model.SearchEverywhereModelProvider
import com.intellij.ide.actions.searcheverywhere.ml.model.SearchEverywhereRankingModel
import com.intellij.internal.statistic.eventLog.events.EventPair
internal class SearchEverywhereMlSearchState(
val sessionStartTime: Long, val searchStartTime: Long,
val searchIndex: Int, val searchStartReason: SearchRestartReason, val tabId: String,
val keysTyped: Int, val backspacesTyped: Int, private val searchQuery: String,
private val modelProvider: SearchEverywhereModelProvider,
private val providersCaches: Map<Class<out SearchEverywhereElementFeaturesProvider>, Any>
) {
private val cachedElementsInfo: MutableMap<Int, SearchEverywhereMLItemInfo> = hashMapOf()
private val cachedMLWeight: MutableMap<Int, Double> = hashMapOf()
val searchStateFeatures = SearchEverywhereStateFeaturesProvider().getSearchStateFeatures(tabId, searchQuery)
private val model: SearchEverywhereRankingModel by lazy {
SearchEverywhereRankingModel(modelProvider.getModel(tabId))
}
@Synchronized
fun getElementFeatures(elementId: Int,
element: Any,
contributor: SearchEverywhereContributor<*>,
priority: Int): SearchEverywhereMLItemInfo {
return cachedElementsInfo.computeIfAbsent(elementId) {
val features = arrayListOf<EventPair<*>>()
val contributorId = contributor.searchProviderId
SearchEverywhereElementFeaturesProvider.getFeatureProvidersForContributor(contributorId).forEach { provider ->
val cache = providersCaches[provider::class.java]
features.addAll(provider.getElementFeatures(element, sessionStartTime, searchQuery, priority, cache))
}
return@computeIfAbsent SearchEverywhereMLItemInfo(elementId, contributorId, features)
}
}
@Synchronized
fun getMLWeightIfDefined(elementId: Int): Double? {
return cachedMLWeight[elementId]
}
@Synchronized
fun getMLWeight(elementId: Int,
element: Any,
contributor: SearchEverywhereContributor<*>,
context: SearchEverywhereMLContextInfo,
priority: Int): Double {
return cachedMLWeight.computeIfAbsent(elementId) {
val features = ArrayList<EventPair<*>>()
features.addAll(context.features)
features.addAll(getElementFeatures(elementId, element, contributor, priority).features)
features.addAll(searchStateFeatures)
model.predict(features.associate { it.field.name to it.data })
}
}
}
internal data class SearchEverywhereMLItemInfo(val id: Int, val contributorId: String, val features: List<EventPair<*>>) {
fun featuresAsMap(): Map<String, Any> = features.mapNotNull {
val data = it.data
if (data == null) null else it.field.name to data
}.toMap()
} | apache-2.0 | 3016b1f9c8cb954ffa77acc984347b6e | 47.197183 | 158 | 0.761766 | 5.090774 | false | false | false | false |
JetBrains/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/NumberConversionFix.kt | 1 | 3893 | // 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.quickfix
import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.config.ApiVersion
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.base.projectStructure.languageVersionSettings
import org.jetbrains.kotlin.idea.base.psi.replaced
import org.jetbrains.kotlin.idea.codeinsight.api.classic.quickfixes.KotlinQuickFixAction
import org.jetbrains.kotlin.idea.util.IdeDescriptorRenderers
import org.jetbrains.kotlin.psi.KtExpression
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.KtPsiFactory
import org.jetbrains.kotlin.psi.createExpressionByPattern
import org.jetbrains.kotlin.psi.psiUtil.endOffset
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.isNullable
import org.jetbrains.kotlin.types.typeUtil.*
class NumberConversionFix(
element: KtExpression,
fromType: KotlinType,
toType: KotlinType,
private val disableIfAvailable: IntentionAction? = null,
private val enableNullableType: Boolean = false,
private val intentionText: (String) -> String = { KotlinBundle.message("convert.expression.to.0", it) }
) : KotlinQuickFixAction<KtExpression>(element) {
private val isConversionAvailable = fromType != toType && fromType.isNumberType() && toType.isNumberType()
private val typePresentation = IdeDescriptorRenderers.SOURCE_CODE_SHORT_NAMES_NO_ANNOTATIONS.renderType(toType.makeNotNullable())
private val fromInt = fromType.isInt()
private val fromChar = fromType.isChar()
private val fromFloatOrDouble = fromType.isFloat() || fromType.isDouble()
private val fromNullable = fromType.isNullable()
private val toChar = toType.isChar()
private val toInt = toType.isInt()
private val toByteOrShort = toType.isByte() || toType.isShort()
private fun KotlinType.isNumberType(): Boolean {
val type = if (enableNullableType) this.makeNotNullable() else this
return type.isSignedOrUnsignedNumberType()
}
override fun isAvailable(project: Project, editor: Editor?, file: KtFile) =
disableIfAvailable?.isAvailable(project, editor, file) != true && isConversionAvailable
override fun getFamilyName() = KotlinBundle.message("insert.number.conversion")
override fun getText() = intentionText(typePresentation)
override fun invoke(project: Project, editor: Editor?, file: KtFile) {
val element = element ?: return
val psiFactory = KtPsiFactory(project)
val apiVersion = element.languageVersionSettings.apiVersion
val dot = if (fromNullable) "?." else "."
val expressionToInsert = when {
fromChar && apiVersion >= ApiVersion.KOTLIN_1_5 ->
if (toInt) {
psiFactory.createExpressionByPattern("$0${dot}code", element)
} else {
psiFactory.createExpressionByPattern("$0${dot}code${dot}to$1()", element, typePresentation)
}
!fromInt && toChar && apiVersion >= ApiVersion.KOTLIN_1_5 ->
psiFactory.createExpressionByPattern("$0${dot}toInt()${dot}toChar()", element)
fromFloatOrDouble && toByteOrShort && apiVersion >= ApiVersion.KOTLIN_1_3 ->
psiFactory.createExpressionByPattern("$0${dot}toInt()${dot}to$1()", element, typePresentation)
else ->
psiFactory.createExpressionByPattern("$0${dot}to$1()", element, typePresentation)
}
val newExpression = element.replaced(expressionToInsert)
editor?.caretModel?.moveToOffset(newExpression.endOffset)
}
} | apache-2.0 | d94bc7259d5aff5c78ca75ebf7e4c71b | 49.571429 | 158 | 0.727973 | 4.684717 | false | false | false | false |
taigua/exercism | kotlin/space-age/src/main/kotlin/SpaceAge.kt | 1 | 857 | class SpaceAge(val seconds: Long) {
companion object {
val EARTH_RATIO = 31557600.0
val MERCURY_RATIO = 0.2408467
val VENUS_RATIO = 0.61519726
val MARS_RATIO = 1.8808158
val JUPITER_RATIO = 11.862615
val SATURN_RATIO = 29.447498
val URANUS_RATIO = 84.016846
val NEPTUNE_RATIO = 164.79132
fun round(v: Double) = Math.round(v * 100) / 100.0
}
private val earth = seconds / EARTH_RATIO
fun onEarth() = round(earth)
fun onMercury() = round(earth / MERCURY_RATIO)
fun onVenus() = round(earth / VENUS_RATIO)
fun onMars() = round(earth / MARS_RATIO)
fun onJupiter() = round(earth / JUPITER_RATIO)
fun onSaturn() = round(earth / SATURN_RATIO)
fun onUranus() = round(earth / URANUS_RATIO)
fun onNeptune() = round(earth / NEPTUNE_RATIO)
} | mit | 2d6eb833ab5d4185f834c6270f7bc92b | 33.32 | 58 | 0.614936 | 2.965398 | false | false | false | false |