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
rolandvitezhu/TodoCloud
app/src/main/java/com/rolandvitezhu/todocloud/ui/activity/main/fragment/SearchFragment.kt
1
14676
package com.rolandvitezhu.todocloud.ui.activity.main.fragment import android.app.SearchManager import android.content.Context import android.content.DialogInterface import android.content.res.Configuration import android.os.Bundle import android.view.* import android.widget.LinearLayout import android.widget.SearchView import androidx.appcompat.view.ActionMode import androidx.fragment.app.Fragment import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.lifecycleScope import androidx.recyclerview.widget.ItemTouchHelper import androidx.recyclerview.widget.RecyclerView import com.rolandvitezhu.todocloud.R import com.rolandvitezhu.todocloud.app.AppController import com.rolandvitezhu.todocloud.app.AppController.Companion.instance import com.rolandvitezhu.todocloud.app.AppController.Companion.isDraggingEnabled import com.rolandvitezhu.todocloud.data.PredefinedList import com.rolandvitezhu.todocloud.data.Todo import com.rolandvitezhu.todocloud.database.TodoCloudDatabaseDao import com.rolandvitezhu.todocloud.databinding.FragmentSearchBinding import com.rolandvitezhu.todocloud.helper.hideSoftInput import com.rolandvitezhu.todocloud.ui.activity.main.MainActivity import com.rolandvitezhu.todocloud.ui.activity.main.adapter.TodoAdapter import com.rolandvitezhu.todocloud.ui.activity.main.dialogfragment.ConfirmDeleteDialogFragment import com.rolandvitezhu.todocloud.ui.activity.main.viewmodel.PredefinedListsViewModel import com.rolandvitezhu.todocloud.ui.activity.main.viewmodel.SearchListsViewModel import com.rolandvitezhu.todocloud.ui.activity.main.viewmodel.TodosViewModel import kotlinx.android.synthetic.main.layout_recyclerview_search.view.* import kotlinx.coroutines.launch import java.util.* import javax.inject.Inject class SearchFragment : Fragment(), DialogInterface.OnDismissListener { @Inject lateinit var todoCloudDatabaseDao: TodoCloudDatabaseDao @Inject lateinit var todoAdapter: TodoAdapter private var searchView: SearchView? = null var actionMode: ActionMode? = null private val todosViewModel by lazy { activity?.let { ViewModelProvider(it).get(TodosViewModel::class.java) } } private val searchListsViewModel by lazy { activity?.let { ViewModelProvider(it).get(SearchListsViewModel::class.java) } } private val predefinedListsViewModel by lazy { activity?.let { ViewModelProvider(it).get(PredefinedListsViewModel::class.java) } } private var swipedTodoAdapterPosition: Int? = null override fun onAttach(context: Context) { super.onAttach(context) Objects.requireNonNull(instance)?.appComponent?.fragmentComponent()?.create()?.inject(this) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setHasOptionsMenu(true) todosViewModel?.todos?.observe( this, Observer { todos -> todos?.let { todoAdapter.update(it.toMutableList()) } todoAdapter.notifyDataSetChanged() } ) } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { val fragmentSearchBinding = FragmentSearchBinding.inflate(layoutInflater, null, false) val view: View = fragmentSearchBinding.root prepareRecyclerView() applySwipeToDismissAndDragToReorder(view) fragmentSearchBinding.lifecycleOwner = this fragmentSearchBinding.searchFragment = this fragmentSearchBinding.executePendingBindings() return view } override fun onResume() { super.onResume() (activity as MainActivity?)?.onSetActionBarTitle("") prepareSearchViewAfterModifyTodo() } private fun prepareRecyclerView() { isDraggingEnabled = false } private fun applySwipeToDismissAndDragToReorder(view: View) { val simpleItemTouchCallback: ItemTouchHelper.SimpleCallback = object : ItemTouchHelper.SimpleCallback( 0, ItemTouchHelper.START ) { override fun onMove( recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder, target: RecyclerView.ViewHolder ): Boolean { return false } override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) { val swipedTodo = getSwipedTodo(viewHolder) swipedTodoAdapterPosition = viewHolder.adapterPosition swipedTodoAdapterPosition?.let { openConfirmDeleteTodosDialog(swipedTodo, it) } } override fun getMovementFlags(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder): Int { val dragFlags: Int val swipeFlags: Int if (AppController.isActionMode()) { dragFlags = ItemTouchHelper.UP or ItemTouchHelper.DOWN swipeFlags = 0 } else { dragFlags = 0 swipeFlags = ItemTouchHelper.START } return ItemTouchHelper.Callback.makeMovementFlags(dragFlags, swipeFlags) } override fun isLongPressDragEnabled(): Boolean { return false } } val itemTouchHelper = ItemTouchHelper(simpleItemTouchCallback) itemTouchHelper.attachToRecyclerView(view.recyclerview_search) todoAdapter.itemTouchHelper = itemTouchHelper } private fun getSwipedTodo(viewHolder: RecyclerView.ViewHolder): Todo { val swipedTodoAdapterPosition = viewHolder.adapterPosition return todoAdapter.getTodo(swipedTodoAdapterPosition) } fun areSelectedItems(): Boolean { return todoAdapter.selectedItemCount > 0 } fun isActionMode(): Boolean { return actionMode != null } fun openModifyTodoFragment(childViewAdapterPosition: Int) { todosViewModel?.todo = todoAdapter.getTodo(childViewAdapterPosition) (activity as MainActivity?)?.openModifyTodoFragment(this, null) } private fun prepareSearchViewAfterModifyTodo() { if (searchView != null && view?.recyclerview_search != null) { searchView?.post { restoreQueryTextState() view?.recyclerview_search?.requestFocusFromTouch() searchView?.clearFocus() hideSoftInput() } } } override fun onConfigurationChanged(newConfig: Configuration) { super.onConfigurationChanged(newConfig) restoreQueryTextState() } private fun restoreQueryTextState() { if (searchView != null) searchView?.setQuery(searchListsViewModel?.queryText, false) } val callback: ActionMode.Callback = object : ActionMode.Callback { override fun onCreateActionMode(mode: ActionMode, menu: Menu): Boolean { setSearchActionMode(mode) mode.menuInflater.inflate(R.menu.layout_appbar_search, menu) preventTypeIntoSearchView() return true } private fun preventTypeIntoSearchView() { if (searchView != null && view?.recyclerview_search != null) { view?.recyclerview_search?.requestFocusFromTouch() } hideSoftInput() } override fun onPrepareActionMode(mode: ActionMode, menu: Menu): Boolean { val title = prepareTitle() actionMode?.title = title return true } override fun onActionItemClicked(mode: ActionMode, item: MenuItem): Boolean { val menuItemId = item.itemId when (menuItemId) { R.id.menuitem_layoutappbarsearch_delete -> openConfirmDeleteTodosDialog() } return true } override fun onDestroyActionMode(mode: ActionMode) { todoAdapter.clearSelection() setSearchActionMode(null) } private fun prepareTitle(): String { val selectedItemCount = todoAdapter.selectedItemCount return selectedItemCount.toString() + " " + getString(R.string.all_selected) } } private fun setSearchActionMode(actionMode: ActionMode?) { this.actionMode = actionMode AppController.setActionMode(actionMode) } private fun openConfirmDeleteTodosDialog() { val selectedTodos = todoAdapter.selectedTodos val arguments = Bundle() arguments.putString("itemType", "todo") arguments.putParcelableArrayList("itemsToDelete", selectedTodos) openConfirmDeleteDialogFragment(arguments) } private fun openConfirmDeleteTodosDialog(swipedTodo: Todo, swipedTodoAdapterPosition: Int) { val selectedTodos = ArrayList<Todo>() selectedTodos.add(swipedTodo) val arguments = Bundle() arguments.putString("itemType", "todo") arguments.putParcelableArrayList("itemsToDelete", selectedTodos) openConfirmDeleteDialogFragment(arguments, swipedTodoAdapterPosition) } private fun openConfirmDeleteDialogFragment(arguments: Bundle) { val confirmDeleteDialogFragment = ConfirmDeleteDialogFragment() confirmDeleteDialogFragment.setTargetFragment(this, 0) confirmDeleteDialogFragment.arguments = arguments confirmDeleteDialogFragment.show(parentFragmentManager, "ConfirmDeleteDialogFragment") } private fun openConfirmDeleteDialogFragment( arguments: Bundle, swipedTodoAdapterPosition: Int ) { val confirmDeleteDialogFragment = ConfirmDeleteDialogFragment() confirmDeleteDialogFragment.setTargetFragment(this, 0) confirmDeleteDialogFragment.arguments = arguments confirmDeleteDialogFragment.show(parentFragmentManager, "ConfirmDeleteDialogFragment") } override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { inflater.inflate(R.menu.fragment_search, menu) prepareSearchView(menu) } private fun prepareSearchView(menu: Menu) { val searchMenuItem = menu.findItem(R.id.menuitem_search) searchView = searchMenuItem.actionView as SearchView val searchManager = activity ?.getSystemService(Context.SEARCH_SERVICE) as SearchManager val searchableInfo = searchManager.getSearchableInfo( requireActivity().componentName ) searchView?.setSearchableInfo(searchableInfo) searchView?.maxWidth = Int.MAX_VALUE searchView?.isIconified = false searchView?.isFocusable = true searchView?.requestFocusFromTouch() disableSearchViewCloseButton() removeSearchViewUnderline() removeSearchViewHintIcon() applyOnQueryTextEvents() } private fun removeSearchViewUnderline() { val searchPlateId = searchView?.context?.resources?.getIdentifier( "android:id/search_plate", null, null ) if (searchPlateId != null) { val searchPlate = searchView?.findViewById<View>(searchPlateId) searchPlate?.setBackgroundResource(0) } } private fun removeSearchViewHintIcon() { if (searchView != null) { val searchMagIconId = searchView?.context?.resources?.getIdentifier( "android:id/search_mag_icon", null, null ) if (searchMagIconId != null) { val searchMagIcon = searchView!!.findViewById<View>(searchMagIconId) if (searchMagIcon != null) { searchView?.isIconifiedByDefault = false searchMagIcon.layoutParams = LinearLayout.LayoutParams(0, 0) } } } } private fun disableSearchViewCloseButton() { searchView?.setOnCloseListener { true } } private fun applyOnQueryTextEvents() { searchView?.setOnQueryTextListener(object : SearchView.OnQueryTextListener { override fun onQueryTextSubmit(query: String): Boolean { preventToExecuteQueryTextSubmitTwice() return true } private fun preventToExecuteQueryTextSubmitTwice() { if (searchView != null) { searchView?.clearFocus() hideSoftInput() } } override fun onQueryTextChange(newText: String): Boolean { saveQueryTextState(newText) if (newText.isNotEmpty()) { showSearchResults(newText) } else { clearSearchResults() } return true } private fun saveQueryTextState(queryText: String) { searchListsViewModel?.queryText = queryText } private fun showSearchResults(newText: String) { lifecycleScope.launch { val whereCondition = todoCloudDatabaseDao.prepareSearchWhereCondition(newText) predefinedListsViewModel?.predefinedList = PredefinedList("0", whereCondition) todosViewModel?.updateTodosViewModelByWhereCondition( "", whereCondition ) } } private fun clearSearchResults() { todoAdapter.clear() } }) } private fun isSetReminder(todo: Todo): Boolean { return !todo.reminderDateTime?.equals("-1")!! } private fun isNotCompleted(todo: Todo): Boolean { return todo.completed?.not() ?: true } private fun shouldCreateReminderService(todoToModify: Todo): Boolean { return isNotCompleted(todoToModify) && isNotDeleted(todoToModify) } private fun isNotDeleted(todo: Todo): Boolean { return todo.deleted?.not() ?: true } /** * Finish action mode, if the Fragment is in action mode. */ fun finishActionMode() { actionMode?.finish() } override fun onDismiss(dialog: DialogInterface?) { if (swipedTodoAdapterPosition != null) todoAdapter.notifyItemChanged(swipedTodoAdapterPosition!!) else todoAdapter.notifyDataSetChanged() } }
mit
3b3478eee7236ed0c032eaa84d2fa608
36.063131
99
0.653107
5.903459
false
false
false
false
JetBrains/ideavim
src/test/java/org/jetbrains/plugins/ideavim/propertybased/IncrementDecrementCheck.kt
1
3930
/* * Copyright 2003-2022 The IdeaVim authors * * Use of this source code is governed by an MIT-style * license that can be found in the LICENSE.txt file or at * https://opensource.org/licenses/MIT. */ package org.jetbrains.plugins.ideavim.propertybased import com.intellij.ide.IdeEventQueue import com.intellij.openapi.editor.Editor import com.intellij.testFramework.PlatformTestUtil import com.maddyhome.idea.vim.VimPlugin import com.maddyhome.idea.vim.api.injector import com.maddyhome.idea.vim.options.OptionConstants import com.maddyhome.idea.vim.options.OptionScope import org.jetbrains.jetCheck.Generator import org.jetbrains.jetCheck.ImperativeCommand import org.jetbrains.jetCheck.PropertyChecker import org.jetbrains.plugins.ideavim.NeovimTesting import org.jetbrains.plugins.ideavim.SkipNeovimReason import org.jetbrains.plugins.ideavim.TestWithoutNeovim import org.jetbrains.plugins.ideavim.VimTestCase import kotlin.math.absoluteValue import kotlin.math.sign class IncrementDecrementTest : VimPropertyTestBase() { @TestWithoutNeovim(SkipNeovimReason.DIFFERENT) fun testPlayingWithNumbers() { PropertyChecker.checkScenarios { ImperativeCommand { env -> val editor = configureByText(numbers) try { moveCaretToRandomPlace(env, editor) env.executeCommands(Generator.sampledFrom(IncrementDecrementActions(editor, this))) } finally { reset(editor) } } } } fun testPlayingWithNumbersGenerateNumber() { setupChecks { this.neoVim.ignoredRegisters = setOf(':') } VimPlugin.getOptionService().appendValue(OptionScope.GLOBAL, OptionConstants.nrformatsName, "octal", OptionConstants.nrformatsName) PropertyChecker.checkScenarios { ImperativeCommand { env -> val number = env.generateValue(testNumberGenerator, "Generate %s number") val editor = configureByText(number) try { moveCaretToRandomPlace(env, editor) NeovimTesting.setupEditor(editor, this) NeovimTesting.typeCommand(":set nrformats+=octal<CR>", this, editor) env.executeCommands(Generator.sampledFrom(IncrementDecrementActions(editor, this))) NeovimTesting.assertState(editor, this) } finally { reset(editor) } } } } } private class IncrementDecrementActions(private val editor: Editor, val test: VimTestCase) : ImperativeCommand { override fun performCommand(env: ImperativeCommand.Environment) { val generator = Generator.sampledFrom("<C-A>", "<C-X>") val key = env.generateValue(generator, null) val action = injector.parser.parseKeys(key).single() env.logMessage("Use command: ${injector.parser.toKeyNotation(action)}.") VimTestCase.typeText(listOf(action), editor, editor.project) NeovimTesting.typeCommand(key, test, editor) IdeEventQueue.getInstance().flushQueue() PlatformTestUtil.dispatchAllInvocationEventsInIdeEventQueue() } } val differentFormNumberGenerator = Generator.from { env -> val form = env.generate(Generator.sampledFrom(/*2,*/ 8, 10, 16)) env.generate( Generator.integers().suchThat { it != Int.MIN_VALUE }.map { val sign = it.sign val stringNumber = it.absoluteValue.toString(form) if (sign < 0) "-$stringNumber" else stringNumber } ) } val brokenNumberGenerator = Generator.from { env -> val bigChar = env.generate(Generator.anyOf(Generator.charsInRange('8', '9'), Generator.charsInRange('G', 'Z'))) val number = env.generate(differentFormNumberGenerator) if (number.length > 4) { val insertAt = env.generate(Generator.integers(4, number.length - 1)) number.take(insertAt) + bigChar + number.substring(insertAt) } else "$number$bigChar" } val testNumberGenerator = Generator.from { env -> env.generate( Generator.frequency( 10, differentFormNumberGenerator, 1, brokenNumberGenerator ) ) }
mit
0a3ec2bc31efebd5bbcd099416b22cf1
34.405405
135
0.73028
4.285714
false
true
false
false
wordpress-mobile/WordPress-Android
WordPress/src/wordpress/java/org/wordpress/android/ui/accounts/login/LoginPrologueRevampedFragment.kt
1
4804
package org.wordpress.android.ui.accounts.login import android.content.Context import android.content.res.Configuration.UI_MODE_NIGHT_YES import android.os.Bundle import android.view.LayoutInflater import android.view.ViewGroup import androidx.compose.foundation.background import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.padding import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.drawBehind import androidx.compose.ui.graphics.drawscope.scale import androidx.compose.ui.graphics.drawscope.translate import androidx.compose.ui.platform.ComposeView import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.platform.LocalLayoutDirection import androidx.compose.ui.res.colorResource import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.tooling.preview.Devices import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.LayoutDirection.Rtl import androidx.compose.ui.unit.dp import androidx.fragment.app.Fragment import org.wordpress.android.R.color import org.wordpress.android.R.drawable import org.wordpress.android.R.string import org.wordpress.android.ui.accounts.login.compose.components.PrimaryButton import org.wordpress.android.ui.accounts.login.compose.components.SecondaryButton import org.wordpress.android.ui.accounts.login.compose.components.Tagline import org.wordpress.android.ui.compose.theme.AppTheme import org.wordpress.android.util.extensions.setEdgeToEdgeContentDisplay class LoginPrologueRevampedFragment : Fragment() { private lateinit var loginPrologueListener: LoginPrologueListener override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ) = ComposeView(requireContext()).apply { setContent { AppTheme { LoginScreenRevamped( onWpComLoginClicked = loginPrologueListener::showEmailLoginScreen, onSiteAddressLoginClicked = loginPrologueListener::loginViaSiteAddress, ) } } } override fun onAttach(context: Context) { super.onAttach(context) check(context is LoginPrologueListener) { "$context must implement LoginPrologueListener" } loginPrologueListener = context } override fun onResume() { super.onResume() requireActivity().window.setEdgeToEdgeContentDisplay(true) } override fun onPause() { super.onPause() requireActivity().window.setEdgeToEdgeContentDisplay(false) } companion object { const val TAG = "login_prologue_revamped_fragment_tag" } } @Composable fun LoginScreenRevamped( onWpComLoginClicked: () -> Unit, onSiteAddressLoginClicked: () -> Unit, ) { val brushStrokePainter = painterResource(id = drawable.brush_stroke) // Flip the background image for RTL locales val scaleX = if (LocalLayoutDirection.current == Rtl) -1f else 1f val offsetX = with(LocalDensity.current) { 10.dp.toPx() } val offsetY = with(LocalDensity.current) { 75.dp.toPx() } Box(modifier = Modifier .background(color = colorResource(id = color.login_prologue_revamped_background)) .drawBehind { scale(scaleX = scaleX, scaleY = 1f) { translate( left = size.width - brushStrokePainter.intrinsicSize.width - offsetX, top = -offsetY ) { with(brushStrokePainter) { draw(intrinsicSize) } } } } ) { Column( horizontalAlignment = Alignment.CenterHorizontally, modifier = Modifier.padding(vertical = 45.dp) ) { Tagline(text = stringResource(string.login_prologue_revamped_tagline)) PrimaryButton( text = stringResource(string.continue_with_wpcom), onClick = onWpComLoginClicked, ) SecondaryButton( text = stringResource(string.enter_your_site_address), onClick = onSiteAddressLoginClicked, ) } } } @Preview(showBackground = true, device = Devices.PIXEL_3A) @Preview(showBackground = true, device = Devices.PIXEL_3A, uiMode = UI_MODE_NIGHT_YES) @Composable fun PreviewLoginScreenRevamped() { AppTheme { LoginScreenRevamped(onWpComLoginClicked = {}, onSiteAddressLoginClicked = {}) } }
gpl-2.0
118cdeba1e39a31f93e4989e73ab25ac
36.53125
99
0.68776
4.553555
false
false
false
false
mdaniel/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/ChopParameterListIntention.kt
1
5768
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.intentions import com.intellij.application.options.CodeStyle import com.intellij.openapi.editor.Editor import com.intellij.psi.PsiDocumentManager import com.intellij.psi.PsiElement import com.intellij.psi.PsiWhiteSpace import com.intellij.psi.codeStyle.CommonCodeStyleSettings import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.base.util.reformatted import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingIntention import org.jetbrains.kotlin.idea.formatter.kotlinCommonSettings import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.allChildren import org.jetbrains.kotlin.psi.psiUtil.createSmartPointer import org.jetbrains.kotlin.psi.psiUtil.siblings import org.jetbrains.kotlin.psi.psiUtil.startOffset abstract class AbstractChopListIntention<TList : KtElement, TElement : KtElement>( listClass: Class<TList>, private val elementClass: Class<TElement>, textGetter: () -> String ) : SelfTargetingIntention<TList>(listClass, textGetter) { override fun skipProcessingFurtherElementsAfter(element: PsiElement) = element is KtValueArgument || super.skipProcessingFurtherElementsAfter(element) open fun leftParOnNewLine(commonCodeStyleSettings: CommonCodeStyleSettings): Boolean = false open fun rightParOnNewLine(commonCodeStyleSettings: CommonCodeStyleSettings): Boolean = false override fun isApplicableTo(element: TList, caretOffset: Int): Boolean { val elements = element.elements() if (elements.size <= 1) return false if (!isApplicableCaretOffset(caretOffset, element)) return false if (elements.dropLast(1).all { hasLineBreakAfter(it) }) return false return true } override fun applyTo(element: TList, editor: Editor?) { val project = element.project val document = editor?.document ?: return val pointer = element.createSmartPointer() val commonCodeStyleSettings = CodeStyle.getSettings(project).kotlinCommonSettings val leftParOnNewLine = leftParOnNewLine(commonCodeStyleSettings) val rightParOnNewLine = rightParOnNewLine(commonCodeStyleSettings) val elements = element.elements() if (rightParOnNewLine && !hasLineBreakAfter(elements.last())) { element.allChildren.lastOrNull { it.node.elementType == KtTokens.RPAR }?.startOffset?.let { document.insertString(it, "\n") } } val maxIndex = elements.size - 1 for ((index, e) in elements.asReversed().withIndex()) { if (index == maxIndex && !leftParOnNewLine) break if (!hasLineBreakBefore(e)) { document.insertString(e.startOffset, "\n") } } val documentManager = PsiDocumentManager.getInstance(project) documentManager.commitDocument(document) pointer.element?.reformatted() } protected fun hasLineBreakAfter(element: TElement): Boolean = nextBreak(element) != null protected fun nextBreak(element: TElement): PsiWhiteSpace? = element.siblings(withItself = false) .takeWhile { !elementClass.isInstance(it) } .firstOrNull { it is PsiWhiteSpace && it.textContains('\n') } as? PsiWhiteSpace protected fun hasLineBreakBefore(element: TElement): Boolean = prevBreak(element) != null protected fun prevBreak(element: TElement): PsiWhiteSpace? = element.siblings(withItself = false, forward = false) .takeWhile { !elementClass.isInstance(it) } .firstOrNull { it is PsiWhiteSpace && it.textContains('\n') } as? PsiWhiteSpace protected fun TList.elements(): List<TElement> = allChildren.filter { elementClass.isInstance(it) } .map { @Suppress("UNCHECKED_CAST") it as TElement } .toList() protected fun isApplicableCaretOffset(caretOffset: Int, element: TList): Boolean { val elementBeforeCaret = element.containingFile.findElementAt(caretOffset - 1) ?: return true if (elementBeforeCaret.node.elementType != KtTokens.RPAR) return true return elementBeforeCaret.parent == element } } class ChopParameterListIntention : AbstractChopListIntention<KtParameterList, KtParameter>( KtParameterList::class.java, KtParameter::class.java, KotlinBundle.lazyMessage("put.parameters.on.separate.lines") ) { override fun isApplicableTo(element: KtParameterList, caretOffset: Int): Boolean { if (element.parent is KtFunctionLiteral) return false return super.isApplicableTo(element, caretOffset) } override fun leftParOnNewLine(commonCodeStyleSettings: CommonCodeStyleSettings): Boolean { return commonCodeStyleSettings.METHOD_PARAMETERS_LPAREN_ON_NEXT_LINE } override fun rightParOnNewLine(commonCodeStyleSettings: CommonCodeStyleSettings): Boolean { return commonCodeStyleSettings.METHOD_PARAMETERS_RPAREN_ON_NEXT_LINE } } class ChopArgumentListIntention : AbstractChopListIntention<KtValueArgumentList, KtValueArgument>( KtValueArgumentList::class.java, KtValueArgument::class.java, KotlinBundle.lazyMessage("put.arguments.on.separate.lines") ) { override fun leftParOnNewLine(commonCodeStyleSettings: CommonCodeStyleSettings): Boolean { return commonCodeStyleSettings.CALL_PARAMETERS_LPAREN_ON_NEXT_LINE } override fun rightParOnNewLine(commonCodeStyleSettings: CommonCodeStyleSettings): Boolean { return commonCodeStyleSettings.CALL_PARAMETERS_RPAREN_ON_NEXT_LINE } }
apache-2.0
98853139230fa3eff02619ff9df4f2e9
44.777778
158
0.743065
4.913118
false
false
false
false
mdaniel/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createVariable/CreateLocalVariableActionFactory.kt
1
4169
// 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.quickfix.createFromUsage.createVariable import com.intellij.codeInsight.intention.IntentionAction import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.psi.PsiElement import com.intellij.psi.util.findParentOfType import org.jetbrains.kotlin.diagnostics.Diagnostic import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.intentions.ConvertToBlockBodyIntention import org.jetbrains.kotlin.idea.quickfix.KotlinSingleIntentionActionFactory import org.jetbrains.kotlin.idea.quickfix.createFromUsage.CreateFromUsageFixBase import org.jetbrains.kotlin.idea.quickfix.createFromUsage.callableBuilder.* import org.jetbrains.kotlin.idea.util.application.executeCommand import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.getAssignmentByLHS import org.jetbrains.kotlin.psi.psiUtil.getParentOfTypeAndBranch import org.jetbrains.kotlin.psi.psiUtil.getQualifiedElement import org.jetbrains.kotlin.types.Variance import java.util.* object CreateLocalVariableActionFactory : KotlinSingleIntentionActionFactory() { override fun createAction(diagnostic: Diagnostic): IntentionAction? { val refExpr = diagnostic.psiElement.findParentOfType<KtNameReferenceExpression>(strict = false) ?: return null if (refExpr.getQualifiedElement() != refExpr) return null if (refExpr.getParentOfTypeAndBranch<KtCallableReferenceExpression> { callableReference } != null) return null if (getContainer(refExpr) == null) return null return CreateLocalFromUsageAction(refExpr) } private fun getContainer(refExpr: KtNameReferenceExpression): KtElement? { var element: PsiElement = refExpr while (true) { when (val parent = element.parent) { null, is KtAnnotationEntry -> return null is KtBlockExpression -> return parent is KtDeclarationWithBody -> { if (parent.bodyExpression == element) return parent element = parent } else -> element = parent } } } class CreateLocalFromUsageAction(refExpr: KtNameReferenceExpression, val propertyName: String = refExpr.getReferencedName()) : CreateFromUsageFixBase<KtNameReferenceExpression>(refExpr) { override fun getText(): String = KotlinBundle.message("fix.create.from.usage.local.variable", propertyName) override fun invoke(project: Project, editor: Editor?, file: KtFile) { val refExpr = element ?: return val container = getContainer(refExpr) ?: return val assignment = refExpr.getAssignmentByLHS() val varExpected = assignment != null var originalElement: KtExpression = assignment ?: refExpr val actualContainer = when (container) { is KtBlockExpression -> container else -> ConvertToBlockBodyIntention.convert(container as KtDeclarationWithBody, true).bodyExpression!! } as KtBlockExpression if (actualContainer != container) { val bodyExpression = actualContainer.statements.first()!! originalElement = (bodyExpression as? KtReturnExpression)?.returnedExpression ?: bodyExpression } val typeInfo = TypeInfo( originalElement.getExpressionForTypeGuess(), if (varExpected) Variance.INVARIANT else Variance.OUT_VARIANCE ) val propertyInfo = PropertyInfo(propertyName, TypeInfo.Empty, typeInfo, varExpected, Collections.singletonList(actualContainer)) with(CallableBuilderConfiguration(listOfNotNull(propertyInfo), originalElement, file, editor).createBuilder()) { placement = CallablePlacement.NoReceiver(actualContainer) project.executeCommand(text) { build() } } } } }
apache-2.0
9a90633f22b32ac4a2d26220bdec5463
49.228916
158
0.710962
5.633784
false
false
false
false
mdaniel/intellij-community
platform/lang-impl/testSources/com/intellij/openapi/roots/TestCustomSourceRoot.kt
7
3854
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.openapi.roots import com.intellij.jps.impl.JpsPluginBean import com.intellij.openapi.Disposable import com.intellij.openapi.application.runWriteActionAndWait import com.intellij.openapi.extensions.DefaultPluginDescriptor import com.intellij.openapi.extensions.PluginId import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.io.FileUtil import com.intellij.util.lang.UrlClassLoader import org.jdom.Element import org.jetbrains.jps.model.ex.JpsElementBase import org.jetbrains.jps.model.ex.JpsElementTypeBase import org.jetbrains.jps.model.module.JpsModuleSourceRootType import org.jetbrains.jps.model.serialization.JpsModelSerializerExtension import org.jetbrains.jps.model.serialization.module.JpsModuleSourceRootPropertiesSerializer import java.io.File class TestCustomRootModelSerializerExtension : JpsModelSerializerExtension() { override fun getModuleSourceRootPropertiesSerializers(): List<JpsModuleSourceRootPropertiesSerializer<*>> = listOf(TestCustomSourceRootPropertiesSerializer(TestCustomSourceRootType.INSTANCE, TestCustomSourceRootType.TYPE_ID)) companion object { fun registerTestCustomSourceRootType(tempPluginRoot: File, disposable: Disposable) { val jpsPluginDisposable = Disposer.newDisposable() Disposer.register(disposable, Disposable { runWriteActionAndWait { Disposer.dispose(jpsPluginDisposable) } }) FileUtil.writeToFile(File(tempPluginRoot, "META-INF/services/${JpsModelSerializerExtension::class.java.name}"), TestCustomRootModelSerializerExtension::class.java.name) val pluginClassLoader = UrlClassLoader.build() .parent(TestCustomRootModelSerializerExtension::class.java.classLoader) .files(listOf(tempPluginRoot.toPath())) .get() val pluginDescriptor = DefaultPluginDescriptor(PluginId.getId("com.intellij.custom.source.root.test"), pluginClassLoader) JpsPluginBean.EP_NAME.point.registerExtension(JpsPluginBean(), pluginDescriptor, jpsPluginDisposable) } } } class TestCustomSourceRootType private constructor() : JpsElementTypeBase<TestCustomSourceRootProperties>(), JpsModuleSourceRootType<TestCustomSourceRootProperties> { override fun isForTests(): Boolean = false override fun createDefaultProperties(): TestCustomSourceRootProperties = TestCustomSourceRootProperties("default properties") companion object { val INSTANCE = TestCustomSourceRootType() const val TYPE_ID = "custom-source-root-type" } } class TestCustomSourceRootProperties(initialTestString: String?) : JpsElementBase<TestCustomSourceRootProperties>() { var testString: String? = initialTestString set(value) { if (value != field) { field = value fireElementChanged() } } override fun createCopy(): TestCustomSourceRootProperties { return TestCustomSourceRootProperties(testString) } override fun applyChanges(modified: TestCustomSourceRootProperties) { testString = modified.testString } } class TestCustomSourceRootPropertiesSerializer( type: JpsModuleSourceRootType<TestCustomSourceRootProperties>, typeId: String) : JpsModuleSourceRootPropertiesSerializer<TestCustomSourceRootProperties>(type, typeId) { override fun loadProperties(sourceRootTag: Element): TestCustomSourceRootProperties { val testString = sourceRootTag.getAttributeValue("testString") return TestCustomSourceRootProperties(testString) } override fun saveProperties(properties: TestCustomSourceRootProperties, sourceRootTag: Element) { val testString = properties.testString if (testString != null) { sourceRootTag.setAttribute("testString", testString) } } }
apache-2.0
a4527570b97f052a9b01648aeb135153
40.891304
166
0.791645
5.382682
false
true
false
false
MER-GROUP/intellij-community
platform/configuration-store-impl/src/ImportSettingsAction.kt
4
5790
/* * Copyright 2000-2015 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.ide.actions import com.intellij.ide.IdeBundle import com.intellij.ide.plugins.PluginManager import com.intellij.ide.startup.StartupActionScriptManager import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.PlatformDataKeys import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.ApplicationNamesInfo import com.intellij.openapi.application.PathManager import com.intellij.openapi.application.ex.ApplicationEx import com.intellij.openapi.project.DumbAware import com.intellij.openapi.ui.Messages import com.intellij.openapi.updateSettings.impl.UpdateSettings import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.util.io.FileUtilRt import com.intellij.openapi.util.io.getParentPath import gnu.trove.THashSet import java.io.File import java.io.IOException import java.io.InputStream import java.util.zip.ZipException import java.util.zip.ZipInputStream private class ImportSettingsAction : AnAction(), DumbAware { override fun actionPerformed(e: AnActionEvent) { val dataContext = e.dataContext val component = PlatformDataKeys.CONTEXT_COMPONENT.getData(dataContext) ChooseComponentsToExportDialog.chooseSettingsFile(PathManager.getConfigPath(), component, IdeBundle.message("title.import.file.location"), IdeBundle.message("prompt.choose.import.file.path")) .done { val saveFile = File(it) try { doImport(saveFile) } catch (e1: ZipException) { Messages.showErrorDialog( IdeBundle.message("error.reading.settings.file", presentableFileName(saveFile), e1.message, promptLocationMessage()), IdeBundle.message("title.invalid.file")) } catch (e1: IOException) { Messages.showErrorDialog(IdeBundle.message("error.reading.settings.file.2", presentableFileName(saveFile), e1.message), IdeBundle.message("title.error.reading.file")) } } } private fun doImport(saveFile: File) { if (!saveFile.exists()) { Messages.showErrorDialog(IdeBundle.message("error.cannot.find.file", presentableFileName(saveFile)), IdeBundle.message("title.file.not.found")) return } val relativePaths = getPaths(saveFile.inputStream()) if (!relativePaths.contains(ImportSettingsFilenameFilter.SETTINGS_JAR_MARKER)) { Messages.showErrorDialog( IdeBundle.message("error.file.contains.no.settings.to.import", presentableFileName(saveFile), promptLocationMessage()), IdeBundle.message("title.invalid.file")) return } val configPath = FileUtil.toSystemIndependentName(PathManager.getConfigPath()) val dialog = ChooseComponentsToExportDialog(getExportableComponentsMap(false, true, onlyPaths = relativePaths), false, IdeBundle.message("title.select.components.to.import"), IdeBundle.message("prompt.check.components.to.import")) if (!dialog.showAndGet()) { return } val tempFile = File(PathManager.getPluginTempPath(), saveFile.name) FileUtil.copy(saveFile, tempFile) val filenameFilter = ImportSettingsFilenameFilter(getRelativeNamesToExtract(dialog.exportableComponents)) StartupActionScriptManager.addActionCommand(StartupActionScriptManager.UnzipCommand(tempFile, File(configPath), filenameFilter)) // remove temp file StartupActionScriptManager.addActionCommand(StartupActionScriptManager.DeleteCommand(tempFile)) UpdateSettings.getInstance().forceCheckForUpdateAfterRestart() val key = if (ApplicationManager.getApplication().isRestartCapable) "message.settings.imported.successfully.restart" else "message.settings.imported.successfully" if (Messages.showOkCancelDialog(IdeBundle.message(key, ApplicationNamesInfo.getInstance().productName, ApplicationNamesInfo.getInstance().fullProductName), IdeBundle.message("title.restart.needed"), Messages.getQuestionIcon()) == Messages.OK) { (ApplicationManager.getApplication() as ApplicationEx).restart(true) } } private fun getRelativeNamesToExtract(chosenComponents: Set<ExportableItem>): Set<String> { val result = THashSet<String>() for (chosenComponent in chosenComponents) { for (exportFile in chosenComponent.files) { result.add(FileUtil.toSystemIndependentName(FileUtilRt.getRelativePath(File(PathManager.getConfigPath()), exportFile)!!)) } } result.add(PluginManager.INSTALLED_TXT) return result } private fun presentableFileName(file: File) = "'" + FileUtil.toSystemDependentName(file.path) + "'" private fun promptLocationMessage() = IdeBundle.message("message.please.ensure.correct.settings") } fun getPaths(input: InputStream): Set<String> { val result = THashSet<String>() val zipIn = ZipInputStream(input) try { while (true) { val entry = zipIn.nextEntry ?: break var path = entry.name result.add(path) while (true) { path = getParentPath(path) ?: break result.add("$path/") } } } finally { zipIn.close() } return result }
apache-2.0
de8b43bf21df9af25f9f33058f0c1d7b
39.774648
195
0.746978
4.680679
false
false
false
false
iPoli/iPoli-android
app/src/main/java/io/ipoli/android/repeatingquest/show/RepeatingQuestViewController.kt
1
12367
package io.ipoli.android.repeatingquest.show import android.content.res.ColorStateList import android.graphics.drawable.GradientDrawable import android.os.Bundle import android.support.annotation.ColorInt import android.support.design.widget.AppBarLayout import android.support.v7.widget.LinearLayoutManager import android.view.* import io.ipoli.android.MainActivity import io.ipoli.android.R import io.ipoli.android.common.ViewUtils import io.ipoli.android.common.redux.android.ReduxViewController import io.ipoli.android.common.text.DateFormatter import io.ipoli.android.common.text.DurationFormatter import io.ipoli.android.common.view.* import io.ipoli.android.common.view.recyclerview.BaseRecyclerViewAdapter import io.ipoli.android.common.view.recyclerview.SimpleRecyclerViewViewModel import io.ipoli.android.common.view.recyclerview.SimpleViewHolder import io.ipoli.android.tag.Tag import kotlinx.android.synthetic.main.controller_repeating_quest.view.* import kotlinx.android.synthetic.main.item_quest_tag_list.view.* import kotlinx.android.synthetic.main.item_repeating_quest_sub_quest.view.* import kotlinx.android.synthetic.main.repeating_quest_progress_indicator_empty.view.* /** * Created by Venelin Valkov <[email protected]> * on 02/21/2018. */ class RepeatingQuestViewController(args: Bundle? = null) : ReduxViewController<RepeatingQuestAction, RepeatingQuestViewState, RepeatingQuestReducer>(args) { override val reducer = RepeatingQuestReducer private var repeatingQuestId: String = "" private val appBarOffsetListener = object : AppBarStateChangeListener() { override fun onStateChanged(appBarLayout: AppBarLayout, state: State) { appBarLayout.post { if (state == State.EXPANDED) { val supportActionBar = (activity as MainActivity).supportActionBar supportActionBar?.setDisplayShowTitleEnabled(false) } else if (state == State.COLLAPSED) { val supportActionBar = (activity as MainActivity).supportActionBar supportActionBar?.setDisplayShowTitleEnabled(true) } } } } constructor( repeatingQuestId: String ) : this() { this.repeatingQuestId = repeatingQuestId } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup, savedViewState: Bundle? ): View { setHasOptionsMenu(true) applyStatusBarColors = false val view = container.inflate(R.layout.controller_repeating_quest) setToolbar(view.toolbar) view.collapsingToolbarContainer.isTitleEnabled = false view.subQuestList.layoutManager = LinearLayoutManager(activity!!) view.subQuestList.adapter = SubQuestsAdapter() view.addQuest.onDebounceClick { navigate().toReschedule( includeToday = true, isNewQuest = true, listener = { date, time, _ -> dispatch(RepeatingQuestAction.AddQuest(repeatingQuestId, date, time)) }) } view.appbar.addOnOffsetChangedListener(appBarOffsetListener) return view } override fun onCreateLoadAction() = RepeatingQuestAction.Load(repeatingQuestId) override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { super.onCreateOptionsMenu(menu, inflater) inflater.inflate(R.menu.repeating_quest_menu, menu) } override fun onOptionsItemSelected(item: MenuItem) = when (item.itemId) { android.R.id.home -> router.handleBack() R.id.actionEdit -> { showEdit() true } R.id.actionDelete -> { navigate().toConfirmation( stringRes(R.string.dialog_confirmation_title), stringRes(R.string.dialog_remove_repeating_quest_message) ) { dispatch(RepeatingQuestAction.Remove(repeatingQuestId)) router.handleBack() } true } else -> super.onOptionsItemSelected(item) } private fun showEdit() { navigateFromRoot().toEditRepeatingQuest(repeatingQuestId) } override fun onAttach(view: View) { super.onAttach(view) showBackButton() val showTitle = appBarOffsetListener.currentState != AppBarStateChangeListener.State.EXPANDED (activity as MainActivity).supportActionBar?.setDisplayShowTitleEnabled(showTitle) } override fun onDetach(view: View) { (activity as MainActivity).supportActionBar?.setDisplayShowTitleEnabled(true) super.onDetach(view) } override fun onDestroyView(view: View) { view.appbar.removeOnOffsetChangedListener(appBarOffsetListener) super.onDestroyView(view) } override fun render(state: RepeatingQuestViewState, view: View) { when (state.type) { RepeatingQuestViewState.StateType.REPEATING_QUEST_CHANGED -> { colorLayout(state, view) renderName(state, view) renderTags(state.tags, view) renderSubQuests(state, view) renderProgress(state, view) renderSummaryStats(state, view) renderNote(state, view) } RepeatingQuestViewState.StateType.HISTORY_CHANGED -> view.historyChart.updateData(state.history!!) else -> { } } } private fun renderTags( tags: List<Tag>, view: View ) { view.tagList.removeAllViews() val inflater = LayoutInflater.from(activity!!) tags.forEach { tag -> val item = inflater.inflate(R.layout.item_quest_tag_list, view.tagList, false) renderTag(item, tag) view.tagList.addView(item) } } private fun renderTag(view: View, tag: Tag) { view.tagName.text = tag.name val indicator = view.tagName.compoundDrawablesRelative[0] as GradientDrawable indicator.setColor(colorRes(tag.color.androidColor.color500)) } private fun renderNote( state: RepeatingQuestViewState, view: View ) { if (state.note != null && state.note.isNotBlank()) { view.note.setMarkdown(state.note) } else { view.note.setText(R.string.tap_to_add_note) view.note.setTextColor(colorRes(colorTextSecondaryResource)) } view.note.setOnClickListener { showEdit() } } private fun renderSubQuests(state: RepeatingQuestViewState, view: View) { if (state.subQuestNames.isEmpty()) { view.emptySubQuestList.visible() view.subQuestList.gone() } else { view.emptySubQuestList.gone() (view.subQuestList.adapter as SubQuestsAdapter).updateAll(state.subQuestNames.map { SimpleRecyclerViewViewModel( it ) }) view.subQuestList.visible() } } private fun renderSummaryStats( state: RepeatingQuestViewState, view: View ) { view.rqLastComplete.text = state.lastCompletedDateText view.rqNextDate.text = state.nextScheduledDateText view.rqScheduledTime.text = state.scheduledTimeText } private fun renderName( state: RepeatingQuestViewState, view: View ) { toolbarTitle = state.name view.questName.text = state.name } private fun renderProgress( state: RepeatingQuestViewState, view: View ) { val inflater = LayoutInflater.from(view.context) view.progressContainer.removeAllViews() state.progressViewModels.forEachIndexed { index, vm -> val progressView = inflater.inflate( R.layout.repeating_quest_progress_indicator_empty, view.progressContainer, false ) val indicatorView = progressView.indicatorDot.background as GradientDrawable indicatorView.setStroke( ViewUtils.dpToPx(2f, view.context).toInt(), colorRes(R.color.md_white) ) indicatorView.setColor(vm.color) if (index == 0) { progressView.indicatorLink.gone() } view.progressContainer.addView(progressView) } view.frequencyText.text = state.frequencyText } private fun colorLayout( state: RepeatingQuestViewState, view: View ) { view.appbar.setBackgroundColor(colorRes(state.color500)) view.toolbar.setBackgroundColor(colorRes(state.color500)) view.collapsingToolbarContainer.setContentScrimColor(colorRes(state.color500)) activity?.window?.navigationBarColor = colorRes(state.color500) activity?.window?.statusBarColor = colorRes(state.color700) } inner class SubQuestsAdapter : BaseRecyclerViewAdapter<SimpleRecyclerViewViewModel<String>>( R.layout.item_repeating_quest_sub_quest ) { override fun onBindViewModel( vm: SimpleRecyclerViewViewModel<String>, view: View, holder: SimpleViewHolder ) { view.subQuestIndicator.backgroundTintList = ColorStateList.valueOf(colorRes(colorTextSecondaryResource)) view.subQuestName.text = vm.value } } private val RepeatingQuestViewState.color500 get() = color.androidColor.color500 private val RepeatingQuestViewState.color700 get() = color.androidColor.color700 private val RepeatingQuestViewState.progressViewModels get() = progress.map { when (it) { RepeatingQuestViewState.ProgressModel.COMPLETE -> { ProgressViewModel(colorRes(R.color.md_white)) } RepeatingQuestViewState.ProgressModel.INCOMPLETE -> { ProgressViewModel(colorRes(color500)) } } } private val RepeatingQuestViewState.lastCompletedDateText get() = when { lastCompletedDate != null -> { DateFormatter.format(view!!.context, lastCompletedDate) } else -> stringRes(R.string.never) } private val RepeatingQuestViewState.nextScheduledDateText get() = when { isCompleted -> stringRes(R.string.completed) nextScheduledDate != null -> { DateFormatter.format(view!!.context, nextScheduledDate) } else -> stringRes(R.string.unscheduled) } private val RepeatingQuestViewState.scheduledTimeText: String get() = if (startTime != null) { "${startTime.toString(shouldUse24HourFormat)} - ${endTime!!.toString( shouldUse24HourFormat )}" } else stringRes(R.string.for_time, DurationFormatter.formatShort(view!!.context, duration)) private val RepeatingQuestViewState.frequencyText get () = when (repeat) { RepeatingQuestViewState.RepeatType.Daily -> { "Every day" } is RepeatingQuestViewState.RepeatType.Weekly -> { repeat.frequency.let { if (it == 1) { "Once per week" } else { "$it times per week" } } } is RepeatingQuestViewState.RepeatType.Monthly -> { repeat.frequency.let { if (it == 1) { "Once per month" } else { "$it times per month" } } } RepeatingQuestViewState.RepeatType.Yearly -> { "Once per year" } RepeatingQuestViewState.RepeatType.Manual -> { stringRes(R.string.manual_schedule_repeat_pattern) } } data class ProgressViewModel(@ColorInt val color: Int) }
gpl-3.0
0ae7fa2d8baf2724883e392c7386e476
32.884932
101
0.613164
5.076765
false
false
false
false
iPoli/iPoli-android
app/src/main/java/io/ipoli/android/quest/CompletedQuestViewState.kt
1
5959
package io.ipoli.android.quest import io.ipoli.android.common.AppState import io.ipoli.android.common.BaseViewStateReducer import io.ipoli.android.common.DataLoadedAction import io.ipoli.android.common.datetime.Duration import io.ipoli.android.common.datetime.Minute import io.ipoli.android.common.datetime.Time import io.ipoli.android.common.datetime.minutes import io.ipoli.android.common.redux.Action import io.ipoli.android.common.redux.BaseViewState import io.ipoli.android.common.view.AndroidColor import io.ipoli.android.common.view.AndroidIcon import io.ipoli.android.pet.Food import io.ipoli.android.quest.CompletedQuestViewState.StateType.* import io.ipoli.android.tag.Tag import org.threeten.bp.LocalDate /** * Created by Polina Zhelyazkova <[email protected]> * on 1/24/18. */ sealed class CompletedQuestAction : Action { data class Load(val questId: String) : CompletedQuestAction() { override fun toMap() = mapOf("questId" to questId) } } object CompletedQuestReducer : BaseViewStateReducer<CompletedQuestViewState>() { override val stateKey = key<CompletedQuestViewState>() override fun reduce( state: AppState, subState: CompletedQuestViewState, action: Action ) = when (action) { is DataLoadedAction.QuestChanged -> { val quest = action.quest if (!quest.isCompleted) { subState.copy( type = QUEST_UNDO_COMPLETED ) } else { val timer = if (!quest.hasTimer) { CompletedQuestViewState.Timer.Untracked } else if (quest.hasPomodoroTimer) { val timeRanges = quest.timeRanges val completedCnt = timeRanges.filter { it.end != null }.size / 2 val work = timeRanges.filter { it.type == TimeRange.Type.POMODORO_WORK } val workDuration = work.map { it.duration }.sum() val workActualDuration = work.map { it.actualDuration() }.sumBy { it.asMinutes.intValue } val breaks = timeRanges.filter { it.type == TimeRange.Type.POMODORO_LONG_BREAK || it.type == TimeRange.Type.POMODORO_SHORT_BREAK } val breakDuration = breaks.map { it.duration }.sum() val breakActualDuration = breaks.map { it.actualDuration() }.sumBy { it.asMinutes.intValue } CompletedQuestViewState.Timer.Pomodoro( completedPomodoros = completedCnt, totalPomodoros = quest.totalPomodoros!!, workDuration = workActualDuration.minutes, overdueWorkDuration = workActualDuration.minutes - workDuration.minutes, breakDuration = breakActualDuration.minutes, overdueBreakDuration = breakActualDuration.minutes - breakDuration.minutes ) } else { CompletedQuestViewState.Timer.Countdown( quest.duration.minutes, quest.actualDuration.asMinutes - quest.duration.minutes ) } val player = state.dataState.player!! val reward = quest.reward!! subState.copy( type = DATA_LOADED, name = quest.name, tags = quest.tags, icon = quest.icon?.let { AndroidIcon.valueOf(it.name) }, color = AndroidColor.valueOf(quest.color.name), totalDuration = quest.actualDuration.asMinutes, completeAt = quest.completedAtDate!!, startedAt = quest.actualStartTime, finishedAt = quest.completedAtTime, timer = timer, experience = reward.experience, coins = reward.coins, bounty = reward.bounty.let { if (it is Quest.Bounty.Food) { it.food } else { null } }, playerLevel = player.level, playerLevelProgress = player.experienceProgressForLevel, playerLevelMaxProgress = player.experienceForNextLevel ) } } else -> subState } override fun defaultState() = CompletedQuestViewState(LOADING) } data class CompletedQuestViewState( val type: StateType, val name: String? = null, val tags: List<Tag> = emptyList(), val icon: AndroidIcon? = null, val color: AndroidColor? = null, val totalDuration: Duration<Minute>? = null, val completeAt: LocalDate? = null, val startedAt: Time? = null, val finishedAt: Time? = null, val timer: Timer? = null, val experience: Int? = null, val coins: Int? = null, val bounty: Food? = null, val playerLevel: Int? = null, val playerLevelProgress: Int? = null, val playerLevelMaxProgress: Int? = null ) : BaseViewState() { enum class StateType { LOADING, DATA_LOADED, QUEST_UNDO_COMPLETED } sealed class Timer { data class Pomodoro( val completedPomodoros: Int, val totalPomodoros: Int, val workDuration: Duration<Minute>, val overdueWorkDuration: Duration<Minute>, val breakDuration: Duration<Minute>, val overdueBreakDuration: Duration<Minute> ) : Timer() data class Countdown( val duration: Duration<Minute>, val overdueDuration: Duration<Minute> ) : Timer() object Untracked : Timer() } }
gpl-3.0
dda76818e66a37522a4f5077326dddef
34.688623
141
0.569391
5.007563
false
false
false
false
GunoH/intellij-community
plugins/ide-features-trainer/src/training/learn/lesson/general/navigation/FindInFilesLesson.kt
2
8927
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package training.learn.lesson.general.navigation import com.intellij.find.FindBundle import com.intellij.find.FindInProjectSettings import com.intellij.find.FindManager import com.intellij.find.SearchTextArea import com.intellij.find.impl.FindInProjectSettingsBase import com.intellij.find.impl.FindPopupItem import com.intellij.find.impl.FindPopupPanel import com.intellij.icons.AllIcons import com.intellij.openapi.actionSystem.impl.ActionButton import com.intellij.openapi.project.Project import com.intellij.util.ui.UIUtil import org.assertj.swing.core.MouseClickInfo import org.assertj.swing.data.TableCell import org.assertj.swing.fixture.JTableFixture import org.assertj.swing.fixture.JTextComponentFixture import training.dsl.* import training.learn.LessonsBundle import training.learn.course.KLesson import training.ui.LearningUiUtil.findComponentWithTimeout import training.util.isToStringContains import java.awt.event.InputEvent import java.awt.event.KeyEvent import javax.swing.* class FindInFilesLesson(override val sampleFilePath: String) : KLesson("Find in files", LessonsBundle.message("find.in.files.lesson.name")) { override val lessonContent: LessonContext.() -> Unit = { sdkConfigurationTasks() prepareRuntimeTask { resetFindSettings(project) } lateinit var showPopupTaskId: TaskContext.TaskId task("FindInPath") { showPopupTaskId = taskId text(LessonsBundle.message("find.in.files.show.find.popup", action(it), LessonUtil.actionName(it))) triggerUI().component { popup: FindPopupPanel -> !popup.helper.isReplaceState } test { actions(it) } } task("apple") { text(LessonsBundle.message("find.in.files.type.to.find", code(it))) stateCheck { getFindPopup()?.stringToFind?.toLowerCase() == it } restoreByUi() test { type(it) } } task { val wholeWordsButtonText = FindBundle.message("find.whole.words").dropMnemonic() text(LessonsBundle.message("find.in.files.whole.words", code("apple"), code("pineapple"), icon(AllIcons.Actions.Words), LessonUtil.rawKeyStroke(KeyStroke.getKeyStroke(KeyEvent.VK_W, InputEvent.ALT_DOWN_MASK)))) highlightAndTriggerWhenButtonSelected(wholeWordsButtonText) showWarningIfPopupClosed(false) test(waitEditorToBeReady = false) { ideFrame { actionButton(wholeWordsButtonText).click() } } } val neededText = "apple..." task { triggerAndBorderHighlight().componentPart { table: JTable -> val rowIndex = table.findLastRowIndexOfItemWithText(neededText) if (rowIndex >= 0) { table.getCellRect(rowIndex, 0, false) } else null } restoreByTimer(1000) transparentRestore = true } task { text(LessonsBundle.message("find.in.files.select.row", action("EditorUp"), action("EditorDown"))) stateCheck { isSelectedNeededItem(neededText) } restoreByUi(restoreId = showPopupTaskId) test { ideFrame { val table = previous.ui as? JTable ?: error("No table") val tableFixture = JTableFixture(robot(), table) val rowIndex = { table.findLastRowIndexOfItemWithText(neededText) } tableFixture.pointAt(TableCell.row(rowIndex()).column(0)) // It seems, the list may change for a while tableFixture.click(TableCell.row(rowIndex()).column(0), MouseClickInfo.leftButton()) } } } task { text(LessonsBundle.message("find.in.files.go.to.file", LessonUtil.rawEnter())) stateCheck { virtualFile.name != sampleFilePath.substringAfterLast('/') } restoreState { !isSelectedNeededItem(neededText) } test { invokeActionViaShortcut("ENTER") } } task("ReplaceInPath") { text(LessonsBundle.message("find.in.files.show.replace.popup", action(it), LessonUtil.actionName(it))) triggerUI().component { popup: FindPopupPanel -> popup.helper.isReplaceState } test { actions(it) } } task("orange") { text(LessonsBundle.message("find.in.files.type.to.replace", code("apple"), code(it))) triggerAndBorderHighlight().component { ui: SearchTextArea -> it.startsWith(ui.textArea.text) && UIUtil.getParentOfType(FindPopupPanel::class.java, ui) != null } stateCheck { getFindPopup()?.helper?.model?.let { model -> model.stringToReplace == it && model.stringToFind == "apple" } ?: false } restoreByUi() test { ideFrame { val textArea = findComponentWithTimeout { textArea: JTextArea -> textArea.text == "" } JTextComponentFixture(robot(), textArea).click() type(it) } } } task { val directoryScopeText = FindBundle.message("find.popup.scope.directory").dropMnemonic() text(LessonsBundle.message("find.in.files.select.directory", strong(directoryScopeText), LessonUtil.rawKeyStroke(KeyStroke.getKeyStroke(KeyEvent.VK_D, InputEvent.ALT_DOWN_MASK)))) highlightAndTriggerWhenButtonSelected(directoryScopeText) showWarningIfPopupClosed(true) test { ideFrame { actionButton(directoryScopeText).click() } } } val replaceButtonText = FindBundle.message("find.replace.command") task { val replaceAllButtonText = FindBundle.message("find.popup.replace.all.button").dropMnemonic() text(LessonsBundle.message("find.in.files.press.replace.all", strong(replaceAllButtonText))) triggerAndFullHighlight().component { button: JButton -> button.text.isToStringContains(replaceAllButtonText) } triggerAndFullHighlight().component { button: JButton -> UIUtil.getParentOfType(JDialog::class.java, button)?.isModal == true && button.text.isToStringContains(replaceButtonText) } showWarningIfPopupClosed(true) test { ideFrame { button(replaceAllButtonText).click() } } } task { addFutureStep { (previous.ui as? JButton)?.addActionListener { completeStep() } } text(LessonsBundle.message("find.in.files.confirm.replace", strong(replaceButtonText))) restoreByUi() test(waitEditorToBeReady = false) { dialog(title = "Replace All") { button(replaceButtonText).click() } } } } private fun TaskRuntimeContext.isSelectedNeededItem(neededText: String): Boolean { return (previous.ui as? JTable)?.let { it.isShowing && it.selectedRow != -1 && it.selectedRow == it.findLastRowIndexOfItemWithText(neededText) } == true } private fun TaskRuntimeContext.getFindPopup(): FindPopupPanel? { return UIUtil.getParentOfType(FindPopupPanel::class.java, focusOwner) } private fun TaskContext.highlightAndTriggerWhenButtonSelected(buttonText: String) { triggerAndFullHighlight().component { button: ActionButton -> button.action.templateText == buttonText } triggerUI().component { button: ActionButton -> button.action.templateText == buttonText && button.isSelected } } private fun JTable.findLastRowIndexOfItemWithText(textToFind: String): Int { for (ind in (rowCount - 1) downTo 0) { val item = getValueAt(ind, 0) as? FindPopupItem if (item?.presentableText?.contains(textToFind, true) == true) { return ind } } return -1 } private fun TaskContext.showWarningIfPopupClosed(isReplacePopup: Boolean) { val actionId = if (isReplacePopup) "ReplaceInPath" else "FindInPath" showWarning(LessonsBundle.message("find.in.files.popup.closed.warning.message", action(actionId), LessonUtil.actionName(actionId))) { getFindPopup()?.helper?.isReplaceState != isReplacePopup } } override val testScriptProperties = TaskTestContext.TestScriptProperties(10) override val helpLinks: Map<String, String> get() = mapOf( Pair(LessonsBundle.message("find.in.files.help.link"), LessonUtil.getHelpLink("finding-and-replacing-text-in-project.html")), ) } private fun resetFindSettings(project: Project) { FindManager.getInstance(project).findInProjectModel.apply { isWholeWordsOnly = false stringToFind = "" stringToReplace = "" directoryName = null } (FindInProjectSettings.getInstance(project) as? FindInProjectSettingsBase) ?.loadState(FindInProjectSettingsBase()) }
apache-2.0
a5a840d68ae0bd5535302d2617980b59
35.440816
158
0.669654
4.594442
false
true
false
false
ktorio/ktor
ktor-io/common/src/io/ktor/utils/io/core/internal/Unsafe.kt
1
1853
@file:Suppress("KDocMissingDocumentation") package io.ktor.utils.io.core.internal import io.ktor.utils.io.core.* import kotlin.jvm.* import kotlin.native.concurrent.* /** * API marked with this annotation is internal and extremely fragile and not intended to be used by library users. * Such API could be changed without notice including rename, removal and behaviour change. * Also using API marked with this annotation could cause data loss or any other damage. */ @Suppress("DEPRECATION") @RequiresOptIn(level = RequiresOptIn.Level.ERROR) public annotation class DangerousInternalIoApi internal fun ByteReadPacket.unsafeAppend(builder: BytePacketBuilder): Int { val builderSize = builder.size val builderHead = builder.stealAll() ?: return 0 if (builderSize <= PACKET_MAX_COPY_SIZE && builderHead.next == null && tryWriteAppend(builderHead)) { builder.afterBytesStolen() return builderSize } append(builderHead) return builderSize } @PublishedApi internal fun Input.prepareReadFirstHead(minSize: Int): ChunkBuffer? = prepareReadHead(minSize) @PublishedApi internal fun Input.completeReadHead(current: ChunkBuffer) { when { current === this -> return !current.canRead() -> ensureNext(current) current.endGap < Buffer.ReservedSize -> fixGapAfterRead(current) else -> headPosition = current.readPosition } } @PublishedApi internal fun Input.prepareReadNextHead(current: ChunkBuffer): ChunkBuffer? { if (current === this) { return if (canRead()) this else null } return ensureNextHead(current) } internal fun Output.prepareWriteHead(capacity: Int, current: ChunkBuffer?): ChunkBuffer { if (current != null) { afterHeadWrite() } return prepareWriteHead(capacity) } @JvmField internal val EmptyByteArray = ByteArray(0)
apache-2.0
2e47a70dc228c1a2980ea5ace37a945d
28.887097
114
0.731247
4.279446
false
false
false
false
inorichi/mangafeed
app/src/main/java/eu/kanade/tachiyomi/ui/manga/chapter/ChaptersAdapter.kt
2
1518
package eu.kanade.tachiyomi.ui.manga.chapter import android.content.Context import eu.kanade.tachiyomi.R import eu.kanade.tachiyomi.data.preference.PreferencesHelper import eu.kanade.tachiyomi.ui.manga.MangaController import eu.kanade.tachiyomi.ui.manga.chapter.base.BaseChaptersAdapter import eu.kanade.tachiyomi.util.system.getResourceColor import uy.kohesive.injekt.injectLazy import java.text.DateFormat import java.text.DecimalFormat import java.text.DecimalFormatSymbols class ChaptersAdapter( controller: MangaController, context: Context ) : BaseChaptersAdapter<ChapterItem>(controller) { private val preferences: PreferencesHelper by injectLazy() var items: List<ChapterItem> = emptyList() val readColor = context.getResourceColor(R.attr.colorOnSurface, 0.38f) val unreadColor = context.getResourceColor(R.attr.colorOnSurface) val unreadColorSecondary = context.getResourceColor(android.R.attr.textColorSecondary) val bookmarkedColor = context.getResourceColor(R.attr.colorAccent) val decimalFormat = DecimalFormat( "#.###", DecimalFormatSymbols() .apply { decimalSeparator = '.' } ) val relativeTime: Int = preferences.relativeTime().get() val dateFormat: DateFormat = preferences.dateFormat() override fun updateDataSet(items: List<ChapterItem>?) { this.items = items ?: emptyList() super.updateDataSet(items) } fun indexOf(item: ChapterItem): Int { return items.indexOf(item) } }
apache-2.0
8022fec30b76adf8ec0634d9f9b178e3
32
90
0.750988
4.517857
false
false
false
false
cfieber/orca
orca-queue/src/main/kotlin/com/netflix/spinnaker/orca/q/handler/CancelStageHandler.kt
1
4323
/* * 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.spinnaker.orca.CancellableStage import com.netflix.spinnaker.orca.ExecutionStatus.RUNNING import com.netflix.spinnaker.orca.Task import com.netflix.spinnaker.orca.pipeline.StageDefinitionBuilderFactory import com.netflix.spinnaker.orca.pipeline.model.Execution.ExecutionType.* import com.netflix.spinnaker.orca.pipeline.persistence.ExecutionRepository import com.netflix.spinnaker.orca.q.CancelStage import com.netflix.spinnaker.orca.q.RescheduleExecution import com.netflix.spinnaker.orca.q.RunTask import com.netflix.spinnaker.q.Queue import org.springframework.beans.factory.annotation.Qualifier import org.springframework.stereotype.Component import java.util.concurrent.Executor @Component class CancelStageHandler( override val queue: Queue, override val repository: ExecutionRepository, override val stageDefinitionBuilderFactory: StageDefinitionBuilderFactory, @Qualifier("messageHandlerPool") private val executor: Executor ) : OrcaMessageHandler<CancelStage>, StageBuilderAware { override val messageType = CancelStage::class.java override fun handle(message: CancelStage) { message.withStage { stage -> /** * When an execution ends with status !SUCCEEDED, still-running stages * remain in the RUNNING state until their running tasks are dequeued * to RunTaskHandler. For tasks leveraging getDynamicBackoffPeriod(), * stages may incorrectly report as RUNNING for a considerable length * of time, unless we short-circuit their backoff time. * * For !SUCCEEDED executions, CompleteExecutionHandler enqueues CancelStage * messages for all top-level stages. For stages still RUNNING, we requeue * RunTask messages for any RUNNING tasks, for immediate execution. This * ensures prompt stage cancellation and correct handling of onFailure or * cancel conditions. This is safe as RunTaskHandler validates execution * status before processing work. RunTask messages are idempotent for * cancelled executions, though additional work is generally avoided due * to queue deduplication. * */ if (stage.status == RUNNING) { stage.tasks .filter { it.status == RUNNING } .forEach { queue.reschedule( RunTask( stage.execution.type, stage.execution.id, stage.execution.application, stage.id, it.id, it.type ) ) } } if (stage.status.isHalt) { stage.builder().let { builder -> if (builder is CancellableStage) { // for the time being we execute this off-thread as some cancel // routines may run long enough to cause message acknowledgment to // time out. executor.execute { builder.cancel(stage) // Special case for PipelineStage to ensure prompt cancellation of // child pipelines and deployment strategies regardless of task backoff if (stage.type.equals("pipeline", true) && stage.context.containsKey("executionId")) { val childId = stage.context["executionId"] as? String if (childId != null) { val child = repository.retrieve(PIPELINE, childId) queue.push(RescheduleExecution(child)) } } } } } } } } @Suppress("UNCHECKED_CAST") private val com.netflix.spinnaker.orca.pipeline.model.Task.type get() = Class.forName(implementingClass) as Class<out Task> }
apache-2.0
0d5536791ce296e41c966d7ac67c0b26
40.171429
100
0.682628
4.851852
false
false
false
false
inorichi/mangafeed
app/src/main/java/eu/kanade/tachiyomi/ui/setting/database/ClearDatabaseController.kt
2
6235
package eu.kanade.tachiyomi.ui.setting.database import android.annotation.SuppressLint import android.app.Dialog import android.os.Bundle import android.view.LayoutInflater import android.view.Menu import android.view.MenuInflater import android.view.MenuItem import android.view.View import androidx.core.view.forEach import androidx.core.view.get import androidx.core.view.isVisible import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.google.android.material.dialog.MaterialAlertDialogBuilder import com.google.android.material.floatingactionbutton.ExtendedFloatingActionButton import dev.chrisbanes.insetter.applyInsetter import eu.davidea.flexibleadapter.FlexibleAdapter import eu.davidea.flexibleadapter.Payload import eu.kanade.tachiyomi.R import eu.kanade.tachiyomi.databinding.ClearDatabaseControllerBinding import eu.kanade.tachiyomi.ui.base.controller.DialogController import eu.kanade.tachiyomi.ui.base.controller.FabController import eu.kanade.tachiyomi.ui.base.controller.NucleusController import eu.kanade.tachiyomi.util.system.toast class ClearDatabaseController : NucleusController<ClearDatabaseControllerBinding, ClearDatabasePresenter>(), FlexibleAdapter.OnItemClickListener, FlexibleAdapter.OnUpdateListener, FabController { private var recycler: RecyclerView? = null private var adapter: FlexibleAdapter<ClearDatabaseSourceItem>? = null private var menu: Menu? = null private var actionFab: ExtendedFloatingActionButton? = null private var actionFabScrollListener: RecyclerView.OnScrollListener? = null init { setHasOptionsMenu(true) } override fun createBinding(inflater: LayoutInflater): ClearDatabaseControllerBinding { return ClearDatabaseControllerBinding.inflate(inflater) } override fun createPresenter(): ClearDatabasePresenter { return ClearDatabasePresenter() } override fun getTitle(): String? { return activity?.getString(R.string.pref_clear_database) } override fun onViewCreated(view: View) { super.onViewCreated(view) binding.recycler.applyInsetter { type(navigationBars = true) { padding() } } adapter = FlexibleAdapter<ClearDatabaseSourceItem>(null, this, true) binding.recycler.adapter = adapter binding.recycler.layoutManager = LinearLayoutManager(activity) binding.recycler.setHasFixedSize(true) adapter?.fastScroller = binding.fastScroller recycler = binding.recycler } override fun onDestroyView(view: View) { adapter = null super.onDestroyView(view) } override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { inflater.inflate(R.menu.generic_selection, menu) this.menu = menu menu.forEach { menuItem -> menuItem.isVisible = (adapter?.itemCount ?: 0) > 0 } } override fun onOptionsItemSelected(item: MenuItem): Boolean { val adapter = adapter ?: return false when (item.itemId) { R.id.action_select_all -> adapter.selectAll() R.id.action_select_inverse -> { val currentSelection = adapter.selectedPositionsAsSet val invertedSelection = (0..adapter.itemCount) .filterNot { currentSelection.contains(it) } currentSelection.clear() currentSelection.addAll(invertedSelection) } } updateFab() adapter.notifyItemRangeChanged(0, adapter.itemCount, Payload.SELECTION) return super.onOptionsItemSelected(item) } override fun onUpdateEmptyView(size: Int) { if (size > 0) { binding.emptyView.hide() } else { binding.emptyView.show(activity!!.getString(R.string.database_clean)) } menu?.forEach { menuItem -> menuItem.isVisible = size > 0 } } override fun onItemClick(view: View?, position: Int): Boolean { val adapter = adapter ?: return false adapter.toggleSelection(position) adapter.notifyItemChanged(position, Payload.SELECTION) updateFab() return true } fun setItems(items: List<ClearDatabaseSourceItem>) { adapter?.updateDataSet(items) } override fun configureFab(fab: ExtendedFloatingActionButton) { fab.setIconResource(R.drawable.ic_delete_24dp) fab.setText(R.string.action_delete) fab.hide() fab.setOnClickListener { val ctrl = ClearDatabaseSourcesDialog() ctrl.targetController = this ctrl.showDialog(router) } actionFab = fab } private fun updateFab() { val adapter = adapter ?: return if (adapter.selectedItemCount > 0) { actionFab?.show() } else { actionFab?.hide() } } override fun cleanupFab(fab: ExtendedFloatingActionButton) { actionFab?.setOnClickListener(null) actionFabScrollListener?.let { recycler?.removeOnScrollListener(it) } actionFab = null } class ClearDatabaseSourcesDialog : DialogController() { override fun onCreateDialog(savedViewState: Bundle?): Dialog { return MaterialAlertDialogBuilder(activity!!) .setMessage(R.string.clear_database_confirmation) .setPositiveButton(android.R.string.ok) { _, _ -> (targetController as? ClearDatabaseController)?.clearDatabaseForSelectedSources() } .setNegativeButton(android.R.string.cancel, null) .create() } } @SuppressLint("NotifyDataSetChanged") private fun clearDatabaseForSelectedSources() { val adapter = adapter ?: return val selectedSourceIds = adapter.selectedPositions.mapNotNull { position -> adapter.getItem(position)?.source?.id } presenter.clearDatabaseForSourceIds(selectedSourceIds) actionFab!!.isVisible = false adapter.clearSelection() adapter.notifyDataSetChanged() activity?.toast(R.string.clear_database_completed) } }
apache-2.0
bc5bdde18d7672ff8874d3bc98df898d
34.426136
101
0.685806
5.098119
false
false
false
false
actions-on-google/actions-shortcut-convert
src/main/kotlin/com/google/assistant/actions/Output.kt
1
1559
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.assistant.actions const val ACTIONS_XML_CONVERTED_SUCCESS_MESSAGE = "Your actions.xml was converted to shortcuts.xml." // TODO: directly output a list of tags that require post-processing rather than directing to README only. const val CHECK_README_MESSAGE = "Be sure to review the README 'Post-processing and Manual Inspection' for instructions on " + "to determine whether the shortcuts.xml output requires further modification." const val COMMENTS_NOT_TRANSFERRED_MESSAGE = "Comments from your actions.xml are not transferred to your shortcuts.xml." private const val ANSI_YELLOW = "\u001B[33m" private const val ANSI_GREEN = "\u001B[32m" private const val ANSI_RESET = "\u001B[0m" fun createInfoMessage(infoMessage: String): String { return ANSI_GREEN + "INFO: " + ANSI_RESET + infoMessage } fun createWarningMessage(warningMessage: String): String { return ANSI_YELLOW + "WARNING: " + ANSI_RESET + warningMessage }
apache-2.0
2e99d4e45923bce2ae1cd2e087bd5a28
43.571429
106
0.751764
4.059896
false
false
false
false
mdanielwork/intellij-community
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/ext/newify/NewifyMemberContributor.kt
3
4143
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.groovy.ext.newify import com.intellij.psi.* import com.intellij.psi.impl.light.LightMethodBuilder import com.intellij.psi.scope.PsiScopeProcessor import com.intellij.psi.util.parents import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression import org.jetbrains.plugins.groovy.lang.psi.impl.GrAnnotationUtil import org.jetbrains.plugins.groovy.lang.psi.impl.GrAnnotationUtil.getClassArrayValue import org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.TypesUtil import org.jetbrains.plugins.groovy.lang.resolve.NonCodeMembersContributor import org.jetbrains.plugins.groovy.lang.resolve.ResolveUtil import org.jetbrains.plugins.groovy.lang.resolve.shouldProcessMethods internal const val newifyAnnotationFqn = "groovy.lang.Newify" internal const val newifyOriginInfo = "by @Newify" class NewifyMemberContributor : NonCodeMembersContributor() { override fun processDynamicElements(qualifierType: PsiType, aClass: PsiClass?, processor: PsiScopeProcessor, place: PsiElement, state: ResolveState) { if (!processor.shouldProcessMethods()) return if (place !is GrReferenceExpression) return val newifyAnnotations = place.listNewifyAnnotations() if (newifyAnnotations.isEmpty()) return val qualifier = place.qualifierExpression val type = (qualifier as? GrReferenceExpression)?.resolve() as? PsiClass for (annotation in newifyAnnotations) { val newifiedClasses = getClassArrayValue(annotation, "value", true) qualifier ?: newifiedClasses.flatMap { buildConstructors(it, it.name) }.forEach { ResolveUtil.processElement(processor, it, state) } val createNewMethods = GrAnnotationUtil.inferBooleanAttributeNotNull(annotation, "auto") if (type != null && createNewMethods) { buildConstructors(type, "new").forEach { ResolveUtil.processElement(processor, it, state) } } } } private fun PsiElement.listNewifyAnnotations() = parents().flatMap { val owner = it as? PsiModifierListOwner val seq = owner?.modifierList?.annotations?.asSequence()?.filter { it.qualifiedName == newifyAnnotationFqn } return@flatMap seq ?: emptySequence() }.toList() private fun buildConstructors(clazz: PsiClass, newName: String?): List<NewifiedConstructor> { newName ?: return emptyList() val constructors = clazz.constructors if (constructors.isNotEmpty()) { return constructors.mapNotNull { buildNewifiedConstructor(it, newName) } } else { return listOf(buildNewifiedConstructor(clazz, newName)) } } private fun buildNewifiedConstructor(myPrototype: PsiMethod, newName: String): NewifiedConstructor? { val builder = NewifiedConstructor(myPrototype.manager, newName) val psiClass = myPrototype.containingClass ?: return null builder.containingClass = psiClass builder.setMethodReturnType(TypesUtil.createType(psiClass)) builder.navigationElement = myPrototype myPrototype.parameterList.parameters.forEach { builder.addParameter(it) } myPrototype.throwsList.referencedTypes.forEach { builder.addException(it) } myPrototype.typeParameters.forEach { builder.addTypeParameter(it) } return builder } private fun buildNewifiedConstructor(myPrototype: PsiClass, newName: String): NewifiedConstructor { val builder = NewifiedConstructor(myPrototype.manager, newName) builder.containingClass = myPrototype builder.setMethodReturnType(TypesUtil.createType(myPrototype)) builder.navigationElement = myPrototype return builder } class NewifiedConstructor(val myManager: PsiManager, val newName: String) : LightMethodBuilder(myManager, newName) { init { addModifier(PsiModifier.STATIC) originInfo = newifyOriginInfo } } }
apache-2.0
52f1b3e18eaf82f524e2f8cadbbf9166
40.858586
140
0.734251
4.973589
false
false
false
false
senyuyuan/Gluttony
gluttony/src/main/java/dao/yuan/sen/gluttony/sqlite_module/operator/sqlite_update.kt
1
3646
package dao.yuan.sen.gluttony.sqlite_module.operator import com.google.gson.Gson import dao.yuan.sen.gluttony.Gluttony import dao.yuan.sen.gluttony.sqlite_module.annotation.PrimaryKey import dao.yuan.sen.gluttony.sqlite_module.condition import dao.yuan.sen.gluttony.sqlite_module.e import org.jetbrains.anko.db.UpdateQueryBuilder import org.jetbrains.anko.db.update import kotlin.reflect.declaredMemberProperties /** * Created by Administrator on 2016/11/28. */ /** * 根据 实例 更新数据 , 依靠实例的主键定位,如果数据库中不存在的话,将保存数据 * @return 更新的数量位1 或 保存数据的id*/ inline fun <reified T : Any> T.updateOrSave(): Long { return if (update() == 0) save() else 1 } inline fun <reified T : Any> T.updateByKey(primaryKey: Any, updateFunctor: (T) -> Unit): Int { val data: T? = this.findOneByKey(primaryKey) ?: return 0 updateFunctor(data!!) return data.update() } /** * 根据 实例 更新数据 , 依靠实例的主键定位 * @return 更新的数量*/ inline fun <reified T : Any> T.update(): Int { val mClass = this.javaClass.kotlin val properties = mClass.declaredMemberProperties var propertyValue: Any? = null properties.forEach { if (it.annotations.map { it.annotationClass }.contains(PrimaryKey::class)) propertyValue = it.get(this) } if (propertyValue == null) throw Exception("${mClass.simpleName} 类型没有设置PrimaryKey, 或是 实例的PrimaryKey属性不能为null") val valuePairs = properties.associate { e("reflect_values", "${it.name}:${it.get(this).toString()}") it.name to it.get(this).let { when (it) { true -> "true" false -> "false" is String, is Int, is Float, is Double -> it else -> Gson().toJson(it) } } }.toList().toTypedArray() return Gluttony.database.use { [email protected](propertyValue!!, *valuePairs) } } /** * 根据 主键 更新数据 * @return 更新的数量*/ inline fun <reified T : Any> T.updateByKey(primaryKey: Any, crossinline pairs: () -> Array<out Pair<String, Any>>): Int = updateByKey(primaryKey, *pairs()) /** * 根据 主键 更新数据 * @return 更新的数量*/ inline fun <reified T : Any> T.updateByKey(primaryKey: Any, vararg pairs: Pair<String, Any>): Int { val mClass = this.javaClass.kotlin val name = "${mClass.simpleName}" var propertyName: String? = null mClass.declaredMemberProperties.forEach { if (it.annotations.map { it.annotationClass }.contains(PrimaryKey::class)) propertyName = it.name } if (propertyName == null) throw Exception("$name 类型没有设置PrimaryKey") return Gluttony.database.use { tryDo { update(name, *pairs).apply { condition { propertyName!! equalsData primaryKey } }.exec() }.let { when (it) { null, "no such table" -> 0 is Int -> it else -> 0 } } as Int } } /**@return 更新的数量*/ inline fun <reified T : Any> T.update(vararg pairs: Pair<String, Any>, crossinline condition: UpdateQueryBuilder.() -> Unit): Int { val name = "${this.javaClass.kotlin.simpleName}" return Gluttony.database.use { tryDo { update(name, *pairs).apply { condition() }.exec() }.let { when (it) { null, "no such table" -> 0 is Int -> it else -> 0 } } } }
apache-2.0
8242c87689b4de13913dc6c447163387
30.453704
155
0.608363
3.798658
false
false
false
false
cdietze/klay
src/test/kotlin/klay/core/json/InternalJsonTypesTest.kt
1
5190
package klay.core.json import klay.core.assertEquals import org.junit.Test import kotlin.test.assertEquals import kotlin.test.assertFailsWith import kotlin.test.assertFalse import kotlin.test.assertTrue class InternalJsonTypesTest { @Test fun testObjectInt() { val o = JsonObject() o.put("key", 1) assertEquals(1, o.getInt("key")) assertEquals(1.0, o.getDouble("key")!!, 0.0001) assertEquals(1.0f, o.getFloat("key")!!, 0.0001f) assertEquals(1f, o.getFloat("key")!!, 0.0001f) assertEquals(1, o["key"]) assertEquals(null, o.getString("key")) assertEquals("foo", o.getString("key") ?: "foo") assertFalse(o.isNull("key")) } @Test fun testObjectString() { val o = JsonObject() o.put("key", "1") assertEquals(null, o.getInt("key")) assertEquals(null, o.getDouble("key")) assertEquals(null, o.getFloat("key")) assertEquals("1", o["key"]) assertFalse(o.isNull("key")) } @Test fun testObjectNull() { val o = JsonObject() o.put("key", null) assertEquals(null, o.getInt("key")) assertEquals(null, o.getDouble("key")) assertEquals(null, o.getFloat("key")) assertEquals(null, o["key"]) assertTrue(o.isNull("key")) } @Test fun testArrayInt() { val o = JsonArray(listOf(null as String?, null, null, null)) o[3] = 1 assertEquals(1, o.getInt(3)) assertEquals(1.0, o.getDouble(3)!!, 0.0001) assertEquals(1.0f, o.getFloat(3)!!, 0.0001f) assertEquals(1f, o.getFloat(3)!!, 0.0001f) assertEquals(1, o[3]) assertEquals(null, o.getString(3)) assertEquals("foo", o.getString(3) ?: "foo") assertFalse(o.isNull(3)) } @Test fun testArrayString() { val o = JsonArray(listOf(null as String?, null, null, null)) o[3] = "1" assertEquals(null, o.getInt(3)) assertEquals(null, o.getDouble(3)) assertEquals(null, o.getFloat(3)) assertEquals("1", o[3]) assertFalse(o.isNull(3)) } @Test fun testArrayNull() { val a = JsonArray(listOf(null as String?, null, null, null)) a[3] = null assertEquals(null, a.getInt(3)) assertEquals(null, a.getDouble(3)) assertEquals(null, a.getFloat(3)) assertEquals(null, a[3]) assertTrue(a.isNull(3)) } @Test fun testArrayBounds() { val a = JsonArray(listOf(null as String?, null, null, null)) assertEquals(null, a.getInt(4)) assertEquals(null, a.getDouble(4)) assertEquals(null, a.getFloat(4)) assertEquals(null, a[4]) assertTrue(a.isNull(4)) } @Test fun testJsonArrayBuilder() { //@formatter:off val a = JsonArray.builder() .value(true) .value(1.0) .value(1.0f) .value(1) .value("hi") .`object`() .value("abc", 123) .end() .array() .value(1) .nul() .end() .array(JsonArray.from(1, 2, 3)) .`object`(JsonObject.builder().nul("a").nul("b").nul("c").done()) .done() //@formatter:on assertEquals( "[true,1.0,1.0,1,\"hi\",{\"abc\":123},[1,null],[1,2,3],{\"a\":null,\"b\":null,\"c\":null}]", JsonStringWriter.toString(a)) } @Test fun testJsonObjectBuilder() { //@formatter:off val a = JsonObject.builder() .value("bool", true) .value("double", 1.0) .value("float", 1.0f) .value("int", 1) .value("string", "hi") .nul("null") .`object`("object") .value("abc", 123) .end() .array("array") .value(1) .nul() .end() .array("existingArray", JsonArray.from(1, 2, 3)) .`object`("existingObject", JsonObject.builder().nul("a").nul("b").nul("c").done()) .done() //@formatter:on assertEquals( "{\"array\":[1,null],\"bool\":true,\"double\":1.0," + "\"existingArray\":[1,2,3],\"existingObject\":{\"a\":null,\"b\":null,\"c\":null}," + "\"float\":1.0,\"int\":1,\"null\":null,\"object\":{\"abc\":123},\"string\":\"hi\"}", JsonStringWriter.toString(a)) } @Test fun testJsonArrayBuilderFailCantCloseRoot() { assertFailsWith(JsonWriterException::class, { JsonArray.builder().end() }) } @Test fun testJsonArrayBuilderFailCantAddKeyToArray() { assertFailsWith(JsonWriterException::class, { JsonArray.builder().value("abc", 1) }) } @Test fun testJsonArrayBuilderFailCantAddNonKeyToObject() { assertFailsWith(JsonWriterException::class, { JsonObject.builder().value(1) }) } }
apache-2.0
467af9868c84fe65f4ebf10d4d86c153
29.529412
108
0.508863
3.955793
false
true
false
false
dahlstrom-g/intellij-community
plugins/kotlin/j2k/old/src/org/jetbrains/kotlin/j2k/ast/Constructors.kt
7
3388
// 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.j2k.ast import com.intellij.util.IncorrectOperationException import org.jetbrains.kotlin.j2k.CodeBuilder import org.jetbrains.kotlin.j2k.Converter abstract class Constructor( annotations: Annotations, modifiers: Modifiers, parameterList: ParameterList, body: DeferredElement<Block> ) : FunctionLike(annotations, modifiers, parameterList, body) { override val parameterList: ParameterList get() = super.parameterList!! } class PrimaryConstructor( annotations: Annotations, modifiers: Modifiers, parameterList: ParameterList, body: DeferredElement<Block> ) : Constructor(annotations, modifiers, parameterList, body) { override fun generateCode(builder: CodeBuilder) { throw IncorrectOperationException() } // Should be lazy, to defer `assignPrototypesFrom(this,...)` a bit, // cause when `PrimaryConstructor` created prototypes not yet assigned val initializer: Initializer by lazy { Initializer(body, Modifiers.Empty).assignPrototypesFrom(this, CommentsAndSpacesInheritance(commentsBefore = false)) } fun createSignature(converter: Converter): PrimaryConstructorSignature { val signature = PrimaryConstructorSignature(annotations, modifiers, parameterList) // assign prototypes later because we don't know yet whether the body is empty or not converter.addPostUnfoldDeferredElementsAction { val inheritance = CommentsAndSpacesInheritance(spacesBefore = SpacesInheritance.NONE, commentsAfter = body!!.isEmpty, commentsInside = body.isEmpty) signature.assignPrototypesFrom(this, inheritance) } return signature } } class PrimaryConstructorSignature(val annotations: Annotations, private val modifiers: Modifiers, val parameterList: ParameterList) : Element() { val accessModifier: Modifier? = run { val modifier = modifiers.accessModifier() if (modifier != Modifier.PUBLIC) modifier else null } override fun generateCode(builder: CodeBuilder) { var needConstructorKeyword = false if (!annotations.isEmpty) { builder append " " append annotations needConstructorKeyword = true } if (accessModifier != null) { builder append " " append Modifiers(listOf(accessModifier)).assignPrototypesFrom(modifiers) needConstructorKeyword = true } if (needConstructorKeyword) { builder.append(" constructor") } builder.append(parameterList) } } class SecondaryConstructor( annotations: Annotations, modifiers: Modifiers, parameterList: ParameterList, body: DeferredElement<Block>, private val thisOrSuperCall: DeferredElement<Expression>? ) : Constructor(annotations, modifiers, parameterList, body) { override fun generateCode(builder: CodeBuilder) { builder.append(annotations) .appendWithSpaceAfter(modifiers) .append("constructor") .append(parameterList) if (thisOrSuperCall != null) { builder append " : " append thisOrSuperCall } builder append " " append body!! } }
apache-2.0
206825dda0acd7d6f70b70d4cdf1bb38
35.042553
160
0.694805
5.133333
false
false
false
false
flesire/ontrack
ontrack-model/src/main/java/net/nemerosa/ontrack/model/structure/RunInfo.kt
2
1113
package net.nemerosa.ontrack.model.structure /** * Contains information about the CI run for a * [validation run][ValidationRun] or a * [build][Build]. * * @property id Unique ID of the run info * @property sourceType Type of source (like "jenkins") * @property sourceUri URI to the source of the run (like the URL to a Jenkins job) * @property triggerType Type of trigger (like "scm" or "user") * @property triggerData Data associated with the trigger (like a user ID or a commit) * @property runTime Time of the run (in seconds) */ open class RunInfo( val id: Int, val sourceType: String?, val sourceUri: String?, val triggerType: String?, val triggerData: String?, val runTime: Int?, val signature: Signature? ) { val empty = id == 0 companion object { fun empty() = RunInfo( id = 0, sourceType = null, sourceUri = null, triggerType = null, triggerData = null, runTime = null, signature = null ) } }
mit
3203dc0f7cf35c654fe777014948c94d
28.289474
86
0.5885
4.347656
false
false
false
false
paplorinc/intellij-community
plugins/stats-collector/log-events/src/com/intellij/stats/completion/LookupEntryInfo.kt
2
1674
/* * 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.stats.completion class LookupEntryInfo(val id: Int, val length: Int, val relevance: Map<String, String?>?) { // returns null if no difference found fun calculateDiff(newValue: LookupEntryInfo): LookupEntryDiff? { assert(id == newValue.id) { "Could not compare infos for differenece lookup elements" } if (this === newValue) return null if (relevance == null && newValue.relevance == null) { return null } return relevanceDiff(id, relevance ?: emptyMap(), newValue.relevance ?: emptyMap()) } private fun relevanceDiff(id: Int, before: Map<String, String?>, after: Map<String, String?>): LookupEntryDiff? { val added = after.filter { it.key !in before } val removed = before.keys.filter { it !in after } val changed = after.filter { it.key in before && it.value != before[it.key] } if (changed.isEmpty() && added.isEmpty() && removed.isEmpty()) { return null } return LookupEntryDiff(id, added, changed, removed) } }
apache-2.0
b328525159b33826aa04624f63f34ef0
38.880952
117
0.672043
4.164179
false
false
false
false
RuneSuite/client
plugins-dev/src/main/java/org/runestar/client/plugins/dev/OnTickTest.kt
1
1070
package org.runestar.client.plugins.dev import org.runestar.client.api.plugins.DisposablePlugin import org.runestar.client.api.Fonts import org.runestar.client.api.game.SceneTile import org.runestar.client.api.game.live.Game import org.runestar.client.api.game.live.Canvas import org.runestar.client.api.game.live.Npcs import org.runestar.client.api.game.live.Players import org.runestar.client.api.plugins.PluginSettings class OnTickTest : DisposablePlugin<PluginSettings>() { override val defaultSettings = PluginSettings() var tiles = ArrayList<SceneTile>() var tick = 0 override fun onStart() { add(Game.ticks.subscribe { tiles = ArrayList() Players.mapTo(tiles) { it.location } Npcs.mapTo(tiles) { it.location } tick++ }) add(Canvas.repaints.subscribe { g -> g.font = Fonts.BOLD_12 tiles.forEach { t -> val o = t.outline() g.draw(o) } g.drawString(tick.toString(), 50, 50) }) } }
mit
5f055a1370380ba17fbff952ca477f95
28.75
55
0.640187
3.948339
false
false
false
false
JetBrains/intellij-community
build/tasks/test/org/jetbrains/intellij/build/io/ZipTest.kt
1
11167
// 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.intellij.build.io import com.intellij.openapi.util.SystemInfoRt import com.intellij.testFramework.rules.InMemoryFsExtension import com.intellij.util.io.write import com.intellij.util.lang.HashMapZipFile import com.intellij.util.lang.ImmutableZipFile import com.intellij.util.lang.ZipFile import org.assertj.core.api.Assertions.assertThat import org.assertj.core.configuration.ConfigurationProvider import org.jetbrains.intellij.build.tasks.DirSource import org.jetbrains.intellij.build.tasks.ZipSource import org.jetbrains.intellij.build.tasks.buildJar import org.junit.jupiter.api.Assumptions import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.RegisterExtension import org.junit.jupiter.api.io.TempDir import java.nio.file.Files import java.nio.file.Path import java.util.concurrent.ForkJoinTask import kotlin.random.Random class ZipTest { @RegisterExtension @JvmField // not used in every test because we want to check the real FS behaviour val fs = InMemoryFsExtension() @Test fun `interrupt thread`(@TempDir tempDir: Path) { val (list, archiveFile) = createLargeArchive(128, tempDir) checkZip(archiveFile) { zipFile -> val tasks = mutableListOf<ForkJoinTask<*>>() // force init of AssertJ to avoid ClosedByInterruptException on reading FileLoader index ConfigurationProvider.CONFIGURATION_PROVIDER for (i in 0..100) { tasks.add(ForkJoinTask.adapt(Runnable { val ioThread = runInThread { while (!Thread.currentThread().isInterrupted) { for (name in list) { assertThat(zipFile.getResource(name)).isNotNull() } } } // once in a while, the IO thread is stopped Thread.sleep(50) ioThread.interrupt() Thread.sleep(10) ioThread.join() })) } ForkJoinTask.invokeAll(tasks) } } @Test fun `read zip file with more than 65K entries`() { Assumptions.assumeTrue(SystemInfoRt.isUnix) val (list, archiveFile) = createLargeArchive(Short.MAX_VALUE * 2 + 20, fs.root) checkZip(archiveFile) { zipFile -> for (name in list) { assertThat(zipFile.getResource(name)).isNotNull() } } } private fun createLargeArchive(size: Int, tempDir: Path): Pair<MutableList<String>, Path> { val random = Random(42) val dir = tempDir.resolve("dir") Files.createDirectories(dir) val list = mutableListOf<String>() for (i in 0..size) { val name = "entry-item${random.nextInt()}-$i" list.add(name) Files.write(dir.resolve(name), random.nextBytes(random.nextInt(32))) } val archiveFile = tempDir.resolve("archive.zip") zip(archiveFile, mapOf(dir to "")) return Pair(list, archiveFile) } @Test fun `custom prefix`(@TempDir tempDir: Path) { val random = Random(42) val dir = tempDir.resolve("dir") Files.createDirectories(dir) val list = mutableListOf<String>() for (i in 0..10) { val name = "entry-item${random.nextInt()}-$i" list.add(name) Files.write(dir.resolve(name), random.nextBytes(random.nextInt(128))) } val archiveFile = tempDir.resolve("archive.zip") zip(archiveFile, mapOf(dir to "test")) checkZip(archiveFile) { zipFile -> for (name in list) { assertThat(zipFile.getResource("test/$name")).isNotNull() } } } @Test fun excludes(@TempDir tempDir: Path) { val random = Random(42) val dir = Files.createDirectories(tempDir.resolve("dir")) val list = mutableListOf<String>() for (i in 0..10) { val name = "entry-item${random.nextInt()}-$i" list.add(name) Files.write(dir.resolve(name), random.nextBytes(random.nextInt(128))) } Files.write(dir.resolve("do-not-ignore-me"), random.nextBytes(random.nextInt(128))) Files.write(dir.resolve("test-relative-ignore"), random.nextBytes(random.nextInt(128))) val iconRobotsFile = dir.resolve("some/nested/dir/icon-robots.txt") iconRobotsFile.write("text") val rootIconRobotsFile = dir.resolve("icon-robots.txt") rootIconRobotsFile.write("text2") val archiveFile = tempDir.resolve("archive.zip") val fs = dir.fileSystem buildJar(archiveFile, listOf(DirSource(dir = dir, excludes = listOf( fs.getPathMatcher("glob:**/entry-item*"), fs.getPathMatcher("glob:test-relative-ignore"), fs.getPathMatcher("glob:**/icon-robots.txt"), )))) checkZip(archiveFile) { zipFile -> if (zipFile is ImmutableZipFile) { assertThat(zipFile.getOrComputeNames()).containsExactly( "entry-item663137163-10", "entry-item972016666-0", "entry-item1791766502-3", "entry-item1705343313-9", "entry-item-942605861-5", "entry-item1578011503-7", "entry-item949746295-2", "entry-item-245744780-1", "do-not-ignore-me", "icon-robots.txt", "entry-item-2145949183-8", "entry-item-1326272896-6", "entry-item828400960-4" ) } for (name in list) { assertThat(zipFile.getResource("test/$name")).isNull() } assertThat(zipFile.getResource("do-not-ignore-me")).isNotNull() assertThat(zipFile.getResource("test-relative-ignore")).isNull() assertThat(zipFile.getResource("some/nested/dir/icon-robots.txt")).isNull() assertThat(zipFile.getResource("unknown")).isNull() } } @Test fun excludesInZipSource(@TempDir tempDir: Path) { val random = Random(42) val dir = Files.createDirectories(tempDir.resolve("zip")) Files.write(dir.resolve("zip-included"), random.nextBytes(random.nextInt(128))) Files.write(dir.resolve("zip-excluded"), random.nextBytes(random.nextInt(128))) val zip = tempDir.resolve("test.zip") zip(zip, mapOf(dir to "")) val archiveFile = tempDir.resolve("archive.zip") buildJar(archiveFile, listOf( ZipSource(file = zip, excludes = listOf(Regex("^zip-excl.*"))) )) checkZip(archiveFile) { zipFile -> if (zipFile is ImmutableZipFile) { assertThat(zipFile.getOrComputeNames()).containsExactly("zip-included") } } } @Test fun skipIndex(@TempDir tempDir: Path) { val dir = Files.createDirectories(tempDir.resolve("dir")) Files.writeString(dir.resolve("file1"), "1") Files.writeString(dir.resolve("file2"), "2") val archiveFile = tempDir.resolve("archive.zip") buildJar(archiveFile, listOf(DirSource(dir = dir, excludes = emptyList())), compress = true) java.util.zip.ZipFile(archiveFile.toString()).use { zipFile -> assertThat(zipFile.entries().asSequence().map { it.name }.toList()) .containsExactlyInAnyOrder("file1", "file2") } checkZip(archiveFile) { } } @Test fun `small file`(@TempDir tempDir: Path) { val dir = tempDir.resolve("dir") val file = dir.resolve("samples/nested_dir/__init__.py") Files.createDirectories(file.parent) Files.writeString(file, "\n") val archiveFile = tempDir.resolve("archive.zip") zipWithCompression(archiveFile, mapOf(dir to "")) HashMapZipFile.load(archiveFile).use { zipFile -> for (name in zipFile.entries) { val entry = zipFile.getRawEntry("samples/nested_dir/__init__.py") assertThat(entry).isNotNull() assertThat(entry!!.isCompressed).isFalse() assertThat(String(entry.getData(zipFile), Charsets.UTF_8)).isEqualTo("\n") } } } @Test fun compression(@TempDir tempDir: Path) { val dir = tempDir.resolve("dir") Files.createDirectories(dir) val data = Random(42).nextBytes(4 * 1024) Files.write(dir.resolve("file"), data + data + data) val archiveFile = tempDir.resolve("archive.zip") zipWithCompression(archiveFile, mapOf(dir to "")) HashMapZipFile.load(archiveFile).use { zipFile -> val entry = zipFile.getRawEntry("file") assertThat(entry).isNotNull() assertThat(entry!!.isCompressed).isTrue() } } @Test fun `large file`(@TempDir tempDir: Path) { val dir = tempDir.resolve("dir") Files.createDirectories(dir) val random = Random(42) Files.write(dir.resolve("largeFile1"), random.nextBytes(10 * 1024 * 1024)) Files.write(dir.resolve("largeFile2"), random.nextBytes(1 * 1024 * 1024)) Files.write(dir.resolve("largeFile3"), random.nextBytes(2 * 1024 * 1024)) val archiveFile = tempDir.resolve("archive.zip") zip(archiveFile, mapOf(dir to "")) checkZip(archiveFile) { zipFile -> val entry = zipFile.getResource("largeFile1") assertThat(entry).isNotNull() } } @Test fun `large incompressible file compressed`(@TempDir tempDir: Path) { val dir = tempDir.resolve("dir") Files.createDirectories(dir) val random = Random(42) val data = random.nextBytes(10 * 1024 * 1024) Files.write(dir.resolve("largeFile1"), data) Files.write(dir.resolve("largeFile2"), random.nextBytes(1 * 1024 * 1024)) Files.write(dir.resolve("largeFile3"), random.nextBytes(2 * 1024 * 1024)) val archiveFile = tempDir.resolve("archive.zip") zipWithCompression(archiveFile, mapOf(dir to "")) checkZip(archiveFile) { zipFile -> val entry = zipFile.getResource("largeFile1") assertThat(entry).isNotNull() } } @Test fun `large compressible file compressed`(@TempDir tempDir: Path) { val dir = tempDir.resolve("dir") Files.createDirectories(dir) val random = Random(42) val data = random.nextBytes(2 * 1024 * 1024) Files.write(dir.resolve("largeFile1"), data + data + data + data + data + data + data + data + data + data) Files.write(dir.resolve("largeFile2"), data + data + data + data) Files.write(dir.resolve("largeFile3"), data + data) val archiveFile = tempDir.resolve("archive.zip") zipWithCompression(archiveFile, mapOf(dir to "")) checkZip(archiveFile) { zipFile -> val entry = zipFile.getResource("largeFile1") assertThat(entry).isNotNull() } } @Test fun `write all dir entries`(@TempDir tempDir: Path) { val dir = tempDir.resolve("dir") Files.createDirectories(dir) val random = Random(42) val data = random.nextBytes(2 * 1024 * 1024) dir.resolve("dir/subDir/foo.class").write(data) val archiveFile = tempDir.resolve("archive.zip") zip(archiveFile, mapOf(dir to ""), addDirEntriesMode = AddDirEntriesMode.ALL) HashMapZipFile.load(archiveFile).use { zipFile -> assertThat(zipFile.getRawEntry("dir/subDir")).isNotNull } } // check both IKV- and non-IKV variants of immutable zip file private fun checkZip(file: Path, checker: (ZipFile) -> Unit) { HashMapZipFile.load(file).use { zipFile -> checker(zipFile) } ImmutableZipFile.load(file).use { zipFile -> checker(zipFile) } } } private fun runInThread(block: () -> Unit): Thread { val thread = Thread(block, "test interrupt") thread.isDaemon = true thread.start() return thread }
apache-2.0
7e70e9c8d7e0b3bd382e63a7af120c65
32.635542
120
0.667055
3.982525
false
true
false
false
JetBrains/intellij-community
plugins/kotlin/idea/tests/testData/checker/Override.fir.kt
1
1488
package override interface MyInterface { fun foo() } abstract class MyAbstractClass { abstract fun bar() } open class MyClass : MyInterface, MyAbstractClass() { override fun foo() {} override fun bar() {} } class MyChildClass : MyClass() {} <error descr="[ABSTRACT_MEMBER_NOT_IMPLEMENTED] Class MyIllegalClass is not abstract and does not implement abstract member foo">class MyIllegalClass</error> : MyInterface, MyAbstractClass() {} <error descr="[ABSTRACT_CLASS_MEMBER_NOT_IMPLEMENTED] Class MyIllegalClass2 is not abstract and does not implement abstract base class member bar">class MyIllegalClass2</error> : MyInterface, MyAbstractClass() { override fun foo() {} } <error descr="[ABSTRACT_MEMBER_NOT_IMPLEMENTED] Class MyIllegalClass3 is not abstract and does not implement abstract member foo">class MyIllegalClass3</error> : MyInterface, MyAbstractClass() { override fun bar() {} } <error descr="[ABSTRACT_CLASS_MEMBER_NOT_IMPLEMENTED] Class MyIllegalClass4 is not abstract and does not implement abstract base class member bar">class MyIllegalClass4</error> : MyInterface, MyAbstractClass() { fun <error descr="[VIRTUAL_MEMBER_HIDDEN] 'foo' hides member of supertype 'MyInterface' and needs 'override' modifier">foo</error>() {} override fun other() {} } class MyChildClass1 : MyClass() { fun foo() {} override fun bar() {} }
apache-2.0
8b547839d21e06290c0a171232ceda04
40.333333
215
0.688172
4.635514
false
false
false
false
vhromada/Catalog
web/src/main/kotlin/com/github/vhromada/catalog/web/validator/YearsValidator.kt
1
1979
package com.github.vhromada.catalog.web.validator import com.github.vhromada.catalog.web.fo.SeasonFO import com.github.vhromada.catalog.web.validator.constraints.Years import java.time.LocalDate import java.util.regex.Pattern import javax.validation.ConstraintValidator import javax.validation.ConstraintValidatorContext /** * A class represents validator for years constraint. * * @author Vladimir Hromada */ class YearsValidator : ConstraintValidator<Years, SeasonFO> { override fun isValid(value: SeasonFO?, constraintValidatorContext: ConstraintValidatorContext): Boolean { if (value == null) { return true } val startYear = value.startYear val endYear = value.endYear if (isNotStringValid(startYear) || isNotStringValid(endYear)) { return true } val startYearValue = startYear!!.toInt() val endYearValue = endYear!!.toInt() return if (isNotIntValid(startYearValue) || isNotIntValid(endYearValue)) { true } else { startYearValue <= endYearValue } } /** * Validates year as string. * * @param value value to validate * @return true if value isn't null and is valid integer */ private fun isNotStringValid(value: String?): Boolean { return value == null || !PATTERN.matcher(value).matches() } /** * Validates year as integer. * * @param value value to validate * @return true if value is in valid range */ private fun isNotIntValid(value: Int): Boolean { return value < MIN_YEAR || value > MAX_YEAR } companion object { /** * Minimal year */ private const val MIN_YEAR = 1930 /** * Current year */ private val MAX_YEAR = LocalDate.now().year /** * Year pattern */ private val PATTERN = Pattern.compile("\\d{4}") } }
mit
276a218234f3a336d4616e6d762cd8ac
25.039474
109
0.618999
4.591647
false
false
false
false
vhromada/Catalog
core/src/main/kotlin/com/github/vhromada/catalog/validator/impl/AccountValidatorImpl.kt
1
1742
package com.github.vhromada.catalog.validator.impl import com.github.vhromada.catalog.common.exception.InputException import com.github.vhromada.catalog.common.result.Event import com.github.vhromada.catalog.common.result.Result import com.github.vhromada.catalog.common.result.Severity import com.github.vhromada.catalog.entity.Credentials import com.github.vhromada.catalog.validator.AccountValidator import org.springframework.stereotype.Component /** * A class represents implementation of validator for accounts. * * @author Vladimir Hromada */ @Component("accountValidator") class AccountValidatorImpl : AccountValidator { override fun validateCredentials(credentials: Credentials) { val result = Result<Unit>() when { credentials.username == null -> { result.addEvent(event = Event(severity = Severity.ERROR, key = "CREDENTIALS_USERNAME_NULL", message = "Username mustn't be null.")) } credentials.username.isEmpty() -> { result.addEvent(event = Event(severity = Severity.ERROR, key = "CREDENTIALS_USERNAME_EMPTY", message = "Username mustn't be empty string.")) } } when { credentials.password == null -> { result.addEvent(event = Event(severity = Severity.ERROR, key = "CREDENTIALS_PASSWORD_NULL", message = "Password mustn't be null.")) } credentials.password.isEmpty() -> { result.addEvent(event = Event(severity = Severity.ERROR, key = "CREDENTIALS_PASSWORD_EMPTY", message = "Password mustn't be empty string.")) } } if (result.isError()) { throw InputException(result = result) } } }
mit
fd75300829127dfe227ddaa5499e0109
40.47619
156
0.667623
4.608466
false
false
false
false
StepicOrg/stepik-android
app/src/main/java/org/stepik/android/view/course_list/ui/fragment/CourseListVisitedFragment.kt
2
4733
package org.stepik.android.view.course_list.ui.fragment import android.os.Bundle import android.view.View import androidx.fragment.app.Fragment import androidx.fragment.app.viewModels import androidx.lifecycle.ViewModelProvider import androidx.recyclerview.widget.GridLayoutManager import kotlinx.android.synthetic.main.fragment_course_list.* import kotlinx.android.synthetic.main.fragment_course_list.courseListCoursesRecycler import org.stepic.droid.R import org.stepic.droid.analytic.Analytic import org.stepic.droid.base.App import org.stepic.droid.core.ScreenManager import org.stepic.droid.preferences.SharedPreferenceHelper import org.stepic.droid.ui.util.initCenteredToolbar import org.stepik.android.domain.course.analytic.CourseViewSource import org.stepik.android.domain.course_payments.mapper.DefaultPromoCodeMapper import org.stepik.android.presentation.course_continue.model.CourseContinueInteractionSource import org.stepik.android.presentation.course_list.CourseListView import org.stepik.android.presentation.course_list.CourseListVisitedPresenter import org.stepik.android.view.course.mapper.DisplayPriceMapper import org.stepik.android.view.course_list.delegate.CourseContinueViewDelegate import org.stepik.android.view.course_list.delegate.CourseListViewDelegate import org.stepik.android.view.ui.delegate.ViewStateDelegate import javax.inject.Inject class CourseListVisitedFragment : Fragment(R.layout.fragment_course_list) { companion object { fun newInstance(): Fragment = CourseListVisitedFragment() } @Inject internal lateinit var analytic: Analytic @Inject internal lateinit var screenManager: ScreenManager @Inject internal lateinit var viewModelFactory: ViewModelProvider.Factory @Inject internal lateinit var sharedPreferenceHelper: SharedPreferenceHelper @Inject internal lateinit var defaultPromoCodeMapper: DefaultPromoCodeMapper @Inject internal lateinit var displayPriceMapper: DisplayPriceMapper private lateinit var courseListViewDelegate: CourseListViewDelegate private val courseListVisitedPresenter: CourseListVisitedPresenter by viewModels { viewModelFactory } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) injectComponent() } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) initCenteredToolbar(R.string.visited_courses_title, true) courseListSwipeRefresh.isEnabled = false courseListCoursesRecycler.layoutManager = GridLayoutManager(context, resources.getInteger(R.integer.course_list_columns)) val viewStateDelegate = ViewStateDelegate<CourseListView.State>() viewStateDelegate.addState<CourseListView.State.Idle>() viewStateDelegate.addState<CourseListView.State.Loading>(courseListCoursesRecycler) viewStateDelegate.addState<CourseListView.State.Content>(courseListCoursesRecycler) viewStateDelegate.addState<CourseListView.State.Empty>(courseListCoursesEmpty) viewStateDelegate.addState<CourseListView.State.NetworkError>(courseListCoursesLoadingErrorVertical) courseListViewDelegate = CourseListViewDelegate( analytic = analytic, courseContinueViewDelegate = CourseContinueViewDelegate( activity = requireActivity(), analytic = analytic, screenManager = screenManager ), courseItemsRecyclerView = courseListCoursesRecycler, courseListViewStateDelegate = viewStateDelegate, onContinueCourseClicked = { courseListItem -> courseListVisitedPresenter .continueCourse( course = courseListItem.course, viewSource = CourseViewSource.Visited, interactionSource = CourseContinueInteractionSource.COURSE_WIDGET ) }, defaultPromoCodeMapper = defaultPromoCodeMapper, displayPriceMapper = displayPriceMapper, itemAdapterDelegateType = CourseListViewDelegate.ItemAdapterDelegateType.STANDARD ) courseListVisitedPresenter.fetchCourses() } private fun injectComponent() { App.component() .courseListVisitedComponentBuilder() .build() .inject(this) } override fun onStart() { super.onStart() courseListVisitedPresenter.attachView(courseListViewDelegate) } override fun onStop() { courseListVisitedPresenter.detachView(courseListViewDelegate) super.onStop() } }
apache-2.0
8108f69e884ea332ec5c906ea5745e3b
39.810345
129
0.749419
5.688702
false
false
false
false
chrislo27/RhythmHeavenRemixEditor2
core/src/main/kotlin/io/github/chrislo27/rhre3/discord/PresenceState.kt
2
1948
package io.github.chrislo27.rhre3.discord import kotlin.math.roundToLong sealed class PresenceState(open val state: String = "", open val smallIcon: String = "", open val smallIconText: String = state, open val largeIcon: String? = null, open val largeIconText: String? = null) { open fun getPartyCount(): Pair<Int, Int> = DefaultRichPresence.DEFAULT_PARTY open fun modifyRichPresence(richPresence: DefaultRichPresence) { } // ---------------- IMPLEMENTATIONS BELOW ---------------- object Loading : PresenceState("Loading...", "gear") object InEditor : PresenceState("In Editor") object Exporting : PresenceState("Exporting a remix", "export") object InSettings : PresenceState("In Info and Settings", "info") object ViewingCredits : PresenceState("Viewing the credits ❤", "credits") object ViewingCreditsTempoUp : PresenceState("Tempo Up Credits!", "credits") object ViewingNews : PresenceState("Reading the news", "news") object ViewingPartners : PresenceState("Viewing our partners", "credits") object PlayingAlong : PresenceState("Using Playalong Mode", "playalong", largeIcon = "playalong_logo") class PlayingEndlessGame(gameName: String) : PresenceState("Playing $gameName", "goat") sealed class Elapsable(state: String, val duration: Float, smallIcon: String = "", smallIconText: String = state) : PresenceState(state, smallIcon, smallIconText) { override fun modifyRichPresence(richPresence: DefaultRichPresence) { super.modifyRichPresence(richPresence) if (duration > 0f) { richPresence.endTimestamp = System.currentTimeMillis() / 1000L + duration.roundToLong() } } class PlayingMidi(duration: Float) : Elapsable("Playing a MIDI", duration) } }
gpl-3.0
4ad0f06465b2a2dc05d88b5a452c6849
31.433333
128
0.646454
4.422727
false
false
false
false
chrislo27/RhythmHeavenRemixEditor2
core/src/main/kotlin/io/github/chrislo27/rhre3/discord/DefaultRichPresence.kt
2
1778
package io.github.chrislo27.rhre3.discord import club.minnced.discord.rpc.DiscordRichPresence import io.github.chrislo27.rhre3.RHRE3 import io.github.chrislo27.rhre3.RHRE3Application class DefaultRichPresence(state: String = "", party: Pair<Int, Int> = DEFAULT_PARTY, smallIcon: String = "", smallIconText: String = state, largeIcon: String? = null, largeIconText: String? = null) : DiscordRichPresence() { companion object { val DEFAULT_PARTY: Pair<Int, Int> = 0 to 0 } constructor(presenceState: PresenceState) : this(presenceState.state, presenceState.getPartyCount(), presenceState.smallIcon, presenceState.smallIconText, presenceState.largeIcon, presenceState.largeIconText) { presenceState.modifyRichPresence(this) } init { details = if (RHRE3.VERSION.suffix.startsWith("DEV")) { "Working on ${RHRE3.VERSION.copy(suffix = "")}" } else if (RHRE3.VERSION.suffix.startsWith("RC") || RHRE3.VERSION.suffix.startsWith("SNAPSHOT")) { "Testing ${RHRE3.VERSION}" } else { "Using ${RHRE3.VERSION}" } startTimestamp = RHRE3Application.instance.startTimeMillis / 1000L // Epoch seconds largeImageKey = largeIcon ?: DiscordHelper.DEFAULT_LARGE_IMAGE largeImageText = largeIconText ?: "RHRE is a custom remix editor for the Rhythm Heaven series" smallImageKey = smallIcon smallImageText = smallIconText this.state = state if (party.first > 0 && party.second > 0) { partySize = party.first partyMax = party.second } } }
gpl-3.0
5c3986cf0c5474063fff7acdcaff894c
37.673913
124
0.613611
4.37931
false
false
false
false
chrislo27/RhythmHeavenRemixEditor2
core/src/main/kotlin/io/github/chrislo27/rhre3/screen/RecoverRemixScreen.kt
2
3857
package io.github.chrislo27.rhre3.screen import com.badlogic.gdx.graphics.Color import com.badlogic.gdx.graphics.Texture import com.badlogic.gdx.graphics.g2d.TextureRegion import com.badlogic.gdx.utils.Align import io.github.chrislo27.rhre3.RHRE3Application import io.github.chrislo27.rhre3.RemixRecovery import io.github.chrislo27.rhre3.stage.GenericStage import io.github.chrislo27.toolboks.ToolboksScreen import io.github.chrislo27.toolboks.i18n.Localization import io.github.chrislo27.toolboks.registry.AssetRegistry import io.github.chrislo27.toolboks.registry.ScreenRegistry import io.github.chrislo27.toolboks.ui.Button import io.github.chrislo27.toolboks.ui.ImageLabel import io.github.chrislo27.toolboks.ui.Stage import io.github.chrislo27.toolboks.ui.TextLabel import java.time.format.DateTimeFormatter import java.time.format.FormatStyle class RecoverRemixScreen(main: RHRE3Application) : ToolboksScreen<RHRE3Application, RecoverRemixScreen>(main) { override val stage: Stage<RecoverRemixScreen> = GenericStage(main.uiPalette, null, main.defaultCamera) private val label: TextLabel<RecoverRemixScreen> init { val palette = main.uiPalette stage as GenericStage stage.titleIcon.image = TextureRegion(AssetRegistry.get<Texture>("ui_icon_folder")) stage.titleLabel.text = "screen.recovery.title" stage.backButton.visible = true stage.backButton.palette = palette.copy(highlightedBackColor = Color(1f, 0f, 0f, 0.5f), clickedBackColor = Color(1f, 0.5f, 0.5f, 0.5f)) stage.onBackButtonClick = { main.screen = ScreenRegistry.getNonNull("editor") } label = TextLabel(palette, stage.centreStage, stage.centreStage).apply { this.location.set(0f, 0f, 1f, 0.6f) this.textAlign = Align.center this.isLocalizationKey = false } stage.centreStage.elements += label stage.centreStage.elements += TextLabel(palette, stage.centreStage, stage.centreStage).apply { this.location.set(0.3f, 0.6f, 0.6f, 0.4f) this.textAlign = Align.left this.isLocalizationKey = true this.text = "screen.recovery.onlyChance" } stage.centreStage.elements += ImageLabel(palette, stage.centreStage, stage.centreStage).apply { this.image = TextureRegion(AssetRegistry.get<Texture>("ui_icon_warn")) this.renderType = ImageLabel.ImageRendering.ASPECT_RATIO this.location.set(0.1f, 0.6f, 0.2f, 0.4f) } stage.bottomStage.elements += Button(palette.copy(highlightedBackColor = Color(0f, 1f, 0f, 0.5f), clickedBackColor = Color(0.5f, 1f, 0.5f, 0.5f)), stage.bottomStage, stage.bottomStage).apply { this.location.set(screenX = 0.2f, screenWidth = 0.6f) addLabel(TextLabel(palette, this, this.stage).apply { this.text = "screen.recovery.button" this.isLocalizationKey = true }) this.leftClickAction = { _, _ -> val screen = ScreenRegistry.getNonNullAsType<OpenRemixScreen>("openRemix") screen.loadFile(RemixRecovery.recoveryFile.file(), overrideAutosave = true) main.screen = ScreenRegistry["editor"] // This forces the last checksum to be of a blank remix main.screen = screen } } } override fun show() { super.show() val formatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG, FormatStyle.SHORT) .withLocale(Localization.currentBundle.locale.locale) label.text = Localization["screen.recovery.label", formatter.format(RemixRecovery.getLastLocalDateTime())] } override fun tickUpdate() { } override fun dispose() { } }
gpl-3.0
df0c63d3bd8d8b9b5d5e81a62b63262d
43.344828
200
0.683173
4.098831
false
false
false
false
customerly/Customerly-Android-SDK
customerly-android-sdk/src/main/java/io/customerly/utils/ggkext/Ext_SharedPreferences.kt
1
1653
@file:Suppress("unused") /* * Copyright (C) 2017 Customerly * * 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.customerly.utils.ggkext import android.content.SharedPreferences import org.json.JSONObject /** * Created by Gianni on 05/01/18. */ internal fun SharedPreferences.safeString(key: String): String? = this.nullOnException { it.getString(key, null) } internal fun SharedPreferences.safeString(key: String, defValue: String): String = this.nullOnException { it.getString(key, defValue) } ?: defValue internal fun SharedPreferences.safeJson(key: String): JSONObject? = this.nullOnException { it.getString(key, null) }?.nullOnException { JSONObject(it) } internal fun SharedPreferences.safeJsonNonNull(key: String): JSONObject = this.safeJson(key = key) ?: JSONObject() internal fun SharedPreferences.safeInt(key: String, default : Int = 0): Int = this.nullOnException { it.getInt(key, default) } ?: default internal fun SharedPreferences.safeBoolean(key: String, default : Boolean = false): Boolean = this.nullOnException { it.getBoolean(key, default) } ?: default
apache-2.0
a8fe9477fe5194a461f6d643ab49d128
36.590909
94
0.732002
4.081481
false
false
false
false
android/wear-os-samples
ComposeStarter/app/src/main/java/com/example/android/wearable/composestarter/presentation/theme/Color.kt
1
1212
/* * 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. */ package com.example.android.wearable.composestarter.presentation.theme import androidx.compose.ui.graphics.Color import androidx.wear.compose.material.Colors val Purple200 = Color(0xFFBB86FC) val Purple500 = Color(0xFF6200EE) val Purple700 = Color(0xFF3700B3) val Teal200 = Color(0xFF03DAC5) val Red400 = Color(0xFFCF6679) internal val wearColorPalette: Colors = Colors( primary = Purple200, primaryVariant = Purple700, secondary = Teal200, secondaryVariant = Teal200, error = Red400, onPrimary = Color.Black, onSecondary = Color.Black, onError = Color.Black )
apache-2.0
6892cba74f6a13def131236d18c71a70
32.666667
75
0.750825
3.872204
false
false
false
false
DmytroTroynikov/aemtools
aem-intellij-core/src/test/kotlin/com/aemtools/findusages/FindUsagesTest.kt
1
1756
package com.aemtools.findusages import com.aemtools.common.util.findParentByType import com.aemtools.test.base.BaseLightTest import com.intellij.psi.PsiElement import com.intellij.psi.PsiMethod import com.intellij.psi.xml.XmlAttribute import org.assertj.core.api.Assertions.assertThat /** * @author Dmytro Troynikov */ class FindUsagesTest : BaseLightTest() { fun testFindUsageOfPropertyMethod() = fileCase { addHtml("test.html", """ <div data-sly-use.bean='com.test.Bean'> $DOLLAR{bean.property} $DOLLAR{bean.getProperty} </div> """) addClass("Bean", """ package com.test; public class Bean { public String ${CARET}getProperty() { return ""; } } """) verify { val elementUnderCaret = elementUnderCaret() val element = elementUnderCaret.findParentByType(PsiMethod::class.java) val usages = myFixture.findUsages(element as PsiElement) assertThat(usages) .isNotNull val holders = usages.map { it.element?.text } .filterNotNull() assertContainsElements(holders, listOf( "bean.property", "bean.getProperty" )) } } fun testFindUsagesOfUseVariable() = fileCase { addHtml("test.html", """ <div ${CARET}data-sly-use.bean=""> $DOLLAR{bean} </div> """) verify { val element = elementUnderCaret() val attr = element.findParentByType(XmlAttribute::class.java) val usages = myFixture.findUsages(attr!!) assertThat(usages) .isNotNull } } //todo add test for nested call e.g. bean.model.field }
gpl-3.0
a4d762662a5376baf7ec6bdfc8ff34b9
24.823529
77
0.598519
4.633245
false
true
false
false
matrix-org/matrix-android-sdk
matrix-sdk/src/main/java/org/matrix/androidsdk/core/FileUtils.kt
1
2055
/* * Copyright 2019 New Vector Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.matrix.androidsdk.core import android.text.TextUtils /** * Get the file extension of a fileUri or a filename * * @param fileUri the fileUri (can be a simple filename) * @return the file extension, in lower case, or null is extension is not available or empty */ fun getFileExtension(fileUri: String): String? { var reducedStr = fileUri if (!TextUtils.isEmpty(reducedStr)) { // Remove fragment val fragment = fileUri.lastIndexOf('#') if (fragment > 0) { reducedStr = fileUri.substring(0, fragment) } // Remove query val query = reducedStr.lastIndexOf('?') if (query > 0) { reducedStr = reducedStr.substring(0, query) } // Remove path val filenamePos = reducedStr.lastIndexOf('/') val filename = if (0 <= filenamePos) reducedStr.substring(filenamePos + 1) else reducedStr // Contrary to method MimeTypeMap.getFileExtensionFromUrl, we do not check the pattern // See https://stackoverflow.com/questions/14320527/android-should-i-use-mimetypemap-getfileextensionfromurl-bugs if (!filename.isEmpty()) { val dotPos = filename.lastIndexOf('.') if (0 <= dotPos) { val ext = filename.substring(dotPos + 1) if (ext.isNotBlank()) { return ext.toLowerCase() } } } } return null }
apache-2.0
f123a779ba118aee1bba69964ebef57b
32.16129
121
0.642336
4.409871
false
false
false
false
leafclick/intellij-community
python/python-psi-impl/src/com/jetbrains/python/codeInsight/typing/PyTypedDictOverridingTypeProvider.kt
1
3357
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.jetbrains.python.codeInsight.typing import com.intellij.openapi.util.Ref import com.intellij.psi.PsiElement import com.jetbrains.python.codeInsight.typing.PyTypingTypeProvider.MAPPING_GET import com.jetbrains.python.psi.* import com.jetbrains.python.psi.impl.PyBuiltinCache import com.jetbrains.python.psi.impl.PyEvaluator import com.jetbrains.python.psi.impl.PyOverridingTypeProvider import com.jetbrains.python.psi.types.* class PyTypedDictOverridingTypeProvider : PyTypeProviderBase(), PyOverridingTypeProvider { override fun getReferenceType(referenceTarget: PsiElement, context: TypeEvalContext, anchor: PsiElement?): Ref<PyType>? { val typedDictGetType = getTypedDictGetType(referenceTarget, context, anchor) if (typedDictGetType != null) { return Ref.create(typedDictGetType) } val type = PyTypedDictTypeProvider.getTypedDictTypeForResolvedCallee(referenceTarget, context) return PyTypeUtil.notNullToRef(type) } override fun getReferenceExpressionType(referenceExpression: PyReferenceExpression, context: TypeEvalContext): PyType? { return getTypedDictGetType(referenceExpression, context, null) } private fun getTypedDictGetType(referenceTarget: PsiElement, context: TypeEvalContext, anchor: PsiElement?): PyCallableType? { val callExpression = if (anchor == null && context.maySwitchToAST(referenceTarget) && referenceTarget.parent is PyCallExpression) referenceTarget.parent else anchor if (callExpression !is PyCallExpression || callExpression.callee == null) return null val receiver = callExpression.getReceiver(null) ?: return null val type = context.getType(receiver) if (type !is PyTypedDictType) return null if (PyTypingTypeProvider.resolveToQualifiedNames(callExpression.callee!!, context).contains(MAPPING_GET)) { val parameters = mutableListOf<PyCallableParameter>() val builtinCache = PyBuiltinCache.getInstance(referenceTarget) val elementGenerator = PyElementGenerator.getInstance(referenceTarget.project) parameters.add(PyCallableParameterImpl.nonPsi("key", builtinCache.strType)) parameters.add(PyCallableParameterImpl.nonPsi("default", null, elementGenerator.createExpressionFromText(LanguageLevel.forElement(referenceTarget), "None"))) val key = PyEvaluator.evaluate(callExpression.getArgument(0, "key", PyExpression::class.java), String::class.java) val defaultArgument = callExpression.getArgument(1, "default", PyExpression::class.java) val default = if (defaultArgument != null) context.getType(defaultArgument) else PyNoneType.INSTANCE val valueTypeAndTotality = type.fields[key] return PyCallableTypeImpl(parameters, when { valueTypeAndTotality == null -> default valueTypeAndTotality.isRequired -> valueTypeAndTotality.type else -> PyUnionType.union(valueTypeAndTotality.type, default) }) } return null } }
apache-2.0
e9e1ced5b5afe725bd21645b6cda9098
54.966667
140
0.71552
5.432039
false
false
false
false
leafclick/intellij-community
platform/platform-api/src/com/intellij/ui/tabs/impl/JBEditorTabsBorder.kt
1
2295
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.ui.tabs.impl import com.intellij.ui.tabs.JBTabsBorder import com.intellij.ui.tabs.JBTabsPosition import java.awt.* class JBEditorTabsBorder(tabs: JBTabsImpl) : JBTabsBorder(tabs) { override val effectiveBorder: Insets get() = Insets(thickness, 0, 0, 0) override fun paintBorder(c: Component, g: Graphics, x: Int, y: Int, width: Int, height: Int) { g as Graphics2D tabs.tabPainter.paintBorderLine(g, thickness, Point(x, y), Point(x + width, y)) if(tabs.isEmptyVisible || tabs.isHideTabs) return if (JBTabsImpl.NEW_TABS) { val borderLines = tabs.lastLayoutPass.extraBorderLines ?: return for (borderLine in borderLines) { tabs.tabPainter.paintBorderLine(g, thickness, borderLine.from(), borderLine.to()) } } else { val myInfo2Label = tabs.myInfo2Label val firstLabel = myInfo2Label[tabs.lastLayoutPass.getTabAt(0, 0)] ?: return val startY = firstLabel.y - if (tabs.position == JBTabsPosition.bottom) 0 else thickness when(tabs.position) { JBTabsPosition.top -> { for (eachRow in 0..tabs.lastLayoutPass.rowCount) { val yl = (eachRow * tabs.myHeaderFitSize.height) + startY tabs.tabPainter.paintBorderLine(g, thickness, Point(x, yl), Point(x + width, yl)) } } JBTabsPosition.bottom -> { tabs.tabPainter.paintBorderLine(g, thickness, Point(x, startY), Point(x + width, startY)) tabs.tabPainter.paintBorderLine(g, thickness, Point(x, y), Point(x + width, y)) } JBTabsPosition.right -> { val lx = firstLabel.x tabs.tabPainter.paintBorderLine(g, thickness, Point(lx, y), Point(lx, y + height)) } JBTabsPosition.left -> { val bounds = firstLabel.bounds val i = bounds.x + bounds.width - thickness tabs.tabPainter.paintBorderLine(g, thickness, Point(i, y), Point(i, y + height)) } } } val selectedLabel = tabs.selectedLabel ?: return tabs.tabPainter.paintUnderline(tabs.position, selectedLabel.bounds, thickness, g, tabs.isActiveTabs(tabs.selectedInfo)) } }
apache-2.0
2bad017c94a86fa80dd70ee3fcce88fe
39.280702
140
0.662309
3.876689
false
false
false
false
leafclick/intellij-community
platform/statistics/devkit/src/com/intellij/internal/statistic/actions/ShowStatisticsEventLogAction.kt
1
3459
// 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.internal.statistic.actions import com.intellij.icons.AllIcons import com.intellij.ide.actions.NonEmptyActionGroup import com.intellij.ide.impl.ContentManagerWatcher import com.intellij.internal.statistic.eventLog.getEventLogProviders import com.intellij.internal.statistic.eventLog.validator.rules.impl.TestModeValidationRule import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.project.DumbAwareAction import com.intellij.openapi.project.Project import com.intellij.openapi.wm.ToolWindow import com.intellij.openapi.wm.ToolWindowAnchor import com.intellij.openapi.wm.ToolWindowManager import com.intellij.openapi.wm.impl.ToolWindowImpl import com.intellij.ui.content.ContentFactory import com.intellij.ui.content.ContentManager /** * Opens a toolwindow with feature usage statistics event log */ internal class ShowStatisticsEventLogAction : DumbAwareAction() { override fun actionPerformed(event: AnActionEvent) { val project = event.project ?: return val toolWindow = getToolWindow(project) val contentManager = toolWindow.contentManager if (contentManager.contentCount == 0) { createNewTab(project, contentManager, "FUS") ContentManagerWatcher.watchContentManager(toolWindow, contentManager) if (toolWindow is ToolWindowImpl) { val newSessionActionGroup = createNewSessionActionGroup(project) toolWindow.setTabActions(newSessionActionGroup) } } toolWindow.activate(null) } override fun update(event: AnActionEvent) { super.update(event) event.presentation.isEnabled = TestModeValidationRule.isTestModeEnabled() } private fun createNewSessionActionGroup(project: Project): NonEmptyActionGroup { val actionGroup = NonEmptyActionGroup() actionGroup.isPopup = true actionGroup.templatePresentation.icon = AllIcons.General.Add val actions = getEventLogProviders().map { logger -> val recorder = logger.recorderId NewStatisticsEventLogSession(project, recorder) } actionGroup.addAll(actions) return actionGroup } class NewStatisticsEventLogSession(private val project: Project, private val recorderId: String) : AnAction(recorderId) { override fun actionPerformed(e: AnActionEvent) { val toolWindow = getToolWindow(project) createNewTab(project, toolWindow.contentManager, recorderId) } } companion object { private fun createNewTab( project: Project, contentManager: ContentManager, recorderId: String ) { val eventLogToolWindow = StatisticsEventLogToolWindow(project, recorderId) val content = ContentFactory.SERVICE.getInstance().createContent(eventLogToolWindow.component, recorderId, true) content.preferredFocusableComponent = eventLogToolWindow.component contentManager.addContent(content) } private fun getToolWindow(project: Project): ToolWindow { val toolWindowManager = ToolWindowManager.getInstance(project) val toolWindow = toolWindowManager.getToolWindow(eventLogToolWindowsId) if (toolWindow != null) { return toolWindow } return toolWindowManager.registerToolWindow(eventLogToolWindowsId, true, ToolWindowAnchor.BOTTOM, project, true) } } }
apache-2.0
492d0710fa5edef57c1c778a4c094671
39.232558
140
0.776814
4.991342
false
false
false
false
zdary/intellij-community
platform/vcs-impl/src/com/intellij/impl/VcsModuleAttachListener.kt
8
2753
// 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.impl import com.intellij.openapi.module.Module import com.intellij.openapi.roots.ModuleRootManager import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.vcs.ProjectLevelVcsManager import com.intellij.openapi.vcs.VcsDirectoryMapping import com.intellij.openapi.vfs.LocalFileSystem import com.intellij.openapi.vfs.VirtualFile import com.intellij.platform.ModuleAttachListener import java.io.File import java.nio.file.Path class VcsModuleAttachListener : ModuleAttachListener { override fun afterAttach(module: Module, primaryModule: Module?, imlFile: Path) { primaryModule ?: return val dotIdeaDirParent = imlFile.parent?.parent?.let { LocalFileSystem.getInstance().findFileByPath(it.toString()) } if (dotIdeaDirParent != null) { addVcsMapping(primaryModule, dotIdeaDirParent) } } override fun beforeDetach(module: Module) { removeVcsMapping(module) } private fun addVcsMapping(primaryModule: Module, addedModuleContentRoot: VirtualFile) { val project = primaryModule.project val vcsManager = ProjectLevelVcsManager.getInstance(project) val mappings = vcsManager.directoryMappings if (mappings.size == 1) { val contentRoots = ModuleRootManager.getInstance(primaryModule).contentRoots // if we had one mapping for the root of the primary module and the added module uses the same VCS, change mapping to <Project Root> if (contentRoots.size == 1 && FileUtil.filesEqual(File(contentRoots[0].path), File(mappings[0].directory))) { val vcs = vcsManager.findVersioningVcs(addedModuleContentRoot) if (vcs != null && vcs.name == mappings[0].vcs) { vcsManager.directoryMappings = listOf(VcsDirectoryMapping.createDefault(vcs.name)) return } } } val vcs = vcsManager.findVersioningVcs(addedModuleContentRoot) if (vcs != null) { val newMappings = ArrayList(mappings) newMappings.add(VcsDirectoryMapping(addedModuleContentRoot.path, vcs.name)) vcsManager.directoryMappings = newMappings } } private fun removeVcsMapping(module: Module) { val project = module.project val vcsManager = ProjectLevelVcsManager.getInstance(project) val mappings = vcsManager.directoryMappings val newMappings = ArrayList(mappings) for (mapping in mappings) { for (root in ModuleRootManager.getInstance(module).contentRoots) { if (FileUtil.filesEqual(File(root.path), File(mapping.directory))) { newMappings.remove(mapping) } } } vcsManager.directoryMappings = newMappings } }
apache-2.0
0ed940930da623a6159cfaf6aa032207
40.727273
140
0.7421
4.681973
false
false
false
false
Raizlabs/DBFlow
processor/src/main/kotlin/com/dbflow5/processor/Validators.kt
1
12406
package com.dbflow5.processor import com.dbflow5.processor.definition.DatabaseDefinition import com.dbflow5.processor.definition.ModelViewDefinition import com.dbflow5.processor.definition.OneToManyDefinition import com.dbflow5.processor.definition.TableDefinition import com.dbflow5.processor.definition.TypeConverterDefinition import com.dbflow5.processor.definition.column.ColumnDefinition import com.dbflow5.processor.definition.column.EnumColumnAccessor import com.dbflow5.processor.definition.column.PrivateScopeColumnAccessor import com.dbflow5.processor.definition.column.ReferenceColumnDefinition import com.dbflow5.processor.definition.provider.ContentProviderDefinition import com.dbflow5.processor.definition.provider.TableEndpointDefinition import com.dbflow5.processor.utils.isNullOrEmpty /** * Description: the base interface for validating annotations. */ interface Validator<in ValidatorDefinition> { /** * @param processorManager The manager * * * @param validatorDefinition The validator to use * * * @return true if validation passed, false if there was an error. */ fun validate(processorManager: ProcessorManager, validatorDefinition: ValidatorDefinition): Boolean } /** * Description: Ensures the integrity of the annotation processor for columns. * @author Andrew Grosner (fuzz) */ class ColumnValidator : Validator<ColumnDefinition> { private var autoIncrementingPrimaryKey: ColumnDefinition? = null override fun validate(processorManager: ProcessorManager, validatorDefinition: ColumnDefinition): Boolean { var success = true // validate getter and setters. if (validatorDefinition.columnAccessor is PrivateScopeColumnAccessor) { val privateColumnAccess = validatorDefinition.columnAccessor as PrivateScopeColumnAccessor if (!validatorDefinition.entityDefinition.classElementLookUpMap.containsKey(privateColumnAccess.getterNameElement)) { processorManager.logError(ColumnValidator::class, """Could not find getter for private element: "${validatorDefinition.elementName}" | from table class: ${validatorDefinition.entityDefinition.elementName}. | Consider adding a getter with name ${privateColumnAccess.getterNameElement}, | making it more accessible, or adding a @get:JvmName("${privateColumnAccess.getterNameElement}") """ .trimMargin()) success = false } if (!validatorDefinition.entityDefinition.classElementLookUpMap.containsKey(privateColumnAccess.setterNameElement)) { processorManager.logError(ColumnValidator::class, """Could not find setter for private element: "${validatorDefinition.elementName}" | from table class: ${validatorDefinition.entityDefinition.elementName}. | Consider adding a setter with name ${privateColumnAccess.setterNameElement}, | making it more accessible, or adding a @set:JvmName("${privateColumnAccess.setterNameElement}").""" .trimMargin()) success = false } } if (!validatorDefinition.defaultValue.isNullOrEmpty()) { val typeName = validatorDefinition.elementTypeName if (validatorDefinition is ReferenceColumnDefinition && validatorDefinition.isReferencingTableObject) { processorManager.logError(ColumnValidator::class, "Default values cannot be specified for model fields") } else if (typeName?.isPrimitive == true) { processorManager.logWarning(ColumnValidator::class.java, "Default value of ${validatorDefinition.defaultValue} from" + " ${validatorDefinition.entityDefinition.elementName}.${validatorDefinition.elementName}" + " is ignored for primitive columns.") } } if (validatorDefinition.columnName.isEmpty()) { success = false processorManager.logError("Field ${validatorDefinition.elementName} " + "cannot have a null column name for column: ${validatorDefinition.columnName}" + " and type: ${validatorDefinition.elementTypeName}") } if (validatorDefinition.columnAccessor is EnumColumnAccessor) { if (validatorDefinition.type is ColumnDefinition.Type.Primary) { success = false processorManager.logError("Enums cannot be primary keys. Column: ${validatorDefinition.columnName}" + " and type: ${validatorDefinition.elementTypeName}") } else if (validatorDefinition is ReferenceColumnDefinition) { success = false processorManager.logError("Enums cannot be foreign keys. Column: ${validatorDefinition.columnName}" + " and type: ${validatorDefinition.elementTypeName}") } } if (validatorDefinition is ReferenceColumnDefinition) { validatorDefinition.column?.let { if (it.name.isNotEmpty()) { success = false processorManager.logError("Foreign Key ${validatorDefinition.elementName} cannot specify the @Column.name() field. " + "Use a @ForeignKeyReference(columnName = {NAME} instead. " + "Column: ${validatorDefinition.columnName} and type: ${validatorDefinition.elementTypeName}") } } // it is an error to specify both a not null and provide explicit references. if (validatorDefinition.explicitReferences && validatorDefinition.notNull) { success = false processorManager.logError("Foreign Key ${validatorDefinition.elementName} " + "cannot specify both @NotNull and references. Remove the top-level @NotNull " + "and use the contained 'notNull' field " + "in each reference to control its SQL notnull conflicts.") } } else { if (autoIncrementingPrimaryKey != null && validatorDefinition.type is ColumnDefinition.Type.Primary) { processorManager.logError("You cannot mix and match autoincrementing and composite primary keys.") success = false } if (validatorDefinition.type is ColumnDefinition.Type.PrimaryAutoIncrement || validatorDefinition.type is ColumnDefinition.Type.RowId) { if (autoIncrementingPrimaryKey == null) { autoIncrementingPrimaryKey = validatorDefinition } else if (autoIncrementingPrimaryKey != validatorDefinition) { processorManager.logError("Only one auto-incrementing primary key is allowed on a table. " + "Found Column: ${validatorDefinition.columnName} and type: ${validatorDefinition.elementTypeName}") success = false } } } return success } } /** * Description: */ class ContentProviderValidator : Validator<ContentProviderDefinition> { override fun validate(processorManager: ProcessorManager, validatorDefinition: ContentProviderDefinition): Boolean { var success = true if (validatorDefinition.endpointDefinitions.isEmpty()) { processorManager.logError("The content provider ${validatorDefinition.element.simpleName} " + "must have at least 1 @TableEndpoint associated with it") success = false } return success } } /** * Description: */ class DatabaseValidator : Validator<DatabaseDefinition> { override fun validate(processorManager: ProcessorManager, validatorDefinition: DatabaseDefinition): Boolean = true } /** * Description: */ class ModelViewValidator : Validator<ModelViewDefinition> { override fun validate(processorManager: ProcessorManager, validatorDefinition: ModelViewDefinition): Boolean = true } /** * Description: Validates to ensure a [OneToManyDefinition] is correctly coded. Will throw failures on the [ProcessorManager] */ class OneToManyValidator : Validator<OneToManyDefinition> { override fun validate(processorManager: ProcessorManager, validatorDefinition: OneToManyDefinition): Boolean = true } class TableEndpointValidator : Validator<TableEndpointDefinition> { override fun validate(processorManager: ProcessorManager, validatorDefinition: TableEndpointDefinition): Boolean { var success = true if (validatorDefinition.contentUriDefinitions.isEmpty()) { processorManager.logError("A table endpoint ${validatorDefinition.elementClassName} " + "must supply at least one @ContentUri") success = false } return success } } /** * Description: Validates proper usage of the [com.dbflow5.annotation.Table] */ class TableValidator : Validator<TableDefinition> { override fun validate(processorManager: ProcessorManager, validatorDefinition: TableDefinition): Boolean { var success = true if (!validatorDefinition.hasPrimaryConstructor) { processorManager.logError(TableValidator::class, "Table ${validatorDefinition.elementClassName}" + " must provide a visible, parameterless constructor. Each field also must have a visible " + "setter for now.") success = false } if (validatorDefinition.columnDefinitions.isEmpty()) { processorManager.logError(TableValidator::class, "Table ${validatorDefinition.associationalBehavior.name} " + "of ${validatorDefinition.elementClassName}, ${validatorDefinition.element.javaClass} " + "needs to define at least one column") success = false } val hasTwoKinds = (validatorDefinition.primaryKeyColumnBehavior.hasAutoIncrement || validatorDefinition.primaryKeyColumnBehavior.hasRowID) && !validatorDefinition._primaryColumnDefinitions.isEmpty() if (hasTwoKinds) { processorManager.logError(TableValidator::class, "Table ${validatorDefinition.associationalBehavior.name}" + " cannot mix and match autoincrement and composite primary keys") success = false } val hasPrimary = (validatorDefinition.primaryKeyColumnBehavior.hasAutoIncrement || validatorDefinition.primaryKeyColumnBehavior.hasRowID) && validatorDefinition._primaryColumnDefinitions.isEmpty() || !validatorDefinition.primaryKeyColumnBehavior.hasAutoIncrement && !validatorDefinition.primaryKeyColumnBehavior.hasRowID && !validatorDefinition._primaryColumnDefinitions.isEmpty() if (!hasPrimary && validatorDefinition.type == TableDefinition.Type.Normal) { processorManager.logError(TableValidator::class, "Table ${validatorDefinition.associationalBehavior.name} " + "needs to define at least one primary key") success = false } return success } } class TypeConverterValidator : Validator<TypeConverterDefinition> { override fun validate(processorManager: ProcessorManager, validatorDefinition: TypeConverterDefinition): Boolean { var success = true if (validatorDefinition.modelTypeName == null) { processorManager.logError("TypeConverter: ${validatorDefinition.className} uses an " + "unsupported Model Element parameter. If it has type parameters, you must " + "remove them or subclass it for proper usage.") success = false } else if (validatorDefinition.dbTypeName == null) { processorManager.logError("TypeConverter: ${validatorDefinition.className} uses an " + "unsupported DB Element parameter. If it has type parameters, you must remove" + " them or subclass it for proper usage.") success = false } return success } }
mit
77f5e28d3b5e06d518038da28c29b357
45.992424
136
0.666774
5.598375
false
false
false
false
zdary/intellij-community
platform/dvcs-impl/src/com/intellij/dvcs/ui/DvcsCloneDialogComponent.kt
3
4382
// 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.dvcs.ui import com.intellij.dvcs.DvcsRememberedInputs import com.intellij.dvcs.repo.ClonePathProvider import com.intellij.dvcs.ui.CloneDvcsValidationUtils.sanitizeCloneUrl import com.intellij.dvcs.ui.DvcsBundle.message import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory import com.intellij.openapi.project.Project import com.intellij.openapi.ui.ValidationInfo import com.intellij.openapi.util.text.StringUtil import com.intellij.openapi.vcs.CheckoutProvider import com.intellij.openapi.vcs.VcsBundle import com.intellij.openapi.vcs.ui.VcsCloneComponent import com.intellij.openapi.vcs.ui.cloneDialog.VcsCloneDialogComponentStateListener import com.intellij.ui.DocumentAdapter import com.intellij.ui.TextFieldWithHistory import com.intellij.ui.layout.* import com.intellij.util.concurrency.annotations.RequiresEdt import com.intellij.util.containers.ContainerUtil import com.intellij.util.ui.JBEmptyBorder import com.intellij.util.ui.UIUtil import com.intellij.util.ui.components.BorderLayoutPanel import javax.swing.JComponent import javax.swing.JPanel import javax.swing.event.DocumentEvent abstract class DvcsCloneDialogComponent(var project: Project, private var vcsDirectoryName: String, protected val rememberedInputs: DvcsRememberedInputs, private val dialogStateListener: VcsCloneDialogComponentStateListener) : VcsCloneComponent { protected val mainPanel: JPanel private val urlEditor = TextFieldWithHistory() private val directoryField = SelectChildTextFieldWithBrowseButton( ClonePathProvider.defaultParentDirectoryPath(project, rememberedInputs)) protected lateinit var errorComponent: BorderLayoutPanel init { val fcd = FileChooserDescriptorFactory.createSingleFolderDescriptor() fcd.isShowFileSystemRoots = true fcd.isHideIgnored = false directoryField.addBrowseFolderListener(message("clone.destination.directory.browser.title"), message("clone.destination.directory.browser.description"), project, fcd) mainPanel = panel { row(VcsBundle.message("vcs.common.labels.url")) { urlEditor(growX) } row(VcsBundle.message("vcs.common.labels.directory")) { directoryField(growX) } .largeGapAfter() row { errorComponent = BorderLayoutPanel(UIUtil.DEFAULT_HGAP, 0) errorComponent() } } val insets = UIUtil.PANEL_REGULAR_INSETS mainPanel.border = JBEmptyBorder(insets.top / 2, insets.left, insets.bottom, insets.right) urlEditor.history = rememberedInputs.visitedUrls urlEditor.addDocumentListener(object : DocumentAdapter() { override fun textChanged(e: DocumentEvent) { directoryField.trySetChildPath(defaultDirectoryPath(urlEditor.text.trim())) updateOkActionState(dialogStateListener) } }) } override fun getPreferredFocusedComponent(): JComponent = urlEditor private fun defaultDirectoryPath(url: String): String { return StringUtil.trimEnd(ClonePathProvider.relativeDirectoryPathForVcsUrl(project, url), vcsDirectoryName) } override fun getView() = mainPanel override fun isOkEnabled(): Boolean { return false } override fun doValidateAll(): List<ValidationInfo> { val list = ArrayList<ValidationInfo>() ContainerUtil.addIfNotNull(list, CloneDvcsValidationUtils.checkDirectory(directoryField.text, directoryField.textField)) ContainerUtil.addIfNotNull(list, CloneDvcsValidationUtils.checkRepositoryURL(urlEditor, urlEditor.text.trim())) return list } abstract override fun doClone(project: Project, listener: CheckoutProvider.Listener) fun getDirectory(): String = directoryField.text.trim() fun getUrl(): String = sanitizeCloneUrl(urlEditor.text) override fun dispose() {} @RequiresEdt protected open fun isOkActionEnabled(): Boolean = getUrl().isNotBlank() @RequiresEdt protected fun updateOkActionState(dialogStateListener: VcsCloneDialogComponentStateListener) { dialogStateListener.onOkActionEnabled(isOkActionEnabled()) } }
apache-2.0
6c7127ba141fcfa7ca0f53176ea02cb4
41.553398
140
0.752853
4.957014
false
false
false
false
mpcjanssen/simpletask-android
app/src/nextcloud/java/nl/mpcjanssen/simpletask/remote/FileStore.kt
1
10689
package nl.mpcjanssen.simpletask.remote import android.content.Context import android.net.ConnectivityManager import android.net.Uri import android.util.Log import com.owncloud.android.lib.common.OwnCloudClient import com.owncloud.android.lib.common.OwnCloudClientFactory import com.owncloud.android.lib.common.OwnCloudClientManagerFactory import com.owncloud.android.lib.common.OwnCloudCredentialsFactory import com.owncloud.android.lib.common.operations.RemoteOperationResult import com.owncloud.android.lib.resources.files.DownloadFileRemoteOperation import com.owncloud.android.lib.resources.files.ReadFileRemoteOperation import com.owncloud.android.lib.resources.files.ReadFolderRemoteOperation import com.owncloud.android.lib.resources.files.UploadFileRemoteOperation import com.owncloud.android.lib.resources.files.model.RemoteFile import nl.mpcjanssen.simpletask.R import nl.mpcjanssen.simpletask.TodoApplication import nl.mpcjanssen.simpletask.TodoException import nl.mpcjanssen.simpletask.util.broadcastAuthFailed import nl.mpcjanssen.simpletask.util.join import nl.mpcjanssen.simpletask.util.showToastLong import java.io.File import java.io.IOException import java.util.* import kotlin.reflect.KClass /** * FileStore implementation backed by Nextcloud */ object FileStore : IFileStore { internal val NEXTCLOUD_USER = "ncUser" internal val NEXTCLOUD_PASS = "ncPass" internal val NEXTCLOUD_URL = "ncURL" private var lastSeenRemoteId by TodoApplication.config.StringOrNullPreference(R.string.file_current_version_id) var username by TodoApplication.config.StringOrNullPreference(NEXTCLOUD_USER) var password by TodoApplication.config.StringOrNullPreference(NEXTCLOUD_PASS) private var serverUrl by TodoApplication.config.StringOrNullPreference(NEXTCLOUD_URL) override val isEncrypted: Boolean get() = false val isAuthenticated: Boolean get() { Log.d("FileStore", "FileStore is authenticated ${username != null}") return username != null } override fun logout() { username = null password = null serverUrl = null } private val TAG = "FileStore" private val mApp = TodoApplication.app private fun getClient () : OwnCloudClient? { serverUrl?.let { url -> val ctx = TodoApplication.app.applicationContext OwnCloudClientManagerFactory.setUserAgent("Mozilla/5.0 (Android) Nextcloud-android/3.8.1") val client = OwnCloudClientFactory.createOwnCloudClient(Uri.parse(url), ctx, true) client.credentials = OwnCloudCredentialsFactory.newBasicCredentials( username, password ) return client } return null } private fun getRemoteVersion(file: File): String { if (!isAuthenticated) { broadcastAuthFailed(TodoApplication.app.localBroadCastManager) return "" } val op = ReadFileRemoteOperation(file.canonicalPath) val res = op.execute(getClient()) return if (res.isSuccess) { val file = res.data[0] as RemoteFile Log.d(TAG, "Remote versions of $file: id: ${file.remoteId} tag: ${file.etag} modified: ${file.modifiedTimestamp} ") file.etag } else { Log.w(TAG, "Failed to get remote version of $file: ${res.code}") throw TodoException("${res.code}: ${res.exception}") } } override val isOnline: Boolean get() { val cm = mApp.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager val netInfo = cm.activeNetworkInfo val online = netInfo != null && netInfo.isConnected Log.d("FileStore","Filestore online: $online") return online } override fun loadTasksFromFile(file: File): List<String> { if (!isAuthenticated) { broadcastAuthFailed(TodoApplication.app.localBroadCastManager) return emptyList() } // If we load a file and changes are pending, we do not want to overwrite // our local changes, instead we try to upload local Log.i(TAG, "Loading file from Nextcloud: " + file) if (!isAuthenticated) { throw IOException("Not authenticated") } val readLines = ArrayList<String>() val cacheDir = mApp.applicationContext.cacheDir val op = DownloadFileRemoteOperation(file.canonicalPath, cacheDir.canonicalPath) val client = getClient() op.execute(client) val infoOp = ReadFileRemoteOperation(file.canonicalPath) val res = infoOp.execute(client) if (res.httpCode == 404) { throw (IOException("File not found")) } val fileInfo = res.data[0] as RemoteFile val cachePath = File(cacheDir, file.path).canonicalPath readLines.addAll(File(cachePath).readLines()) lastSeenRemoteId = fileInfo.etag return readLines } override fun needSync(file: File): Boolean { if (!isAuthenticated) { broadcastAuthFailed(TodoApplication.app.localBroadCastManager) return true } return getRemoteVersion(file) != lastSeenRemoteId } override fun todoNameChanged() { lastSeenRemoteId = "" } override fun loginActivity(): KClass<*>? { return LoginScreen::class } @Synchronized @Throws(IOException::class) override fun saveTasksToFile(file: File, lines: List<String>, eol: String) : File { if (!isAuthenticated) { broadcastAuthFailed(TodoApplication.app.localBroadCastManager) return file } val contents = join(lines, eol) + eol val timestamp = timeStamp() Log.i(TAG, "Saving to file " + file) val cacheDir = mApp.applicationContext.cacheDir val tmpFile = File(cacheDir, "tmp.txt") tmpFile.writeText(contents) val client = getClient() // if we have previously seen a file from the server, we don't upload unless it's the // one we've seen before. If we've never seen a file, we just upload unconditionally val res = UploadFileRemoteOperation(tmpFile.absolutePath, file.canonicalPath, "text/plain", timestamp).execute(client) val conflict = 412 val currentName = if (res.httpCode == conflict) { val parent = file.parent val name = file.name val nameWithoutTxt = "\\.txt$".toRegex().replace(name, "") val newName = nameWithoutTxt + "_conflict_" + UUID.randomUUID() + ".txt" val newPath = parent + "/" + newName UploadFileRemoteOperation(tmpFile.absolutePath, newPath, "text/plain", timestamp).execute(client) showToastLong(TodoApplication.app, "CONFLICT! Uploaded as " + newName + ". Review differences manually with a text editor.") newPath } else { file.canonicalPath } val infoOp = ReadFileRemoteOperation(file.canonicalPath) val infoRes = infoOp.execute(client) val fileInfo = infoRes.data[0] as RemoteFile Log.i(TAG,"New remote version tag: ${fileInfo.etag}, id: ${fileInfo.remoteId}, modified: ${fileInfo.modifiedTimestamp}") lastSeenRemoteId = fileInfo.etag return File(currentName) } @Throws(IOException::class) override fun appendTaskToFile(file: File, lines: List<String>, eol: String) { if (!isAuthenticated) { broadcastAuthFailed(TodoApplication.app.localBroadCastManager) return } if (!isOnline) { throw IOException("Device is offline") } val cacheDir = mApp.applicationContext.cacheDir val client = getClient() val op = DownloadFileRemoteOperation(file.canonicalPath, cacheDir.canonicalPath) val result = op.execute(client) val doneContents = if (result.isSuccess) { val cachePath = File(cacheDir, file.canonicalPath).canonicalPath File(cachePath).readLines().toMutableList() } else { ArrayList<String>() } doneContents.addAll(lines) val contents = join(doneContents, eol) + eol val tmpFile = File(cacheDir, "tmp.txt") tmpFile.writeText(contents) val timestamp = timeStamp() val writeOp = UploadFileRemoteOperation(tmpFile.absolutePath, file.canonicalPath, "text/plain", timestamp) writeOp.execute(client) } override fun writeFile(file: File, contents: String) { if (!isAuthenticated) { broadcastAuthFailed(TodoApplication.app.localBroadCastManager) return } val cacheDir = mApp.applicationContext.cacheDir val tmpFile = File(cacheDir, "tmp.txt") tmpFile.writeText(contents) val op = UploadFileRemoteOperation(tmpFile.absolutePath, file.canonicalPath, "text/plain", timeStamp()) val result = op.execute(getClient()) Log.i(TAG, "Wrote file to $file, result ${result.isSuccess}") } private fun timeStamp() = (System.currentTimeMillis() / 1000).toString() @Throws(IOException::class) override fun readFile(file: File, fileRead: (String) -> Unit) { if (!isAuthenticated) { return } val cacheDir = mApp.applicationContext.cacheDir val op = DownloadFileRemoteOperation(file.canonicalPath, cacheDir.canonicalPath) op.execute(getClient()) val cachePath = File(cacheDir, file.canonicalPath).canonicalPath val contents = File(cachePath).readText() fileRead(contents) } override fun loadFileList(file: File, txtOnly: Boolean): List<FileEntry> { if (!isAuthenticated) { broadcastAuthFailed(TodoApplication.app.localBroadCastManager) return emptyList() } val result = ArrayList<FileEntry>() val op = ReadFolderRemoteOperation(file.canonicalPath) getClient()?.let { val res: RemoteOperationResult = op.execute(it) // Loop over the resulting files // Drop the first one as it is the current folder res.data.drop(1).forEach { remoteFile -> if (remoteFile is RemoteFile) { result.add(FileEntry(File(remoteFile.remotePath).name, isFolder = (remoteFile.mimeType == "DIR"))) } } } return result } override fun getDefaultFile(): File { return File("/todo.txt") } }
gpl-3.0
a6f600db5d73a647284d260a184d37d8
36.770318
128
0.652914
4.887517
false
false
false
false
Nunnery/MythicDrops
src/main/kotlin/com/tealcube/minecraft/bukkit/mythicdrops/utils/GemUtil.kt
1
5881
/* * 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.utils import com.tealcube.minecraft.bukkit.mythicdrops.MythicDropsPlugin import com.tealcube.minecraft.bukkit.mythicdrops.api.settings.SocketingSettings import com.tealcube.minecraft.bukkit.mythicdrops.api.socketing.SocketGem import com.tealcube.minecraft.bukkit.mythicdrops.api.socketing.SocketGemManager import com.tealcube.minecraft.bukkit.mythicdrops.stripColors import com.tealcube.minecraft.bukkit.mythicdrops.strippedIndexOf import io.pixeloutlaw.minecraft.spigot.hilt.getLore import io.pixeloutlaw.minecraft.spigot.mythicdrops.getSocketGem import net.md_5.bungee.api.ChatColor import org.bukkit.Material import org.bukkit.entity.EntityType import org.bukkit.inventory.ItemStack /** * Utility methods for working with Socket Gems. */ object GemUtil { private val disableLegacyItemCheck: Boolean get() = MythicDropsPlugin.getInstance().settingsManager.configSettings.options.isDisableLegacyItemChecks private val socketGemManager: SocketGemManager get() = MythicDropsPlugin.getInstance().socketGemManager private val socketingSettings: SocketingSettings get() = MythicDropsPlugin.getInstance().settingsManager.socketingSettings /** * Gets the gem associated with an [ItemStack] like * [com.tealcube.minecraft.bukkit.mythicdrops.socketing.SocketItem]. * * @param itemStack ItemStack to check */ fun getSocketGemFromPotentialSocketItem(itemStack: ItemStack?): SocketGem? { return itemStack?.getSocketGem(socketGemManager, socketingSettings, disableLegacyItemCheck) } /** * Returns index of first open socket in [list], -1 if there are none. * * @param list List of Strings to check against * * @return index of first open socket */ fun indexOfFirstOpenSocket(list: List<String>): Int { val socketString = socketingSettings.items.socketedItem.socket.replace('&', '\u00A7') .replace("\u00A7\u00A7", "&") .replace("%tiercolor%", "") return list.strippedIndexOf(ChatColor.stripColor(socketString), true) } /** * Returns index of first open socket on [itemStack], -1 if there are none. * * @param itemStack ItemStack to check against * * @return index of first open socket */ fun indexOfFirstOpenSocket(itemStack: ItemStack): Int = indexOfFirstOpenSocket(itemStack.getLore()) /** * Gets [SocketGem] from [SocketGemManager] with case-insensitive searching. Also checks for [name] with underscores * replaced by spaces. * * @param name Name to attempt to find * @return */ fun getSocketGemFromName(name: String): SocketGem? { for (sg in socketGemManager.get()) { if (sg.name.equals(name, ignoreCase = true) || sg.name.equals(name.replace("_", " "), ignoreCase = true)) { return sg } } return null } fun getRandomSocketGemByWeightFromFamily(family: String): SocketGem? = socketGemManager.randomByWeight() { it.family.equals(family, ignoreCase = true) } fun getRandomSocketGemByWeightFromFamilyWithLevel(family: String, level: Int): SocketGem? = socketGemManager.randomByWeight { it.family.equals(family, ignoreCase = true) && it.level == level } fun getRandomSocketGemByWeightWithLevel(level: Int): SocketGem? = socketGemManager.randomByWeight { it.level == level } fun getRandomSocketGemMaterial(): Material? = if (socketingSettings.options.socketGemMaterialIds.isNotEmpty()) { socketingSettings.options.socketGemMaterialIds.random() } else { null } @JvmOverloads fun getRandomSocketGemByWeight(entityType: EntityType? = null): SocketGem? = socketGemManager.randomByWeight { entityType == null || it.canDropFrom(entityType) } fun getSocketGemsFromStringList(list: List<String>): List<SocketGem> = list.mapNotNull { getSocketGemFromName(it.stripColors()) } fun getSocketGemsFromItemStackLore(itemStack: ItemStack?): List<SocketGem> = getSocketGemsFromStringList(itemStack?.getLore() ?: emptyList()) fun doAllGemsHaveSameFamily(gems: List<SocketGem>): Boolean { if (gems.isEmpty()) { return true } val family = gems.first().family return gems.all { it.family.equals(family, ignoreCase = true) } } fun doAllGemsHaveSameLevel(gems: List<SocketGem>): Boolean { if (gems.isEmpty()) { return true } val level = gems.first().level return gems.all { it.level == level } } }
mit
e9f1aa8bb781f6e9ee8d6c8ae45b7a0e
41.007143
120
0.708893
4.365999
false
false
false
false
AndroidX/androidx
compose/ui/ui/benchmark/src/androidTest/java/androidx/compose/ui/benchmark/input/pointer/ComposeTapIntegrationBenchmark.kt
3
5661
/* * Copyright 2019 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.ui.benchmark.input.pointer import androidx.compose.foundation.gestures.detectTapGestures import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.requiredHeight import androidx.compose.foundation.text.BasicText import androidx.compose.runtime.Composable import androidx.compose.testutils.ComposeTestCase import androidx.compose.testutils.benchmark.ComposeBenchmarkRule import androidx.compose.testutils.doFramesUntilNoChangesPending import androidx.compose.ui.Modifier import androidx.compose.ui.input.pointer.pointerInput import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.unit.dp import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.filters.LargeTest import com.google.common.truth.Truth.assertThat import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith /** * Benchmark for simply tapping on an item in Compose. * * The intent is to measure the speed of all parts necessary for a normal tap starting from * [MotionEvent]s getting dispatched to a particular view. The test therefore includes hit * testing and dispatch. * * This is intended to be an equivalent counterpart to [AndroidTapIntegrationBenchmark]. * * The hierarchy is set up to look like: * rootView * -> Column * -> Text (with click listener) * -> Text (with click listener) * -> Text (with click listener) * -> ... * * MotionEvents are dispatched to rootView as ACTION_DOWN followed by ACTION_UP. The validity of * the test is verified inside the click listener with com.google.common.truth.Truth.assertThat * and by counting the clicks in the click listener and later verifying that they count is * sufficiently high. */ @LargeTest @RunWith(AndroidJUnit4::class) class ComposeTapIntegrationBenchmark { @get:Rule val benchmarkRule = ComposeBenchmarkRule() @Test fun clickOnLateItem() { // As items that are laid out last are hit tested first (so z order is respected), item // at 0 will be hit tested late. clickOnItem(0, "0") } // This test requires less hit testing so changes to dispatch will be tracked more by this test. @Test fun clickOnEarlyItemFyi() { // As items that are laid out last are hit tested first (so z order is respected), item // at NumItems - 1 will be hit tested early. val lastItem = NumItems - 1 clickOnItem(lastItem, "$lastItem") } private fun clickOnItem(item: Int, expectedLabel: String) { // half height of an item + top of the chosen item = middle of the chosen item val y = (ItemHeightPx / 2) + (item * ItemHeightPx) benchmarkRule.runBenchmarkFor({ ComposeTapTestCase() }) { doFramesUntilNoChangesPending() val case = getTestCase() case.expectedLabel = expectedLabel val rootView = getHostView() // Simple Events val down = MotionEvent( 0, android.view.MotionEvent.ACTION_DOWN, 1, 0, arrayOf(PointerProperties(0)), arrayOf(PointerCoords(0f, y)), rootView ) val up = MotionEvent( 10, android.view.MotionEvent.ACTION_UP, 1, 0, arrayOf(PointerProperties(0)), arrayOf(PointerCoords(0f, y)), rootView ) benchmarkRule.measureRepeated { rootView.dispatchTouchEvent(down) rootView.dispatchTouchEvent(up) case.expectedClickCount++ assertThat(case.actualClickCount).isEqualTo(case.expectedClickCount) } } } private class ComposeTapTestCase : ComposeTestCase { private var itemHeightDp = 0.dp // Is set to correct value during composition. var actualClickCount = 0 var expectedClickCount = 0 lateinit var expectedLabel: String @Composable override fun Content() { with(LocalDensity.current) { itemHeightDp = ItemHeightPx.toDp() } EmailList(NumItems) } @Composable fun EmailList(count: Int) { Column { repeat(count) { i -> Email("$i") } } } @Composable fun Email(label: String) { BasicText( text = label, modifier = Modifier .pointerInput(label) { detectTapGestures { assertThat(label).isEqualTo(expectedLabel) actualClickCount++ } } .fillMaxWidth() .requiredHeight(itemHeightDp) ) } } }
apache-2.0
c5bde76cc0e4c32e5d29e77c28a4a8fe
33.10241
100
0.632397
4.8509
false
true
false
false
exponent/exponent
packages/expo-image-picker/android/src/main/java/expo/modules/imagepicker/exporters/RawImageExporter.kt
2
1895
package expo.modules.imagepicker.exporters import android.content.ContentResolver import android.graphics.BitmapFactory import android.net.Uri import expo.modules.imagepicker.exporters.ImageExporter.Listener import org.apache.commons.io.IOUtils import java.io.ByteArrayOutputStream import java.io.File import java.io.FileOutputStream import java.io.IOException class RawImageExporter( private val contentResolver: ContentResolver, private val mBase64: Boolean ) : ImageExporter { override fun export(source: Uri, output: File, exporterListener: Listener) { val base64Stream = if (mBase64) ByteArrayOutputStream() else null base64Stream.use { try { copyImage(source, output, base64Stream) val options = BitmapFactory.Options().apply { inJustDecodeBounds = true } BitmapFactory.decodeFile(output.absolutePath, options) exporterListener.onResult(base64Stream, options.outWidth, options.outHeight) } catch (e: IOException) { exporterListener.onFailure(e) } } } /** * Copy the image file from `originalUri` to `file`, optionally saving it in * `out` if base64 is requested. * * @param originalUri uri to the file to copy the data from * @param file file to save the image to * @param out if not null, the stream to save the image to */ @Throws(IOException::class) private fun copyImage(originalUri: Uri, file: File, out: ByteArrayOutputStream?) { contentResolver.openInputStream(originalUri)?.use { input -> if (out != null) { IOUtils.copy(input, out) } if (originalUri.compareTo(Uri.fromFile(file)) != 0) { // do not copy file over the same file FileOutputStream(file).use { fos -> if (out != null) { fos.write(out.toByteArray()) } else { IOUtils.copy(input, fos) } } } } } }
bsd-3-clause
5fc89696fe98da39a15166c47e708695
31.118644
98
0.684433
4.229911
false
false
false
false
WillowChat/Kale
src/test/kotlin/chat/willow/kale/irc/message/rfc1459/PassMessageTests.kt
2
1147
package chat.willow.kale.irc.message.rfc1459 import chat.willow.kale.core.message.IrcMessage import org.junit.Assert.assertEquals import org.junit.Assert.assertNull import org.junit.Before import org.junit.Test class PassMessageTests { private lateinit var messageParser: PassMessage.Command.Parser private lateinit var messageSerialiser: PassMessage.Command.Serialiser @Before fun setUp() { messageParser = PassMessage.Command.Parser messageSerialiser = PassMessage.Command.Serialiser } @Test fun test_parse() { val message = messageParser.parse(IrcMessage(command = "PASS", parameters = listOf("password"))) assertEquals(message, PassMessage.Command(password = "password")) } @Test fun test_parse_tooFewParameters() { val message = messageParser.parse(IrcMessage(command = "PASS", parameters = listOf())) assertNull(message) } @Test fun test_serialise() { val message = messageSerialiser.serialise(PassMessage.Command(password = "password")) assertEquals(message, IrcMessage(command = "PASS", parameters = listOf("password"))) } }
isc
97f0ab3d52b09fb5912a062c4b53747d
30.027027
104
0.718396
4.533597
false
true
false
false
smmribeiro/intellij-community
platform/platform-impl/src/com/intellij/internal/ml/ResourcesModelMetadataReader.kt
9
1615
// 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.internal.ml open class ResourcesModelMetadataReader(protected val metadataHolder: Class<*>, private val featuresDirectory: String): ModelMetadataReader { override fun binaryFeatures(): String = resourceContent("binary.json") override fun floatFeatures(): String = resourceContent("float.json") override fun categoricalFeatures(): String = resourceContent("categorical.json") override fun allKnown(): String = resourceContent("all_features.json") override fun featureOrderDirect(): List<String> = resourceContent("features_order.txt").lines() override fun extractVersion(): String? { val versionFile = "version.txt" if (metadataHolder.classLoader.getResource("$featuresDirectory/$versionFile") != null) { return resourceContent(versionFile).trim() } val resource = metadataHolder.classLoader.getResource("$featuresDirectory/binary.json") ?: return null val result = resource.file.substringBeforeLast(".jar!", "").substringAfterLast("-", "") return if (result.isBlank()) null else result } private fun resourceContent(fileName: String): String { val resource = "$featuresDirectory/$fileName" val fileStream = metadataHolder.classLoader.getResourceAsStream(resource) ?: throw InconsistentMetadataException( "Metadata file not found: $resource. Resources holder: ${metadataHolder.name}") return fileStream.bufferedReader().use { it.readText() } } }
apache-2.0
2ef5237bba19d8b0904329d761398d5c
54.689655
141
0.734985
4.84985
false
false
false
false
siosio/intellij-community
plugins/kotlin/gradle/gradle-native/src/org/jetbrains/kotlin/ide/konan/KotlinNativeABICompatibilityChecker.kt
1
11113
// 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.ide.konan import com.intellij.ProjectTopics import com.intellij.notification.Notification import com.intellij.notification.NotificationType import com.intellij.openapi.Disposable import com.intellij.openapi.application.ModalityState import com.intellij.openapi.application.ReadAction.nonBlocking import com.intellij.openapi.project.Project import com.intellij.openapi.project.guessProjectDir import com.intellij.openapi.roots.ModuleRootEvent import com.intellij.openapi.roots.ModuleRootListener import com.intellij.openapi.startup.StartupActivity import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.Ref import com.intellij.openapi.util.text.StringUtilRt import com.intellij.util.PathUtilRt import com.intellij.util.concurrency.AppExecutorUtil import org.jetbrains.concurrency.CancellablePromise import org.jetbrains.kotlin.idea.caches.project.getModuleInfosFromIdeaModel import org.jetbrains.kotlin.idea.configuration.klib.KotlinNativeLibraryNameUtil.isGradleLibraryName import org.jetbrains.kotlin.idea.configuration.klib.KotlinNativeLibraryNameUtil.parseIDELibraryName import org.jetbrains.kotlin.idea.klib.KlibCompatibilityInfo.IncompatibleMetadata import org.jetbrains.kotlin.idea.util.application.getServiceSafe import org.jetbrains.kotlin.idea.util.application.isUnitTestMode import org.jetbrains.kotlin.idea.versions.UnsupportedAbiVersionNotificationPanelProvider import org.jetbrains.kotlin.idea.versions.bundledRuntimeVersion import org.jetbrains.kotlin.konan.library.KONAN_STDLIB_NAME /** TODO: merge [KotlinNativeABICompatibilityChecker] in the future with [UnsupportedAbiVersionNotificationPanelProvider], KT-34525 */ class KotlinNativeABICompatibilityChecker : StartupActivity { override fun runActivity(project: Project) { KotlinNativeABICompatibilityCheckerService.getInstance(project).runActivity() } } class KotlinNativeABICompatibilityCheckerService(private val project: Project): Disposable { fun runActivity() { project.messageBus.connect(this).subscribe(ProjectTopics.PROJECT_ROOTS, object : ModuleRootListener { override fun rootsChanged(event: ModuleRootEvent) { // run when project roots are changes, e.g. on project import validateKotlinNativeLibraries() } }) validateKotlinNativeLibraries() } private sealed class LibraryGroup(private val ordinal: Int) : Comparable<LibraryGroup> { override fun compareTo(other: LibraryGroup) = when { this == other -> 0 this is FromDistribution && other is FromDistribution -> kotlinVersion.compareTo(other.kotlinVersion) else -> ordinal.compareTo(other.ordinal) } data class FromDistribution(val kotlinVersion: String) : LibraryGroup(0) object ThirdParty : LibraryGroup(1) object User : LibraryGroup(2) } private val cachedIncompatibleLibraries = mutableSetOf<String>() internal fun validateKotlinNativeLibraries() { if (isUnitTestMode() || project.isDisposed) return val backgroundJob: Ref<CancellablePromise<*>> = Ref() val disposable = Disposable { backgroundJob.get()?.let(CancellablePromise<*>::cancel) } Disposer.register(this, disposable) backgroundJob.set( nonBlocking<List<Notification>> { val librariesToNotify = getLibrariesToNotifyAbout() prepareNotifications(librariesToNotify) } .finishOnUiThread(ModalityState.defaultModalityState()) { notifications -> notifications.forEach { it.notify(project) } } .expireWith(this) // cancel job when project is disposed .coalesceBy(this@KotlinNativeABICompatibilityCheckerService) // cancel previous job when new one is submitted .withDocumentsCommitted(project) .submit(AppExecutorUtil.getAppExecutorService()) .onProcessed { backgroundJob.set(null) Disposer.dispose(disposable) }) } private fun getLibrariesToNotifyAbout(): Map<String, NativeKlibLibraryInfo> { val incompatibleLibraries = getModuleInfosFromIdeaModel(project) .filterIsInstance<NativeKlibLibraryInfo>() .filter { !it.compatibilityInfo.isCompatible } .associateBy { it.libraryRoot } val newEntries = if (cachedIncompatibleLibraries.isNotEmpty()) incompatibleLibraries.filterKeys { it !in cachedIncompatibleLibraries } else incompatibleLibraries cachedIncompatibleLibraries.clear() cachedIncompatibleLibraries.addAll(incompatibleLibraries.keys) return newEntries } private fun prepareNotifications(librariesToNotify: Map<String, NativeKlibLibraryInfo>): List<Notification> { if (librariesToNotify.isEmpty()) return emptyList() val librariesByGroups = HashMap<Pair<LibraryGroup, Boolean>, MutableList<Pair<String, String>>>() librariesToNotify.forEach { (libraryRoot, libraryInfo) -> val isOldMetadata = (libraryInfo.compatibilityInfo as? IncompatibleMetadata)?.isOlder ?: true val (libraryName, libraryGroup) = parseIDELibraryName(libraryInfo) librariesByGroups.computeIfAbsent(libraryGroup to isOldMetadata) { mutableListOf() } += libraryName to libraryRoot } return librariesByGroups.keys.sortedWith( compareBy( { (libraryGroup, _) -> libraryGroup }, { (_, isOldMetadata) -> isOldMetadata } ) ).map { key -> val (libraryGroup, isOldMetadata) = key val libraries = librariesByGroups.getValue(key).sortedWith(compareBy(LIBRARY_NAME_COMPARATOR) { (libraryName, _) -> libraryName }) val message = when (libraryGroup) { is LibraryGroup.FromDistribution -> { val libraryNamesInOneLine = libraries .joinToString(limit = MAX_LIBRARY_NAMES_IN_ONE_LINE) { (libraryName, _) -> libraryName } val text = KotlinGradleNativeBundle.message( "error.incompatible.libraries", libraries.size, libraryGroup.kotlinVersion, libraryNamesInOneLine ) val explanation = when (isOldMetadata) { true -> KotlinGradleNativeBundle.message("error.incompatible.libraries.older") false -> KotlinGradleNativeBundle.message("error.incompatible.libraries.newer") } val recipe = KotlinGradleNativeBundle.message("error.incompatible.libraries.recipe", bundledRuntimeVersion()) "$text\n\n$explanation\n$recipe" } is LibraryGroup.ThirdParty -> { val text = when (isOldMetadata) { true -> KotlinGradleNativeBundle.message("error.incompatible.3p.libraries.older", libraries.size) false -> KotlinGradleNativeBundle.message("error.incompatible.3p.libraries.newer", libraries.size) } val librariesLineByLine = libraries.joinToString(separator = "\n") { (libraryName, _) -> libraryName } val recipe = KotlinGradleNativeBundle.message("error.incompatible.3p.libraries.recipe", bundledRuntimeVersion()) "$text\n$librariesLineByLine\n\n$recipe" } is LibraryGroup.User -> { val projectRoot = project.guessProjectDir()?.canonicalPath fun getLibraryTextToPrint(libraryNameAndRoot: Pair<String, String>): String { val (libraryName, libraryRoot) = libraryNameAndRoot val relativeRoot = projectRoot?.let { libraryRoot.substringAfter(projectRoot) .takeIf { it != libraryRoot } ?.trimStart('/', '\\') ?.let { "${'$'}project/$it" } } ?: libraryRoot return KotlinGradleNativeBundle.message("library.name.0.at.1.relative.root", libraryName, relativeRoot) } val text = when (isOldMetadata) { true -> KotlinGradleNativeBundle.message("error.incompatible.user.libraries.older", libraries.size) false -> KotlinGradleNativeBundle.message("error.incompatible.user.libraries.newer", libraries.size) } val librariesLineByLine = libraries.joinToString(separator = "\n", transform = ::getLibraryTextToPrint) val recipe = KotlinGradleNativeBundle.message("error.incompatible.user.libraries.recipe", bundledRuntimeVersion()) "$text\n$librariesLineByLine\n\n$recipe" } } Notification( NOTIFICATION_GROUP_ID, NOTIFICATION_TITLE, StringUtilRt.convertLineSeparators(message, "<br/>"), NotificationType.ERROR ) } } // returns pair of library name and library group private fun parseIDELibraryName(libraryInfo: NativeKlibLibraryInfo): Pair<String, LibraryGroup> { val ideLibraryName = libraryInfo.library.name?.takeIf(String::isNotEmpty) if (ideLibraryName != null) { parseIDELibraryName(ideLibraryName)?.let { (kotlinVersion, libraryName) -> return libraryName to LibraryGroup.FromDistribution(kotlinVersion) } if (isGradleLibraryName(ideLibraryName)) return ideLibraryName to LibraryGroup.ThirdParty } return (ideLibraryName ?: PathUtilRt.getFileName(libraryInfo.libraryRoot)) to LibraryGroup.User } override fun dispose() { } companion object { private val LIBRARY_NAME_COMPARATOR = Comparator<String> { libraryName1, libraryName2 -> when { libraryName1 == libraryName2 -> 0 libraryName1 == KONAN_STDLIB_NAME -> -1 // stdlib must go the first libraryName2 == KONAN_STDLIB_NAME -> 1 else -> libraryName1.compareTo(libraryName2) } } private const val MAX_LIBRARY_NAMES_IN_ONE_LINE = 5 private val NOTIFICATION_TITLE get() = KotlinGradleNativeBundle.message("error.incompatible.libraries.title") private const val NOTIFICATION_GROUP_ID = "Incompatible Kotlin/Native libraries" fun getInstance(project: Project): KotlinNativeABICompatibilityCheckerService = project.getServiceSafe() } }
apache-2.0
126bea648c325a272ac9890683d96f2a
47.528384
158
0.654279
5.458251
false
false
false
false
rei-m/HBFav_material
app/src/main/kotlin/me/rei_m/hbfavmaterial/infra/network/response/EntryRssItemXml.kt
1
1567
/* * Copyright (c) 2017. Rei Matsushita * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See * the License for the specific language governing permissions and limitations under the License. */ package me.rei_m.hbfavmaterial.infra.network.response import org.simpleframework.xml.Element import org.simpleframework.xml.Path import org.simpleframework.xml.Root @Root(name = "item", strict = false) class EntryRssItemXml { @set:Element @get:Element var title: String = "" @set:Element @get:Element var link: String = "" @set:Element(required = false) @get:Element(required = false) var description: String = "" @Path("dc/subject") @set:Element(required = false) @get:Element(required = false) var subject: String = "" @Path("dc/date") @set:Element(name = "date") @get:Element(name = "date") var dateString: String = "" @Path("hatena/bookmarkcount") @set:Element(name = "bookmarkcount") @get:Element(name = "bookmarkcount") var bookmarkCount: Int = 0 @Path("content/encoded") @set:Element(name = "encoded") @get:Element(name = "encoded") var content: String = "" }
apache-2.0
8c224aaafeb8008e87ca6bd731a5e27a
28.018519
112
0.685386
3.775904
false
false
false
false
feelfreelinux/WykopMobilny
app/src/main/kotlin/io/github/feelfreelinux/wykopmobilny/ui/modules/Navigator.kt
1
4899
package io.github.feelfreelinux.wykopmobilny.ui.modules import android.app.Activity import android.content.Intent import io.github.feelfreelinux.wykopmobilny.api.ENTRY_COMMENT_REPORT_URL import io.github.feelfreelinux.wykopmobilny.api.ENTRY_REPORT_URL import io.github.feelfreelinux.wykopmobilny.models.dataclass.Link import io.github.feelfreelinux.wykopmobilny.ui.modules.input.BaseInputActivity import io.github.feelfreelinux.wykopmobilny.ui.modules.input.entry.add.AddEntryActivity import io.github.feelfreelinux.wykopmobilny.ui.modules.input.entry.comment.EditEntryCommentActivity import io.github.feelfreelinux.wykopmobilny.ui.modules.input.entry.edit.EditEntryActivity import io.github.feelfreelinux.wykopmobilny.ui.modules.links.linkdetails.LinkDetailsActivity import io.github.feelfreelinux.wykopmobilny.ui.modules.loginscreen.LoginScreenActivity import io.github.feelfreelinux.wykopmobilny.ui.modules.mainnavigation.MainNavigationActivity import io.github.feelfreelinux.wykopmobilny.ui.modules.mikroblog.entry.EntryActivity import io.github.feelfreelinux.wykopmobilny.ui.modules.photoview.PhotoViewActivity import io.github.feelfreelinux.wykopmobilny.ui.modules.pm.conversation.ConversationActivity import io.github.feelfreelinux.wykopmobilny.ui.modules.settings.SettingsActivity import io.github.feelfreelinux.wykopmobilny.ui.modules.tag.TagActivity import io.github.feelfreelinux.wykopmobilny.utils.openBrowser interface NavigatorApi { fun openMainActivity(context: Activity, targetFragment: String? = null) fun openEntryDetailsActivity(context: Activity, entryId: Int, isRevealed: Boolean) fun openTagActivity(context: Activity, tag: String) fun openConversationListActivity(context: Activity, user: String) fun openPhotoViewActivity(context: Activity, url: String) fun openSettingsActivity(context: Activity) fun openLoginScreen(context: Activity, requestCode: Int) fun openAddEntryActivity(context: Activity, receiver: String? = null, extraBody: String? = null) fun openEditEntryActivity(context: Activity, body: String, entryId: Int) fun openEditEntryCommentActivity(context: Activity, body: String, entryId: Int, commentId: Int) fun openBrowser(context: Activity, url: String) fun openReportEntryScreen(context: Activity, entryId: Int) fun openReportEntryCommentScreen(context: Activity, entryCommentId: Int) fun openLinkDetailsActivity(context: Activity, link: Link) } class Navigator : NavigatorApi { override fun openMainActivity(context: Activity, targetFragment: String?) { context.startActivity(MainNavigationActivity.getIntent(context, targetFragment) .apply { addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK) }) } override fun openEntryDetailsActivity(context: Activity, entryId: Int, isRevealed: Boolean) = context.startActivity(EntryActivity.createIntent(context, entryId, null, isRevealed)) override fun openTagActivity(context: Activity, tag: String) = context.startActivity(TagActivity.createIntent(context, tag)) override fun openConversationListActivity(context: Activity, user: String) = context.startActivity(ConversationActivity.createIntent(context, user)) override fun openPhotoViewActivity(context: Activity, url: String) = context.startActivity(PhotoViewActivity.createIntent(context, url)) override fun openSettingsActivity(context: Activity) = context.startActivity(SettingsActivity.createIntent(context)) override fun openLoginScreen(context: Activity, requestCode: Int) = context.startActivityForResult(LoginScreenActivity.createIntent(context), requestCode) override fun openAddEntryActivity(context: Activity, receiver: String?, extraBody: String?) = context.startActivity(AddEntryActivity.createIntent(context, receiver, extraBody)) override fun openEditEntryActivity(context: Activity, body: String, entryId: Int) = context.startActivityForResult(EditEntryActivity.createIntent(context, body, entryId), BaseInputActivity.REQUEST_CODE) override fun openEditEntryCommentActivity(context: Activity, body: String, entryId: Int, commentId: Int) = context.startActivityForResult(EditEntryCommentActivity.createIntent(context, body, entryId, commentId), BaseInputActivity.REQUEST_CODE) override fun openBrowser(context: Activity, url: String) = context.openBrowser(url) override fun openReportEntryScreen(context: Activity, entryId: Int) = context.openBrowser(ENTRY_REPORT_URL + entryId) override fun openReportEntryCommentScreen(context: Activity, entryCommentId: Int) = context.openBrowser(ENTRY_COMMENT_REPORT_URL + entryCommentId) override fun openLinkDetailsActivity(context: Activity, link: Link) = context.startActivity(LinkDetailsActivity.createIntent(context, link)) }
mit
8d9e49de36e0b1e41279078f076cdf94
57.333333
144
0.802613
4.692529
false
false
false
false
ZhangQinglian/dcapp
src/main/kotlin/com/zqlite/android/diycode/device/view/userdetail/UserDetailActivity.kt
1
2024
/* * Copyright 2017 zhangqinglian * * 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.zqlite.android.diycode.device.view.userdetail import com.zqlite.android.diycode.R import com.zqlite.android.diycode.device.view.BaseActivity import com.zqlite.android.diycode.device.view.custom.DecorViewProxy import kotlinx.android.synthetic.main.activity_user_detail.* /** * Created by scott on 2017/8/14. */ class UserDetailActivity:BaseActivity(){ private var mPresenter:UserDetailContract.Presenter? = null private var mFragment:UserDetailFragment? = null override fun getLayoutId(): Int { return R.layout.activity_user_detail } override fun initView() { //action bar setSupportActionBar(toolbar) supportActionBar!!.setTitle(R.string.user_detail) toolbar.setNavigationIcon(R.drawable.ic_toolbar_back) toolbar.setNavigationOnClickListener({ finish() }) //slide DecorViewProxy().bind(this) //add fragment mFragment = UserDetailFragment.getInstance(null) mPresenter = UserDetailPresenter(mFragment!!) addFragment(mFragment!!,R.id.user_detail_container) } override fun initData() { val extra = intent.extras if(extra != null){ val login :String= extra[kUserLoiginKey] as String mPresenter!!.loadUser(login) } } companion object { val kUserLoiginKey = "login" } }
apache-2.0
0b819637c8169ca8e81d4be54c73e966
29.681818
78
0.682806
4.390456
false
false
false
false
androidx/androidx
compose/integration-tests/docs-snippets/src/main/java/androidx/compose/integration/docs/state/State.kt
3
12543
/* * 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. */ // Ignore lint warnings in documentation snippets @file:Suppress("unused", "ControlFlowWithEmptyBody", "UNUSED_PARAMETER", "UNUSED_VARIABLE") package androidx.compose.integration.docs.state import android.content.res.Resources import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.LazyListState import androidx.compose.foundation.lazy.items import androidx.compose.material.Button import androidx.compose.material.MaterialTheme import androidx.compose.material.OutlinedTextField import androidx.compose.material.Scaffold import androidx.compose.material.ScaffoldState import androidx.compose.material.Text import androidx.compose.material.rememberScaffoldState import androidx.compose.runtime.Composable import androidx.compose.runtime.MutableState import androidx.compose.runtime.State import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.saveable.listSaver import androidx.compose.runtime.saveable.mapSaver import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.unit.dp import androidx.lifecycle.SavedStateHandle import androidx.lifecycle.ViewModel import androidx.lifecycle.viewmodel.compose.viewModel import androidx.navigation.NavHostController import androidx.navigation.compose.NavHost import androidx.navigation.compose.rememberNavController import kotlinx.coroutines.launch /** * This file lets DevRel track changes to snippets present in * https://developer.android.com/jetpack/compose/state * * No action required if it's modified. */ private object StateSnippet1 { @Composable fun HelloContent() { Column(modifier = Modifier.padding(16.dp)) { Text( text = "Hello!", modifier = Modifier.padding(bottom = 8.dp), style = MaterialTheme.typography.h5 ) OutlinedTextField( value = "", onValueChange = { }, label = { Text("Name") } ) } } } private object StateSnippet2 { /* * MutableState is part of the API, so StateSnippet2 can't have the exact code * for the published documentation. Instead, use the following commented code * in the doc. If FakeState<T> changes, update the commented code accordingly. * interface MutableState<T> : State<T> { override var value: T } */ interface FakeState<T> : State<T> { override var value: T } interface FakeMutableState<T> : MutableState<String> } private object StateSnippet3 { @Composable fun HelloContent() { Column(modifier = Modifier.padding(16.dp)) { var name by remember { mutableStateOf("") } if (name.isNotEmpty()) { Text( text = "Hello, $name!", modifier = Modifier.padding(bottom = 8.dp), style = MaterialTheme.typography.h5 ) } OutlinedTextField( value = name, onValueChange = { name = it }, label = { Text("Name") } ) } } } private object StateSnippet4 { @Composable fun HelloScreen() { var name by rememberSaveable { mutableStateOf("") } HelloContent(name = name, onNameChange = { name = it }) } @Composable fun HelloContent(name: String, onNameChange: (String) -> Unit) { Column(modifier = Modifier.padding(16.dp)) { Text( text = "Hello, $name", modifier = Modifier.padding(bottom = 8.dp), style = MaterialTheme.typography.h5 ) OutlinedTextField( value = name, onValueChange = onNameChange, label = { Text("Name") } ) } } } private object StateSnippet5 { @Parcelize data class City(val name: String, val country: String) : Parcelable @Composable fun CityScreen() { var selectedCity = rememberSaveable { mutableStateOf(City("Madrid", "Spain")) } } } private object StateSnippet6 { data class City(val name: String, val country: String) val CitySaver = run { val nameKey = "Name" val countryKey = "Country" mapSaver( save = { mapOf(nameKey to it.name, countryKey to it.country) }, restore = { City(it[nameKey] as String, it[countryKey] as String) } ) } @Composable fun CityScreen() { var selectedCity = rememberSaveable(stateSaver = CitySaver) { mutableStateOf(City("Madrid", "Spain")) } } } @Composable private fun StateSnippets7() { data class City(val name: String, val country: String) val CitySaver = listSaver<City, Any>( save = { listOf(it.name, it.country) }, restore = { City(it[0] as String, it[1] as String) } ) @Composable fun CityScreen() { var selectedCity = rememberSaveable(stateSaver = CitySaver) { mutableStateOf(City("Madrid", "Spain")) } } } @Composable private fun StateSnippets8() { @Composable fun MyApp() { MyTheme { val scaffoldState = rememberScaffoldState() val coroutineScope = rememberCoroutineScope() Scaffold(scaffoldState = scaffoldState) { innerPadding -> MyContent( showSnackbar = { message -> coroutineScope.launch { scaffoldState.snackbarHostState.showSnackbar(message) } }, modifier = Modifier.padding(innerPadding) ) } } } } @Composable private fun StateSnippets9() { // Plain class that manages App's UI logic and UI elements' state class MyAppState( val scaffoldState: ScaffoldState, val navController: NavHostController, private val resources: Resources, /* ... */ ) { val bottomBarTabs = /* State */ // DO NOT COPY IN DAC Unit // Logic to decide when to show the bottom bar val shouldShowBottomBar: Boolean get() = /* ... */ // DO NOT COPY IN DAC false // Navigation logic, which is a type of UI logic fun navigateToBottomBarRoute(route: String) { /* ... */ } // Show snackbar using Resources fun showSnackbar(message: String) { /* ... */ } } @Composable fun rememberMyAppState( scaffoldState: ScaffoldState = rememberScaffoldState(), navController: NavHostController = rememberNavController(), resources: Resources = LocalContext.current.resources, /* ... */ ) = remember(scaffoldState, navController, resources, /* ... */) { MyAppState(scaffoldState, navController, resources, /* ... */) } } @Composable private fun StateSnippets10() { @Composable fun MyApp() { MyTheme { val myAppState = rememberMyAppState() Scaffold( scaffoldState = myAppState.scaffoldState, bottomBar = { if (myAppState.shouldShowBottomBar) { BottomBar( tabs = myAppState.bottomBarTabs, navigateToRoute = { myAppState.navigateToBottomBarRoute(it) } ) } } ) { innerPadding -> NavHost( navController = myAppState.navController, startDestination = "initial", modifier = Modifier.padding(innerPadding) ) { /* ... */ } } } } } @Composable private fun StateSnippets11() { data class ExampleUiState( val dataToDisplayOnScreen: List<Example> = emptyList(), val userMessages: List<Message> = emptyList(), val loading: Boolean = false ) class ExampleViewModel( private val repository: MyRepository, private val savedState: SavedStateHandle ) : ViewModel() { var uiState by mutableStateOf(ExampleUiState()) private set // Business logic fun somethingRelatedToBusinessLogic() { /* ... */ } } @Composable fun ExampleScreen(viewModel: ExampleViewModel = viewModel()) { val uiState = viewModel.uiState /* ... */ ExampleReusableComponent( someData = uiState.dataToDisplayOnScreen, onDoSomething = { viewModel.somethingRelatedToBusinessLogic() } ) } @Composable fun ExampleReusableComponent(someData: Any, onDoSomething: () -> Unit) { /* ... */ Button(onClick = onDoSomething) { Text("Do something") } } } @Composable private fun StateSnippets12() { class ExampleState( val lazyListState: LazyListState, private val resources: Resources, private val expandedItems: List<Item> = emptyList() ) { fun isExpandedItem(item: Item): Boolean = TODO() /* ... */ } @Composable fun rememberExampleState(/* ... */): ExampleState { TODO() } @Composable fun ExampleScreen(viewModel: ExampleViewModel = viewModel()) { val uiState = viewModel.uiState val exampleState = rememberExampleState() LazyColumn(state = exampleState.lazyListState) { items(uiState.dataToDisplayOnScreen) { item -> if (exampleState.isExpandedItem(item)) { /* ... */ } /* ... */ } } } } /* * Fakes needed for snippets to build: */ private object binding { object helloText { var text = "" } object textInput { fun doAfterTextChanged(function: () -> Unit) {} } } @Composable private fun MyTheme(content: @Composable () -> Unit) {} @Composable private fun MyContent(showSnackbar: (String) -> Unit, modifier: Modifier = Modifier) {} @Composable private fun BottomBar(tabs: Unit, navigateToRoute: (String) -> Unit) {} @Composable private fun rememberMyAppState( scaffoldState: ScaffoldState = rememberScaffoldState(), navController: NavHostController = rememberNavController(), resources: Resources = LocalContext.current.resources ) = remember(scaffoldState, navController, resources) { MyAppState(scaffoldState, navController, resources) } private class MyAppState( val scaffoldState: ScaffoldState, val navController: NavHostController, private val resources: Resources, ) { val shouldShowBottomBar: Boolean = false val bottomBarTabs = Unit fun navigateToBottomBarRoute(route: String) {} } /** * Add fake Parcelize and Parcelable to avoid adding AndroidX wide dependency on * kotlin-parcelize just for snippets */ private annotation class Parcelize private interface Parcelable private class Example private class Item private class Message private class MyRepository @Composable private fun ExampleReusableComponent(someData: List<Example>, onDoSomething: () -> Unit) {} private class ExampleViewModel : ViewModel() { val uiState = ExampleUiState() } private data class ExampleUiState( val dataToDisplayOnScreen: List<Item> = emptyList(), val userMessages: List<Message> = emptyList(), val loading: Boolean = false )
apache-2.0
87cdb87d7de55ef0ad5ca78ae2504a2b
28.866667
91
0.623934
4.824231
false
false
false
false
androidx/androidx
emoji2/emoji2-benchmark/src/androidTest/java/androidx/emoji2/benchmark/text/EmojiStrings.kt
3
1862
/* * 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.emoji2.benchmark.text import android.content.Context import androidx.test.core.app.ApplicationProvider import java.io.BufferedReader import java.io.InputStreamReader const val POLARBEAR = "\uD83D\uDC3B\u200D❄️" private val loadedEmojiStrings: List<String> by lazy { loadEmojiStrings() } fun emojisString(size: Int) = emojisList(size).joinToString("") fun emojisList(size: Int) = loadedEmojiStrings.take(size) fun loadEmojiStrings(): List<String> { val context = ApplicationProvider.getApplicationContext<Context>() val inputStream = context.assets.open("emojis.txt") val result = mutableListOf<String>() return inputStream.use { val reader = BufferedReader(InputStreamReader(inputStream)) val stringBuilder = StringBuilder() reader.forEachLine { val line = it.trim() if (line.isEmpty() || line.startsWith("#")) return@forEachLine stringBuilder.setLength(0) line.split(" ") .toTypedArray() .map { intVal -> Character.toChars(intVal.toInt(16)) } .forEach { charArray -> stringBuilder.append(charArray) } result.add(stringBuilder.toString()) } result } }
apache-2.0
c77d51b0685682d8ab38248e2ef7bfe1
36.18
75
0.695371
4.371765
false
false
false
false
androidx/androidx
compose/ui/ui/src/commonMain/kotlin/androidx/compose/ui/layout/LookaheadScope.kt
3
1793
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.ui.layout import androidx.compose.runtime.snapshots.MutableSnapshot import androidx.compose.runtime.snapshots.Snapshot import androidx.compose.ui.node.LayoutNode /** * [LookaheadScope] manages a disposable snapshot. Lookahead measure pass runs in this * snapshot, which gets disposed after lookahead such that lookahead pass does not result * in any state changes to the global snapshot. */ internal class LookaheadScope(val root: LayoutNode) { private var disposableSnapshot: MutableSnapshot? = null /** * This method runs the [block] in a snapshot that will be disposed. It is used * in the lookahead pass, where no state changes are intended to be applied to the global * snapshot. */ fun <T> withDisposableSnapshot(block: () -> T): T { check(disposableSnapshot == null) { "Disposable snapshot is already active" } return Snapshot.takeMutableSnapshot().let { disposableSnapshot = it try { it.enter(block) } finally { it.dispose() disposableSnapshot = null } } } }
apache-2.0
bd0182577aa110c1f6ffc43b09f4641c
34.156863
93
0.685443
4.585678
false
false
false
false
nrizzio/Signal-Android
app/src/main/java/org/thoughtcrime/securesms/conversation/ConversationItemSelection.kt
1
3506
package org.thoughtcrime.securesms.conversation import android.graphics.Bitmap import android.graphics.Path import android.view.ViewGroup import androidx.core.graphics.applyCanvas import androidx.core.graphics.createBitmap import androidx.core.graphics.withClip import androidx.core.graphics.withTranslation import androidx.core.view.children import androidx.recyclerview.widget.RecyclerView import org.signal.core.util.DimensionUnit import org.thoughtcrime.securesms.database.model.MessageRecord import org.thoughtcrime.securesms.util.hasNoBubble object ConversationItemSelection { @JvmStatic fun snapshotView( conversationItem: ConversationItem, list: RecyclerView, messageRecord: MessageRecord, videoBitmap: Bitmap?, ): Bitmap { val isOutgoing = messageRecord.isOutgoing val hasNoBubble = messageRecord.hasNoBubble(conversationItem.context) return snapshotMessage( conversationItem = conversationItem, list = list, videoBitmap = videoBitmap, drawConversationItem = !isOutgoing || hasNoBubble, hasReaction = messageRecord.reactions.isNotEmpty(), ) } private fun snapshotMessage( conversationItem: ConversationItem, list: RecyclerView, videoBitmap: Bitmap?, drawConversationItem: Boolean, hasReaction: Boolean, ): Bitmap { val bodyBubble = conversationItem.bodyBubble val reactionsView = conversationItem.reactionsView val originalScale = bodyBubble.scaleX bodyBubble.scaleX = 1.0f bodyBubble.scaleY = 1.0f val projections = conversationItem.getSnapshotProjections(list, false) val path = Path() val xTranslation = -conversationItem.x - bodyBubble.x val yTranslation = -conversationItem.y - bodyBubble.y val mp4Projection = conversationItem.getGiphyMp4PlayableProjection(list) var scaledVideoBitmap = videoBitmap if (videoBitmap != null) { scaledVideoBitmap = Bitmap.createScaledBitmap( videoBitmap, (videoBitmap.width / originalScale).toInt(), (videoBitmap.height / originalScale).toInt(), true ) mp4Projection.translateX(xTranslation) mp4Projection.translateY(yTranslation) mp4Projection.applyToPath(path) } projections.use { it.forEach { p -> p.translateX(xTranslation) p.translateY(yTranslation) p.applyToPath(path) } } conversationItem.destroyAllDrawingCaches() var bitmapHeight = bodyBubble.height if (hasReaction) { bitmapHeight += (reactionsView.height - DimensionUnit.DP.toPixels(4f)).toInt() } return createBitmap(bodyBubble.width, bitmapHeight).applyCanvas { if (drawConversationItem) { bodyBubble.draw(this) } withClip(path) { withTranslation(x = xTranslation, y = yTranslation) { list.draw(this) if (scaledVideoBitmap != null) { drawBitmap(scaledVideoBitmap, mp4Projection.x - xTranslation, mp4Projection.y - yTranslation, null) } } } withTranslation( x = reactionsView.x - bodyBubble.x, y = reactionsView.y - bodyBubble.y ) { reactionsView.draw(this) } }.also { mp4Projection.release() bodyBubble.scaleX = originalScale bodyBubble.scaleY = originalScale } } } private fun ViewGroup.destroyAllDrawingCaches() { children.forEach { it.destroyDrawingCache() if (it is ViewGroup) { it.destroyAllDrawingCaches() } } }
gpl-3.0
1d66584369b14f4f8e4a637ce8604fd8
27.274194
111
0.705077
4.449239
false
false
false
false
GunoH/intellij-community
plugins/groovy/src/org/jetbrains/plugins/groovy/codeInsight/template/postfix/GroovyPostfixTemplateUtils.kt
2
5354
// 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.groovy.codeInsight.template.postfix import com.intellij.codeInsight.template.postfix.templates.PostfixTemplateExpressionSelectorBase import com.intellij.codeInsight.template.postfix.templates.PostfixTemplatePsiInfo import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.editor.Document import com.intellij.openapi.util.Condition import com.intellij.openapi.util.Conditions import com.intellij.psi.* import com.intellij.psi.util.InheritanceUtil import com.intellij.psi.util.PsiTreeUtil import com.siyeh.ig.psiutils.BoolUtils import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElementFactory import org.jetbrains.plugins.groovy.lang.psi.api.GrFunctionalExpression import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.* import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.path.GrMethodCallExpression import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod import org.jetbrains.plugins.groovy.lang.psi.impl.GrMapType import org.jetbrains.plugins.groovy.lang.typing.ListLiteralType import kotlin.math.max object GroovyPostfixTemplateUtils { val LOG: Logger = Logger.getInstance(GroovyPostfixTemplateUtils::class.java) val GROOVY_PSI_INFO: PostfixTemplatePsiInfo = object : PostfixTemplatePsiInfo() { override fun createExpression(context: PsiElement, prefix: String, suffix: String): PsiElement { val factory = GroovyPsiElementFactory.getInstance(context.project) return factory.createExpressionFromText(prefix + context.text + suffix, context) } override fun getNegatedExpression(element: PsiElement): GrExpression { LOG.assertTrue(element is GrExpression) val negatedExpressionText = BoolUtils.getNegatedExpressionText(element as PsiExpression) return GroovyPsiElementFactory.getInstance(element.getProject()).createExpressionFromText(negatedExpressionText, element) } } private fun booleanTypeCondition(expr: GrExpression): Boolean { val type = expr.type return type == null || type == PsiType.BOOLEAN || type.equalsToText(CommonClassNames.JAVA_LANG_BOOLEAN) } private fun nullableTypeCondition(expr: GrExpression): Boolean = expr.type !is PsiPrimitiveType private fun getGenericExpressionSelector(onlyLast: Boolean, condition: Condition<in GrExpression>) = object : PostfixTemplateExpressionSelectorBase({ it is GrExpression && condition.value(it) }) { override fun getNonFilteredExpressions(context: PsiElement, document: Document, offset: Int): List<PsiElement> { val actualOffset = max(offset - 1, 0) val file = PsiDocumentManager.getInstance(context.project).getPsiFile(document) ?: return emptyList() var currentElement: PsiElement? = PsiTreeUtil.findElementOfClassAtOffset(file, actualOffset, GrExpression::class.java, false) val expressions = mutableListOf<GrExpression>() val offsetFilter = getBorderOffsetFilter(offset) while (currentElement is GrExpression && offsetFilter.value(currentElement)) { expressions.add(currentElement) currentElement = currentElement.parent } if (onlyLast) { return listOfNotNull(expressions.lastOrNull()) } else { return expressions.toList() } } } fun getExpressionSelector() = getGenericExpressionSelector(false, Conditions.alwaysTrue()) fun getTopExpressionSelector() = getGenericExpressionSelector(true, Conditions.alwaysTrue()) fun getNullableTopExpressionSelector() = getGenericExpressionSelector(true, this::nullableTypeCondition) fun getNullableExpressionSelector() = getGenericExpressionSelector(false, this::nullableTypeCondition) fun getMethodLocalTopExpressionSelector() = getGenericExpressionSelector(true) { element -> PsiTreeUtil.getParentOfType(element, GrMethod::class.java, GrFunctionalExpression::class.java) != null } fun getTopBooleanExpressionSelector() = getGenericExpressionSelector(true, this::booleanTypeCondition) fun getBooleanExpressionSelector() = getGenericExpressionSelector(false, this::booleanTypeCondition) fun getSubclassExpressionSelector(baseClassFqn: String) = getGenericExpressionSelector(true) { expr -> val type = expr.type type == null || InheritanceUtil.isInheritor(type, baseClassFqn) } fun getIterableExpressionSelector() = getGenericExpressionSelector(true) { expr -> val type = expr.type type == null || // unknown type may be actually iterable in runtime type is GrMapType || type is ListLiteralType || type is PsiArrayType || InheritanceUtil.isInheritor(type, CommonClassNames.JAVA_LANG_ITERABLE) } fun getConstructorSelector() = getGenericExpressionSelector(false) { expr -> expr is GrMethodCallExpression || (expr is GrReferenceExpression && expr.resolve() is PsiClass) } fun shouldBeParenthesized(expr: GrExpression): Boolean = when (expr) { is GrOperatorExpression -> true is GrConditionalExpression -> true is GrSafeCastExpression -> true is GrMethodCallExpression -> expr.argumentList.leftParen == null && expr.argumentList.rightParen == null else -> false } }
apache-2.0
f535a2853efa1f958bd583a39e12b8db
45.973684
131
0.77232
4.994403
false
false
false
false
siosio/intellij-community
plugins/kotlin/refIndex/src/org/jetbrains/kotlin/idea/search/refIndex/KotlinCompilerReferenceIndexService.kt
1
17182
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.search.refIndex import com.intellij.compiler.CompilerReferenceService import com.intellij.compiler.backwardRefs.CompilerReferenceServiceBase import com.intellij.compiler.backwardRefs.DirtyScopeHolder import com.intellij.compiler.server.BuildManager import com.intellij.compiler.server.BuildManagerListener import com.intellij.compiler.server.CustomBuilderMessageHandler import com.intellij.compiler.server.PortableCachesLoadListener import com.intellij.ide.highlighter.JavaFileType import com.intellij.lang.injection.InjectedLanguageManager import com.intellij.lang.jvm.JvmModifier import com.intellij.openapi.Disposable import com.intellij.openapi.compiler.CompilerManager import com.intellij.openapi.components.Service import com.intellij.openapi.components.service import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.fileEditor.FileDocumentManager import com.intellij.openapi.fileTypes.FileType import com.intellij.openapi.module.Module import com.intellij.openapi.module.ModuleManager import com.intellij.openapi.options.advanced.AdvancedSettings import com.intellij.openapi.project.Project import com.intellij.openapi.roots.ProjectRootManager import com.intellij.openapi.startup.StartupActivity import com.intellij.openapi.util.ModificationTracker import com.intellij.openapi.vfs.VfsUtil import com.intellij.openapi.vfs.VirtualFile import com.intellij.psi.* import com.intellij.psi.search.GlobalSearchScope import com.intellij.psi.search.ProjectScope import com.intellij.psi.util.CachedValueProvider import com.intellij.psi.util.CachedValuesManager import com.intellij.psi.util.PsiModificationTracker import com.intellij.psi.util.PsiUtilCore import com.intellij.util.Processor import com.intellij.util.messages.MessageBusConnection import org.jetbrains.annotations.TestOnly import org.jetbrains.jps.builders.impl.BuildDataPathsImpl import org.jetbrains.kotlin.asJava.unwrapped import org.jetbrains.kotlin.config.SettingConstants import org.jetbrains.kotlin.idea.KotlinFileType import org.jetbrains.kotlin.idea.core.isOverridable import org.jetbrains.kotlin.idea.refactoring.fqName.getKotlinFqName import org.jetbrains.kotlin.idea.search.declarationsSearch.HierarchySearchRequest import org.jetbrains.kotlin.idea.search.declarationsSearch.searchInheritors import org.jetbrains.kotlin.idea.search.not import org.jetbrains.kotlin.idea.search.restrictToKotlinSources import org.jetbrains.kotlin.idea.util.application.isUnitTestMode import org.jetbrains.kotlin.idea.util.application.runReadAction import org.jetbrains.kotlin.incremental.LookupStorage import org.jetbrains.kotlin.incremental.LookupSymbol import org.jetbrains.kotlin.incremental.storage.RelativeFileToPathConverter import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.containingClass import org.jetbrains.kotlin.psi.psiUtil.containingClassOrObject import org.jetbrains.kotlin.psi.psiUtil.parameterIndex import org.jetbrains.kotlin.utils.addToStdlib.safeAs import java.io.File import java.nio.file.Path import java.util.* import java.util.concurrent.atomic.LongAdder import java.util.concurrent.locks.ReentrantReadWriteLock import kotlin.concurrent.read import kotlin.concurrent.write import kotlin.io.path.Path import kotlin.io.path.exists import kotlin.io.path.isDirectory import kotlin.io.path.listDirectoryEntries /** * Based on [com.intellij.compiler.backwardRefs.CompilerReferenceServiceBase] and [com.intellij.compiler.backwardRefs.CompilerReferenceServiceImpl] */ @Service(Service.Level.PROJECT) class KotlinCompilerReferenceIndexService(val project: Project) : Disposable, ModificationTracker { private var storage: LookupStorage? = null private var activeBuildCount = 0 private val compilationCounter = LongAdder() private val projectFileIndex = ProjectRootManager.getInstance(project).fileIndex private val supportedFileTypes: Set<FileType> = setOf(KotlinFileType.INSTANCE, JavaFileType.INSTANCE) private val dirtyScopeHolder = DirtyScopeHolder( project, supportedFileTypes, projectFileIndex, this, this, FileDocumentManager.getInstance(), PsiDocumentManager.getInstance(project), ) { connect: MessageBusConnection, mutableSet: MutableSet<String> -> connect.subscribe( CustomBuilderMessageHandler.TOPIC, CustomBuilderMessageHandler { builderId, _, messageText -> if (builderId == SettingConstants.KOTLIN_COMPILER_REFERENCE_INDEX_BUILDER_ID) { mutableSet += messageText } }, ) } private val lock = ReentrantReadWriteLock() private fun <T> withWriteLock(action: () -> T): T = lock.write(action) private fun <T> withReadLock(action: () -> T): T = lock.read(action) private fun <T> tryWithReadLock(action: () -> T): T? = lock.readLock().run { if (tryLock()) try { action() } finally { unlock() } else null } private fun withDirtyScopeUnderWriteLock(updater: DirtyScopeHolder.() -> Unit): Unit = withWriteLock { dirtyScopeHolder.updater() } private fun <T> withDirtyScopeUnderReadLock(readAction: DirtyScopeHolder.() -> T): T = withReadLock { dirtyScopeHolder.readAction() } init { dirtyScopeHolder.installVFSListener(this) val compilerManager = CompilerManager.getInstance(project) val isUpToDate = compilerManager.takeIf { kotlinDataContainer != null } ?.createProjectCompileScope(project) ?.let(compilerManager::isUpToDate) ?: false executeOnBuildThread { if (isUpToDate) { withDirtyScopeUnderWriteLock { upToDateCheckFinished(Module.EMPTY_ARRAY) openStorage() } } else { markAsOutdated() } } subscribeToCompilerEvents() } private val projectIfNotDisposed: Project? get() = project.takeUnless(Project::isDisposed) private fun subscribeToCompilerEvents() { val connection = projectIfNotDisposed?.messageBus?.connect(this) ?: return connection.subscribe(BuildManagerListener.TOPIC, object : BuildManagerListener { override fun buildStarted(project: Project, sessionId: UUID, isAutomake: Boolean) { if (project === [email protected]) { compilationStarted() } } override fun buildFinished(project: Project, sessionId: UUID, isAutomake: Boolean) { if (project === [email protected]) { executeOnBuildThread { if (!runReadAction { [email protected] }) { compilationFinished() } } } } }) connection.subscribe(PortableCachesLoadListener.TOPIC, object : PortableCachesLoadListener { override fun loadingStarted() { withWriteLock { closeStorage() } } }) } private fun compilationFinished() { val compilerModules = runReadAction { projectIfNotDisposed?.let { val manager = ModuleManager.getInstance(it) dirtyScopeHolder.compilationAffectedModules.map(manager::findModuleByName) } } withDirtyScopeUnderWriteLock { --activeBuildCount compilerActivityFinished(compilerModules) if (activeBuildCount == 0) openStorage() compilationCounter.increment() } } private fun compilationStarted(): Unit = withDirtyScopeUnderWriteLock { ++activeBuildCount compilerActivityStarted() closeStorage() } private val kotlinDataContainer: Path? get() = BuildDataPathsImpl(BuildManager.getInstance().getProjectSystemDirectory(project)).targetsDataRoot .toPath() .resolve(SettingConstants.KOTLIN_DATA_CONTAINER_ID) .takeIf { it.exists() && it.isDirectory() } ?.listDirectoryEntries("${SettingConstants.KOTLIN_DATA_CONTAINER_ID}*") ?.firstOrNull() private fun openStorage() { val basePath = runReadAction { projectIfNotDisposed?.basePath } ?: return val pathConverter = RelativeFileToPathConverter(File(basePath)) val targetDataDir = kotlinDataContainer?.toFile() ?: run { LOG.warn("try to open storage without index directory") return } storage = LookupStorage(targetDataDir, pathConverter) LOG.info("kotlin CRI storage is opened") } private fun closeStorage() { storage?.close().let { LOG.info("kotlin CRI storage is closed" + if (it == null) " (didn't exist)" else "") } storage = null } private fun markAsOutdated() { val modules = runReadAction { projectIfNotDisposed?.let { ModuleManager.getInstance(it).modules } } ?: return withDirtyScopeUnderWriteLock { upToDateCheckFinished(modules) } } fun scopeWithCodeReferences(element: PsiElement): GlobalSearchScope? = element.takeIf(this::isServiceEnabledFor)?.let { CachedValuesManager.getCachedValue(element) { CachedValueProvider.Result.create( buildScopeWithReferences(referentFiles(element), element), PsiModificationTracker.MODIFICATION_COUNT, this, ) } } @TestOnly fun findReferenceFilesInTests(element: PsiElement): Set<VirtualFile>? = referentFiles(element) private fun referentFiles(element: PsiElement): Set<VirtualFile>? = tryWithReadLock(fun(): Set<VirtualFile>? { val storage = storage ?: return null val originalFqNames = extractFqNames(element).ifEmpty { return null } val virtualFile = PsiUtilCore.getVirtualFile(element) ?: return null if (projectFileIndex.isInSource(virtualFile) && virtualFile in dirtyScopeHolder) return null if (projectFileIndex.isInLibrary(virtualFile)) return null return originalFqNames.flatMapTo(mutableSetOf()) { currentFqName -> val name = currentFqName.shortName().asString() val scope = currentFqName.parent().takeUnless(FqName::isRoot)?.asString() ?: "" storage.get(LookupSymbol(name, scope)).mapNotNull { VfsUtil.findFile(Path(it), true) } } }) private val isInsideLibraryScopeThreadLocal = ThreadLocal.withInitial { false } private fun isInsideLibraryScope(): Boolean = CompilerReferenceService.getInstanceIfEnabled(project) ?.safeAs<CompilerReferenceServiceBase<*>>() ?.isInsideLibraryScope ?: isInsideLibraryScopeThreadLocal.get() private fun <T> computeInLibraryScope(action: () -> T): T = CompilerReferenceService.getInstanceIfEnabled(project) ?.safeAs<CompilerReferenceServiceBase<*>>() ?.computeInLibraryScope<T, Throwable>(action) ?: run { isInsideLibraryScopeThreadLocal.set(true) try { action() } finally { isInsideLibraryScopeThreadLocal.set(false) } } private fun findHierarchyInLibrary(basePsiElement: PsiElement): List<FqName> { val baseClass = when (basePsiElement) { is KtClassOrObject, is PsiClass -> basePsiElement is PsiMember -> basePsiElement.containingClass is KtDeclaration -> basePsiElement.containingClassOrObject else -> null } ?: return emptyList() val overridden: MutableList<FqName> = baseClass.getKotlinFqName()?.let { mutableListOf(it) } ?: mutableListOf() val processor = Processor { clazz: PsiClass -> clazz.takeUnless { it.hasModifierProperty(PsiModifier.PRIVATE) } ?.let { runReadAction { it.qualifiedName } } ?.let { overridden += FqName(it) } true } HierarchySearchRequest( originalElement = baseClass, searchScope = ProjectScope.getLibrariesScope(project), searchDeeply = true, ).searchInheritors().forEach(processor) return overridden } private fun isServiceEnabledFor(element: PsiElement): Boolean = !isInsideLibraryScope() && storage != null && isEnabled && runReadAction { element.containingFile } ?.let(InjectedLanguageManager.getInstance(project)::isInjectedFragment) ?.not() == true private fun buildScopeWithReferences(virtualFiles: Set<VirtualFile>?, element: PsiElement): GlobalSearchScope? { if (virtualFiles == null) return null // knows everything val referencesScope = GlobalSearchScope.filesWithoutLibrariesScope(project, virtualFiles) /*** * can contain all languages, but depends on [supportedFileTypes] * [com.intellij.compiler.backwardRefs.DirtyScopeHolder.getModuleForSourceContentFile] */ val knownDirtyScope = withDirtyScopeUnderReadLock { dirtyScope } // [supportedFileTypes] without references + can contain references from other languages val wholeClearScope = knownDirtyScope.not() // [supportedFileTypes] without references //val knownCleanScope = GlobalSearchScope.getScopeRestrictedByFileTypes(wholeClearScope, *supportedFileTypes.toTypedArray()) val knownCleanScope = wholeClearScope.restrictToKotlinSources() // [supportedFileTypes] from dirty scope + other languages from the whole project val wholeDirtyScope = knownCleanScope.not() /* * Example: * module1 (dirty): 1.java, 2.kt, 3.groovy * module2: 4.groovy * module3: 5.java, 6.kt, 7.groovy * ----- * [knownDirtyScope] contains m1[1, 2, 3] * [wholeClearScope] contains m2[4], m3[5, 6, 7] * [knownCleanScope] contains m3[6] * [wholeDirtyScope] contains m1[1, 2, 3], m2[4], m3[5, 7] */ val mayContainReferencesScope = referencesScope.uniteWith(wholeDirtyScope) return CompilerReferenceServiceBase.scopeWithLibraryIfNeeded(project, projectFileIndex, mayContainReferencesScope, element) } override fun dispose(): Unit = withWriteLock { closeStorage() } override fun getModificationCount(): Long = compilationCounter.sum() companion object { operator fun get(project: Project): KotlinCompilerReferenceIndexService = project.service() fun getInstanceIfEnable(project: Project): KotlinCompilerReferenceIndexService? = if (isEnabled) get(project) else null const val SETTINGS_ID: String = "kotlin.compiler.ref.index" val isEnabled: Boolean get() = AdvancedSettings.getBoolean(SETTINGS_ID) private val LOG: Logger = logger<KotlinCompilerReferenceIndexService>() } class InitializationActivity : StartupActivity.DumbAware { override fun runActivity(project: Project) { getInstanceIfEnable(project) } } } private fun executeOnBuildThread(compilationFinished: () -> Unit): Unit = if (isUnitTestMode()) { compilationFinished() } else { BuildManager.getInstance().runCommand(compilationFinished) } private fun extractFqNames(element: PsiElement): List<FqName> { val originalElement = element.unwrapped ?: return emptyList() extractFqName(originalElement)?.let { return listOf(it) } return if (originalElement is KtParameter) extractFqNamesFromParameter(originalElement) else emptyList() } private fun extractFqName(element: PsiElement): FqName? = when (element) { is KtClassOrObject, is PsiClass -> element.getKotlinFqName() is KtConstructor<*> -> element.getContainingClassOrObject().fqName is KtNamedFunction -> element.fqName is KtProperty -> element.takeUnless(KtProperty::isOverridable)?.fqName is PsiMethod -> if (element.isConstructor) element.containingClass?.getKotlinFqName() else element.getKotlinFqName() is PsiField -> element.takeIf { it.hasModifier(JvmModifier.STATIC) }?.getKotlinFqName() else -> null } private fun extractFqNamesFromParameter(parameter: KtParameter): List<FqName> { val parameterFqName = parameter.takeIf(KtParameter::hasValOrVar)?.fqName ?: return emptyList() if (parameter.containingClass()?.isData() == false) return listOfNotNull(parameterFqName.takeUnless { parameter.isOverridable }) val parameterIndex = parameter.parameterIndex().takeUnless { it == -1 }?.plus(1) ?: return emptyList() return listOf(parameterFqName, FqName(parameterFqName.parent().asString() + ".component$parameterIndex")) }
apache-2.0
d347344b09c918bc39f613340284fe6b
43.169666
158
0.701606
5.02104
false
false
false
false
siosio/intellij-community
plugins/kotlin/gradle/gradle-idea/src/org/jetbrains/kotlin/idea/configuration/KotlinDslGradleKotlinFrameworkSupportProvider.kt
1
12615
// 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.configuration import com.intellij.framework.FrameworkTypeEx import com.intellij.framework.addSupport.FrameworkSupportInModuleProvider import com.intellij.ide.util.frameworkSupport.FrameworkSupportModel import com.intellij.openapi.externalSystem.model.ExternalSystemDataKeys import com.intellij.openapi.externalSystem.model.project.ProjectId import com.intellij.openapi.module.Module import com.intellij.openapi.roots.ModifiableModelsProvider import com.intellij.openapi.roots.ModifiableRootModel import org.gradle.util.GradleVersion import org.jetbrains.kotlin.idea.KotlinIcons import org.jetbrains.kotlin.idea.KotlinIdeaGradleBundle import org.jetbrains.kotlin.idea.configuration.KotlinBuildScriptManipulator.Companion.GSK_KOTLIN_VERSION_PROPERTY_NAME import org.jetbrains.kotlin.idea.configuration.KotlinBuildScriptManipulator.Companion.getKotlinGradlePluginClassPathSnippet import org.jetbrains.kotlin.idea.configuration.KotlinBuildScriptManipulator.Companion.getKotlinModuleDependencySnippet import org.jetbrains.kotlin.idea.formatter.KotlinStyleGuideCodeStyle import org.jetbrains.kotlin.idea.formatter.ProjectCodeStyleImporter import org.jetbrains.kotlin.idea.projectWizard.WizardStatsService import org.jetbrains.kotlin.idea.util.isSnapshot import org.jetbrains.kotlin.idea.versions.* import org.jetbrains.plugins.gradle.frameworkSupport.BuildScriptDataBuilder import org.jetbrains.plugins.gradle.frameworkSupport.KotlinDslGradleFrameworkSupportProvider import javax.swing.Icon abstract class KotlinDslGradleKotlinFrameworkSupportProvider( val frameworkTypeId: String, val displayName: String, val frameworkIcon: Icon ) : KotlinDslGradleFrameworkSupportProvider() { override fun getFrameworkType(): FrameworkTypeEx = object : FrameworkTypeEx(frameworkTypeId) { override fun getIcon(): Icon = frameworkIcon override fun getPresentableName(): String = displayName override fun createProvider(): FrameworkSupportInModuleProvider = this@KotlinDslGradleKotlinFrameworkSupportProvider } override fun createConfigurable(model: FrameworkSupportModel) = KotlinGradleFrameworkSupportInModuleConfigurable(model, this) override fun addSupport( projectId: ProjectId, module: Module, rootModel: ModifiableRootModel, modifiableModelsProvider: ModifiableModelsProvider, buildScriptData: BuildScriptDataBuilder ) { var kotlinVersion = kotlinCompilerVersionShort() val additionalRepository = getRepositoryForVersion(kotlinVersion) if (isSnapshot(bundledRuntimeVersion())) { kotlinVersion = LAST_SNAPSHOT_VERSION } val useNewSyntax = buildScriptData.gradleVersion >= MIN_GRADLE_VERSION_FOR_NEW_PLUGIN_SYNTAX if (useNewSyntax) { if (additionalRepository != null) { val repository = additionalRepository.toKotlinRepositorySnippet() updateSettingsScript(module) { with(it) { addPluginRepository(additionalRepository) addMavenCentralPluginRepository() addPluginRepository(DEFAULT_GRADLE_PLUGIN_REPOSITORY) } } buildScriptData.addRepositoriesDefinition("mavenCentral()") buildScriptData.addRepositoriesDefinition(repository) } buildScriptData .addPluginDefinitionInPluginsGroup(getPluginDefinition() + " version \"$kotlinVersion\"") } else { if (additionalRepository != null) { val repository = additionalRepository.toKotlinRepositorySnippet() buildScriptData.addBuildscriptRepositoriesDefinition(repository) buildScriptData.addRepositoriesDefinition("mavenCentral()") buildScriptData.addRepositoriesDefinition(repository) } buildScriptData .addPropertyDefinition("val $GSK_KOTLIN_VERSION_PROPERTY_NAME: String by extra") .addPluginDefinition(getOldSyntaxPluginDefinition()) .addBuildscriptRepositoriesDefinition("mavenCentral()") // TODO: in gradle > 4.1 this could be single declaration e.g. 'val kotlin_version: String by extra { "1.1.11" }' .addBuildscriptPropertyDefinition("var $GSK_KOTLIN_VERSION_PROPERTY_NAME: String by extra\n $GSK_KOTLIN_VERSION_PROPERTY_NAME = \"$kotlinVersion\"") .addBuildscriptDependencyNotation(getKotlinGradlePluginClassPathSnippet()) } buildScriptData.addRepositoriesDefinition("mavenCentral()") val isNewProject = module.project.getUserData(ExternalSystemDataKeys.NEWLY_CREATED_PROJECT) == true if (isNewProject) { ProjectCodeStyleImporter.apply(module.project, KotlinStyleGuideCodeStyle.INSTANCE) GradlePropertiesFileFacade.forProject(module.project).addCodeStyleProperty(KotlinStyleGuideCodeStyle.CODE_STYLE_SETTING) } val projectCreationStats = WizardStatsService.ProjectCreationStats("Gradle", this.presentableName, "gradleKotlin") WizardStatsService.logDataOnProjectGenerated(session = null, module.project, projectCreationStats) } protected abstract fun getOldSyntaxPluginDefinition(): String protected abstract fun getPluginDefinition(): String protected fun composeDependency(buildScriptData: BuildScriptDataBuilder, artifactId: String): String { return if (buildScriptData.gradleVersion >= MIN_GRADLE_VERSION_FOR_NEW_PLUGIN_SYNTAX) "implementation(${getKotlinModuleDependencySnippet(artifactId, null)})" else "implementation(${getKotlinModuleDependencySnippet(artifactId, "\$$GSK_KOTLIN_VERSION_PROPERTY_NAME")})" } } class KotlinDslGradleKotlinJavaFrameworkSupportProvider : KotlinDslGradleKotlinFrameworkSupportProvider( "KOTLIN", KotlinIdeaGradleBundle.message("display.name.kotlin.jvm"), KotlinIcons.SMALL_LOGO ) { override fun getOldSyntaxPluginDefinition() = "plugin(\"${KotlinGradleModuleConfigurator.KOTLIN}\")" override fun getPluginDefinition() = "kotlin(\"jvm\")" override fun addSupport( projectId: ProjectId, module: Module, rootModel: ModifiableRootModel, modifiableModelsProvider: ModifiableModelsProvider, buildScriptData: BuildScriptDataBuilder ) { super.addSupport(projectId, module, rootModel, modifiableModelsProvider, buildScriptData) val jvmTarget = getDefaultJvmTarget(rootModel.sdk, bundledRuntimeVersion()) if (jvmTarget != null) { addJvmTargetTask(buildScriptData) } val artifactId = getStdlibArtifactId(rootModel.sdk, bundledRuntimeVersion()) buildScriptData.addDependencyNotation(composeDependency(buildScriptData, artifactId)) } private fun addJvmTargetTask(buildScriptData: BuildScriptDataBuilder) { val minGradleVersion = GradleVersion.version("5.0") if (buildScriptData.gradleVersion >= minGradleVersion) buildScriptData .addOther( """ tasks { compileKotlin { kotlinOptions.jvmTarget = "1.8" } compileTestKotlin { kotlinOptions.jvmTarget = "1.8" } }""".trimIndent() ) else { buildScriptData .addImport("import org.jetbrains.kotlin.gradle.tasks.KotlinCompile") .addOther("tasks.withType<KotlinCompile> {\n kotlinOptions.jvmTarget = \"1.8\"\n}\n") } } } abstract class AbstractKotlinDslGradleKotlinJSFrameworkSupportProvider( frameworkTypeId: String, displayName: String ) : KotlinDslGradleKotlinFrameworkSupportProvider(frameworkTypeId, displayName, KotlinIcons.JS) { abstract val jsSubTargetName: String override fun addSupport( projectId: ProjectId, module: Module, rootModel: ModifiableRootModel, modifiableModelsProvider: ModifiableModelsProvider, buildScriptData: BuildScriptDataBuilder ) { super.addSupport(projectId, module, rootModel, modifiableModelsProvider, buildScriptData) buildScriptData.addOther( """ kotlin { js { $jsSubTargetName { """.trimIndent() + ( additionalSubTargetSettings() ?.lines() ?.joinToString("\n", "\n", "\n") { line: String -> if (line.isBlank()) { line } else { line .prependIndent() .prependIndent() .prependIndent() } } ?: "\n" ) + """ } binaries.executable() } } """.trimIndent() ) val artifactId = MAVEN_JS_STDLIB_ID.removePrefix("kotlin-") buildScriptData.addDependencyNotation(composeDependency(buildScriptData, artifactId)) } abstract fun additionalSubTargetSettings(): String? override fun getOldSyntaxPluginDefinition(): String = "plugin(\"${KotlinJsGradleModuleConfigurator.KOTLIN_JS}\")" override fun getPluginDefinition(): String = "id(\"org.jetbrains.kotlin.js\")" } class KotlinDslGradleKotlinJSBrowserFrameworkSupportProvider : AbstractKotlinDslGradleKotlinJSFrameworkSupportProvider( "KOTLIN_JS_BROWSER", KotlinIdeaGradleBundle.message("display.name.kotlin.js.for.browser") ) { override val jsSubTargetName: String get() = "browser" override fun addSupport( projectId: ProjectId, module: Module, rootModel: ModifiableRootModel, modifiableModelsProvider: ModifiableModelsProvider, buildScriptData: BuildScriptDataBuilder ) { super.addSupport(projectId, module, rootModel, modifiableModelsProvider, buildScriptData) addBrowserSupport(module) } override fun additionalSubTargetSettings(): String? = browserConfiguration() } class KotlinDslGradleKotlinJSNodeFrameworkSupportProvider : AbstractKotlinDslGradleKotlinJSFrameworkSupportProvider( "KOTLIN_JS_NODE", KotlinIdeaGradleBundle.message("display.name.kotlin.js.for.node.js") ) { override val jsSubTargetName: String get() = "nodejs" override fun additionalSubTargetSettings(): String? = null } class KotlinDslGradleKotlinMPPFrameworkSupportProvider : KotlinDslGradleKotlinFrameworkSupportProvider( "KOTLIN_MPP", KotlinIdeaGradleBundle.message("display.name.kotlin.multiplatform"), KotlinIcons.MPP ) { override fun getOldSyntaxPluginDefinition() = "plugin(\"org.jetbrains.kotlin.multiplatform\")" override fun getPluginDefinition() = "kotlin(\"multiplatform\")" override fun addSupport( projectId: ProjectId, module: Module, rootModel: ModifiableRootModel, modifiableModelsProvider: ModifiableModelsProvider, buildScriptData: BuildScriptDataBuilder ) { super.addSupport(projectId, module, rootModel, modifiableModelsProvider, buildScriptData) buildScriptData.addOther( """kotlin { /* Targets configuration omitted. * To find out how to configure the targets, please follow the link: * https://kotlinlang.org/docs/reference/building-mpp-with-gradle.html#setting-up-targets */ sourceSets { val commonMain by getting { dependencies { implementation(kotlin("stdlib-common")) } } val commonTest by getting { dependencies { implementation(kotlin("test-common")) implementation(kotlin("test-annotations-common")) } } } }""" ) } }
apache-2.0
2c3a9e3b243d813d5e0d1ca8fa9e0568
42.350515
167
0.665398
6.012869
false
false
false
false
K0zka/kerub
src/main/kotlin/com/github/kerubistan/kerub/planner/steps/storage/block/duplicate/AbstractBlockDuplicateExecutor.kt
2
1163
package com.github.kerubistan.kerub.planner.steps.storage.block.duplicate import com.github.kerubistan.kerub.data.dynamic.VirtualStorageDeviceDynamicDao import com.github.kerubistan.kerub.host.HostCommandExecutor import com.github.kerubistan.kerub.planner.execution.AbstractStepExecutor import com.github.kerubistan.kerub.utils.junix.ssh.openssh.OpenSsh abstract class AbstractBlockDuplicateExecutor<T : AbstractBlockDuplicate<*>> : AbstractStepExecutor<T, Unit>() { abstract val hostCommandExecutor: HostCommandExecutor abstract val virtualStorageDynamicDao: VirtualStorageDeviceDynamicDao override fun perform(step: T) { allocate(step) hostCommandExecutor.execute(step.sourceHost) { OpenSsh.copyBlockDevice( session = it, sourceDevice = step.source.getPath(step.virtualStorageDevice.id), targetAddress = step.targetHost.address, targetDevice = step.target.getPath(step.virtualStorageDevice.id) ) } } abstract fun allocate(step: T) override fun update(step: T, updates: Unit) { virtualStorageDynamicDao.update(step.virtualStorageDevice.id) { it.copy( allocations = it.allocations + step.target ) } } }
apache-2.0
3f5311563fb68f4a61cfb4da6902b528
32.257143
112
0.790198
4.080702
false
false
false
false
GunoH/intellij-community
plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/idea/externalAnnotations/AbstractExternalAnnotationTest.kt
1
2677
// 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.externalAnnotations import com.intellij.openapi.module.Module import com.intellij.openapi.roots.JavaModuleExternalPaths import com.intellij.openapi.roots.ModifiableRootModel import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.vfs.VfsUtilCore import com.intellij.psi.codeStyle.JavaCodeStyleSettings import com.intellij.testFramework.LightPlatformTestCase import com.intellij.util.ThrowableRunnable import org.jetbrains.kotlin.idea.test.KotlinLightCodeInsightFixtureTestCase import org.jetbrains.kotlin.idea.test.KotlinWithJdkAndRuntimeLightProjectDescriptor import org.jetbrains.kotlin.idea.test.runAll import com.intellij.openapi.application.runWriteAction import java.io.File abstract class AbstractExternalAnnotationTest: KotlinLightCodeInsightFixtureTestCase() { override fun setUp() { super.setUp() JavaCodeStyleSettings.getInstance(project).USE_EXTERNAL_ANNOTATIONS = true addFile(dataFilePath(classWithExternalAnnotatedMembers)) } override fun tearDown() { runAll( ThrowableRunnable { JavaCodeStyleSettings.getInstance(project).USE_EXTERNAL_ANNOTATIONS = false }, ThrowableRunnable { super.tearDown() } ) } private fun addFile(path: String) { val file = File(path) val root = LightPlatformTestCase.getSourceRoot() runWriteAction { val virtualFile = root.createChildData(null, file.name) virtualFile.getOutputStream(null).writer().use { it.write(FileUtil.loadFile(file)) } } } protected fun doTest(kotlinFilePath: String) { myFixture.configureByFiles(kotlinFilePath, dataFilePath(externalAnnotationsFile), dataFilePath(classWithExternalAnnotatedMembers)) myFixture.checkHighlighting() } override fun getProjectDescriptor() = object : KotlinWithJdkAndRuntimeLightProjectDescriptor() { override fun configureModule(module: Module, model: ModifiableRootModel) { super.configureModule(module, model) model.getModuleExtension(JavaModuleExternalPaths::class.java) .setExternalAnnotationUrls(arrayOf(VfsUtilCore.pathToUrl(dataFilePath(externalAnnotationsPath)))) } } companion object { private const val externalAnnotationsPath = "annotations/" private const val classWithExternalAnnotatedMembers = "ClassWithExternalAnnotatedMembers.java" private const val externalAnnotationsFile = "$externalAnnotationsPath/annotations.xml" } }
apache-2.0
b4b425694ae244eb4e1f283278071672
43.633333
138
0.759806
5.238748
false
true
false
false
GunoH/intellij-community
uast/uast-common/src/org/jetbrains/uast/evaluation/TreeBasedEvaluator.kt
7
31229
// 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.uast.evaluation import com.intellij.openapi.diagnostic.Attachment import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.util.registry.Registry import com.intellij.psi.JavaPsiFacade import com.intellij.psi.PsiModifier import com.intellij.psi.PsiType import com.intellij.psi.PsiVariable import org.jetbrains.uast.* import org.jetbrains.uast.values.* import org.jetbrains.uast.values.UNothingValue.JumpKind.BREAK import org.jetbrains.uast.values.UNothingValue.JumpKind.CONTINUE import org.jetbrains.uast.visitor.UastTypedVisitor class TreeBasedEvaluator( override val context: UastLanguagePlugin, val extensions: List<UEvaluatorExtension> ) : UEvaluator { override fun getDependents(dependency: UDependency): Set<UValue> { return resultCache.values.map { it.value }.filter { dependency in it.dependencies }.toSet() } private val inputStateCache = mutableMapOf<UExpression, UEvaluationState>() private val resultCache = mutableMapOf<UExpression, UEvaluationInfo>() private val maxAnalyzeDepth get() = Registry.intValue("uast.evaluator.depth.limit", 15) private val loopIterationLimit get() = Registry.intValue("uast.evaluator.loop.iteration.limit", 20) override fun analyze(method: UMethod, state: UEvaluationState) { method.uastBody?.accept(DepthLimitingEvaluatorVisitor(maxAnalyzeDepth, this::EvaluatingVisitor), state) } override fun analyze(field: UField, state: UEvaluationState) { field.uastInitializer?.accept(DepthLimitingEvaluatorVisitor(maxAnalyzeDepth, this::EvaluatingVisitor), state) } internal fun getCached(expression: UExpression): UValue? { return resultCache[expression]?.value } override fun evaluate(expression: UExpression, state: UEvaluationState?): UValue = getEvaluationInfo(expression, state).value private fun getEvaluationInfo(expression: UExpression, state: UEvaluationState? = null): UEvaluationInfo { if (state == null) { val result = resultCache[expression] if (result != null) return result } val inputState = state ?: inputStateCache[expression] ?: expression.createEmptyState() return expression.accept(DepthLimitingEvaluatorVisitor(maxAnalyzeDepth, this::EvaluatingVisitor), inputState) } override fun evaluateVariableByReference(variableReference: UReferenceExpression, state: UEvaluationState?): UValue { val target = variableReference.resolveToUElement() as? UVariable ?: return UUndeterminedValue return getEvaluationInfo(variableReference, state).state[target] } // ----------------------- // private infix fun UEvaluationInfo.storeResultFor(expression: UExpression) = apply { resultCache[expression] = this } private inner class EvaluatingVisitor(chain: UastTypedVisitor<UEvaluationState, UEvaluationInfo>?) : UastTypedVisitor<UEvaluationState, UEvaluationInfo> { private val chain = chain ?: this override fun visitElement(node: UElement, data: UEvaluationState): UEvaluationInfo { return UEvaluationInfo(UUndeterminedValue, data).apply { if (node is UExpression) { this storeResultFor node } } } override fun visitLiteralExpression(node: ULiteralExpression, data: UEvaluationState): UEvaluationInfo { storeState(node, data) val value = node.value return value.toConstant(node) to data storeResultFor node } private fun storeState(node: UExpression, data: UEvaluationState) { ProgressManager.checkCanceled() inputStateCache[node] = data } override fun visitClassLiteralExpression(node: UClassLiteralExpression, data: UEvaluationState): UEvaluationInfo { storeState(node, data) return (node.type?.let { value -> UClassConstant(value, node) } ?: UUndeterminedValue) to data storeResultFor node } override fun visitReturnExpression(node: UReturnExpression, data: UEvaluationState): UEvaluationInfo { storeState(node, data) val argument = node.returnExpression return UValue.UNREACHABLE to (argument?.accept(chain, data)?.state ?: data) storeResultFor node } override fun visitBreakExpression(node: UBreakExpression, data: UEvaluationState): UEvaluationInfo { storeState(node, data) return UNothingValue(node) to data storeResultFor node } override fun visitYieldExpression(node: UYieldExpression, data: UEvaluationState): UEvaluationInfo { storeState(node, data) val value = node.expression?.accept(chain, data)?.let { UYieldResult(it.value, node) } ?: UUndeterminedValue return value to data storeResultFor node } override fun visitContinueExpression(node: UContinueExpression, data: UEvaluationState): UEvaluationInfo { storeState(node, data) return UNothingValue(node) to data storeResultFor node } override fun visitThrowExpression(node: UThrowExpression, data: UEvaluationState): UEvaluationInfo { storeState(node, data) return UValue.UNREACHABLE to data storeResultFor node } // ----------------------- // override fun visitSimpleNameReferenceExpression( node: USimpleNameReferenceExpression, data: UEvaluationState ): UEvaluationInfo { storeState(node, data) return when (val resolvedElement = node.resolveToUElement()) { is UEnumConstant -> UEnumEntryValueConstant(resolvedElement, node) is UField -> if (resolvedElement.hasModifierProperty(PsiModifier.FINAL)) { data[resolvedElement].ifUndetermined { val helper = JavaPsiFacade.getInstance(resolvedElement.project).constantEvaluationHelper val evaluated = helper.computeConstantExpression(resolvedElement.initializer) evaluated?.toConstant() ?: UUndeterminedValue } } else { return super.visitSimpleNameReferenceExpression(node, data) } is UVariable -> data[resolvedElement].ifUndetermined { node.evaluateViaExtensions { evaluateVariable(resolvedElement, data) }?.value ?: UUndeterminedValue } else -> return super.visitSimpleNameReferenceExpression(node, data) } to data storeResultFor node } override fun visitReferenceExpression( node: UReferenceExpression, data: UEvaluationState ): UEvaluationInfo { storeState(node, data) return UCallResultValue(node, emptyList()) to data storeResultFor node } // ----------------------- // private fun UExpression.assign( valueInfo: UEvaluationInfo, operator: UastBinaryOperator.AssignOperator = UastBinaryOperator.ASSIGN ): UEvaluationInfo { this.accept(chain, valueInfo.state) if (this is UResolvable) { val resolvedElement = resolve() if (resolvedElement is PsiVariable) { val variable = context.convertWithParent<UVariable>(resolvedElement)!! val currentValue = valueInfo.state[variable] val result = when (operator) { UastBinaryOperator.ASSIGN -> valueInfo.value UastBinaryOperator.PLUS_ASSIGN -> currentValue + valueInfo.value UastBinaryOperator.MINUS_ASSIGN -> currentValue - valueInfo.value UastBinaryOperator.MULTIPLY_ASSIGN -> currentValue * valueInfo.value UastBinaryOperator.DIVIDE_ASSIGN -> currentValue / valueInfo.value UastBinaryOperator.REMAINDER_ASSIGN -> currentValue % valueInfo.value UastBinaryOperator.AND_ASSIGN -> currentValue bitwiseAnd valueInfo.value UastBinaryOperator.OR_ASSIGN -> currentValue bitwiseOr valueInfo.value UastBinaryOperator.XOR_ASSIGN -> currentValue bitwiseXor valueInfo.value UastBinaryOperator.SHIFT_LEFT_ASSIGN -> currentValue shl valueInfo.value UastBinaryOperator.SHIFT_RIGHT_ASSIGN -> currentValue shr valueInfo.value UastBinaryOperator.UNSIGNED_SHIFT_RIGHT_ASSIGN -> currentValue ushr valueInfo.value else -> UUndeterminedValue } return result to valueInfo.state.assign(variable, result, this) } } return UUndeterminedValue to valueInfo.state } private fun UExpression.assign( operator: UastBinaryOperator.AssignOperator, value: UExpression, data: UEvaluationState ) = assign(value.accept(chain, data), operator) override fun visitPrefixExpression(node: UPrefixExpression, data: UEvaluationState): UEvaluationInfo { storeState(node, data) val operandInfo = node.operand.accept(chain, data) val operandValue = operandInfo.value if (!operandValue.reachable) return operandInfo storeResultFor node return when (node.operator) { UastPrefixOperator.UNARY_PLUS -> operandValue UastPrefixOperator.UNARY_MINUS -> -operandValue UastPrefixOperator.LOGICAL_NOT -> !operandValue UastPrefixOperator.INC -> { val resultValue = operandValue.inc() val newState = node.operand.assign(resultValue to operandInfo.state).state return resultValue to newState storeResultFor node } UastPrefixOperator.DEC -> { val resultValue = operandValue.dec() val newState = node.operand.assign(resultValue to operandInfo.state).state return resultValue to newState storeResultFor node } else -> { return node.evaluateViaExtensions { evaluatePrefix(node.operator, operandValue, operandInfo.state) } ?: (UUndeterminedValue to operandInfo.state storeResultFor node) } } to operandInfo.state storeResultFor node } inline fun UElement.evaluateViaExtensions(block: UEvaluatorExtension.() -> UEvaluationInfo): UEvaluationInfo? { for (ext in extensions) { val extResult = ext.block() if (extResult.value != UUndeterminedValue) return extResult } languageExtension()?.block()?.let { if (it.value != UUndeterminedValue) return it } return null } override fun visitPostfixExpression(node: UPostfixExpression, data: UEvaluationState): UEvaluationInfo { storeState(node, data) val operandInfo = node.operand.accept(chain, data) val operandValue = operandInfo.value if (!operandValue.reachable) return operandInfo storeResultFor node return when (node.operator) { UastPostfixOperator.INC -> { operandValue to node.operand.assign(operandValue.inc() to operandInfo.state).state } UastPostfixOperator.DEC -> { operandValue to node.operand.assign(operandValue.dec() to operandInfo.state).state } else -> { return node.evaluateViaExtensions { evaluatePostfix(node.operator, operandValue, operandInfo.state) } ?: (UUndeterminedValue to operandInfo.state storeResultFor node) } } storeResultFor node } private fun UastBinaryOperator.evaluate(left: UValue, right: UValue): UValue? = when (this) { UastBinaryOperator.PLUS -> left + right UastBinaryOperator.MINUS -> left - right UastBinaryOperator.MULTIPLY -> left * right UastBinaryOperator.DIV -> left / right UastBinaryOperator.MOD -> left % right UastBinaryOperator.EQUALS -> left valueEquals right UastBinaryOperator.NOT_EQUALS -> left valueNotEquals right UastBinaryOperator.IDENTITY_EQUALS -> left identityEquals right UastBinaryOperator.IDENTITY_NOT_EQUALS -> left identityNotEquals right UastBinaryOperator.GREATER -> left greater right UastBinaryOperator.LESS -> left less right UastBinaryOperator.GREATER_OR_EQUALS -> left greaterOrEquals right UastBinaryOperator.LESS_OR_EQUALS -> left lessOrEquals right UastBinaryOperator.LOGICAL_AND -> left and right UastBinaryOperator.LOGICAL_OR -> left or right UastBinaryOperator.BITWISE_AND -> left bitwiseAnd right UastBinaryOperator.BITWISE_OR -> left bitwiseOr right UastBinaryOperator.BITWISE_XOR -> left bitwiseXor right UastBinaryOperator.SHIFT_LEFT -> left shl right UastBinaryOperator.SHIFT_RIGHT -> left shr right UastBinaryOperator.UNSIGNED_SHIFT_RIGHT -> left ushr right else -> null } override fun visitBinaryExpression(node: UBinaryExpression, data: UEvaluationState): UEvaluationInfo { storeState(node, data) val operator = node.operator if (operator is UastBinaryOperator.AssignOperator) { return node.leftOperand.assign(operator, node.rightOperand, data) storeResultFor node } val leftInfo = node.leftOperand.accept(chain, data) if (!leftInfo.reachable) { return leftInfo storeResultFor node } val rightInfo = node.rightOperand.accept(chain, leftInfo.state) operator.evaluate(leftInfo.value, rightInfo.value)?.let { return it to rightInfo.state storeResultFor node } return node.evaluateViaExtensions { evaluateBinary(node, leftInfo.value, rightInfo.value, rightInfo.state) } ?: (UUndeterminedValue to rightInfo.state storeResultFor node) } override fun visitPolyadicExpression(node: UPolyadicExpression, data: UEvaluationState): UEvaluationInfo { storeState(node, data) val operator = node.operator val infos = node.operands.map { it.accept(chain, data).apply { if (!reachable) { return this storeResultFor node } } } if(infos.isEmpty()){ logger<TreeBasedEvaluator>().error("empty infos on $node of class ${node.javaClass}", Attachment("nodetext", node.sourcePsi?.text ?: "")) return UUndeterminedValue to data storeResultFor node } val lastInfo = infos.last() val firstValue = infos.first().value val restInfos = infos.drop(1) return restInfos.fold(firstValue) { accumulator, info -> operator.evaluate(accumulator, info.value) ?: return UUndeterminedValue to info.state storeResultFor node } to lastInfo.state storeResultFor node } private fun evaluateTypeCast(operandInfo: UEvaluationInfo, type: PsiType): UEvaluationInfo { val constant = operandInfo.value.toConstant() ?: return UUndeterminedValue to operandInfo.state val resultConstant = when (type) { PsiType.BOOLEAN -> { constant as? UBooleanConstant } PsiType.CHAR -> when (constant) { is UNumericConstant -> UCharConstant(constant.value.toInt().toChar()) is UCharConstant -> constant else -> null } PsiType.LONG -> { (constant as? UNumericConstant)?.value?.toLong()?.let { value -> ULongConstant(value) } } PsiType.BYTE, PsiType.SHORT, PsiType.INT -> { (constant as? UNumericConstant)?.value?.toInt()?.let { UIntConstant(it, type) } } PsiType.FLOAT, PsiType.DOUBLE -> { (constant as? UNumericConstant)?.value?.toDouble()?.let { UFloatConstant.create(it, type) } } else -> when (type.name) { "java.lang.String" -> UStringConstant(constant.asString()) else -> null } } ?: return UUndeterminedValue to operandInfo.state return when (operandInfo.value) { resultConstant -> return operandInfo is UConstant -> resultConstant is UDependentValue -> UDependentValue.create(resultConstant, operandInfo.value.dependencies) else -> UUndeterminedValue } to operandInfo.state } private fun evaluateTypeCheck(operandInfo: UEvaluationInfo, type: PsiType): UEvaluationInfo { val constant = operandInfo.value.toConstant() ?: return UUndeterminedValue to operandInfo.state val valid = when (type) { PsiType.BOOLEAN -> constant is UBooleanConstant PsiType.LONG -> constant is ULongConstant PsiType.BYTE, PsiType.SHORT, PsiType.INT, PsiType.CHAR -> constant is UIntConstant PsiType.FLOAT, PsiType.DOUBLE -> constant is UFloatConstant else -> when (type.name) { "java.lang.String" -> constant is UStringConstant else -> false } } return UBooleanConstant.valueOf(valid) to operandInfo.state } override fun visitBinaryExpressionWithType( node: UBinaryExpressionWithType, data: UEvaluationState ): UEvaluationInfo { storeState(node, data) val operandInfo = node.operand.accept(chain, data) if (!operandInfo.reachable || operandInfo.value == UUndeterminedValue) { return operandInfo storeResultFor node } return when (node.operationKind) { UastBinaryExpressionWithTypeKind.TypeCast.INSTANCE -> evaluateTypeCast(operandInfo, node.type) UastBinaryExpressionWithTypeKind.InstanceCheck.INSTANCE -> evaluateTypeCheck(operandInfo, node.type) else -> UUndeterminedValue to operandInfo.state } storeResultFor node } override fun visitParenthesizedExpression(node: UParenthesizedExpression, data: UEvaluationState): UEvaluationInfo { storeState(node, data) return node.expression.accept(chain, data) storeResultFor node } override fun visitLabeledExpression(node: ULabeledExpression, data: UEvaluationState): UEvaluationInfo { storeState(node, data) return node.expression.accept(chain, data) storeResultFor node } override fun visitCallExpression(node: UCallExpression, data: UEvaluationState): UEvaluationInfo { storeState(node, data) var currentInfo = UUndeterminedValue to data currentInfo = node.receiver?.accept(chain, currentInfo.state) ?: currentInfo if (!currentInfo.reachable) return currentInfo storeResultFor node val argumentValues = mutableListOf<UValue>() for (valueArgument in node.valueArguments) { currentInfo = valueArgument.accept(chain, currentInfo.state) if (!currentInfo.reachable) return currentInfo storeResultFor node argumentValues.add(currentInfo.value) } return (node.evaluateViaExtensions { node.resolve()?.let { method -> evaluateMethodCall(method, argumentValues, currentInfo.state) } ?: (UUndeterminedValue to currentInfo.state) } ?: (UCallResultValue(node, argumentValues) to currentInfo.state)) storeResultFor node } override fun visitQualifiedReferenceExpression( node: UQualifiedReferenceExpression, data: UEvaluationState ): UEvaluationInfo { storeState(node, data) var currentInfo = UUndeterminedValue to data currentInfo = node.receiver.accept(chain, currentInfo.state) if (!currentInfo.reachable) return currentInfo storeResultFor node val selectorInfo = node.selector.accept(chain, currentInfo.state) return when (node.accessType) { UastQualifiedExpressionAccessType.SIMPLE -> { selectorInfo } else -> { return node.evaluateViaExtensions { evaluateQualified(node.accessType, currentInfo, selectorInfo) } ?: (UUndeterminedValue to selectorInfo.state storeResultFor node) } } storeResultFor node } override fun visitDeclarationsExpression( node: UDeclarationsExpression, data: UEvaluationState ): UEvaluationInfo { storeState(node, data) var currentInfo = UUndeterminedValue to data for (variable in node.declarations) { currentInfo = variable.accept(chain, currentInfo.state) if (!currentInfo.reachable) return currentInfo storeResultFor node } return currentInfo storeResultFor node } override fun visitVariable(node: UVariable, data: UEvaluationState): UEvaluationInfo { val initializer = node.uastInitializer val initializerInfo = initializer?.accept(chain, data) ?: (UUndeterminedValue to data) if (!initializerInfo.reachable) return initializerInfo return UUndeterminedValue to initializerInfo.state.assign(node, initializerInfo.value, node) } // ----------------------- // override fun visitBlockExpression(node: UBlockExpression, data: UEvaluationState): UEvaluationInfo { storeState(node, data) var currentInfo = UUndeterminedValue to data for (expression in node.expressions) { currentInfo = expression.accept(chain, currentInfo.state) if (!currentInfo.reachable) return currentInfo storeResultFor node } return currentInfo storeResultFor node } override fun visitIfExpression(node: UIfExpression, data: UEvaluationState): UEvaluationInfo { storeState(node, data) val conditionInfo = node.condition.accept(chain, data) if (!conditionInfo.reachable) return conditionInfo storeResultFor node val thenInfo = node.thenExpression?.accept(chain, conditionInfo.state) val elseInfo = node.elseExpression?.accept(chain, conditionInfo.state) val conditionValue = conditionInfo.value val defaultInfo = UUndeterminedValue to conditionInfo.state return when (val constantConditionValue = conditionValue.toConstant()) { is UBooleanConstant -> { if (constantConditionValue.value) thenInfo ?: defaultInfo else elseInfo ?: defaultInfo } else -> when { thenInfo == null -> elseInfo?.merge(defaultInfo) ?: defaultInfo elseInfo == null -> thenInfo.merge(defaultInfo) else -> thenInfo.merge(elseInfo) } } storeResultFor node } override fun visitSwitchExpression(node: USwitchExpression, data: UEvaluationState): UEvaluationInfo { storeState(node, data) val subjectInfo = node.expression?.accept(chain, data) ?: (UUndeterminedValue to data) if (!subjectInfo.reachable) return subjectInfo storeResultFor node var resultInfo: UEvaluationInfo? = null var clauseInfo = subjectInfo var fallThroughCondition: UValue = UBooleanConstant.False fun List<UExpression>.evaluateAndFold(): UValue = this.map { clauseInfo = it.accept(chain, clauseInfo.state) (clauseInfo.value valueEquals subjectInfo.value).toConstant() as? UValueBase ?: UUndeterminedValue }.fold(UBooleanConstant.False) { previous: UValue, next -> previous or next } clausesLoop@ for (expression in node.body.expressions) { val switchClauseWithBody = expression as USwitchClauseExpressionWithBody val caseCondition = switchClauseWithBody.caseValues.evaluateAndFold().or(fallThroughCondition) if (caseCondition != UBooleanConstant.False) { for (bodyExpression in switchClauseWithBody.body.expressions) { clauseInfo = bodyExpression.accept(chain, clauseInfo.state) if (!clauseInfo.reachable) break } val clauseValue = clauseInfo.value if (exitingNode(clauseValue) == node) { // break from switch resultInfo = resultInfo merge getBreakResult(clauseInfo) if (caseCondition == UBooleanConstant.True) break@clausesLoop clauseInfo = subjectInfo fallThroughCondition = UBooleanConstant.False } // TODO: jump out else { fallThroughCondition = caseCondition clauseInfo = clauseInfo.merge(subjectInfo) } } } resultInfo = resultInfo ?: subjectInfo val resultValue = resultInfo.value if (resultValue is UNothingValue && resultValue.containingLoopOrSwitch == node) { resultInfo = resultInfo.copy(UUndeterminedValue) } return resultInfo storeResultFor node } private fun exitingNode(uValue: UValue): UExpression? { when (uValue) { is UNothingValue -> return uValue.containingLoopOrSwitch is UPhiValue -> { for (value in uValue.values) if (value is UYieldResult) return value.containingLoopOrSwitch for (value in uValue.values) if (value is UNothingValue) value.containingLoopOrSwitch?.let { return it } return null } else -> return null } } private fun getBreakResult(clauseInfo: UEvaluationInfo): UEvaluationInfo { return when (val clauseValue = clauseInfo.value) { is UYieldResult -> clauseValue.value to clauseInfo.state is UPhiValue -> UPhiValue.create(clauseValue.values.map { when (it) { is UYieldResult -> it.value else -> it } }) to clauseInfo.state else -> clauseInfo } } private fun evaluateLoop( loop: ULoopExpression, inputState: UEvaluationState, condition: UExpression? = null, infinite: Boolean = false, update: UExpression? = null ): UEvaluationInfo { fun evaluateCondition(inputState: UEvaluationState): UEvaluationInfo = condition?.accept(chain, inputState) ?: ((if (infinite) UBooleanConstant.True else UUndeterminedValue) to inputState) var resultInfo = UUndeterminedValue to inputState var iterationsAllowed = loopIterationLimit do { ProgressManager.checkCanceled() iterationsAllowed-- if (iterationsAllowed <= 0) { LOG.error("evaluateLoop iterations count exceeded the limit $loopIterationLimit", Attachment("loop.txt", loop.sourcePsi?.text ?: "<no-info>")) return UUndeterminedValue to inputState storeResultFor loop } val previousInfo = resultInfo resultInfo = evaluateCondition(resultInfo.state) val conditionConstant = resultInfo.value.toConstant() if (conditionConstant == UBooleanConstant.False) { return resultInfo.copy(UUndeterminedValue) storeResultFor loop } val bodyInfo = loop.body.accept(chain, resultInfo.state) val bodyValue = bodyInfo.value if (bodyValue is UNothingValue) { if (bodyValue.kind == BREAK && bodyValue.containingLoopOrSwitch == loop) { return if (conditionConstant == UBooleanConstant.True) { bodyInfo.copy(UUndeterminedValue) } else { bodyInfo.copy(UUndeterminedValue).merge(previousInfo) } storeResultFor loop } else if (bodyValue.kind == CONTINUE && bodyValue.containingLoopOrSwitch == loop) { val updateInfo = update?.accept(chain, bodyInfo.state) ?: bodyInfo resultInfo = updateInfo.copy(UUndeterminedValue).merge(previousInfo) } else { return if (conditionConstant == UBooleanConstant.True) { bodyInfo } else { resultInfo.copy(UUndeterminedValue) } storeResultFor loop } } else { val updateInfo = update?.accept(chain, bodyInfo.state) ?: bodyInfo resultInfo = updateInfo.merge(previousInfo) } } while (previousInfo != resultInfo) return resultInfo.copy(UUndeterminedValue) storeResultFor loop } override fun visitForEachExpression(node: UForEachExpression, data: UEvaluationState): UEvaluationInfo { storeState(node, data) val iterableInfo = node.iteratedValue.accept(chain, data) return evaluateLoop(node, iterableInfo.state) } override fun visitForExpression(node: UForExpression, data: UEvaluationState): UEvaluationInfo { storeState(node, data) val initialState = node.declaration?.accept(chain, data)?.state ?: data return evaluateLoop(node, initialState, node.condition, node.condition == null, node.update) } override fun visitWhileExpression(node: UWhileExpression, data: UEvaluationState): UEvaluationInfo { storeState(node, data) return evaluateLoop(node, data, node.condition) } override fun visitDoWhileExpression(node: UDoWhileExpression, data: UEvaluationState): UEvaluationInfo { storeState(node, data) val bodyInfo = node.body.accept(chain, data) return evaluateLoop(node, bodyInfo.state, node.condition) } override fun visitTryExpression(node: UTryExpression, data: UEvaluationState): UEvaluationInfo { storeState(node, data) val tryInfo = node.tryClause.accept(chain, data) val mergedTryInfo = tryInfo.merge(UUndeterminedValue to data) val catchInfoList = node.catchClauses.map { it.accept(chain, mergedTryInfo.state) } val mergedTryCatchInfo = catchInfoList.fold(mergedTryInfo, UEvaluationInfo::merge) val finallyInfo = node.finallyClause?.accept(chain, mergedTryCatchInfo.state) ?: mergedTryCatchInfo return finallyInfo storeResultFor node } // ----------------------- // override fun visitObjectLiteralExpression(node: UObjectLiteralExpression, data: UEvaluationState): UEvaluationInfo { storeState(node, data) val objectInfo = node.declaration.accept(chain, data) val resultState = data.merge(objectInfo.state) return UUndeterminedValue to resultState storeResultFor node } override fun visitLambdaExpression(node: ULambdaExpression, data: UEvaluationState): UEvaluationInfo { storeState(node, data) val lambdaInfo = node.body.accept(chain, data) val resultState = data.merge(lambdaInfo.state) return UUndeterminedValue to resultState storeResultFor node } override fun visitClass(node: UClass, data: UEvaluationState): UEvaluationInfo { // fields / initializers / nested classes? var resultState = data for (method in node.methods) { resultState = resultState.merge(method.accept(chain, resultState).state) } return UUndeterminedValue to resultState } override fun visitMethod(node: UMethod, data: UEvaluationState): UEvaluationInfo { return UUndeterminedValue to (node.uastBody?.accept(chain, data)?.state ?: data) } } } fun Any?.toConstant(node: ULiteralExpression? = null): UValueBase = when (this) { null -> UNullConstant is Float -> UFloatConstant.create(this.toDouble(), UNumericType.FLOAT, node) is Double -> UFloatConstant.create(this, UNumericType.DOUBLE, node) is Long -> ULongConstant(this, node) is Int -> UIntConstant(this, UNumericType.INT, node) is Short -> UIntConstant(this.toInt(), UNumericType.SHORT, node) is Byte -> UIntConstant(this.toInt(), UNumericType.BYTE, node) is Char -> UCharConstant(this, node) is Boolean -> UBooleanConstant.valueOf(this) is String -> UStringConstant(this, node) else -> UUndeterminedValue } private val LOG = Logger.getInstance(TreeBasedEvaluator::class.java)
apache-2.0
8235cf0c8b5f227c40523b8c1a2caf58
42.984507
156
0.686285
5.397338
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/gradle/gradle-idea/src/org/jetbrains/kotlin/idea/gradle/statistics/KotlinGradleFUSLogger.kt
1
11904
// 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.gradle.statistics import com.intellij.ide.highlighter.ProjectFileType import com.intellij.ide.util.PropertiesComponent import com.intellij.internal.statistic.eventLog.EventLogConfiguration import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.project.DumbAware import com.intellij.openapi.project.Project import com.intellij.openapi.startup.StartupActivity import com.intellij.openapi.util.io.FileUtil import com.intellij.util.PathUtilRt import com.intellij.util.concurrency.AppExecutorUtil import com.intellij.util.text.trimMiddle import org.jetbrains.kotlin.idea.statistics.FUSEventGroups import org.jetbrains.kotlin.idea.statistics.GradleStatisticsEvents import org.jetbrains.kotlin.idea.statistics.KotlinFUSLogger import org.jetbrains.kotlin.statistics.BuildSessionLogger import org.jetbrains.kotlin.statistics.BuildSessionLogger.Companion.STATISTICS_FOLDER_NAME import org.jetbrains.kotlin.statistics.fileloggers.MetricsContainer import org.jetbrains.kotlin.statistics.metrics.BooleanMetrics import org.jetbrains.kotlin.statistics.metrics.NumericalMetrics import org.jetbrains.kotlin.statistics.metrics.StringMetrics import java.io.File import java.util.* import java.util.concurrent.TimeUnit import java.util.concurrent.atomic.AtomicBoolean import kotlin.io.path.Path import kotlin.io.path.exists class KotlinGradleFUSLogger : StartupActivity, DumbAware, Runnable { override fun runActivity(project: Project) { AppExecutorUtil.getAppScheduledExecutorService() .scheduleWithFixedDelay(this, EXECUTION_DELAY_MIN, EXECUTION_DELAY_MIN, TimeUnit.MINUTES) } override fun run() { reportStatistics() } companion object { private val IDE_STRING_ANONYMIZERS = lazy { mapOf( StringMetrics.PROJECT_PATH to { path: String -> // This code duplicated logics of StatisticsUtil.getProjectId, which could not be directly reused: // 1. the path of gradle project may not have corresponding project // 2. the projectId should be stable and independent on IDE version val presentableUrl = FileUtil.toSystemIndependentName(path) val name = PathUtilRt.getFileName(presentableUrl).lowercase(Locale.US).removeSuffix(ProjectFileType.DOT_DEFAULT_EXTENSION) val locationHash = Integer.toHexString((presentableUrl).hashCode()) val projectHash = "${name.trimMiddle(name.length.coerceAtMost(254 - locationHash.length), useEllipsisSymbol = false)}.$locationHash" EventLogConfiguration.getInstance().anonymize(projectHash) }) } private fun String.anonymizeIdeString(metric: StringMetrics) = if (metric.anonymization.anonymizeOnIdeSize()) IDE_STRING_ANONYMIZERS.value[metric]?.invoke(this) else this /** * Maximum amount of directories which were reported as gradle user dirs * These directories should be monitored for reported gradle statistics. */ const val MAXIMUM_USER_DIRS = 10 /** * Delay between sequential checks of gradle statistics */ const val EXECUTION_DELAY_MIN = 60L /** * Property name used for persisting gradle user dirs */ private const val GRADLE_USER_DIRS_PROPERTY_NAME = "kotlin-gradle-user-dirs" private val isRunning = AtomicBoolean(false) private fun MetricsContainer.log(event: GradleStatisticsEvents, vararg metrics: Any) { val data = HashMap<String, String>() fun putIfNotNull(key: String, value: String?) { if (value != null) { data[key.toLowerCase()] = value } } for (metric in metrics) { when (metric) { is BooleanMetrics -> putIfNotNull(metric.name, this.getMetric(metric)?.toStringRepresentation()) is StringMetrics -> putIfNotNull( metric.name, this.getMetric(metric)?.toStringRepresentation()?.anonymizeIdeString(metric) ) is NumericalMetrics -> putIfNotNull(metric.name, this.getMetric(metric)?.toStringRepresentation()) is Pair<*, *> -> putIfNotNull(metric.first.toString(), metric.second?.toString()) } } if (data.size > 0) { KotlinFUSLogger.log(FUSEventGroups.GradlePerformance, event.name, data) } } private fun processMetricsContainer(container: MetricsContainer, previous: MetricsContainer?) { container.log( GradleStatisticsEvents.Environment, NumericalMetrics.CPU_NUMBER_OF_CORES, StringMetrics.GRADLE_VERSION, NumericalMetrics.ARTIFACTS_DOWNLOAD_SPEED, StringMetrics.IDES_INSTALLED, BooleanMetrics.EXECUTED_FROM_IDEA, StringMetrics.PROJECT_PATH ) container.log( GradleStatisticsEvents.Kapt, BooleanMetrics.ENABLED_KAPT, BooleanMetrics.ENABLED_DAGGER, BooleanMetrics.ENABLED_DATABINDING ) container.log( GradleStatisticsEvents.CompilerPlugins, BooleanMetrics.ENABLED_COMPILER_PLUGIN_ALL_OPEN, BooleanMetrics.ENABLED_COMPILER_PLUGIN_NO_ARG, BooleanMetrics.ENABLED_COMPILER_PLUGIN_JPA_SUPPORT, BooleanMetrics.ENABLED_COMPILER_PLUGIN_SAM_WITH_RECEIVER, BooleanMetrics.JVM_COMPILER_IR_MODE, StringMetrics.JVM_DEFAULTS, StringMetrics.USE_OLD_BACKEND ) container.log( GradleStatisticsEvents.JS, BooleanMetrics.JS_GENERATE_EXTERNALS, StringMetrics.JS_GENERATE_EXECUTABLE_DEFAULT, StringMetrics.JS_TARGET_MODE ) container.log( GradleStatisticsEvents.MPP, StringMetrics.MPP_PLATFORMS, BooleanMetrics.ENABLED_HMPP, StringMetrics.JS_COMPILER_MODE ) container.log( GradleStatisticsEvents.Libraries, StringMetrics.LIBRARY_SPRING_VERSION, StringMetrics.LIBRARY_VAADIN_VERSION, StringMetrics.LIBRARY_GWT_VERSION, StringMetrics.LIBRARY_HIBERNATE_VERSION ) container.log( GradleStatisticsEvents.GradleConfiguration, NumericalMetrics.GRADLE_DAEMON_HEAP_SIZE, NumericalMetrics.GRADLE_BUILD_NUMBER_IN_CURRENT_DAEMON, NumericalMetrics.CONFIGURATION_API_COUNT, NumericalMetrics.CONFIGURATION_IMPLEMENTATION_COUNT, NumericalMetrics.CONFIGURATION_COMPILE_COUNT, NumericalMetrics.CONFIGURATION_RUNTIME_COUNT, NumericalMetrics.GRADLE_NUMBER_OF_TASKS, NumericalMetrics.GRADLE_NUMBER_OF_UNCONFIGURED_TASKS, NumericalMetrics.GRADLE_NUMBER_OF_INCREMENTAL_TASKS ) container.log( GradleStatisticsEvents.ComponentVersions, StringMetrics.KOTLIN_COMPILER_VERSION, StringMetrics.KOTLIN_STDLIB_VERSION, StringMetrics.KOTLIN_REFLECT_VERSION, StringMetrics.KOTLIN_COROUTINES_VERSION, StringMetrics.KOTLIN_SERIALIZATION_VERSION, StringMetrics.ANDROID_GRADLE_PLUGIN_VERSION ) container.log( GradleStatisticsEvents.KotlinFeatures, StringMetrics.KOTLIN_LANGUAGE_VERSION, StringMetrics.KOTLIN_API_VERSION, BooleanMetrics.BUILD_SRC_EXISTS, NumericalMetrics.BUILD_SRC_COUNT, BooleanMetrics.GRADLE_BUILD_CACHE_USED, BooleanMetrics.GRADLE_WORKER_API_USED, BooleanMetrics.KOTLIN_OFFICIAL_CODESTYLE, BooleanMetrics.KOTLIN_PROGRESSIVE_MODE, BooleanMetrics.KOTLIN_KTS_USED ) container.log( GradleStatisticsEvents.GradlePerformance, NumericalMetrics.GRADLE_BUILD_DURATION, NumericalMetrics.GRADLE_EXECUTION_DURATION, NumericalMetrics.NUMBER_OF_SUBPROJECTS, NumericalMetrics.STATISTICS_VISIT_ALL_PROJECTS_OVERHEAD, NumericalMetrics.STATISTICS_COLLECT_METRICS_OVERHEAD ) val finishTime = container.getMetric(NumericalMetrics.BUILD_FINISH_TIME)?.getValue() val prevFinishTime = previous?.getMetric(NumericalMetrics.BUILD_FINISH_TIME)?.getValue() val betweenBuilds = if (finishTime != null && prevFinishTime != null) finishTime - prevFinishTime else null container.log( GradleStatisticsEvents.UseScenarios, Pair("time_between_builds", betweenBuilds), BooleanMetrics.DEBUGGER_ENABLED, BooleanMetrics.COMPILATION_STARTED, BooleanMetrics.TESTS_EXECUTED, BooleanMetrics.MAVEN_PUBLISH_EXECUTED, BooleanMetrics.BUILD_FAILED ) } fun reportStatistics() { if (isRunning.compareAndSet(false, true)) { try { for (gradleUserHome in gradleUserDirs) { BuildSessionLogger.listProfileFiles(File(gradleUserHome, STATISTICS_FOLDER_NAME))?.forEach { statisticFile -> var fileWasRead = true try { var previousEvent: MetricsContainer? = null fileWasRead = MetricsContainer.readFromFile(statisticFile) { metricContainer -> processMetricsContainer(metricContainer, previousEvent) previousEvent = metricContainer } } catch (e: Exception) { Logger.getInstance(KotlinFUSLogger::class.java) .info("Failed to process file ${statisticFile.absolutePath}: ${e.message}", e) } finally { if (fileWasRead && !statisticFile.delete()) { Logger.getInstance(KotlinFUSLogger::class.java) .warn("[FUS] Failed to delete file ${statisticFile.absolutePath}") } } } } } finally { isRunning.set(false) } } } private var gradleUserDirs: List<String> set(value) = PropertiesComponent.getInstance().setList( GRADLE_USER_DIRS_PROPERTY_NAME, value ) get() = PropertiesComponent.getInstance().getList(GRADLE_USER_DIRS_PROPERTY_NAME) ?: emptyList() fun populateGradleUserDir(path: String) { val currentState = gradleUserDirs if (path in currentState) return val result = ArrayList<String>() result.add(path) result.addAll(currentState) gradleUserDirs = result.filter { filePath -> Path(filePath).exists() }.take(MAXIMUM_USER_DIRS) } } }
apache-2.0
21aa6f3dde7fd70ead3a7915399829d2
44.090909
138
0.605595
5.673975
false
false
false
false
TachiWeb/TachiWeb-Server
Tachiyomi-App/src/main/java/eu/kanade/tachiyomi/source/model/Page.kt
1
1191
package eu.kanade.tachiyomi.source.model import android.net.Uri import eu.kanade.tachiyomi.network.ProgressListener import rx.subjects.Subject open class Page( val index: Int, val url: String = "", var imageUrl: String? = null, @Transient var uri: Uri? = null // Deprecated but can't be deleted due to extensions ) : ProgressListener { val number: Int get() = index + 1 @Transient @Volatile var status: Int = 0 set(value) { field = value statusSubject?.onNext(value) } @Transient @Volatile var progress: Int = 0 @Transient private var statusSubject: Subject<Int, Int>? = null override fun update(bytesRead: Long, contentLength: Long, done: Boolean) { progress = if (contentLength > 0) { (100 * bytesRead / contentLength).toInt() } else { -1 } } fun setStatusSubject(subject: Subject<Int, Int>?) { this.statusSubject = subject } companion object { const val QUEUE = 0 const val LOAD_PAGE = 1 const val DOWNLOAD_IMAGE = 2 const val READY = 3 const val ERROR = 4 } }
apache-2.0
70d296991d31e3508a017a2678ff6b04
23.8125
92
0.595298
4.362637
false
false
false
false
joaomneto/TitanCompanion
src/main/java/pt/joaomneto/titancompanion/adventure/impl/HOTWAdventure.kt
1
2942
package pt.joaomneto.titancompanion.adventure.impl import android.os.Bundle import android.view.Menu import java.io.BufferedWriter import java.io.IOException import java.util.ArrayList import java.util.Arrays import pt.joaomneto.titancompanion.R import pt.joaomneto.titancompanion.adventure.Adventure import pt.joaomneto.titancompanion.adventure.impl.fragments.AdventureCombatFragment import pt.joaomneto.titancompanion.adventure.impl.fragments.AdventureEquipmentFragment import pt.joaomneto.titancompanion.adventure.impl.fragments.hotw.HOTWAdventureNotesFragment import pt.joaomneto.titancompanion.adventure.impl.fragments.hotw.HOTWAdventureVitalStatsFragment import pt.joaomneto.titancompanion.util.AdventureFragmentRunner class HOTWAdventure : Adventure( arrayOf( AdventureFragmentRunner( R.string.vitalStats, HOTWAdventureVitalStatsFragment::class ), AdventureFragmentRunner( R.string.fights, AdventureCombatFragment::class ), AdventureFragmentRunner( R.string.goldEquipment, AdventureEquipmentFragment::class ), AdventureFragmentRunner( R.string.notes, HOTWAdventureNotesFragment::class ) ) ) { var change: Int? = null private var keywords: MutableList<String> = ArrayList() override fun onCreate(savedInstanceState: Bundle?) { try { super.onCreate(savedInstanceState) } catch (e: Exception) { e.printStackTrace() } } override fun onCreateOptionsMenu(menu: Menu): Boolean { menuInflater.inflate(R.menu.adventure, menu) return true } @Throws(IOException::class) override fun storeAdventureSpecificValuesInFile(bw: BufferedWriter) { var keywordS = "" if (!keywords.isEmpty()) { for (note in keywords) { keywordS += note + "#" } keywordS = keywordS.substring(0, keywordS.length - 1) } bw.write("gold=" + gold + "\n") bw.write("keywords=" + keywordS + "\n") bw.write("change=" + change + "\n") } override fun loadAdventureSpecificValuesFromFile() { gold = Integer.valueOf(savedGame.getProperty("gold")) change = Integer.valueOf(savedGame.getProperty("change")) val keywordsValue = savedGame.getProperty("keywords") if (keywordsValue != null) { val keywordsS = String(keywordsValue.toByteArray(java.nio.charset.Charset.forName("UTF-8"))) this.keywords = ArrayList() val list = Arrays.asList(*keywordsS.split("#".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()) for (string in list) { if (!string.isEmpty()) this.keywords.add(string) } } } fun getKeywords(): List<String> { return keywords } }
lgpl-3.0
8d0fb5410e55d2c21ee5de19346c9ce3
31.688889
115
0.650578
4.714744
false
false
false
false
batagliao/onebible.android
app/src/main/java/com/claraboia/bibleandroid/adapters/BookSelectionAdapter.kt
1
4099
package com.claraboia.bibleandroid.adapters import android.graphics.drawable.Drawable import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.claraboia.bibleandroid.R import com.claraboia.bibleandroid.helpers.getBookAbbrev import com.claraboia.bibleandroid.helpers.getBookName import com.claraboia.bibleandroid.helpers.getBookType import com.claraboia.bibleandroid.models.Book import com.claraboia.bibleandroid.models.BookTypeEnum import com.claraboia.bibleandroid.viewmodels.BookForSort import com.claraboia.bibleandroid.views.BooksSelectDisplay import com.claraboia.bibleandroid.views.BooksSelectSortOrder import kotlinx.android.synthetic.main.layout_books_grid_item.* import kotlinx.android.synthetic.main.layout_books_grid_item.view.* import java.util.* import java.util.Collections.sort import kotlin.comparisons.compareBy import kotlin.comparisons.compareByDescending /** * Created by lucas.batagliao on 13/10/2016. */ class BookSelectionAdapter(val books: MutableList<BookForSort>, val click: (item: BookForSort) -> Unit) : RecyclerView.Adapter<BookSelectionAdapter.BookSelectionViewHolder>() { private val booksCopy: List<BookForSort> = ArrayList(books) class BookSelectionViewHolder(itemView: View?) : RecyclerView.ViewHolder(itemView) { fun bind(book: BookForSort, click: (BookForSort) -> Unit) { val size = book.chapterCount itemView.item_ChapterQty.text = itemView.context.resources.getQuantityString(R.plurals.chapters, size, size) itemView.item_bookName.text = book.bookName itemView.item_bookAbbrev.text = book.bookAbbrev itemView.item_book_frame.background = book.type.color() itemView.item_book_card.setOnClickListener { click.invoke(book) } } } var displayType : BooksSelectDisplay.BookLayoutDisplayType = BooksSelectDisplay.BookLayoutDisplayType.GRID override fun getItemCount(): Int { return books.size } override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): BookSelectionViewHolder { val inflater = LayoutInflater.from(parent?.context) val view: View if(displayType == BooksSelectDisplay.BookLayoutDisplayType.GRID) { view = inflater.inflate(R.layout.layout_books_grid_item, parent, false) }else{ view = inflater.inflate(R.layout.layout_books_list_item, parent, false) } val holder = BookSelectionViewHolder(view) return holder } override fun onBindViewHolder(holder: BookSelectionViewHolder?, position: Int) { val book = books[position] holder?.bind(book, click) } fun sortNormal(order: BooksSelectSortOrder.BookSortOrder){ if(order == BooksSelectSortOrder.BookSortOrder.ASC) { books.sortWith(compareBy { it.bookOrder }) }else{ books.sortWith(compareByDescending { it.bookOrder }) } notifyItemRangeChanged(0, itemCount -1) } fun sortAlpha(order: BooksSelectSortOrder.BookSortOrder){ if(order == BooksSelectSortOrder.BookSortOrder.ASC){ books.sortWith(compareBy { it.bookName }) }else{ books.sortWith(compareByDescending { it.bookName }) } notifyItemRangeChanged(0, itemCount -1) } fun filter(query: String?){ books.clear() if(query.isNullOrEmpty()){ books.addAll(booksCopy) }else{ val text = query!!.toLowerCase() for(b in booksCopy){ if(b.bookName.toLowerCase().contains(text) || b.bookAbbrev.toLowerCase().contains(text)){ books.add(b) } } } notifyDataSetChanged() } // fun notifyRemoveEach() { // for (i in 0..books.size - 1) { // notifyItemRemoved(i) // } // // } // // fun notifyAddEach() { // for (i in 0..books.size - 1) { // notifyItemInserted(i) // } // } }
apache-2.0
5d246bfe150970fca62d54da6cf3a461
34.652174
176
0.679922
4.278706
false
false
false
false
aosp-mirror/platform_frameworks_support
room/compiler/src/main/kotlin/androidx/room/solver/query/result/GuavaListenableFutureQueryResultBinder.kt
1
4769
/* * Copyright 2018 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.room.solver.query.result import androidx.room.ext.AndroidTypeNames import androidx.room.ext.L import androidx.room.ext.N import androidx.room.ext.RoomGuavaTypeNames import androidx.room.ext.T import androidx.room.ext.typeName import androidx.room.solver.CodeGenScope import androidx.room.writer.DaoWriter import com.squareup.javapoet.FieldSpec import com.squareup.javapoet.MethodSpec import com.squareup.javapoet.ParameterizedTypeName import com.squareup.javapoet.TypeSpec import javax.lang.model.element.Modifier import javax.lang.model.type.TypeMirror /** * A ResultBinder that emits a ListenableFuture<T> where T is the input {@code typeArg}. * * <p>The Future runs on the background thread Executor. */ class GuavaListenableFutureQueryResultBinder( val typeArg: TypeMirror, adapter: QueryResultAdapter?) : BaseObservableQueryResultBinder(adapter) { override fun convertAndReturn( roomSQLiteQueryVar: String, canReleaseQuery: Boolean, dbField: FieldSpec, inTransaction: Boolean, scope: CodeGenScope) { // Callable<T> val callableImpl = createCallableOfT( roomSQLiteQueryVar, dbField, inTransaction, scope) scope.builder().apply { addStatement( "return $T.createListenableFuture($L, $L, $L)", RoomGuavaTypeNames.GUAVA_ROOM, callableImpl, roomSQLiteQueryVar, canReleaseQuery) } } /** * Returns an anonymous subclass of Callable<T> that executes the database transaction and * constitutes the result T. * * <p>Note that this method does not release the query object. */ private fun createCallableOfT( roomSQLiteQueryVar: String, dbField: FieldSpec, inTransaction: Boolean, scope: CodeGenScope): TypeSpec { return TypeSpec.anonymousClassBuilder("").apply { superclass( ParameterizedTypeName.get(java.util.concurrent.Callable::class.typeName(), typeArg.typeName())) addMethod( MethodSpec.methodBuilder("call").apply { // public T call() throws Exception {} returns(typeArg.typeName()) addAnnotation(Override::class.typeName()) addModifiers(Modifier.PUBLIC) addException(Exception::class.typeName()) // Body. val transactionWrapper = if (inTransaction) { transactionWrapper(dbField) } else { null } transactionWrapper?.beginTransactionWithControlFlow() apply { val outVar = scope.getTmpVar("_result") val cursorVar = scope.getTmpVar("_cursor") addStatement("final $T $L = $N.query($L)", AndroidTypeNames.CURSOR, cursorVar, DaoWriter.dbField, roomSQLiteQueryVar) beginControlFlow("try").apply { val adapterScope = scope.fork() adapter?.convert(outVar, cursorVar, adapterScope) addCode(adapterScope.builder().build()) transactionWrapper?.commitTransaction() addStatement("return $L", outVar) } nextControlFlow("finally").apply { addStatement("$L.close()", cursorVar) } endControlFlow() } transactionWrapper?.endTransactionWithControlFlow() }.build()) }.build() } }
apache-2.0
a501dedee7dc07f5356b66ee3ab9226e
39.07563
95
0.561334
5.677381
false
false
false
false
hazuki0x0/YuzuBrowser
legacy/src/main/java/jp/hazuki/yuzubrowser/legacy/utils/view/templatepreserving/TemplatePreservingSnackBar.kt
1
5653
/* * Copyright (C) 2017 Hazuki * * 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 jp.hazuki.yuzubrowser.legacy.utils.view.templatepreserving import android.text.TextUtils import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.FrameLayout import android.widget.TextView import androidx.annotation.StringRes import com.google.android.material.snackbar.BaseTransientBottomBar import jp.hazuki.yuzubrowser.legacy.R class TemplatePreservingSnackBar /** * Constructor for the transient bottom bar. * * @param parent The parent for this transient bottom bar. * @param content The content view for this transient bottom bar. * @param contentViewCallback The content view callback for this transient bottom bar. */ private constructor(parent: ViewGroup, content: View, contentViewCallback: ContentViewCallback) : BaseTransientBottomBar<TemplatePreservingSnackBar>(parent, content, contentViewCallback) { private val textView: TemplatePreservingTextView = content.findViewById(R.id.snackbarText) private val action: TextView = content.findViewById(R.id.snackbarAction) var isDismissByAction = false private set fun setTemplateText(text: String) { textView.setTemplateText(text) } fun setText(text: CharSequence) { textView.text = text } fun setAction(@StringRes text: Int, listener: View.OnClickListener): TemplatePreservingSnackBar { return setAction(context.getText(text), listener) } fun setAction(text: CharSequence, listener: View.OnClickListener?): TemplatePreservingSnackBar { val tv = action if (TextUtils.isEmpty(text) || listener == null) { tv.visibility = View.GONE tv.setOnClickListener(null) } else { tv.visibility = View.VISIBLE tv.text = text tv.setOnClickListener { listener.onClick(it) // Now dismiss the Snackbar isDismissByAction = true dismiss() } } return this } private class ContentViewCallback internal constructor(private val content: View) : com.google.android.material.snackbar.ContentViewCallback { override fun animateContentIn(delay: Int, duration: Int) { // add custom *in animations for your views // e.g. original snackbar uses alpha animation, from 0 to 1 content.scaleY = 0f content.animate() .scaleY(1f) .setDuration(duration.toLong()).startDelay = delay.toLong() } override fun animateContentOut(delay: Int, duration: Int) { // add custom *out animations for your views // e.g. original snackbar uses alpha animation, from 1 to 0 content.scaleY = 1f content.animate() .scaleY(0f) .setDuration(duration.toLong()).startDelay = delay.toLong() } } companion object { fun make(view: ViewGroup, template: String, title: CharSequence, duration: Int): TemplatePreservingSnackBar { val parent = findSuitableParent(view) ?: throw IllegalArgumentException("No suitable parent found from the given view. " + "Please provide a valid view.") val inflater = LayoutInflater.from(parent.context) val content = inflater.inflate(R.layout.template_preserving_snackbar, parent, false) val callback = ContentViewCallback(content) val snackBar = TemplatePreservingSnackBar(parent, content, callback) snackBar.duration = duration snackBar.setTemplateText(template) snackBar.setText(title) return snackBar } private fun findSuitableParent(view: View?): ViewGroup? { var selection = view var fallback: ViewGroup? = null do { if (selection is androidx.coordinatorlayout.widget.CoordinatorLayout) { // We've found a CoordinatorLayout, use it return selection } else if (selection is FrameLayout) { if (selection.id == android.R.id.content) { // If we've hit the decor content view, then we didn't find a CoL in the // hierarchy, so use it. return selection } else { // It's not the content view but we'll use it as our fallback fallback = selection } } if (selection != null) { // Else, we will loop and crawl up the view hierarchy and try to find a parent val parent = selection.parent selection = if (parent is View) parent else null } } while (selection != null) // If we reach here then we didn't find a CoL or a suitable content view so we'll fallback return fallback } } }
apache-2.0
6b91ba4c3287a67b4fb7b277f77a7631
39.092199
188
0.630108
5.060877
false
false
false
false
orgzly/orgzly-android
app/src/main/java/com/orgzly/android/db/dao/NoteDao.kt
1
15903
package com.orgzly.android.db.dao import androidx.lifecycle.LiveData import androidx.room.Dao import androidx.room.Query import androidx.room.Transaction import com.orgzly.android.db.OrgzlyDatabase import com.orgzly.android.db.entity.Note import com.orgzly.android.db.entity.NotePosition import org.intellij.lang.annotations.Language @Dao abstract class NoteDao : BaseDao<Note> { @Query("SELECT * FROM notes WHERE level > 0") abstract fun getAll(): List<Note> @Query("SELECT count(*) FROM notes WHERE book_id = :bookId AND level > 0 AND is_cut = 0") abstract fun getCount(bookId: Long): Int @Query("SELECT * FROM notes WHERE id = :id") abstract fun get(id: Long): Note? @Query("SELECT * FROM notes WHERE title = :title ORDER BY lft DESC LIMIT 1") abstract fun getLast(title: String): Note? @Query("SELECT * FROM notes WHERE title = :title ORDER BY lft") abstract fun getByTitle(title: String): List<Note> @Query("SELECT * FROM notes WHERE id IN (:ids)") abstract fun get(ids: Set<Long>): List<Note> @Query("SELECT * FROM notes WHERE id IN (:ids) ORDER BY lft LIMIT 1") abstract fun getFirst(ids: Set<Long>): Note? @Query("SELECT * FROM notes WHERE id IN (:ids) ORDER BY lft DESC LIMIT 1") abstract fun getLast(ids: Set<Long>): Note? @Query("SELECT * FROM notes WHERE book_id = :bookId AND level = 1 AND $WHERE_EXISTING_NOTES ORDER BY lft") abstract fun getTopLevel(bookId: Long): List<Note> @Query("SELECT * FROM notes WHERE parent_id = :id AND $WHERE_EXISTING_NOTES ORDER BY lft") abstract fun getChildren(id: Long): List<Note> @Query("SELECT DISTINCT tags FROM notes WHERE tags IS NOT NULL AND tags != ''") abstract fun getDistinctTagsLiveData(): LiveData<List<String>> @Query("SELECT DISTINCT tags FROM notes WHERE tags IS NOT NULL AND tags != ''") abstract fun getDistinctTags(): List<String> @Query("DELETE FROM notes WHERE id IN ($SELECT_SUBTREE_IDS_FOR_IDS)") abstract fun deleteById(ids: Set<Long>): Int @Query("DELETE FROM notes WHERE book_id = :bookId") abstract fun deleteByBookId(bookId: Long) @Query(SELECT_NOTE_AND_ANCESTORS_IDS_FOR_IDS) abstract fun getNoteAndAncestorsIds(ids: List<Long>): List<Long> @Query(""" SELECT a.* FROM notes n, notes a WHERE n.id = (:id) AND n.book_id = a.book_id AND a.is_cut = 0 AND a.level > 0 AND a.lft < n.lft AND n.rgt < a.rgt ORDER BY a.lft """) abstract fun getAncestors(id: Long): List<Note> @Query(""" SELECT a.* FROM notes n, notes a WHERE n.id = (:id) AND n.book_id = a.book_id AND a.is_cut = 0 AND a.level > 0 AND a.lft <= n.lft AND n.rgt <= a.rgt ORDER BY a.lft """) abstract fun getNoteAndAncestors(id: Long): List<Note> @Query(SELECT_SUBTREE_FOR_IDS) abstract fun getNotesForSubtrees(ids: Set<Long>): List<Note> @Query("SELECT count(*) FROM ($SELECT_SUBTREE_FOR_IDS)") abstract fun getNotesForSubtreesCount(ids: Set<Long>): Int @Query(""" SELECT count(*) FROM notes WHERE book_id = :bookId AND $WHERE_EXISTING_NOTES AND (is_folded IS NULL OR is_folded = 0) """) abstract fun getBookUnfoldedNoteCount(bookId: Long): Int @Query(""" SELECT count(*) FROM notes WHERE id IN ($SELECT_SUBTREE_IDS_FOR_IDS) AND is_folded = 1 """) abstract fun getSubtreeFoldedNoteCount(ids: List<Long>): Int @Query(""" SELECT * FROM notes WHERE book_id = :bookId AND $WHERE_EXISTING_NOTES AND rgt < :lft AND parent_id = :parentId ORDER BY lft DESC LIMIT 1 """) abstract fun getPreviousSibling(bookId: Long, lft: Long, parentId: Long): Note? @Query(""" SELECT * FROM notes WHERE book_id = :bookId AND $WHERE_EXISTING_NOTES AND :rgt < lft AND parent_id = :parentId ORDER BY lft LIMIT 1 """) abstract fun getNextSibling(bookId: Long, rgt: Long, parentId: Long): Note? @Query(""" SELECT * FROM notes WHERE book_id = :bookId AND $WHERE_EXISTING_NOTES AND :lft < lft AND rgt < :rgt ORDER BY level, lft DESC LIMIT 1 """) abstract fun getLastHighestLevelDescendant(bookId: Long, lft: Long, rgt: Long): Note? @Query(""" UPDATE notes SET descendants_count = descendants_count + 1 WHERE book_id = :bookId AND $WHERE_EXISTING_NOTES AND lft < :lft AND :rgt < rgt """) abstract fun incrementDescendantsCountForAncestors(bookId: Long, lft: Long, rgt: Long): Int @Query("UPDATE notes SET rgt = rgt + 2 WHERE book_id = :bookId AND level = 0") abstract fun incrementRgtForRootNote(bookId: Long) @Query("SELECT id FROM notes WHERE book_id = :bookId AND level = 0") abstract fun getRootNodeId(bookId: Long): Long? @Query("SELECT * FROM notes WHERE book_id = :bookId AND level = 0") abstract fun getRootNode(bookId: Long): Note? @Query(""" UPDATE notes SET descendants_count = ( SELECT count(*) FROM notes d WHERE (notes.book_id = d.book_id AND $WHERE_EXISTING_NOTES AND notes.lft < d.lft AND d.rgt < notes.rgt) ) WHERE id IN ($SELECT_NOTE_AND_ANCESTORS_IDS_FOR_IDS) """) abstract fun updateDescendantsCountForNoteAndAncestors(ids: List<Long>) @Query(""" UPDATE notes SET descendants_count = ( SELECT count(*) FROM notes d WHERE (notes.book_id = d.book_id AND $WHERE_EXISTING_NOTES AND notes.lft < d.lft AND d.rgt < notes.rgt AND d.id NOT IN (:ignoreIds)) ) WHERE id IN ($SELECT_ANCESTORS_IDS_FOR_IDS) """) abstract fun updateDescendantsCountForAncestors(ids: Set<Long>, ignoreIds: Set<Long> = emptySet()) @Query("UPDATE notes SET content = :content, content_line_count = :contentLineCount WHERE id = :id") abstract fun updateContent(id: Long, content: String?, contentLineCount: Int) @Query(""" UPDATE notes SET title = :title, content = :content, content_line_count = :contentLineCount, state = :state, scheduled_range_id = :scheduled, deadline_range_id = :deadline, closed_range_id = :closed WHERE id = :id """) abstract fun update(id: Long, title: String, content: String?, contentLineCount: Int, state: String?, scheduled: Long?, deadline: Long?, closed: Long?): Int @Query("UPDATE notes SET title = :title, state = :state, priority = :priority WHERE id = :id") abstract fun update(id: Long, title: String, state: String?, priority: String?): Int @Query("UPDATE notes SET scheduled_range_id = :timeId WHERE id IN (:ids)") abstract fun updateScheduledTime(ids: Set<Long>, timeId: Long?) @Query("UPDATE notes SET deadline_range_id = :timeId WHERE id IN (:ids)") abstract fun updateDeadlineTime(ids: Set<Long>, timeId: Long?) @Transaction open fun foldAll(bookId: Long) { foldAll1(bookId) foldAll2(bookId) } @Query(""" UPDATE notes SET folded_under_id = parent_id WHERE (book_id = :bookId AND $WHERE_EXISTING_NOTES) AND level > ( SELECT min(level) FROM notes WHERE (book_id = :bookId AND $WHERE_EXISTING_NOTES) ) """) abstract fun foldAll1(bookId: Long) @Query("UPDATE notes SET is_folded = 1 WHERE book_id = :bookId AND $WHERE_EXISTING_NOTES") abstract fun foldAll2(bookId: Long) @Query("UPDATE notes SET is_folded = 0, folded_under_id = 0 WHERE book_id = :bookId") abstract fun unfoldAll(bookId: Long) @Query("UPDATE notes SET is_folded = 0 WHERE id IN (:ids)") abstract fun unfoldNotes(ids: List<Long>) @Query(""" UPDATE notes SET is_folded = 0, folded_under_id = 0 WHERE id IN ($SELECT_SUBTREE_IDS_FOR_IDS) """) abstract fun unfoldSubtrees(ids: List<Long>) @Transaction open fun foldSubtrees(ids: List<Long>) { foldSubtreesSetRoots(ids) foldSubtreesSetDescendants(ids) } @Query("UPDATE notes SET is_folded = 1 WHERE id IN (:ids)") abstract fun foldSubtreesSetRoots(ids: List<Long>) @Query(""" UPDATE notes SET is_folded = 1, folded_under_id = parent_id WHERE id IN ($SELECT_DESCENDANTS_IDS_FOR_IDS) """) abstract fun foldSubtreesSetDescendants(ids: List<Long>) @Query("UPDATE notes SET folded_under_id = 0 WHERE folded_under_id IN (:ids)") abstract fun updateFoldedUnderForNoteFoldedUnderId(ids: List<Long>) @Query("UPDATE notes SET is_folded = :isFolded WHERE id = :id") abstract fun updateIsFolded(id: Long, isFolded: Boolean): Int /** All descendants which are not already hidden (due to one of the ancestors being folded). */ @Query(""" UPDATE notes SET folded_under_id = :noteId WHERE book_id = :bookId AND $WHERE_EXISTING_NOTES AND :lft < lft AND rgt < :rgt AND (folded_under_id IS NULL OR folded_under_id = 0) """) abstract fun foldDescendantsUnderId(bookId: Long, noteId: Long, lft: Long, rgt: Long) /** All descendants which are hidden because of this note being folded. */ @Query(""" UPDATE notes SET folded_under_id = 0 WHERE book_id = :bookId AND $WHERE_EXISTING_NOTES AND :lft < lft AND rgt < :rgt AND folded_under_id = :noteId """) abstract fun unfoldDescendantsUnderId(bookId: Long, noteId: Long, lft: Long, rgt: Long) @Query("UPDATE notes SET lft = lft + :inc WHERE (book_id = :bookId AND $WHERE_EXISTING_NOTES) AND lft >= :value") abstract fun incrementLftForLftGe(bookId: Long, value: Long, inc: Int) @Query("UPDATE notes SET lft = lft + :inc WHERE (book_id = :bookId AND $WHERE_EXISTING_NOTES) AND lft > :value") abstract fun incrementLftForLftGt(bookId: Long, value: Long, inc: Int) @Query("UPDATE notes SET rgt = rgt + :inc WHERE book_id = :bookId AND is_cut = 0 AND rgt > :value") abstract fun incrementRgtForRgtGtOrRoot(bookId: Long, value: Long, inc: Int) @Query("UPDATE notes SET rgt = rgt + :inc WHERE book_id = :bookId AND is_cut = 0 AND rgt >= :value") abstract fun incrementRgtForRgtGeOrRoot(bookId: Long, value: Long, inc: Int) @Transaction open fun unfoldNotesFoldedUnderOthers(ids: Set<Long>) { ids.chunked(OrgzlyDatabase.SQLITE_MAX_VARIABLE_NUMBER/2).forEach { chunk -> unfoldNotesFoldedUnderOthersChunk(chunk) } } @Query(""" UPDATE notes SET folded_under_id = 0 WHERE id IN (:ids) AND folded_under_id NOT IN (:ids) """) abstract fun unfoldNotesFoldedUnderOthersChunk(ids: List<Long>) @Query("UPDATE notes SET folded_under_id = :foldedUnder WHERE id IN (:ids) AND folded_under_id = 0") abstract fun foldUnfolded(ids: Set<Long>, foldedUnder: Long) @Query("UPDATE notes SET folded_under_id = :parentId WHERE id = :noteId") abstract fun setFoldedUnder(noteId: Long, parentId: Long) @Query("UPDATE notes SET parent_id = :parentId WHERE id = :noteId") abstract fun updateParentForNote(noteId: Long, parentId: Long) @Query(""" UPDATE notes SET book_id = :bookId, level = :level, lft = :lft, rgt = :rgt, parent_id = :parentId WHERE id = :noteId """) abstract fun updateNote(noteId: Long, bookId: Long, level: Int, lft: Long, rgt: Long, parentId: Long) @Query(""" SELECT notes.id as noteId, notes.book_id as bookId FROM note_properties LEFT JOIN notes ON (notes.id = note_properties.note_id) WHERE LOWER(note_properties.name) = :name AND LOWER(note_properties.value) = :value AND notes.id IS NOT NULL ORDER BY notes.lft LIMIT 1 """) abstract fun firstNoteHavingPropertyLowerCase(name: String, value: String): NoteIdBookId? @Query(""" UPDATE notes SET state = :state, closed_range_id = null WHERE id IN (:ids) AND COALESCE(state, "") != COALESCE(:state, "") """) abstract fun updateStateAndRemoveClosedTime(ids: Set<Long>, state: String?): Int @Query(""" SELECT notes.id as noteId, state, title, content, st.string AS scheduled, dt.string AS deadline FROM notes LEFT JOIN org_ranges sr ON (sr.id = notes.scheduled_range_id) LEFT JOIN org_timestamps st ON (st.id = sr.start_timestamp_id) LEFT JOIN org_ranges dr ON (dr.id = notes.deadline_range_id) LEFT JOIN org_timestamps dt ON (dt.id = dr.start_timestamp_id) WHERE notes.id IN (:ids) AND COALESCE(state, "") != COALESCE(:state, "") """) abstract fun getNoteForStateChange(ids: Set<Long>, state: String?): List<NoteForStateUpdate> @Query("""SELECT DISTINCT book_id FROM notes WHERE id IN (:ids) AND COALESCE(state, "") != COALESCE(:state, "")""") abstract fun getBookIdsForNotesNotMatchingState(ids: Set<Long>, state: String?): List<Long> @Query("SELECT MAX(rgt) FROM notes WHERE book_id = :bookId AND is_cut = 0") abstract fun getMaxRgtForBook(bookId: Long): Long? @Query("SELECT * FROM notes WHERE book_id = :bookId AND level > 0 ORDER BY lft LIMIT 1") abstract fun getFirstNoteInBook(bookId: Long): Note? @Query("UPDATE notes SET created_at= :time WHERE id = :noteId") abstract fun updateCreatedAtTime(noteId: Long, time: Long) companion object { /* Every book has a root note with level 0. */ const val WHERE_EXISTING_NOTES = "(is_cut = 0 AND level > 0)" @Language("RoomSql") const val SELECT_ANCESTORS_IDS_FOR_IDS = """ SELECT DISTINCT a.id FROM notes n, notes a WHERE n.id IN (:ids) AND n.book_id = a.book_id AND a.is_cut = 0 AND a.level > 0 AND a.lft < n.lft AND n.rgt < a.rgt """ @Language("RoomSql") const val SELECT_NOTE_AND_ANCESTORS_IDS_FOR_IDS = """ SELECT DISTINCT a.id FROM notes n, notes a WHERE n.id IN (:ids) AND n.book_id = a.book_id AND a.is_cut = 0 AND a.level > 0 AND a.lft <= n.lft AND n.rgt <= a.rgt """ @Language("RoomSql") private const val SELECT_SUBTREE_FOR_IDS = """ SELECT d.* FROM notes n, notes d WHERE n.id IN (:ids) AND n.level > 0 AND d.book_id = n.book_id AND d.is_cut = 0 AND n.is_cut = 0 AND n.lft <= d.lft AND d.rgt <= n.rgt GROUP BY d.id ORDER BY d.lft """ @Language("RoomSql") private const val SELECT_SUBTREE_IDS_FOR_IDS = """ SELECT DISTINCT d.id FROM notes n, notes d WHERE n.id IN (:ids) AND d.book_id = n.book_id AND d.is_cut = 0 AND n.lft <= d.lft AND d.rgt <= n.rgt """ @Language("RoomSql") private const val SELECT_DESCENDANTS_IDS_FOR_IDS = """ SELECT DISTINCT d.id FROM notes n, notes d WHERE n.id IN (:ids) AND d.book_id = n.book_id AND d.is_cut = 0 AND n.lft < d.lft AND d.rgt < n.rgt """ fun rootNote(bookId: Long): Note { return Note(id = 0, position = NotePosition(bookId, lft = 1, rgt = 2, level = 0)) } } data class NoteIdBookId(val noteId: Long, val bookId: Long) data class NoteForStateUpdate( val noteId: Long, val state: String?, val title: String, val content: String?, val scheduled: String?, val deadline: String?) }
gpl-3.0
4240727706bcfb23a4b3c27cf466204a
36.330986
193
0.614412
3.748056
false
false
false
false
soeminnminn/EngMyanDictionary
app/src/main/java/com/s16/engmyan/adapters/FavoriteListAdapter.kt
1
3889
package com.s16.engmyan.adapters import android.content.Context import android.graphics.drawable.Drawable import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Checkable import android.widget.CheckedTextView import com.s16.engmyan.R import com.s16.engmyan.data.FavoriteItem import com.s16.view.LongClickSelectable import com.s16.view.RecyclerViewArrayAdapter import com.s16.view.SelectableViewHolder class FavoriteListAdapter : RecyclerViewArrayAdapter<FavoriteListAdapter.FavoriteItemHolder, FavoriteItem>(), LongClickSelectable { interface OnItemSelectListener { fun onItemSelectStart() fun onItemSelectionChange(position: Int, count: Int) } interface OnItemClickListener { fun onItemClick(view: View, id: Long, position: Int) } private var mItemClickListener: OnItemClickListener? = null private var mItemSelectListener: OnItemSelectListener? = null private val mCheckedItems: MutableList<FavoriteItem> = mutableListOf() private var mSelectMode = false val hasSelectedItems: Boolean get() = mCheckedItems.size > 0 private fun getCheckMarkDrawable(context: Context): Drawable? { val attrs = intArrayOf(android.R.attr.listChoiceIndicatorMultiple) val ta = context.theme.obtainStyledAttributes(attrs) val drawable = ta.getDrawable(0) ta.recycle() return drawable } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): FavoriteItemHolder { val view = LayoutInflater.from(parent.context).inflate(R.layout.list_item_selectable, parent, false) return FavoriteItemHolder(view, this) } override fun onBindViewHolder(holder: FavoriteItemHolder, item: FavoriteItem) { val textView : CheckedTextView = holder.findViewById(android.R.id.text1) textView.text = item.word textView.isChecked = mCheckedItems.count { d -> d.id == item.id } > 0 if (isSelectedMode()) { textView.checkMarkDrawable = getCheckMarkDrawable(textView.context) } else { textView.checkMarkDrawable = null } } fun setItemClickListener(listener: OnItemClickListener) { mItemClickListener = listener; } fun setItemSelectListener(listener: OnItemSelectListener) { mItemSelectListener = listener; } override fun onItemClick(view: View, position: Int) { if (mItemClickListener != null) { getItem(position)?.let { item -> mItemClickListener!!.onItemClick(view, item.refId!!, position) } } } override fun setSelectMode(mode: Boolean) { mSelectMode = mode notifyDataSetChanged() } override fun isSelectedMode(): Boolean = mSelectMode override fun onSelectStart() { if (!mSelectMode && mItemSelectListener != null) { mItemSelectListener!!.onItemSelectStart() } } override fun onSelectionChange(position: Int, checked: Boolean) { getItem(position)?.let { item -> if (checked) { if (!mCheckedItems.contains(item)) mCheckedItems.add(item) } else { if (mCheckedItems.contains(item)) mCheckedItems.remove(item) } if (mItemSelectListener != null) { mItemSelectListener!!.onItemSelectionChange(position, mCheckedItems.size) } } } fun getSelectedItems(): List<FavoriteItem> = mCheckedItems fun endSelection() { mSelectMode = false mCheckedItems.clear() notifyDataSetChanged() } class FavoriteItemHolder(view: View, adapter: LongClickSelectable) : SelectableViewHolder(view, adapter) { override fun getCheckableView(): Checkable = findViewById<CheckedTextView>(android.R.id.text1) } }
gpl-2.0
80f53f2e9ab7da1d04484a2311aee04e
31.689076
110
0.682952
4.783518
false
false
false
false
openbase/jul
module/communication/mqtt/src/main/java/org/openbase/jul/communication/mqtt/RPCClientImpl.kt
1
4917
package org.openbase.jul.communication.mqtt import com.hivemq.client.mqtt.datatypes.MqttQos import com.hivemq.client.mqtt.mqtt5.message.publish.Mqtt5Publish import com.hivemq.client.mqtt.mqtt5.message.subscribe.Mqtt5Subscribe import com.hivemq.client.mqtt.mqtt5.message.unsubscribe.Mqtt5Unsubscribe import org.openbase.jul.communication.config.CommunicatorConfig import org.openbase.jul.communication.data.RPCResponse import org.openbase.jul.communication.exception.RPCException import org.openbase.jul.communication.exception.RPCResolvedException import org.openbase.jul.communication.iface.RPCClient import org.openbase.jul.schedule.GlobalCachedExecutorService import org.openbase.type.communication.ScopeType import org.openbase.type.communication.mqtt.RequestType.Request import org.openbase.type.communication.mqtt.ResponseType.Response import java.util.* import java.util.concurrent.CompletableFuture import java.util.concurrent.Future import kotlin.Any import kotlin.reflect.KClass import com.google.protobuf.Any as protoAny class RPCClientImpl( scope: ScopeType.Scope, config: CommunicatorConfig ) : RPCCommunicatorImpl(scope, config), RPCClient { private val parameterParserMap: HashMap<String, List<(Any) -> protoAny>> = HashMap() private val resultParserMap: HashMap<String, (protoAny) -> Any> = HashMap() private var active = false override fun <RETURN : Any> callMethod( methodName: String, return_clazz: KClass<RETURN>, vararg parameters: Any ): Future<RPCResponse<RETURN>> { lazyRegisterMethod(methodName, return_clazz, *parameters) val request = generateRequest(methodName, *parameters) val rpcFuture: CompletableFuture<RPCResponse<RETURN>> = CompletableFuture(); mqttClient.subscribe( Mqtt5Subscribe.builder() .topicFilter("$topic/${request.id}") .qos(MqttQos.EXACTLY_ONCE) .build(), { mqtt5Publish: Mqtt5Publish -> handleRPCResponse(mqtt5Publish, rpcFuture, request) }, GlobalCachedExecutorService.getInstance().executorService ).whenComplete { _, throwable -> if (throwable != null) { rpcFuture.completeExceptionally(throwable) } else { mqttClient.publish( Mqtt5Publish.builder() .topic(topic) .qos(MqttQos.EXACTLY_ONCE) .payload(request.toByteArray()) .attachTimestamp() .build() ) } } return rpcFuture } override fun activate() { active = true } override fun deactivate() { active = false } override fun isActive(): Boolean { return active } private fun <RETURN> handleRPCResponse( mqtt5Publish: Mqtt5Publish, rpcFuture: CompletableFuture<RPCResponse<RETURN>>, request: Request ) { val response = Response.parseFrom(mqtt5Publish.payloadAsBytes) if (response.error.isEmpty() && response.status != Response.Status.FINISHED) { //TODO update timeout for coroutine which checks if server is still active return } mqttClient.unsubscribe( Mqtt5Unsubscribe.builder() .topicFilter("$topic/${request.id}") .build() ) if (response.error.isNotEmpty()) { rpcFuture.completeExceptionally(RPCResolvedException(RPCException(response.error))) } else { rpcFuture.complete( RPCResponse( response = resultParserMap[request.methodName]!!(response.result) as RETURN, properties = mqtt5Publish .userProperties .asList() .associate { it.name.toString() to it.value.toString() } ) ) } } private fun lazyRegisterMethod(methodName: String, return_clazz: KClass<*>, vararg parameters: Any) { resultParserMap.getOrPut(methodName) { RPCMethod.protoAnyToAny(return_clazz) } parameterParserMap.getOrPut(methodName) { parameters .map { param -> param::class } .map { param_clazz -> RPCMethod.anyToProtoAny(param_clazz) } } } fun generateRequestId(): String { return UUID.randomUUID().toString() } private fun generateRequest(methodName: String, vararg parameters: Any): Request { return Request.newBuilder() .setId(generateRequestId()) .setMethodName(methodName) .addAllParams(parameters .asList() .zip(parameterParserMap[methodName]!!) .map { (param, parser) -> parser(param) }) .build() } }
lgpl-3.0
5e3bcb83783981af2ebf629b5e079948
35.69403
105
0.630872
4.764535
false
false
false
false
AlmasB/FXGL
fxgl-core/src/main/kotlin/com/almasb/fxgl/localization/Language.kt
1
2772
/* * FXGL - JavaFX Game Library. The MIT License (MIT). * Copyright (c) AlmasB ([email protected]). * See LICENSE for details. */ package com.almasb.fxgl.localization /** * @author Almas Baimagambetov ([email protected]) */ class Language @JvmOverloads constructor( /** * In English. */ name: String, /** * In the target language. */ val nativeName: String = name) { val name = name.uppercase() companion object { // this language list is a cross-reference adaptation of Android 10 and iOS 13 languages // it will grow as the community members add new languages and translations @JvmField val NONE = Language("NONE") @JvmField val ARABIC = Language("ARABIC") @JvmField val CATALAN = Language("CATALAN") @JvmField val CHINESE = Language("CHINESE") @JvmField val CROATIAN = Language("CROATIAN") @JvmField val CZECH = Language("CZECH") @JvmField val DANISH = Language("DANISH") @JvmField val DUTCH = Language("DUTCH") @JvmField val ENGLISH = Language("ENGLISH") @JvmField val ESTONIAN = Language("ESTONIAN") @JvmField val FILIPINO = Language("FILIPINO") @JvmField val FINNISH = Language("FINNISH") @JvmField val FRENCH = Language("FRENCH", "Français") @JvmField val GERMAN = Language("GERMAN", "Deutsch") @JvmField val GREEK = Language("GREEK") @JvmField val HEBREW = Language("HEBREW") @JvmField val HINDI = Language("HINDI") @JvmField val HUNGARIAN = Language("HUNGARIAN", "Magyar") @JvmField val INDONESIAN = Language("INDONESIAN") @JvmField val ITALIAN = Language("ITALIAN") @JvmField val JAPANESE = Language("JAPANESE") @JvmField val KOREAN = Language("KOREAN") @JvmField val MALAY = Language("MALAY") @JvmField val NORWEGIAN = Language("NORWEGIAN") @JvmField val PORTUGUESE = Language("PORTUGUESE") @JvmField val ROMANIAN = Language("ROMANIAN") @JvmField val RUSSIAN = Language("RUSSIAN", "Русский") @JvmField val SLOVAK = Language("SLOVAK") @JvmField val SPANISH = Language("SPANISH") @JvmField val SWEDISH = Language("SWEDISH") @JvmField val THAI = Language("THAI") @JvmField val TURKISH = Language("TURKISH") @JvmField val UKRAINIAN = Language("UKRAINIAN") @JvmField val VIETNAMESE = Language("VIETNAMESE") } override fun equals(other: Any?): Boolean { if (other !is Language) return false return other.name == name } override fun hashCode(): Int { return name.hashCode() } override fun toString(): String = name }
mit
9417271d9ce8f2cde3dfcf49ce274d42
33.5625
96
0.621201
4.040936
false
false
false
false
AlmasB/FXGL
fxgl-core/src/main/kotlin/com/almasb/fxgl/texture/ScrollingView.kt
1
2996
/* * FXGL - JavaFX Game Library. The MIT License (MIT). * Copyright (c) AlmasB ([email protected]). * See LICENSE for details. */ package com.almasb.fxgl.texture import com.almasb.fxgl.core.View import javafx.geometry.Orientation import javafx.scene.Node import javafx.scene.Parent import javafx.scene.canvas.Canvas import javafx.scene.image.Image /** * View that that can be infinitely scrolled either horizontally or vertically. * Useful for side-scrolling backgrounds. * * @author Almas Baimagambetov ([email protected]) */ open class ScrollingView @JvmOverloads constructor( /** * The full image to be used for scrolling over. */ private val image: Image, /** * Width of this view. */ viewWidth: Double = image.width, /** * Height of this view. */ viewHeight: Double = image.height, /** * The direction of scroll. */ val orientation: Orientation = Orientation.HORIZONTAL, ) : Parent(), View { private val canvas = Canvas(viewWidth, viewHeight) private val g = canvas.graphicsContext2D // image source coordinates, never negative values private var sx = 0.0 private var sy = 0.0 // semantic scroll coordinates, can be negative var scrollX = 0.0 set(value) { field = value sx = value % image.width if (sx < 0) sx += image.width redraw() } var scrollY = 0.0 set(value) { field = value sy = value % image.height if (sy < 0) sy += image.height redraw() } init { children += canvas redraw() } private fun redraw() { g.clearRect(0.0, 0.0, canvas.width, canvas.height) if (orientation == Orientation.HORIZONTAL) { redrawX() } else { redrawY() } } private fun redrawX() { var w = canvas.width val h = canvas.height val overflowX = sx + w > image.width if (overflowX) { w = image.width - sx } g.drawImage(image, sx, sy, w, h, 0.0, 0.0, w, h) if (overflowX) { g.drawImage(image, 0.0, 0.0, canvas.width - w, h, w, 0.0, canvas.width - w, h) } } private fun redrawY() { val w = canvas.width var h = canvas.height val overflowY = sy + h > image.height if (overflowY) { h = image.height - sy } g.drawImage(image, sx, sy, w, h, 0.0, 0.0, w, h) if (overflowY) { g.drawImage(image, 0.0, 0.0, w, canvas.height - h, 0.0, h, w, canvas.height - h) } } override fun onUpdate(tpf: Double) { } override fun getNode(): Node { return this } override fun dispose() { } }
mit
235e3102f96660a3eff3f32b89bc5c2c
20.4
79
0.525033
4.048649
false
false
false
false
Ch3D/QuickTiles
app/src/main/java/com/ch3d/android/quicktiles/ScreenTimeoutTileService.kt
1
2282
package com.ch3d.android.quicktiles import android.provider.Settings import android.provider.Settings.System.SCREEN_OFF_TIMEOUT import android.provider.Settings.System.putInt import android.service.quicksettings.Tile import java.util.concurrent.TimeUnit /** * Created by Dmitry on 4/5/2016. */ class ScreenTimeoutTileService : BaseTileService(ScreenTimeoutTileService.DISABLED) { private val screenTimeOut: Int get() = Settings.System.getInt(contentResolver, SCREEN_OFF_TIMEOUT, DELAY_DISABLED) override fun updateTile(tile: Tile) { when (screenTimeOut) { DELAY_DISABLED -> mCurrentState = DISABLED DELAY_INTERMEDIATE -> mCurrentState = INTERMEDIATE DELAY_ENABLED -> mCurrentState = ENABLED else -> mCurrentState = DISABLED } updateState(tile, mCurrentState) } override fun onTileClick(tile: Tile) = when (mCurrentState.primaryValue) { DELAY_DISABLED -> updateState(tile, INTERMEDIATE) DELAY_INTERMEDIATE -> updateState(tile, ENABLED) DELAY_ENABLED -> updateState(tile, DISABLED) else -> Unit } override fun setMode(state: TileState) = putInt(contentResolver, SCREEN_OFF_TIMEOUT, state.primaryValue) companion object { private val DELAY_DISABLED = TimeUnit.SECONDS.toMillis(15).toInt() private val DELAY_INTERMEDIATE = TimeUnit.MINUTES.toMillis(1).toInt() private val DELAY_ENABLED = TimeUnit.MINUTES.toMillis(2).toInt() val ENABLED = TileState(Tile.STATE_ACTIVE, R.drawable.vector_tile_timeout_enabled, DELAY_ENABLED, BaseTileService.DEFAULT_VALUE, R.string.state_timeout_enabled) val INTERMEDIATE = TileState(Tile.STATE_ACTIVE, R.drawable.vector_tile_timeout_intermediate, DELAY_INTERMEDIATE, BaseTileService.DEFAULT_VALUE, R.string.state_timeout_internediate) val DISABLED = TileState(Tile.STATE_INACTIVE, R.drawable.vector_tile_timeout_disabled, DELAY_DISABLED, BaseTileService.DEFAULT_VALUE, R.string.state_timeout_disabled) } }
apache-2.0
b6254f6f2374f118057bf6955938b78d
37.033333
108
0.650307
4.685832
false
true
false
false
elect86/modern-jogl-examples
src/main/kotlin/glNext/sampler.kt
2
3059
package glNext import com.jogamp.opengl.GL import com.jogamp.opengl.GL2ES3 import com.jogamp.opengl.GL3 import java.nio.IntBuffer /** * Created by GBarbieri on 12.04.2017. */ fun GL3.glGenSampler(sampler: IntBuffer) = glGenSamplers(1, sampler) fun GL3.glGenSamplers(samplers: IntBuffer) = glGenSamplers(samplers.capacity(), samplers) fun GL3.glDeleteSampler(sampler: IntBuffer) = glDeleteSamplers(1, sampler) fun GL3.glDeleteSamplers(samplers: IntBuffer) = glDeleteSamplers(samplers.capacity(), samplers) fun GL3.glSamplerParameteri(sampler: IntBuffer, pname: Int, param: Int) = glSamplerParameteri(sampler[0], pname, param) fun GL3.glBindSampler(unit: Int, sampler: IntBuffer) = glBindSampler(unit, sampler[0]) fun GL3.glBindSampler(unit: Int) = glBindSampler(unit, 0) fun GL3.initSampler(sampler: IntBuffer, block: Sampler.() -> Unit) { glGenSamplers(1, sampler) Sampler.gl = this Sampler.name = sampler[0] Sampler.block() } object Sampler { lateinit var gl: GL3 var name = 0 val linear = Filer.linear val nearest = Filer.nearest val nearest_mmNearest = Filer.nearest_mmNearest val linear_mmNearest = Filer.linear_mmNearest val nearest_mmLinear = Filer.nearest_mmLinear val linear_mmLinear = Filer.linear_mmLinear val clampToEdge = Wrap.clampToEdge val mirroredRepeat = Wrap.mirroredRepeat val repeat = Wrap.repeat var magFilter = linear set(value) { gl.glSamplerParameteri(name, GL2ES3.GL_TEXTURE_MAG_FILTER, value.i) field = value } var minFilter = nearest_mmLinear set(value) { gl.glSamplerParameteri(name, GL2ES3.GL_TEXTURE_MIN_FILTER, value.i) field = value } var maxAnisotropy = 1.0f set(value) { gl.glSamplerParameterf(name, GL2ES3.GL_TEXTURE_MAX_ANISOTROPY_EXT, value) field = value } var wrapS = repeat set(value) { gl.glSamplerParameteri(name, GL.GL_TEXTURE_WRAP_S, value.i) field = value } var wrapT = repeat set(value) { gl.glSamplerParameteri(name, GL.GL_TEXTURE_WRAP_T, value.i) field = value } enum class Filer(val i: Int) {nearest(GL.GL_NEAREST), linear(GL.GL_LINEAR), nearest_mmNearest(GL.GL_NEAREST_MIPMAP_NEAREST), linear_mmNearest(GL.GL_LINEAR_MIPMAP_NEAREST), nearest_mmLinear(GL.GL_NEAREST_MIPMAP_LINEAR), linear_mmLinear(GL.GL_LINEAR_MIPMAP_LINEAR) } enum class Wrap(val i: Int) {clampToEdge(GL.GL_CLAMP_TO_EDGE), mirroredRepeat(GL.GL_MIRRORED_REPEAT), repeat(GL.GL_REPEAT) } } fun GL3.initSamplers(samplers: IntBuffer, block: Samplers.() -> Unit) { glGenSamplers(samplers.capacity(), samplers) Samplers.gl = this Samplers.names = samplers Samplers.block() } object Samplers { lateinit var gl: GL3 lateinit var names: IntBuffer fun at(index: Int, block: Sampler.() -> Unit) { Sampler.gl = gl Sampler.name = names[index] // bind Sampler.block() } }
mit
09948ae9228802c9f0495403ea9d9272
29.6
128
0.671788
3.556977
false
false
false
false
nickthecoder/tickle
tickle-editor/src/main/kotlin/uk/co/nickthecoder/tickle/editor/scene/SnapEditor.kt
1
2646
/* Tickle Copyright (C) 2017 Nick Robinson This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package uk.co.nickthecoder.tickle.editor.scene import javafx.event.EventHandler import javafx.scene.Scene import javafx.scene.control.Button import javafx.scene.layout.BorderPane import javafx.scene.layout.FlowPane import javafx.stage.Stage import uk.co.nickthecoder.paratask.ParaTask import uk.co.nickthecoder.paratask.gui.MyTab import uk.co.nickthecoder.paratask.gui.MyTabPane import uk.co.nickthecoder.paratask.parameters.fields.TaskForm class SnapEditor(val snapTos: Map<String, HasTask>) { val whole = BorderPane() val tabPane = MyTabPane<MyTab>() val buttons = FlowPane() val okButton = Button("Ok") val cancelButton = Button("Cancel") val taskForms = mutableListOf<TaskForm>() val stage = Stage() fun show() { with(okButton) { okButton.onAction = EventHandler { onOk() } okButton.isDefaultButton = true } with(cancelButton) { cancelButton.onAction = EventHandler { onCancel() } cancelButton.isCancelButton = true } with(buttons) { children.addAll(okButton, cancelButton) styleClass.add("buttons") } snapTos.forEach { name, snapTo -> val form = TaskForm(snapTo.task()) tabPane.add(MyTab(name, form.build())) taskForms.add(form) } with(whole) { center = tabPane bottom = buttons } val scene = Scene(whole) ParaTask.style(scene) with(stage) { title = "Snapping" this.scene = scene centerOnScreen() show() } } fun onOk() { try { taskForms.forEach { form -> form.check() } taskForms.forEach { form -> form.task.run() } } catch (e: Exception) { // Do nothing } } fun onCancel() { stage.close() } }
gpl-3.0
5157d799404cbd86255f1a3d3b5d2c0a
24.68932
69
0.624339
4.373554
false
false
false
false
YiiGuxing/TranslationPlugin
src/main/kotlin/cn/yiiguxing/plugin/translate/ui/CheckRegExpDialog.kt
1
1820
package cn.yiiguxing.plugin.translate.ui import cn.yiiguxing.plugin.translate.message import com.intellij.openapi.editor.Document import com.intellij.openapi.editor.event.DocumentEvent import com.intellij.openapi.editor.event.DocumentListener import com.intellij.openapi.project.Project import com.intellij.openapi.ui.DialogWrapper import com.intellij.psi.PsiDocumentManager import com.intellij.psi.PsiFile import com.intellij.psi.PsiFileFactory import org.intellij.lang.regexp.RegExpLanguage import org.intellij.lang.regexp.intention.CheckRegExpForm import javax.swing.Action import javax.swing.JComponent /** * CheckRegExpDialog */ class CheckRegExpDialog(project: Project, regExp: String, private val ok: (String) -> Unit) : DialogWrapper(project) { private val regExpPsiFile: PsiFile private val document: Document private val checkRegExpForm: CheckRegExpForm init { title = message("settings.check.regex.title") isResizable = false regExpPsiFile = PsiFileFactory.getInstance(project).createFileFromText(RegExpLanguage.INSTANCE, regExp) document = PsiDocumentManager.getInstance(project).getDocument(regExpPsiFile)!! val documentManager = PsiDocumentManager.getInstance(project) document.addDocumentListener(object : DocumentListener { override fun documentChanged(e: DocumentEvent) { documentManager.commitDocument(e.document) } }, disposable) checkRegExpForm = CheckRegExpForm(regExpPsiFile) init() } override fun createCenterPanel(): JComponent = checkRegExpForm.rootPanel override fun createActions(): Array<Action> = arrayOf(okAction, cancelAction) override fun doOKAction() { regExpPsiFile.text?.let { ok(it) } super.doOKAction() } }
mit
8a996171ff232cdcc200f8ccceb6b69f
33.358491
118
0.750549
4.666667
false
false
false
false
ujpv/intellij-rust
toml/src/main/kotlin/org/toml/ide/TomlCommenter.kt
4
396
package org.toml.ide import com.intellij.lang.Commenter class TomlCommenter : Commenter { override fun getLineCommentPrefix(): String = "#" override fun getBlockCommentPrefix(): String? = null override fun getBlockCommentSuffix(): String? = null override fun getCommentedBlockCommentPrefix(): String? = null override fun getCommentedBlockCommentSuffix(): String? = null }
mit
91e2cb30d8553c9fe95cf92c32fe5e14
29.461538
65
0.75
5.210526
false
false
false
false
angcyo/RLibrary
uiview/src/main/java/com/angcyo/uiview/kotlin/ViewGroupEx.kt
1
7262
package com.angcyo.uiview.kotlin import android.app.Activity import android.graphics.Rect import android.support.v7.widget.RecyclerView import android.view.* import android.widget.EditText import com.angcyo.uiview.widget.RSoftInputLayout /** * Kotlin ViewGroup的扩展 * Created by angcyo on 2017-07-26. */ /** * 计算child在parent中的位置坐标, 请确保child在parent中. * */ public fun ViewGroup.getLocationInParent(child: View, location: Rect) { var x = 0 var y = 0 var view = child while (view.parent != this) { x += view.left y += view.top view = view.parent as View } x += view.left y += view.top location.set(x, y, x + child.measuredWidth, y + child.measuredHeight) } /**返回当软键盘弹出时, 布局向上偏移了多少距离*/ public fun View.getLayoutOffsetTopWidthSoftInput(): Int { val rect = Rect() var offsetTop = 0 try { val activity = this.context as Activity val softInputMode = activity.window.attributes.softInputMode if (softInputMode == WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN) { val keyboardHeight = RSoftInputLayout.getSoftKeyboardHeight(this) /**在ADJUST_PAN模式下, 键盘弹出时, 坐标需要进行偏移*/ if (keyboardHeight > 0) { //return targetView val findFocus = this.findFocus() if (findFocus is EditText) { findFocus.getWindowVisibleDisplayFrame(rect) offsetTop = findFocus.bottom - rect.bottom } } } } catch (e: Exception) { } return offsetTop } /**获取touch坐标对应的RecyclerView, 如果没有则null*/ public fun ViewGroup.getTouchOnRecyclerView(touchRawX: Float, touchRawY: Float): RecyclerView? { return findRecyclerView(this, touchRawX, touchRawY, getLayoutOffsetTopWidthSoftInput()) } /** * 根据touch坐标, 返回touch的View */ public fun ViewGroup.findView(event: MotionEvent): View? { return findView(this, event.rawX, event.rawY, getLayoutOffsetTopWidthSoftInput()) } public fun ViewGroup.findView(touchRawX: Float, touchRawY: Float): View? { return findView(this, touchRawX, touchRawY, getLayoutOffsetTopWidthSoftInput()) } public fun ViewGroup.findView(targetView: View /*判断需要结果的View*/, touchRawX: Float, touchRawY: Float, offsetTop: Int = 0): View? { /**键盘的高度*/ var touchView: View? = targetView val rect = Rect() for (i in childCount - 1 downTo 0) { val childAt = getChildAt(i) if (childAt.visibility != View.VISIBLE) { continue } // childAt.getWindowVisibleDisplayFrame(rect) // L.e("${this}:1 ->$i $rect") childAt.getGlobalVisibleRect(rect) // L.e("${this}:2 ->$i $rect") // L.e("call: ------------------end -> ") rect.offset(0, -offsetTop) fun check(view: View): View? { if (view.visibility == View.VISIBLE && view.measuredHeight != 0 && view.measuredWidth != 0 && (view.left != view.right) && (view.top != view.bottom) && rect.contains(touchRawX.toInt(), touchRawY.toInt())) { return view } return null } if (childAt is ViewGroup && childAt.childCount > 0) { val resultView = childAt.findView(targetView, touchRawX, touchRawY, offsetTop) if (resultView != null && resultView != targetView) { touchView = resultView break } else { val check = check(childAt) if (check != null) { touchView = childAt break } } } else { val check = check(childAt) if (check != null) { touchView = childAt break } } } return touchView } public fun ViewGroup.findRecyclerView(targetView: View /*判断需要结果的View*/, touchRawX: Float, touchRawY: Float, offsetTop: Int = 0): RecyclerView? { /**键盘的高度*/ var touchView: RecyclerView? = null val rect = Rect() for (i in childCount - 1 downTo 0) { val childAt = getChildAt(i) if (childAt.visibility != View.VISIBLE) { continue } childAt.getGlobalVisibleRect(rect) rect.offset(0, -offsetTop) fun check(view: View): View? { if (view.visibility == View.VISIBLE && view.measuredHeight != 0 && view.measuredWidth != 0 && (view.left != view.right) && (view.top != view.bottom) && rect.contains(touchRawX.toInt(), touchRawY.toInt())) { return view } return null } if (childAt is RecyclerView) { val check = check(childAt) if (check != null) { touchView = childAt break } } else if (childAt is ViewGroup && childAt.childCount > 0) { val resultView = childAt.findRecyclerView(targetView, touchRawX, touchRawY, offsetTop) if (resultView != null) { touchView = resultView break } } } return touchView } /**将子View的数量, 重置到指定的数量*/ public fun ViewGroup.resetChildCount(newSize: Int, onAddView: () -> View) { val oldSize = childCount val count = newSize - oldSize if (count > 0) { //需要补充子View for (i in 0 until count) { addView(onAddView.invoke()) } } else if (count < 0) { //需要移除子View for (i in 0 until count.abs()) { removeViewAt(oldSize - 1 - i) } } } /**动态添加View, 并初始化 (做了性能优化)*/ public fun <T> ViewGroup.addView(datas: List<T>, onAddViewCallback: OnAddViewCallback<T>) { addView(datas.size, datas, onAddViewCallback) } public fun <T> ViewGroup.addView(size: Int, datas: List<T>, onAddViewCallback: OnAddViewCallback<T>) { this.resetChildCount(size, { val layoutId = onAddViewCallback.getLayoutId() if (layoutId > 0) { LayoutInflater.from(context).inflate(layoutId, this, false) } else onAddViewCallback.getView()!! }) for (i in 0 until size) { onAddViewCallback.onInitView(getChildAt(i), if (i < datas.size) datas[i] else null, i) } } /**枚举所有child view*/ public fun ViewGroup.childs(map: (Int, View) -> Unit) { for (i in 0 until childCount) { val childAt = getChildAt(i) map.invoke(i, childAt) } } abstract class OnAddViewCallback<T> { open fun getLayoutId(): Int = -1 open fun getView(): View? = null open fun onInitView(view: View, data: T?, index: Int) { } }
apache-2.0
7bd88d89cec6f6b850e32bd05d4c5ea0
28.920354
144
0.55282
4.073469
false
false
false
false
Jachu5/Koans
src/i_introduction/_3_Lambdas/Lambdas.kt
1
1044
package i_introduction._3_Lambdas import util.TODO import com.google.common.collect.Iterables fun examples() { val sum = { x: Int, y: Int -> x + y } val three = sum(1, 2) fun apply(i: Int, f: (Int) -> Unit) = f(i) apply(2, { x -> x + 25 }) //you can omit round brackets if lambda is the last argument apply(2) { x -> x + 25 } fun applyToStrangeArguments(f: (Int, Int) -> Int) = f(938, 241) applyToStrangeArguments(sum) applyToStrangeArguments({ x, y -> x + y }) applyToStrangeArguments() { x, y -> x + y } applyToStrangeArguments { x, y -> x + y } } fun todoTask3(collection: Collection<Int>) = TODO( """ Task 3. Rewrite 'JavaCode3.task3()' to Kotlin using lambdas. Please find the appropriate function on collection through completion. (Don't use the class 'Iterables'). """, references = { JavaCode3().task3(collection) }) fun task3(collection: Collection<Int>): Boolean { return collection.map({x -> x % 42 == 0}).contains(true) }
mit
18f5c2c45eaa5a0fb7819c2d87802df4
22.2
78
0.610153
3.55102
false
false
false
false
kotlintest/kotlintest
kotest-assertions/src/commonMain/kotlin/io/kotest/matchers/Diff.kt
1
4387
package io.kotest.matchers sealed class Diff { abstract fun isEmpty(): Boolean abstract fun toString(level: Int): String override fun toString(): String = toString(level = 0) protected fun getIndent(level: Int): String = " ".repeat(2 * level) companion object { fun create(value: Any?, expected: Any?, ignoreExtraMapKeys: Boolean = false): Diff { return when { value is Map<*, *> && expected is Map<*, *> -> { val missingKeys = ArrayList<Any?>() val extraKeys = ArrayList<Any?>() val differentValues = ArrayList<Diff>() expected.forEach { (k, v) -> if (!value.containsKey(k)) { missingKeys.add(k) } else if (value[k] != v) { differentValues.add(MapValues(k, create(value[k], v, ignoreExtraMapKeys = ignoreExtraMapKeys)) ) } } if (!ignoreExtraMapKeys) { value.keys.forEach { k -> if (!expected.containsKey(k)) { extraKeys.add(k) } } } Maps(missingKeys, extraKeys, differentValues) } else -> { Values(value, expected) } } } } class Values( private val value: Any?, private val expected: Any? ) : Diff() { override fun isEmpty(): Boolean = value == expected override fun toString(level: Int): String { return """ |expected: | ${stringify(expected)} |but was: | ${stringify(value)} """.replaceIndentByMargin(getIndent(level)) } } class MapValues( private val key: Any?, private val valueDiff: Diff ) : Diff() { override fun isEmpty(): Boolean = valueDiff.isEmpty() override fun toString(level: Int): String { return """ |${getIndent(level)}${stringify(key)}: |${valueDiff.toString(level + 1)} """.trimMargin() } } class Maps( private val missingKeys: List<Any?>, private val extraKeys: List<Any?>, private val differentValues: List<Diff> ) : Diff() { override fun isEmpty(): Boolean { return missingKeys.isEmpty() && extraKeys.isEmpty() && differentValues.isEmpty() } override fun toString(level: Int): String { val diffValues = differentValues.map { it.toString(level + 1) } return listOf( "missing keys" to missingKeys.map { getIndent(level + 1) + stringify(it) }, "extra keys" to extraKeys.map { getIndent(level + 1) + stringify(it) }, "different values" to diffValues ).filter { it.second.isNotEmpty() }.joinToString("\n") { """ |${getIndent(level)}${it.first}: |${it.second.joinToString("\n")} """.trimMargin() } } } } internal fun stringify(value: Any?): String = when (value) { null -> "null" is String -> "\"${escapeString(value)}\"" is Int -> "$value" is Double -> "$value" is Char -> "'${escapeString(value.toString())}'" is Byte -> "$value.toByte()" is Short -> "$value.toShort()" is Long -> "${value}L" is Float -> "${value}F" is Map<*, *> -> { value.entries.joinToString(prefix = "mapOf(", postfix = ")") { "${stringify(it.key)} to ${stringify(it.value)}" } } is List<*> -> reprCollection("listOf", value) is Set<*> -> reprCollection("setOf", value) is Array<*> -> reprCollection("arrayOf", value.asList()) is ByteArray -> reprCollection("byteArrayOf", value.asList()) is ShortArray -> reprCollection("shortArrayOf", value.asList()) is IntArray -> reprCollection("intArrayOf", value.asList()) is LongArray -> reprCollection("longArrayOf", value.asList()) is FloatArray -> reprCollection("floatArrayOf", value.asList()) is DoubleArray -> reprCollection("doubleArrayOf", value.asList()) is CharArray -> reprCollection("charArrayOf", value.asList()) else -> value.toString() } private fun reprCollection(funcName: String, value: Collection<*>): String { return value.joinToString(prefix = "$funcName(", postfix = ")") { stringify(it) } } private fun escapeString(s: String): String { return s .replace("\\", "\\\\") .replace("\"", "\\\"") .replace("\'", "\\\'") .replace("\t", "\\\t") .replace("\b", "\\\b") .replace("\n", "\\\n") .replace("\r", "\\\r") .replace("\$", "\\\$") }
apache-2.0
8fcc1d23b55085e7132274573755a620
29.047945
108
0.56827
4.146503
false
false
false
false
jitsi/jitsi-videobridge
jitsi-media-transform/src/main/kotlin/org/jitsi/nlj/dtls/DtlsClient.kt
1
2184
/* * Copyright @ 2018 - present 8x8, 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 org.jitsi.nlj.dtls import org.bouncycastle.tls.Certificate import org.bouncycastle.tls.DTLSClientProtocol import org.bouncycastle.tls.DTLSTransport import org.bouncycastle.tls.DatagramTransport import org.jitsi.nlj.srtp.TlsRole import org.jitsi.utils.logging2.Logger import org.jitsi.utils.logging2.cdebug import org.jitsi.utils.logging2.cerror import org.jitsi.utils.logging2.createChildLogger class DtlsClient( private val datagramTransport: DatagramTransport, certificateInfo: CertificateInfo, private val handshakeCompleteHandler: (Int, TlsRole, ByteArray) -> Unit = { _, _, _ -> }, verifyAndValidateRemoteCertificate: (Certificate?) -> Unit = {}, parentLogger: Logger, private val dtlsClientProtocol: DTLSClientProtocol = DTLSClientProtocol() ) : DtlsRole { private val logger = createChildLogger(parentLogger) private val tlsClient: TlsClientImpl = TlsClientImpl(certificateInfo, verifyAndValidateRemoteCertificate, logger) override fun start(): DTLSTransport = connect() fun connect(): DTLSTransport { try { return dtlsClientProtocol.connect(this.tlsClient, datagramTransport).also { logger.cdebug { "DTLS handshake finished" } handshakeCompleteHandler( tlsClient.chosenSrtpProtectionProfile, TlsRole.CLIENT, tlsClient.srtpKeyingMaterial ) } } catch (e: Exception) { logger.cerror { "Error during DTLS connection: $e" } throw e } } }
apache-2.0
cf18704e87339bf7abcde5a1461b0cc6
36.655172
117
0.70467
4.25731
false
false
false
false
yschimke/oksocial
src/main/kotlin/com/baulsupp/okurl/tracing/ZipkinTracingListener.kt
1
6282
package com.baulsupp.okurl.tracing import brave.Span import brave.Tracer import brave.http.HttpTracing import brave.propagation.TraceContext import okhttp3.Call import okhttp3.Connection import okhttp3.EventListener import okhttp3.Handshake import okhttp3.Protocol import okhttp3.Request import okhttp3.Response import java.io.IOException import java.net.InetAddress import java.net.InetSocketAddress import java.net.Proxy import java.util.function.Consumer class ZipkinTracingListener( private val call: Call, private val tracer: Tracer, private val tracing: HttpTracing, private val opener: Consumer<TraceContext>, private val detailed: Boolean ) : EventListener() { private lateinit var callSpan: Span private var connectSpan: Span? = null private var dnsSpan: Span? = null private var spanInScope: Tracer.SpanInScope? = null private var requestSpan: Span? = null private var responseSpan: Span? = null private var secureConnectSpan: Span? = null private var connectionSpan: Span? = null override fun callStart(call: Call) { callSpan = tracer.newTrace().name("http").start() callSpan.tag("http.path", call.request().url.encodedPath) callSpan.tag("http.method", call.request().method) callSpan.tag("http.host", call.request().url.host) callSpan.tag("http.url", call.request().url.toString()) callSpan.tag("http.route", "${call.request().method.toUpperCase()} ${call.request().url.encodedPath}") callSpan.kind(Span.Kind.CLIENT) spanInScope = tracer.withSpanInScope(callSpan) } override fun callEnd(call: Call) { if (callSpan.isNoop) { return } spanInScope!!.close() callSpan.finish() opener.accept(callSpan.context()) } override fun callFailed(call: Call, ioe: IOException) { if (callSpan.isNoop) { return } callSpan.tag("error", ioe.toString()) callEnd(call) } override fun dnsStart(call: Call, domainName: String) { if (callSpan.isNoop || !detailed) { return } dnsSpan = tracer.newChild(callSpan.context()).start().name("dns") } override fun dnsEnd(call: Call, domainName: String, inetAddressList: List<InetAddress>) { if (callSpan.isNoop || !detailed) { return } dnsSpan!!.tag("dns.results", inetAddressList.joinToString(", ", transform = { it.toString() }) ) dnsSpan!!.finish() } override fun connectStart(call: Call, inetSocketAddress: InetSocketAddress, proxy: Proxy) { if (callSpan.isNoop || !detailed) { return } connectSpan = tracer.newChild(callSpan.context()).start().name("connect") connectSpan!!.tag("host", inetSocketAddress.toString()) connectSpan!!.tag("proxy", proxy.toString()) } override fun connectEnd( call: Call, inetSocketAddress: InetSocketAddress, proxy: Proxy, protocol: Protocol? ) { if (callSpan.isNoop || !detailed) { return } connectSpan!!.tag("protocol", protocol.toString()) connectSpan!!.finish() } override fun connectFailed( call: Call, inetSocketAddress: InetSocketAddress, proxy: Proxy, protocol: Protocol?, ioe: IOException ) { if (callSpan.isNoop || !detailed) { return } if (protocol != null) { connectSpan!!.tag("protocol", protocol.toString()) } connectSpan!!.tag("failed", ioe.toString()) connectSpan!!.finish() } override fun connectionAcquired(call: Call, connection: Connection) { if (callSpan.isNoop) { return } val route = connection.route().socketAddress.toString() connectionSpan = tracer.newChild(callSpan.context()).start().name("connection $route") connectionSpan!!.tag("route", route) } override fun connectionReleased(call: Call, connection: Connection) { if (callSpan.isNoop) { return } if (connection.route().proxy.type() != Proxy.Type.DIRECT) { connectionSpan!!.tag("proxy", connection.route().proxy.toString()) } if (connection.handshake() != null) { connectionSpan!!.tag("cipher", connection.handshake()!!.cipherSuite.toString()) connectionSpan!!.tag("peer", connection.handshake()!!.peerPrincipal!!.toString()) connectionSpan!!.tag("tls", connection.handshake()!!.tlsVersion.toString()) } connectionSpan!!.tag("protocol", connection.protocol().toString()) connectionSpan!!.finish() } override fun secureConnectStart(call: Call) { if (callSpan.isNoop || !detailed) { return } secureConnectSpan = tracer.newChild(callSpan.context()).start().name("tls") } override fun secureConnectEnd(call: Call, handshake: Handshake?) { if (callSpan.isNoop || !detailed) { return } secureConnectSpan!!.finish() } override fun requestHeadersStart(call: Call) { if (callSpan.isNoop || !detailed) { return } requestSpan = tracer.newChild(callSpan.context()).start().name("request") } override fun requestHeadersEnd(call: Call, request: Request) { if (callSpan.isNoop || !detailed) { return } requestSpan!!.tag("requestHeaderLength", "" + request.headers.byteCount()) } override fun requestBodyEnd(call: Call, byteCount: Long) { if (callSpan.isNoop) { return } requestSpan!!.tag("http.request.size", "" + byteCount) requestSpan = finish(requestSpan) } private fun finish(span: Span?): Span? { span?.finish() return null } override fun responseHeadersStart(call: Call) { if (callSpan.isNoop || !detailed) { return } requestSpan = finish(requestSpan) } override fun responseHeadersEnd(call: Call, response: Response) { if (callSpan.isNoop || !detailed) { return } responseSpan = tracer.newChild(callSpan.context()).start() .name("response") .tag("responseHeaderLength", "" + response.headers.byteCount()) .tag("http.status_code", response.code.toString()) } override fun responseBodyEnd(call: Call, byteCount: Long) { if (callSpan.isNoop || !detailed) { return } responseSpan!!.tag("http.response.size", "" + byteCount) responseSpan = finish(responseSpan) } override fun responseBodyStart(call: Call) { if (callSpan.isNoop || !detailed) { return } } }
apache-2.0
640d11036a47b2e6c54fde2774ffd833
24.640816
106
0.669054
3.986041
false
false
false
false
anton-okolelov/intellij-rust
src/main/kotlin/org/rust/cargo/CargoConstants.kt
2
546
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.cargo object CargoConstants { const val MANIFEST_FILE = "Cargo.toml" const val XARGO_MANIFEST_FILE = "Xargo.toml" const val LOCK_FILE = "Cargo.lock" const val BUILD_RS_FILE = "build.rs" const val RUST_BACTRACE_ENV_VAR = "RUST_BACKTRACE" object ProjectLayout { val sources = listOf("src", "examples") val tests = listOf("tests", "benches") val target = "target" } }
mit
e02b178fd4e76e246fa70f5118133681
23.818182
69
0.64652
3.522581
false
true
false
false
Deletescape-Media/Lawnchair
lawnchair/src/app/lawnchair/util/backHandler.kt
1
1062
package app.lawnchair.util import androidx.activity.OnBackPressedCallback import androidx.activity.compose.LocalOnBackPressedDispatcherOwner import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.rememberUpdatedState import androidx.lifecycle.Lifecycle @Composable fun BackHandler(onBack: () -> Unit) { val backDispatcher = LocalOnBackPressedDispatcherOwner.current?.onBackPressedDispatcher val currentOnBack by rememberUpdatedState(onBack) val resumed = lifecycleState().isAtLeast(Lifecycle.State.RESUMED) DisposableEffect(resumed, backDispatcher) { if (!resumed || backDispatcher == null) { return@DisposableEffect onDispose { } } val backCallback = object : OnBackPressedCallback(true) { override fun handleOnBackPressed() { currentOnBack() } } backDispatcher.addCallback(backCallback) onDispose { backCallback.remove() } } }
gpl-3.0
aa1332647a24ac8a998b4d035a87cace
35.62069
91
0.740113
5.446154
false
false
false
false
mikaelhg/ksoup
src/main/kotlin/io/mikael/ksoup/simple.kt
1
4429
package io.mikael.ksoup import org.jsoup.nodes.Document import org.jsoup.nodes.Element import kotlin.reflect.KMutableProperty1 /** * A container for each command to extract information from an Element, * and stuff it into an object instance field. */ data class ExtractionCommand<in V : Any>(private val css: String, private val command: (Element, V) -> Unit) { fun extract(doc: Document, item: V) = doc.select(css).forEach { element -> command(element, item) } } /** * Don't know yet if we'll be keeping this, or just using the ExtractorBase. * Depends on how the more complicated use cases pan out. */ interface Extractor<out V> { fun extract(): V } @KSoupDsl abstract class ExtractorBase<V : Any> : Extractor<V>, WebSupport() { internal lateinit var instanceGenerator: () -> V internal lateinit var urlGenerator: () -> String var url: String get() = urlGenerator() set(value) { this.urlGenerator = { value } } protected fun document() = get(url) /** * Pass me a generator function for your result type. * I'll make you one of these, so you can stuff it with information from the page. */ fun result(generator: () -> V) { this.instanceGenerator = generator } /** * Pass me an instance, and I'll fill it in with data from the page. */ fun result(instance: V) = result { instance } } /** * Hit one page, get some data. */ open class SimpleExtractor<V: Any>(url: String = "") : ExtractorBase<V>() { init { this.urlGenerator = { url } } protected var extractionCommands: MutableList<ExtractionCommand<V>> = mutableListOf() override fun extract(): V { val instance = instanceGenerator() val doc = document() extractionCommands.forEach { it.extract(doc, instance) } return instance } /** * If I find a match for your CSS selector, I'll call your extractor function, and pass it an Element. * * ## Usage: * ```kotlin * element(".p-nickname") { element, page -> * page.username = element.text() * } * ``` */ fun element(css: String, extract: (Element, V) -> Unit) { extractionCommands.add(ExtractionCommand(css, extract)) } /** * If I find a match for your CSS selector, I'll call your extractor function, and pass it an Element. * * ## Usage: * ```kotlin * element(".p-nickname", Element::text, GitHubPage::username) * ``` */ fun <P> element(css: String, from: Element.() -> P, toProperty: KMutableProperty1<in V, P>) { extractionCommands.add(ExtractionCommand(css) { e, v -> toProperty.set(v, e.from()) }) } /** * If I find a match for your CSS selector, I'll call your extractor function, and pass it a String. * * ## Usage: * ```kotlin * text(".p-name") { text, page -> * page.fullName = text * } * ``` */ fun text(css: String, extract: (String, V) -> Unit) { extractionCommands.add(ExtractionCommand(css) { e, v -> extract(e.text(), v) }) } /** * If I find a match for your CSS selector, I'll stuff the results into your instance property. * * ## Usage: * ```kotlin * text(".p-name", GitHubPage::fullName) * ``` */ fun text(css: String, property: KMutableProperty1<V, String>) { extractionCommands.add(ExtractionCommand(css) { e, v -> property.set(v, e.text()) }) } /** * Call for a copy. Pass in the values you want to change in the new instance. */ fun copy(urlGenerator: () -> String = this.urlGenerator, instanceGenerator: () -> V = this.instanceGenerator, extractionCommands: MutableList<ExtractionCommand<V>> = this.extractionCommands, userAgent: String? = null, userAgentGenerator: () -> String = this.userAgentGenerator, url: String? = null, instance: V? = null) = SimpleExtractor<V>().apply { [email protected] = if (url == null) urlGenerator else ({ url }) [email protected] = if (instance == null) instanceGenerator else ({ instance }) [email protected] = if (userAgent == null) userAgentGenerator else ({ userAgent }) [email protected] = extractionCommands } }
apache-2.0
b6b7e859c56bf63b5a0b52a713dd9486
30.635714
110
0.60578
4.037375
false
false
false
false
yshrsmz/monotweety
app/src/main/java/net/yslibrary/monotweety/notification/ServiceConnection.kt
1
1603
package net.yslibrary.monotweety.notification import android.content.ComponentName import android.content.Context import android.content.Intent import android.os.IBinder import com.gojuno.koptional.None import com.gojuno.koptional.Optional import com.gojuno.koptional.rxjava2.filterSome import com.gojuno.koptional.toOptional import io.reactivex.Observable import io.reactivex.subjects.BehaviorSubject import timber.log.Timber class ServiceConnection( context: Context, private val intent: Intent ) : android.content.ServiceConnection { private val context: Context = context.applicationContext private val subject = BehaviorSubject.create<Optional<NotificationService>>() override fun onServiceConnected(name: ComponentName?, binder: IBinder?) { Timber.d("Service connected") initWithBinder(binder) } override fun onServiceDisconnected(name: ComponentName?) { Timber.d("Service disconnected") dispose() } fun initWithBinder(binder: IBinder?) { if (binder == null) { Timber.d("Service not bound") subject.onNext(None) return } Timber.d("Service bound") val service = (binder as NotificationService.ServiceBinder).service subject.onNext(service.toOptional()) } fun dispose() { subject.onNext(None) } fun bindService(): Observable<NotificationService> { if (subject.value == null) { context.bindService(intent, this, Context.BIND_AUTO_CREATE) } return subject .filterSome() } }
apache-2.0
72ba620c05696aacc5cfd98cc4bfef6c
27.122807
81
0.693699
4.799401
false
false
false
false
Kotlin/dokka
plugins/templating/src/main/kotlin/templates/SubstitutionCommandHandler.kt
1
2932
package org.jetbrains.dokka.templates import org.jetbrains.dokka.base.templating.Command import org.jetbrains.dokka.base.templating.SubstitutionCommand import org.jetbrains.dokka.plugability.DokkaContext import org.jetbrains.dokka.plugability.plugin import org.jetbrains.dokka.plugability.query import org.jsoup.nodes.DataNode import org.jsoup.nodes.Element import org.jsoup.nodes.Node import org.jsoup.nodes.TextNode import java.io.File class SubstitutionCommandHandler(context: DokkaContext) : CommandHandler { override fun handleCommandAsTag(command: Command, body: Element, input: File, output: File) { command as SubstitutionCommand val childrenCopy = body.children().toList() substitute(childrenCopy, TemplatingContext(input, output, childrenCopy, command)) val position = body.elementSiblingIndex() val parent = body.parent() body.remove() parent?.insertChildren(position, childrenCopy) } override fun handleCommandAsComment(command: Command, body: List<Node>, input: File, output: File) { command as SubstitutionCommand substitute(body, TemplatingContext(input, output, body, command)) } override fun canHandle(command: Command): Boolean = command is SubstitutionCommand override fun finish(output: File) { } private val substitutors = context.plugin<TemplatingPlugin>().query { substitutor } private fun findSubstitution(commandContext: TemplatingContext<SubstitutionCommand>, match: MatchResult): String = substitutors.asSequence().mapNotNull { it.trySubstitute(commandContext, match) }.firstOrNull() ?: match.value private fun substitute(elements: List<Node>, commandContext: TemplatingContext<SubstitutionCommand>) { val regex = commandContext.command.pattern.toRegex() elements.forEach { it.traverseToSubstitute(regex, commandContext) } } private fun Node.traverseToSubstitute(regex: Regex, commandContext: TemplatingContext<SubstitutionCommand>) { when (this) { is TextNode -> replaceWith(TextNode(wholeText.substitute(regex, commandContext))) is DataNode -> replaceWith(DataNode(wholeData.substitute(regex, commandContext))) is Element -> { attributes().forEach { attr(it.key, it.value.substitute(regex, commandContext)) } childNodes().forEach { it.traverseToSubstitute(regex, commandContext) } } } } private fun String.substitute(regex: Regex, commandContext: TemplatingContext<SubstitutionCommand>) = buildString { var lastOffset = 0 regex.findAll(this@substitute).forEach { match -> append(this@substitute, lastOffset, match.range.first) append(findSubstitution(commandContext, match)) lastOffset = match.range.last + 1 } append(this@substitute, lastOffset, [email protected]) } }
apache-2.0
6dff864f798e381d838c8651837a1440
42.776119
119
0.72101
4.713826
false
false
false
false
google/prefab
cli/src/test/kotlin/com/google/prefab/cli/CMakePluginTest.kt
1
17158
/* * 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.prefab.cli import com.google.prefab.api.Android import com.google.prefab.api.Package import com.google.prefab.api.SchemaVersion import com.google.prefab.cmake.CMakePlugin import com.google.prefab.cmake.sanitize import org.junit.jupiter.api.assertThrows import org.junit.runner.RunWith import org.junit.runners.Parameterized import java.nio.file.Files import java.nio.file.Path import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertFalse import kotlin.test.assertTrue @RunWith(Parameterized::class) class CMakePluginTest(override val schemaVersion: SchemaVersion) : PerSchemaTest { companion object { @Parameterized.Parameters(name = "schema version = {0}") @JvmStatic fun data(): List<SchemaVersion> = SchemaVersion.values().toList() } private val staleOutputDir: Path = Files.createTempDirectory("stale").apply { toFile().apply { deleteOnExit() } } private val staleFile: Path = staleOutputDir.resolve("bogus").apply { toFile().createNewFile() } private val outputDirectory: Path = Files.createTempDirectory("output").apply { toFile().apply { deleteOnExit() } } private fun cmakeConfigName(packageName: String): String = "${packageName}Config" private fun cmakeConfigFile(packageName: String): String = "${cmakeConfigName(packageName)}.cmake" private fun cmakeVersionFile(packageName: String): String = "${cmakeConfigName(packageName)}Version.cmake" @Test fun `multi-target generations are rejected`() { val generator = CMakePlugin(staleOutputDir.toFile(), emptyList()) val requirements = Android.Abi.values() .map { Android(it, 21, Android.Stl.CxxShared, 21) } assertTrue(requirements.size > 1) assertThrows<UnsupportedOperationException> { generator.generate(requirements) } } @Test fun `stale files are removed from extant output directory`() { assertTrue(staleFile.toFile().exists()) CMakePlugin(staleOutputDir.toFile(), emptyList()).generate( listOf(Android(Android.Abi.Arm64, 21, Android.Stl.CxxShared, 21)) ) assertFalse(staleFile.toFile().exists()) } @Test fun `basic project generates correctly`() { val fooPath = packagePath("foo") val foo = Package(fooPath) val quxPath = packagePath("qux") val qux = Package(quxPath) CMakePlugin(outputDirectory.toFile(), listOf(foo, qux)).generate( listOf(Android(Android.Abi.Arm64, 19, Android.Stl.CxxShared, 21)) ) val archDir = outputDirectory.resolve("lib/aarch64-linux-android/cmake") val fooConfigFile = archDir.resolve("${foo.name}/${cmakeConfigFile(foo.name)}").toFile() val fooVersionFile = archDir.resolve( "${foo.name}/${cmakeVersionFile(foo.name)}" ).toFile() assertTrue(fooConfigFile.exists()) assertTrue(fooVersionFile.exists()) val quxConfigFile = archDir.resolve("${qux.name}/${cmakeConfigFile(qux.name)}").toFile() val quxVersionFile = archDir.resolve( "${qux.name}/${cmakeVersionFile(qux.name)}" ).toFile() assertTrue(quxConfigFile.exists()) assertTrue(quxVersionFile.exists()) val barDir = fooPath.resolve("modules/bar").sanitize() val bazDir = fooPath.resolve("modules/baz").sanitize() assertEquals( """ find_package(quux REQUIRED CONFIG) find_package(qux REQUIRED CONFIG) if(NOT TARGET foo::bar) add_library(foo::bar SHARED IMPORTED) set_target_properties(foo::bar PROPERTIES IMPORTED_LOCATION "$barDir/libs/android.arm64-v8a/libbar.so" INTERFACE_INCLUDE_DIRECTORIES "$barDir/include" INTERFACE_LINK_LIBRARIES "-landroid" ) endif() if(NOT TARGET foo::baz) add_library(foo::baz SHARED IMPORTED) set_target_properties(foo::baz PROPERTIES IMPORTED_LOCATION "$bazDir/libs/android.arm64-v8a/libbaz.so" INTERFACE_INCLUDE_DIRECTORIES "$bazDir/include" INTERFACE_LINK_LIBRARIES "-llog;foo::bar;qux::libqux" ) endif() """.trimIndent(), fooConfigFile.readText() ) assertEquals( """ set(PACKAGE_VERSION 1) if("${'$'}{PACKAGE_VERSION}" VERSION_LESS "${'$'}{PACKAGE_FIND_VERSION}") set(PACKAGE_VERSION_COMPATIBLE FALSE) else() set(PACKAGE_VERSION_COMPATIBLE TRUE) if("${'$'}{PACKAGE_VERSION}" VERSION_EQUAL "${'$'}{PACKAGE_FIND_VERSION}") set(PACKAGE_VERSION_EXACT TRUE) endif() endif() """.trimIndent(), fooVersionFile.readText() ) val quxDir = quxPath.resolve("modules/libqux").sanitize() assertEquals( """ find_package(foo REQUIRED CONFIG) if(NOT TARGET qux::libqux) add_library(qux::libqux STATIC IMPORTED) set_target_properties(qux::libqux PROPERTIES IMPORTED_LOCATION "$quxDir/libs/android.arm64-v8a/libqux.a" INTERFACE_INCLUDE_DIRECTORIES "$quxDir/include" INTERFACE_LINK_LIBRARIES "foo::bar" ) endif() """.trimIndent(), quxConfigFile.readText() ) assertEquals( """ set(PACKAGE_VERSION 1.2.1.4) if("${'$'}{PACKAGE_VERSION}" VERSION_LESS "${'$'}{PACKAGE_FIND_VERSION}") set(PACKAGE_VERSION_COMPATIBLE FALSE) else() set(PACKAGE_VERSION_COMPATIBLE TRUE) if("${'$'}{PACKAGE_VERSION}" VERSION_EQUAL "${'$'}{PACKAGE_FIND_VERSION}") set(PACKAGE_VERSION_EXACT TRUE) endif() endif() """.trimIndent(), quxVersionFile.readText() ) } @Test fun `header only module works`() { val packagePath = packagePath("header_only") val pkg = Package(packagePath) CMakePlugin(outputDirectory.toFile(), listOf(pkg)).generate( listOf(Android(Android.Abi.Arm64, 21, Android.Stl.CxxShared, 21)) ) val name = pkg.name val archDir = outputDirectory.resolve("lib/aarch64-linux-android/cmake") val configFile = archDir.resolve("$name/${cmakeConfigFile(name)}").toFile() val versionFile = archDir.resolve("$name/${cmakeVersionFile(name)}").toFile() assertTrue(configFile.exists()) assertTrue(versionFile.exists()) val fooDir = packagePath.resolve("modules/foo").sanitize() val barDir = packagePath.resolve("modules/bar").sanitize() assertEquals( """ if(NOT TARGET header_only::bar) add_library(header_only::bar SHARED IMPORTED) set_target_properties(header_only::bar PROPERTIES IMPORTED_LOCATION "$barDir/libs/android.arm64-v8a/libbar.so" INTERFACE_INCLUDE_DIRECTORIES "$barDir/include" INTERFACE_LINK_LIBRARIES "header_only::foo" ) endif() if(NOT TARGET header_only::foo) add_library(header_only::foo INTERFACE IMPORTED) set_target_properties(header_only::foo PROPERTIES INTERFACE_INCLUDE_DIRECTORIES "$fooDir/include" INTERFACE_LINK_LIBRARIES "" ) endif() """.trimIndent(), configFile.readText() ) assertEquals( """ set(PACKAGE_VERSION 2.2) if("${'$'}{PACKAGE_VERSION}" VERSION_LESS "${'$'}{PACKAGE_FIND_VERSION}") set(PACKAGE_VERSION_COMPATIBLE FALSE) else() set(PACKAGE_VERSION_COMPATIBLE TRUE) if("${'$'}{PACKAGE_VERSION}" VERSION_EQUAL "${'$'}{PACKAGE_FIND_VERSION}") set(PACKAGE_VERSION_EXACT TRUE) endif() endif() """.trimIndent(), versionFile.readText() ) } @Test fun `per-platform includes work`() { val path = packagePath("per_platform_includes") val pkg = Package(path) CMakePlugin(outputDirectory.toFile(), listOf(pkg)).generate( listOf(Android(Android.Abi.Arm64, 21, Android.Stl.CxxShared, 19)) ) val name = pkg.name var archDir = outputDirectory.resolve("lib/aarch64-linux-android/cmake") var configFile = archDir.resolve("$name/${cmakeConfigFile(name)}").toFile() val versionFile = archDir.resolve("$name/${cmakeVersionFile(name)}").toFile() assertTrue(configFile.exists()) // No version is provided for this package, so we shouldn't provide a // version file. assertFalse(versionFile.exists()) val modDir = path.resolve("modules/perplatform").sanitize() assertEquals( """ if(NOT TARGET per_platform_includes::perplatform) add_library(per_platform_includes::perplatform SHARED IMPORTED) set_target_properties(per_platform_includes::perplatform PROPERTIES IMPORTED_LOCATION "$modDir/libs/android.arm64-v8a/libperplatform.so" INTERFACE_INCLUDE_DIRECTORIES "$modDir/libs/android.arm64-v8a/include" INTERFACE_LINK_LIBRARIES "" ) endif() """.trimIndent(), configFile.readText() ) // Only some of the platforms in this module have their own headers. // Verify that the module level headers are used for platforms that // don't. CMakePlugin(outputDirectory.toFile(), listOf(pkg)).generate( listOf(Android(Android.Abi.X86_64, 21, Android.Stl.CxxShared, 19)) ) archDir = outputDirectory.resolve("lib/x86_64-linux-android/cmake") configFile = archDir.resolve("$name/${cmakeConfigFile(name)}").toFile() assertEquals( """ if(NOT TARGET per_platform_includes::perplatform) add_library(per_platform_includes::perplatform SHARED IMPORTED) set_target_properties(per_platform_includes::perplatform PROPERTIES IMPORTED_LOCATION "$modDir/libs/android.x86_64/libperplatform.so" INTERFACE_INCLUDE_DIRECTORIES "$modDir/include" INTERFACE_LINK_LIBRARIES "" ) endif() """.trimIndent(), configFile.readText() ) } @Test fun `old NDKs use non-arch specific layout`() { val packagePath = packagePath("header_only") val pkg = Package(packagePath) CMakePlugin(outputDirectory.toFile(), listOf(pkg)).generate( listOf(Android(Android.Abi.Arm64, 21, Android.Stl.CxxShared, 18)) ) val name = pkg.name val configFile = outputDirectory.resolve(cmakeConfigFile(name)).toFile() val versionFile = outputDirectory.resolve(cmakeVersionFile(name)).toFile() assertTrue(configFile.exists()) assertTrue(versionFile.exists()) val fooDir = packagePath.resolve("modules/foo").sanitize() val barDir = packagePath.resolve("modules/bar").sanitize() assertEquals( """ if(NOT TARGET header_only::bar) add_library(header_only::bar SHARED IMPORTED) set_target_properties(header_only::bar PROPERTIES IMPORTED_LOCATION "$barDir/libs/android.arm64-v8a/libbar.so" INTERFACE_INCLUDE_DIRECTORIES "$barDir/include" INTERFACE_LINK_LIBRARIES "header_only::foo" ) endif() if(NOT TARGET header_only::foo) add_library(header_only::foo INTERFACE IMPORTED) set_target_properties(header_only::foo PROPERTIES INTERFACE_INCLUDE_DIRECTORIES "$fooDir/include" INTERFACE_LINK_LIBRARIES "" ) endif() """.trimIndent(), configFile.readText() ) assertEquals( """ set(PACKAGE_VERSION 2.2) if("${'$'}{PACKAGE_VERSION}" VERSION_LESS "${'$'}{PACKAGE_FIND_VERSION}") set(PACKAGE_VERSION_COMPATIBLE FALSE) else() set(PACKAGE_VERSION_COMPATIBLE TRUE) if("${'$'}{PACKAGE_VERSION}" VERSION_EQUAL "${'$'}{PACKAGE_FIND_VERSION}") set(PACKAGE_VERSION_EXACT TRUE) endif() endif() """.trimIndent(), versionFile.readText() ) } @Test fun `mixed static and shared libraries are both exposed when compatible`() { val packagePath = packagePath("static_and_shared") val pkg = Package(packagePath) CMakePlugin(outputDirectory.toFile(), listOf(pkg)).generate( listOf(Android(Android.Abi.Arm64, 21, Android.Stl.CxxShared, 18)) ) val configFile = outputDirectory.resolve(cmakeConfigFile(pkg.name)).toFile() assertTrue(configFile.exists()) val fooDir = packagePath.resolve("modules/foo").sanitize() val fooStaticDir = packagePath.resolve("modules/foo_static").sanitize() assertEquals( """ if(NOT TARGET static_and_shared::foo) add_library(static_and_shared::foo SHARED IMPORTED) set_target_properties(static_and_shared::foo PROPERTIES IMPORTED_LOCATION "$fooDir/libs/android.shared/libfoo.so" INTERFACE_INCLUDE_DIRECTORIES "$fooDir/include" INTERFACE_LINK_LIBRARIES "" ) endif() if(NOT TARGET static_and_shared::foo_static) add_library(static_and_shared::foo_static STATIC IMPORTED) set_target_properties(static_and_shared::foo_static PROPERTIES IMPORTED_LOCATION "$fooStaticDir/libs/android.static/libfoo.a" INTERFACE_INCLUDE_DIRECTORIES "$fooStaticDir/include" INTERFACE_LINK_LIBRARIES "" ) endif() """.trimIndent(), configFile.readText() ) } @Test fun `incompatible libraries are skipped for static STL`() { val packagePath = packagePath("static_and_shared") val pkg = Package(packagePath) CMakePlugin(outputDirectory.toFile(), listOf(pkg)).generate( listOf(Android(Android.Abi.Arm64, 21, Android.Stl.CxxStatic, 18)) ) val configFile = outputDirectory.resolve(cmakeConfigFile(pkg.name)).toFile() assertTrue(configFile.exists()) val fooStaticDir = packagePath.resolve("modules/foo_static").sanitize() assertEquals( """ if(NOT TARGET static_and_shared::foo_static) add_library(static_and_shared::foo_static STATIC IMPORTED) set_target_properties(static_and_shared::foo_static PROPERTIES IMPORTED_LOCATION "$fooStaticDir/libs/android.static/libfoo.a" INTERFACE_INCLUDE_DIRECTORIES "$fooStaticDir/include" INTERFACE_LINK_LIBRARIES "" ) endif() """.trimIndent(), configFile.readText() ) } @Test fun `empty include directories are skipped`() { // Regression test for https://issuetracker.google.com/178594838. val path = packagePath("no_headers") val pkg = Package(path) CMakePlugin(outputDirectory.toFile(), listOf(pkg)).generate( listOf(Android(Android.Abi.Arm64, 21, Android.Stl.CxxShared, 18)) ) val configFile = outputDirectory.resolve(cmakeConfigFile(pkg.name)).toFile() assertTrue(configFile.exists()) val moduleDir = path.resolve("modules/runtime").sanitize() assertEquals( """ if(NOT TARGET no_headers::runtime) add_library(no_headers::runtime SHARED IMPORTED) set_target_properties(no_headers::runtime PROPERTIES IMPORTED_LOCATION "$moduleDir/libs/android.arm64-v8a/libruntime.so" INTERFACE_LINK_LIBRARIES "" ) endif() """.trimIndent(), configFile.readText() ) } }
apache-2.0
a16aa27c8add3b4438b347b0fcc5ad53
36.138528
90
0.597914
4.581575
false
true
false
false
alygin/intellij-rust
src/main/kotlin/org/rust/cargo/project/CargoToolWindow.kt
1
4906
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.cargo.project import com.intellij.ProjectTopics import com.intellij.openapi.actionSystem.ActionManager import com.intellij.openapi.actionSystem.ActionToolbar import com.intellij.openapi.actionSystem.DefaultActionGroup import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.module.Module import com.intellij.openapi.project.Project import com.intellij.openapi.roots.ModuleRootEvent import com.intellij.openapi.roots.ModuleRootListener import com.intellij.openapi.ui.SimpleToolWindowPanel import com.intellij.openapi.vfs.VirtualFileManager import com.intellij.openapi.vfs.newvfs.BulkFileListener import com.intellij.openapi.vfs.newvfs.events.VFileEvent import com.intellij.openapi.wm.ToolWindow import com.intellij.openapi.wm.ToolWindowFactory import com.intellij.ui.ColorUtil import com.intellij.ui.content.ContentFactory import com.intellij.ui.layout.CCFlags import com.intellij.ui.layout.panel import com.intellij.util.ui.UIUtil import org.rust.cargo.project.workspace.CargoWorkspace import org.rust.cargo.project.workspace.cargoWorkspace import org.rust.cargo.project.workspace.impl.CargoTomlWatcher import org.rust.cargo.util.modulesWithCargoProject import javax.swing.JEditorPane class CargoToolWindowFactory : ToolWindowFactory { override fun createToolWindowContent(project: Project, toolWindow: ToolWindow) { val toolwindowPanel = run { val cargoTab = CargoToolWindow(project) SimpleToolWindowPanel(true, false).apply { setToolbar(cargoTab.toolbar.component) cargoTab.toolbar.setTargetComponent(this) setContent(cargoTab.content) } } val tab = ContentFactory.SERVICE.getInstance() .createContent(toolwindowPanel, "", false) toolWindow.contentManager.addContent(tab) } } private class CargoToolWindow( private val project: Project ) { private var _cargoProjects: List<Pair<Module, CargoWorkspace?>> = emptyList() private var cargoProjects: List<Pair<Module, CargoWorkspace?>> get() = _cargoProjects set(value) { check(ApplicationManager.getApplication().isDispatchThread) _cargoProjects = value updateUi() } val toolbar: ActionToolbar = run { val actionManager = ActionManager.getInstance() actionManager.createActionToolbar("Cargo Toolbar", actionManager.getAction("Rust.Cargo") as DefaultActionGroup, true) } val note = JEditorPane("text/html", html("")).apply { background = UIUtil.getTreeBackground() isEditable = false } val content = panel { row { note(CCFlags.push, CCFlags.grow) } } init { with(project.messageBus.connect()) { subscribe(ProjectTopics.PROJECT_ROOTS, object : ModuleRootListener { override fun rootsChanged(event: ModuleRootEvent?) { updateData() } }) subscribe(VirtualFileManager.VFS_CHANGES, object : BulkFileListener { override fun after(events: List<VFileEvent>) { if (events.any { CargoTomlWatcher.isCargoTomlChange(it) }) { updateData() } } override fun before(events: List<VFileEvent>) {} }) } updateData() } private fun updateData() { ApplicationManager.getApplication().invokeLater { cargoProjects = project.modulesWithCargoProject.map { module -> module to module.cargoWorkspace } } } private fun updateUi() { note.text = if (cargoProjects.isEmpty()) { html("There are no Cargo projects to display.") } else { html(buildString { for ((module, ws) in cargoProjects) { if (ws != null) { val projectName = ws.manifestPath?.parent?.fileName?.toString() if (projectName != null) append("Project $projectName up-to-date.") } else { append("Project ${module.name} failed to update!") } append("</br>") } }) } } override fun toString(): String { return "CargoToolWindow(workspaces = $_cargoProjects)" } private fun html(body: String): String = """ <html> <head> ${UIUtil.getCssFontDeclaration(UIUtil.getLabelFont())} <style>body {background: #${ColorUtil.toHex(UIUtil.getTreeBackground())}; text-align: center; }</style> </head> <body> $body </body> </html> """ }
mit
6360dd661a50ca51133764f86ad74c24
34.294964
125
0.63779
4.960566
false
false
false
false
SimpleTimeTracking/StandaloneClient
src/main/kotlin/org/stt/update/UpdateChecker.kt
1
1235
package org.stt.update import java.net.URL import java.util.concurrent.CompletableFuture import java.util.concurrent.CompletionStage import java.util.regex.Pattern import javax.inject.Inject import javax.inject.Named class UpdateChecker @Inject constructor(@Named("version") val appVersion: String, @Named("release url") val projectURL: URL) { fun queryNewerVersion(): CompletionStage<String?> { return CompletableFuture.supplyAsync<String> { projectURL.openStream().use { stream -> stream.bufferedReader().readText() } }.thenApply { receivedReply -> val matcher = TAG_PATTERN.matcher(receivedReply) var version: String? = null while (matcher.find()) { val nextVersion = matcher.group(1) if (VERSION_COMPARATOR.compare(nextVersion, appVersion) > 0 && (version == null || VERSION_COMPARATOR.compare(nextVersion, version) > 0)) { version = nextVersion } } version } } companion object { private val TAG_PATTERN = Pattern.compile("tag_name\":\\s*\"v?([^\"]+)\"", Pattern.MULTILINE) private val VERSION_COMPARATOR = VersionComparator() } }
gpl-3.0
01a278bb917da2f7a5413c298d7d7c14
37.59375
155
0.640486
4.591078
false
false
false
false
AM5800/polyglot
app/src/main/kotlin/com/am5800/polyglot/app/QuizSource.kt
1
1373
package com.am5800.polyglot.app import com.am5800.polyglot.app.sentenceGeneration.content.LessonGrammar import com.am5800.polyglot.app.sentenceGeneration.content.WordPair import com.am5800.polyglot.app.sentenceGeneration.english.EnglishSentenceGenerator import com.am5800.polyglot.app.sentenceGeneration.english.Pronoun import com.am5800.polyglot.app.sentenceGeneration.russian.RussianSentenceGenerator import com.am5800.polyglot.app.sentenceGeneration.russian.RussianVerb import java.util.* class Quiz(val question: String, val answer: String) class QuizSource(private val words: List<WordPair>, private val grammars: List<LessonGrammar>) { private val random = Random() private val pronouns = words.filter { it.russian is Pronoun }.toList() private val verbs = words.filter { it.russian is RussianVerb }.toList() private val russianGenerator = RussianSentenceGenerator() private val englishGenerator = EnglishSentenceGenerator() fun next(): Quiz { val grammar = grammars[random.nextInt(grammars.size)] val pronoun = pronouns[random.nextInt(pronouns.size)] val verb = verbs[random.nextInt(verbs.size)] val russian = russianGenerator.generate(grammar.russian, listOf(pronoun.russian, verb.russian)) val english = englishGenerator.generate(grammar.english, listOf(pronoun.english, verb.english)) return Quiz(russian, english) } }
gpl-3.0
02944712413930e9f716fd265cc6de0f
43.322581
99
0.796795
3.968208
false
false
false
false
sangcomz/FishBun
FishBun/src/main/java/com/sangcomz/fishbun/util/RadioWithTextButton.kt
1
3864
package com.sangcomz.fishbun.util import android.content.Context import android.graphics.Canvas import android.graphics.Paint import android.graphics.Rect import android.graphics.drawable.Drawable import android.util.AttributeSet import android.util.TypedValue import android.view.View import androidx.annotation.ColorInt import androidx.annotation.VisibleForTesting import com.sangcomz.fishbun.R /** * Created by sangcomz on 01/05/2017. */ class RadioWithTextButton @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0 ) : View(context, attrs, defStyleAttr) { @VisibleForTesting(otherwise = VisibleForTesting.NONE) constructor(context: Context, textPaint: Paint, strokePaint: Paint, circlePaint: Paint) : this(context) { this.textPaint = textPaint this.strokePaint = strokePaint this.circlePaint = circlePaint } private var radioType: RadioType = RadioType.None private var textPaint: Paint = Paint(Paint.ANTI_ALIAS_FLAG).apply { isFakeBoldText = true } private var strokePaint: Paint = Paint(Paint.ANTI_ALIAS_FLAG) private var circlePaint: Paint = Paint(Paint.ANTI_ALIAS_FLAG) private val textWidth: Float get() = (width / 3) * 2 - PADDING_TEXT private val centerRect: Rect get() = _centerRect!! private var _centerRect: Rect? = null get() { if (field == null) { val r = Rect(0, 0, width, height) val width = width / 4 field = Rect((r.exactCenterX() - width).toInt(), (r.exactCenterY() - width).toInt(), getWidth() - width, height - width) } return field } override fun onDraw(canvas: Canvas) { strokePaint.strokeWidth = (width / 18).toFloat() isSelected { canvas.drawCircle((width / 2).toFloat(), (height / 2).toFloat(), (width / 3).toFloat(), circlePaint) } with(radioType) { isRadioText { drawTextCentered(canvas, textPaint, text, (width / 2).toFloat(), (height / 2).toFloat()) } isRadioDrawable { drawable.bounds = centerRect drawable.draw(canvas) } isRadioNone { strokePaint.style = Paint.Style.STROKE canvas.drawCircle((width / 2).toFloat(), (height / 2).toFloat(), (width / 3).toFloat(), strokePaint) } } } fun setTextColor(@ColorInt color: Int) = textPaint.run { this.color = color } fun setCircleColor(@ColorInt color: Int) = circlePaint.run { this.color = color } fun setStrokeColor(@ColorInt color: Int) = strokePaint.run { this.color = color } fun setText(text: String) { radioType = RadioType.RadioText(text) invalidate() } fun setDrawable(drawable: Drawable) { radioType = RadioType.RadioDrawable(drawable) invalidate() } fun unselect() { radioType = RadioType.None invalidate() } private fun isSelected(block: () -> Unit) = if (radioType != RadioType.None) block() else Unit private fun drawTextCentered(canvas: Canvas, paint: Paint, text: String, cx: Float, cy: Float) { val textBounds = Rect() with(paint) { setTextSizeForWidth(text, textWidth) getTextBounds(text, 0, text.length, textBounds) } canvas.drawText(text, cx - textBounds.exactCenterX(), cy - textBounds.exactCenterY(), paint) } private fun fetchAccentColor(): Int { val typedValue = TypedValue() val a = context.obtainStyledAttributes(typedValue.data, intArrayOf(R.attr.colorAccent)) val color = a.getColor(0, 0) a.recycle() return color } companion object { private const val PADDING_TEXT = 20.toFloat() } }
apache-2.0
5b099396c71cfe6f70fc12b4218e72a9
31.745763
136
0.630176
4.326988
false
false
false
false
aewhite/intellij-eclipse-collections-plugin
src/net/andrewewhite/eclipse/collections/intellij/plugin/inspections/EclipseCollectionsNeedlessIntermediateCollectionsInspection.kt
1
6694
package net.andrewewhite.eclipse.collections.intellij.plugin.inspections import com.intellij.codeInspection.* import com.intellij.openapi.project.Project import com.intellij.openapi.util.TextRange import com.intellij.psi.* import com.intellij.psi.JavaTokenType.DOT import com.intellij.psi.codeStyle.CodeStyleManager import com.intellij.psi.codeStyle.JavaCodeStyleManager import com.intellij.psi.search.GlobalSearchScope import org.eclipse.collections.api.RichIterable import org.eclipse.collections.api.list.MutableList import org.eclipse.collections.api.set.ImmutableSet import org.eclipse.collections.impl.factory.Lists import org.eclipse.collections.impl.factory.Sets import org.eclipse.jdt.internal.compiler.ast.ReferenceExpression import javax.swing.JComponent /** * Created by awhite on 1/3/17. */ class EclipseCollectionsNeedlessIntermediateCollectionsInspection : BaseJavaBatchLocalInspectionTool() { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor { if (!isEclipseCollectionsBeingUsed(holder)) { return PsiElementVisitor.EMPTY_VISITOR } return EclipseCollectionsNeedlessIntermediateCollectionsInspection.Visitor(holder, isOnTheFly) } internal class Visitor(val holder: ProblemsHolder, val isOnTheFly: Boolean) : JavaElementVisitor() { val elementFactory: PsiElementFactory = JavaPsiFacade.getElementFactory(holder.project) val richIterableType: PsiClassType = elementFactory.createTypeByFQClassName(CommonEclipseCollectionClassNames.EC_RICH_ITERABLE) val lazyIterableType: PsiClassType = elementFactory.createTypeByFQClassName(CommonEclipseCollectionClassNames.EC_LAZY_ITERABLE) val lazyClass: PsiClass = lazyIterableType.resolve()!! val lazyMethodsNames: ImmutableSet<String> = findInterestingLazyMethod() val allLazyMethodsNames: ImmutableSet<String> = Sets.immutable.of(*lazyClass.allMethods).collect { it.name } val seenMethods = Sets.mutable.empty<PsiMethodCallExpression>() // TODO handle primitive lazy iterables private fun findInterestingLazyMethod() = Sets.immutable.of(*lazyClass.methods) .collectIf( { it.returnType?.isAssignableFrom(lazyIterableType) ?: false }, { it.name }) override fun visitMethodCallExpression(expression: PsiMethodCallExpression) { super.visitMethodCallExpression(expression) if (!isMethodCallInteresting(expression)) { return } val callChain = buildLazyCallChain(expression) if (!isCallChainInteresting(callChain)) { return } if (expression in seenMethods) { return } seenMethods.addAll(callChain) holder.registerProblem( expression, "Should use asLazy to avoid intermediate collections", ProblemHighlightType.GENERIC_ERROR_OR_WARNING, TextRange.create(0, callChain.last().textRange.endOffset - callChain.first().textRange.startOffset), EclipseCollectionAsLazyQuickFix()) } private fun isCallChainInteresting(callChain: MutableList<PsiMethodCallExpression>) = callChain.size >= 2 && callChain.allSatisfy { it.methodExpression.referenceName in allLazyMethodsNames } private fun isMethodCallInteresting(expression: PsiMethodCallExpression): Boolean { when { !isMethodNameCandidateForAsLazy(expression) -> return false !isTypeCandidateForAsLazy(expression) -> return false } return doesLazyIterableSupportMethod(expression) } private fun doesLazyIterableSupportMethod(expression: PsiMethodCallExpression): Boolean { val method = expression.resolveMethod() ?: return true val containingClass = method.containingClass ?: return true if (!supportsAsLazy(containingClass)) { return false } return true } private fun isTypeCandidateForAsLazy(expression: PsiMethodCallExpression): Boolean { val type = expression.type ?: return false when { !richIterableType.isAssignableFrom(type) -> return false lazyIterableType.isAssignableFrom(type) -> return false else -> return true } } private fun isMethodNameCandidateForAsLazy(expression: PsiMethodCallExpression): Boolean { val methodReferenceName = expression.methodExpression.referenceName ?: return true return methodReferenceName in lazyMethodsNames } private fun supportsAsLazy(containingClass: PsiClass) = containingClass.findMethodsByName("asLazy", true).isNotEmpty() private fun buildLazyCallChain(expression: PsiMethodCallExpression): MutableList<PsiMethodCallExpression> { val methodCallExpressions = Lists.mutable.empty<PsiMethodCallExpression>() var currentExpression = expression while (true) { methodCallExpressions.add(currentExpression) val parent = currentExpression.parent ?: break val grandParent = parent.parent ?: break if (parent is PsiReferenceExpression && grandParent is PsiMethodCallExpression && grandParent.methodExpression.referenceName in allLazyMethodsNames ) { // method calls should have a parent that defines the actual reference to the method; note that a // method call is a reference to a method plus the parameters currentExpression = grandParent } else { break } } return methodCallExpressions } } } class EclipseCollectionAsLazyQuickFix : LocalQuickFix { override fun getFamilyName(): String = "Use asLazy" override fun applyFix(project: Project, descriptor: ProblemDescriptor) { val element: PsiMethodCallExpression = descriptor.getPsiElement() as PsiMethodCallExpression val elementFactory = JavaPsiFacade.getElementFactory(element.getProject()) val referenceExpression = element.firstChild as PsiReferenceExpression val sourceExpression = referenceExpression.firstChild sourceExpression.replace(elementFactory.createExpressionFromText(sourceExpression.text + ".asLazy()", sourceExpression)) CodeStyleManager.getInstance(project).reformat(JavaCodeStyleManager.getInstance(project).shortenClassReferences(element)) } }
mit
e2d6c9b16a1dd1924153c79e0322cb04
46.140845
198
0.699134
5.736075
false
false
false
false
afollestad/material-dialogs
sample/src/main/java/com/afollestad/materialdialogssample/Utils.kt
2
1813
/** * Designed and developed by Aidan Follestad (@afollestad) * * 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.afollestad.materialdialogssample import android.app.Activity import android.content.SharedPreferences import android.widget.Toast import java.text.SimpleDateFormat import java.util.Calendar import java.util.Locale private var toast: Toast? = null internal fun Activity.toast(message: CharSequence) { toast?.cancel() toast = Toast.makeText(this, message, Toast.LENGTH_SHORT) .apply { show() } } typealias PrefEditor = SharedPreferences.Editor internal fun SharedPreferences.boolean( key: String, defaultValue: Boolean = false ): Boolean { return getBoolean(key, defaultValue) } internal inline fun SharedPreferences.commit(crossinline exec: PrefEditor.() -> Unit) { val editor = this.edit() editor.exec() editor.apply() } internal fun Int.toHex() = "#${Integer.toHexString(this)}" internal fun Calendar.formatTime(): String { return SimpleDateFormat("kk:mm a", Locale.US).format(this.time) } internal fun Calendar.formatDate(): String { return SimpleDateFormat("MMMM dd, yyyy", Locale.US).format(this.time) } internal fun Calendar.formatDateTime(): String { return SimpleDateFormat("kk:mm a, MMMM dd, yyyy", Locale.US).format(this.time) }
apache-2.0
1fe51a620ffdce184dc8ac23585126ce
29.216667
87
0.749586
4.046875
false
false
false
false
ankidroid/Anki-Android
AnkiDroid/src/main/java/com/ichi2/libanki/backend/exception/DeckRenameException.kt
1
1412
//noinspection MissingCopyrightHeader #8659 package com.ichi2.libanki.backend.exception import android.content.res.Resources import com.ichi2.anki.R class DeckRenameException (private val errorCode: Int) : Exception() { // region only if FILTERED_NOSUBDECKS private var mFilteredAncestorName: String? = null private var mDeckName: String? = null // endregion override val message: String? get() = if (errorCode == FILTERED_NOSUBDECKS) { "Deck $mDeckName has filtered ancestor $mFilteredAncestorName" } else super.message fun getLocalizedMessage(res: Resources): String { return when (errorCode) { ALREADY_EXISTS -> res.getString(R.string.decks_rename_exists) FILTERED_NOSUBDECKS -> res.getString(R.string.decks_rename_filtered_nosubdecks) else -> "" } } companion object { const val ALREADY_EXISTS = 0 private const val FILTERED_NOSUBDECKS = 1 /** Generates a {@link com.ichi2.libanki.backend.exception.DeckRenameException} with additional information in the message */ fun filteredAncestor(deckName: String?, filteredAncestorName: String?): DeckRenameException { val ex = DeckRenameException(FILTERED_NOSUBDECKS) ex.mFilteredAncestorName = filteredAncestorName ex.mDeckName = deckName return ex } } }
gpl-3.0
5a4c99a2cf9510763cd0159c28c35239
35.205128
133
0.677054
4.468354
false
false
false
false
nosix/vue-kotlin
guide/syntax/main/Syntax.kt
1
1082
@file:Suppress("UnsafeCastFromDynamic") import org.musyozoku.vuekt.* @JsModule(vue.MODULE) @JsNonModule @JsName(vue.CLASS) external class ExampleVue(options: ComponentOptions<ExampleVue>) : Vue { var msg: String var rawHtml: String var dynamicId: String var isButtonDisabled: Boolean var number: Int var ok: Boolean var message: String var id: String var url: String } fun main(args: Array<String>) { val vm = ExampleVue(ComponentOptions { el = ElementConfig("#example") data = Data(json = json { msg = "Hi" rawHtml = """<input type="text" name="username" value="taro">""" dynamicId = "id-0101" isButtonDisabled = true number = 1 ok = true message = "hello" id = "1" url = "https://jp.vuejs.org/" }) methods = json { this["doSomething"] = { val self = thisAs<ExampleVue>() self.message = "do something" } } }) vm.msg = "Oh!" }
apache-2.0
62ef2131e68996a34b10ea79bcd7c2df
24.186047
76
0.543438
3.99262
false
false
false
false
JetBrains/anko
anko/library/generated/sdk19/src/main/java/Layouts.kt
2
60211
@file:JvmName("Sdk19LayoutsKt") package org.jetbrains.anko import android.content.Context import android.util.AttributeSet import android.view.ViewGroup import android.widget.FrameLayout import android.appwidget.AppWidgetHostView import android.view.View import android.widget.AbsoluteLayout import android.widget.Gallery import android.widget.GridLayout import android.widget.GridView import android.widget.AbsListView import android.widget.HorizontalScrollView import android.widget.ImageSwitcher import android.widget.LinearLayout import android.widget.RadioGroup import android.widget.RelativeLayout import android.widget.ScrollView import android.widget.TableLayout import android.widget.TableRow import android.widget.TextSwitcher import android.widget.ViewAnimator import android.widget.ViewSwitcher open class _AppWidgetHostView(ctx: Context): AppWidgetHostView(ctx) { inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(c!!, attrs!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet? ): T { val layoutParams = FrameLayout.LayoutParams(c!!, attrs!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(width, height) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT ): T { val layoutParams = FrameLayout.LayoutParams(width, height) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, gravity: Int, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(width, height, gravity) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, gravity: Int ): T { val layoutParams = FrameLayout.LayoutParams(width, height, gravity) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: FrameLayout.LayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: FrameLayout.LayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } } open class _AbsoluteLayout(ctx: Context): AbsoluteLayout(ctx) { inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, x: Int, y: Int, init: AbsoluteLayout.LayoutParams.() -> Unit ): T { val layoutParams = AbsoluteLayout.LayoutParams(width, height, x, y) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, x: Int, y: Int ): T { val layoutParams = AbsoluteLayout.LayoutParams(width, height, x, y) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet?, init: AbsoluteLayout.LayoutParams.() -> Unit ): T { val layoutParams = AbsoluteLayout.LayoutParams(c!!, attrs!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet? ): T { val layoutParams = AbsoluteLayout.LayoutParams(c!!, attrs!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams?, init: AbsoluteLayout.LayoutParams.() -> Unit ): T { val layoutParams = AbsoluteLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams? ): T { val layoutParams = AbsoluteLayout.LayoutParams(source!!) [email protected] = layoutParams return this } } open class _FrameLayout(ctx: Context): FrameLayout(ctx) { inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(c!!, attrs!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet? ): T { val layoutParams = FrameLayout.LayoutParams(c!!, attrs!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(width, height) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT ): T { val layoutParams = FrameLayout.LayoutParams(width, height) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, gravity: Int, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(width, height, gravity) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, gravity: Int ): T { val layoutParams = FrameLayout.LayoutParams(width, height, gravity) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: FrameLayout.LayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: FrameLayout.LayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } } open class _Gallery(ctx: Context): Gallery(ctx) { inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet?, init: Gallery.LayoutParams.() -> Unit ): T { val layoutParams = Gallery.LayoutParams(c!!, attrs!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet? ): T { val layoutParams = Gallery.LayoutParams(c!!, attrs!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, init: Gallery.LayoutParams.() -> Unit ): T { val layoutParams = Gallery.LayoutParams(width, height) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT ): T { val layoutParams = Gallery.LayoutParams(width, height) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams?, init: Gallery.LayoutParams.() -> Unit ): T { val layoutParams = Gallery.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams? ): T { val layoutParams = Gallery.LayoutParams(source!!) [email protected] = layoutParams return this } } open class _GridLayout(ctx: Context): GridLayout(ctx) { inline fun <T: View> T.lparams( rowSpec: GridLayout.Spec?, columnSpec: GridLayout.Spec?, init: GridLayout.LayoutParams.() -> Unit ): T { val layoutParams = GridLayout.LayoutParams(rowSpec!!, columnSpec!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( rowSpec: GridLayout.Spec?, columnSpec: GridLayout.Spec? ): T { val layoutParams = GridLayout.LayoutParams(rowSpec!!, columnSpec!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( init: GridLayout.LayoutParams.() -> Unit ): T { val layoutParams = GridLayout.LayoutParams() layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( ): T { val layoutParams = GridLayout.LayoutParams() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( params: ViewGroup.LayoutParams?, init: GridLayout.LayoutParams.() -> Unit ): T { val layoutParams = GridLayout.LayoutParams(params!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( params: ViewGroup.LayoutParams? ): T { val layoutParams = GridLayout.LayoutParams(params!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( params: ViewGroup.MarginLayoutParams?, init: GridLayout.LayoutParams.() -> Unit ): T { val layoutParams = GridLayout.LayoutParams(params!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( params: ViewGroup.MarginLayoutParams? ): T { val layoutParams = GridLayout.LayoutParams(params!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: GridLayout.LayoutParams?, init: GridLayout.LayoutParams.() -> Unit ): T { val layoutParams = GridLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: GridLayout.LayoutParams? ): T { val layoutParams = GridLayout.LayoutParams(source!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( context: Context?, attrs: AttributeSet?, init: GridLayout.LayoutParams.() -> Unit ): T { val layoutParams = GridLayout.LayoutParams(context!!, attrs!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( context: Context?, attrs: AttributeSet? ): T { val layoutParams = GridLayout.LayoutParams(context!!, attrs!!) [email protected] = layoutParams return this } } open class _GridView(ctx: Context): GridView(ctx) { inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet?, init: AbsListView.LayoutParams.() -> Unit ): T { val layoutParams = AbsListView.LayoutParams(c!!, attrs!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet? ): T { val layoutParams = AbsListView.LayoutParams(c!!, attrs!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, init: AbsListView.LayoutParams.() -> Unit ): T { val layoutParams = AbsListView.LayoutParams(width, height) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT ): T { val layoutParams = AbsListView.LayoutParams(width, height) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, viewType: Int, init: AbsListView.LayoutParams.() -> Unit ): T { val layoutParams = AbsListView.LayoutParams(width, height, viewType) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, viewType: Int ): T { val layoutParams = AbsListView.LayoutParams(width, height, viewType) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams?, init: AbsListView.LayoutParams.() -> Unit ): T { val layoutParams = AbsListView.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams? ): T { val layoutParams = AbsListView.LayoutParams(source!!) [email protected] = layoutParams return this } } open class _HorizontalScrollView(ctx: Context): HorizontalScrollView(ctx) { inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(c!!, attrs!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet? ): T { val layoutParams = FrameLayout.LayoutParams(c!!, attrs!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(width, height) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT ): T { val layoutParams = FrameLayout.LayoutParams(width, height) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, gravity: Int, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(width, height, gravity) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, gravity: Int ): T { val layoutParams = FrameLayout.LayoutParams(width, height, gravity) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: FrameLayout.LayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: FrameLayout.LayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } } open class _ImageSwitcher(ctx: Context): ImageSwitcher(ctx) { inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(c!!, attrs!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet? ): T { val layoutParams = FrameLayout.LayoutParams(c!!, attrs!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(width, height) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT ): T { val layoutParams = FrameLayout.LayoutParams(width, height) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, gravity: Int, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(width, height, gravity) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, gravity: Int ): T { val layoutParams = FrameLayout.LayoutParams(width, height, gravity) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: FrameLayout.LayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: FrameLayout.LayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } } open class _LinearLayout(ctx: Context): LinearLayout(ctx) { inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet?, init: LinearLayout.LayoutParams.() -> Unit ): T { val layoutParams = LinearLayout.LayoutParams(c!!, attrs!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet? ): T { val layoutParams = LinearLayout.LayoutParams(c!!, attrs!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, init: LinearLayout.LayoutParams.() -> Unit ): T { val layoutParams = LinearLayout.LayoutParams(width, height) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT ): T { val layoutParams = LinearLayout.LayoutParams(width, height) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, weight: Float, init: LinearLayout.LayoutParams.() -> Unit ): T { val layoutParams = LinearLayout.LayoutParams(width, height, weight) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, weight: Float ): T { val layoutParams = LinearLayout.LayoutParams(width, height, weight) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( p: ViewGroup.LayoutParams?, init: LinearLayout.LayoutParams.() -> Unit ): T { val layoutParams = LinearLayout.LayoutParams(p!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( p: ViewGroup.LayoutParams? ): T { val layoutParams = LinearLayout.LayoutParams(p!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams?, init: LinearLayout.LayoutParams.() -> Unit ): T { val layoutParams = LinearLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams? ): T { val layoutParams = LinearLayout.LayoutParams(source!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: LinearLayout.LayoutParams?, init: LinearLayout.LayoutParams.() -> Unit ): T { val layoutParams = LinearLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: LinearLayout.LayoutParams? ): T { val layoutParams = LinearLayout.LayoutParams(source!!) [email protected] = layoutParams return this } } open class _RadioGroup(ctx: Context): RadioGroup(ctx) { inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet?, init: RadioGroup.LayoutParams.() -> Unit ): T { val layoutParams = RadioGroup.LayoutParams(c!!, attrs!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet? ): T { val layoutParams = RadioGroup.LayoutParams(c!!, attrs!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, init: RadioGroup.LayoutParams.() -> Unit ): T { val layoutParams = RadioGroup.LayoutParams(width, height) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT ): T { val layoutParams = RadioGroup.LayoutParams(width, height) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, initWeight: Float, init: RadioGroup.LayoutParams.() -> Unit ): T { val layoutParams = RadioGroup.LayoutParams(width, height, initWeight) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, initWeight: Float ): T { val layoutParams = RadioGroup.LayoutParams(width, height, initWeight) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( p: ViewGroup.LayoutParams?, init: RadioGroup.LayoutParams.() -> Unit ): T { val layoutParams = RadioGroup.LayoutParams(p!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( p: ViewGroup.LayoutParams? ): T { val layoutParams = RadioGroup.LayoutParams(p!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams?, init: RadioGroup.LayoutParams.() -> Unit ): T { val layoutParams = RadioGroup.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams? ): T { val layoutParams = RadioGroup.LayoutParams(source!!) [email protected] = layoutParams return this } } open class _RelativeLayout(ctx: Context): RelativeLayout(ctx) { inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet?, init: RelativeLayout.LayoutParams.() -> Unit ): T { val layoutParams = RelativeLayout.LayoutParams(c!!, attrs!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet? ): T { val layoutParams = RelativeLayout.LayoutParams(c!!, attrs!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, init: RelativeLayout.LayoutParams.() -> Unit ): T { val layoutParams = RelativeLayout.LayoutParams(width, height) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT ): T { val layoutParams = RelativeLayout.LayoutParams(width, height) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams?, init: RelativeLayout.LayoutParams.() -> Unit ): T { val layoutParams = RelativeLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams? ): T { val layoutParams = RelativeLayout.LayoutParams(source!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams?, init: RelativeLayout.LayoutParams.() -> Unit ): T { val layoutParams = RelativeLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams? ): T { val layoutParams = RelativeLayout.LayoutParams(source!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: RelativeLayout.LayoutParams?, init: RelativeLayout.LayoutParams.() -> Unit ): T { val layoutParams = RelativeLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: RelativeLayout.LayoutParams? ): T { val layoutParams = RelativeLayout.LayoutParams(source!!) [email protected] = layoutParams return this } } open class _ScrollView(ctx: Context): ScrollView(ctx) { inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(c!!, attrs!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet? ): T { val layoutParams = FrameLayout.LayoutParams(c!!, attrs!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(width, height) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT ): T { val layoutParams = FrameLayout.LayoutParams(width, height) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, gravity: Int, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(width, height, gravity) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, gravity: Int ): T { val layoutParams = FrameLayout.LayoutParams(width, height, gravity) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: FrameLayout.LayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: FrameLayout.LayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } } open class _TableLayout(ctx: Context): TableLayout(ctx) { inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet?, init: TableLayout.LayoutParams.() -> Unit ): T { val layoutParams = TableLayout.LayoutParams(c!!, attrs!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet? ): T { val layoutParams = TableLayout.LayoutParams(c!!, attrs!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, init: TableLayout.LayoutParams.() -> Unit ): T { val layoutParams = TableLayout.LayoutParams(width, height) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT ): T { val layoutParams = TableLayout.LayoutParams(width, height) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, initWeight: Float, init: TableLayout.LayoutParams.() -> Unit ): T { val layoutParams = TableLayout.LayoutParams(width, height, initWeight) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, initWeight: Float ): T { val layoutParams = TableLayout.LayoutParams(width, height, initWeight) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( init: TableLayout.LayoutParams.() -> Unit ): T { val layoutParams = TableLayout.LayoutParams() layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( ): T { val layoutParams = TableLayout.LayoutParams() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( p: ViewGroup.LayoutParams?, init: TableLayout.LayoutParams.() -> Unit ): T { val layoutParams = TableLayout.LayoutParams(p!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( p: ViewGroup.LayoutParams? ): T { val layoutParams = TableLayout.LayoutParams(p!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams?, init: TableLayout.LayoutParams.() -> Unit ): T { val layoutParams = TableLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams? ): T { val layoutParams = TableLayout.LayoutParams(source!!) [email protected] = layoutParams return this } } open class _TableRow(ctx: Context): TableRow(ctx) { inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet?, init: TableRow.LayoutParams.() -> Unit ): T { val layoutParams = TableRow.LayoutParams(c!!, attrs!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet? ): T { val layoutParams = TableRow.LayoutParams(c!!, attrs!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, init: TableRow.LayoutParams.() -> Unit ): T { val layoutParams = TableRow.LayoutParams(width, height) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT ): T { val layoutParams = TableRow.LayoutParams(width, height) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, initWeight: Float, init: TableRow.LayoutParams.() -> Unit ): T { val layoutParams = TableRow.LayoutParams(width, height, initWeight) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, initWeight: Float ): T { val layoutParams = TableRow.LayoutParams(width, height, initWeight) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( init: TableRow.LayoutParams.() -> Unit ): T { val layoutParams = TableRow.LayoutParams() layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( ): T { val layoutParams = TableRow.LayoutParams() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( column: Int, init: TableRow.LayoutParams.() -> Unit ): T { val layoutParams = TableRow.LayoutParams(column) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( column: Int ): T { val layoutParams = TableRow.LayoutParams(column) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( p: ViewGroup.LayoutParams?, init: TableRow.LayoutParams.() -> Unit ): T { val layoutParams = TableRow.LayoutParams(p!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( p: ViewGroup.LayoutParams? ): T { val layoutParams = TableRow.LayoutParams(p!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams?, init: TableRow.LayoutParams.() -> Unit ): T { val layoutParams = TableRow.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams? ): T { val layoutParams = TableRow.LayoutParams(source!!) [email protected] = layoutParams return this } } open class _TextSwitcher(ctx: Context): TextSwitcher(ctx) { inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(c!!, attrs!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet? ): T { val layoutParams = FrameLayout.LayoutParams(c!!, attrs!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(width, height) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT ): T { val layoutParams = FrameLayout.LayoutParams(width, height) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, gravity: Int, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(width, height, gravity) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, gravity: Int ): T { val layoutParams = FrameLayout.LayoutParams(width, height, gravity) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: FrameLayout.LayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: FrameLayout.LayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } } open class _ViewAnimator(ctx: Context): ViewAnimator(ctx) { inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(c!!, attrs!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet? ): T { val layoutParams = FrameLayout.LayoutParams(c!!, attrs!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(width, height) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT ): T { val layoutParams = FrameLayout.LayoutParams(width, height) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, gravity: Int, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(width, height, gravity) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, gravity: Int ): T { val layoutParams = FrameLayout.LayoutParams(width, height, gravity) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: FrameLayout.LayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: FrameLayout.LayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } } open class _ViewSwitcher(ctx: Context): ViewSwitcher(ctx) { inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(c!!, attrs!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet? ): T { val layoutParams = FrameLayout.LayoutParams(c!!, attrs!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(width, height) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT ): T { val layoutParams = FrameLayout.LayoutParams(width, height) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, gravity: Int, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(width, height, gravity) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, gravity: Int ): T { val layoutParams = FrameLayout.LayoutParams(width, height, gravity) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: FrameLayout.LayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: FrameLayout.LayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } }
apache-2.0
2676b18f9b1dee1417f89dd3c47caaa6
30.857672
78
0.611134
4.875385
false
false
false
false
matkoniecz/StreetComplete
app/src/main/java/de/westnordost/streetcomplete/quests/AbstractQuestAnswerFragment.kt
1
16919
package de.westnordost.streetcomplete.quests import android.content.Context import android.content.res.Configuration import android.content.res.Resources import android.os.Bundle import android.view.LayoutInflater import android.view.Menu import android.view.View import android.view.ViewGroup import android.widget.PopupMenu import android.widget.TextView import androidx.annotation.AnyThread import androidx.appcompat.app.AlertDialog import androidx.core.os.bundleOf import androidx.core.view.isGone import androidx.core.widget.NestedScrollView import androidx.viewbinding.ViewBinding import de.westnordost.osmfeatures.FeatureDictionary import de.westnordost.streetcomplete.Injector import de.westnordost.streetcomplete.R import de.westnordost.streetcomplete.data.meta.CountryInfo import de.westnordost.streetcomplete.data.meta.CountryInfos import de.westnordost.streetcomplete.data.osm.geometry.ElementGeometry import de.westnordost.streetcomplete.data.osm.mapdata.Element import de.westnordost.streetcomplete.data.osm.mapdata.ElementType import de.westnordost.streetcomplete.data.osm.mapdata.Way import de.westnordost.streetcomplete.data.osm.osmquests.OsmElementQuestType import de.westnordost.streetcomplete.data.quest.* import de.westnordost.streetcomplete.databinding.ButtonPanelButtonBinding import de.westnordost.streetcomplete.databinding.FragmentQuestAnswerBinding import de.westnordost.streetcomplete.ktx.* import de.westnordost.streetcomplete.quests.shop_type.ShopGoneDialog import kotlinx.serialization.decodeFromString import kotlinx.serialization.encodeToString import kotlinx.serialization.json.Json import java.lang.ref.WeakReference import java.util.Locale import java.util.concurrent.FutureTask import javax.inject.Inject /** Abstract base class for any bottom sheet with which the user answers a specific quest(ion) */ abstract class AbstractQuestAnswerFragment<T> : AbstractBottomSheetFragment(), IsShowingQuestDetails, IsLockable { private var _binding: FragmentQuestAnswerBinding? = null private val binding get() = _binding!! protected var otherAnswersButton: TextView? = null private set override val bottomSheetContainer get() = binding.bottomSheetContainer override val bottomSheet get() = binding.bottomSheet override val scrollViewChild get() = binding.scrollViewChild override val bottomSheetTitle get() = binding.speechBubbleTitleContainer override val bottomSheetContent get() = binding.speechbubbleContentContainer override val floatingBottomView get() = binding.okButton override val backButton get() = binding.closeButton protected val scrollView: NestedScrollView get() = binding.scrollView // dependencies private val countryInfos: CountryInfos private val questTypeRegistry: QuestTypeRegistry private val featureDictionaryFuture: FutureTask<FeatureDictionary> private var _countryInfo: CountryInfo? = null // lazy but resettable because based on lateinit var get() { if(field == null) { val latLon = elementGeometry.center field = countryInfos.get(latLon.longitude, latLon.latitude) } return field } protected val countryInfo get() = _countryInfo!! protected val featureDictionary: FeatureDictionary get() = featureDictionaryFuture.get() // passed in parameters override lateinit var questKey: QuestKey protected lateinit var elementGeometry: ElementGeometry private set private lateinit var questType: QuestType<T> private var initialMapRotation = 0f private var initialMapTilt = 0f protected var osmElement: Element? = null private set private var currentContext = WeakReference<Context>(null) private val englishResources: Resources get() { val conf = Configuration(resources.configuration) conf.setLocale(Locale.ENGLISH) val localizedContext = super.requireContext().createConfigurationContext(conf) return localizedContext.resources } private var startedOnce = false override var locked: Boolean = false set(value) { field = value binding.glassPane.isGone = !locked } // overridable by child classes open val contentLayoutResId: Int? = null open val buttonPanelAnswers = listOf<AnswerItem>() open val otherAnswers = listOf<AnswerItem>() open val contentPadding = true interface Listener { /** Called when the user answered the quest with the given id. What is in the bundle, is up to * the dialog with which the quest was answered */ fun onAnsweredQuest(questKey: QuestKey, answer: Any) /** Called when the user chose to leave a note instead */ fun onComposeNote(questKey: QuestKey, questTitle: String) /** Called when the user chose to split the way */ fun onSplitWay(osmQuestKey: OsmQuestKey) /** Called when the user chose to skip the quest */ fun onSkippedQuest(questKey: QuestKey) /** Called when the node shall be deleted */ fun onDeletePoiNode(osmQuestKey: OsmQuestKey) /** Called when a new feature has been selected for an element (a shop of some kind) */ fun onReplaceShopElement(osmQuestKey: OsmQuestKey, tags: Map<String, String>) } private val listener: Listener? get() = parentFragment as? Listener ?: activity as? Listener init { val fields = InjectedFields() Injector.applicationComponent.inject(fields) countryInfos = fields.countryInfos featureDictionaryFuture = fields.featureDictionaryFuture questTypeRegistry = fields.questTypeRegistry } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val args = requireArguments() questKey = Json.decodeFromString(args.getString(ARG_QUEST_KEY)!!) osmElement = args.getString(ARG_ELEMENT)?.let { Json.decodeFromString(it) } elementGeometry = Json.decodeFromString(args.getString(ARG_GEOMETRY)!!) questType = questTypeRegistry.getByName(args.getString(ARG_QUESTTYPE)!!) as QuestType<T> initialMapRotation = args.getFloat(ARG_MAP_ROTATION) initialMapTilt = args.getFloat(ARG_MAP_TILT) _countryInfo = null // reset lazy field /* The Android resource system is not designed to offer different resources depending on the * country (code). But what it can do is to offer different resources for different * "mobile country codes" - i.e. in which country your mobile phone network provider * operates. * * A few quest forms want to display different resources depending on the country. * * So what we do here is to override the parent activity's "mobile country code" resource * configuration and use this mechanism to access our country-dependent resources */ countryInfo.mobileCountryCode?.let { activity?.resources?.updateConfiguration { mcc = it } } } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { _binding = FragmentQuestAnswerBinding.inflate(inflater, container, false) /* content and buttons panel should be inflated in onCreateView because in onViewCreated, * subclasses may already want to access the content. */ otherAnswersButton = ButtonPanelButtonBinding.inflate(layoutInflater, binding.buttonPanel, true).root contentLayoutResId?.let { setContentView(it) } updateButtonPanel() return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) binding.titleLabel.text = resources.getHtmlQuestTitle(questType, osmElement, featureDictionaryFuture) val levelLabelText = osmElement?.let { resources.getLocationLabelString(it.tags) } binding.titleHintLabel.isGone = levelLabelText == null if (levelLabelText != null) { binding.titleHintLabel.text = levelLabelText } // no content? -> hide the content container if (binding.content.childCount == 0) { binding.content.visibility = View.GONE } } override fun onDestroyView() { super.onDestroyView() _binding = null otherAnswersButton = null } private fun assembleOtherAnswers() : List<AnswerItem> { val answers = mutableListOf<AnswerItem>() val cantSay = AnswerItem(R.string.quest_generic_answer_notApplicable) { onClickCantSay() } answers.add(cantSay) createSplitWayAnswer()?.let { answers.add(it) } createDeleteOrReplaceElementAnswer()?.let { answers.add(it) } answers.addAll(otherAnswers) return answers } private fun createSplitWayAnswer(): AnswerItem? { val isSplitWayEnabled = (questType as? OsmElementQuestType)?.isSplitWayEnabled == true if (!isSplitWayEnabled) return null val way = osmElement as? Way ?: return null /* splitting up a closed roundabout can be very complex if it is part of a route relation, so it is not supported https://wiki.openstreetmap.org/wiki/Relation:route#Bus_routes_and_roundabouts */ val isClosedRoundabout = way.nodeIds.firstOrNull() == way.nodeIds.lastOrNull() && way.tags["junction"] == "roundabout" if (isClosedRoundabout) return null if (way.isArea()) return null return AnswerItem(R.string.quest_generic_answer_differs_along_the_way) { onClickSplitWayAnswer() } } private fun createDeleteOrReplaceElementAnswer(): AnswerItem? { val isDeletePoiEnabled = (questType as? OsmElementQuestType)?.isDeleteElementEnabled == true && osmElement?.type == ElementType.NODE val isReplaceShopEnabled = (questType as? OsmElementQuestType)?.isReplaceShopEnabled == true if (!isDeletePoiEnabled && !isReplaceShopEnabled) return null check(!(isDeletePoiEnabled && isReplaceShopEnabled)) { "Only isDeleteElementEnabled OR isReplaceShopEnabled may be true at the same time" } return AnswerItem(R.string.quest_generic_answer_does_not_exist) { if (isDeletePoiEnabled) deletePoiNode() else if (isReplaceShopEnabled) replaceShopElement() } } private fun showOtherAnswers() { val otherAnswersButton = otherAnswersButton ?: return val answers = assembleOtherAnswers() val popup = PopupMenu(requireContext(), otherAnswersButton) for (i in answers.indices) { val otherAnswer = answers[i] val order = answers.size - i popup.menu.add(Menu.NONE, i, order, otherAnswer.titleResourceId) } popup.show() popup.setOnMenuItemClickListener { item -> answers[item.itemId].action() true } } override fun onStart() { super.onStart() if(!startedOnce) { onMapOrientation(initialMapRotation, initialMapTilt) startedOnce = true } val answers = assembleOtherAnswers() if (answers.size == 1) { otherAnswersButton?.setText(answers.first().titleResourceId) otherAnswersButton?.setOnClickListener { answers.first().action() } } else { otherAnswersButton?.setText(R.string.quest_generic_otherAnswers) otherAnswersButton?.setOnClickListener { showOtherAnswers() } } } protected fun onClickCantSay() { context?.let { AlertDialog.Builder(it) .setTitle(R.string.quest_leave_new_note_title) .setMessage(R.string.quest_leave_new_note_description) .setNegativeButton(R.string.quest_leave_new_note_no) { _, _ -> skipQuest() } .setPositiveButton(R.string.quest_leave_new_note_yes) { _, _ -> composeNote() } .show() } } protected fun composeNote() { val questTitle = englishResources.getQuestTitle(questType, osmElement, featureDictionaryFuture) listener?.onComposeNote(questKey, questTitle) } private fun onClickSplitWayAnswer() { context?.let { AlertDialog.Builder(it) .setMessage(R.string.quest_split_way_description) .setNegativeButton(android.R.string.cancel, null) .setPositiveButton(android.R.string.ok) { _, _ -> listener?.onSplitWay(questKey as OsmQuestKey) } .show() } } protected fun applyAnswer(data: T) { listener?.onAnsweredQuest(questKey, data as Any) } protected fun skipQuest() { listener?.onSkippedQuest(questKey) } protected fun replaceShopElement() { val ctx = context ?: return val element = osmElement ?: return val isoCountryCode = countryInfo.countryCode.substringBefore('-') if (element.isSomeKindOfShop()) { ShopGoneDialog( ctx, element.geometryType, isoCountryCode, featureDictionary, onSelectedFeature = { tags -> listener?.onReplaceShopElement(questKey as OsmQuestKey, tags) }, onLeaveNote = this::composeNote ).show() } else { composeNote() } } protected fun deletePoiNode() { val context = context ?: return AlertDialog.Builder(context) .setMessage(R.string.osm_element_gone_description) .setPositiveButton(R.string.osm_element_gone_confirmation) { _, _ -> listener?.onDeletePoiNode(questKey as OsmQuestKey) } .setNeutralButton(R.string.leave_note) { _, _ -> composeNote() }.show() } /** Inflate given layout resource id into the content view and return the inflated view */ protected fun setContentView(resourceId: Int): View { if (binding.content.childCount > 0) { binding.content.removeAllViews() } binding.content.visibility = View.VISIBLE updateContentPadding() layoutInflater.inflate(resourceId, binding.content) return binding.content.getChildAt(0) } private fun updateContentPadding() { if(!contentPadding) { binding.content.setPadding(0,0,0,0) } else { val horizontal = resources.getDimensionPixelSize(R.dimen.quest_form_horizontal_padding) val vertical = resources.getDimensionPixelSize(R.dimen.quest_form_vertical_padding) binding.content.setPadding(horizontal, vertical, horizontal, vertical) } } protected fun updateButtonPanel() { // the other answers button is never removed/replaced if (binding.buttonPanel.childCount > 1) { binding.buttonPanel.removeViews(1, binding.buttonPanel.childCount - 1) } for (buttonPanelAnswer in buttonPanelAnswers) { val button = ButtonPanelButtonBinding.inflate(layoutInflater, binding.buttonPanel, true).root button.setText(buttonPanelAnswer.titleResourceId) button.setOnClickListener { buttonPanelAnswer.action() } } } @AnyThread open fun onMapOrientation(rotation: Float, tilt: Float) { // default empty implementation } class InjectedFields { @Inject internal lateinit var countryInfos: CountryInfos @Inject internal lateinit var questTypeRegistry: QuestTypeRegistry @Inject internal lateinit var featureDictionaryFuture: FutureTask<FeatureDictionary> } protected inline fun <reified T : ViewBinding> contentViewBinding( noinline viewBinder: (View) -> T ) = FragmentViewBindingPropertyDelegate(this, viewBinder, R.id.content) companion object { private const val ARG_QUEST_KEY = "quest_key" private const val ARG_ELEMENT = "element" private const val ARG_GEOMETRY = "geometry" private const val ARG_QUESTTYPE = "quest_type" private const val ARG_MAP_ROTATION = "map_rotation" private const val ARG_MAP_TILT = "map_tilt" fun createArguments(quest: Quest, element: Element?, rotation: Float, tilt: Float) = bundleOf( ARG_QUEST_KEY to Json.encodeToString(quest.key), ARG_ELEMENT to element?.let { Json.encodeToString(element) }, ARG_GEOMETRY to Json.encodeToString(quest.geometry), ARG_QUESTTYPE to quest.type::class.simpleName!!, ARG_MAP_ROTATION to rotation, ARG_MAP_TILT to tilt ) } } data class AnswerItem(val titleResourceId: Int, val action: () -> Unit)
gpl-3.0
6e3858e61e253bb2672bf9e18e9f452d
39.187648
116
0.681482
4.882828
false
false
false
false
rafaelwkerr/duplicate-user
app/src/main/java/ninenine/com/duplicateuser/presenter/UserPresenterImpl.kt
1
1266
package ninenine.com.duplicateuser.presenter import android.util.Log import io.reactivex.Flowable import io.reactivex.rxkotlin.toFlowable import ninenine.com.duplicateuser.functions.convertDateISO8601 import ninenine.com.duplicateuser.repository.UserRepository import ninenine.com.duplicateuser.view.UserContractView import javax.inject.Inject import javax.inject.Singleton @Singleton class UserPresenterImpl @Inject constructor(private val userRepository: UserRepository) : UserPresenter { private val TAG = UserPresenterImpl::class.java.simpleName var userContractView: UserContractView? = null override fun attachView(view: UserContractView) { view.let { userContractView=view } } override fun loadUsers() { val userSetObservable = userRepository.getUsersWithSet()?.toFlowable() userSetObservable?.let { it .flatMap { it.birthday = convertDateISO8601(it.birthday) Flowable.just(it) } .toList() .subscribe( {userContractView?.showUsers(it)}, {Log.e(TAG, "error=" + it)} ) } } }
mit
071eea100fd1989321ef48b610ae4cda
30.675
105
0.632701
5.146341
false
false
false
false
pdvrieze/ProcessManager
PE-common/src/commonMain/kotlin/org/w3/soapEnvelope/NotUnderstoodType.kt
1
1618
/* * Copyright (c) 2018. * * This file is part of ProcessManager. * * ProcessManager is free software: you can redistribute it and/or modify it under the terms of version 3 of the * GNU Lesser General Public License as published by the Free Software Foundation. * * ProcessManager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even * the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License along with ProcessManager. If not, * see <http://www.gnu.org/licenses/>. */ // // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2009.09.24 at 08:12:58 PM CEST // package org.w3.soapEnvelope import nl.adaptivity.xmlutil.QName /** * * * Java class for NotUnderstoodType complex type. * * * The following schema fragment specifies the expected content contained within * this class. * * ``` * <complexType name="NotUnderstoodType"> * <complexContent> * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * <attribute name="qname" use="required" type="{http://www.w3.org/2001/XMLSchema}QName" /> * </restriction> * </complexContent> * </complexType> * ``` */ class NotUnderstoodType { var qname: QName? = null }
lgpl-3.0
2239e8c5a615d6f8294582a553d0f987
29.528302
124
0.720643
3.702517
false
false
false
false
Kotlin/kotlinx.serialization
benchmark/src/jmh/kotlin/kotlinx/benchmarks/protobuf/ProtoListBenchmark.kt
1
1075
/* * Copyright 2017-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. */ package kotlinx.benchmarks.protobuf import kotlinx.serialization.* import kotlinx.serialization.protobuf.* import kotlinx.serialization.protobuf.ProtoBuf.Default.encodeToByteArray import org.openjdk.jmh.annotations.* import java.util.concurrent.* @Warmup(iterations = 5, time = 1) @Measurement(iterations = 5, time = 1) @BenchmarkMode(Mode.Throughput) @OutputTimeUnit(TimeUnit.MICROSECONDS) @State(Scope.Benchmark) @Fork(1) open class ProtoListBenchmark { @Serializable class Holder(val a: Int, val b: Int, val c: Long, val d: Double) @Serializable class HolderList(val list: List<Holder>) private val h = Holder(1, 2, 3L, 4.0) private val value = HolderList(listOf(h, h, h, h, h)) private val bytes = ProtoBuf.encodeToByteArray(value) @Benchmark fun toBytes() = ProtoBuf.encodeToByteArray(HolderList.serializer(), value) @Benchmark fun fromBytes() = ProtoBuf.decodeFromByteArray(HolderList.serializer(), bytes) }
apache-2.0
60fa7d43ece482b8123d3fa2f753c9fa
29.714286
102
0.740465
3.866906
false
false
false
false