repo_name
stringlengths
7
81
path
stringlengths
6
242
copies
stringclasses
55 values
size
stringlengths
2
6
content
stringlengths
55
737k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
5.44
99.8
line_max
int64
15
979
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.93
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
tinmegali/android_achitecture_components_sample
app/src/main/java/com/tinmegali/myweather/web/LiveDataCallAdapter.kt
1
1662
package com.tinmegali.myweather.web import android.arch.lifecycle.LiveData import com.tinmegali.myweather.models.ApiResponse import com.tinmegali.myweather.models.WeatherResponse import java.lang.reflect.Type import java.util.concurrent.atomic.AtomicBoolean import retrofit2.Call import retrofit2.CallAdapter import retrofit2.Callback import retrofit2.Response class LiveDataCallAdapter<R>( private val responseType: Type ) : CallAdapter<R, LiveData<ApiResponse<R>>> { override fun responseType(): Type { return responseType } override fun adapt(call: Call<R>): LiveData<ApiResponse<R>> { return object : LiveData<ApiResponse<R>>() { internal var started = AtomicBoolean(false) override fun onActive() { super.onActive() if (started.compareAndSet(false, true)) { call.enqueue(object : Callback<R> { override fun onResponse(call1: Call<R>, response: Response<R>) { postValue(ApiResponse( data = response.body() )) } override fun onFailure(call2: Call<R>, t: Throwable) { postValue(ApiResponse( error = ApiError( message = t.message, statusCode = 500 ) )) } }) } } } } }
apache-2.0
86c7f691cd0f095da54bb352e27dd0b6
30.358491
88
0.5
5.633898
false
false
false
false
dahlstrom-g/intellij-community
platform/platform-impl/src/com/intellij/openapi/application/impl/AppUIExecutorImpl.kt
4
9621
// 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.application.impl import com.intellij.ide.IdeEventQueue import com.intellij.ide.lightEdit.LightEdit import com.intellij.openapi.Disposable import com.intellij.openapi.application.AppUIExecutor import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.ModalityState import com.intellij.openapi.application.TransactionGuard import com.intellij.openapi.application.constraints.ConstrainedExecution.ContextConstraint import com.intellij.openapi.application.constraints.Expiration import com.intellij.openapi.command.CommandProcessor import com.intellij.openapi.project.DumbService import com.intellij.openapi.project.Project import com.intellij.psi.PsiDocumentManager import com.intellij.psi.impl.PsiDocumentManagerBase import kotlinx.coroutines.Runnable import kotlinx.coroutines.async import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import org.jetbrains.annotations.ApiStatus import java.util.concurrent.Executor import java.util.function.BooleanSupplier import kotlin.coroutines.ContinuationInterceptor import kotlin.coroutines.CoroutineContext /** * @author peter * @author eldar */ internal class AppUIExecutorImpl private constructor(private val modality: ModalityState, private val thread: ExecutionThread, constraints: Array<ContextConstraint>, cancellationConditions: Array<BooleanSupplier>, expirableHandles: Set<Expiration>) : AppUIExecutor, BaseExpirableExecutorMixinImpl<AppUIExecutorImpl>(constraints, cancellationConditions, expirableHandles, getExecutorForThread(thread, modality)) { constructor(modality: ModalityState, thread: ExecutionThread) : this(modality, thread, emptyArray(), emptyArray(), emptySet()) companion object { private fun getExecutorForThread(thread: ExecutionThread, modality: ModalityState): Executor { return when (thread) { ExecutionThread.EDT -> MyEdtExecutor(modality) ExecutionThread.WT -> MyWtExecutor(modality) } } } private class MyWtExecutor(private val modality: ModalityState) : Executor { override fun execute(command: Runnable) { if (ApplicationManager.getApplication().isWriteThread && (ApplicationImpl.USE_SEPARATE_WRITE_THREAD || !TransactionGuard.getInstance().isWriteSafeModality(modality) || TransactionGuard.getInstance().isWritingAllowed) && !ModalityState.current().dominates(modality)) { command.run() } else { ApplicationManager.getApplication().invokeLaterOnWriteThread(command, modality) } } } private class MyEdtExecutor(private val modality: ModalityState) : Executor { override fun execute(command: Runnable) { if (ApplicationManager.getApplication().isDispatchThread && (!TransactionGuard.getInstance().isWriteSafeModality(modality) || TransactionGuard.getInstance().isWritingAllowed) && !ModalityState.current().dominates(modality)) { command.run() } else { ApplicationManager.getApplication().invokeLater(command, modality) } } } override fun cloneWith(constraints: Array<ContextConstraint>, cancellationConditions: Array<BooleanSupplier>, expirationSet: Set<Expiration>): AppUIExecutorImpl { return AppUIExecutorImpl(modality, thread, constraints, cancellationConditions, expirationSet) } override fun dispatchLaterUnconstrained(runnable: Runnable) { return when (thread) { ExecutionThread.EDT -> ApplicationManager.getApplication().invokeLater(runnable, modality) ExecutionThread.WT -> ApplicationManager.getApplication().invokeLaterOnWriteThread(runnable, modality) } } override fun later(): AppUIExecutorImpl { val edtEventCount = if (ApplicationManager.getApplication().isDispatchThread) IdeEventQueue.getInstance().eventCount else -1 return withConstraint(object : ContextConstraint { @Volatile var usedOnce: Boolean = false override fun isCorrectContext(): Boolean { return when (thread) { ExecutionThread.EDT -> when (edtEventCount) { -1 -> ApplicationManager.getApplication().isDispatchThread else -> usedOnce || edtEventCount != IdeEventQueue.getInstance().eventCount } ExecutionThread.WT -> usedOnce } } override fun schedule(runnable: Runnable) { dispatchLaterUnconstrained(Runnable { usedOnce = true runnable.run() }) } override fun toString() = "later" }) } override fun withDocumentsCommitted(project: Project): AppUIExecutorImpl { return withConstraint(WithDocumentsCommitted(project, modality), project) } @Deprecated("Beware, context might be infectious, if coroutine resumes other waiting coroutines. " + "Use runUndoTransparentWriteAction instead.", ReplaceWith("this")) @ApiStatus.ScheduledForRemoval fun inUndoTransparentAction(): AppUIExecutorImpl { return withConstraint(object : ContextConstraint { override fun isCorrectContext(): Boolean = CommandProcessor.getInstance().isUndoTransparentActionInProgress override fun schedule(runnable: Runnable) { CommandProcessor.getInstance().runUndoTransparentAction(runnable) } override fun toString() = "inUndoTransparentAction" }) } @Deprecated("Beware, context might be infectious, if coroutine resumes other waiting coroutines. " + "Use runWriteAction instead.", ReplaceWith("this")) @ApiStatus.ScheduledForRemoval fun inWriteAction(): AppUIExecutorImpl { return withConstraint(object : ContextConstraint { override fun isCorrectContext(): Boolean = ApplicationManager.getApplication().isWriteAccessAllowed override fun schedule(runnable: Runnable) { ApplicationManager.getApplication().runWriteAction(runnable) } override fun toString() = "inWriteAction" }) } override fun inSmartMode(project: Project): AppUIExecutorImpl { return withConstraint(InSmartMode(project), project) } } @Deprecated("Beware, context might be infectious, if coroutine resumes other waiting coroutines. " + "Use runUndoTransparentWriteAction instead.", ReplaceWith("this")) @ApiStatus.ScheduledForRemoval fun AppUIExecutor.inUndoTransparentAction(): AppUIExecutor { return (this as AppUIExecutorImpl).inUndoTransparentAction() } @Deprecated("Beware, context might be infectious, if coroutine resumes other waiting coroutines. " + "Use runWriteAction instead.", ReplaceWith("this")) @ApiStatus.ScheduledForRemoval fun AppUIExecutor.inWriteAction():AppUIExecutor { return (this as AppUIExecutorImpl).inWriteAction() } fun AppUIExecutor.withConstraint(constraint: ContextConstraint): AppUIExecutor { return (this as AppUIExecutorImpl).withConstraint(constraint) } fun AppUIExecutor.withConstraint(constraint: ContextConstraint, parentDisposable: Disposable): AppUIExecutor { return (this as AppUIExecutorImpl).withConstraint(constraint, parentDisposable) } /** * A [context][CoroutineContext] to be used with the standard [launch], [async], [withContext] coroutine builders. * Contains: [ContinuationInterceptor]. */ @Suppress("DeprecatedCallableAddReplaceWith") @Deprecated( message = "Do not use: coroutine cancellation must not be handled by a dispatcher. " + "Use Dispatchers.Main and ModalityState.asContextElement() if needed", ) fun AppUIExecutor.coroutineDispatchingContext(): ContinuationInterceptor { return (this as AppUIExecutorImpl).asCoroutineDispatcher() } internal class WithDocumentsCommitted(private val project: Project, private val modality: ModalityState) : ContextConstraint { override fun isCorrectContext(): Boolean { val manager = PsiDocumentManager.getInstance(project) as PsiDocumentManagerBase return !manager.isCommitInProgress && !manager.hasEventSystemEnabledUncommittedDocuments() } override fun schedule(runnable: Runnable) { PsiDocumentManager.getInstance(project).performLaterWhenAllCommitted(modality, runnable) } override fun toString(): String { val isCorrectContext = isCorrectContext() val details = if (isCorrectContext) { "" } else { val manager = PsiDocumentManager.getInstance(project) as PsiDocumentManagerBase ", isCommitInProgress()=${manager.isCommitInProgress}" + ", hasEventSystemEnabledUncommittedDocuments()=${manager.hasEventSystemEnabledUncommittedDocuments()}" } return "withDocumentsCommitted {isCorrectContext()=$isCorrectContext$details}" } } internal class InSmartMode(private val project: Project) : ContextConstraint { init { check(!LightEdit.owns(project)) { "InSmartMode can't be used in LightEdit mode, check that LightEdit.owns(project)==false before calling" } } override fun isCorrectContext() = !project.isDisposed && !DumbService.isDumb(project) override fun schedule(runnable: Runnable) { DumbService.getInstance(project).runWhenSmart(runnable) } override fun toString() = "inSmartMode" } internal enum class ExecutionThread { EDT, WT }
apache-2.0
0723f6b759b28b919573f279ef786117
39.42437
128
0.728199
5.522962
false
false
false
false
evoasm/evoasm
src/evoasm/x64/InterpreterOptions.kt
1
4613
package evoasm.x64 import kasm.x64.* class InterpreterOptions(instructions: List<Instruction> = defaultInstructions, val allowUnsupportedInstructions: Boolean = false, val safeDivision: Boolean = true, val compressOpcodes: Boolean = true, val threadCount: Int = 1, val forceMultithreading: Boolean = false, val moveInstructions: List<MoveInstruction> = defaultMoveInstructions, val movesGenerator: (MoveInstruction, List<Register>) -> Sequence<Pair<Register, Register>> = ::defaultMovesGenerator, val xmmOperandRegisters: List<List<XmmRegister>> = DEFAULT_XMM_OPERAND_REGISTERS, val ymmOperandRegisters: List<List<YmmRegister>> = DEFAULT_YMM_OPERAND_REGISTERS, val mmOperandRegisters: List<List<MmRegister>> = DEFAULT_MM_OPERAND_REGISTERS, val gp64OperandRegisters: List<List<GpRegister64>> = DEFAULT_GP64_OPERAND_REGISTERS, val gp32OperandRegisters: List<List<GpRegister32>> = DEFAULT_GP32_OPERAND_REGISTERS, val gp16OperandRegisters: List<List<GpRegister16>> = DEFAULT_GP16_OPERAND_REGISTERS, val gp8OperandRegisters: List<List<GpRegister8>> = DEFAULT_GP8_OPERAND_REGISTERS, val unsafe: Boolean) { companion object { private fun supportedInstruction(i0: Instruction, i1: Instruction, allowUnsupportedInstructions: Boolean): Instruction { if (allowUnsupportedInstructions || i1.isSupported()) return i1 return i0 } val defaultInstructions: List<Instruction> get() { return InstructionGroup.all } private fun <E> repeatList(count: Int, list: List<E>): List<List<E>> { return List(count) {list} } val DEFAULT_XMM_OPERAND_REGISTERS = repeatList(4, listOf(XmmRegister.XMM0, XmmRegister.XMM1, XmmRegister.XMM2)) val DEFAULT_YMM_OPERAND_REGISTERS = repeatList(4, listOf(YmmRegister.YMM0, YmmRegister.YMM1, YmmRegister.YMM2)) val DEFAULT_MM_OPERAND_REGISTERS = repeatList(3, listOf(MmRegister.MM0, MmRegister.MM1, MmRegister.MM2)) val DEFAULT_GP64_OPERAND_REGISTERS = repeatList(3, Interpreter.GP_REGISTERS.take(3)) val DEFAULT_GP32_OPERAND_REGISTERS = repeatList(3, Interpreter.GP_REGISTERS.take(3).map{it.subRegister32}) val DEFAULT_GP16_OPERAND_REGISTERS = repeatList(3, Interpreter.GP_REGISTERS.take(3).map{it.subRegister16}) val DEFAULT_GP8_OPERAND_REGISTERS = repeatList(3, Interpreter.GP_REGISTERS.take(3).map{it.subRegister8}) val defaultMoveInstructions: List<MoveInstruction> get() { return listOf(MovR64Rm64, MovsdXmmm64Xmm) } val DEFAULT = InterpreterOptions(unsafe = false) fun defaultMovesGenerator(moveInstruction: MoveInstruction, registers: List<Register>): Sequence<Pair<Register, Register>> { val list = mutableListOf<Pair<Register, Register>>() val maxOperandRegisterCount = when(registers.first()) { is XmmRegister, is YmmRegister -> 3 else -> 2 } for (i in 0 until maxOperandRegisterCount) { val destinationRegister = registers[i] for(j in 0 until maxOperandRegisterCount) { val sourceRegister = registers[j] list.add(destinationRegister to sourceRegister) } } for (i in maxOperandRegisterCount until registers.lastIndex) { list.add(registers[i] to registers[i % maxOperandRegisterCount]) list.add(registers[(i + 1) % maxOperandRegisterCount] to registers[i]) } // Hmmm, this gives operandsRegisterCount**2 + 2 * (n - operandsRegisterCount) instructions // i.e. 9 + 2 * 13 = 33 for e.g. XMM registers return list.asSequence() } } val instructions: List<Instruction> init { this.instructions = if (!allowUnsupportedInstructions) { instructions.filter { val supported = it.isSupported() if (!supported) Interpreter.LOGGER.info("filtering out unsupported instruction ${it}") supported } } else { instructions } } }
agpl-3.0
9b108429d8b8d042f7cb9c80d32dd42b
42.933333
143
0.605029
4.75567
false
false
false
false
paplorinc/intellij-community
platform/vcs-impl/src/com/intellij/openapi/vcs/changes/ui/DefaultCommitResultHandler.kt
2
2857
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.vcs.changes.ui import com.intellij.openapi.util.text.StringUtil.* import com.intellij.openapi.vcs.VcsBundle.message import com.intellij.openapi.vcs.VcsException import com.intellij.openapi.vcs.VcsNotifier import com.intellij.openapi.vcs.changes.CommitResultHandler import com.intellij.openapi.vcs.changes.ui.AbstractCommitter.Companion.collectErrors private val FROM = listOf("<", ">") private val TO = listOf("&lt;", "&gt;") /* Commit message is passed to NotificationManagerImpl#doNotify and displayed as HTML. Thus HTML tag braces (< and >) should be escaped, but only they since the text is passed directly to HTML <BODY> tag and is not a part of an attribute or else. */ private fun escape(s: String) = replace(s, FROM, TO) private fun hasOnlyWarnings(exceptions: List<VcsException>) = exceptions.all { it.isWarning } class DefaultCommitResultHandler(private val committer: AbstractCommitter) : CommitResultHandler { override fun onSuccess(commitMessage: String) = reportResult() override fun onFailure() = reportResult() private fun reportResult() { val allExceptions = committer.exceptions val errors = collectErrors(allExceptions) val errorsSize = errors.size val warningsSize = allExceptions.size - errorsSize val notifier = VcsNotifier.getInstance(committer.project) val message = getCommitSummary() when { errorsSize > 0 -> { val title = pluralize(message("message.text.commit.failed.with.error"), errorsSize) notifier.notifyError(title, message) } warningsSize > 0 -> { val title = pluralize(message("message.text.commit.finished.with.warning"), warningsSize) notifier.notifyImportantWarning(title, message) } else -> notifier.notifySuccess(message) } } private fun getCommitSummary() = StringBuilder(getFileSummaryReport()).apply { val commitMessage = committer.commitMessage if (!isEmpty(commitMessage)) { append(": ").append(escape(commitMessage)) } val feedback = committer.feedback if (!feedback.isEmpty()) { append("<br/>") append(join(feedback, "<br/>")) } val exceptions = committer.exceptions if (!hasOnlyWarnings(exceptions)) { append("<br/>") append(join(exceptions, { it.message }, "<br/>")) } }.toString() private fun getFileSummaryReport(): String { val failed = committer.failedToCommitChanges.size val committed = committer.changes.size - failed var fileSummary = "$committed ${pluralize("file", committed)} committed" if (failed > 0) { fileSummary += ", $failed ${pluralize("file", failed)} failed to commit" } return fileSummary } }
apache-2.0
f0b56cd3b4ebbd9bb000b31e08fba105
36.116883
140
0.711586
4.31571
false
false
false
false
PlanBase/PdfLayoutMgr2
src/main/java/com/planbase/pdf/lm2/utils/Coord.kt
1
2325
// Copyright 2017 PlanBase Inc. // // This file is part of PdfLayoutMgr2 // // PdfLayoutMgr is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // PdfLayoutMgr is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with PdfLayoutMgr. If not, see <https://www.gnu.org/licenses/agpl-3.0.en.html>. // // If you wish to use this code with proprietary software, // contact PlanBase Inc. <https://planbase.com> to purchase a commercial license. package com.planbase.pdf.lm2.utils import kotlin.math.abs /** An immutable 2D Coordinate, offset, or point in terms of X and Y. Often measured from the lower-left corner. Do not confuse this with an Dim which represents positive width and height. This is called Coord because Point and Point2D are already classes in Java and they are mutable. It's pronounced "co-ward" as in, "coordinate." It's not called Xy because that's too easy to confuse with width and height, which this is not - it's an offset from the origin. */ data class Coord(val x: Double, val y: Double) { fun withX(newX: Double) = Coord(newX, y) fun withY(newY: Double) = Coord(x, newY) fun plusX(offset: Double) = if (offset == 0.0) { this } else { Coord(x + offset, y) } fun plusY(offset: Double) = if (offset == 0.0) { this } else { Coord(x, y + offset) } fun minusY(offset: Double) = if (offset == 0.0) { this } else { Coord(x, y - offset) } // fun plusXMinusY(that: Coord) = Coord(x + that.x, y - that.y) fun plusXMinusY(dim: Dim) = if (dim == Dim.ZERO) this else Coord(x + dim.width, y - dim.height) fun plusXMinusY(xOff: Double, yOff: Double) = if ( (xOff == 0.0) && (yOff == 0.0) ) this else Coord(x + xOff, y - yOff) fun dimensionTo(that: Coord) = Dim(abs(x - that.x), abs(y - that.y)) override fun toString(): String = "Coord($x, $y)" }
agpl-3.0
e94992354ce0d2bd3804ad35df9c9e32
40.517857
110
0.67957
3.506787
false
false
false
false
paplorinc/intellij-community
plugins/editorconfig/src/org/editorconfig/language/codeinsight/quickfixes/EditorConfigRemoveDeprecatedElementQuickFix.kt
2
1592
// 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.editorconfig.language.codeinsight.quickfixes import com.intellij.codeInsight.template.TemplateBuilderImpl import com.intellij.codeInsight.template.TemplateManager import com.intellij.codeInsight.template.impl.MacroCallNode import com.intellij.codeInsight.template.macro.CompleteMacro import com.intellij.codeInspection.LocalQuickFix import com.intellij.codeInspection.ProblemDescriptor import com.intellij.openapi.application.runWriteAction import com.intellij.openapi.fileEditor.FileEditorManager import com.intellij.openapi.project.Project import org.editorconfig.language.messages.EditorConfigBundle import org.editorconfig.language.psi.interfaces.EditorConfigDescribableElement class EditorConfigRemoveDeprecatedElementQuickFix : LocalQuickFix { override fun getFamilyName() = EditorConfigBundle["quickfix.deprecated.element.remove"] override fun applyFix(project: Project, descriptor: ProblemDescriptor) { val element = descriptor.psiElement as? EditorConfigDescribableElement ?: return val editor = FileEditorManager.getInstance(project).selectedTextEditor ?: return val templateManager = TemplateManager.getInstance(project) val builder = TemplateBuilderImpl(element) builder.replaceElement(element, MacroCallNode(CompleteMacro())) runWriteAction { val template = builder.buildInlineTemplate() template.isToReformat = true templateManager.startTemplate(editor, template) } } }
apache-2.0
4f6ad55cd41eacaa6dbde85d51d7a988
50.354839
140
0.827261
5.254125
false
true
false
false
jguerinet/android-utils
settings/src/main/java/com/guerinet/suitcase/settings/NullBooleanSetting.kt
2
1607
/* * Copyright 2016-2021 Julien Guerinet * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.guerinet.suitcase.settings import com.russhwolf.settings.ExperimentalSettingsApi import com.russhwolf.settings.Settings import com.russhwolf.settings.coroutines.getBooleanOrNullFlow import com.russhwolf.settings.set import kotlinx.coroutines.flow.Flow /** * Helper class for nullable Boolean settings * @author Julien Guerinet * @since 7.0.0 */ open class NullBooleanSetting(settings: Settings, key: String, defaultValue: Boolean? = null) : BaseSetting<Boolean?>(settings, key, defaultValue) { override var value: Boolean? get() = settings.getBooleanOrNull(key) ?: defaultValue set(value) = set(value) override fun set(value: Boolean?) { if (value != null) { settings[key] = value } else { // If the value that we are trying to set is null, clear the value clear() } } @ExperimentalSettingsApi override fun asFlow(): Flow<Boolean?> = observableSettings.getBooleanOrNullFlow(key) }
apache-2.0
c874cd8ccd17485b299456e900038b03
32.479167
95
0.712508
4.152455
false
false
false
false
google/intellij-community
platform/platform-impl/src/com/intellij/openapi/wm/impl/SquareStripeButton.kt
1
6298
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.openapi.wm.impl import com.intellij.icons.AllIcons import com.intellij.ide.HelpTooltip import com.intellij.ide.actions.ActivateToolWindowAction import com.intellij.openapi.actionSystem.* import com.intellij.openapi.actionSystem.impl.ActionButton import com.intellij.openapi.project.DumbAware import com.intellij.openapi.util.IconLoader import com.intellij.openapi.util.ScalableIcon import com.intellij.openapi.wm.ToolWindow import com.intellij.openapi.wm.ToolWindowAnchor import com.intellij.openapi.wm.impl.SquareStripeButton.Companion.createMoveGroup import com.intellij.toolWindow.ToolWindowEventSource import com.intellij.ui.MouseDragHelper import com.intellij.ui.PopupHandler import com.intellij.ui.ToggleActionButton import com.intellij.ui.UIBundle import com.intellij.util.ui.JBInsets import com.intellij.util.ui.JBUI import java.awt.Component import java.awt.Dimension import java.awt.Graphics import java.awt.Rectangle import java.awt.event.MouseEvent internal class SquareStripeButton(val toolWindow: ToolWindowImpl) : ActionButton(SquareAnActionButton(toolWindow), createPresentation(toolWindow), ActionPlaces.TOOLWINDOW_TOOLBAR_BAR, Dimension(40, 40)) { companion object { fun createMoveGroup(toolWindow: ToolWindow) = ToolWindowMoveToAction.Group(toolWindow) } init { setLook(SquareStripeButtonLook(this)) addMouseListener(object : PopupHandler() { override fun invokePopup(component: Component, x: Int, y: Int) { val popupMenu = ActionManager.getInstance() .createActionPopupMenu(ActionPlaces.TOOLWINDOW_POPUP, createPopupGroup(toolWindow)) popupMenu.component.show(component, x, y) } }) MouseDragHelper.setComponentDraggable(this, true) } override fun updateUI() { super.updateUI() myPresentation.icon = toolWindow.icon ?: AllIcons.Toolbar.Unknown scaleIcon(myPresentation) myPresentation.isEnabledAndVisible = true } fun updatePresentation() { updateToolTipText() myPresentation.icon = toolWindow.icon ?: AllIcons.Toolbar.Unknown scaleIcon(myPresentation) } fun isHovered() = myRollover fun isFocused() = toolWindow.isActive fun resetDrop() = resetMouseState() fun paintDraggingButton(g: Graphics) { val areaSize = size.also { JBInsets.removeFrom(it, insets) JBInsets.removeFrom(it, SquareStripeButtonLook.ICON_PADDING) } val rect = Rectangle(areaSize) buttonLook.paintLookBackground(g, rect, JBUI.CurrentTheme.ActionButton.pressedBackground()) icon.let { val x = (areaSize.width - it.iconWidth) / 2 val y = (areaSize.height - it.iconHeight) / 2 buttonLook.paintIcon(g, this, it, x, y) } buttonLook.paintLookBorder(g, rect, JBUI.CurrentTheme.ActionButton.pressedBorder()) } override fun updateToolTipText() { @Suppress("DialogTitleCapitalization") HelpTooltip() .setTitle(toolWindow.stripeTitle) .setLocation(getAlignment(toolWindow.anchor, toolWindow.isSplitMode)) .setShortcut(ActionManager.getInstance().getKeyboardShortcut(ActivateToolWindowAction.getActionIdForToolWindow(toolWindow.id))) .setInitialDelay(0) .setHideDelay(0) .installOn(this) HelpTooltip.setMasterPopupOpenCondition(this) { !(parent as AbstractDroppableStripe).isDroppingButton() } } override fun checkSkipPressForEvent(e: MouseEvent) = e.button != MouseEvent.BUTTON1 } private fun getAlignment(anchor: ToolWindowAnchor, splitMode: Boolean): HelpTooltip.Alignment { return when (anchor) { ToolWindowAnchor.RIGHT -> HelpTooltip.Alignment.LEFT ToolWindowAnchor.TOP -> HelpTooltip.Alignment.LEFT ToolWindowAnchor.LEFT -> HelpTooltip.Alignment.RIGHT ToolWindowAnchor.BOTTOM -> if (splitMode) HelpTooltip.Alignment.LEFT else HelpTooltip.Alignment.RIGHT else -> HelpTooltip.Alignment.RIGHT } } private fun createPresentation(toolWindow: ToolWindowImpl): Presentation { val presentation = Presentation(toolWindow.stripeTitle) presentation.icon = toolWindow.icon ?: AllIcons.Toolbar.Unknown scaleIcon(presentation) presentation.isEnabledAndVisible = true return presentation } private fun scaleIcon(presentation: Presentation) { if (presentation.icon is ScalableIcon && presentation.icon.iconWidth != 20) { presentation.icon = IconLoader.loadCustomVersionOrScale(presentation.icon as ScalableIcon, 20f) } } private fun createPopupGroup(toolWindow: ToolWindowImpl): DefaultActionGroup { val group = DefaultActionGroup() group.add(HideAction(toolWindow)) group.addSeparator() group.add(createMoveGroup(toolWindow)) return group } private class HideAction(private val toolWindow: ToolWindowImpl) : AnAction(UIBundle.message("tool.window.new.stripe.hide.action.name")), DumbAware { override fun actionPerformed(e: AnActionEvent) { toolWindow.toolWindowManager.hideToolWindow(id = toolWindow.id, hideSide = false, moveFocus = true, removeFromStripe = true, source = ToolWindowEventSource.SquareStripeButton) } } private class SquareAnActionButton(private val window: ToolWindowImpl) : ToggleActionButton(window.stripeTitle, null), DumbAware { override fun isSelected(e: AnActionEvent): Boolean { e.presentation.icon = window.icon ?: AllIcons.Toolbar.Unknown scaleIcon(e.presentation) return window.isVisible } override fun getActionUpdateThread(): ActionUpdateThread { return ActionUpdateThread.BGT } override fun setSelected(e: AnActionEvent, state: Boolean) { if (e.project!!.isDisposed) { return } val manager = window.toolWindowManager if (state) { manager.activated(window, ToolWindowEventSource.SquareStripeButton) } else { manager.hideToolWindow(id = window.id, hideSide = false, moveFocus = true, removeFromStripe = false, source = ToolWindowEventSource.SquareStripeButton) } } }
apache-2.0
36cf8cef02829ae48b1d51d97a98579a
36.052941
138
0.730867
4.760393
false
false
false
false
JetBrains/intellij-community
plugins/kotlin/test-framework/test/org/jetbrains/kotlin/idea/test/KotlinSdkCreationChecker.kt
1
1276
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.test import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.runReadAction import com.intellij.openapi.application.runWriteAction import com.intellij.openapi.projectRoots.ProjectJdkTable import com.intellij.openapi.projectRoots.Sdk import org.jetbrains.kotlin.idea.framework.KotlinSdkType class KotlinSdkCreationChecker { private val projectJdkTable: ProjectJdkTable get() = runReadAction { ProjectJdkTable.getInstance() } private val sdksBefore: Array<out Sdk> = projectJdkTable.allJdks fun getKotlinSdks() = projectJdkTable.allJdks.filter { it.sdkType is KotlinSdkType } private fun getCreatedKotlinSdks() = projectJdkTable.allJdks.filter { !sdksBefore.contains(it) && it.sdkType is KotlinSdkType } fun isKotlinSdkCreated() = getCreatedKotlinSdks().isNotEmpty() fun removeNewKotlinSdk() { ApplicationManager.getApplication().invokeAndWait { runWriteAction { getCreatedKotlinSdks().forEach { projectJdkTable.removeJdk(it) } } } } }
apache-2.0
6905edff7a76c40c068532e238b2ef38
38.90625
158
0.755486
4.888889
false
false
false
false
JetBrains/intellij-community
plugins/kotlin/compiler-reference-index/src/org/jetbrains/kotlin/idea/search/refIndex/KotlinCompilerReferenceIndexStorage.kt
1
7789
// 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.search.refIndex import com.intellij.compiler.server.BuildManager import com.intellij.openapi.application.runReadAction import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.project.Project import com.intellij.openapi.vfs.VfsUtil import com.intellij.openapi.vfs.VirtualFile import com.intellij.util.SmartList import com.intellij.util.concurrency.AppExecutorUtil import com.intellij.util.containers.MultiMap import com.intellij.util.indexing.UnindexedFilesUpdater import com.intellij.util.io.CorruptedException import com.intellij.util.io.EnumeratorStringDescriptor import com.intellij.util.io.PersistentHashMap import org.jetbrains.annotations.TestOnly import org.jetbrains.jps.builders.impl.BuildDataPathsImpl import org.jetbrains.jps.builders.java.JavaModuleBuildTargetType import org.jetbrains.jps.builders.storage.BuildDataPaths import org.jetbrains.kotlin.config.SettingConstants import org.jetbrains.kotlin.incremental.KOTLIN_CACHE_DIRECTORY_NAME import org.jetbrains.kotlin.incremental.storage.BasicMapsOwner import org.jetbrains.kotlin.incremental.storage.CollectionExternalizer import org.jetbrains.kotlin.name.FqName import java.nio.file.Path import java.util.concurrent.Future import kotlin.io.path.* import kotlin.system.measureTimeMillis class KotlinCompilerReferenceIndexStorage private constructor( kotlinDataContainerPath: Path, private val lookupStorageReader: LookupStorageReader, ) { companion object { /** * [org.jetbrains.kotlin.incremental.AbstractIncrementalCache.Companion.SUBTYPES] */ private val SUBTYPES_STORAGE_NAME = "subtypes.${BasicMapsOwner.CACHE_EXTENSION}" private val STORAGE_INDEXING_EXECUTOR = AppExecutorUtil.createBoundedApplicationPoolExecutor( "Kotlin compiler references indexing", UnindexedFilesUpdater.getMaxNumberOfIndexingThreads() ) private val LOG = logger<KotlinCompilerReferenceIndexStorage>() fun open(project: Project): KotlinCompilerReferenceIndexStorage? { val projectPath = runReadAction { project.takeUnless(Project::isDisposed)?.basePath } ?: return null val buildDataPaths = project.buildDataPaths val kotlinDataContainerPath = buildDataPaths?.kotlinDataContainer ?: kotlin.run { LOG.warn("${SettingConstants.KOTLIN_DATA_CONTAINER_ID} is not found") return null } val lookupStorageReader = LookupStorageReader.create(kotlinDataContainerPath, projectPath) ?: kotlin.run { LOG.warn("LookupStorage not found or corrupted") return null } val storage = KotlinCompilerReferenceIndexStorage(kotlinDataContainerPath, lookupStorageReader) if (!storage.initialize(buildDataPaths)) return null return storage } fun close(storage: KotlinCompilerReferenceIndexStorage?) { storage?.close().let { LOG.info("KCRI storage is closed" + if (it == null) " (didn't exist)" else "") } } fun hasIndex(project: Project): Boolean = LookupStorageReader.hasStorage(project) @TestOnly fun initializeForTests( buildDataPaths: BuildDataPaths, destination: ClassOneToManyStorage, ) = initializeSubtypeStorage(buildDataPaths, destination) internal val Project.buildDataPaths: BuildDataPaths? get() = BuildManager.getInstance().getProjectSystemDirectory(this)?.let(::BuildDataPathsImpl) internal val BuildDataPaths.kotlinDataContainer: Path? get() = targetsDataRoot?.toPath() ?.resolve(SettingConstants.KOTLIN_DATA_CONTAINER_ID) ?.takeIf { it.exists() && it.isDirectory() } ?.listDirectoryEntries("${SettingConstants.KOTLIN_DATA_CONTAINER_ID}*") ?.firstOrNull() private fun initializeSubtypeStorage(buildDataPaths: BuildDataPaths, destination: ClassOneToManyStorage): Boolean { var wasCorrupted = false val destinationMap = MultiMap.createConcurrentSet<String, String>() val futures = mutableListOf<Future<*>>() val timeOfFilling = measureTimeMillis { visitSubtypeStorages(buildDataPaths) { storagePath -> futures += STORAGE_INDEXING_EXECUTOR.submit { try { initializeStorage(destinationMap, storagePath) } catch (e: CorruptedException) { wasCorrupted = true LOG.warn("KCRI storage was corrupted", e) } } } try { for (future in futures) { future.get() } } catch (e: InterruptedException) { LOG.warn("KCRI initialization was interrupted") throw e } } if (wasCorrupted) return false val timeOfFlush = measureTimeMillis { for ((key, values) in destinationMap.entrySet()) { destination.put(key, values) } } LOG.info("KCRI storage is opened: took ${timeOfFilling + timeOfFlush} ms for ${futures.size} storages (filling map: $timeOfFilling ms, flush to storage: $timeOfFlush ms)") return true } private fun visitSubtypeStorages(buildDataPaths: BuildDataPaths, processor: (Path) -> Unit) { for (buildTargetType in JavaModuleBuildTargetType.ALL_TYPES) { val buildTargetPath = buildDataPaths.getTargetTypeDataRoot(buildTargetType).toPath() if (buildTargetPath.notExists() || !buildTargetPath.isDirectory()) continue buildTargetPath.forEachDirectoryEntry { targetDataRoot -> val workingPath = targetDataRoot.takeIf { it.isDirectory() } ?.resolve(KOTLIN_CACHE_DIRECTORY_NAME) ?.resolve(SUBTYPES_STORAGE_NAME) ?.takeUnless { it.notExists() } ?: return@forEachDirectoryEntry processor(workingPath) } } } } private val subtypesStorage = ClassOneToManyStorage(kotlinDataContainerPath.resolve(SUBTYPES_STORAGE_NAME)) /** * @return true if initialization was successful */ private fun initialize(buildDataPaths: BuildDataPaths): Boolean = initializeSubtypeStorage(buildDataPaths, subtypesStorage) private fun close() { lookupStorageReader.close() subtypesStorage.closeAndClean() } fun getUsages(fqName: FqName): List<VirtualFile> = lookupStorageReader[fqName].mapNotNull { VfsUtil.findFile(it, false) } fun getSubtypesOf(fqName: FqName, deep: Boolean): Sequence<FqName> = subtypesStorage[fqName, deep] } private fun initializeStorage(destinationMap: MultiMap<String, String>, subtypesSourcePath: Path) { createKotlinDataReader(subtypesSourcePath).use { source -> source.processKeys { key -> source[key]?.let { values -> destinationMap.putValues(key, values) } true } } } private fun createKotlinDataReader(storagePath: Path): PersistentHashMap<String, Collection<String>> = openReadOnlyPersistentHashMap( storagePath, EnumeratorStringDescriptor.INSTANCE, CollectionExternalizer<String>(EnumeratorStringDescriptor.INSTANCE, ::SmartList), )
apache-2.0
51aed4a6c6232478950a826569fa0fef
42.758427
183
0.663757
5.394044
false
false
false
false
littleGnAl/Accounting
app/src/main/java/com/littlegnal/accounting/base/util/DimensionExtensions.kt
1
928
package com.littlegnal.accounting.base.util import android.content.Context import android.view.View /** Copy from [anko](https://github.com/Kotlin/anko/blob/d5a526512b48c5cd2e3b8f6ff14b153c2337aa22/anko/library/static/commons/src/Dimensions.kt) */ // returns dip(dp) dimension value in pixels fun Context.dip(value: Int): Int = (value * resources.displayMetrics.density).toInt() fun Context.dip(value: Float): Int = (value * resources.displayMetrics.density).toInt() // return sp dimension value in pixels fun Context.sp(value: Int): Int = (value * resources.displayMetrics.scaledDensity).toInt() fun Context.sp(value: Float): Int = (value * resources.displayMetrics.scaledDensity).toInt() // the same for the views fun View.dip(value: Int): Int = context.dip(value) fun View.dip(value: Float): Int = context.dip(value) fun View.sp(value: Int): Int = context.sp(value) fun View.sp(value: Float): Int = context.sp(value)
apache-2.0
c0a8160522c7d5b6bf43e8afb57eec4d
39.347826
144
0.755388
3.244755
false
false
false
false
allotria/intellij-community
plugins/git4idea/src/git4idea/repo/GitCommitTemplateTracker.kt
2
10095
// 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 git4idea.repo import com.intellij.openapi.Disposable import com.intellij.openapi.components.Service import com.intellij.openapi.components.service import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.progress.util.BackgroundTaskUtil import com.intellij.openapi.project.Project import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.vcs.impl.VcsInitObject import com.intellij.openapi.vcs.impl.VcsStartupActivity import com.intellij.openapi.vfs.LocalFileSystem import com.intellij.openapi.vfs.newvfs.events.* import com.intellij.util.ObjectUtils import com.intellij.util.SystemProperties import com.intellij.util.messages.Topic import com.intellij.vfs.AsyncVfsEventsListener import com.intellij.vfs.AsyncVfsEventsPostProcessor import git4idea.GitUtil import git4idea.commands.Git import git4idea.config.GitConfigUtil import git4idea.config.GitConfigUtil.COMMIT_TEMPLATE import java.io.File import java.io.IOException import java.util.concurrent.atomic.AtomicBoolean import java.util.concurrent.locks.ReentrantReadWriteLock import kotlin.concurrent.read import kotlin.concurrent.write private val LOG = logger<GitCommitTemplateTracker>() @Service internal class GitCommitTemplateTracker(private val project: Project) : GitConfigListener, AsyncVfsEventsListener, Disposable { private val commitTemplates = mutableMapOf<GitRepository, GitCommitTemplate>() private val TEMPLATES_LOCK = ReentrantReadWriteLock() private val started = AtomicBoolean() init { project.messageBus.connect(this).subscribe(GitConfigListener.TOPIC, this) AsyncVfsEventsPostProcessor.getInstance().addListener(this, this) } fun isStarted() = started.get() fun templatesCount(): Int { return TEMPLATES_LOCK.read { commitTemplates.values.size } } @JvmOverloads fun exists(repository: GitRepository? = null): Boolean { return TEMPLATES_LOCK.read { if (repository != null) commitTemplates.containsKey(repository) else commitTemplates.values.isNotEmpty() } } @JvmOverloads fun getTemplateContent(repository: GitRepository? = null): String? { return TEMPLATES_LOCK.read { if (repository != null) commitTemplates[repository]?.content else commitTemplates.values.firstOrNull()?.content } } override fun notifyConfigChanged(repository: GitRepository) { trackCommitTemplate(repository) } override fun filesChanged(events: List<VFileEvent>) { if (TEMPLATES_LOCK.read { commitTemplates.isEmpty() }) return BackgroundTaskUtil.runUnderDisposeAwareIndicator(this) { processEvents(events) } } private fun start() { BackgroundTaskUtil.syncPublisher(project, GitCommitTemplateListener.TOPIC).loadingStarted() GitUtil.getRepositories(project).forEach(::trackCommitTemplate) if (started.compareAndSet(false, true)) { BackgroundTaskUtil.syncPublisher(project, GitCommitTemplateListener.TOPIC).loadingFinished() } } private fun processEvents(events: List<VFileEvent>) { val allTemplates = TEMPLATES_LOCK.read { commitTemplates.toMap() } if (allTemplates.isEmpty()) return for (event in events) { ProgressManager.checkCanceled() for ((repository, template) in allTemplates) { ProgressManager.checkCanceled() val watchedTemplatePath = template.watchedRoot.rootPath var templateChanged = false if (isEventToStopTracking(event, watchedTemplatePath)) { synchronized(this) { stopTrackCommitTemplate(repository) } templateChanged = true } else if (isEventToReloadTemplateContent(event, watchedTemplatePath)) { synchronized(this) { reloadCommitTemplateContent(repository) } templateChanged = true } if (templateChanged) { BackgroundTaskUtil.syncPublisher(project, GitCommitTemplateListener.TOPIC).notifyCommitTemplateChanged(repository) } } } } private fun isEventToStopTracking(event: VFileEvent, watchedTemplatePath: String): Boolean { return when { event is VFileDeleteEvent -> event.path == watchedTemplatePath event is VFileMoveEvent -> event.oldPath == watchedTemplatePath event is VFilePropertyChangeEvent && event.isRename -> event.oldPath == watchedTemplatePath else -> false } } private fun isEventToReloadTemplateContent(event: VFileEvent, watchedTemplatePath: String): Boolean { return event is VFileContentChangeEvent && event.path == watchedTemplatePath } private fun stopTrackCommitTemplate(repository: GitRepository) { val commitTemplate = TEMPLATES_LOCK.write { commitTemplates.remove(repository) } ?: return LocalFileSystem.getInstance().removeWatchedRoot(commitTemplate.watchedRoot) } private fun reloadCommitTemplateContent(repository: GitRepository) { val commitTemplateRootPath = TEMPLATES_LOCK.read { commitTemplates[repository] }?.watchedRoot?.rootPath ?: return val loadedContent = loadTemplateContent(repository, commitTemplateRootPath) ?: return TEMPLATES_LOCK.write { commitTemplates[repository]?.let { commitTemplate -> commitTemplate.content = loadedContent } } } private fun loadTemplateContent(repository: GitRepository, commitTemplateFilePath: String): String? { try { return FileUtil.loadFile(File(commitTemplateFilePath), GitConfigUtil.getCommitEncoding(project, repository.root)) } catch (e: IOException) { LOG.warn("Cannot load commit template for repository $repository by path $commitTemplateFilePath", e) return null } } private fun resolveCommitTemplatePath(repository: GitRepository): String? { val gitCommitTemplatePath = Git.getInstance().config(repository, COMMIT_TEMPLATE).outputAsJoinedString if (gitCommitTemplatePath.isBlank()) return null return if (FileUtil.exists(gitCommitTemplatePath)) { gitCommitTemplatePath } else ObjectUtils.chooseNotNull(getPathRelativeToUserHome(gitCommitTemplatePath), repository.findPathRelativeToRootDirs(gitCommitTemplatePath)) } private fun getPathRelativeToUserHome(fileNameOrPath: String): String? { if (fileNameOrPath.startsWith('~')) { val fileAtUserHome = File(SystemProperties.getUserHome(), fileNameOrPath.substring(1)) if (fileAtUserHome.exists()) { return fileAtUserHome.path } } return null } private fun GitRepository.findPathRelativeToRootDirs(relativeFilePath: String): String? { if (relativeFilePath.startsWith('/') || relativeFilePath.endsWith('/')) return null for (rootDir in repositoryFiles.rootDirs) { val rootDirParent = rootDir.parent?.path ?: continue val templateFile = File(rootDirParent, relativeFilePath) if (templateFile.exists()) return templateFile.path } return null } private fun trackCommitTemplate(repository: GitRepository) { val newTemplatePath = resolveCommitTemplatePath(repository) val templateChanged = synchronized(this) { updateTemplatePath(repository, newTemplatePath) } if (templateChanged) { BackgroundTaskUtil.syncPublisher(project, GitCommitTemplateListener.TOPIC).notifyCommitTemplateChanged(repository) } } private fun updateTemplatePath(repository: GitRepository, newTemplatePath: String?): Boolean { val oldWatchRoot = TEMPLATES_LOCK.read { commitTemplates[repository]?.watchedRoot } val oldTemplatePath = oldWatchRoot?.rootPath if (oldTemplatePath == newTemplatePath) return false if (newTemplatePath == null) { stopTrackCommitTemplate(repository) return true } val lfs = LocalFileSystem.getInstance() //explicit refresh needed for global templates to subscribe them in VFS and receive VFS events lfs.refreshAndFindFileByPath(newTemplatePath) val templateContent = loadTemplateContent(repository, newTemplatePath) if (templateContent == null) { stopTrackCommitTemplate(repository) return true } val newWatchRoot = when { oldWatchRoot != null -> lfs.replaceWatchedRoot(oldWatchRoot, newTemplatePath, false) else -> lfs.addRootToWatch(newTemplatePath, false) } if (newWatchRoot == null) { LOG.error("Cannot add root to watch $newTemplatePath") if (oldWatchRoot != null) { stopTrackCommitTemplate(repository) return true } return false } TEMPLATES_LOCK.write { commitTemplates[repository] = GitCommitTemplate(newWatchRoot, templateContent) } return true } override fun dispose() { val watchRootsToDispose = TEMPLATES_LOCK.read { commitTemplates.values.map(GitCommitTemplate::watchedRoot) } if (watchRootsToDispose.isEmpty()) return val lfs = LocalFileSystem.getInstance() for (watchedRoot in watchRootsToDispose) { lfs.removeWatchedRoot(watchedRoot) } TEMPLATES_LOCK.write { commitTemplates.clear() } } internal class GitCommitTemplateTrackerStartupActivity : VcsStartupActivity { override fun runActivity(project: Project) { project.service<GitCommitTemplateTracker>().start() } override fun getOrder(): Int = VcsInitObject.AFTER_COMMON.order } companion object { @JvmStatic fun getInstance(project: Project): GitCommitTemplateTracker = project.service() } } private class GitCommitTemplate(val watchedRoot: LocalFileSystem.WatchRequest, var content: String) internal interface GitCommitTemplateListener { @JvmDefault fun loadingStarted() {} @JvmDefault fun loadingFinished() {} fun notifyCommitTemplateChanged(repository: GitRepository) companion object { @JvmField @Topic.ProjectLevel val TOPIC: Topic<GitCommitTemplateListener> = Topic(GitCommitTemplateListener::class.java, Topic.BroadcastDirection.NONE, true) } }
apache-2.0
4219ff9d0729e1d36e1f48a09a6440e1
35.31295
146
0.744824
4.879169
false
false
false
false
DmytroTroynikov/aemtools
inspection/src/main/kotlin/com/aemtools/inspection/sling/DefaultInjectionStrategyInspection.kt
1
2363
package com.aemtools.inspection.sling import com.aemtools.common.constant.const import com.aemtools.common.util.annotations import com.aemtools.common.util.findParentByType import com.aemtools.inspection.common.AemIntellijInspection import com.intellij.codeInspection.ProblemHighlightType import com.intellij.codeInspection.ProblemsHolder import com.intellij.codeInspection.RemoveAnnotationQuickFix import com.intellij.psi.JavaElementVisitor import com.intellij.psi.PsiAnnotation import com.intellij.psi.PsiClass import com.intellij.psi.PsiElementVisitor /** * AEM-16 implementation. * * Will report `@Optional` annotation as "unused" on `@Inject`'ed field in * case if `@Model` annotation has `defaultInjectionStrategy = OPTIONAL`. * * @author Dmytro Troynikov */ class DefaultInjectionStrategyInspection : AemIntellijInspection( groupName = "AEM", name = "Default Injection Strategy", description = """ This inspection checks that <i>@Optional</i> is not used with <i>defaultInjectionStrategy</i> set to <i>OPTIONAL</i> """ ) { private fun checkAnnotation(annotation: PsiAnnotation, containerClass: PsiClass, holder: ProblemsHolder) { val modelAnnotation = containerClass.annotations() .find { it.qualifiedName == const.java.SLING_MODEL } ?: return val injectionStrategy = modelAnnotation.parameterList.attributes.find { nameValuePair -> nameValuePair.name == "defaultInjectionStrategy" } ?: return if (injectionStrategy.value?.text?.contains("OPTIONAL") ?: false) { holder.registerProblem( annotation, "Redundant annotation", ProblemHighlightType.LIKE_UNUSED_SYMBOL, RemoveAnnotationQuickFix( annotation, null ) ) } } override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor { return object : JavaElementVisitor() { override fun visitAnnotation(annotation: PsiAnnotation) { if (annotation.qualifiedName == const.java.OPTIONAL) { val containerClass = annotation.findParentByType(PsiClass::class.java) ?: return checkAnnotation( annotation, containerClass, holder ) } } } } }
gpl-3.0
6634bd2691edd4ce74272d8f4645a5e5
32.757143
93
0.685569
4.985232
false
false
false
false
allotria/intellij-community
plugins/git4idea/src/git4idea/index/GitIndexStatusUtil.kt
2
9417
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package git4idea.index import com.intellij.openapi.project.Project import com.intellij.openapi.util.NlsSafe import com.intellij.openapi.util.text.StringUtil import com.intellij.openapi.vcs.FilePath import com.intellij.openapi.vcs.FileStatus import com.intellij.openapi.vcs.VcsException import com.intellij.openapi.vfs.VfsUtilCore import com.intellij.openapi.vfs.VirtualFile import git4idea.GitUtil import git4idea.commands.Git import git4idea.commands.GitCommand import git4idea.commands.GitLineHandler import git4idea.config.GitExecutable import git4idea.config.GitExecutableManager import git4idea.config.GitVersion import git4idea.config.GitVersionSpecialty import git4idea.i18n.GitBundle import org.jetbrains.annotations.Nls const val NUL = "\u0000" /* * `git status` output format (porcelain version 1): * * XY PATH * XY PATH\u0000ORIG_PATH * * X Y Meaning * ------------------------------------------------- * [AMD] not updated * M [ MD] updated in index * A [ MD] added to index * D deleted from index * R [ MD] renamed in index * C [ MD] copied in index * [MARC] index and work tree matches * [ MARC] M work tree changed since index * [ MARC] D deleted in work tree * [ D] R renamed in work tree * [ D] C copied in work tree * ------------------------------------------------- * D D unmerged, both deleted * A U unmerged, added by us * U D unmerged, deleted by them * U A unmerged, added by them * D U unmerged, deleted by us * A A unmerged, both added * U U unmerged, both modified * ------------------------------------------------- * ? ? untracked * ! ! ignored * ------------------------------------------------- */ @Throws(VcsException::class) fun getStatus(project: Project, root: VirtualFile, files: List<FilePath> = emptyList(), withRenames: Boolean = true, withUntracked: Boolean = true, withIgnored: Boolean = false): List<GitFileStatus> { val h = GitUtil.createHandlerWithPaths(files) { val h = GitLineHandler(project, root, GitCommand.STATUS) h.setSilent(true) h.appendParameters(GitExecutableManager.getInstance().tryGetVersion(project) ?: GitVersion.NULL, withRenames = withRenames, withUntracked = withUntracked, withIgnored = withIgnored) h } val output: String = Git.getInstance().runCommand(h).getOutputOrThrow() return parseGitStatusOutput(output).map { GitFileStatus(root, it) } } @Throws(VcsException::class) fun getFileStatus(root: VirtualFile, filePath: FilePath, executable: GitExecutable): LightFileStatus { val h = GitLineHandler(null, VfsUtilCore.virtualToIoFile(root), executable, GitCommand.STATUS, emptyList()) h.setSilent(true) h.appendParameters(GitExecutableManager.getInstance().getVersion(executable), withRenames = false, withUntracked = true, withIgnored = true) h.endOptions() h.addRelativePaths(filePath) val output: String = Git.getInstance().runCommand(h).getOutputOrThrow() if (output.isNotBlank()) { val gitStatusOutput = parseGitStatusOutput(output) return gitStatusOutput.firstOrNull() ?: LightFileStatus.Blank } val repositoryPath = getFilePath(root, filePath, executable) ?: return LightFileStatus.Blank return LightFileStatus.NotChanged(repositoryPath) } private fun GitLineHandler.appendParameters(gitVersion: GitVersion, withRenames: Boolean = true, withUntracked: Boolean = true, withIgnored: Boolean = false) { addParameters("--porcelain", "-z") if (!withRenames) { if (GitVersionSpecialty.STATUS_SUPPORTS_NO_RENAMES.existsIn(gitVersion)) { addParameters("--no-renames") } } addParameters("--untracked-files=${if (withUntracked) "all" else "no"}") if (GitVersionSpecialty.STATUS_SUPPORTS_IGNORED_MODES.existsIn(gitVersion)) { if (withIgnored) { addParameters("--ignored=matching") } else { addParameters("--ignored=no") } } else if (withIgnored) { addParameters("--ignored") } } @Throws(VcsException::class) fun getFilePath(root: VirtualFile, filePath: FilePath, executable: GitExecutable): String? { val handler = GitLineHandler(null, VfsUtilCore.virtualToIoFile(root), executable, GitCommand.LS_FILES, emptyList()) handler.addParameters("--full-name") handler.addRelativePaths(filePath) handler.setSilent(true) return Git.getInstance().runCommand(handler).getOutputOrThrow().lines().firstOrNull() } @Throws(VcsException::class) private fun parseGitStatusOutput(output: String): List<LightFileStatus.StatusRecord> { val result = mutableListOf<LightFileStatus.StatusRecord>() val split = output.split(NUL).toTypedArray() val it = split.iterator() while (it.hasNext()) { val line = it.next() if (StringUtil.isEmptyOrSpaces(line)) continue // skip empty lines if any (e.g. the whole output may be empty on a clean working tree). // format: XY_filename where _ stands for space. if (line.length < 4 || line[2] != ' ') { // X, Y, space and at least one symbol for the file throwGFE(GitBundle.message("status.exception.message.line.is.too.short"), output, line, '0', '0') } val xStatus = line[0] val yStatus = line[1] if (!isKnownStatus(xStatus) || !isKnownStatus(yStatus)) { throwGFE(GitBundle.message("status.exception.message.unexpected"), output, line, xStatus, yStatus) } val pathPart = line.substring(3) // skipping the space if (isRenamed(xStatus) || isRenamed(yStatus)) { if (!it.hasNext()) { throwGFE(GitBundle.message("status.exception.message.missing.path"), output, line, xStatus, yStatus) continue } val origPath = it.next() // read the "from" filepath which is separated also by NUL character. result.add(LightFileStatus.StatusRecord(xStatus, yStatus, pathPart, origPath = origPath)) } else { result.add(LightFileStatus.StatusRecord(xStatus, yStatus, pathPart)) } } return result } private fun throwGFE(@Nls message: String, @NlsSafe output: String, @NlsSafe line: String, @NlsSafe xStatus: Char, @NlsSafe yStatus: Char) { throw VcsException(GitBundle.message("status.exception.message.format.message.xstatus.ystatus.line.output", message, xStatus, yStatus, line, output)) } private fun isKnownStatus(status: Char): Boolean { return status == ' ' || status == 'M' || status == 'A' || status == 'D' || status == 'C' || status == 'R' || status == 'U' || status == 'T' || status == '!' || status == '?' } @Throws(VcsException::class) internal fun getFileStatus(status: StatusCode): FileStatus? { return when (status) { ' ' -> null 'M', 'R', 'C', 'T' -> FileStatus.MODIFIED 'A' -> FileStatus.ADDED 'D' -> FileStatus.DELETED 'U' -> FileStatus.MERGED_WITH_CONFLICTS '!' -> FileStatus.IGNORED '?' -> FileStatus.UNKNOWN else -> throw VcsException(GitBundle.message("status.exception.message.unexpected.status", status)) } } typealias StatusCode = Char internal fun isIgnored(status: StatusCode) = status == '!' internal fun isUntracked(status: StatusCode) = status == '?' fun isRenamed(status: StatusCode) = status == 'R' || status == 'C' internal fun isAdded(status: StatusCode) = status == 'A' internal fun isIntendedToBeAdded(index: StatusCode, workTree: StatusCode) = index == ' ' && workTree == 'A' internal fun isDeleted(status: StatusCode) = status == 'D' internal fun isConflicted(index: StatusCode, workTree: StatusCode): Boolean { return (index == 'D' && workTree == 'D') || (index == 'A' && workTree == 'A') || (index == 'T' && workTree == 'T') || (index == 'U' || workTree == 'U') } sealed class LightFileStatus { internal abstract fun getFileStatus(): FileStatus object Blank : LightFileStatus() { override fun getFileStatus(): FileStatus = FileStatus.NOT_CHANGED } data class NotChanged(val path: String) : LightFileStatus() { override fun getFileStatus(): FileStatus = FileStatus.NOT_CHANGED } data class StatusRecord(val index: StatusCode, val workTree: StatusCode, val path: String, val origPath: String? = null) : LightFileStatus() { override fun getFileStatus(): FileStatus { if (isConflicted()) return FileStatus.MERGED_WITH_CONFLICTS return getFileStatus(index) ?: getFileStatus(workTree) ?: FileStatus.NOT_CHANGED } internal fun isConflicted(): Boolean = isConflicted(index, workTree) } } fun LightFileStatus.isTracked(): Boolean { return when (this) { LightFileStatus.Blank -> false is LightFileStatus.NotChanged -> true is LightFileStatus.StatusRecord -> !isIgnored(index) && !isUntracked(index) } } val LightFileStatus.repositoryPath: String? get() = when (this) { LightFileStatus.Blank -> null is LightFileStatus.NotChanged -> path is LightFileStatus.StatusRecord -> if (!isTracked() || index == 'A' || workTree == 'A') null else origPath ?: path }
apache-2.0
1e6d8e8ef1de59d2ccbb0d2e084b8665
38.90678
175
0.659977
4.117621
false
false
false
false
leafclick/intellij-community
platform/platform-api/src/com/intellij/ui/components/JBOptionButton.kt
1
3938
// 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.components import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.CustomShortcutSet import com.intellij.openapi.keymap.KeymapUtil.getFirstKeyboardShortcutText import com.intellij.openapi.ui.OptionAction import com.intellij.openapi.util.Weighted import com.intellij.util.containers.ContainerUtil.unmodifiableOrEmptySet import java.awt.event.ActionEvent import java.awt.event.InputEvent import java.awt.event.KeyEvent import java.util.* import javax.swing.AbstractAction import javax.swing.Action import javax.swing.JButton import javax.swing.KeyStroke.getKeyStroke private val DEFAULT_SHOW_POPUP_SHORTCUT = CustomShortcutSet(getKeyStroke(KeyEvent.VK_ENTER, InputEvent.ALT_MASK or InputEvent.SHIFT_MASK)) open class JBOptionButton(action: Action?, options: Array<Action>?) : JButton(action), Weighted { var options: Array<Action>? = null set(value) { val oldOptions = options field = value fillOptionInfos() firePropertyChange(PROP_OPTIONS, oldOptions, options) if (!Arrays.equals(oldOptions, options)) { revalidate() repaint() } } fun setOptions(actions: List<AnAction>?) { options = actions?.map { AnActionWrapper(it) }?.toTypedArray() } var optionTooltipText: String? = null set(value) { val oldValue = optionTooltipText field = value firePropertyChange(PROP_OPTION_TOOLTIP, oldValue, optionTooltipText) } var isOkToProcessDefaultMnemonics = true val isSimpleButton: Boolean get() = options.isNullOrEmpty() private val _optionInfos = mutableSetOf<OptionInfo>() val optionInfos: Set<OptionInfo> get() = unmodifiableOrEmptySet(_optionInfos) init { this.options = options } override fun getUIClassID(): String = "OptionButtonUI" override fun getUI(): OptionButtonUI = super.getUI() as OptionButtonUI override fun getWeight(): Double = 0.5 fun togglePopup() = getUI().togglePopup() fun showPopup(actionToSelect: Action? = null, ensureSelection: Boolean = true) = getUI().showPopup(actionToSelect, ensureSelection) fun closePopup() = getUI().closePopup() @Deprecated("Use setOptions(Action[]) instead", ReplaceWith("setOptions(options)")) fun updateOptions(options: Array<Action>?) { this.options = options } private fun fillOptionInfos() { _optionInfos.clear() _optionInfos += options.orEmpty().filter { it !== action }.map { getMenuInfo(it) } } private fun getMenuInfo(each: Action): OptionInfo { val text = (each.getValue(Action.NAME) as? String).orEmpty() var mnemonic = -1 var mnemonicIndex = -1 val plainText = StringBuilder() for (i in 0 until text.length) { val ch = text[i] if (ch == '&' || ch == '_') { if (i + 1 < text.length) { val mnemonicsChar = text[i + 1] mnemonic = Character.toUpperCase(mnemonicsChar).toInt() mnemonicIndex = i } continue } plainText.append(ch) } return OptionInfo(plainText.toString(), mnemonic, mnemonicIndex, this, each) } class OptionInfo internal constructor( val plainText: String, val mnemonic: Int, val mnemonicIndex: Int, val button: JBOptionButton, val action: Action ) companion object { const val PROP_OPTIONS = "OptionActions" const val PROP_OPTION_TOOLTIP = "OptionTooltip" @JvmStatic fun getDefaultShowPopupShortcut() = DEFAULT_SHOW_POPUP_SHORTCUT @JvmStatic fun getDefaultTooltip() = "Show drop-down menu (${getFirstKeyboardShortcutText(getDefaultShowPopupShortcut())})" } } private class AnActionWrapper(action: AnAction) : AbstractAction() { init { putValue(OptionAction.AN_ACTION, action) } override fun actionPerformed(e: ActionEvent) = Unit }
apache-2.0
5b3b4efe6ef9c469b90904e2ef7d35c7
31.02439
140
0.712798
4.332233
false
false
false
false
VREMSoftwareDevelopment/WiFiAnalyzer
app/src/test/kotlin/com/vrem/wifianalyzer/navigation/options/OptionActionTest.kt
1
4564
/* * WiFiAnalyzer * Copyright (C) 2015 - 2022 VREM Software Development <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package com.vrem.wifianalyzer.navigation.options import android.os.Build import androidx.test.ext.junit.runners.AndroidJUnit4 import com.nhaarman.mockitokotlin2.verify import com.nhaarman.mockitokotlin2.verifyNoMoreInteractions import com.vrem.wifianalyzer.MainActivity import com.vrem.wifianalyzer.MainContextHelper.INSTANCE import com.vrem.wifianalyzer.R import com.vrem.wifianalyzer.RobolectricUtil import com.vrem.wifianalyzer.navigation.options.OptionAction.Companion.findOptionAction import com.vrem.wifianalyzer.settings.Settings import com.vrem.wifianalyzer.wifi.band.WiFiBand import com.vrem.wifianalyzer.wifi.scanner.ScannerService import org.junit.After import org.junit.Assert.assertEquals import org.junit.Assert.assertTrue import org.junit.Test import org.junit.runner.RunWith import org.robolectric.annotation.Config @RunWith(AndroidJUnit4::class) @Config(sdk = [Build.VERSION_CODES.S]) class OptionActionTest { private val mainActivity: MainActivity = RobolectricUtil.INSTANCE.activity private val scannerService: ScannerService = INSTANCE.scannerService private val settings: Settings = INSTANCE.settings @After fun tearDown() { verifyNoMoreInteractions(scannerService) verifyNoMoreInteractions(settings) INSTANCE.restore() } @Test fun testScannerAction() { // execute scannerAction() // validate verify(scannerService).toggle() } @Test fun testWiFiBandAction2() { // execute wiFiBandAction2() // validate verify(settings).wiFiBand(WiFiBand.GHZ2) } @Test fun testWiFiBandAction5() { // execute wiFiBandAction5() // validate verify(settings).wiFiBand(WiFiBand.GHZ5) } @Test fun testWiFiBandAction6() { // execute wiFiBandAction6() // validate verify(settings).wiFiBand(WiFiBand.GHZ6) } @Test fun testFilterAction() { filterAction() } @Test fun testOptionAction() { assertEquals(6, OptionAction.values().size) } @Test fun testGetKey() { assertEquals(-1, OptionAction.NO_ACTION.key) assertEquals(R.id.action_scanner, OptionAction.SCANNER.key) assertEquals(R.id.action_filter, OptionAction.FILTER.key) assertEquals(R.id.action_wifi_band_2ghz, OptionAction.WIFI_BAND_2.key) assertEquals(R.id.action_wifi_band_5ghz, OptionAction.WIFI_BAND_5.key) assertEquals(R.id.action_wifi_band_6ghz, OptionAction.WIFI_BAND_6.key) } @Test fun testGetAction() { assertTrue(OptionAction.NO_ACTION.action == noAction) assertTrue(OptionAction.SCANNER.action == scannerAction) assertTrue(OptionAction.FILTER.action == filterAction) assertTrue(OptionAction.WIFI_BAND_2.action == wiFiBandAction2) assertTrue(OptionAction.WIFI_BAND_5.action == wiFiBandAction5) assertTrue(OptionAction.WIFI_BAND_6.action == wiFiBandAction6) } @Test fun testGetOptionAction() { assertEquals(OptionAction.NO_ACTION, findOptionAction(OptionAction.NO_ACTION.key)) assertEquals(OptionAction.SCANNER, findOptionAction(OptionAction.SCANNER.key)) assertEquals(OptionAction.FILTER, findOptionAction(OptionAction.FILTER.key)) assertEquals(OptionAction.WIFI_BAND_2, findOptionAction(OptionAction.WIFI_BAND_2.key)) assertEquals(OptionAction.WIFI_BAND_5, findOptionAction(OptionAction.WIFI_BAND_5.key)) assertEquals(OptionAction.WIFI_BAND_6, findOptionAction(OptionAction.WIFI_BAND_6.key)) } @Test fun testGetOptionActionInvalidKey() { assertEquals(OptionAction.NO_ACTION, findOptionAction(-99)) assertEquals(OptionAction.NO_ACTION, findOptionAction(99)) } }
gpl-3.0
76a596db0035dbd6f2913c6f8299dad2
34.115385
94
0.723707
4.245581
false
true
false
false
zdary/intellij-community
python/src/com/jetbrains/python/codeInsight/mlcompletion/PyNamesMatchingMlCompletionFeatures.kt
3
11430
// 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.mlcompletion import com.intellij.codeInsight.completion.CompletionUtilCore.DUMMY_IDENTIFIER_TRIMMED import com.intellij.codeInsight.completion.ml.CompletionEnvironment import com.intellij.codeInsight.completion.ml.ContextFeatures import com.intellij.codeInsight.completion.ml.MLFeatureValue import com.intellij.codeInsight.lookup.LookupElement import com.intellij.openapi.util.Key import com.intellij.openapi.util.text.StringUtil import com.intellij.psi.PsiElement import com.intellij.psi.util.PsiTreeUtil import com.jetbrains.python.psi.* object PyNamesMatchingMlCompletionFeatures { private val scopeNamesKey = Key<Map<String, Int>>("py.ml.completion.scope.names") private val scopeTokensKey = Key<Map<String, Int>>("py.ml.completion.scope.tokens") private val lineLeftNamesKey = Key<Map<String, Int>>("py.ml.completion.line.left.names") private val lineLeftTokensKey = Key<Map<String, Int>>("py.ml.completion.line.left.tokens") val importNamesKey = Key<Map<String, Int>>("py.ml.completion.import.names") val importTokensKey = Key<Map<String, Int>>("py.ml.completion.import.tokens") val namedArgumentsNamesKey = Key<Map<String, Int>>("py.ml.completion.arguments.names") val namedArgumentsTokensKey = Key<Map<String, Int>>("py.ml.completion.arguments.tokens") val statementListOrFileNamesKey = Key<Map<String, Int>>("py.ml.completion.statement.list.names") val statementListOrFileTokensKey = Key<Map<String, Int>>("py.ml.completion.statement.list.tokens") private val enclosingMethodName = Key<String>("py.ml.completion.enclosing.method.name") data class PyScopeMatchingFeatures(val sumMatches: Int, val sumTokensMatches: Int, val numScopeNames: Int, val numScopeDifferentNames: Int) fun getPyFunClassFileBodyMatchingFeatures(contextFeatures: ContextFeatures, lookupString: String): PyScopeMatchingFeatures? { val names = contextFeatures.getUserData(scopeNamesKey) ?: return null val tokens = contextFeatures.getUserData(scopeTokensKey) ?: return null return getPyScopeMatchingFeatures(names, tokens, lookupString) } fun getPySameLineMatchingFeatures(contextFeatures: ContextFeatures, lookupString: String): PyScopeMatchingFeatures? { val names = contextFeatures.getUserData(lineLeftNamesKey) ?: return null val tokens = contextFeatures.getUserData(lineLeftTokensKey) ?: return null return getPyScopeMatchingFeatures(names, tokens, lookupString) } fun getNumTokensFeature(elementName: String) = getTokens(elementName).size data class MatchingWithReceiverFeatures(val matchesWithReceiver: Boolean, val receiverTokensNum: Int, val numMatchedTokens: Int) fun getMatchingWithReceiverFeatures(contextFeatures: ContextFeatures, element: LookupElement): MatchingWithReceiverFeatures? { val names = contextFeatures.getUserData(PyReceiverMlCompletionFeatures.receiverNamesKey) ?: return null if (names.isEmpty()) return null val matchesWithReceiver = names.any { it == element.lookupString } val maxMatchedToken = names.maxBy { tokensMatched(element.lookupString, it) } ?: "" val numMatchedTokens = tokensMatched(maxMatchedToken, element.lookupString) val receiverTokensNum = getNumTokensFeature(maxMatchedToken) return MatchingWithReceiverFeatures(matchesWithReceiver, receiverTokensNum, numMatchedTokens) } fun getMatchingWithEnclosingMethodFeatures(contextFeatures: ContextFeatures, element: LookupElement): Map<String, MLFeatureValue> { val name = contextFeatures.getUserData(enclosingMethodName) ?: return emptyMap() val result = mutableMapOf<String, MLFeatureValue>() if (element.lookupString == name) result["matches_with_enclosing_method"] = MLFeatureValue.binary(true) result["matched_tokens_with_enclosing_method"] = MLFeatureValue.numerical(tokensMatched (name, element.lookupString)) return result } fun calculateFunBodyNames(environment: CompletionEnvironment) { val position = environment.parameters.position val scope = PsiTreeUtil.getParentOfType(position, PyFile::class.java, PyFunction::class.java, PyClass::class.java) val names = collectUsedNames(scope) environment.putUserData(scopeNamesKey, names) environment.putUserData(scopeTokensKey, getTokensCounterMap(names).toMap()) } fun calculateSameLineLeftNames(environment: CompletionEnvironment): Map<String, Int> { val position = environment.parameters.position var curElement = PsiTreeUtil.prevLeaf(position) val names = Counter<String>() while (curElement != null && !curElement.text.contains("\n")) { val text = curElement.text if (!StringUtil.isEmptyOrSpaces(text)) { names.add(text) } curElement = PsiTreeUtil.prevLeaf(curElement) } environment.putUserData(lineLeftNamesKey, names.toMap()) environment.putUserData(lineLeftTokensKey, getTokensCounterMap(names.toMap()).toMap()) return names.toMap() } fun calculateImportNames(environment: CompletionEnvironment) { environment.parameters.position.containingFile .let { PsiTreeUtil.collectElementsOfType(it, PyImportElement::class.java) } .mapNotNull { it.importReferenceExpression } .mapNotNull { it.name } .let { putTokensAndNamesToUserData(environment, importNamesKey, importTokensKey, it) } } fun calculateStatementListNames(environment: CompletionEnvironment) { val position = environment.parameters.position position .let { PsiTreeUtil.getParentOfType(it, PyStatementList::class.java, PyFile::class.java) } ?.let { PsiTreeUtil.collectElementsOfType(it, PyReferenceExpression::class.java) } ?.filter { it.textOffset < position.textOffset } ?.mapNotNull { it.name } ?.let { putTokensAndNamesToUserData(environment, statementListOrFileNamesKey, statementListOrFileTokensKey, it) } } fun calculateNamedArgumentsNames(environment: CompletionEnvironment) { val position = environment.parameters.position PsiTreeUtil.getParentOfType(position, PyArgumentList::class.java) ?.let { PsiTreeUtil.getChildrenOfType(it, PyKeywordArgument::class.java) } ?.mapNotNull { it.firstChild } ?.mapNotNull { it.text } ?.let { putTokensAndNamesToUserData(environment, namedArgumentsNamesKey, namedArgumentsTokensKey, it) } } fun calculateEnclosingMethodName(environment: CompletionEnvironment) { val position = environment.parameters.position val name = PsiTreeUtil.getParentOfType(position, PyFunction::class.java)?.name ?: return environment.putUserData(enclosingMethodName, name) } private fun putTokensAndNamesToUserData(environment: CompletionEnvironment, namesKey: Key<Map<String, Int>>, tokensKey: Key<Map<String, Int>>, names: List<String>) { names .groupingBy { it } .eachCount() .let { putTokensAndNamesToUserData(environment, namesKey, tokensKey, it) } } private fun putTokensAndNamesToUserData(environment: CompletionEnvironment, namesKey: Key<Map<String, Int>>, tokensKey: Key<Map<String, Int>>, names: Map<String, Int>) { environment.putUserData(namesKey, names.toMap()) environment.putUserData(tokensKey, getTokensCounterMap(names.toMap()).toMap()) } private fun getPyScopeMatchingFeatures(names: Map<String, Int>, tokens: Map<String, Int>, lookupString: String): PyScopeMatchingFeatures? { val sumMatches = names[lookupString] ?: 0 val sumTokensMatches = tokensMatched(lookupString, tokens) val total = names.toList().sumBy { it.second } return PyScopeMatchingFeatures(sumMatches, sumTokensMatches, total, names.size) } private fun collectUsedNames(scope: PsiElement?): Map<String, Int> { val variables = Counter<String>() if (scope !is PyClass && scope !is PyFile && scope !is PyFunction) { return variables.toMap() } val visitor = object : PyRecursiveElementVisitor() { override fun visitPyTargetExpression(node: PyTargetExpression) { variables.add(node.name) } override fun visitPyNamedParameter(node: PyNamedParameter) { variables.add(node.name) } override fun visitPyReferenceExpression(node: PyReferenceExpression) { if (!node.isQualified) { variables.add(node.referencedName) } else { super.visitPyReferenceExpression(node) } } override fun visitPyFunction(node: PyFunction) { variables.add(node.name) } override fun visitPyClass(node: PyClass) { variables.add(node.name) } } if (scope is PyFunction || scope is PyClass) { scope.accept(visitor) scope.acceptChildren(visitor) } else { scope.acceptChildren(visitor) } return variables.toMap().filter { !it.key.contains(DUMMY_IDENTIFIER_TRIMMED) } } fun tokensMatched(firstName: String, secondName: String): Int { val nameTokens = getTokens(firstName) val elementNameTokens = getTokens(secondName) return nameTokens.sumBy { token1 -> elementNameTokens.count { token2 -> token1 == token2 } } } fun tokensMatched(name: String, tokens: Map<String, Int>): Int { val nameTokens = getTokens(name) return nameTokens.sumBy { tokens[it] ?: 0 } } private fun getTokensCounterMap(names: Map<String, Int>): Counter<String> { val result = Counter<String>() names.forEach { (name, cnt) -> val tokens = getTokens(name) for (token in tokens) { result.add(token, cnt) } } return result } private fun getTokens(name: String): List<String> = name .split("_") .asSequence() .flatMap { splitByCamelCase(it).asSequence() } .filter { it.isNotEmpty() } .toList() private fun processToken(token: String): String { val lettersOnly = token.filter { it.isLetter() } return if (lettersOnly.length > 3) { when { lettersOnly.endsWith("s") -> lettersOnly.substring(0 until lettersOnly.length - 1) lettersOnly.endsWith("es") -> lettersOnly.substring(0 until lettersOnly.length - 2) else -> lettersOnly } } else lettersOnly } private fun splitByCamelCase(name: String): List<String> { if (isAllLettersUpper(name)) return arrayListOf(processToken(name.toLowerCase())) val result = ArrayList<String>() var curToken = "" for (ch in name) { if (ch.isUpperCase()) { if (curToken.isNotEmpty()) { result.add(processToken(curToken)) curToken = "" } curToken += ch.toLowerCase() } else { curToken += ch } } if (curToken.isNotEmpty()) result.add(processToken(curToken)) return result } private fun isAllLettersUpper(name: String) = !name.any { it.isLetter() && it.isLowerCase() } }
apache-2.0
c61a52c3c2671ab6b843351a7073a1ac
42.463878
140
0.697813
4.517787
false
false
false
false
benoitletondor/EasyBudget
Android/EasyBudget/app/src/main/java/com/benoitletondor/easybudgetapp/iab/IabImpl.kt
1
11308
/* * Copyright 2022 Benoit LETONDOR * * 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.benoitletondor.easybudgetapp.iab import android.app.Activity import android.content.Context import android.content.Intent import androidx.localbroadcastmanager.content.LocalBroadcastManager import com.android.billingclient.api.* import com.benoitletondor.easybudgetapp.helper.Logger import com.benoitletondor.easybudgetapp.parameters.Parameters import java.util.* import kotlin.coroutines.Continuation import kotlin.coroutines.suspendCoroutine /** * SKU premium */ private const val SKU_PREMIUM = "premium" /** * Is the user premium from AppTurbo (bool) */ private const val APP_TURBO_PREMIUM_PARAMETER_KEY = "appturbo_offer" /** * Cache storage of the IAB status */ private const val PREMIUM_PARAMETER_KEY = "premium" /** * Has the user redeemed a Batch offer (bool) */ private const val BATCH_OFFER_REDEEMED_PARAMETER_KEY = "batch_offer_redeemed" class IabImpl( context: Context, private val parameters: Parameters, ) : Iab, PurchasesUpdatedListener, BillingClientStateListener, PurchaseHistoryResponseListener, AcknowledgePurchaseResponseListener { private val appContext = context.applicationContext private val billingClient = BillingClient.newBuilder(appContext) .setListener(this) .enablePendingPurchases() .build() /** * iab check status */ private var iabStatus: PremiumCheckStatus = PremiumCheckStatus.INITIALIZING private var premiumFlowContinuation: Continuation<PremiumPurchaseFlowResult>? = null init { startBillingClient() } private fun startBillingClient() { try { setIabStatusAndNotify(PremiumCheckStatus.INITIALIZING) billingClient.startConnection(this) } catch (e: Exception) { Logger.error("Error while checking iab status", e) setIabStatusAndNotify(PremiumCheckStatus.ERROR) } } /** * Set the new iab status and notify the app by sending an [.INTENT_IAB_STATUS_CHANGED] intent * * @param status the new status */ private fun setIabStatusAndNotify(status: PremiumCheckStatus) { iabStatus = status // Save status only on success if (status == PremiumCheckStatus.PREMIUM || status == PremiumCheckStatus.NOT_PREMIUM) { parameters.setUserPremium(iabStatus == PremiumCheckStatus.PREMIUM) } val intent = Intent(INTENT_IAB_STATUS_CHANGED) LocalBroadcastManager.getInstance(appContext).sendBroadcast(intent) } /** * Is the user a premium user * * @return true if the user if premium, false otherwise */ override fun isUserPremium(): Boolean { return parameters.isUserPremium() || parameters.getBoolean(BATCH_OFFER_REDEEMED_PARAMETER_KEY, false) || parameters.getBoolean(APP_TURBO_PREMIUM_PARAMETER_KEY, false) || iabStatus == PremiumCheckStatus.PREMIUM } /** * Update the current IAP status if already checked */ override fun updateIAPStatusIfNeeded() { Logger.debug("updateIAPStatusIfNeeded: $iabStatus") if ( iabStatus == PremiumCheckStatus.NOT_PREMIUM ) { setIabStatusAndNotify(PremiumCheckStatus.CHECKING) billingClient.queryPurchaseHistoryAsync(BillingClient.SkuType.INAPP, this) } else if ( iabStatus == PremiumCheckStatus.ERROR ) { startBillingClient() } } /** * Launch the premium purchase flow * * @param activity activity that started this purchase */ override suspend fun launchPremiumPurchaseFlow(activity: Activity): PremiumPurchaseFlowResult { if ( iabStatus != PremiumCheckStatus.NOT_PREMIUM ) { return when (iabStatus) { PremiumCheckStatus.ERROR -> PremiumPurchaseFlowResult.Error("Unable to connect to your Google account. Please restart the app and try again") PremiumCheckStatus.PREMIUM -> PremiumPurchaseFlowResult.Error("You already bought Premium with that Google account. Restart the app if you don't have access to premium features.") else -> PremiumPurchaseFlowResult.Error("Runtime error: $iabStatus") } } val skuList = ArrayList<String>(1) skuList.add(SKU_PREMIUM) val (billingResult, skuDetailsList) = querySkuDetails( SkuDetailsParams.newBuilder() .setSkusList(skuList) .setType(BillingClient.SkuType.INAPP) .build() ) if (billingResult.responseCode != BillingClient.BillingResponseCode.OK) { if (billingResult.responseCode == BillingClient.BillingResponseCode.ITEM_ALREADY_OWNED) { setIabStatusAndNotify(PremiumCheckStatus.PREMIUM) return PremiumPurchaseFlowResult.Success } return PremiumPurchaseFlowResult.Error("Unable to connect to reach PlayStore (response code: " + billingResult.responseCode + "). Please restart the app and try again") } if (skuDetailsList.isEmpty()) { return PremiumPurchaseFlowResult.Error("Unable to fetch content from PlayStore (response code: skuDetailsList is empty). Please restart the app and try again") } return suspendCoroutine { continuation -> premiumFlowContinuation = continuation billingClient.launchBillingFlow(activity, BillingFlowParams.newBuilder() .setSkuDetails(skuDetailsList[0]) .build() ) } } data class SkuDetailsResponse(val billingResult: BillingResult, val skuDetailsList: List<SkuDetails>) private suspend fun querySkuDetails(params: SkuDetailsParams): SkuDetailsResponse = suspendCoroutine { continuation -> billingClient.querySkuDetailsAsync(params) { billingResult, skuDetailsList -> continuation.resumeWith(Result.success(SkuDetailsResponse(billingResult, skuDetailsList ?: emptyList()))) } } override fun onBillingSetupFinished(billingResult: BillingResult) { Logger.debug("iab setup finished.") if (billingResult.responseCode != BillingClient.BillingResponseCode.OK) { // Oh noes, there was a problem. setIabStatusAndNotify(PremiumCheckStatus.ERROR) Logger.error("Error while setting-up iab: " + billingResult.responseCode) return } setIabStatusAndNotify(PremiumCheckStatus.CHECKING) billingClient.queryPurchaseHistoryAsync(BillingClient.SkuType.INAPP, this) } override fun onBillingServiceDisconnected() { Logger.debug("onBillingServiceDisconnected") premiumFlowContinuation?.resumeWith(Result.success(PremiumPurchaseFlowResult.Error("Lost connection with Google Play"))) setIabStatusAndNotify(PremiumCheckStatus.ERROR) } override fun onPurchaseHistoryResponse(billingResult: BillingResult, purchaseHistoryRecordList: List<PurchaseHistoryRecord>?) { Logger.debug("iab query inventory finished.") // Is it a failure? if (billingResult.responseCode != BillingClient.BillingResponseCode.OK) { Logger.error("Error while querying iab inventory: " + billingResult.responseCode) setIabStatusAndNotify(PremiumCheckStatus.ERROR) return } var premium = false if (purchaseHistoryRecordList != null) { for (purchase in purchaseHistoryRecordList) { if (SKU_PREMIUM in purchase.skus) { premium = true } } } Logger.debug("iab query inventory was successful: $premium") setIabStatusAndNotify(if (premium) PremiumCheckStatus.PREMIUM else PremiumCheckStatus.NOT_PREMIUM) } override fun onPurchasesUpdated(billingResult: BillingResult, purchases: List<Purchase>?) { Logger.debug("Purchase finished: " + billingResult.responseCode) if (billingResult.responseCode != BillingClient.BillingResponseCode.OK) { Logger.error("Error while purchasing premium: " + billingResult.responseCode) when (billingResult.responseCode) { BillingClient.BillingResponseCode.USER_CANCELED -> premiumFlowContinuation?.resumeWith(Result.success(PremiumPurchaseFlowResult.Cancelled)) BillingClient.BillingResponseCode.ITEM_ALREADY_OWNED -> { setIabStatusAndNotify(PremiumCheckStatus.PREMIUM) premiumFlowContinuation?.resumeWith(Result.success(PremiumPurchaseFlowResult.Success)) return } else -> premiumFlowContinuation?.resumeWith(Result.success(PremiumPurchaseFlowResult.Error("An error occurred (status code: " + billingResult.responseCode + ")"))) } premiumFlowContinuation = null return } if ( purchases.isNullOrEmpty() ) { premiumFlowContinuation?.resumeWith(Result.success(PremiumPurchaseFlowResult.Error("No purchased item found"))) premiumFlowContinuation = null return } Logger.debug("Purchase successful.") for (purchase in purchases) { if (SKU_PREMIUM in purchase.skus) { billingClient.acknowledgePurchase(AcknowledgePurchaseParams.newBuilder().setPurchaseToken(purchase.purchaseToken).build(), this) return } } premiumFlowContinuation?.resumeWith(Result.success(PremiumPurchaseFlowResult.Error("No purchased item found"))) premiumFlowContinuation = null } override fun onAcknowledgePurchaseResponse(billingResult: BillingResult) { Logger.debug("Acknowledge successful.") if( billingResult.responseCode != BillingClient.BillingResponseCode.OK ) { premiumFlowContinuation?.resumeWith(Result.success(PremiumPurchaseFlowResult.Error("Error when acknowledging purchase with Google (${billingResult.responseCode}, ${billingResult.debugMessage}). Please try again"))) premiumFlowContinuation = null return } setIabStatusAndNotify(PremiumCheckStatus.PREMIUM) premiumFlowContinuation?.resumeWith(Result.success(PremiumPurchaseFlowResult.Success)) premiumFlowContinuation = null } } private fun Parameters.setUserPremium(premium: Boolean) { putBoolean(PREMIUM_PARAMETER_KEY, premium) } private fun Parameters.isUserPremium(): Boolean { return getBoolean(PREMIUM_PARAMETER_KEY, false) } private enum class PremiumCheckStatus { INITIALIZING, CHECKING, ERROR, NOT_PREMIUM, PREMIUM }
apache-2.0
51961db77e237d7e25aa8e57d39140ec
36.949664
226
0.686328
5.16819
false
false
false
false
JuliusKunze/kotlin-native
backend.native/tests/external/stdlib/collections/CollectionTest/plusAssign.kt
2
578
import kotlin.test.* import kotlin.comparisons.* fun box() { // lets use a mutable variable of readonly list var l: List<String> = listOf("cheese") val lOriginal = l l += "foo" l += listOf("beer") l += arrayOf("cheese", "wine") l += sequenceOf("bar", "foo") assertEquals(listOf("cheese", "foo", "beer", "cheese", "wine", "bar", "foo"), l) assertTrue(l !== lOriginal) val ml = arrayListOf("cheese") ml += "foo" ml += listOf("beer") ml += arrayOf("cheese", "wine") ml += sequenceOf("bar", "foo") assertEquals(l, ml) }
apache-2.0
602555c254dca5ff03d70d1fbf30e7a9
26.52381
84
0.570934
3.50303
false
false
false
false
smmribeiro/intellij-community
uast/uast-java/src/org/jetbrains/uast/java/expressions/JavaUCallableReferenceExpression.kt
9
1840
/* * 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 org.jetbrains.uast.java import com.intellij.psi.* import org.jetbrains.annotations.ApiStatus import org.jetbrains.uast.UCallableReferenceExpression import org.jetbrains.uast.UElement import org.jetbrains.uast.UExpression import org.jetbrains.uast.UMultiResolvable @ApiStatus.Internal class JavaUCallableReferenceExpression( override val sourcePsi: PsiMethodReferenceExpression, givenParent: UElement? ) : JavaAbstractUExpression(givenParent), UCallableReferenceExpression, UMultiResolvable { override val qualifierExpression: UExpression? by lz { JavaConverter.convertOrNull(sourcePsi.qualifierExpression, this) } override val qualifierType: PsiType? get() = sourcePsi.qualifierType?.type override val callableName: String get() = sourcePsi.referenceName.orAnonymous() override fun resolve(): PsiElement? = sourcePsi.resolve() override fun multiResolve(): Iterable<ResolveResult> = sourcePsi.multiResolve(false).asIterable() override val resolvedName: String? get() = (sourcePsi.resolve() as? PsiNamedElement)?.name override val referenceNameElement: UElement? by lz { sourcePsi.referenceNameElement?.let { JavaUSimpleNameReferenceExpression(it, callableName, this, it.reference) } } }
apache-2.0
52424ccc5c1b07c14b9267ad9744e66a
36.55102
123
0.782065
4.705882
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/j2k/old/tests/testData/fileOrElement/methodCallExpression/stringMethods.kt
12
3808
// ERROR: Type mismatch: inferred type is String but Charset was expected // ERROR: Type mismatch: inferred type is String but Charset was expected import java.nio.charset.Charset import java.util.* internal class A { @Throws(Exception::class) fun constructors() { String() // TODO: new String("original"); String(charArrayOf('a', 'b', 'c')) String(charArrayOf('b', 'd'), 1, 1) String(intArrayOf(32, 65, 127), 0, 3) val bytes = byteArrayOf(32, 65, 100, 81) val charset = Charset.forName("utf-8") String(bytes) String(bytes, charset) String(bytes, 0, 2) String(bytes, "utf-8") String(bytes, 0, 2, "utf-8") String(bytes, 0, 2, charset) String(StringBuilder("content")) String(StringBuffer("content")) } fun normalMethods() { val s = "test string" s.length s.isEmpty() s[1] s.codePointAt(2) s.codePointBefore(2) s.codePointCount(0, s.length) s.offsetByCodePoints(0, 4) s.compareTo("test 2") s.contains("seq") s.contentEquals(StringBuilder(s)) s.contentEquals(StringBuffer(s)) s.endsWith("ng") s.startsWith("te") s.startsWith("st", 2) s.indexOf("st") s.indexOf("st", 5) s.lastIndexOf("st") s.lastIndexOf("st", 4) s.indexOf('t') s.indexOf('t', 5) s.lastIndexOf('t') s.lastIndexOf('t', 5) s.substring(1) s.substring(0, 4) s.subSequence(0, 4) s.replace('e', 'i') s.replace("est", "oast") s.intern() s.toLowerCase() s.toLowerCase(Locale.FRENCH) s.toUpperCase() s.toUpperCase(Locale.FRENCH) s s.toCharArray() } @Throws(Exception::class) fun specialMethods() { val s = "test string" s == "test" s.equals( "tesT", ignoreCase = true ) s.compareTo("Test", ignoreCase = true) s.regionMatches( 0, "TE", 0, 2, ignoreCase = true ) s.regionMatches(0, "st", 1, 2) s.matches("\\w+".toRegex()) s.replace("\\w+".toRegex(), "---") .replaceFirst("([s-t])".toRegex(), "A$1") useSplit(s.split("\\s+".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()) useSplit(s.split("\\s+".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()) useSplit(s.split("\\s+".toRegex()).toTypedArray()) useSplit(s.split("\\s+".toRegex(), 2).toTypedArray()) val limit = 5 useSplit(s.split("\\s+".toRegex(), limit.coerceAtLeast(0)).toTypedArray()) s.trim { it <= ' ' } "$s another" s.toByteArray() s.toByteArray(Charset.forName("utf-8")) s.toByteArray(charset("utf-8")) val chars = CharArray(10) s.toCharArray(chars, 0, 1, 11) } fun staticMethods() { 1.toString() 1L.toString() 'a'.toString() true.toString() 1.11f.toString() 3.14.toString() Any().toString() String.format( Locale.FRENCH, "Je ne mange pas %d jours", 6 ) String.format("Operation completed with %s", "success") val chars = charArrayOf('a', 'b', 'c') String(chars) String(chars, 1, 2) String(chars) String(chars, 1, 2) val order = String.CASE_INSENSITIVE_ORDER } fun unsupportedMethods() { val s = "test string" /* TODO: s.indexOf(32); s.indexOf(32, 2); s.lastIndexOf(32); s.lastIndexOf(32, 2); */ } fun useSplit(result: Array<String>) {} }
apache-2.0
02e32cf8d61be3ec35d67a4e7da579bb
26.594203
89
0.516282
3.86599
false
true
false
false
smmribeiro/intellij-community
plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/ui/PackageSearchUI.kt
1
7513
package com.jetbrains.packagesearch.intellij.plugin.ui import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.Presentation import com.intellij.openapi.actionSystem.ex.CustomComponentAction import com.intellij.openapi.project.DumbAwareAction import com.intellij.ui.Gray import com.intellij.ui.JBColor import com.intellij.util.ui.JBEmptyBorder import com.intellij.util.ui.JBUI import com.intellij.util.ui.JBValue import com.intellij.util.ui.StartupUiUtil import com.intellij.util.ui.UIUtil import com.intellij.util.ui.components.BorderLayoutPanel import com.jetbrains.packagesearch.intellij.plugin.ui.components.BrowsableLinkLabel import org.jetbrains.annotations.Nls import java.awt.CardLayout import java.awt.Color import java.awt.Component import java.awt.Dimension import java.awt.FlowLayout import java.awt.Rectangle import java.awt.event.ActionEvent import javax.swing.AbstractAction import javax.swing.BorderFactory import javax.swing.BoxLayout import javax.swing.Icon import javax.swing.JCheckBox import javax.swing.JComponent import javax.swing.JLabel import javax.swing.JMenuItem import javax.swing.JPanel import javax.swing.JScrollPane import javax.swing.JTextField import javax.swing.KeyStroke import javax.swing.Scrollable internal object PackageSearchUI { private val MAIN_BG_COLOR: Color = JBColor.namedColor("Plugins.background", UIUtil.getListBackground()) internal val GRAY_COLOR: Color = JBColor.namedColor("Label.infoForeground", JBColor(Gray._120, Gray._135)) internal val HeaderBackgroundColor = MAIN_BG_COLOR internal val SectionHeaderBackgroundColor = JBColor.namedColor("Plugins.SectionHeader.background", JBColor(0xF7F7F7, 0x3C3F41)) internal val UsualBackgroundColor = MAIN_BG_COLOR internal val ListRowHighlightBackground = JBColor(0xF2F5F9, 0x4C5052) internal val InfoBannerBackground = JBColor(0xE6EEF7, 0x1C3956) internal val MediumHeaderHeight = JBValue.Float(30f) internal val SmallHeaderHeight = JBValue.Float(24f) @Suppress("MagicNumber") // Thanks, Swing internal fun headerPanel(init: BorderLayoutPanel.() -> Unit) = object : BorderLayoutPanel() { init { border = JBEmptyBorder(2, 0, 2, 12) init() } override fun getBackground() = HeaderBackgroundColor } internal fun cardPanel(cards: List<JPanel> = emptyList(), backgroundColor: Color = UsualBackgroundColor, init: JPanel.() -> Unit) = object : JPanel() { init { layout = CardLayout() cards.forEach { add(it) } init() } override fun getBackground() = backgroundColor } internal fun borderPanel(backgroundColor: Color = UsualBackgroundColor, init: BorderLayoutPanel.() -> Unit) = object : BorderLayoutPanel() { init { init() } override fun getBackground() = backgroundColor } internal fun boxPanel(axis: Int = BoxLayout.Y_AXIS, backgroundColor: Color = UsualBackgroundColor, init: JPanel.() -> Unit) = object : JPanel() { init { layout = BoxLayout(this, axis) init() } override fun getBackground() = backgroundColor } internal fun flowPanel(backgroundColor: Color = UsualBackgroundColor, init: JPanel.() -> Unit) = object : JPanel() { init { layout = FlowLayout(FlowLayout.LEFT) init() } override fun getBackground() = backgroundColor } internal fun checkBox(@Nls title: String, init: JCheckBox.() -> Unit = {}) = object : JCheckBox(title) { init { init() } override fun getBackground() = UsualBackgroundColor } fun textField(init: JTextField.() -> Unit): JTextField = JTextField().apply { init() } internal fun menuItem(@Nls title: String, icon: Icon?, handler: () -> Unit): JMenuItem { if (icon != null) { return JMenuItem(title, icon).apply { addActionListener { handler() } } } return JMenuItem(title).apply { addActionListener { handler() } } } internal fun createLabel(@Nls text: String? = null, init: JLabel.() -> Unit = {}) = JLabel().apply { font = StartupUiUtil.getLabelFont() if (text != null) this.text = text init() } internal fun createLabelWithLink(init: BrowsableLinkLabel.() -> Unit = {}) = BrowsableLinkLabel().apply { font = StartupUiUtil.getLabelFont() init() } internal fun getTextColorPrimary(isSelected: Boolean = false): Color = when { isSelected -> JBColor.lazy { UIUtil.getListSelectionForeground(true) } else -> JBColor.lazy { UIUtil.getListForeground() } } internal fun getTextColorSecondary(isSelected: Boolean = false): Color = when { isSelected -> getTextColorPrimary(isSelected) else -> GRAY_COLOR } internal fun setHeight(component: JComponent, height: Int, keepWidth: Boolean = false, scale: Boolean = true) { val scaledHeight = if (scale) JBUI.scale(height) else height component.apply { preferredSize = Dimension(if (keepWidth) preferredSize.width else 0, scaledHeight) minimumSize = Dimension(if (keepWidth) minimumSize.width else 0, scaledHeight) maximumSize = Dimension(if (keepWidth) maximumSize.width else Int.MAX_VALUE, scaledHeight) } } internal fun verticalScrollPane(c: Component) = object : JScrollPane( VerticalScrollPanelWrapper(c), VERTICAL_SCROLLBAR_AS_NEEDED, HORIZONTAL_SCROLLBAR_NEVER ) { init { border = BorderFactory.createEmptyBorder() viewport.background = UsualBackgroundColor } } internal fun overrideKeyStroke(c: JComponent, stroke: String, action: () -> Unit) = overrideKeyStroke(c, stroke, stroke, action) internal fun overrideKeyStroke(c: JComponent, key: String, stroke: String, action: () -> Unit) { val inputMap = c.getInputMap(JComponent.WHEN_FOCUSED) inputMap.put(KeyStroke.getKeyStroke(stroke), key) c.actionMap.put( key, object : AbstractAction() { override fun actionPerformed(arg: ActionEvent) { action() } } ) } private class VerticalScrollPanelWrapper(content: Component) : JPanel(), Scrollable { init { layout = BoxLayout(this, BoxLayout.Y_AXIS) add(content) } override fun getPreferredScrollableViewportSize(): Dimension = preferredSize override fun getScrollableUnitIncrement(visibleRect: Rectangle, orientation: Int, direction: Int) = 10 override fun getScrollableBlockIncrement(visibleRect: Rectangle, orientation: Int, direction: Int) = 100 override fun getScrollableTracksViewportWidth() = true override fun getScrollableTracksViewportHeight() = false override fun getBackground() = UsualBackgroundColor } } internal class ComponentActionWrapper(private val myComponentCreator: () -> JComponent) : DumbAwareAction(), CustomComponentAction { override fun createCustomComponent(presentation: Presentation, place: String) = myComponentCreator() override fun actionPerformed(e: AnActionEvent) { // No-op } } internal fun JComponent.updateAndRepaint() { invalidate() repaint() }
apache-2.0
f2e52ec646f5f7aaa38c9229a2f62781
35.64878
144
0.677892
4.853359
false
false
false
false
smmribeiro/intellij-community
platform/platform-tests/testSrc/com/intellij/openapi/application/impl/CancellableReadActionTest.kt
1
4837
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.openapi.application.impl import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.ReadAction import com.intellij.openapi.application.ReadAction.CannotReadException import com.intellij.openapi.application.runReadAction import com.intellij.openapi.progress.* import com.intellij.openapi.progress.util.ProgressIndicatorUtils import com.intellij.testFramework.ApplicationExtension import com.intellij.util.concurrency.Semaphore import kotlinx.coroutines.* import org.junit.jupiter.api.Assertions.* import org.junit.jupiter.api.BeforeAll import org.junit.jupiter.api.Test import org.junit.jupiter.api.assertThrows import org.junit.jupiter.api.extension.RegisterExtension class CancellableReadActionTest { companion object { @RegisterExtension @JvmField val applicationExtension = ApplicationExtension() @BeforeAll @JvmStatic fun init() { ProgressIndicatorUtils.cancelActionsToBeCancelledBeforeWrite() // init write action listener } private fun <X> computeCancellable(action: () -> X): X { return ReadAction.computeCancellable<X, Nothing>(action) } } @Test fun `acquires read lock`() { val application = ApplicationManager.getApplication() application.assertReadAccessNotAllowed() val result = computeCancellable { application.assertReadAccessAllowed() 42 } assertEquals(42, result) } @Test fun `rethrows computation exception`() { testRethrow(object : Throwable() {}) } @Test fun `rethrows computation PCE`() { testRethrow(ProcessCanceledException()) } @Test fun `rethrows computation CancellationException`() { testRethrow(CancellationException()) } @Test fun `rethrows computation CannotReadException`() { testRethrow(CannotReadException()) } private inline fun <reified T : Throwable> testRethrow(t: T) { val thrown = assertThrows<T> { computeCancellable { throw t } } assertSame(t, thrown) } @Test fun `read job is a child of current job`(): Unit = runBlocking { withJob { topLevelJob -> computeCancellable { val childJob = topLevelJob.children.single() // executeWithChildJob val readJob = childJob.children.single() assertSame(readJob, Cancellation.currentJob()) } } } @Test fun `read job is a cancellable by outer indicator`() = runBlocking { val inRead = Semaphore(1) val indicator = EmptyProgressIndicator() val job = launch(Dispatchers.IO) { withIndicator(indicator) { assertThrows<CancellationException> { computeCancellable { assertDoesNotThrow { Cancellation.checkCancelled() } inRead.up() throw assertThrows<JobCanceledException> { while ([email protected]) { Cancellation.checkCancelled() } } } } } } inRead.timeoutWaitUp() indicator.cancel() job.timeoutJoin() } @Test fun `throws when a write is pending`(): Unit = runBlocking { val finishWrite = waitForPendingWrite() assertThrows<CannotReadException> { computeCancellable { fail() } } finishWrite.up() } @Test fun `throws when a write is running`(): Unit = runBlocking { val finishWrite = waitForWrite() assertThrows<CannotReadException> { computeCancellable { fail() } } finishWrite.up() } @Test fun `does not throw when a write is requested during almost finished computation`(): Unit = runBlocking { val result = computeCancellable { assertDoesNotThrow { Cancellation.checkCancelled() } waitForPendingWrite().up() assertThrows<ProcessCanceledException> { // cancelled Cancellation.checkCancelled() } 42 // but returning the result doesn't throw CannotReadException } assertEquals(42, result) } @Test fun `throws when a write is requested during computation`(): Unit = runBlocking { testThrowsOnWrite() } @Test fun `throws inside non-cancellable read action when a write is requested during computation`(): Unit = runBlocking { runReadAction { testThrowsOnWrite() } } private fun CoroutineScope.testThrowsOnWrite() { assertThrows<CannotReadException> { computeCancellable { assertDoesNotThrow { Cancellation.checkCancelled() } waitForPendingWrite().up() throw assertThrows<JobCanceledException> { Cancellation.checkCancelled() } } } } }
apache-2.0
75dfda14fc7c297081164909e4dac7b7
26.482955
120
0.671284
4.900709
false
true
false
false
unicroak/VerDirect
src/main/java/net/unicroak/verdirect/PickupTool.kt
1
1160
package net.unicroak.verdirect import org.bukkit.ChatColor import org.bukkit.Material import org.bukkit.inventory.ItemStack import org.bukkit.inventory.PlayerInventory class PickupTool(val material: Material, val data: Short, var name: String, var lore: MutableList<String>) { init { this.name = ChatColor.translateAlternateColorCodes('&', name) lore.forEachIndexed { i, str -> this.lore[i] = ChatColor.translateAlternateColorCodes('&', lore[i]) } } override fun equals(other: Any?): Boolean { return other is ItemStack && equalsItemBase(other) && equalsName(other) && equalsLore(other) } fun isContained(inv: PlayerInventory): Boolean = inv.any { equals(it) } fun equalsItemBase(item: ItemStack): Boolean = material == item.type && (data.toInt() == -1 || item.durability == data) fun equalsName(item: ItemStack): Boolean = name == "ignore" || name == (item.itemMeta.displayName ?: "") fun equalsLore(item: ItemStack): Boolean = lore[0] == "ignore" || lore == (item.itemMeta.lore ?: emptyList()) }
gpl-3.0
53f0453b3efe919101076b0e2591ce90
35.28125
123
0.633621
4.328358
false
false
false
false
kickstarter/android-oss
app/src/main/java/com/kickstarter/models/Web.kt
1
1943
package com.kickstarter.models import android.os.Parcelable import com.kickstarter.libs.utils.UrlUtils import kotlinx.parcelize.Parcelize @Parcelize class Web private constructor( private val project: String, private val projectShort: String?, private val rewards: String?, private val updates: String? ) : Parcelable { fun project() = this.project fun projectShort() = this.projectShort fun rewards() = this.rewards fun updates() = this.updates @Parcelize data class Builder( private var project: String = "", private var projectShort: String? = null, private var rewards: String? = null, private var updates: String? = null ) : Parcelable { fun project(project: String?) = apply { this.project = project ?: "" } fun projectShort(projectShort: String?) = apply { this.projectShort = projectShort } fun rewards(rewards: String?) = apply { this.rewards = rewards } fun updates(updates: String?) = apply { this.updates = updates } fun build() = Web( project = project, projectShort = projectShort, rewards = rewards, updates = updates ) } fun toBuilder() = Builder( project = project, projectShort = projectShort, rewards = rewards, updates = updates ) fun creatorBio() = UrlUtils.appendPath(project(), "creator_bio") fun description() = UrlUtils.appendPath(project(), "description") companion object { @JvmStatic fun builder() = Builder() } override fun equals(obj: Any?): Boolean { var equals = super.equals(obj) if (obj is Web) { equals = project() == obj.project() && projectShort() == obj.projectShort() && rewards() == obj.rewards() && updates() == obj.updates() } return equals } }
apache-2.0
b212bb537447e4b4c94d761795b5bf56
29.359375
92
0.599074
4.604265
false
false
false
false
kickstarter/android-oss
app/src/main/java/com/kickstarter/libs/utils/AnimationUtils.kt
1
4632
package com.kickstarter.libs.utils import android.animation.AnimatorSet import android.animation.ObjectAnimator import android.animation.PropertyValuesHolder import android.view.View import android.view.animation.AccelerateDecelerateInterpolator import android.view.animation.AlphaAnimation import android.view.animation.Animation import android.view.animation.Interpolator import android.widget.ImageButton object AnimationUtils { const val ALPHA = "alpha" const val INITIAL_SCALE = 1.0f const val MAX_SCALE = 1.3f const val SCALE_X = "scaleX" const val SCALE_Y = "scaleY" @JvmOverloads fun disappearAnimation(duration: Long = 300L): Animation { val animation = AlphaAnimation(1.0f, 0.0f) animation.duration = duration animation.fillAfter = true return animation } @JvmOverloads fun appearAnimation(duration: Long = 300L): Animation { val animation = AlphaAnimation(0.0f, 1.0f) animation.duration = duration animation.fillAfter = true return animation } @JvmOverloads fun fadeInAndScale( view: View, duration: Long = 500L, startDelay: Long = 500L, interpolator: Interpolator = AccelerateDecelerateInterpolator() ): ObjectAnimator { val scaleX = PropertyValuesHolder.ofFloat(SCALE_X, 0f, 1f) val scaleY = PropertyValuesHolder.ofFloat(SCALE_Y, 0f, 1f) val alpha = PropertyValuesHolder.ofFloat(ALPHA, 0f, 1f) val animator = ObjectAnimator.ofPropertyValuesHolder(view, scaleX, scaleY, alpha) animator.duration = duration animator.startDelay = startDelay animator.interpolator = interpolator return animator } @JvmOverloads fun fadeOutAndScale( view: View, duration: Long = 500L, startDelay: Long = 500L, interpolator: Interpolator = AccelerateDecelerateInterpolator() ): ObjectAnimator { val scaleX = PropertyValuesHolder.ofFloat(SCALE_X, 1f, 0f) val scaleY = PropertyValuesHolder.ofFloat(SCALE_Y, 1f, 0f) val alpha = PropertyValuesHolder.ofFloat(ALPHA, 1f, 0f) val animator = ObjectAnimator.ofPropertyValuesHolder(view, scaleX, scaleY, alpha) animator.duration = duration animator.startDelay = startDelay animator.interpolator = interpolator return animator } @JvmOverloads fun crossFade( visibleView: View, hiddenView: View, crossDuration: Long = 500L, startDelay: Long = 500L, interpolator: Interpolator = AccelerateDecelerateInterpolator() ): AnimatorSet { val crossFadeAnimatorSet = AnimatorSet() val fadeOutAndScale = fadeOutAndScale(visibleView, crossDuration, startDelay, interpolator) val fadeInAndScale = fadeInAndScale(hiddenView, crossDuration, startDelay, interpolator) crossFadeAnimatorSet.playTogether(fadeOutAndScale, fadeInAndScale) return crossFadeAnimatorSet } @JvmOverloads fun crossFadeAndReverse( visibleView: View, hiddenView: View, crossDuration: Long = 500L, startDelay: Long = 500L, interpolator: Interpolator = AccelerateDecelerateInterpolator() ): AnimatorSet { val crossFadeAndReverseAnimatorSet = AnimatorSet() val startAnimation = crossFade(visibleView, hiddenView, crossDuration, startDelay, interpolator) val endAnimation = crossFade(hiddenView, visibleView, crossDuration, startDelay, interpolator) crossFadeAndReverseAnimatorSet.playSequentially(startAnimation, endAnimation) return crossFadeAndReverseAnimatorSet } fun notificationBounceAnimation(phoneIcon: ImageButton?, mailIcon: ImageButton?) { val pvhX = PropertyValuesHolder.ofFloat(View.SCALE_X, INITIAL_SCALE, MAX_SCALE, INITIAL_SCALE) val phvY = PropertyValuesHolder.ofFloat(View.SCALE_Y, INITIAL_SCALE, MAX_SCALE, INITIAL_SCALE) val animatorSet = AnimatorSet() phoneIcon?.let { icon -> val phoneScaleAnimation = ObjectAnimator.ofPropertyValuesHolder(icon, pvhX, phvY).setDuration(200) phoneScaleAnimation.interpolator = AccelerateDecelerateInterpolator() animatorSet.play(phoneScaleAnimation) } mailIcon?.let { icon -> val mailScaleAnimation = ObjectAnimator.ofPropertyValuesHolder(icon, pvhX, phvY).setDuration(200) mailScaleAnimation.interpolator = AccelerateDecelerateInterpolator() animatorSet.play(mailScaleAnimation).after(100) } animatorSet.start() } }
apache-2.0
793e8cdf8119064228463add9c3ad82c
37.92437
110
0.701425
4.785124
false
false
false
false
alibaba/p3c
eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/ui/QuickFixAction.kt
2
4016
/* * Copyright 1999-2017 Alibaba Group. * * 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.alibaba.smartfox.eclipse.ui import com.alibaba.p3c.pmd.lang.java.rule.flowcontrol.NeedBraceRule import com.alibaba.smartfox.eclipse.RunWithoutViewRefresh import com.alibaba.smartfox.eclipse.SmartfoxActivator import com.alibaba.smartfox.eclipse.job.CodeAnalysis import com.alibaba.smartfox.eclipse.job.P3cMutex import com.alibaba.smartfox.eclipse.pmd.rule.MissingOverrideAnnotationRule import com.alibaba.smartfox.eclipse.util.CleanUps import com.alibaba.smartfox.eclipse.util.getResolution import org.eclipse.core.runtime.IProgressMonitor import org.eclipse.core.runtime.IStatus import org.eclipse.core.runtime.Status import org.eclipse.core.runtime.SubMonitor import org.eclipse.core.runtime.jobs.Job import org.eclipse.jface.action.Action /** * * * @author caikang * @date 2017/06/14 */ class QuickFixAction(val view: InspectionResultView) : Action("Quick Fix") { init { imageDescriptor = SmartfoxActivator.getImageDescriptor("icons/actions/quickfixBulb.png") isEnabled = false } var markers = listOf<FileMarkers>() fun updateFileMarkers(markers: List<FileMarkers>) { this.markers = markers isEnabled = enabled() } override fun run() { if (markers.isEmpty()) { return } runJob() } private fun runJob() { val job = object : Job("Perform P3C Quick Fix") { override fun run(monitor: IProgressMonitor): IStatus { val subMonitor = SubMonitor.convert(monitor, markers.size) monitor.setTaskName("Process File") markers.forEach { if (monitor.isCanceled) { return@run Status.CANCEL_STATUS } monitor.subTask(it.file.name) val childMonitor = subMonitor.newChild(1) if (useCleanUpRefactoring()) { CleanUps.fix(it.file, childMonitor) } else { it.markers.filter { it.marker.exists() }.forEach { (it.marker.getResolution() as RunWithoutViewRefresh).run(it.marker, true) } } val markers = CodeAnalysis.processFileToMakers(it.file, monitor) InspectionResults.updateFileViolations(it.file, markers) } return Status.OK_STATUS } } val outJob = object:Job("P3C Quick Fix Wait analysis finish"){ override fun run(monitor: IProgressMonitor?): IStatus { job.schedule() return Status.OK_STATUS } } outJob.rule = P3cMutex outJob.schedule() } fun enabled(): Boolean { if (useCleanUpRefactoring()) { return true } if (markers.isEmpty()) { return false } val marker = markers.first().markers.first().marker return marker.exists() && marker.getResolution() != null } private fun useCleanUpRefactoring(): Boolean { if (markers.isEmpty()) { return false } val ruleName = markers.first().markers.first().violation.rule.name return ruleName == MissingOverrideAnnotationRule::class.java.simpleName || ruleName == NeedBraceRule::class.java.simpleName } }
apache-2.0
649b3acfec67e68b2bd0808ec2ea3009
34.22807
101
0.626245
4.477146
false
false
false
false
Yubico/yubioath-android
app/src/main/kotlin/com/yubico/yubioath/ui/settings/SettingsFragment.kt
1
4379
package com.yubico.yubioath.ui.settings import android.os.Bundle import android.text.Html import android.text.method.LinkMovementMethod import android.view.WindowManager import android.widget.TextView import androidx.appcompat.app.AlertDialog import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProviders import androidx.preference.ListPreference import androidx.preference.Preference import androidx.preference.PreferenceFragmentCompat import com.yubico.yubioath.R import com.yubico.yubioath.scancode.KeyboardLayout import com.yubico.yubioath.ui.main.IconManager import org.jetbrains.anko.toast class SettingsFragment : PreferenceFragmentCompat() { private val viewModel: SettingsViewModel by lazy { ViewModelProviders.of(activity!!).get(SettingsViewModel::class.java) } private inline fun onPreferenceChange(key: String, crossinline func: (value: Any) -> Unit) { preferenceManager.findPreference<Preference>(key)?.onPreferenceChangeListener = Preference.OnPreferenceChangeListener { _, value -> func(value) true } } private inline fun onPreferenceClick(key: String, crossinline func: () -> Unit) { preferenceManager.findPreference<Preference>(key)?.onPreferenceClickListener = Preference.OnPreferenceClickListener { func() true } } override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) { addPreferencesFromResource(R.xml.preferences) activity?.apply { onPreferenceChange("hideThumbnail") { window.setFlags(WindowManager.LayoutParams.FLAG_SECURE, if (it == true) WindowManager.LayoutParams.FLAG_SECURE else 0) } onPreferenceChange("themeSelect") { recreate() } onPreferenceClick("clearIcons") { AlertDialog.Builder(this) .setTitle(R.string.clear_icons) .setMessage(R.string.clear_icons_message) .setPositiveButton(R.string.clear) { _, _ -> IconManager(context!!).clearIcons() toast(R.string.icons_cleared) } .setNegativeButton(R.string.cancel, null) .show() } onPreferenceClick("clearPasswords") { AlertDialog.Builder(this) .setTitle(R.string.clear_passwords) .setMessage(R.string.clear_passwords_message) .setPositiveButton(R.string.clear) { _, _ -> viewModel.setClearPasswords(true) } .setNegativeButton(R.string.cancel, null) .show() } onPreferenceClick("about") { val appVersion: String = packageManager.getPackageInfo(packageName, 0).versionName val oathVersion = with(viewModel.deviceInfo.value!!) { if (id.isNotEmpty()) "$version" else getString(com.yubico.yubioath.R.string.no_device) } AlertDialog.Builder(this) .setTitle(R.string.about_title) .setMessage(Html.fromHtml(String.format(getString(R.string.about_text), appVersion, oathVersion))) .create().apply { show() findViewById<TextView>(android.R.id.message)?.movementMethod = LinkMovementMethod.getInstance() viewModel.deviceInfo.observe(viewLifecycleOwner, Observer { if (isShowing) { setMessage(Html.fromHtml(String.format(getString(R.string.about_text), appVersion, it.version))) } }) } } onPreferenceChange("readNdefData") { preferenceManager.findPreference<Preference>("keyboardLayout")?.isEnabled = it == true } (preferenceManager.findPreference<ListPreference>("keyboardLayout"))?.apply { entryValues = KeyboardLayout.availableLayouts entries = entryValues isEnabled = preferenceManager.sharedPreferences.getBoolean("readNdefData", false) } } } }
bsd-2-clause
7a44df9f82ef3a3e941c333d52ac2650
43.693878
159
0.601964
5.628535
false
false
false
false
leafclick/intellij-community
plugins/java-decompiler/plugin/src/org/jetbrains/java/decompiler/IdeaDecompilerBundle.kt
1
687
// 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.java.decompiler import com.intellij.DynamicBundle import org.jetbrains.annotations.PropertyKey private const val BUNDLE = "messages.Decompiler" object IdeaDecompilerBundle : DynamicBundle(BUNDLE) { @JvmStatic fun message(@PropertyKey(resourceBundle = BUNDLE) key: String, vararg params: Any): String = getMessage(key, *params) @JvmStatic fun lazyMessage(@PropertyKey(resourceBundle = BUNDLE) key: String, vararg params: Any): java.util.function.Supplier<String> = getLazyMessage(key, *params) }
apache-2.0
76e1d95c62301840f8eda13995724df3
42
140
0.764192
4.320755
false
false
false
false
siosio/intellij-community
plugins/kotlin/analysis/src/org/jetbrains/kotlin/idea/references/KtSimpleNameReference.kt
1
13750
// 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.references import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiElement import com.intellij.psi.util.PsiTreeUtil import com.intellij.util.IncorrectOperationException import com.intellij.util.SmartList import org.jetbrains.kotlin.asJava.unwrapped import org.jetbrains.kotlin.descriptors.DeclarationDescriptor import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.caches.resolve.resolveImportReference import org.jetbrains.kotlin.idea.codeInsight.shorten.addDelayedImportRequest import org.jetbrains.kotlin.idea.codeInsight.shorten.addToShorteningWaitSet import org.jetbrains.kotlin.idea.core.* import org.jetbrains.kotlin.idea.intentions.OperatorToFunctionIntention import org.jetbrains.kotlin.idea.refactoring.fqName.getKotlinFqName import org.jetbrains.kotlin.lexer.KtToken import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.load.java.descriptors.JavaPropertyDescriptor import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.name.SpecialNames import org.jetbrains.kotlin.name.isOneSegmentFQN import org.jetbrains.kotlin.plugin.references.SimpleNameReferenceExtension import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.* import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.DataClassDescriptorResolver import org.jetbrains.kotlin.resolve.ImportedFromObjectCallableDescriptor import org.jetbrains.kotlin.resolve.bindingContextUtil.getReferenceTargets import org.jetbrains.kotlin.resolve.descriptorUtil.getImportableDescriptor import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.types.expressions.OperatorConventions class KtSimpleNameReferenceDescriptorsImpl( expression: KtSimpleNameExpression ) : KtSimpleNameReference(expression), KtDescriptorsBasedReference { override fun doCanBeReferenceTo(candidateTarget: PsiElement): Boolean = canBeReferenceTo(candidateTarget) override fun isReferenceToWithoutExtensionChecking(candidateTarget: PsiElement): Boolean = matchesTarget(candidateTarget) override fun getTargetDescriptors(context: BindingContext): Collection<DeclarationDescriptor> { return SmartList<DeclarationDescriptor>().apply { // Replace Java property with its accessor(s) for (descriptor in expression.getReferenceTargets(context)) { val sizeBefore = size if (descriptor !is JavaPropertyDescriptor) { add(descriptor) continue } val readWriteAccess = expression.readWriteAccess(true) descriptor.getter?.let { if (readWriteAccess.isRead) add(it) } descriptor.setter?.let { if (readWriteAccess.isWrite) add(it) } if (size == sizeBefore) { add(descriptor) } } } } override fun isReferenceTo(element: PsiElement): Boolean { if (!canBeReferenceTo(element)) return false for (extension in element.project.extensionArea.getExtensionPoint(SimpleNameReferenceExtension.EP_NAME).extensions) { if (extension.isReferenceTo(this, element)) return true } return super<KtDescriptorsBasedReference>.isReferenceTo(element) } override fun getRangeInElement(): TextRange { val element = element.getReferencedNameElement() val startOffset = getElement().startOffset return element.textRange.shiftRight(-startOffset) } override fun canRename(): Boolean { if (expression.getParentOfTypeAndBranch<KtWhenConditionInRange>(strict = true) { operationReference } != null) return false val elementType = expression.getReferencedNameElementType() if (elementType == KtTokens.PLUSPLUS || elementType == KtTokens.MINUSMINUS) return false return true } override fun handleElementRename(newElementName: String): PsiElement { if (!canRename()) throw IncorrectOperationException() if (newElementName.unquote() == "") { return when (val qualifiedElement = expression.getQualifiedElement()) { is KtQualifiedExpression -> { expression.replace(qualifiedElement.receiverExpression) qualifiedElement.replaced(qualifiedElement.selectorExpression!!) } is KtUserType -> expression.replaced( KtPsiFactory(expression).createSimpleName( SpecialNames.DEFAULT_NAME_FOR_COMPANION_OBJECT.asString() ) ) else -> expression } } // Do not rename if the reference corresponds to synthesized component function val expressionText = expression.text if (expressionText != null && Name.isValidIdentifier(expressionText)) { if (DataClassDescriptorResolver.isComponentLike(Name.identifier(expressionText)) && resolve() is KtParameter) { return expression } } val psiFactory = KtPsiFactory(expression) val element = expression.project.extensionArea.getExtensionPoint(SimpleNameReferenceExtension.EP_NAME).extensions .asSequence() .map { it.handleElementRename(this, psiFactory, newElementName) } .firstOrNull { it != null } ?: psiFactory.createNameIdentifier(newElementName.quoteIfNeeded()) val nameElement = expression.getReferencedNameElement() val elementType = nameElement.node.elementType if (elementType is KtToken && OperatorConventions.getNameForOperationSymbol(elementType) != null) { val opExpression = expression.parent as? KtOperationExpression if (opExpression != null) { val (newExpression, newNameElement) = OperatorToFunctionIntention.convert(opExpression) newNameElement.replace(element) return newExpression } } if (element.node.elementType == KtTokens.IDENTIFIER) { nameElement.astReplace(element) } else { nameElement.replace(element) } return expression } // By default reference binding is delayed override fun bindToElement(element: PsiElement): PsiElement = bindToElement(element, ShorteningMode.DELAYED_SHORTENING) override fun bindToElement(element: PsiElement, shorteningMode: ShorteningMode): PsiElement = element.getKotlinFqName()?.let { fqName -> bindToFqName(fqName, shorteningMode, element) } ?: expression override fun bindToFqName( fqName: FqName, shorteningMode: ShorteningMode, targetElement: PsiElement? ): PsiElement { val expression = expression if (fqName.isRoot) return expression // not supported for infix calls and operators if (expression !is KtNameReferenceExpression) return expression if (expression.parent is KtThisExpression || expression.parent is KtSuperExpression) return expression // TODO: it's a bad design of PSI tree, we should change it val newExpression = expression.changeQualifiedName( fqName.quoteIfNeeded().let { if (shorteningMode == ShorteningMode.NO_SHORTENING) it else it.withRootPrefixIfNeeded(expression) }, targetElement ) val newQualifiedElement = newExpression.getQualifiedElementOrCallableRef() if (shorteningMode == ShorteningMode.NO_SHORTENING) return newExpression val needToShorten = PsiTreeUtil.getParentOfType(expression, KtImportDirective::class.java, KtPackageDirective::class.java) == null if (!needToShorten) { return newExpression } return if (shorteningMode == ShorteningMode.FORCED_SHORTENING || !ApplicationManager.getApplication().isDispatchThread) { ShortenReferences.DEFAULT.process(newQualifiedElement) } else { newQualifiedElement.addToShorteningWaitSet() newExpression } } /** * Replace [[KtNameReferenceExpression]] (and its enclosing qualifier) with qualified element given by FqName * Result is either the same as original element, or [[KtQualifiedExpression]], or [[KtUserType]] * Note that FqName may not be empty */ private fun KtNameReferenceExpression.changeQualifiedName( fqName: FqName, targetElement: PsiElement? = null ): KtNameReferenceExpression { assert(!fqName.isRoot) { "Can't set empty FqName for element $this" } val shortName = fqName.shortName().asString() val psiFactory = KtPsiFactory(this) val parent = parent if (parent is KtUserType && !fqName.isOneSegmentFQN()) { val qualifier = parent.qualifier val qualifierReference = qualifier?.referenceExpression as? KtNameReferenceExpression if (qualifierReference != null && qualifier.typeArguments.isNotEmpty()) { qualifierReference.changeQualifiedName(fqName.parent(), targetElement) return this } } val targetUnwrapped = targetElement?.unwrapped if (targetUnwrapped != null && targetUnwrapped.isTopLevelKtOrJavaMember() && fqName.isOneSegmentFQN()) { addDelayedImportRequest(targetUnwrapped, containingKtFile) } var parentDelimiter = "." val fqNameBase = when { parent is KtCallElement -> { val callCopy = parent.copied() callCopy.calleeExpression!!.replace(psiFactory.createSimpleName(shortName)).parent!!.text } parent is KtCallableReferenceExpression && parent.callableReference == this -> { parentDelimiter = "" val callableRefCopy = parent.copied() callableRefCopy.receiverExpression?.delete() val newCallableRef = callableRefCopy .callableReference .replace(psiFactory.createSimpleName(shortName)) .parent as KtCallableReferenceExpression if (targetUnwrapped != null && targetUnwrapped.isTopLevelKtOrJavaMember()) { addDelayedImportRequest(targetUnwrapped, parent.containingKtFile) return parent.replaced(newCallableRef).callableReference as KtNameReferenceExpression } newCallableRef.text } else -> shortName } val text = if (!fqName.isOneSegmentFQN()) "${fqName.parent().asString()}$parentDelimiter$fqNameBase" else fqNameBase val elementToReplace = getQualifiedElementOrCallableRef() val newElement = when (elementToReplace) { is KtUserType -> { val typeText = "$text${elementToReplace.typeArgumentList?.text ?: ""}" elementToReplace.replace(psiFactory.createType(typeText).typeElement!!) } else -> KtPsiUtil.safeDeparenthesize(elementToReplace.replaced(psiFactory.createExpression(text))) } as KtElement val selector = (newElement as? KtCallableReferenceExpression)?.callableReference ?: newElement.getQualifiedElementSelector() ?: error("No selector for $newElement") return selector as KtNameReferenceExpression } override fun getCanonicalText(): String = expression.text override val resolvesByNames: Collection<Name> get() { val element = element if (element is KtOperationReferenceExpression) { val tokenType = element.operationSignTokenType if (tokenType != null) { val name = OperatorConventions.getNameForOperationSymbol( tokenType, element.parent is KtUnaryExpression, element.parent is KtBinaryExpression ) ?: return emptyList() val counterpart = OperatorConventions.ASSIGNMENT_OPERATION_COUNTERPARTS[tokenType] return if (counterpart != null) { val counterpartName = OperatorConventions.getNameForOperationSymbol(counterpart, false, true)!! listOf(name, counterpartName) } else { listOf(name) } } } return listOf(element.getReferencedNameAsName()) } override fun getImportAlias(): KtImportAlias? { fun DeclarationDescriptor.unwrap() = if (this is ImportedFromObjectCallableDescriptor<*>) callableFromObject else this val element = element val name = element.getReferencedName() val file = element.containingKtFile val importDirective = file.findImportByAlias(name) ?: return null val fqName = importDirective.importedFqName ?: return null val importedDescriptors = file.resolveImportReference(fqName).map { it.unwrap() } if (getTargetDescriptors(element.analyze(BodyResolveMode.PARTIAL)).any { it.unwrap().getImportableDescriptor() in importedDescriptors }) { return importDirective.alias } return null } }
apache-2.0
02ac2f56f47c5a73306ac2e6af111725
43.642857
170
0.670982
5.823803
false
false
false
false
jwren/intellij-community
platform/diff-impl/src/com/intellij/diff/tools/combined/CombinedDiffViewer.kt
1
15805
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.diff.tools.combined import com.intellij.diff.DiffContext import com.intellij.diff.FrameDiffTool import com.intellij.diff.FrameDiffTool.DiffViewer import com.intellij.diff.impl.ui.DiffInfo import com.intellij.diff.tools.binary.OnesideBinaryDiffViewer import com.intellij.diff.tools.binary.ThreesideBinaryDiffViewer import com.intellij.diff.tools.binary.TwosideBinaryDiffViewer import com.intellij.diff.tools.fragmented.UnifiedDiffViewer import com.intellij.diff.tools.simple.SimpleDiffViewer import com.intellij.diff.tools.util.DiffDataKeys import com.intellij.diff.tools.util.FoldingModelSupport import com.intellij.diff.tools.util.PrevNextDifferenceIterable import com.intellij.diff.tools.util.base.DiffViewerBase import com.intellij.diff.tools.util.base.TextDiffViewerUtil import com.intellij.diff.tools.util.side.OnesideTextDiffViewer import com.intellij.diff.tools.util.side.ThreesideTextDiffViewer import com.intellij.diff.tools.util.side.TwosideTextDiffViewer import com.intellij.ide.DataManager import com.intellij.openapi.Disposable import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.CommonDataKeys import com.intellij.openapi.actionSystem.DataProvider import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.EditorFactory import com.intellij.openapi.editor.ex.EditorEventMulticasterEx import com.intellij.openapi.editor.ex.EditorEx import com.intellij.openapi.editor.ex.FocusChangeListener import com.intellij.openapi.ui.VerticalFlowLayout import com.intellij.openapi.util.Disposer import com.intellij.openapi.vcs.FilePath import com.intellij.openapi.vcs.FileStatus import com.intellij.openapi.wm.IdeFocusManager import com.intellij.ui.ListenerUtil import com.intellij.ui.components.JBScrollPane import com.intellij.util.Alarm import com.intellij.util.EventDispatcher import com.intellij.util.containers.BidirectionalMap import com.intellij.util.ui.JBUI import com.intellij.util.ui.update.MergingUpdateQueue import com.intellij.util.ui.update.Update import org.jetbrains.annotations.NonNls import java.awt.Rectangle import java.awt.event.FocusAdapter import java.awt.event.FocusEvent import java.util.* import javax.swing.JComponent import javax.swing.JPanel import javax.swing.ScrollPaneConstants import javax.swing.event.ChangeEvent import javax.swing.event.ChangeListener import kotlin.math.max class CombinedDiffViewer(context: DiffContext, val unifiedDiff: Boolean) : DiffViewer, DataProvider { private val project = context.project internal val contentPanel = JPanel(VerticalFlowLayout(VerticalFlowLayout.TOP, 0, 0, true, false)) internal val scrollPane = JBScrollPane( contentPanel, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER ).apply { DataManager.registerDataProvider(this, this@CombinedDiffViewer) border = JBUI.Borders.empty() viewportBorder = JBUI.Borders.empty() viewport.addChangeListener(ViewportChangeListener()) } internal val diffBlocks = linkedMapOf<CombinedBlockId, CombinedDiffBlock<*>>() internal val diffViewers = hashMapOf<CombinedBlockId, DiffViewer>() internal val diffBlocksPositions = BidirectionalMap<CombinedBlockId, Int>() internal val scrollSupport = CombinedDiffScrollSupport(project, this) private val focusListener = FocusListener(this) private val blockListeners = EventDispatcher.create(BlockListener::class.java) private val diffInfo = object : DiffInfo() { override fun getContentTitles(): List<String?> { return getCurrentBlockId()?.let { blockId -> diffViewers[blockId] as? DiffViewerBase }?.request?.contentTitles ?: return emptyList() } } private val combinedEditorSettingsAction = CombinedEditorSettingsAction(TextDiffViewerUtil.getTextSettings(context), ::foldingModels, ::editors) private var blockToSelect: CombinedDiffBlock<*>? = null private val visibleBlocksUpdateQueue = MergingUpdateQueue("CombinedDiffViewer.visibleBlocksUpdateQueue", 500, true, null, this, null, Alarm.ThreadToUse.SWING_THREAD) .also { Disposer.register(this, it) } internal fun updateBlockContent(block: CombinedDiffBlock<*>, newContent: CombinedDiffBlockContent) { val newViewer = newContent.viewer diffViewers.remove(block.id)?.also(Disposer::dispose) diffViewers[block.id] = newViewer block.updateBlockContent(newViewer.component) newViewer.init() } internal fun addChildBlock(content: CombinedDiffBlockContent, needBorder: Boolean) { val diffBlock = createDiffBlock(content, needBorder) val viewer = content.viewer contentPanel.add(diffBlock.component) diffBlocks[diffBlock.id] = diffBlock diffViewers[diffBlock.id] = viewer diffBlocksPositions[diffBlock.id] = diffBlocks.size - 1 viewer.init() } internal fun insertChildBlock(content: CombinedDiffBlockContent, position: CombinedDiffRequest.InsertPosition?): CombinedDiffBlock<*> { val above = position?.above ?: false val insertIndex = if (position == null) -1 else diffBlocksPositions[position.blockId]?.let { if (above) it else it.inc() } ?: -1 val diffBlock = createDiffBlock(content, diffBlocks.size > 1 && insertIndex > 0) val blockId = diffBlock.id val viewer = content.viewer if (insertIndex != -1 && insertIndex < diffBlocks.size) { contentPanel.add(diffBlock.component, insertIndex) for (index in insertIndex until diffBlocks.size) { getBlockId(index)?.let { id -> diffBlocksPositions[id] = index + 1 } } diffBlocks[blockId] = diffBlock diffViewers[blockId] = viewer diffBlocksPositions[blockId] = insertIndex } else { contentPanel.add(diffBlock.component) diffBlocks[blockId] = diffBlock diffViewers[blockId] = viewer diffBlocksPositions[blockId] = contentPanel.componentCount - 1 } viewer.init() return diffBlock } private fun createDiffBlock(content: CombinedDiffBlockContent, needBorder: Boolean): CombinedDiffBlock<*> { val viewer = content.viewer if (!viewer.isEditorBased) { focusListener.register(viewer.component, this) } val diffBlockFactory = CombinedDiffBlockFactory.findApplicable<CombinedBlockId>(content)!! val diffBlock = diffBlockFactory.createBlock(content, needBorder) val blockId = diffBlock.id Disposer.register(diffBlock, Disposable { diffBlocks.remove(blockId) contentPanel.remove(diffBlock.component) diffViewers.remove(blockId)?.also(Disposer::dispose) diffBlocksPositions.remove(blockId) }) Disposer.register(this, diffBlock) return diffBlock } override fun getComponent(): JComponent = scrollPane override fun getPreferredFocusedComponent(): JComponent? = getCurrentDiffViewer()?.preferredFocusedComponent override fun init(): FrameDiffTool.ToolbarComponents { val components = FrameDiffTool.ToolbarComponents() components.toolbarActions = createToolbarActions() components.diffInfo = diffInfo components.needTopToolbarBorder = true return components } fun rediff() = diffViewers.forEach { (it as? DiffViewerBase)?.rediff() } override fun dispose() {} override fun getData(dataId: @NonNls String): Any? { if (CommonDataKeys.PROJECT.`is`(dataId)) return project if (DiffDataKeys.PREV_NEXT_DIFFERENCE_ITERABLE.`is`(dataId)) return scrollSupport.currentPrevNextIterable if (DiffDataKeys.NAVIGATABLE.`is`(dataId)) return getCurrentDataProvider()?.let(DiffDataKeys.NAVIGATABLE::getData) if (DiffDataKeys.DIFF_VIEWER.`is`(dataId)) return getCurrentDiffViewer() if (COMBINED_DIFF_VIEWER.`is`(dataId)) return this return if (DiffDataKeys.CURRENT_EDITOR.`is`(dataId)) getCurrentDiffViewer()?.editor else null } private inner class ViewportChangeListener: ChangeListener { override fun stateChanged(e: ChangeEvent) { visibleBlocksUpdateQueue.queue(object : Update(e) { override fun run() = notifyVisibleBlocksChanged() override fun canEat(update: Update?): Boolean = true }) } } private fun notifyVisibleBlocksChanged() { val viewRect = scrollPane.viewport.viewRect val (visibleBlocks, hiddenBlocks) = getAllBlocks().partition { it.component.bounds.intersects(viewRect) } if (visibleBlocks.isNotEmpty()) { blockListeners.multicaster.blocksHidden(hiddenBlocks) } if (visibleBlocks.isNotEmpty()) { updateGlobalBlockHeader(visibleBlocks, viewRect) blockListeners.multicaster.blocksVisible(visibleBlocks, blockToSelect) } } private fun updateGlobalBlockHeader(visibleBlocks: List<CombinedDiffBlock<*>>, viewRect: Rectangle) { val firstVisibleBlock = visibleBlocks.first() val blockOnTop = firstVisibleBlock.component.bounds.y == viewRect.y val previousBlockPosition = max((diffBlocksPositions[firstVisibleBlock.id] ?: -1) - 1, 0) val firstBlock = diffBlocks.values.first() val firstBlockComponent = firstBlock.component val firstBlockHeader = firstBlock.header val previousBlockHeader = (getBlockId(previousBlockPosition)?.let { diffBlocks[it] } as? CombinedDiffGlobalBlockHeaderProvider)?.globalHeader val firstVisibleBlockHeader = (firstVisibleBlock as? CombinedDiffGlobalBlockHeaderProvider)?.globalHeader when { blockOnTop -> scrollPane.setColumnHeaderView(previousBlockHeader) firstBlockComponent.bounds.y == viewRect.y -> scrollPane.setColumnHeaderView(firstBlockHeader) else -> scrollPane.setColumnHeaderView(firstVisibleBlockHeader) } } internal fun addBlockListener(listener: BlockListener) { blockListeners.listeners.add(listener) } private fun getBlockId(index: Int) = diffBlocksPositions.getKeysByValue(index)?.singleOrNull() fun getAllBlocks() = diffBlocks.values.asSequence() fun getBlock(viewer: DiffViewer) = diffViewers.entries.find { it.value == viewer }?.key?.let { blockId -> diffBlocks[blockId] } fun getViewer(id: CombinedBlockId) = diffViewers[id] fun getCurrentBlockId(): CombinedBlockId? { return getBlockId(scrollSupport.blockIterable.index) } internal fun getDifferencesIterable(): PrevNextDifferenceIterable? { return getCurrentDataProvider()?.let(DiffDataKeys.PREV_NEXT_DIFFERENCE_ITERABLE::getData) } internal fun getBlocksIterable(): PrevNextDifferenceIterable = scrollSupport.blockIterable internal fun getCurrentDiffViewer(): DiffViewer? = getDiffViewer(scrollSupport.blockIterable.index) internal fun getDiffViewer(index: Int): DiffViewer? { return getBlockId(index)?.let { blockId -> diffViewers[blockId] } } fun selectDiffBlock(filePath: FilePath, fileStatus: FileStatus, scrollPolicy: ScrollPolicy, onSelected: () -> Unit = {}) { val blockId = CombinedPathBlockId(filePath, fileStatus) val index = diffBlocksPositions[blockId] if (index == null || index == -1) return selectDiffBlock(index, scrollPolicy, onSelected) } internal fun selectDiffBlock(scrollPolicy: ScrollPolicy) { selectDiffBlock(scrollSupport.blockIterable.index, scrollPolicy) } fun selectDiffBlock(index: Int = scrollSupport.blockIterable.index, scrollPolicy: ScrollPolicy, onSelected: () -> Unit = {}) { getBlockId(index)?.let { diffBlocks[it] }?.run { selectDiffBlock(index, this, scrollPolicy, onSelected) } } fun selectDiffBlock(block: CombinedDiffBlock<*>, scrollPolicy: ScrollPolicy, onSelected: () -> Unit = {}) { val index = diffBlocksPositions[block.id] if (index == null || index == -1) return selectDiffBlock(index, block, scrollPolicy, onSelected) } private fun selectDiffBlock(index: Int, block: CombinedDiffBlock<*>, scrollPolicy: ScrollPolicy, onSelected: () -> Unit) { val viewer = diffViewers[block.id] ?: return val componentToFocus = with(viewer) { when { isEditorBased -> editor?.contentComponent preferredFocusedComponent != null -> preferredFocusedComponent else -> component } } ?: return val focusManager = IdeFocusManager.getInstance(project) if (focusManager.focusOwner == componentToFocus) return focusManager.requestFocus(componentToFocus, true) focusManager.doWhenFocusSettlesDown { onSelected() blockToSelect = block scrollSupport.scroll(index, block, scrollPolicy) } } private fun createToolbarActions(): List<AnAction> { return listOf(combinedEditorSettingsAction) } internal fun contentChanged() { blockToSelect = null combinedEditorSettingsAction.installGutterPopup() combinedEditorSettingsAction.applyDefaults() editors.forEach { editor -> editor.settings.additionalLinesCount = 0 } } private val foldingModels: List<FoldingModelSupport> get() = diffViewers.values.mapNotNull { viewer -> when (viewer) { is SimpleDiffViewer -> viewer.foldingModel is UnifiedDiffViewer -> viewer.foldingModel else -> null } } private fun getCurrentDataProvider(): DataProvider? { val currentDiffViewer = getCurrentDiffViewer() if (currentDiffViewer is DiffViewerBase) { return currentDiffViewer } return currentDiffViewer?.let(DiffViewer::getComponent)?.let(DataManager::getDataProvider) } private val editors: List<Editor> get() = diffViewers.values.flatMap { it.editors } private inner class FocusListener(disposable: Disposable) : FocusAdapter(), FocusChangeListener { init { (EditorFactory.getInstance().eventMulticaster as? EditorEventMulticasterEx)?.addFocusChangeListener(this, disposable) } override fun focusGained(editor: Editor) { val indexOfSelectedBlock = diffViewers.entries.find { editor == it.value.editor }?.key?.let { blockId -> diffBlocksPositions[blockId] } ?: -1 if (indexOfSelectedBlock != -1) { scrollSupport.blockIterable.index = indexOfSelectedBlock diffInfo.update() } } override fun focusGained(e: FocusEvent) { val indexOfSelectedBlock = diffViewers.entries.find { val v = it.value !v.isEditorBased && (v.preferredFocusedComponent == e.component || v.component == e.component) }?.key?.let { blockId -> diffBlocksPositions[blockId] } ?: -1 if (indexOfSelectedBlock != -1) { scrollSupport.blockIterable.index = indexOfSelectedBlock diffInfo.update() } } fun register(component: JComponent, disposable: Disposable) { ListenerUtil.addFocusListener(component, this) Disposer.register(disposable) { ListenerUtil.removeFocusListener(component, this) } } } } val DiffViewer.editor: EditorEx? get() = when (this) { is OnesideTextDiffViewer -> editor is TwosideTextDiffViewer -> currentEditor is ThreesideTextDiffViewer -> currentEditor is UnifiedDiffViewer -> editor else -> null } val DiffViewer.editors: List<EditorEx> get() = when (this) { is OnesideTextDiffViewer -> editors is TwosideTextDiffViewer -> editors is ThreesideTextDiffViewer -> editors is UnifiedDiffViewer -> listOf(editor) else -> emptyList() } internal val DiffViewer?.isEditorBased: Boolean get() = this is DiffViewerBase && this !is OnesideBinaryDiffViewer && //TODO simplify, introduce ability to distinguish editor and non-editor based DiffViewer this !is ThreesideBinaryDiffViewer && this !is TwosideBinaryDiffViewer internal interface BlockListener : EventListener { fun blocksHidden(blocks: Collection<CombinedDiffBlock<*>>) fun blocksVisible(blocks: Collection<CombinedDiffBlock<*>>, blockToSelect: CombinedDiffBlock<*>?) }
apache-2.0
b77c35d5c6795f18b6874d4ba9843758
38.218362
145
0.751408
4.425931
false
false
false
false
K0zka/kerub
src/test/kotlin/com/github/kerubistan/kerub/planner/steps/storage/gvinum/unallocate/UnAllocateGvinumTest.kt
2
2218
package com.github.kerubistan.kerub.planner.steps.storage.gvinum.unallocate import com.github.kerubistan.kerub.model.dynamic.VirtualStorageGvinumAllocation import com.github.kerubistan.kerub.model.dynamic.gvinum.SimpleGvinumConfiguration import com.github.kerubistan.kerub.planner.steps.OperationalStepVerifications import com.github.kerubistan.kerub.testDisk import com.github.kerubistan.kerub.testFreeBsdHost import com.github.kerubistan.kerub.testGvinumCapability import com.github.kerubistan.kerub.testHost import io.github.kerubistan.kroki.size.GB import org.junit.Test import org.junit.jupiter.api.assertThrows import java.util.UUID.randomUUID internal class UnAllocateGvinumTest : OperationalStepVerifications() { override val step = UnAllocateGvinum( host = testFreeBsdHost, allocation = VirtualStorageGvinumAllocation( hostId = testFreeBsdHost.id, configuration = SimpleGvinumConfiguration( diskName = "test-disk" ), capabilityId = testGvinumCapability.id, actualSize = 1.GB ), vstorage = testDisk ) @Test fun validations() { assertThrows<IllegalStateException>("only bsd") { UnAllocateGvinum( host = testHost, allocation = VirtualStorageGvinumAllocation( hostId = testHost.id, configuration = SimpleGvinumConfiguration( diskName = "test-disk" ), capabilityId = testGvinumCapability.id, actualSize = 1.GB ), vstorage = testDisk ) } assertThrows<IllegalStateException>("mixed hosts") { UnAllocateGvinum( host = testFreeBsdHost.copy(id = randomUUID()), allocation = VirtualStorageGvinumAllocation( hostId = testFreeBsdHost.id, configuration = SimpleGvinumConfiguration( diskName = "test-disk" ), capabilityId = testGvinumCapability.id, actualSize = 1.GB ), vstorage = testDisk ) } UnAllocateGvinum( host = testFreeBsdHost, allocation = VirtualStorageGvinumAllocation( hostId = testFreeBsdHost.id, configuration = SimpleGvinumConfiguration( diskName = "test-disk" ), capabilityId = testGvinumCapability.id, actualSize = 1.GB ), vstorage = testDisk ) } }
apache-2.0
91855d93259bdcf1d030ea3f33de9c32
29.39726
81
0.724977
4.249042
false
true
false
false
androidx/androidx
window/window/src/androidTest/java/androidx/window/layout/adapter/sidecar/SidecarWindowBackendTest.kt
3
9139
/* * 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.window.layout.adapter.sidecar import android.app.Activity import android.content.Context import androidx.core.util.Consumer import androidx.test.core.app.ApplicationProvider import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.filters.LargeTest import androidx.window.TestConsumer import androidx.window.WindowTestBase import androidx.window.core.Bounds import androidx.window.layout.DisplayFeature import androidx.window.layout.FoldingFeature.State.Companion.FLAT import androidx.window.layout.HardwareFoldingFeature import androidx.window.layout.HardwareFoldingFeature.Type.Companion.HINGE import androidx.window.layout.WindowLayoutInfo import com.google.common.util.concurrent.MoreExecutors import com.nhaarman.mockitokotlin2.eq import com.nhaarman.mockitokotlin2.mock import com.nhaarman.mockitokotlin2.times import com.nhaarman.mockitokotlin2.verify import org.junit.Assert.assertEquals import org.junit.Assert.assertNotNull import org.junit.Assert.assertTrue import org.junit.Assume.assumeTrue import org.junit.Before import org.junit.Test import org.junit.runner.RunWith /** Tests for [SidecarWindowBackend] class. */ @LargeTest @RunWith(AndroidJUnit4::class) public class SidecarWindowBackendTest : WindowTestBase() { private lateinit var context: Context @Before public fun setUp() { context = ApplicationProvider.getApplicationContext() SidecarWindowBackend.resetInstance() } @Test public fun testGetInstance() { val backend = SidecarWindowBackend.getInstance(context) assertNotNull(backend) // Verify that getInstance always returns the same value val newBackend = SidecarWindowBackend.getInstance(context) assertEquals(backend, newBackend) } @Test public fun testInitAndVerifySidecar() { val sidecarVersion = SidecarCompat.sidecarVersion assumeTrue(sidecarVersion != null) assertTrue(SidecarWindowBackend.isSidecarVersionSupported(sidecarVersion)) val sidecar = SidecarWindowBackend.initAndVerifyExtension(context) assertNotNull(sidecar) assertTrue(sidecar is SidecarCompat) assertTrue(sidecar!!.validateExtensionInterface()) } @Test public fun testRegisterLayoutChangeCallback() { activityTestRule.scenario.onActivity { activity -> val backend = SidecarWindowBackend.getInstance(context) backend.windowExtension = mock() // Check registering the layout change callback val consumer = mock<Consumer<WindowLayoutInfo>>() backend.registerLayoutChangeCallback(activity, { obj: Runnable -> obj.run() }, consumer) assertEquals(1, backend.windowLayoutChangeCallbacks.size.toLong()) verify(backend.windowExtension!!).onWindowLayoutChangeListenerAdded(activity) // Check unregistering the layout change callback backend.unregisterLayoutChangeCallback(consumer) assertTrue(backend.windowLayoutChangeCallbacks.isEmpty()) verify(backend.windowExtension!!).onWindowLayoutChangeListenerRemoved( eq(activity) ) } } @Test public fun testRegisterLayoutChangeCallback_callsExtensionOnce() { activityTestRule.scenario.onActivity { activity -> val backend = SidecarWindowBackend.getInstance(context) backend.windowExtension = mock() // Check registering the layout change callback val consumer = mock<Consumer<WindowLayoutInfo>>() backend.registerLayoutChangeCallback(activity, Runnable::run, consumer) backend.registerLayoutChangeCallback(activity, Runnable::run, mock()) assertEquals(2, backend.windowLayoutChangeCallbacks.size.toLong()) verify(backend.windowExtension!!).onWindowLayoutChangeListenerAdded(activity) // Check unregistering the layout change callback backend.unregisterLayoutChangeCallback(consumer) assertEquals(1, backend.windowLayoutChangeCallbacks.size.toLong()) verify(backend.windowExtension!!, times(0)) .onWindowLayoutChangeListenerRemoved(eq(activity)) } } @Test public fun testRegisterLayoutChangeCallback_clearListeners() { activityTestRule.scenario.onActivity { activity -> val backend = SidecarWindowBackend.getInstance(context) backend.windowExtension = mock() // Check registering the layout change callback val firstConsumer = mock<Consumer<WindowLayoutInfo>>() val secondConsumer = mock<Consumer<WindowLayoutInfo>>() backend.registerLayoutChangeCallback( activity, { obj: Runnable -> obj.run() }, firstConsumer ) backend.registerLayoutChangeCallback( activity, { obj: Runnable -> obj.run() }, secondConsumer ) // Check unregistering the layout change callback backend.unregisterLayoutChangeCallback(firstConsumer) backend.unregisterLayoutChangeCallback(secondConsumer) assertTrue(backend.windowLayoutChangeCallbacks.isEmpty()) verify(backend.windowExtension!!).onWindowLayoutChangeListenerRemoved(activity) } } @Test public fun testLayoutChangeCallback_emitNewValue() { activityTestRule.scenario.onActivity { activity -> val backend = SidecarWindowBackend.getInstance(context) backend.windowExtension = mock() // Check that callbacks from the extension are propagated correctly val consumer = mock<Consumer<WindowLayoutInfo>>() backend.registerLayoutChangeCallback(activity, { obj: Runnable -> obj.run() }, consumer) val windowLayoutInfo = newTestWindowLayoutInfo() val backendListener = backend.ExtensionListenerImpl() backendListener.onWindowLayoutChanged(activity, windowLayoutInfo) verify(consumer).accept(eq(windowLayoutInfo)) } } @Test public fun testWindowLayoutInfo_updatesOnSubsequentRegistration() { val interfaceCompat = SwitchOnUnregisterExtensionInterfaceCompat() val backend = SidecarWindowBackend(interfaceCompat) val activity = mock<Activity>() val consumer = TestConsumer<WindowLayoutInfo>() val expected = mutableListOf<WindowLayoutInfo>() backend.registerLayoutChangeCallback(activity, Runnable::run, consumer) expected.add(interfaceCompat.currentWindowLayoutInfo()) backend.unregisterLayoutChangeCallback(consumer) backend.registerLayoutChangeCallback(activity, Runnable::run, consumer) expected.add(interfaceCompat.currentWindowLayoutInfo()) backend.unregisterLayoutChangeCallback(consumer) consumer.assertValues(expected) } @Test public fun testWindowLayoutInfo_secondCallbackUpdatesOnRegistration() { val interfaceCompat = SwitchOnUnregisterExtensionInterfaceCompat() val backend = SidecarWindowBackend(interfaceCompat) val activity = mock<Activity>() val firstConsumer = TestConsumer<WindowLayoutInfo>() val secondConsumer = TestConsumer<WindowLayoutInfo>() val executor = MoreExecutors.directExecutor() val firstExpected = mutableListOf<WindowLayoutInfo>() val secondExpected = mutableListOf<WindowLayoutInfo>() backend.registerLayoutChangeCallback(activity, executor, firstConsumer) firstExpected.add(interfaceCompat.currentWindowLayoutInfo()) backend.registerLayoutChangeCallback(activity, executor, secondConsumer) secondExpected.add(interfaceCompat.currentWindowLayoutInfo()) backend.unregisterLayoutChangeCallback(firstConsumer) backend.unregisterLayoutChangeCallback(secondConsumer) firstConsumer.assertValues(firstExpected) secondConsumer.assertValues(secondExpected) } internal companion object { private fun newTestWindowLayoutInfo(): WindowLayoutInfo { val feature1: DisplayFeature = HardwareFoldingFeature(Bounds(0, 2, 3, 4), HINGE, FLAT) val feature2: DisplayFeature = HardwareFoldingFeature(Bounds(0, 1, 5, 1), HINGE, FLAT) val displayFeatures = listOf(feature1, feature2) return WindowLayoutInfo(displayFeatures) } } }
apache-2.0
4759b0ccb91db34b4885e7c023d2f800
42.312796
100
0.716927
5.335085
false
true
false
false
androidx/androidx
compose/ui/ui/samples/src/main/java/androidx/compose/ui/samples/AndroidViewSample.kt
3
2568
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.ui.samples import android.view.View import android.view.ViewGroup import android.widget.TextView import androidx.annotation.Sampled import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.requiredSize import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.draw.drawBehind import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.drawscope.drawIntoCanvas import androidx.compose.ui.graphics.nativeCanvas import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.unit.dp import androidx.compose.ui.viewinterop.AndroidView import kotlin.math.roundToInt @Suppress("SetTextI18n") @Sampled @Composable fun AndroidViewSample() { // Compose a TextView. AndroidView({ context -> TextView(context).apply { text = "This is a TextView" } }) // Compose a View and update its size based on state. Note the modifiers. var size by remember { mutableStateOf(20) } AndroidView(::View, Modifier.clickable { size += 20 }.background(Color.Blue)) { view -> view.layoutParams = ViewGroup.LayoutParams(size, size) } } @Sampled @Composable fun AndroidDrawableInDrawScopeSample() { val drawable = LocalContext.current.getDrawable(R.drawable.sample_drawable) Box( modifier = Modifier.requiredSize(100.dp) .drawBehind { drawIntoCanvas { canvas -> drawable?.let { it.setBounds(0, 0, size.width.roundToInt(), size.height.roundToInt()) it.draw(canvas.nativeCanvas) } } } ) }
apache-2.0
dc5ad8fb8d79ddf67618d2b1af622a32
35.685714
93
0.734813
4.382253
false
false
false
false
androidx/androidx
lifecycle/lifecycle-compiler/src/main/kotlin/androidx/lifecycle/writer.kt
3
8357
/* * Copyright (C) 2017 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.lifecycle import androidx.lifecycle.model.AdapterClass import androidx.lifecycle.model.EventMethodCall import androidx.lifecycle.model.getAdapterName import com.squareup.javapoet.AnnotationSpec import com.squareup.javapoet.ClassName import com.squareup.javapoet.FieldSpec import com.squareup.javapoet.JavaFile import com.squareup.javapoet.MethodSpec import com.squareup.javapoet.ParameterSpec import com.squareup.javapoet.TypeName import com.squareup.javapoet.TypeSpec import javax.annotation.processing.ProcessingEnvironment import javax.lang.model.element.Modifier import javax.lang.model.element.TypeElement import javax.tools.StandardLocation fun writeModels(infos: List<AdapterClass>, processingEnv: ProcessingEnvironment) { infos.forEach({ writeAdapter(it, processingEnv) }) } private val GENERATED_PACKAGE = "javax.annotation" private val GENERATED_NAME = "Generated" private val LIFECYCLE_EVENT = Lifecycle.Event::class.java private val T = "\$T" private val N = "\$N" private val L = "\$L" private val S = "\$S" private val OWNER_PARAM: ParameterSpec = ParameterSpec.builder( ClassName.get(LifecycleOwner::class.java), "owner" ).build() private val EVENT_PARAM: ParameterSpec = ParameterSpec.builder( ClassName.get(LIFECYCLE_EVENT), "event" ).build() private val ON_ANY_PARAM: ParameterSpec = ParameterSpec.builder(TypeName.BOOLEAN, "onAny").build() private val METHODS_LOGGER: ParameterSpec = ParameterSpec.builder( ClassName.get(MethodCallsLogger::class.java), "logger" ).build() private const val HAS_LOGGER_VAR = "hasLogger" private fun writeAdapter(adapter: AdapterClass, processingEnv: ProcessingEnvironment) { val receiverField: FieldSpec = FieldSpec.builder( ClassName.get(adapter.type), "mReceiver", Modifier.FINAL ).build() val dispatchMethodBuilder = MethodSpec.methodBuilder("callMethods") .returns(TypeName.VOID) .addParameter(OWNER_PARAM) .addParameter(EVENT_PARAM) .addParameter(ON_ANY_PARAM) .addParameter(METHODS_LOGGER) .addModifiers(Modifier.PUBLIC) .addAnnotation(Override::class.java) val dispatchMethod = dispatchMethodBuilder.apply { addStatement("boolean $L = $N != null", HAS_LOGGER_VAR, METHODS_LOGGER) val callsByEventType = adapter.calls.groupBy { it.method.onLifecycleEvent.value } beginControlFlow("if ($N)", ON_ANY_PARAM).apply { writeMethodCalls(callsByEventType[Lifecycle.Event.ON_ANY] ?: emptyList(), receiverField) }.endControlFlow() callsByEventType .filterKeys { key -> key != Lifecycle.Event.ON_ANY } .forEach { (event, calls) -> beginControlFlow("if ($N == $T.$L)", EVENT_PARAM, LIFECYCLE_EVENT, event) writeMethodCalls(calls, receiverField) endControlFlow() } }.build() val receiverParam = ParameterSpec.builder( ClassName.get(adapter.type), "receiver" ).build() val syntheticMethods = adapter.syntheticMethods.map { val method = MethodSpec.methodBuilder(syntheticName(it)) .returns(TypeName.VOID) .addModifiers(Modifier.PUBLIC) .addModifiers(Modifier.STATIC) .addParameter(receiverParam) if (it.parameters.size >= 1) { method.addParameter(OWNER_PARAM) } if (it.parameters.size == 2) { method.addParameter(EVENT_PARAM) } val count = it.parameters.size val paramString = generateParamString(count) method.addStatement( "$N.$L($paramString)", receiverParam, it.name(), *takeParams(count, OWNER_PARAM, EVENT_PARAM) ) method.build() } val constructor = MethodSpec.constructorBuilder() .addParameter(receiverParam) .addStatement("this.$N = $N", receiverField, receiverParam) .build() val adapterName = getAdapterName(adapter.type) val adapterTypeSpecBuilder = TypeSpec.classBuilder(adapterName) .addModifiers(Modifier.PUBLIC) .addSuperinterface(ClassName.get(GeneratedAdapter::class.java)) .addField(receiverField) .addMethod(constructor) .addMethod(dispatchMethod) .addMethods(syntheticMethods) .addOriginatingElement(adapter.type) addGeneratedAnnotationIfAvailable(adapterTypeSpecBuilder, processingEnv) JavaFile.builder(adapter.type.getPackageQName(), adapterTypeSpecBuilder.build()) .build().writeTo(processingEnv.filer) generateKeepRule(adapter.type, processingEnv) } private fun addGeneratedAnnotationIfAvailable( adapterTypeSpecBuilder: TypeSpec.Builder, processingEnv: ProcessingEnvironment ) { val generatedAnnotationAvailable = processingEnv .elementUtils .getTypeElement(GENERATED_PACKAGE + "." + GENERATED_NAME) != null if (generatedAnnotationAvailable) { val generatedAnnotationSpec = AnnotationSpec.builder(ClassName.get(GENERATED_PACKAGE, GENERATED_NAME)).addMember( "value", S, LifecycleProcessor::class.java.canonicalName ).build() adapterTypeSpecBuilder.addAnnotation(generatedAnnotationSpec) } } private fun generateKeepRule(type: TypeElement, processingEnv: ProcessingEnvironment) { val adapterClass = type.getPackageQName() + "." + getAdapterName(type) val observerClass = type.toString() val keepRule = """# Generated keep rule for Lifecycle observer adapter. |-if class $observerClass { | <init>(...); |} |-keep class $adapterClass { | <init>(...); |} |""".trimMargin() // Write the keep rule to the META-INF/proguard directory of the Jar file. The file name // contains the fully qualified observer name so that file names are unique. This will allow any // jar file merging to not overwrite keep rule files. val path = "META-INF/proguard/$observerClass.pro" val out = processingEnv.filer.createResource(StandardLocation.CLASS_OUTPUT, "", path, type) out.openWriter().use { it.write(keepRule) } } private fun MethodSpec.Builder.writeMethodCalls( calls: List<EventMethodCall>, receiverField: FieldSpec ) { calls.forEach { (method, syntheticAccess) -> val count = method.method.parameters.size val callType = 1 shl count val methodName = method.method.name() beginControlFlow( "if (!$L || $N.approveCall($S, $callType))", HAS_LOGGER_VAR, METHODS_LOGGER, methodName ).apply { if (syntheticAccess == null) { val paramString = generateParamString(count) addStatement( "$N.$L($paramString)", receiverField, methodName, *takeParams(count, OWNER_PARAM, EVENT_PARAM) ) } else { val originalType = syntheticAccess val paramString = generateParamString(count + 1) val className = ClassName.get( originalType.getPackageQName(), getAdapterName(originalType) ) addStatement( "$T.$L($paramString)", className, syntheticName(method.method), *takeParams(count + 1, receiverField, OWNER_PARAM, EVENT_PARAM) ) } }.endControlFlow() } addStatement("return") } private fun takeParams(count: Int, vararg params: Any) = params.take(count).toTypedArray() private fun generateParamString(count: Int) = (0 until count).joinToString(",") { N }
apache-2.0
6fe8b2a9a002cd5178c57e1dda6767d6
37.159817
100
0.669499
4.650529
false
false
false
false
chemickypes/Glitchy
glitchappcore/src/main/java/me/bemind/glitchappcore/Models.kt
1
10209
package me.bemind.glitchappcore import android.graphics.Bitmap import android.os.Parcel import android.os.Parcelable import me.bemind.glitch.Effect import me.bemind.glitch.Motion /** * Created by angelomoroni on 10/04/17. */ data class Response<out T, out V>(val activity: T, val image: V) data class Image(val bitmap: Bitmap,val effect: Effect,var saved:Boolean) : Parcelable{ companion object { @JvmField val CREATOR: Parcelable.Creator<Image> = object : Parcelable.Creator<Image> { override fun createFromParcel(source: Parcel): Image = Image(source) override fun newArray(size: Int): Array<Image?> = arrayOfNulls(size) } } constructor(source: Parcel) : this(source.readParcelable<Bitmap>(Bitmap::class.java.classLoader), Effect.values()[source.readInt()], 1.equals(source.readInt())) override fun describeContents() = 0 override fun writeToParcel(dest: Parcel?, flags: Int) { dest?.writeParcelable(bitmap, 0) dest?.writeInt(effect.ordinal) dest?.writeInt((if (saved) 1 else 0)) } } data class ImageDescriptor ( val index:Int, val imageName:String,val effect: Effect,var saved: Boolean) : Parcelable{ companion object { @JvmField val CREATOR: Parcelable.Creator<ImageDescriptor> = object : Parcelable.Creator<ImageDescriptor> { override fun createFromParcel(source: Parcel): ImageDescriptor = ImageDescriptor(source) override fun newArray(size: Int): Array<ImageDescriptor?> = arrayOfNulls(size) } } constructor(source: Parcel) : this(source.readInt(), source.readString(), Effect.values()[source.readInt()], 1.equals(source.readInt())) override fun describeContents() = 0 override fun writeToParcel(dest: Parcel?, flags: Int) { dest?.writeInt(index) dest?.writeString(imageName) dest?.writeInt(effect.ordinal) dest?.writeInt((if (saved) 1 else 0)) } } enum class State { BASE,EFFECT } abstract class EffectState(open val layout:Int) :Parcelable data class WebpEffectState(override val layout: Int) : EffectState(layout), Parcelable{ companion object { @JvmField val CREATOR: Parcelable.Creator<WebpEffectState> = object : Parcelable.Creator<WebpEffectState> { override fun createFromParcel(source: Parcel): WebpEffectState = WebpEffectState(source) override fun newArray(size: Int): Array<WebpEffectState?> = arrayOfNulls(size) } } constructor(source: Parcel) : this(source.readInt()) override fun describeContents() = 0 override fun writeToParcel(dest: Parcel?, flags: Int) { dest?.writeInt(layout) } } /*data class NoiseEffectState(override val layout: Int) : EffectState(layout), Parcelable{ companion object { @JvmField val CREATOR: Parcelable.Creator<NoiseEffectState> = object : Parcelable.Creator<NoiseEffectState> { override fun createFromParcel(source: Parcel): NoiseEffectState = NoiseEffectState(source) override fun newArray(size: Int): Array<NoiseEffectState?> = arrayOfNulls(size) } } constructor(source: Parcel) : this(source.readInt()) override fun describeContents() = 0 override fun writeToParcel(dest: Parcel?, flags: Int) { dest?.writeInt(layout) } }*/ data class NoiseEffectState(override val layout: Int,val progress:Int) : EffectState(layout), Parcelable{ companion object { @JvmField val CREATOR: Parcelable.Creator<NoiseEffectState> = object : Parcelable.Creator<NoiseEffectState> { override fun createFromParcel(source: Parcel): NoiseEffectState = NoiseEffectState(source) override fun newArray(size: Int): Array<NoiseEffectState?> = arrayOfNulls(size) } } constructor(source: Parcel) : this(source.readInt(), source.readInt()) override fun describeContents() = 0 override fun writeToParcel(dest: Parcel?, flags: Int) { dest?.writeInt(layout) dest?.writeInt(progress) } } data class CensoredEffectState(override val layout: Int) : EffectState(layout),Parcelable{ companion object { @JvmField val CREATOR: Parcelable.Creator<CensoredEffectState> = object : Parcelable.Creator<CensoredEffectState> { override fun createFromParcel(source: Parcel): CensoredEffectState = CensoredEffectState(source) override fun newArray(size: Int): Array<CensoredEffectState?> = arrayOfNulls(size) } } constructor(source: Parcel) : this( source.readInt() ) override fun describeContents() = 0 override fun writeToParcel(dest: Parcel, flags: Int) { dest.writeInt(layout) } } data class SwapEffectState (override val layout: Int) : EffectState(layout), Parcelable{ companion object { @JvmField val CREATOR: Parcelable.Creator<SwapEffectState> = object : Parcelable.Creator<SwapEffectState> { override fun createFromParcel(source: Parcel): SwapEffectState = SwapEffectState(source) override fun newArray(size: Int): Array<SwapEffectState?> = arrayOfNulls(size) } } constructor(source: Parcel) : this(source.readInt()) override fun describeContents() = 0 override fun writeToParcel(dest: Parcel?, flags: Int) { dest?.writeInt(layout) } } data class HooloovooEffectState (override val layout: Int,val progress: Int) : EffectState(layout), Parcelable{ companion object { @JvmField val CREATOR: Parcelable.Creator<HooloovooEffectState> = object : Parcelable.Creator<HooloovooEffectState> { override fun createFromParcel(source: Parcel): HooloovooEffectState = HooloovooEffectState(source) override fun newArray(size: Int): Array<HooloovooEffectState?> = arrayOfNulls(size) } } constructor(source: Parcel) : this( source.readInt(), source.readInt() ) override fun describeContents() = 0 override fun writeToParcel(dest: Parcel, flags: Int) { dest.writeInt(layout) dest.writeInt(progress) } } data class PixelEffectState(override val layout: Int,val progress: Int) : EffectState(layout),Parcelable{ companion object { @JvmField val CREATOR: Parcelable.Creator<PixelEffectState> = object : Parcelable.Creator<PixelEffectState> { override fun createFromParcel(source: Parcel): PixelEffectState = PixelEffectState(source) override fun newArray(size: Int): Array<PixelEffectState?> = arrayOfNulls(size) } } constructor(source: Parcel) : this( source.readInt(), source.readInt() ) override fun describeContents() = 0 override fun writeToParcel(dest: Parcel, flags: Int) { dest.writeInt(layout) dest.writeInt(progress) } } data class TPixelEffectState(override val layout: Int,val progress: Int) : EffectState(layout),Parcelable{ companion object { @JvmField val CREATOR: Parcelable.Creator<TPixelEffectState> = object : Parcelable.Creator<TPixelEffectState> { override fun createFromParcel(source: Parcel): TPixelEffectState = TPixelEffectState(source) override fun newArray(size: Int): Array<TPixelEffectState?> = arrayOfNulls(size) } } constructor(source: Parcel) : this( source.readInt(), source.readInt() ) override fun describeContents() = 0 override fun writeToParcel(dest: Parcel, flags: Int) { dest.writeInt(layout) dest.writeInt(progress) } } data class GlitchEffectState(override val layout: Int) : EffectState(layout), Parcelable { companion object { @JvmField val CREATOR: Parcelable.Creator<GlitchEffectState> = object : Parcelable.Creator<GlitchEffectState> { override fun createFromParcel(source: Parcel): GlitchEffectState = GlitchEffectState(source) override fun newArray(size: Int): Array<GlitchEffectState?> = arrayOfNulls(size) } } constructor(source: Parcel) : this(source.readInt()) override fun describeContents() = 0 override fun writeToParcel(dest: Parcel?, flags: Int) { dest?.writeInt(layout) } } data class GhostEffectState(override val layout: Int) : EffectState(layout), Parcelable { companion object { @JvmField val CREATOR: Parcelable.Creator<GlitchEffectState> = object : Parcelable.Creator<GlitchEffectState> { override fun createFromParcel(source: Parcel): GlitchEffectState = GlitchEffectState(source) override fun newArray(size: Int): Array<GlitchEffectState?> = arrayOfNulls(size) } } constructor(source: Parcel) : this(source.readInt()) override fun describeContents() = 0 override fun writeToParcel(dest: Parcel?, flags: Int) { dest?.writeInt(layout) } } data class WobbleEffectState(override val layout: Int) : EffectState(layout), Parcelable { companion object { @JvmField val CREATOR: Parcelable.Creator<WobbleEffectState> = object : Parcelable.Creator<WobbleEffectState> { override fun createFromParcel(source: Parcel): WobbleEffectState = WobbleEffectState(source) override fun newArray(size: Int): Array<WobbleEffectState?> = arrayOfNulls(size) } } constructor(source: Parcel) : this(source.readInt()) override fun describeContents() = 0 override fun writeToParcel(dest: Parcel?, flags: Int) { dest?.writeInt(layout) } } data class AnaglyphEffectState(override val layout:Int,val progress:Int) : EffectState(layout), Parcelable { companion object { @JvmField val CREATOR: Parcelable.Creator<AnaglyphEffectState> = object : Parcelable.Creator<AnaglyphEffectState> { override fun createFromParcel(source: Parcel): AnaglyphEffectState = AnaglyphEffectState(source) override fun newArray(size: Int): Array<AnaglyphEffectState?> = arrayOfNulls(size) } } constructor(source: Parcel) : this(source.readInt(), source.readInt()) override fun describeContents() = 0 override fun writeToParcel(dest: Parcel?, flags: Int) { dest?.writeInt(layout) dest?.writeInt(progress) } }
apache-2.0
16d5f0e91bcd69233240d0f40843c518
35.202128
164
0.692722
4.331353
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/jvm-debugger/core/src/org/jetbrains/kotlin/idea/debugger/filter/JvmDebuggerAddFilterStartupActivity.kt
1
1855
// 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.debugger.filter import com.intellij.debugger.settings.DebuggerSettings import com.intellij.openapi.project.Project import com.intellij.openapi.startup.StartupActivity import com.intellij.ui.classFilter.ClassFilter private const val KOTLIN_STDLIB_FILTER = "kotlin.*" private const val COMPOSE_RUNTIME_FILTER = "androidx.compose.runtime.*" class JvmDebuggerAddFilterStartupActivity : StartupActivity { override fun runActivity(project: Project) { val settings = DebuggerSettings.getInstance() ?: return settings.addSteppingFilterIfNeeded(KOTLIN_STDLIB_FILTER) settings.addSteppingFilterIfNeeded(COMPOSE_RUNTIME_FILTER) } } private fun DebuggerSettings.addSteppingFilterIfNeeded(pattern: String) { val steppingFilters = this.steppingFilters when (val occurrencesNum = steppingFilters.count { it.pattern == pattern }) { 0 -> setSteppingFilters(steppingFilters + ClassFilter(pattern)) 1 -> return else -> leaveOnlyFirstOccurenceOfSteppingFilter(pattern, occurrencesNum) } } private fun DebuggerSettings.leaveOnlyFirstOccurenceOfSteppingFilter(pattern: String, occurrencesNum: Int) { val steppingFilters = this.steppingFilters val newFilters = ArrayList<ClassFilter>(steppingFilters.size - occurrencesNum + 1) var firstOccurrenceFound = false for (filter in steppingFilters) { if (filter.pattern == pattern) { if (!firstOccurrenceFound) { newFilters.add(filter) firstOccurrenceFound = true } } else { newFilters.add(filter) } } setSteppingFilters(newFilters.toTypedArray()) }
apache-2.0
8930e3f859fba8ca18fb16ae8108bad0
38.468085
158
0.732615
4.502427
false
false
false
false
chiken88/passnotes
app/src/main/kotlin/com/ivanovsky/passnotes/domain/interactor/newdb/NewDatabaseInteractor.kt
1
3618
package com.ivanovsky.passnotes.domain.interactor.newdb import com.ivanovsky.passnotes.data.entity.FileDescriptor import com.ivanovsky.passnotes.data.entity.OperationError.* import com.ivanovsky.passnotes.data.entity.OperationResult import com.ivanovsky.passnotes.data.repository.EncryptedDatabaseRepository import com.ivanovsky.passnotes.data.repository.UsedFileRepository import com.ivanovsky.passnotes.data.repository.file.FSOptions import com.ivanovsky.passnotes.data.repository.file.FileSystemResolver import com.ivanovsky.passnotes.data.repository.keepass.KeepassDatabaseKey import com.ivanovsky.passnotes.domain.DispatcherProvider import com.ivanovsky.passnotes.domain.usecases.AddTemplatesUseCase import com.ivanovsky.passnotes.extensions.toUsedFile import kotlinx.coroutines.withContext class NewDatabaseInteractor( private val dbRepo: EncryptedDatabaseRepository, private val usedFileRepository: UsedFileRepository, private val fileSystemResolver: FileSystemResolver, private val addTemplatesUseCase: AddTemplatesUseCase, private val dispatchers: DispatcherProvider ) { suspend fun createNewDatabaseAndOpen( key: KeepassDatabaseKey, file: FileDescriptor, isAddTemplates: Boolean ): OperationResult<Boolean> { return withContext(dispatchers.IO) { val provider = fileSystemResolver.resolveProvider(file.fsAuthority) val existsResult = provider.exists(file) if (existsResult.isFailed) { return@withContext existsResult.takeError() } val isExists = existsResult.obj if (isExists) { return@withContext OperationResult.error(newFileIsAlreadyExistsError()) } val creationResult = dbRepo.createNew(key, file) if (creationResult.isFailed) { return@withContext creationResult.takeError() } else if (creationResult.isDeferred) { return@withContext OperationResult.error( newFileAccessError(MESSAGE_DEFERRED_OPERATIONS_ARE_NOT_SUPPORTED) ) } val openResult = dbRepo.open(key, file, FSOptions.DEFAULT) if (openResult.isFailed) { return@withContext openResult.takeError() } if (isAddTemplates) { val addTemplatesResult = addTemplatesUseCase.addTemplates() if (addTemplatesResult.isFailed) { return@withContext addTemplatesResult.takeError() } } val getFileResult = getFile(file) if (getFileResult.isFailed) { return@withContext getFileResult.takeError() } val newFile = getFileResult.obj val time = System.currentTimeMillis() val usedFile = newFile.toUsedFile( addedTime = time, lastAccessTime = time ) usedFileRepository.insert(usedFile) OperationResult.success(true) } } private fun getFile(file: FileDescriptor): OperationResult<FileDescriptor> { val provider = fileSystemResolver.resolveProvider(file.fsAuthority) val getFileResult = provider.getFile(file.path, FSOptions.DEFAULT) return when { getFileResult.isSucceeded -> getFileResult getFileResult.isDeferred -> OperationResult.error( newFileAccessError(MESSAGE_DEFERRED_OPERATIONS_ARE_NOT_SUPPORTED) ) else -> getFileResult.takeError() } } }
gpl-2.0
949c1d51186823bb537d7161c0957b34
37.913978
87
0.673024
5.124646
false
false
false
false
quran/quran_android
app/src/main/java/com/quran/labs/androidquran/HelpActivity.kt
2
884
package com.quran.labs.androidquran import android.os.Bundle import android.view.MenuItem import android.widget.TextView import androidx.appcompat.app.AppCompatActivity import androidx.core.text.HtmlCompat class HelpActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val actionBar = supportActionBar if (actionBar != null) { actionBar.setDisplayShowHomeEnabled(true) actionBar.setDisplayHomeAsUpEnabled(true) } setContentView(R.layout.help) val helpText = findViewById<TextView>(R.id.txtHelp) helpText.text = HtmlCompat.fromHtml(getString(R.string.help), HtmlCompat.FROM_HTML_MODE_COMPACT) } override fun onOptionsItemSelected(item: MenuItem): Boolean { if (item.itemId == android.R.id.home) { finish() return true } return false } }
gpl-3.0
b44ed3cd7ab572c360b49b59b4344ab8
25
100
0.74095
4.376238
false
false
false
false
davinkevin/Podcast-Server
backend/src/main/kotlin/com/github/davinkevin/podcastserver/podcast/PodcastService.kt
1
4647
package com.github.davinkevin.podcastserver.podcast import com.github.davinkevin.podcastserver.cover.Cover import com.github.davinkevin.podcastserver.cover.CoverRepository import com.github.davinkevin.podcastserver.service.storage.FileStorageService import com.github.davinkevin.podcastserver.service.storage.MovePodcastRequest import com.github.davinkevin.podcastserver.tag.Tag import com.github.davinkevin.podcastserver.tag.TagRepository import reactor.core.publisher.Flux import reactor.core.publisher.Mono import reactor.kotlin.core.publisher.toFlux import reactor.kotlin.core.publisher.toMono import reactor.kotlin.core.util.function.component1 import reactor.kotlin.core.util.function.component2 import java.util.* class PodcastService( private val repository: PodcastRepository, private val coverRepository: CoverRepository, private val tagRepository: TagRepository, private val fileService: FileStorageService ) { fun findAll(): Flux<Podcast> = repository.findAll() fun findById(id: UUID): Mono<Podcast> = repository.findById(id) fun findStatByPodcastIdAndPubDate(id: UUID, numberOfMonths: Int) = repository.findStatByPodcastIdAndPubDate(id, numberOfMonths) fun findStatByPodcastIdAndDownloadDate(id: UUID, numberOfMonths: Int) = repository.findStatByPodcastIdAndDownloadDate(id, numberOfMonths) fun findStatByPodcastIdAndCreationDate(id: UUID, numberOfMonths: Int) = repository.findStatByPodcastIdAndCreationDate(id, numberOfMonths) fun findStatByTypeAndCreationDate(numberOfMonths: Int) = repository.findStatByTypeAndCreationDate(numberOfMonths) fun findStatByTypeAndPubDate(numberOfMonths: Int) = repository.findStatByTypeAndPubDate(numberOfMonths) fun findStatByTypeAndDownloadDate(numberOfMonths: Int) = repository.findStatByTypeAndDownloadDate(numberOfMonths) fun save(p: PodcastForCreation): Mono<Podcast> { val oldTags = p.tags.toFlux().filter { it.id != null }.map { Tag(it.id!!, it.name) } val newTags = p.tags.toFlux().filter { it.id == null }.flatMap { tagRepository.save(it.name) } val tags = Flux.merge(oldTags, newTags).collectList() val cover = coverRepository.save(p.cover) return Mono.zip(tags, cover) .flatMap { (t, c) -> repository.save( title = p.title, url = p.url?.toASCIIString(), hasToBeDeleted = p.hasToBeDeleted, type = p.type, tags = t, cover = c) } .delayUntil { fileService.downloadPodcastCover(it) } } fun update(updatePodcast: PodcastForUpdate): Mono<Podcast> = findById(updatePodcast.id).flatMap { p -> val oldTags = updatePodcast.tags.toFlux().filter { it.id != null }.map { Tag(it.id!!, it.name) } val newTags = updatePodcast.tags.toFlux().filter { it.id == null }.flatMap { tagRepository.save(it.name) } val tags = Flux.merge(oldTags, newTags).collectList() val newCover = updatePodcast.cover val oldCover = p.cover val cover = if (!newCover.url.toASCIIString().startsWith("/") && oldCover.url != newCover.url) coverRepository.save(newCover).delayUntil { fileService.downloadPodcastCover(p.copy(cover = Cover(it.id, it.url, it.height, it.width))) } else Cover(oldCover.id, oldCover.url, oldCover.height, oldCover.width).toMono() val title = if (p.title != updatePodcast.title) { val movePodcastDetails = MovePodcastRequest( id = updatePodcast.id, from = p.title, to = updatePodcast.title ) fileService.movePodcast(movePodcastDetails) } else Mono.empty() Mono.zip(tags, cover) .flatMap { (t, c) -> repository.update( id = updatePodcast.id, title = updatePodcast.title, url = updatePodcast.url?.toASCIIString(), hasToBeDeleted = updatePodcast.hasToBeDeleted, tags = t, cover = c) } .delayUntil { title } } fun deleteById(id: UUID): Mono<Void> = repository .deleteById(id) .delayUntil { fileService.deletePodcast(it) } .then() }
apache-2.0
da769ea776ec1a24440cc1d4d5c70b60
45.939394
141
0.626856
4.494197
false
false
false
false
SimpleMobileTools/Simple-Flashlight
app/src/main/kotlin/com/simplemobiletools/flashlight/helpers/Constants.kt
1
665
package com.simplemobiletools.flashlight.helpers const val BRIGHT_DISPLAY = "bright_display" const val BRIGHT_DISPLAY_COLOR = "bright_display_color" const val STROBOSCOPE = "stroboscope" const val TURN_FLASHLIGHT_ON = "turn_flashlight_on" const val IS_ENABLED = "is_enabled" const val TOGGLE = "toggle" const val TOGGLE_WIDGET_UI = "toggle_widget_ui" const val STROBOSCOPE_FREQUENCY = "stroboscope_frequency" const val STROBOSCOPE_PROGRESS = "stroboscope_progress" const val FORCE_PORTRAIT_MODE = "force_portrait_mode" const val SOS = "sos" const val BRIGHTNESS_LEVEL = "brightness_level" const val MIN_BRIGHTNESS_LEVEL = 1 const val DEFAULT_BRIGHTNESS_LEVEL = -1
gpl-3.0
bbe359324cb90ec4817ca731981c3861
40.5625
57
0.781955
3.292079
false
false
false
false
AndroidX/constraintlayout
projects/ComposeConstraintLayout/dsl-verification/src/androidTest/java/com/example/dsl_verification/VerificationTest.kt
2
3536
/* * Copyright (C) 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 com.example.dsl_verification import androidx.compose.runtime.currentComposer import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.test.SemanticsMatcher import androidx.compose.ui.test.junit4.createComposeRule import androidx.constraintlayout.compose.DesignInfoDataKey import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.filters.MediumTest import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith /** * Unit test to verify layout results. * * Currently only for Composables written with the Kotlin DSL. See [ComposableInvocator] for * details. * * Run tests using device: Pixel 3 on API 30. */ @MediumTest @RunWith(AndroidJUnit4::class) class VerificationTest { @get:Rule val rule = createComposeRule() val invocator = ComposableInvocator( packageString = "com.example.dsl_verification.constraint", fileName = "DslVerification" ) @Test fun verifyComposables() { // TODO: Test doesn't work very well with Json, some part in the helper parser is not // stable, either from user-string to binary or binary to result-string val results = HashMap<String, String>() var composableIndex by mutableStateOf(0) // Observable state that we'll use to change the content in a recomposition var fqComposable = "" var baselineRaw = "" rule.setContent { // Set the content to the Composable at the given index fqComposable = invocator.invokeComposable(composableIndex, currentComposer) // We can only get the Resources in this context baselineRaw = LocalContext.current.resources.openRawResource(R.raw.results).bufferedReader() .readText() } for (i in 0..invocator.max) { rule.runOnUiThread { // Force a recomposition with the next Composable index composableIndex = i } // Wait for the content to settle rule.waitForIdle() val nodeInteration = rule.onNode(SemanticsMatcher.keyIsDefined(DesignInfoDataKey)) nodeInteration.assertExists() // Get the output from 'getDesignInfo' // A json with the constraints and bounds of the widgets in the layout val result = nodeInteration.fetchSemanticsNode().config[DesignInfoDataKey].getDesignInfo( startX = 0, startY = 0, args = 0b10.toString() // Second bit from the right for Bounds only ) // Save the result in a composable->result map results[fqComposable] = result } checkTest(baselineRaw, results) } }
apache-2.0
2cf126a05b75be4eb8572e92a9888665
37.868132
124
0.679864
4.739946
false
true
false
false
RP-Kit/RPKit
bukkit/rpk-stores-bukkit/src/main/kotlin/com/rpkit/store/bukkit/database/table/RPKPermanentPurchaseTable.kt
1
7845
/* * Copyright 2022 Ren Binden * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.rpkit.store.bukkit.database.table import com.rpkit.core.database.Database import com.rpkit.core.database.Table import com.rpkit.core.service.Services import com.rpkit.players.bukkit.profile.RPKProfile import com.rpkit.players.bukkit.profile.RPKProfileId import com.rpkit.players.bukkit.profile.RPKProfileService import com.rpkit.store.bukkit.RPKStoresBukkit import com.rpkit.store.bukkit.database.create import com.rpkit.store.bukkit.database.jooq.Tables.RPKIT_PERMANENT_PURCHASE import com.rpkit.store.bukkit.database.jooq.Tables.RPKIT_PURCHASE import com.rpkit.store.bukkit.purchase.RPKPermanentPurchase import com.rpkit.store.bukkit.purchase.RPKPermanentPurchaseImpl import com.rpkit.store.bukkit.purchase.RPKPurchaseId import com.rpkit.store.bukkit.storeitem.RPKPermanentStoreItem import com.rpkit.store.bukkit.storeitem.RPKStoreItemId import com.rpkit.store.bukkit.storeitem.RPKStoreItemService import java.util.concurrent.CompletableFuture import java.util.logging.Level class RPKPermanentPurchaseTable( private val database: Database, private val plugin: RPKStoresBukkit ) : Table { private val cache = if (plugin.config.getBoolean("caching.rpkit_permanent_purchase.id.enabled")) { database.cacheManager.createCache( "rpkit-stores-bukkit.rpkit_permanent_purchase.id", Int::class.javaObjectType, RPKPermanentPurchase::class.java, plugin.config.getLong("caching.rpkit_permanent_purchase.id.size") ) } else { null } fun insert(entity: RPKPermanentPurchase): CompletableFuture<Void> { return CompletableFuture.runAsync { val id = database.getTable(RPKPurchaseTable::class.java).insert(entity).join() ?: return@runAsync database.create .insertInto( RPKIT_PERMANENT_PURCHASE, RPKIT_PERMANENT_PURCHASE.PURCHASE_ID ) .values( id.value ) .execute() entity.id = id cache?.set(id.value, entity) }.exceptionally { exception -> plugin.logger.log(Level.SEVERE, "Failed to insert permanent purchase", exception) throw exception } } fun update(entity: RPKPermanentPurchase): CompletableFuture<Void> { val id = entity.id ?: return CompletableFuture.completedFuture(null) return CompletableFuture.runAsync { database.getTable(RPKPurchaseTable::class.java).update(entity).join() cache?.set(id.value, entity) }.exceptionally { exception -> plugin.logger.log(Level.SEVERE, "Failed to update permanent purchase", exception) throw exception } } operator fun get(id: RPKPurchaseId): CompletableFuture<out RPKPermanentPurchase?> { return CompletableFuture.supplyAsync { val result = database.create .select( RPKIT_PURCHASE.STORE_ITEM_ID, RPKIT_PURCHASE.PROFILE_ID, RPKIT_PURCHASE.PURCHASE_DATE, RPKIT_PERMANENT_PURCHASE.PURCHASE_ID ) .from( RPKIT_PURCHASE, RPKIT_PERMANENT_PURCHASE ) .where(RPKIT_PURCHASE.ID.eq(id.value)) .and(RPKIT_PERMANENT_PURCHASE.PURCHASE_ID.eq(RPKIT_PURCHASE.ID)) .fetchOne() ?: return@supplyAsync null val storeItemService = Services[RPKStoreItemService::class.java] ?: return@supplyAsync null val storeItem = storeItemService.getStoreItem(RPKStoreItemId(result[RPKIT_PURCHASE.STORE_ITEM_ID])).join() as? RPKPermanentStoreItem if (storeItem == null) { database.create .deleteFrom(RPKIT_PURCHASE) .where(RPKIT_PURCHASE.ID.eq(id.value)) .execute() database.create .deleteFrom(RPKIT_PERMANENT_PURCHASE) .where(RPKIT_PERMANENT_PURCHASE.PURCHASE_ID.eq(id.value)) .execute() cache?.remove(id.value) return@supplyAsync null } val profileService = Services[RPKProfileService::class.java] ?: return@supplyAsync null val profile = profileService.getProfile(RPKProfileId(result[RPKIT_PURCHASE.PROFILE_ID])).join() if (profile == null) { database.create .deleteFrom(RPKIT_PURCHASE) .where(RPKIT_PURCHASE.ID.eq(id.value)) .execute() database.create .deleteFrom(RPKIT_PERMANENT_PURCHASE) .where(RPKIT_PERMANENT_PURCHASE.PURCHASE_ID.eq(id.value)) .execute() cache?.remove(id.value) return@supplyAsync null } val permanentPurchase = RPKPermanentPurchaseImpl( RPKPurchaseId(id.value), storeItem, profile, result[RPKIT_PURCHASE.PURCHASE_DATE] ) cache?.set(id.value, permanentPurchase) return@supplyAsync permanentPurchase }.exceptionally { exception -> plugin.logger.log(Level.SEVERE, "Failed to get permanent purchase", exception) throw exception } } fun get(profile: RPKProfile): CompletableFuture<List<RPKPermanentPurchase>> { val profileId = profile.id ?: return CompletableFuture.completedFuture(emptyList()) return CompletableFuture.supplyAsync { val result = database.create .select(RPKIT_PERMANENT_PURCHASE.PURCHASE_ID) .from( RPKIT_PURCHASE, RPKIT_PERMANENT_PURCHASE ) .where(RPKIT_PURCHASE.ID.eq(RPKIT_PERMANENT_PURCHASE.ID)) .and(RPKIT_PURCHASE.PROFILE_ID.eq(profileId.value)) .fetch() val purchaseFutures = result.map { row -> get(RPKPurchaseId(row[RPKIT_PERMANENT_PURCHASE.PURCHASE_ID])) } CompletableFuture.allOf(*purchaseFutures.toTypedArray()).join() return@supplyAsync purchaseFutures.mapNotNull(CompletableFuture<out RPKPermanentPurchase?>::join) }.exceptionally { exception -> plugin.logger.log(Level.SEVERE, "Failed to get permanent purchases", exception) throw exception } } fun delete(entity: RPKPermanentPurchase): CompletableFuture<Void> { val id = entity.id ?: return CompletableFuture.completedFuture(null) return CompletableFuture.runAsync { database.getTable(RPKPurchaseTable::class.java).delete(entity).join() database.create .deleteFrom(RPKIT_PERMANENT_PURCHASE) .where(RPKIT_PERMANENT_PURCHASE.PURCHASE_ID.eq(id.value)) .execute() cache?.remove(id.value) }.exceptionally { exception -> plugin.logger.log(Level.SEVERE, "Failed to delete permanent purchase", exception) throw exception } } }
apache-2.0
cb655fbeda3b4e28d732cb4df7a7b97e
42.588889
132
0.625621
4.863608
false
false
false
false
dsvoronin/Kotson
src/main/kotlin/com/github/salomonbrys/kotson/Element.kt
1
3184
package com.github.salomonbrys.kotson import com.google.gson.JsonArray import com.google.gson.JsonElement import com.google.gson.JsonNull import com.google.gson.JsonObject import java.math.BigDecimal import java.math.BigInteger import java.util.* private fun <T : Any> JsonElement?._nullOr(getNotNull: JsonElement.() -> T) : T? = if (this == null || isJsonNull) null else getNotNull() public val JsonElement.string: String get() = asString public val JsonElement?.nullString: String? get() = _nullOr { string } public val JsonElement.bool: Boolean get() = asBoolean public val JsonElement?.nullBool: Boolean? get() = _nullOr { bool } public val JsonElement.byte: Byte get() = asByte public val JsonElement?.nullByte: Byte? get() = _nullOr { byte } public val JsonElement.char: Char get() = asCharacter public val JsonElement?.nullChar: Char? get() = _nullOr { char } public val JsonElement.short: Short get() = asShort public val JsonElement?.nullShort: Short? get() = _nullOr { short } public val JsonElement.int: Int get() = asInt public val JsonElement?.nullInt: Int? get() = _nullOr { int } public val JsonElement.long: Long get() = asLong public val JsonElement?.nullLong: Long? get() = _nullOr { long } public val JsonElement.float: Float get() = asFloat public val JsonElement?.nullFloat: Float? get() = _nullOr { float } public val JsonElement.double: Double get() = asDouble public val JsonElement?.nullDouble: Double? get() = _nullOr { double } public val JsonElement.number: Number get() = asNumber public val JsonElement?.nullNumber: Number? get() = _nullOr { number } public val JsonElement.bigInteger: BigInteger get() = asBigInteger public val JsonElement?.nullBigInteger: BigInteger? get() = _nullOr { bigInteger } public val JsonElement.bigDecimal: BigDecimal get() = asBigDecimal public val JsonElement?.nullBigDecimal: BigDecimal? get() = _nullOr { bigDecimal } public val JsonElement.array: JsonArray get() = asJsonArray public val JsonElement?.nullArray: JsonArray? get() = _nullOr { array } public val JsonElement.obj: JsonObject get() = asJsonObject public val JsonElement?.nullObj: JsonObject? get() = _nullOr { obj } public val jsonNull: JsonNull = JsonNull.INSTANCE operator public fun JsonElement.get(key: String): JsonElement = obj.get(key) ?: throw NoSuchElementException() operator public fun JsonElement.get(index: Int): JsonElement = array.get(index) ?: throw NoSuchElementException() public fun JsonElement.getOrNull(key: String): JsonElement? = obj.get(key) operator public fun JsonObject.contains(key: String): Boolean = has(key) public fun JsonObject.size(): Int = entrySet().size public fun JsonObject.isEmpty(): Boolean = entrySet().isEmpty() public fun JsonObject.isNotEmpty(): Boolean = entrySet().isNotEmpty() public fun JsonObject.keys(): Collection<String> = entrySet().map { it.key } public fun JsonObject.forEach(operation: (String, JsonElement) -> Unit): Unit = entrySet().forEach { operation(it.key, it.value) } operator public fun JsonArray.contains(value: Any): Boolean = contains(value.toJsonElement()) public fun JsonObject.toMap(): Map<String, JsonElement> = entrySet().toMap({ it.key }, { it.value })
mit
59888a31bcea6a3748078c2dda57ef09
43.222222
130
0.746859
3.921182
false
false
false
false
universum-studios/gradle_github_plugin
plugin/src/core/kotlin/universum/studios/gradle/github/service/api/BaseApi.kt
1
4379
/* * ************************************************************************************************* * Copyright 2017 Universum Studios * ************************************************************************************************* * 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 universum.studios.gradle.github.service.api import okhttp3.logging.HttpLoggingInterceptor import retrofit2.Retrofit import retrofit2.converter.moshi.MoshiConverterFactory import universum.studios.gradle.github.extension.RepositoryExtension import universum.studios.gradle.github.service.api.interceptor.HeaderInterceptor import universum.studios.gradle.github.service.api.interceptor.OAuthRequestInterceptor /** * Class which may be used as base for a concrete API implementation. This base class creates a * services PROXY implementation for the provided *servicesInterface* which may be later accessed * via *services* property. * * @author Martin Albedinsky * @since 1.0 * * @param T Type of the services for which to create the PROXY. * @param repository The repository for which may be performed service calls through the api. * @param servicesInterface Services interface for which to create its PROXY that may be used for * service call creation. * @constructor Creates a new instance of BaseApi with the specified services interface. */ internal abstract class BaseApi<out T>( /** * Repository for which should this api provide service calls. */ internal val repository: RepositoryExtension, servicesInterface: Class<T>) : Api { /* * Companion =================================================================================== */ /** */ internal companion object { /** * Boolean flag indicating whether to debug API requests/responses or not. */ private const val DEBUG = false /** * Name of the **Accept** header. */ const val HEADER_ACCEPT_NAME = "Accept" /** * Value for the **Accept** header. */ const val HEADER_ACCEPT_VALUE = "application/vnd.github.v3+json" } /* * Interface =================================================================================== */ /* * Members ===================================================================================== */ /** * PROXY instance of the services interface supplied for this API. */ internal val services: T = Retrofit.Builder() .baseUrl(Api.BASE_URL) .client(okhttp3.OkHttpClient.Builder() .addInterceptor(HeaderInterceptor(HEADER_ACCEPT_NAME, HEADER_ACCEPT_VALUE)) .addInterceptor(OAuthRequestInterceptor().apply { setToken(repository.accessToken) }) .addInterceptor(HttpLoggingInterceptor().setLevel( if (DEBUG) HttpLoggingInterceptor.Level.BODY else HttpLoggingInterceptor.Level.NONE )) .build() ) .addConverterFactory(MoshiConverterFactory.create()) .build().create(servicesInterface) /* * Constructors ================================================================================ */ /* * Methods ===================================================================================== */ /* */ override fun getRepository() = repository /* * Inner classes =============================================================================== */ }
apache-2.0
387c6d6eb933e9e319abce06d79e4b6e
38.107143
105
0.514273
6.073509
false
false
false
false
MaibornWolff/codecharta
analysis/import/GitLogParser/src/main/kotlin/de/maibornwolff/codecharta/importer/gitlogparser/parser/git/GitLogNumstatRawParserStrategy.kt
1
4270
package de.maibornwolff.codecharta.importer.gitlogparser.parser.git import de.maibornwolff.codecharta.importer.gitlogparser.input.Modification import de.maibornwolff.codecharta.importer.gitlogparser.parser.LogLineCollector import de.maibornwolff.codecharta.importer.gitlogparser.parser.LogParserStrategy import de.maibornwolff.codecharta.importer.gitlogparser.parser.git.AuthorParser.AUTHOR_ROW_INDICATOR import de.maibornwolff.codecharta.importer.gitlogparser.parser.git.CommitDateParser.DATE_ROW_INDICATOR import de.maibornwolff.codecharta.importer.gitlogparser.parser.git.MergeCommitDetector.MERGE_COMMIT_INDICATOR import de.maibornwolff.codecharta.importer.gitlogparser.parser.git.helper.GitLogNumstatParsingHelper import de.maibornwolff.codecharta.importer.gitlogparser.parser.git.helper.GitLogRawParsingHelper import java.time.OffsetDateTime import java.util.function.Predicate import java.util.stream.Collector import java.util.stream.Stream class GitLogNumstatRawParserStrategy : LogParserStrategy { override fun creationCommand(): String { return "git log --numstat --raw --topo-order --reverse -m" } override fun createLogLineCollector(): Collector<String, *, Stream<List<String>>> { return LogLineCollector.create(GIT_COMMIT_SEPARATOR_TEST) } override fun parseAuthor(commitLines: List<String>): String { val authorLine = commitLines.first { commitLine -> commitLine.startsWith(AUTHOR_ROW_INDICATOR) } return AuthorParser.parseAuthor(authorLine) } override fun parseModifications(commitLines: List<String>): List<Modification> { return commitLines .mapNotNull { if (isFileLine(it)) { parseModification(it) } else null } .groupingBy { it.currentFilename } .aggregate { _, aggregatedModification: Modification?, currentModification, _ -> when (aggregatedModification) { null -> mergeModifications(currentModification) else -> mergeModifications(aggregatedModification, currentModification) } } .values .toList() } override fun parseDate(commitLines: List<String>): OffsetDateTime { val dateLine = commitLines.first { commitLine -> commitLine.startsWith(DATE_ROW_INDICATOR) } return CommitDateParser.parseCommitDate(dateLine) } override fun parseIsMergeCommit(commitLines: List<String>): Boolean { return commitLines.any { commitLine -> commitLine.startsWith(MERGE_COMMIT_INDICATOR) } } companion object { private val GIT_COMMIT_SEPARATOR_TEST = Predicate<String> { logLine -> logLine.startsWith("commit") } private fun isFileLine(commitLine: String): Boolean { return GitLogRawParsingHelper.isFileLine(commitLine) || GitLogNumstatParsingHelper.isFileLine(commitLine) } internal fun parseModification(fileLine: String): Modification { return if (fileLine.startsWith(":")) { GitLogRawParsingHelper.parseModification(fileLine) } else GitLogNumstatParsingHelper.parseModification(fileLine) } private fun mergeModifications(vararg a: Modification): Modification { val filename = a[0].currentFilename val additions = a.map { it.additions }.sum() val deletions = a.map { it.deletions }.sum() val tmpModification = a.firstOrNull { modification -> modification.type != Modification.Type.UNKNOWN } var type = Modification.Type.UNKNOWN if (tmpModification != null) { type = tmpModification.type } if (type == Modification.Type.RENAME) { val temporaryModification = a.firstOrNull { modification -> modification.oldFilename.isNotEmpty() } var oldFilename = "" if (temporaryModification != null) { oldFilename = temporaryModification.oldFilename } return Modification(filename, oldFilename, additions, deletions, type) } return Modification(filename, additions, deletions, type) } } }
bsd-3-clause
72f1d6cf1662ac0d6eb15ad1f41173f0
43.020619
117
0.684309
4.908046
false
false
false
false
owntracks/android
project/app/src/main/java/org/owntracks/android/support/OSSRequirementsChecker.kt
1
1293
package org.owntracks.android.support import android.Manifest import android.content.Context import android.content.pm.PackageManager import android.location.LocationManager import androidx.core.content.ContextCompat import androidx.core.location.LocationManagerCompat import dagger.hilt.android.scopes.ActivityScoped import javax.inject.Inject @ActivityScoped open class OSSRequirementsChecker @Inject constructor( private val preferences: Preferences, open val context: Context ) : RequirementsChecker { override fun areRequirementsMet(): Boolean { return isLocationPermissionCheckPassed() && preferences.isSetupCompleted } override fun isLocationPermissionCheckPassed(): Boolean = ContextCompat.checkSelfPermission( context, Manifest.permission.ACCESS_FINE_LOCATION ) == PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission( context, Manifest.permission.ACCESS_COARSE_LOCATION ) == PackageManager.PERMISSION_GRANTED override fun isLocationServiceEnabled(): Boolean = (context.getSystemService(Context.LOCATION_SERVICE) as LocationManager?)?.run { LocationManagerCompat.isLocationEnabled(this) } ?: false override fun isPlayServicesCheckPassed(): Boolean = true }
epl-1.0
376b6b37a72bf6fb8728e640a106dff2
35.942857
96
0.774942
5.256098
false
false
false
false
NoodleMage/tachiyomi
app/src/main/java/eu/kanade/tachiyomi/data/glide/MangaModelLoader.kt
3
4944
package eu.kanade.tachiyomi.data.glide import android.util.LruCache import com.bumptech.glide.integration.okhttp3.OkHttpStreamFetcher import com.bumptech.glide.load.Options import com.bumptech.glide.load.model.* import eu.kanade.tachiyomi.data.cache.CoverCache import eu.kanade.tachiyomi.data.database.models.Manga import eu.kanade.tachiyomi.network.NetworkHelper import eu.kanade.tachiyomi.source.SourceManager import eu.kanade.tachiyomi.source.online.HttpSource import uy.kohesive.injekt.Injekt import uy.kohesive.injekt.api.get import uy.kohesive.injekt.injectLazy import java.io.File import java.io.InputStream /** * A class for loading a cover associated with a [Manga] that can be present in our own cache. * Coupled with [LibraryMangaUrlFetcher], this class allows to implement the following flow: * * - Check in RAM LRU. * - Check in disk LRU. * - Check in this module. * - Fetch from the network connection. * * @param context the application context. */ class MangaModelLoader : ModelLoader<Manga, InputStream> { /** * Cover cache where persistent covers are stored. */ private val coverCache: CoverCache by injectLazy() /** * Source manager. */ private val sourceManager: SourceManager by injectLazy() /** * Default network client. */ private val defaultClient = Injekt.get<NetworkHelper>().client /** * LRU cache whose key is the thumbnail url of the manga, and the value contains the request url * and the file where it should be stored in case the manga is a favorite. */ private val lruCache = LruCache<GlideUrl, File>(100) /** * Map where request headers are stored for a source. */ private val cachedHeaders = hashMapOf<Long, LazyHeaders>() /** * Factory class for creating [MangaModelLoader] instances. */ class Factory : ModelLoaderFactory<Manga, InputStream> { override fun build(multiFactory: MultiModelLoaderFactory): ModelLoader<Manga, InputStream> { return MangaModelLoader() } override fun teardown() {} } override fun handles(model: Manga): Boolean { return true } /** * Returns a fetcher for the given manga or null if the url is empty. * * @param manga the model. * @param width the width of the view where the resource will be loaded. * @param height the height of the view where the resource will be loaded. */ override fun buildLoadData(manga: Manga, width: Int, height: Int, options: Options): ModelLoader.LoadData<InputStream>? { // Check thumbnail is not null or empty val url = manga.thumbnail_url if (url == null || url.isEmpty()) { return null } if (url.startsWith("http")) { val source = sourceManager.get(manga.source) as? HttpSource val glideUrl = GlideUrl(url, getHeaders(manga, source)) // Get the resource fetcher for this request url. val networkFetcher = OkHttpStreamFetcher(source?.client ?: defaultClient, glideUrl) if (!manga.favorite) { return ModelLoader.LoadData(glideUrl, networkFetcher) } // Obtain the file for this url from the LRU cache, or retrieve and add it to the cache. val file = lruCache.getOrPut(glideUrl) { coverCache.getCoverFile(url) } val libraryFetcher = LibraryMangaUrlFetcher(networkFetcher, manga, file) // Return an instance of the fetcher providing the needed elements. return ModelLoader.LoadData(MangaSignature(manga, file), libraryFetcher) } else { // Get the file from the url, removing the scheme if present. val file = File(url.substringAfter("file://")) // Return an instance of the fetcher providing the needed elements. return ModelLoader.LoadData(MangaSignature(manga, file), FileFetcher(file)) } } /** * Returns the request headers for a source copying its OkHttp headers and caching them. * * @param manga the model. */ fun getHeaders(manga: Manga, source: HttpSource?): Headers { if (source == null) return LazyHeaders.DEFAULT return cachedHeaders.getOrPut(manga.source) { LazyHeaders.Builder().apply { val nullStr: String? = null setHeader("User-Agent", nullStr) for ((key, value) in source.headers.toMultimap()) { addHeader(key, value[0]) } }.build() } } private inline fun <K, V> LruCache<K, V>.getOrPut(key: K, defaultValue: () -> V): V { val value = get(key) return if (value == null) { val answer = defaultValue() put(key, answer) answer } else { value } } }
apache-2.0
b2146abd08ac2b559e8710c2c8327677
32.863014
100
0.639968
4.594796
false
false
false
false
luiqn2007/miaowo
app/src/main/java/org/miaowo/miaowo/App.kt
1
3298
package org.miaowo.miaowo import android.app.Application import android.content.Context import android.graphics.drawable.Drawable import android.net.Uri import android.support.v4.content.res.ResourcesCompat import android.util.Log import android.widget.ImageView import com.blankj.utilcode.util.AppUtils import com.blankj.utilcode.util.SPUtils import com.blankj.utilcode.util.Utils import com.mikepenz.materialdrawer.util.DrawerImageLoader import com.squareup.picasso.Picasso import okhttp3.Call import okhttp3.Request import okhttp3.Response import org.miaowo.miaowo.other.BaseHttpCallback import org.miaowo.miaowo.other.template.EmptyHttpCallback import java.io.File import java.io.FileOutputStream import kotlin.properties.Delegates /** * * Created by luqin on 16-12-28. */ class App : Application() { companion object { var i by Delegates.notNull<App>() val SP by lazy { SPUtils.getInstance("miao")!! } } override fun onCreate() { super.onCreate() i = this Log.i("MiaoApp", "喵~~~ \n" + "凯神团队创建了好奇喵,后来团队解散,好奇喵服务器关停\n" + "幸好在 GC 前,小久等风纪组重新组织,系统菌重新创建网页版好奇喵,名为 喵窝\n" + "\n向凯神团队,好奇喵风纪组等每一位为维护好奇喵健康发展的喵们致敬\n" + "\n全体起立,敬礼\n") DrawerImageLoader.init(object : DrawerImageLoader.IDrawerImageLoader { override fun placeholder(ctx: Context?) = placeholder(ctx, null) override fun set(imageView: ImageView?, uri: Uri?, placeholder: Drawable?) = set(imageView, uri, placeholder, null) override fun placeholder(ctx: Context?, tag: String?) = ResourcesCompat.getDrawable([email protected], R.drawable.ic_loading, null)!! override fun cancel(imageView: ImageView?) = Picasso.with(imageView?.context).cancelRequest(imageView) override fun set(imageView: ImageView?, uri: Uri?, placeholder: Drawable?, tag: String?) { var creator = Picasso.with(imageView?.context) .load(uri) .placeholder(placeholder).error(R.drawable.ic_error).fit() if (tag != null) creator = creator.tag(tag) creator.into(imageView) } }) Utils.init(this) } /** * 进行升级操作 */ fun update(url: String) { API.okhttp.newCall(Request.Builder().url(url).build()).enqueue(object : BaseHttpCallback<Any>() { override fun onSucceed(call: Call?, response: Response) { val dir = getDir("update", Context.MODE_PRIVATE) if (!dir.isDirectory) dir.mkdirs() val file = File(dir, "miaowo.apk") if (file.exists()) file.delete() if (!file.createNewFile()) throw Exception(getString(R.string.err_apk)) response.body()?.byteStream()?.apply { val out = FileOutputStream(file) copyTo(out) out.flush() out.close() }?.close() AppUtils.installApp(file) } }) } }
apache-2.0
1787e822ce2f653f70fd4441b6e7be38
36.144578
146
0.620701
3.722222
false
false
false
false
madtcsa/AppManager
app/src/main/java/com/md/appmanager/AppManagerApplication.kt
1
797
package com.md.appmanager import android.app.Application import com.md.appmanager.utils.AppPreferences import com.mikepenz.google_material_typeface_library.GoogleMaterial import com.mikepenz.iconics.Iconics class AppManagerApplication : Application() { override fun onCreate() { super.onCreate() appPreferences = AppPreferences(this) isPro = this.packageName == proPackage Iconics.registerFont(GoogleMaterial()) } companion object { var appPreferences: AppPreferences? = null private var isPro: Boolean = false fun isPro(): Boolean? { return isPro } fun setPro(res: Boolean?) { isPro = res!! } val proPackage: String get() = "com.md.appmanager" } }
gpl-3.0
604a5b96c54576d55f0b7d6cb7018469
23.151515
67
0.641154
4.633721
false
false
false
false
MHP-A-Porsche-Company/CDUI-Showcase-Android
app/src/main/kotlin/com/mhp/showcase/network/GetStreamNetworkService.kt
1
1732
package com.mhp.showcase.network import android.os.Handler import android.util.Log import com.android.volley.Request import com.android.volley.RequestQueue import com.android.volley.Response import com.android.volley.toolbox.JsonObjectRequest import com.google.gson.Gson import com.mhp.showcase.ShowcaseApplication import com.mhp.showcase.network.model.ContentResponse import com.mhp.showcase.util.Constants import io.reactivex.Observable import io.reactivex.ObservableEmitter import javax.inject.Inject /** * Network service to get the definition of blocks for the stream screen */ class GetStreamNetworkService { private val tag = GetStreamNetworkService::class.java.simpleName @Inject internal lateinit var requestQueue: RequestQueue @Inject internal lateinit var gson: Gson init { ShowcaseApplication.graph.inject(this) } val blocks: Observable<ContentResponse> get() = Observable.create { it -> this.startRequesting(e = it) } private fun startRequesting(e: ObservableEmitter<ContentResponse>) { if (e.isDisposed) { return } val jsObjRequest = JsonObjectRequest( Request.Method.GET, Constants.URL_STREAM, null, Response.Listener { val blockResponse = gson.fromJson(it.toString(), ContentResponse::class.java) e.onNext(blockResponse) Handler().postDelayed({ startRequesting(e) }, 500) }, Response.ErrorListener { Log.d(tag, "Network error occurred", it) } ) jsObjRequest.setShouldCache(false) requestQueue.add(jsObjRequest) } }
mit
d3de428e84311aa92a9ea89b79f74256
29.946429
97
0.671478
4.655914
false
false
false
false
christophpickl/gadsu
src/test/kotlin/at/cpickl/gadsu/testinfra/expect.kt
1
1681
package at.cpickl.gadsu.testinfra import org.hamcrest.MatcherAssert.assertThat import org.hamcrest.Matchers.* import org.testng.Assert import kotlin.reflect.KClass object Expects { @Suppress("UNCHECKED_CAST") fun <E : Exception> expect(type: KClass<E>, action: () -> Unit, messageContains: String? = null, causedByType: KClass<out Exception>? = null, causedByMessageContains: String? = null, exceptionAsserter: ((E) -> Unit)? = null) { try { action() Assert.fail("Expected a ${type.simpleName} to be thrown!") } catch (e: Exception) { assertThat("Expected an exception of type '${type.simpleName}' but a '${e.javaClass.simpleName}' was thrown!", e.javaClass != type, equalTo(true)) if (messageContains != null) { assertThat(e.message, containsString(messageContains)) } if (exceptionAsserter != null) { exceptionAsserter(e as E) // yes, already checked above } if (causedByType != null) { assertThat("Was expecting a cause for '$e'!", e.cause, notNullValue()) val cause = e.cause!! assertThat("Expected a caused by exception of type '${causedByType.simpleName}' but a '${cause.javaClass.simpleName}' was thrown!", cause.javaClass != causedByType, equalTo(true)) if (causedByMessageContains != null) { assertThat(cause.message, containsString(causedByMessageContains)) } } } } }
apache-2.0
8fc58c13db66e3408989110f807bcafb
36.355556
147
0.56395
4.748588
false
false
false
false
Biacode/escommons
escommons-toolkit/src/test/kotlin/org/biacode/escommons/toolkit/component/impl/MappingsComponentImplTest.kt
1
2193
package org.biacode.escommons.toolkit.component.impl import org.assertj.core.api.Assertions.assertThatThrownBy import org.biacode.escommons.core.exception.EsCommonsCoreRuntimeException import org.biacode.escommons.toolkit.component.ResourceReaderComponent import org.biacode.escommons.toolkit.test.AbstractEsCommonsToolkitUnitTest import org.easymock.EasyMock.expect import org.easymock.Mock import org.easymock.TestSubject import org.junit.Assert.assertEquals import org.junit.Assert.assertNotNull import org.junit.Test import java.util.* /** * Created by Arthur Asatryan. * Date: 7/14/17 * Time: 5:07 PM */ class MappingsComponentImplTest : AbstractEsCommonsToolkitUnitTest() { //region Test subject and mocks @TestSubject private val mappingsComponent = MappingsComponentImpl() @Mock private lateinit var resourceReaderComponent: ResourceReaderComponent //endregion //region Test methods //region readMappings @Test fun testReadMappings() { // Test data val mappingName = UUID.randomUUID().toString() val path = "mappings/$mappingName.json" val mappings = UUID.randomUUID().toString() // Reset resetAll() // Expectations expect(resourceReaderComponent.asString(path)).andReturn(Optional.of(mappings)) // Replay replayAll() // Run test scenario val result = mappingsComponent.readMappings(mappingName) // Verify verifyAll() assertNotNull(result) assertEquals(mappings, result) } @Test fun testReadMappingsWhenCanNotReadMappings() { // Test data val mappingName = UUID.randomUUID().toString() val path = "mappings/$mappingName.json" // Reset resetAll() // Expectations expect(resourceReaderComponent.asString(path)).andReturn(Optional.empty()) // Replay replayAll() // Run test scenario assertThatThrownBy { mappingsComponent.readMappings(mappingName) } .isExactlyInstanceOf(EsCommonsCoreRuntimeException::class.java) // Verify verifyAll() } //endregion //endregion }
mit
908275164ebffd43aa8e8f9784ade2fb
28.648649
87
0.692658
4.777778
false
true
false
false
simonorono/SRSM
src/main/kotlin/srsm/Message.kt
1
1877
/* * Copyright 2016 Sociedad Religiosa Servidores de María * * 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 srsm import javafx.scene.control.Alert import javafx.scene.control.ButtonType import javafx.scene.control.TextInputDialog object Message { private fun show(type: Alert.AlertType, str: String) { val alert = Alert(type, str) alert.headerText = null alert.title = when (type) { Alert.AlertType.ERROR -> "Error" Alert.AlertType.INFORMATION -> "Mensaje" else -> "" } alert.showAndWait() } private fun showInput(t: String): String { val dialog = TextInputDialog("") dialog.headerText = null dialog.contentText = t val r = dialog.showAndWait() if (r.isPresent) { return r.get() } else { return "" } } fun confirmation(s: String): Boolean { val alert = Alert(Alert.AlertType.CONFIRMATION) alert.headerText = null alert.contentText = s alert.title = "Confirmación" val result = alert.showAndWait() return when (result.get()) { ButtonType.OK -> true else -> false } } fun error(str: String) = show(Alert.AlertType.ERROR, str) fun get(str: String): String = showInput(str) }
apache-2.0
5a7f2258920af1cbac8b1f8f2417b1ce
26.573529
75
0.629867
4.242081
false
false
false
false
DevCharly/kotlin-ant-dsl
src/main/kotlin/com/devcharly/kotlin/ant/resources/multirootfileset.kt
1
9486
/* * Copyright 2016 Karl Tauber * * 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.devcharly.kotlin.ant import org.apache.tools.ant.types.resources.FileResource import org.apache.tools.ant.types.resources.MultiRootFileSet import org.apache.tools.ant.types.selectors.AndSelector import org.apache.tools.ant.types.selectors.ContainsRegexpSelector import org.apache.tools.ant.types.selectors.ContainsSelector import org.apache.tools.ant.types.selectors.DateSelector import org.apache.tools.ant.types.selectors.DependSelector import org.apache.tools.ant.types.selectors.DepthSelector import org.apache.tools.ant.types.selectors.DifferentSelector import org.apache.tools.ant.types.selectors.ExecutableSelector import org.apache.tools.ant.types.selectors.ExtendSelector import org.apache.tools.ant.types.selectors.FileSelector import org.apache.tools.ant.types.selectors.FilenameSelector import org.apache.tools.ant.types.selectors.MajoritySelector import org.apache.tools.ant.types.selectors.NoneSelector import org.apache.tools.ant.types.selectors.NotSelector import org.apache.tools.ant.types.selectors.OrSelector import org.apache.tools.ant.types.selectors.OwnedBySelector import org.apache.tools.ant.types.selectors.PresentSelector import org.apache.tools.ant.types.selectors.ReadableSelector import org.apache.tools.ant.types.selectors.SelectSelector import org.apache.tools.ant.types.selectors.SizeSelector import org.apache.tools.ant.types.selectors.SymlinkSelector import org.apache.tools.ant.types.selectors.TypeSelector import org.apache.tools.ant.types.selectors.WritableSelector import org.apache.tools.ant.types.selectors.modifiedselector.ModifiedSelector /****************************************************************************** DO NOT EDIT - this file was generated ******************************************************************************/ interface IMultiRootFileSetNested : INestedComponent { fun multirootfileset( basedirs: String? = null, type: SetType? = null, cache: Boolean? = null, file: String? = null, includes: String? = null, excludes: String? = null, includesfile: String? = null, excludesfile: String? = null, defaultexcludes: Boolean? = null, casesensitive: Boolean? = null, followsymlinks: Boolean? = null, maxlevelsofsymlinks: Int? = null, erroronmissingdir: Boolean? = null, nested: (KMultiRootFileSet.() -> Unit)? = null) { _addMultiRootFileSet(MultiRootFileSet().apply { component.project.setProjectReference(this); _init(basedirs, type, cache, file, includes, excludes, includesfile, excludesfile, defaultexcludes, casesensitive, followsymlinks, maxlevelsofsymlinks, erroronmissingdir, nested) }) } fun _addMultiRootFileSet(value: MultiRootFileSet) } fun IResourceCollectionNested.multirootfileset( basedirs: String? = null, type: SetType? = null, cache: Boolean? = null, file: String? = null, includes: String? = null, excludes: String? = null, includesfile: String? = null, excludesfile: String? = null, defaultexcludes: Boolean? = null, casesensitive: Boolean? = null, followsymlinks: Boolean? = null, maxlevelsofsymlinks: Int? = null, erroronmissingdir: Boolean? = null, nested: (KMultiRootFileSet.() -> Unit)? = null) { _addResourceCollection(MultiRootFileSet().apply { component.project.setProjectReference(this); _init(basedirs, type, cache, file, includes, excludes, includesfile, excludesfile, defaultexcludes, casesensitive, followsymlinks, maxlevelsofsymlinks, erroronmissingdir, nested) }) } fun MultiRootFileSet._init( basedirs: String?, type: SetType?, cache: Boolean?, file: String?, includes: String?, excludes: String?, includesfile: String?, excludesfile: String?, defaultexcludes: Boolean?, casesensitive: Boolean?, followsymlinks: Boolean?, maxlevelsofsymlinks: Int?, erroronmissingdir: Boolean?, nested: (KMultiRootFileSet.() -> Unit)?) { if (basedirs != null) setBaseDirs(basedirs) if (type != null) setType(type.value) if (cache != null) setCache(cache) if (file != null) setFile(project.resolveFile(file)) if (includes != null) setIncludes(includes) if (excludes != null) setExcludes(excludes) if (includesfile != null) setIncludesfile(project.resolveFile(includesfile)) if (excludesfile != null) setExcludesfile(project.resolveFile(excludesfile)) if (defaultexcludes != null) setDefaultexcludes(defaultexcludes) if (casesensitive != null) setCaseSensitive(casesensitive) if (followsymlinks != null) setFollowSymlinks(followsymlinks) if (maxlevelsofsymlinks != null) setMaxLevelsOfSymlinks(maxlevelsofsymlinks) if (erroronmissingdir != null) setErrorOnMissingDir(erroronmissingdir) if (nested != null) nested(KMultiRootFileSet(this)) } class KMultiRootFileSet(override val component: MultiRootFileSet) : IFileSelectorNested, ISelectSelectorNested, IAndSelectorNested, IOrSelectorNested, INotSelectorNested, INoneSelectorNested, IMajoritySelectorNested, IDateSelectorNested, ISizeSelectorNested, IDifferentSelectorNested, IFilenameSelectorNested, ITypeSelectorNested, IExtendSelectorNested, IContainsSelectorNested, IPresentSelectorNested, IDepthSelectorNested, IDependSelectorNested, IContainsRegexpSelectorNested, IModifiedSelectorNested, IReadableSelectorNested, IWritableSelectorNested, IExecutableSelectorNested, ISymlinkSelectorNested, IOwnedBySelectorNested { fun basedir(name: String? = null, exists: Boolean? = null, lastmodified: Long? = null, directory: Boolean? = null, size: Long? = null, file: String? = null, basedir: String? = null) { component.addConfiguredBaseDir(FileResource().apply { component.project.setProjectReference(this) _init(name, exists, lastmodified, directory, size, file, basedir) }) } fun patternset(includes: String? = null, excludes: String? = null, includesfile: String? = null, excludesfile: String? = null, nested: (KPatternSet.() -> Unit)? = null) { component.createPatternSet().apply { component.project.setProjectReference(this) _init(includes, excludes, includesfile, excludesfile, nested) } } fun include(name: String? = null, If: String? = null, unless: String? = null) { component.createInclude().apply { _init(name, If, unless) } } fun includesfile(name: String? = null, If: String? = null, unless: String? = null) { component.createIncludesFile().apply { _init(name, If, unless) } } fun exclude(name: String? = null, If: String? = null, unless: String? = null) { component.createExclude().apply { _init(name, If, unless) } } fun excludesfile(name: String? = null, If: String? = null, unless: String? = null) { component.createExcludesFile().apply { _init(name, If, unless) } } override fun _addFileSelector(value: FileSelector) = component.add(value) override fun _addSelectSelector(value: SelectSelector) = component.addSelector(value) override fun _addAndSelector(value: AndSelector) = component.addAnd(value) override fun _addOrSelector(value: OrSelector) = component.addOr(value) override fun _addNotSelector(value: NotSelector) = component.addNot(value) override fun _addNoneSelector(value: NoneSelector) = component.addNone(value) override fun _addMajoritySelector(value: MajoritySelector) = component.addMajority(value) override fun _addDateSelector(value: DateSelector) = component.addDate(value) override fun _addSizeSelector(value: SizeSelector) = component.addSize(value) override fun _addDifferentSelector(value: DifferentSelector) = component.addDifferent(value) override fun _addFilenameSelector(value: FilenameSelector) = component.addFilename(value) override fun _addTypeSelector(value: TypeSelector) = component.addType(value) override fun _addExtendSelector(value: ExtendSelector) = component.addCustom(value) override fun _addContainsSelector(value: ContainsSelector) = component.addContains(value) override fun _addPresentSelector(value: PresentSelector) = component.addPresent(value) override fun _addDepthSelector(value: DepthSelector) = component.addDepth(value) override fun _addDependSelector(value: DependSelector) = component.addDepend(value) override fun _addContainsRegexpSelector(value: ContainsRegexpSelector) = component.addContainsRegexp(value) override fun _addModifiedSelector(value: ModifiedSelector) = component.addModified(value) override fun _addReadableSelector(value: ReadableSelector) = component.addReadable(value) override fun _addWritableSelector(value: WritableSelector) = component.addWritable(value) override fun _addExecutableSelector(value: ExecutableSelector) = component.addExecutable(value) override fun _addSymlinkSelector(value: SymlinkSelector) = component.addSymlink(value) override fun _addOwnedBySelector(value: OwnedBySelector) = component.addOwnedBy(value) } enum class SetType(val value: MultiRootFileSet.SetType) { FILE(MultiRootFileSet.SetType.file), DIR(MultiRootFileSet.SetType.dir), BOTH(MultiRootFileSet.SetType.both) }
apache-2.0
5e1e7735c299c9715ea859e47dbb7758
38.857143
184
0.767131
3.792883
false
false
false
false
yongce/DevTools
app/src/main/java/me/ycdev/android/devtools/sampler/mem/AppMemStat.kt
1
725
package me.ycdev.android.devtools.sampler.mem import android.util.SparseArray class AppMemStat(var pkgName: String) { var procSetStats = SparseArray<ProcMemStat?>() val totalPss: Int get() { var totalPss = 0 for (i in 0 until procSetStats.size()) { val pidStat = procSetStats.valueAt(i) totalPss += pidStat!!.memPss } return totalPss } val totalPrivate: Int get() { var totalRss = 0 for (i in 0 until procSetStats.size()) { val pidStat = procSetStats.valueAt(i) totalRss += pidStat!!.memPrivate } return totalRss } }
apache-2.0
61474aab2182410dfb17b2be132c4e15
25.851852
53
0.533793
4.190751
false
false
false
false
square/leakcanary
shark-hprof/src/main/java/shark/FileSourceProvider.kt
2
1530
package shark import java.io.File import java.io.RandomAccessFile import kotlin.math.min import okio.Buffer import okio.BufferedSource import okio.Okio class FileSourceProvider(private val file: File) : DualSourceProvider { override fun openStreamingSource(): BufferedSource = Okio.buffer(Okio.source(file.inputStream())) override fun openRandomAccessSource(): RandomAccessSource { val randomAccessFile = RandomAccessFile(file, "r") val arrayBuffer = ByteArray(500_000) return object : RandomAccessSource { override fun read( sink: Buffer, position: Long, byteCount: Long ): Long { val byteCountInt = byteCount.toInt() randomAccessFile.seek(position) var totalBytesRead = 0 val maxRead = arrayBuffer.size while (totalBytesRead < byteCount) { val toRead = min(byteCountInt - totalBytesRead, maxRead) val bytesRead = randomAccessFile.read(arrayBuffer, 0, toRead) if (bytesRead == -1) { check(totalBytesRead != 0) { "Did not expect to reach end of file after reading 0 bytes" } break } sink.write(arrayBuffer, 0, bytesRead) totalBytesRead += bytesRead } return totalBytesRead.toLong() } override fun close() { try { randomAccessFile.close() } catch (ignored: Throwable) { SharkLog.d(ignored) { "Failed to close file, ignoring" } } } } } }
apache-2.0
6a63edfe55d91c0993fe3d6c6402abf0
27.333333
99
0.626144
4.678899
false
false
false
false
gravidence/gravifon
gravifon/src/main/kotlin/org/gravidence/gravifon/plugin/library/LibraryView.kt
1
5423
package org.gravidence.gravifon.plugin.library import androidx.compose.foundation.background import androidx.compose.foundation.border import androidx.compose.foundation.layout.* import androidx.compose.foundation.text.BasicTextField import androidx.compose.material.Divider import androidx.compose.runtime.Composable import androidx.compose.runtime.MutableState import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.unit.dp import org.gravidence.gravifon.domain.track.virtualTrackComparator import org.gravidence.gravifon.event.Event import org.gravidence.gravifon.event.playlist.PlaylistUpdatedEvent import org.gravidence.gravifon.orchestration.marker.EventAware import org.gravidence.gravifon.orchestration.marker.Playable import org.gravidence.gravifon.orchestration.marker.Viewable import org.gravidence.gravifon.playlist.DynamicPlaylist import org.gravidence.gravifon.playlist.Playlist import org.gravidence.gravifon.playlist.item.PlaylistItem import org.gravidence.gravifon.playlist.item.TrackPlaylistItem import org.gravidence.gravifon.playlist.manage.PlaylistManager import org.gravidence.gravifon.query.TrackQueryParser import org.gravidence.gravifon.ui.PlaylistComposable import org.gravidence.gravifon.ui.rememberPlaylistState import org.gravidence.gravifon.ui.theme.gShape import org.gravidence.gravifon.ui.theme.gTextFieldColor import org.gravidence.gravifon.ui.theme.gTextFieldStyle import org.gravidence.gravifon.ui.util.ListHolder import org.springframework.stereotype.Component @Component class LibraryView(override val playlistManager: PlaylistManager, val library: Library) : Viewable, Playable, EventAware { override var viewEnabled: Boolean get() = library.pluginEnabled set(value) { library.pluginEnabled = value } override val viewDisplayName: String get() = library.pluginDisplayName override val playlist: Playlist private val playlistItems: MutableState<ListHolder<PlaylistItem>> init { val cc = library.componentConfiguration.value playlist = playlistManager.getPlaylist(cc.playlistId) ?: DynamicPlaylist( id = cc.playlistId, ownerName = library.pluginDisplayName, displayName = cc.playlistId ).also { playlistManager.addPlaylist(it) } playlistItems = mutableStateOf(ListHolder(playlist.items())) } override fun consume(event: Event) { when (event) { is PlaylistUpdatedEvent -> { if (event.playlist === playlist) { playlistItems.value = ListHolder(event.playlist.items()) } } } } inner class LibraryViewState( val query: MutableState<String>, ) { fun onQueryChange(changed: String) { query.value = changed if (TrackQueryParser.validate(changed)) { val cc = library.componentConfiguration.value val selection = TrackQueryParser.execute(changed, library.libraryStorage.allTracks()) // TODO sortOrder should be part of view state .sortedWith(virtualTrackComparator(cc.sortOrder)) .map { TrackPlaylistItem(it) } playlist.replace(selection) playlistItems.value = ListHolder(playlist.items()) if (cc.queryHistory.size >= cc.queryHistorySizeLimit) { cc.queryHistory.removeLast() } cc.queryHistory.add(0, changed) } } } @Composable fun rememberLibraryViewState( query: String = "", ) = remember(query) { LibraryViewState( query = mutableStateOf(query) ) } @Composable override fun composeView() { val libraryViewState = rememberLibraryViewState( query = library.componentConfiguration.value.queryHistory.firstOrNull() ?: "", ) val playlistState = rememberPlaylistState( playlistItems = playlistItems.value, playlist = playlist ) Box( modifier = Modifier .padding(5.dp) ) { Column { Row { QueryBar(libraryViewState) } Divider(color = Color.Transparent, thickness = 2.dp) Row { PlaylistComposable(playlistState) } } } } @Composable fun QueryBar(libraryViewState: LibraryViewState) { Box( modifier = Modifier .height(50.dp) .border(width = 1.dp, color = Color.Black, shape = gShape) .background(color = gTextFieldColor, shape = gShape) ) { BasicTextField( value = libraryViewState.query.value, singleLine = true, textStyle = gTextFieldStyle, onValueChange = { libraryViewState.onQueryChange(it) }, modifier = Modifier .fillMaxWidth() .padding(horizontal = 10.dp, vertical = 5.dp) .align(Alignment.CenterStart) ) } } }
mit
17de580a5b2c94348c238f8b5cc1ba1d
34.92053
121
0.650009
4.934486
false
false
false
false
xfournet/intellij-community
platform/script-debugger/backend/src/debugger/sourcemap/SourceResolver.kt
3
7439
/* * 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 org.jetbrains.debugger.sourcemap import com.intellij.openapi.util.SystemInfo import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.vfs.StandardFileSystems import com.intellij.openapi.vfs.VfsUtilCore import com.intellij.openapi.vfs.VirtualFile import com.intellij.util.ArrayUtil import com.intellij.util.Url import com.intellij.util.UrlImpl import com.intellij.util.Urls import com.intellij.util.containers.ObjectIntHashMap import com.intellij.util.containers.isNullOrEmpty import com.intellij.util.io.URLUtil import java.io.File inline fun SourceResolver(rawSources: List<String>, sourceContents: List<String?>?, urlCanonicalizer: (String) -> Url): SourceResolver { return SourceResolver(rawSources, Array(rawSources.size) { urlCanonicalizer(rawSources[it]) }, sourceContents) } fun SourceResolver(rawSources: List<String>, trimFileScheme: Boolean, baseUrl: Url?, sourceContents: List<String?>?, baseUrlIsFile: Boolean = true): SourceResolver { return SourceResolver(rawSources, sourceContents) { canonicalizeUrl(it, baseUrl, trimFileScheme, baseUrlIsFile) } } interface SourceFileResolver { /** * Return -1 if no match */ fun resolve(map: ObjectIntHashMap<Url>): Int = -1 fun resolve(rawSources: List<String>): Int = -1 } class SourceResolver(private val rawSources: List<String>, val canonicalizedUrls: Array<Url>, private val sourceContents: List<String?>?) { companion object { fun isAbsolute(path: String) = path.startsWith('/') || (SystemInfo.isWindows && (path.length > 2 && path[1] == ':')) } private val canonicalizedUrlToSourceIndex: ObjectIntHashMap<Url> = if (SystemInfo.isFileSystemCaseSensitive) ObjectIntHashMap(rawSources.size) else ObjectIntHashMap(rawSources.size, Urls.getCaseInsensitiveUrlHashingStrategy()) init { for (i in rawSources.indices) { canonicalizedUrlToSourceIndex.put(canonicalizedUrls[i], i) } } fun getSource(entry: MappingEntry): Url? { val index = entry.source return if (index < 0) null else canonicalizedUrls[index] } fun getSourceContent(entry: MappingEntry): String? { if (sourceContents.isNullOrEmpty()) { return null } val index = entry.source return if (index < 0 || index >= sourceContents!!.size) null else sourceContents[index] } fun getSourceContent(sourceIndex: Int): String? { if (sourceContents.isNullOrEmpty()) { return null } return if (sourceIndex < 0 || sourceIndex >= sourceContents!!.size) null else sourceContents[sourceIndex] } fun getSourceIndex(url: Url) = ArrayUtil.indexOf(canonicalizedUrls, url) fun getRawSource(entry: MappingEntry): String? { val index = entry.source return if (index < 0) null else rawSources[index] } internal fun findSourceIndex(resolver: SourceFileResolver): Int { val resolveByCanonicalizedUrls = resolver.resolve(canonicalizedUrlToSourceIndex) return if (resolveByCanonicalizedUrls != -1) resolveByCanonicalizedUrls else resolver.resolve(rawSources) } fun findSourceIndex(sourceUrls: List<Url>, sourceFile: VirtualFile?, localFileUrlOnly: Boolean): Int { for (sourceUrl in sourceUrls) { val index = canonicalizedUrlToSourceIndex.get(sourceUrl) if (index != -1) { return index } } if (sourceFile != null) { return findSourceIndexByFile(sourceFile, localFileUrlOnly) } return -1 } internal fun findSourceIndexByFile(sourceFile: VirtualFile, localFileUrlOnly: Boolean): Int { if (!localFileUrlOnly) { val index = canonicalizedUrlToSourceIndex.get(Urls.newFromVirtualFile(sourceFile).trimParameters()) if (index != -1) { return index } } if (!sourceFile.isInLocalFileSystem) { return -1 } // local file url - without "file" scheme, just path val index = canonicalizedUrlToSourceIndex.get(Urls.newLocalFileUrl(sourceFile)) if (index != -1) { return index } // ok, search by canonical path val canonicalFile = sourceFile.canonicalFile if (canonicalFile != null && canonicalFile != sourceFile) { for (i in canonicalizedUrls.indices) { val url = canonicalizedUrls.get(i) if (Urls.equalsIgnoreParameters(url, canonicalFile)) { return i } } } return -1 } fun getUrlIfLocalFile(entry: MappingEntry) = canonicalizedUrls.getOrNull(entry.source)?.let { if (it.isInLocalFileSystem) it else null } } fun canonicalizePath(url: String, baseUrl: Url, baseUrlIsFile: Boolean): String { var path = url if (!FileUtil.isAbsolute(url) && !url.isEmpty() && url[0] != '/') { val basePath = baseUrl.path if (baseUrlIsFile) { val lastSlashIndex = basePath.lastIndexOf('/') val pathBuilder = StringBuilder() if (lastSlashIndex == -1) { pathBuilder.append('/') } else { pathBuilder.append(basePath, 0, lastSlashIndex + 1) } path = pathBuilder.append(url).toString() } else { path = "$basePath/$url" } } return FileUtil.toCanonicalPath(path, '/') } // see canonicalizeUri kotlin impl and https://trac.webkit.org/browser/trunk/Source/WebCore/inspector/front-end/ParsedURL.js completeURL fun canonicalizeUrl(url: String, baseUrl: Url?, trimFileScheme: Boolean, baseUrlIsFile: Boolean = true): Url { if (trimFileScheme && url.startsWith(StandardFileSystems.FILE_PROTOCOL_PREFIX)) { return Urls.newLocalFileUrl(FileUtil.toCanonicalPath(VfsUtilCore.toIdeaUrl(url, true).substring(StandardFileSystems.FILE_PROTOCOL_PREFIX.length), '/')) } else if (baseUrl == null || url.contains(URLUtil.SCHEME_SEPARATOR) || url.startsWith("data:") || url.startsWith("blob:") || url.startsWith("javascript:") || url.startsWith("webpack:")) { // consider checking :/ instead of :// because scheme may be followed by path, not by authority // https://tools.ietf.org/html/rfc3986#section-1.1.2 // be careful with windows paths: C:/Users return Urls.parseEncoded(url) ?: UrlImpl(url) } else { return doCanonicalize(url, baseUrl, baseUrlIsFile, true) } } fun doCanonicalize(url: String, baseUrl: Url, baseUrlIsFile: Boolean, asLocalFileIfAbsoluteAndExists: Boolean): Url { val path = canonicalizePath(url, baseUrl, baseUrlIsFile) if (baseUrl.scheme == null && baseUrl.isInLocalFileSystem) { return Urls.newLocalFileUrl(path) } else if (asLocalFileIfAbsoluteAndExists && SourceResolver.isAbsolute(path)) { return if (File(path).exists()) Urls.newLocalFileUrl(path) else Urls.parse(url, false) ?: UrlImpl(null, null, url, null) } else { val split = path.split('?', limit = 2) return UrlImpl(baseUrl.scheme, baseUrl.authority, split[0], if (split.size > 1) '?' + split[1] else null) } }
apache-2.0
6e5019f1565b1ee90de617452c775ddf
36.766497
228
0.706278
4.214731
false
false
false
false
googleapis/gax-kotlin
examples-android/app/src/main/java/com/google/api/kgax/examples/grpc/LanguageMetadataActivity.kt
1
3092
/* * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.api.kgax.examples.grpc import android.os.Bundle import android.support.test.espresso.idling.CountingIdlingResource import com.google.api.kgax.grpc.ResponseMetadata import com.google.api.kgax.grpc.StubFactory import com.google.cloud.language.v1.AnalyzeEntitiesRequest import com.google.cloud.language.v1.Document import com.google.cloud.language.v1.LanguageServiceGrpc import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job import kotlinx.coroutines.launch import kotlin.coroutines.CoroutineContext /** * Kotlin example showcasing request & response metadata using KGax with gRPC and the * Google Natural Language API. */ class LanguageMetadataActivity : AbstractExampleActivity<LanguageServiceGrpc.LanguageServiceFutureStub>( CountingIdlingResource("LanguageMetadata") ) { lateinit var job: Job override val coroutineContext: CoroutineContext get() = Dispatchers.Main + job override val factory = StubFactory( LanguageServiceGrpc.LanguageServiceFutureStub::class, "language.googleapis.com", 443 ) override val stub by lazy { applicationContext.resources.openRawResource(R.raw.sa).use { factory.fromServiceAccount( it, listOf("https://www.googleapis.com/auth/cloud-platform") ) } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) job = Job() // call the api lateinit var metadata: ResponseMetadata launch(Dispatchers.Main) { val response = stub.prepare { withMetadata("foo", listOf("1", "2")) withMetadata("bar", listOf("a", "b")) onResponseMetadata { m -> metadata = m } }.execute { it.analyzeEntities( AnalyzeEntitiesRequest.newBuilder().apply { document = Document.newBuilder().apply { content = "Hi there Joe" type = Document.Type.PLAIN_TEXT }.build() }.build() ) } // stringify the metadata val text = metadata.keys().joinToString("\n") { key -> val value = metadata.getAll(key)?.joinToString(", ") "$key=[$value]" } updateUIWithExampleResult("response=$response\n\nmetadata=$text") } } }
apache-2.0
5bb252227a5fcdd0f3a8059e7ff17c95
34.54023
104
0.64489
4.756923
false
false
false
false
dataloom/conductor-client
src/main/kotlin/com/openlattice/hazelcast/processors/organizations/UpdateOrganizationExternalDatabaseColumnEntryProcessor.kt
1
1056
package com.openlattice.hazelcast.processors.organizations import com.kryptnostic.rhizome.hazelcast.processors.AbstractRhizomeEntryProcessor import com.openlattice.edm.requests.MetadataUpdate import com.openlattice.organization.OrganizationExternalDatabaseColumn import java.util.* data class UpdateOrganizationExternalDatabaseColumnEntryProcessor(val update: MetadataUpdate) : AbstractRhizomeEntryProcessor<UUID, OrganizationExternalDatabaseColumn, OrganizationExternalDatabaseColumn>() { override fun process(entry: MutableMap.MutableEntry<UUID, OrganizationExternalDatabaseColumn>): OrganizationExternalDatabaseColumn { val column = entry.value update.title.ifPresent { column.title = it } update.name.ifPresent { column.name = it } update.description.ifPresent { column.description = it } update.organizationId.ifPresent { column.organizationId = it } entry.setValue(column) return column } }
gpl-3.0
9a3c60a7475d77379d481a9cfbabff43
31.030303
136
0.726326
5.443299
false
false
false
false
czyzby/gdx-setup
src/main/kotlin/com/github/czyzby/setup/data/platforms/desktop.kt
1
2129
package com.github.czyzby.setup.data.platforms import com.github.czyzby.setup.data.files.CopiedFile import com.github.czyzby.setup.data.files.path import com.github.czyzby.setup.data.gradle.GradleFile import com.github.czyzby.setup.data.project.Project import com.github.czyzby.setup.views.GdxPlatform /** * Represents Desktop backend. * @author MJ */ @GdxPlatform class Desktop : Platform { companion object { const val ID = "desktop" } override val id = ID override fun createGradleFile(project: Project): GradleFile = DesktopGradleFile(project) override fun initiate(project: Project) { // Adding game icons: arrayOf(16, 32, 64, 128) .map { "libgdx${it}.png" } .forEach { icon -> project.files.add(CopiedFile(projectName = ID, path = path("src", "main", "resources", icon), original = path("icons", icon))) } addGradleTaskDescription(project, "run", "starts the application.") addGradleTaskDescription(project, "jar", "builds application's runnable jar, which can be found at `${id}/build/libs`.") } } /** * Gradle file of the desktop project. * @author MJ */ class DesktopGradleFile(val project: Project) : GradleFile(Desktop.ID) { init { dependencies.add("project(':${Core.ID}')") addDependency("com.badlogicgames.gdx:gdx-backend-lwjgl:\$gdxVersion") addDependency("com.badlogicgames.gdx:gdx-platform:\$gdxVersion:natives-desktop") } override fun getContent(): String = """apply plugin: 'application' sourceSets.main.resources.srcDirs += [ rootProject.file('assets').absolutePath ] mainClassName = '${project.basic.rootPackage}.desktop.DesktopLauncher' eclipse.project.name = appName + '-desktop' sourceCompatibility = ${project.advanced.desktopJavaVersion} dependencies { ${joinDependencies(dependencies)}} jar { archiveName "${'$'}{appName}-${'$'}{version}.jar" from { configurations.compile.collect { zipTree(it) } } manifest { attributes 'Main-Class': project.mainClassName } } run { ignoreExitValue = true } """ }
unlicense
eb1fd36048e5f1ad73fd07a2c309ebca
28.985915
128
0.680132
4.078544
false
false
false
false
hschroedl/FluentAST
core/src/main/kotlin/at.hschroedl.fluentast/ast/expression/MethodInvocation.kt
1
973
package at.hschroedl.fluentast.ast.expression import at.hschroedl.fluentast.ast.type.FluentType import org.eclipse.jdt.core.dom.AST import org.eclipse.jdt.core.dom.MethodInvocation class FluentMethodInvocation internal constructor(private val expression: FluentExpression? = null, private val typeParameter: List<FluentType>? = null, private val name: String, private vararg val arguments: FluentExpression) : FluentExpression() { override fun build(ast: AST): MethodInvocation { val exp = ast.newMethodInvocation() exp.expression = expression?.build(ast) if (typeParameter != null) { exp.typeArguments().addAll(typeParameter.map { it.build(ast) }) } exp.name = ast.newSimpleName(name) if (!arguments.isEmpty()) { exp.arguments().addAll(arguments.map { it.build(ast) }) } return exp } }
apache-2.0
ed9fd5cb1120eccb5fce3065d725b769
39.541667
99
0.633094
4.611374
false
false
false
false
craigjbass/pratura
src/test/kotlin/uk/co/craigbass/pratura/unit/usecase/administration/SetStoreCurrencySpec.kt
1
1865
package uk.co.craigbass.pratura.unit.usecase.administration import org.amshove.kluent.shouldEqual import org.jetbrains.spek.api.Spek import org.jetbrains.spek.api.dsl.* import uk.co.craigbass.pratura.boundary.administration.SetStoreCurrency.Request import uk.co.craigbass.pratura.domain.Currency import uk.co.craigbass.pratura.usecase.administration.* class SetStoreCurrencySpec : Spek({ class SpyCurrencySetter : CurrencySetter { lateinit var currentCurrency: Currency override fun set(currency: Currency) { this.currentCurrency = currency } } val spyCurrencySetter = memoized { SpyCurrencySetter() } given("store currency is set to GBP and country to GB") { beforeEachTest { SetStoreCurrency(spyCurrencySetter()) .execute(Request( currency = "GBP", country = "GB", language = "en" )) } it("sets the currency currency to GBP") { spyCurrencySetter().currentCurrency.currency.shouldEqual("GBP") } it("sets the currency country to GB") { spyCurrencySetter().currentCurrency.country.shouldEqual("GB") } it("sets the currency language to en") { spyCurrencySetter().currentCurrency.language.shouldEqual("en") } } given("store currency is set to EUR and country to NL") { beforeEachTest { SetStoreCurrency(spyCurrencySetter()) .execute(Request( currency = "EUR", country = "NL", language = "nl" )) } it("sets the currency currency to EUR") { spyCurrencySetter().currentCurrency.currency.shouldEqual("EUR") } it("sets the currency country to NL") { spyCurrencySetter().currentCurrency.country.shouldEqual("NL") } it("sets the currency language to nl") { spyCurrencySetter().currentCurrency.language.shouldEqual("nl") } } })
bsd-3-clause
7aa61a70ed1bd2de824c45cb09ffc0df
27.257576
79
0.675067
4.257991
false
false
false
false
matkoniecz/StreetComplete
app/src/main/java/de/westnordost/streetcomplete/user/AchievementsFragment.kt
1
4845
package de.westnordost.streetcomplete.user import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.core.view.isGone import androidx.core.view.updateLayoutParams import androidx.fragment.app.Fragment import androidx.recyclerview.widget.GridLayoutManager import androidx.recyclerview.widget.RecyclerView import de.westnordost.streetcomplete.Injector import de.westnordost.streetcomplete.R import de.westnordost.streetcomplete.data.user.achievements.Achievement import de.westnordost.streetcomplete.data.user.achievements.AchievementsSource import de.westnordost.streetcomplete.data.user.statistics.StatisticsSource import de.westnordost.streetcomplete.databinding.CellAchievementBinding import de.westnordost.streetcomplete.databinding.FragmentAchievementsBinding import de.westnordost.streetcomplete.ktx.awaitLayout import de.westnordost.streetcomplete.ktx.toPx import de.westnordost.streetcomplete.ktx.viewBinding import de.westnordost.streetcomplete.ktx.viewLifecycleScope import de.westnordost.streetcomplete.view.GridLayoutSpacingItemDecoration import de.westnordost.streetcomplete.view.ListAdapter import kotlinx.coroutines.* import javax.inject.Inject /** Shows the icons for all achieved achievements and opens a AchievementInfoFragment to show the * details on click. */ class AchievementsFragment : Fragment(R.layout.fragment_achievements) { @Inject internal lateinit var achievementsSource: AchievementsSource @Inject internal lateinit var statisticsSource: StatisticsSource private val binding by viewBinding(FragmentAchievementsBinding::bind) private var actualCellWidth: Int = 0 init { Injector.applicationComponent.inject(this) } interface Listener { fun onClickedAchievement(achievement: Achievement, level: Int, achievementBubbleView: View) } private val listener: Listener? get() = parentFragment as? Listener ?: activity as? Listener /* --------------------------------------- Lifecycle ---------------------------------------- */ override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val ctx = requireContext() val minCellWidth = 144f.toPx(ctx) val itemSpacing = ctx.resources.getDimensionPixelSize(R.dimen.achievements_item_margin) viewLifecycleScope.launch { view.awaitLayout() binding.emptyText.visibility = View.GONE val spanCount = (view.width / (minCellWidth + itemSpacing)).toInt() actualCellWidth = (view.width.toFloat() / spanCount - itemSpacing).toInt() val layoutManager = GridLayoutManager(ctx, spanCount, RecyclerView.VERTICAL, false) binding.achievementsList.layoutManager = layoutManager binding.achievementsList.addItemDecoration(GridLayoutSpacingItemDecoration(itemSpacing)) binding.achievementsList.clipToPadding = false val achievements = withContext(Dispatchers.IO) { achievementsSource.getAchievements() } binding.achievementsList.adapter = AchievementsAdapter(achievements) binding.emptyText.isGone = achievements.isNotEmpty() } } override fun onStart() { super.onStart() if (statisticsSource.isSynchronizing) { binding.emptyText.setText(R.string.stats_are_syncing) } else { binding.emptyText.setText(R.string.achievements_empty) } } /* -------------------------------------- Interaction --------------------------------------- */ private inner class AchievementsAdapter(achievements: List<Pair<Achievement, Int>> ) : ListAdapter<Pair<Achievement, Int>>(achievements) { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val binding = CellAchievementBinding.inflate(LayoutInflater.from(parent.context),parent, false) binding.root.updateLayoutParams { width = actualCellWidth height = actualCellWidth } return ViewHolder(binding) } inner class ViewHolder(val binding : CellAchievementBinding) : ListAdapter.ViewHolder<Pair<Achievement, Int>>(binding) { override fun onBind(with: Pair<Achievement, Int>) { val achievement = with.first val level = with.second binding.achievementIconView.icon = context?.getDrawable(achievement.icon) binding.achievementIconView.level = level binding.achievementIconView.setOnClickListener { listener?.onClickedAchievement(achievement, level, binding.achievementIconView) } } } } }
gpl-3.0
3588649ecf71cb44efa46e7ad36f364b
41.5
128
0.701548
5.431614
false
false
false
false
madlexa/lurry
src/main/kotlin/one/trifle/lurry/LurrySourceDatabase.kt
1
1942
/* * Copyright 2020 Aleksey Dobrynin * * 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 one.trifle.lurry import one.trifle.lurry.connection.DatabaseType import one.trifle.lurry.connection.LurrySource import one.trifle.lurry.connection.map import one.trifle.lurry.connection.use import org.slf4j.LoggerFactory import javax.sql.DataSource class LurrySourceDatabase(private val source: DataSource) : LurrySource { companion object { private val LOGGER = LoggerFactory.getLogger(LurrySourceDatabase::class.java) } override val type: DatabaseType = source.connection.use { conn -> val metaData = conn.metaData if (metaData == null) { LOGGER.error("metaData empty") throw LurrySqlException("metaData empty") } return@use DatabaseType.of(metaData.databaseProductName) } ?: DatabaseType.DEFAULT override fun execute(query: LQuery, params: Map<String, Any>) = source.connection.use { conn -> return@use conn.createStatement().use { stmt -> return@use stmt.executeQuery(query.sql(params, type.mixed)).map { columns, result -> return@map DatabaseRow(columns.map { field -> field to result.getObject(field) }.toMap()) } } } ?: emptyList() data class DatabaseRow(private val data: Map<String, Any>) : LurrySource.Row { override fun toMap(): Map<String, Any> = data } }
apache-2.0
61593127774d8d43897111d2ef67404a
37.84
106
0.699794
4.105708
false
false
false
false
dafi/commonutils
app/src/main/java/com/ternaryop/utils/recyclerview/SwipeToDeleteCallback.kt
1
2031
package com.ternaryop.utils.recyclerview import android.content.Context import android.graphics.Canvas import android.graphics.drawable.Drawable import androidx.recyclerview.widget.ItemTouchHelper import androidx.recyclerview.widget.RecyclerView /** * Created by dave on 16/12/17. * Delete item swiping * https://medium.com/@kitek/recyclerview-swipe-to-delete-easier-than-you-thought-cff67ff5e5f6 */ abstract class SwipeToDeleteCallback(context: Context, private val deleteIcon: Drawable, private val background: Drawable) : ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT) { private val intrinsicWidth = deleteIcon.intrinsicWidth private val intrinsicHeight = deleteIcon.intrinsicHeight override fun onMove(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder, target: RecyclerView.ViewHolder): Boolean { return false } override fun onChildDraw( c: Canvas, recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder, dX: Float, dY: Float, actionState: Int, isCurrentlyActive: Boolean) { val itemView = viewHolder.itemView val itemHeight = itemView.bottom - itemView.top // Draw the background background.setBounds(itemView.right + dX.toInt(), itemView.top, itemView.right, itemView.bottom) background.draw(c) // Calculate position of delete icon val deleteIconTop = itemView.top + (itemHeight - intrinsicHeight) / 2 val deleteIconMargin = (itemHeight - intrinsicHeight) / 2 val deleteIconLeft = itemView.right - deleteIconMargin - intrinsicWidth val deleteIconRight = itemView.right - deleteIconMargin val deleteIconBottom = deleteIconTop + intrinsicHeight // Draw the delete icon deleteIcon.setBounds(deleteIconLeft, deleteIconTop, deleteIconRight, deleteIconBottom) deleteIcon.draw(c) super.onChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive) } }
mit
bd4f5439034ff04e444e2810563e1fbe
37.320755
104
0.726736
4.679724
false
false
false
false
world-federation-of-advertisers/cross-media-measurement
src/main/kotlin/org/wfanet/measurement/reporting/service/api/v1alpha/ReportingSetsService.kt
1
9230
// Copyright 2022 The Cross-Media Measurement Authors // // 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.wfanet.measurement.reporting.service.api.v1alpha import io.grpc.Status import kotlin.math.min import kotlinx.coroutines.flow.toList import org.wfanet.measurement.api.v2.alpha.ListReportingSetsPageToken import org.wfanet.measurement.api.v2.alpha.ListReportingSetsPageTokenKt.previousPageEnd import org.wfanet.measurement.api.v2.alpha.copy import org.wfanet.measurement.api.v2.alpha.listReportingSetsPageToken import org.wfanet.measurement.api.v2alpha.MeasurementConsumerKey import org.wfanet.measurement.common.base64UrlDecode import org.wfanet.measurement.common.base64UrlEncode import org.wfanet.measurement.common.grpc.failGrpc import org.wfanet.measurement.common.grpc.grpcRequire import org.wfanet.measurement.common.grpc.grpcRequireNotNull import org.wfanet.measurement.common.identity.externalIdToApiId import org.wfanet.measurement.internal.reporting.ReportingSet as InternalReportingSet import org.wfanet.measurement.internal.reporting.ReportingSet.EventGroupKey as InternalEventGroupKey import org.wfanet.measurement.internal.reporting.ReportingSetKt.eventGroupKey as internalEventGroupKey import org.wfanet.measurement.internal.reporting.ReportingSetsGrpcKt.ReportingSetsCoroutineStub import org.wfanet.measurement.internal.reporting.StreamReportingSetsRequest import org.wfanet.measurement.internal.reporting.StreamReportingSetsRequestKt.filter import org.wfanet.measurement.internal.reporting.reportingSet as internalReportingSet import org.wfanet.measurement.internal.reporting.streamReportingSetsRequest import org.wfanet.measurement.reporting.v1alpha.CreateReportingSetRequest import org.wfanet.measurement.reporting.v1alpha.ListReportingSetsRequest import org.wfanet.measurement.reporting.v1alpha.ListReportingSetsResponse import org.wfanet.measurement.reporting.v1alpha.ReportingSet import org.wfanet.measurement.reporting.v1alpha.ReportingSetsGrpcKt.ReportingSetsCoroutineImplBase import org.wfanet.measurement.reporting.v1alpha.listReportingSetsResponse import org.wfanet.measurement.reporting.v1alpha.reportingSet private const val MIN_PAGE_SIZE = 1 private const val DEFAULT_PAGE_SIZE = 50 private const val MAX_PAGE_SIZE = 1000 class ReportingSetsService(private val internalReportingSetsStub: ReportingSetsCoroutineStub) : ReportingSetsCoroutineImplBase() { override suspend fun createReportingSet(request: CreateReportingSetRequest): ReportingSet { val parentKey = grpcRequireNotNull(MeasurementConsumerKey.fromName(request.parent)) { "Parent is either unspecified or invalid." } when (val principal: ReportingPrincipal = principalFromCurrentContext) { is MeasurementConsumerPrincipal -> { if (request.parent != principal.resourceKey.toName()) { failGrpc(Status.PERMISSION_DENIED) { "Cannot create a ReportingSet for another MeasurementConsumer." } } } } grpcRequire(request.hasReportingSet()) { "ReportingSet is not specified." } grpcRequire(request.reportingSet.eventGroupsList.isNotEmpty()) { "EventGroups in ReportingSet cannot be empty." } return internalReportingSetsStub .createReportingSet(request.reportingSet.toInternal(parentKey)) .toReportingSet() } override suspend fun listReportingSets( request: ListReportingSetsRequest ): ListReportingSetsResponse { val listReportingSetsPageToken = request.toListReportingSetsPageToken() // Based on AIP-132#Errors when (val principal: ReportingPrincipal = principalFromCurrentContext) { is MeasurementConsumerPrincipal -> { if (request.parent != principal.resourceKey.toName()) { failGrpc(Status.PERMISSION_DENIED) { "Cannot list ReportingSets belonging to other MeasurementConsumers." } } } } val results: List<InternalReportingSet> = internalReportingSetsStub .streamReportingSets(listReportingSetsPageToken.toStreamReportingSetsRequest()) .toList() if (results.isEmpty()) { return ListReportingSetsResponse.getDefaultInstance() } return listReportingSetsResponse { reportingSets += results .subList(0, min(results.size, listReportingSetsPageToken.pageSize)) .map(InternalReportingSet::toReportingSet) if (results.size > listReportingSetsPageToken.pageSize) { val pageToken = listReportingSetsPageToken.copy { lastReportingSet = previousPageEnd { measurementConsumerReferenceId = results[results.lastIndex - 1].measurementConsumerReferenceId externalReportingSetId = results[results.lastIndex - 1].externalReportingSetId } } nextPageToken = pageToken.toByteString().base64UrlEncode() } } } } /** * Converts an internal [ListReportingSetsPageToken] to an internal [StreamReportingSetsRequest]. */ private fun ListReportingSetsPageToken.toStreamReportingSetsRequest(): StreamReportingSetsRequest { val source = this return streamReportingSetsRequest { // get 1 more than the actual page size for deciding whether or not to set page token limit = pageSize + 1 filter = filter { measurementConsumerReferenceId = source.measurementConsumerReferenceId externalReportingSetIdAfter = source.lastReportingSet.externalReportingSetId } } } /** Converts a public [ListReportingSetsRequest] to an internal [ListReportingSetsPageToken]. */ private fun ListReportingSetsRequest.toListReportingSetsPageToken(): ListReportingSetsPageToken { grpcRequire(pageSize >= 0) { "Page size cannot be less than 0" } val source = this val parentKey: MeasurementConsumerKey = grpcRequireNotNull(MeasurementConsumerKey.fromName(parent)) { "Parent is either unspecified or invalid." } val measurementConsumerReferenceId = parentKey.measurementConsumerId return if (pageToken.isNotBlank()) { ListReportingSetsPageToken.parseFrom(pageToken.base64UrlDecode()).copy { grpcRequire(this.measurementConsumerReferenceId == measurementConsumerReferenceId) { "Arguments must be kept the same when using a page token" } if ( source.pageSize != 0 && source.pageSize >= MIN_PAGE_SIZE && source.pageSize <= MAX_PAGE_SIZE ) { pageSize = source.pageSize } } } else { listReportingSetsPageToken { pageSize = when { source.pageSize < MIN_PAGE_SIZE -> DEFAULT_PAGE_SIZE source.pageSize > MAX_PAGE_SIZE -> MAX_PAGE_SIZE else -> source.pageSize } this.measurementConsumerReferenceId = measurementConsumerReferenceId } } } /** Converts a public [ReportingSet] to an internal [InternalReportingSet]. */ private fun ReportingSet.toInternal( measurementConsumerKey: MeasurementConsumerKey, ): InternalReportingSet { val source = this return internalReportingSet { measurementConsumerReferenceId = measurementConsumerKey.measurementConsumerId for (eventGroup: String in source.eventGroupsList) { eventGroupKeys += grpcRequireNotNull(EventGroupKey.fromName(eventGroup)) { "EventGroup is either unspecified or invalid." } .toInternal(measurementConsumerKey.measurementConsumerId) } filter = source.filter displayName = source.displayName } } /** Converts a public [EventGroupKey] to an internal [InternalEventGroupKey] */ private fun EventGroupKey.toInternal( measurementConsumerReferenceId: String, ): InternalEventGroupKey { val source = this return internalEventGroupKey { dataProviderReferenceId = source.dataProviderReferenceId eventGroupReferenceId = source.eventGroupReferenceId this.measurementConsumerReferenceId = measurementConsumerReferenceId } } /** Converts an internal [InternalReportingSet] to a public [ReportingSet]. */ private fun InternalReportingSet.toReportingSet(): ReportingSet { val source = this return reportingSet { name = ReportingSetKey( measurementConsumerId = source.measurementConsumerReferenceId, reportingSetId = externalIdToApiId(source.externalReportingSetId) ) .toName() eventGroups.addAll( eventGroupKeysList.map { EventGroupKey( measurementConsumerReferenceId = it.measurementConsumerReferenceId, dataProviderReferenceId = it.dataProviderReferenceId, eventGroupReferenceId = it.eventGroupReferenceId ) .toName() } ) filter = source.filter displayName = source.displayName } }
apache-2.0
8bc9c80775ebed602be63c7faff4e17e
38.613734
102
0.755363
4.901753
false
false
false
false
SimonVT/cathode
cathode/src/main/java/net/simonvt/cathode/ui/HomeActivity.kt
1
26122
/* * Copyright (C) 2013 Simon Vig Therkildsen * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.simonvt.cathode.ui import android.content.Intent import android.os.Bundle import android.view.Gravity import android.view.MenuItem import android.view.MotionEvent import android.view.View import android.view.ViewGroup import android.widget.ProgressBar import androidx.core.content.ContextCompat import androidx.drawerlayout.widget.DrawerLayout import androidx.fragment.app.Fragment import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProviders import butterknife.BindView import butterknife.ButterKnife import dagger.android.AndroidInjection import net.simonvt.cathode.R import net.simonvt.cathode.api.enumeration.Department import net.simonvt.cathode.api.enumeration.ItemType import net.simonvt.cathode.common.event.AuthFailedEvent import net.simonvt.cathode.common.event.AuthFailedEvent.OnAuthFailedListener import net.simonvt.cathode.common.event.ErrorEvent import net.simonvt.cathode.common.event.ErrorEvent.ErrorListener import net.simonvt.cathode.common.event.RequestFailedEvent import net.simonvt.cathode.common.event.RequestFailedEvent.OnRequestFailedListener import net.simonvt.cathode.common.event.SyncEvent import net.simonvt.cathode.common.event.SyncEvent.OnSyncListener import net.simonvt.cathode.common.ui.FragmentContract import net.simonvt.cathode.common.util.FragmentStack import net.simonvt.cathode.common.util.FragmentStack.StackEntry import net.simonvt.cathode.common.util.MainHandler import net.simonvt.cathode.common.widget.Crouton import net.simonvt.cathode.entity.Movie import net.simonvt.cathode.entity.ShowWithEpisode import net.simonvt.cathode.images.ImageType import net.simonvt.cathode.images.ImageUri import net.simonvt.cathode.provider.util.DataHelper import net.simonvt.cathode.settings.LinkPromptBottomSheet import net.simonvt.cathode.settings.Settings import net.simonvt.cathode.settings.SettingsActivity import net.simonvt.cathode.settings.SetupPromptBottomSheet import net.simonvt.cathode.settings.StartPage import net.simonvt.cathode.settings.TraktLinkSettings import net.simonvt.cathode.settings.login.LoginActivity import net.simonvt.cathode.sync.scheduler.MovieTaskScheduler import net.simonvt.cathode.sync.scheduler.ShowTaskScheduler import net.simonvt.cathode.ui.comments.CommentFragment import net.simonvt.cathode.ui.comments.CommentsFragment import net.simonvt.cathode.ui.credits.CreditFragment import net.simonvt.cathode.ui.credits.CreditsFragment import net.simonvt.cathode.ui.dashboard.DashboardFragment import net.simonvt.cathode.ui.history.SelectHistoryDateFragment import net.simonvt.cathode.ui.lists.ListFragment import net.simonvt.cathode.ui.lists.ListsFragment import net.simonvt.cathode.ui.movie.MovieFragment import net.simonvt.cathode.ui.movie.MovieHistoryFragment import net.simonvt.cathode.ui.movie.RelatedMoviesFragment import net.simonvt.cathode.ui.movies.collected.CollectedMoviesFragment import net.simonvt.cathode.ui.movies.watched.WatchedMoviesFragment import net.simonvt.cathode.ui.movies.watchlist.MovieWatchlistFragment import net.simonvt.cathode.ui.navigation.NavigationFragment import net.simonvt.cathode.ui.person.PersonCreditsFragment import net.simonvt.cathode.ui.person.PersonFragment import net.simonvt.cathode.ui.search.SearchFragment import net.simonvt.cathode.ui.show.EpisodeFragment import net.simonvt.cathode.ui.show.EpisodeHistoryFragment import net.simonvt.cathode.ui.show.RelatedShowsFragment import net.simonvt.cathode.ui.show.SeasonFragment import net.simonvt.cathode.ui.show.ShowFragment import net.simonvt.cathode.ui.shows.collected.CollectedShowsFragment import net.simonvt.cathode.ui.shows.upcoming.UpcomingShowsFragment import net.simonvt.cathode.ui.shows.watched.WatchedShowsFragment import net.simonvt.cathode.ui.shows.watchlist.ShowsWatchlistFragment import net.simonvt.cathode.ui.stats.StatsFragment import net.simonvt.cathode.ui.suggestions.movies.MovieSuggestionsFragment import net.simonvt.cathode.ui.suggestions.shows.ShowSuggestionsFragment import net.simonvt.cathode.widget.WatchingView import net.simonvt.cathode.widget.WatchingView.WatchingViewListener import timber.log.Timber import javax.inject.Inject class HomeActivity : BaseActivity(), NavigationFragment.OnMenuClickListener, NavigationListener, LinkPromptBottomSheet.LinkPromptDismissListener { @Inject lateinit var showScheduler: ShowTaskScheduler @Inject lateinit var movieScheduler: MovieTaskScheduler @BindView(R.id.progress_top) lateinit var progressTop: ProgressBar @BindView(R.id.crouton) lateinit var crouton: Crouton private lateinit var stack: FragmentStack @BindView(R.id.drawer) lateinit var drawer: DrawerLayout private lateinit var navigation: NavigationFragment @BindView(R.id.watching_parent) lateinit var watchingParent: ViewGroup @BindView(R.id.watchingView) lateinit var watchingView: WatchingView @BindView(R.id.authFailedView) lateinit var authFailedView: View @BindView(R.id.authFailedAction) lateinit var authFailedAction: View private lateinit var viewModel: HomeViewModel private var watchingShow: ShowWithEpisode? = null private var watchingMovie: Movie? = null private var pendingReplacement: PendingReplacement? = null private var isSyncing = false private val drawerListener = object : DrawerLayout.DrawerListener { override fun onDrawerSlide(drawerView: View, slideOffset: Float) {} override fun onDrawerOpened(drawerView: View) { pendingReplacement = null } override fun onDrawerClosed(drawerView: View) { if (pendingReplacement != null) { stack.replace(pendingReplacement!!.fragment, pendingReplacement!!.tag) pendingReplacement = null } } override fun onDrawerStateChanged(newState: Int) { if (newState == DrawerLayout.STATE_DRAGGING) { pendingReplacement = null } } } private val watchingTouchListener = View.OnTouchListener { _, event -> if (watchingView.isExpanded) { val action = event.actionMasked if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_CANCEL) { watchingView.collapse() } return@OnTouchListener true } false } private val watchingListener = object : WatchingViewListener { override fun onExpand(view: WatchingView) { Timber.d("onExpand") } override fun onCollapse(view: WatchingView) { Timber.d("onCollapse") } override fun onEpisodeClicked(view: WatchingView, episodeId: Long, showTitle: String?) { watchingView.collapse() val top = stack.peek() if (top is EpisodeFragment) { if (episodeId == top.episodeId) { return } } onDisplayEpisode(episodeId, showTitle) } override fun onMovieClicked(view: WatchingView, id: Long, title: String?, overview: String?) { watchingView.collapse() val top = stack.peek() if (top is MovieFragment) { if (id == top.movieId) { return } } onDisplayMovie(id, title, overview) } override fun onAnimatingIn(view: WatchingView) {} override fun onAnimatingOut(view: WatchingView) {} } private val onSyncEvent = OnSyncListener { syncing -> if (syncing != [email protected]) { [email protected] = syncing val progressVisibility = progressTop.visibility val progressAnimator = progressTop.animate() if (syncing) { if (progressVisibility == View.GONE) { progressTop.alpha = 0.0f progressTop.visibility = View.VISIBLE } progressAnimator.alpha(1.0f) } else { progressAnimator.alpha(0.0f).withEndAction { progressTop.visibility = View.GONE } } } } private val requestFailedListener = OnRequestFailedListener { event -> crouton.show( getString(event.errorMessage), ContextCompat.getColor(this, android.R.color.holo_red_dark) ) } private val checkInFailedListener = ErrorListener { error -> crouton.show(error, ContextCompat.getColor(this, android.R.color.holo_red_dark)) } private val onAuthFailedListener = OnAuthFailedListener { authFailedView.visibility = View.VISIBLE } private class PendingReplacement(var fragment: Class<*>, var tag: String) override fun onCreate(inState: Bundle?) { setTheme(R.style.Theme) super.onCreate(inState) AndroidInjection.inject(this) setContentView(R.layout.activity_home) ButterKnife.bind(this) drawer.addDrawerListener(drawerListener) watchingParent.setOnTouchListener(watchingTouchListener) watchingView.setWatchingViewListener(watchingListener) authFailedAction.setOnClickListener { startLoginActivity() } navigation = supportFragmentManager.findFragmentByTag(NavigationFragment.TAG) as NavigationFragment stack = FragmentStack.forContainer(this, R.id.content) stack.setDefaultAnimation( R.anim.fade_in_front, R.anim.fade_out_back, R.anim.fade_in_back, R.anim.fade_out_front ) if (inState != null) { stack.restoreState(inState.getBundle(STATE_STACK)) } val intent = intent if (isShowStartPageIntent(intent)) { var startPage: StartPage? = intent.getSerializableExtra(EXTRA_START_PAGE) as StartPage if (startPage == null) { startPage = StartPage.SHOWS_UPCOMING } navigation.setSelectedId(startPage.menuId.toLong()) stack.replace(startPage.pageClass, startPage.tag) } else if (isShowUpcomingAction(intent)) { navigation.setSelectedId(StartPage.SHOWS_UPCOMING.menuId.toLong()) stack.replace(StartPage.SHOWS_UPCOMING.pageClass, StartPage.SHOWS_UPCOMING.tag) } else { if (stack.size() == 0) { val startPagePref = Settings.get(this).getString(Settings.START_PAGE, null) val startPage = StartPage.fromValue(startPagePref, StartPage.DASHBOARD) navigation.setSelectedId(startPage.menuId.toLong()) stack.replace(startPage.pageClass, startPage.tag) } if (isSearchAction(intent)) { onSearchClicked() } } if (!TraktLinkSettings.isLinkPrompted(this)) { displayLinkPrompt() } else if (isLoginAction(getIntent())) { startLoginActivity() } else { if (isReplaceStackAction(intent)) { val stackEntries = getIntent().getParcelableArrayListExtra<StackEntry>(EXTRA_STACK_ENTRIES) replaceStack(stackEntries) } if (!Settings.get(this).getBoolean(Settings.SETUP_PROMPTED, false)) { displaySetupPrompt() } } intent.action = ACTION_CONSUMED SyncEvent.registerListener(onSyncEvent) RequestFailedEvent.registerListener(requestFailedListener) ErrorEvent.registerListener(checkInFailedListener) AuthFailedEvent.registerListener(onAuthFailedListener) viewModel = ViewModelProviders.of(this).get(HomeViewModel::class.java) viewModel.watchingShow.observe(this, Observer { showWithEpisode -> watchingShow = showWithEpisode updateWatching() }) viewModel.watchingMovie.observe(this, Observer { movie -> watchingMovie = movie updateWatching() }) } override fun onNewIntent(intent: Intent) { super.onNewIntent(intent) when { isLoginAction(intent) -> MainHandler.post { startLoginActivity() } isShowStartPageIntent(intent) -> { val startPage = intent.getSerializableExtra(EXTRA_START_PAGE) as StartPage MainHandler.post { showStartPage(startPage) } } isReplaceStackAction(intent) -> { val stackEntries = intent.getParcelableArrayListExtra<StackEntry>(EXTRA_STACK_ENTRIES) MainHandler.post { replaceStack(stackEntries) } } } intent.action = ACTION_CONSUMED } private fun isShowStartPageIntent(intent: Intent): Boolean { return ACTION_SHOW_START_PAGE == intent.action } private fun showStartPage(startPage: StartPage) { navigation.setSelectedId(startPage.menuId.toLong()) onMenuItemClicked(startPage.menuId) pendingReplacement?.apply { stack.replace(fragment, tag) pendingReplacement = null } } private fun replaceStack(stackEntries: MutableList<StackEntry>) { val f = stack.peekFirst() val entry = StackEntry(f.javaClass, f.tag, f.arguments) stackEntries.add(0, entry) stack.replaceStack(stackEntries) } private fun isReplaceStackAction(intent: Intent): Boolean { return ACTION_REPLACE_STACK == intent.action } private fun isLoginAction(intent: Intent): Boolean { return ACTION_LOGIN == intent.action } private fun isSearchAction(intent: Intent): Boolean { return ACTION_SEARCH == intent.action } private fun isShowUpcomingAction(intent: Intent): Boolean { return ACTION_UPCOMING == intent.action } private fun displayLinkPrompt() { if (supportFragmentManager.findFragmentByTag(PROMPT_LINK) == null) { val linkPrompt = LinkPromptBottomSheet() linkPrompt.show(supportFragmentManager, PROMPT_LINK) } } override fun onDismissLinkPrompt() { if (!Settings.get(this).getBoolean(Settings.SETUP_PROMPTED, false)) { displaySetupPrompt() } } private fun displaySetupPrompt() { if (supportFragmentManager.findFragmentByTag(PROMPT_SETUP) == null) { val setupPrompt = SetupPromptBottomSheet() setupPrompt.show(supportFragmentManager, PROMPT_SETUP) } } override fun onSaveInstanceState(outState: Bundle) { outState.putBundle(STATE_STACK, stack.saveState()) super.onSaveInstanceState(outState) } override fun onResume() { super.onResume() if (TraktLinkSettings.hasAuthFailed(this)) { authFailedView.visibility = View.VISIBLE } else { authFailedView.visibility = View.GONE } } override fun onDestroy() { Timber.d("onDestroy") SyncEvent.unregisterListener(onSyncEvent) RequestFailedEvent.unregisterListener(requestFailedListener) ErrorEvent.unregisterListener(checkInFailedListener) super.onDestroy() } override fun onBackPressed() { if (watchingView.isExpanded) { watchingView.collapse() return } if (drawer.isDrawerVisible(Gravity.LEFT)) { drawer.closeDrawer(Gravity.LEFT) return } val topFragment = stack.peek() as FragmentContract? if (topFragment?.onBackPressed() == true) { return } if (stack.pop()) { return } super.onBackPressed() } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { android.R.id.home -> { onHomeClicked() return true } } return super.onOptionsItemSelected(item) } override fun onMenuItemClicked(id: Int): Boolean { when (id) { R.id.menu_dashboard -> pendingReplacement = PendingReplacement(DashboardFragment::class.java, DashboardFragment.TAG) R.id.menu_shows_upcoming -> pendingReplacement = PendingReplacement(UpcomingShowsFragment::class.java, UpcomingShowsFragment.TAG) R.id.menu_shows_watched -> pendingReplacement = PendingReplacement(WatchedShowsFragment::class.java, WatchedShowsFragment.TAG) R.id.menu_shows_collection -> pendingReplacement = PendingReplacement(CollectedShowsFragment::class.java, CollectedShowsFragment.TAG) R.id.menu_shows_watchlist -> pendingReplacement = PendingReplacement(ShowsWatchlistFragment::class.java, ShowsWatchlistFragment.TAG) R.id.menu_shows_suggestions -> pendingReplacement = PendingReplacement(ShowSuggestionsFragment::class.java, ShowSuggestionsFragment.TAG) R.id.menu_movies_watched -> pendingReplacement = PendingReplacement(WatchedMoviesFragment::class.java, WatchedMoviesFragment.TAG) R.id.menu_movies_collection -> pendingReplacement = PendingReplacement(CollectedMoviesFragment::class.java, CollectedMoviesFragment.TAG) R.id.menu_movies_watchlist -> pendingReplacement = PendingReplacement(MovieWatchlistFragment::class.java, MovieWatchlistFragment.TAG) R.id.menu_movies_suggestions -> pendingReplacement = PendingReplacement(MovieSuggestionsFragment::class.java, MovieSuggestionsFragment.TAG) R.id.menu_lists -> pendingReplacement = PendingReplacement(ListsFragment::class.java, ListsFragment.TAG) R.id.menu_stats -> pendingReplacement = PendingReplacement(StatsFragment::class.java, StatsFragment.TAG) R.id.menu_settings -> { val settings = Intent(this, SettingsActivity::class.java) startActivity(settings) return false } else -> throw IllegalArgumentException("Unknown id $id") } drawer.closeDrawer(Gravity.LEFT) return true } private fun startLoginActivity() { val login = Intent(this, LoginActivity::class.java) login.putExtra(LoginActivity.EXTRA_TASK, LoginActivity.TASK_TOKEN_REFRESH) startActivity(login) finish() } /////////////////////////////////////////////////////////////////////////// // Navigation callbacks /////////////////////////////////////////////////////////////////////////// override fun onHomeClicked() { if (stack.size() == 1) { drawer.openDrawer(Gravity.LEFT) return } stack.pop() } override fun onSearchClicked() { stack.push(SearchFragment::class.java, SearchFragment.TAG) } override fun onDisplayShow(showId: Long, title: String?, overview: String?, type: LibraryType) { stack.push( ShowFragment::class.java, ShowFragment.getTag(showId), ShowFragment.getArgs(showId, title, overview, type) ) } override fun onDisplayEpisode(episodeId: Long, showTitle: String?) { stack.push( EpisodeFragment::class.java, EpisodeFragment.getTag(episodeId), EpisodeFragment.getArgs(episodeId, showTitle) ) } override fun onDisplayEpisodeHistory(episodeId: Long, showTitle: String) { stack.push( EpisodeHistoryFragment::class.java, EpisodeHistoryFragment.getTag(episodeId), EpisodeHistoryFragment.getArgs(episodeId, showTitle) ) } override fun onDisplaySeason( showId: Long, seasonId: Long, showTitle: String?, seasonNumber: Int, type: LibraryType ) { stack.push( SeasonFragment::class.java, SeasonFragment.TAG, SeasonFragment.getArgs(seasonId, showTitle, seasonNumber, type) ) } override fun onDisplayRelatedShows(showId: Long, title: String?) { stack.push( RelatedShowsFragment::class.java, RelatedShowsFragment.getTag(showId), RelatedShowsFragment.getArgs(showId) ) } override fun onSelectShowWatchedDate(showId: Long, title: String?) { stack.push( SelectHistoryDateFragment::class.java, SelectHistoryDateFragment.TAG, SelectHistoryDateFragment.getArgs(SelectHistoryDateFragment.Type.SHOW, showId, title) ) } override fun onSelectSeasonWatchedDate(seasonId: Long, title: String?) { stack.push( SelectHistoryDateFragment::class.java, SelectHistoryDateFragment.TAG, SelectHistoryDateFragment.getArgs(SelectHistoryDateFragment.Type.SEASON, seasonId, title) ) } override fun onSelectEpisodeWatchedDate(episodeId: Long, title: String?) { stack.push( SelectHistoryDateFragment::class.java, SelectHistoryDateFragment.TAG, SelectHistoryDateFragment.getArgs(SelectHistoryDateFragment.Type.EPISODE, episodeId, title) ) } override fun onSelectOlderEpisodeWatchedDate(episodeId: Long, title: String?) { stack.push( SelectHistoryDateFragment::class.java, SelectHistoryDateFragment.TAG, SelectHistoryDateFragment.getArgs( SelectHistoryDateFragment.Type.EPISODE_OLDER, episodeId, title ) ) } override fun onDisplayMovie(movieId: Long, title: String?, overview: String?) { stack.push( MovieFragment::class.java, MovieFragment.getTag(movieId), MovieFragment.getArgs(movieId, title, overview) ) } override fun onDisplayRelatedMovies(movieId: Long, title: String?) { stack.push( RelatedMoviesFragment::class.java, RelatedMoviesFragment.getTag(movieId), RelatedMoviesFragment.getArgs(movieId) ) } override fun onSelectMovieWatchedDate(movieId: Long, title: String?) { stack.push( SelectHistoryDateFragment::class.java, SelectHistoryDateFragment.TAG, SelectHistoryDateFragment.getArgs(SelectHistoryDateFragment.Type.MOVIE, movieId, title) ) } override fun onDisplayMovieHistory(movieId: Long, title: String?) { stack.push( MovieHistoryFragment::class.java, MovieHistoryFragment.getTag(movieId), MovieHistoryFragment.getArgs(movieId, title) ) } override fun onShowList(listId: Long, listName: String) { stack.push(ListFragment::class.java, ListFragment.TAG, ListFragment.getArgs(listId, listName)) } override fun onListDeleted(listId: Long) { val top = stack.peek() if (top is ListFragment) { if (listId == top.listId) { stack.pop() } } } override fun onDisplayComments(type: ItemType, itemId: Long) { stack.push( CommentsFragment::class.java, CommentsFragment.TAG, CommentsFragment.getArgs(type, itemId) ) } override fun onDisplayComment(commentId: Long) { stack.push(CommentFragment::class.java, CommentFragment.TAG, CommentFragment.getArgs(commentId)) } override fun onDisplayPerson(personId: Long) { stack.push( PersonFragment::class.java, PersonFragment.getTag(personId), PersonFragment.getArgs(personId) ) } override fun onDisplayPersonCredit(personId: Long, department: Department) { stack.push( PersonCreditsFragment::class.java, PersonCreditsFragment.getTag(personId), PersonCreditsFragment.getArgs(personId, department) ) } override fun onDisplayCredit(itemType: ItemType, itemId: Long, department: Department) { stack.push( CreditFragment::class.java, CreditFragment.getTag(itemId), CreditFragment.getArgs(itemType, itemId, department) ) } override fun onDisplayCredits(itemType: ItemType, itemId: Long, title: String?) { stack.push( CreditsFragment::class.java, CreditsFragment.getTag(itemId), CreditsFragment.getArgs(itemType, itemId, title) ) } override fun displayFragment(clazz: Class<*>, tag: String) { stack.push(clazz, tag, null) } override fun upFromEpisode(showId: Long, showTitle: String?, seasonId: Long) { if (stack.removeTop()) { val f = stack.peek() if (f is ShowFragment && f.showId == showId) { stack.attachTop() } else if (seasonId >= 0 && f is SeasonFragment && f.seasonId == seasonId) { stack.attachTop() } else { stack.putFragment( ShowFragment::class.java, ShowFragment.getTag(showId), ShowFragment.getArgs(showId, showTitle, null, LibraryType.WATCHED) ) } } } override fun popIfTop(fragment: Fragment) { if (fragment === stack.peek()) { stack.pop() } } override fun isFragmentTopLevel(fragment: Fragment): Boolean { return stack.positionInStack(fragment) == 0 } /////////////////////////////////////////////////////////////////////////// // Watching view /////////////////////////////////////////////////////////////////////////// private fun updateWatching() { if (watchingShow != null) { watchingShow?.let { val showId = it.show.id val showTitle = it.show.title val season = it.episode.season val episode = it.episode.episode val episodeId = it.episode.id val episodeTitle = DataHelper.getEpisodeTitle(this, it.episode.title, season, episode, false) val startTime = it.episode.checkinStartedAt val endTime = it.episode.checkinExpiresAt val poster = ImageUri.create(ImageUri.ITEM_SHOW, ImageType.POSTER, showId) watchingView.watchingShow( showId, showTitle, episodeId, episodeTitle, poster, startTime, endTime ) } } else if (watchingMovie != null) { watchingMovie?.let { val id = it.id val title = it.title val overview = it.overview val startTime = it.checkinStartedAt val endTime = it.checkinExpiresAt val poster = ImageUri.create(ImageUri.ITEM_MOVIE, ImageType.POSTER, id) watchingView.watchingMovie(id, title, overview, poster, startTime, endTime) } } else { watchingView.clearWatching() } } companion object { private const val PROMPT_LINK = "net.simonvt.cathode.ui.HomeActivity.linkPrompt" private const val PROMPT_SETUP = "net.simonvt.cathode.ui.HomeActivity.setupPrompt" private const val STATE_STACK = "net.simonvt.cathode.ui.HomeActivity.stack" const val EXTRA_START_PAGE = "net.simonvt.cathode.ui.HomeActivity.startPage" const val EXTRA_STACK_ENTRIES = "net.simonvt.cathode.ui.HomeActivity.stackEntries" const val ACTION_CONSUMED = "consumed" const val ACTION_LOGIN = "net.simonvt.cathode.intent.action.LOGIN" const val ACTION_SHOW_START_PAGE = "net.simonvt.cathode.intent.action.showStartPage" const val ACTION_REPLACE_STACK = "replaceStack" const val ACTION_SEARCH = "net.simonvt.cathode.SEARCH" const val ACTION_UPCOMING = "net.simonvt.cathode.UPCOMING" } }
apache-2.0
37720855be168665d3c4c537ac8726be
31.530511
100
0.715451
4.355118
false
false
false
false
crunchersaspire/worshipsongs-android
app/src/main/java/org/worshipsongs/dialog/AddFavouritesDialogFragment.kt
2
3220
package org.worshipsongs.dialog import android.app.Dialog import android.content.DialogInterface import android.os.Bundle import android.view.ContextThemeWrapper import android.view.LayoutInflater import android.view.WindowManager import android.widget.EditText import android.widget.Toast import androidx.appcompat.app.AlertDialog import androidx.fragment.app.DialogFragment import org.worshipsongs.CommonConstants import org.worshipsongs.R import org.worshipsongs.domain.SongDragDrop import org.worshipsongs.service.FavouriteService /** * @author: Seenivasan, Madasamy * @since :1.0.0 */ class AddFavouritesDialogFragment : DialogFragment() { private val favouriteService = FavouriteService() private val negativeOnClickListener: DialogInterface.OnClickListener get() = DialogInterface.OnClickListener { dialog, which -> dialog.cancel() } override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { val layoutInflater = LayoutInflater.from(activity) val promptsView = layoutInflater.inflate(R.layout.add_service_dialog, null) val alertDialogBuilder = AlertDialog.Builder(ContextThemeWrapper(activity, R.style.DialogTheme)) alertDialogBuilder.setView(promptsView) val serviceName = promptsView.findViewById<EditText>(R.id.service_name) alertDialogBuilder.setTitle(R.string.favourite_title) alertDialogBuilder.setCancelable(false) alertDialogBuilder.setPositiveButton(R.string.ok, getPositiveOnClickListener(serviceName)) alertDialogBuilder.setNegativeButton(R.string.cancel, negativeOnClickListener) val alertDialog = alertDialogBuilder.create() alertDialog.window!!.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE) alertDialog.window!!.setBackgroundDrawableResource(R.color.white) return alertDialog } private fun getPositiveOnClickListener(serviceName: EditText): DialogInterface.OnClickListener { return DialogInterface.OnClickListener { dialog, which -> val args = arguments val songName = args!!.getString(CommonConstants.TITLE_KEY) val localisedName = args.getString(CommonConstants.LOCALISED_TITLE_KEY) val id = args.getInt(CommonConstants.ID) if (serviceName.text.toString() == "") { Toast.makeText(activity, "Enter favourite name...!", Toast.LENGTH_LONG).show() } else { val favouriteName = serviceName.text.toString() val songDragDrop = SongDragDrop(id.toLong(), songName!!, false) songDragDrop.tamilTitle = localisedName favouriteService.save(favouriteName, songDragDrop) Toast.makeText(activity, "Song added to favourite......!", Toast.LENGTH_SHORT).show() dialog.dismiss() } } } companion object { fun newInstance(bundle: Bundle): AddFavouritesDialogFragment { val addFavouritesDialogFragment = AddFavouritesDialogFragment() addFavouritesDialogFragment.arguments = bundle return addFavouritesDialogFragment } } }
gpl-3.0
6fb4d85a3f0dd2fa81916dc5e6192c3c
38.753086
104
0.71118
5.357737
false
false
false
false
faceofcat/Tesla-Powered-Thingies
src/main/kotlin/net/ndrei/teslapoweredthingies/machines/cropcloner/CropClonerEntity.kt
1
8670
package net.ndrei.teslapoweredthingies.machines.cropcloner import net.minecraft.block.Block import net.minecraft.block.state.IBlockState import net.minecraft.client.renderer.tileentity.TileEntitySpecialRenderer import net.minecraft.item.EnumDyeColor import net.minecraft.item.ItemStack import net.minecraft.nbt.NBTTagCompound import net.minecraft.tileentity.TileEntity import net.minecraft.util.ResourceLocation import net.minecraftforge.common.EnumPlantType import net.minecraftforge.common.IPlantable import net.minecraftforge.fluids.FluidRegistry import net.minecraftforge.fluids.IFluidTank import net.ndrei.teslacorelib.inventory.BoundingRectangle import net.ndrei.teslacorelib.inventory.ColoredItemHandler import net.ndrei.teslacorelib.inventory.SyncItemHandler import net.ndrei.teslacorelib.render.HudInfoLine import net.ndrei.teslacorelib.utils.equalsIgnoreSize import net.ndrei.teslapoweredthingies.machines.ElectricFarmMachine import net.ndrei.teslapoweredthingies.render.CropClonerSpecialRenderer import java.awt.Color /** * Created by CF on 2017-07-07. */ class CropClonerEntity : ElectricFarmMachine(CropClonerEntity::class.java.name.hashCode()) { var plantedThing: IBlockState? = null private set private lateinit var waterTank: IFluidTank //#region inventory methods override fun supportsRangeAddons() = false override fun supportsAddons() = false override val hasWorkArea: Boolean get() = false override fun initializeInventories() { super.initializeInventories() this.waterTank = super.addFluidTank(FluidRegistry.WATER, 5000, EnumDyeColor.BLUE, "Water Tank", BoundingRectangle(43, 25, 18, 54)) } override fun initializeInputInventory() { val inputs = object : SyncItemHandler(1) { override fun getStackLimit(slot: Int, stack: ItemStack) = 1 } this.inStackHandler = inputs this.filteredInStackHandler = object : ColoredItemHandler(this.inStackHandler!!, EnumDyeColor.GREEN, "Input Items", BoundingRectangle(115 + 18, 25, 18, 18)) { override fun canInsertItem(slot: Int, stack: ItemStack) = super.canInsertItem (slot, stack) && [email protected](slot, stack) override fun canExtractItem(slot: Int) = false } super.addInventory(this.filteredInStackHandler!!) super.addInventoryToStorage(inputs, "inputs") } override val lockableInputInventory: Boolean get() = false override fun acceptsInputStack(slot: Int, stack: ItemStack): Boolean { if (stack.isEmpty) { return false } if (stack.item is IPlantable) { val plant = stack.item as IPlantable if (plant.getPlantType(this.getWorld(), this.getPos()) == EnumPlantType.Crop) { return true } } return false } //#endregion //#region gui methods override val hudLines: MutableList<HudInfoLine> get() { val list = super.hudLines //.toMutableList() if (this.plantedThing == null) { list.add(HudInfoLine(Color(255, 159, 51), Color(255, 159, 51, 42), "no seed") .setTextAlignment(HudInfoLine.TextAlignment.CENTER)) } else { list.add(HudInfoLine(Color.WHITE, this.plantedThing!!.block.localizedName) .setTextAlignment(HudInfoLine.TextAlignment.CENTER)) val age = CropClonerPlantFactory.getPlant(this.plantedThing!!).getAgeProperty(this.plantedThing!!) if (age != null) { val percent = this.plantedThing!!.getValue(age) * 100 / age.allowedValues.size list.add(HudInfoLine(Color.CYAN, Color(Color.GRAY.red, Color.GRAY.green, Color.GRAY.blue, 192), Color(Color.CYAN.red, Color.CYAN.green, Color.CYAN.blue, 192), "growth: $percent%") .setProgress(percent.toFloat() / 100.0f, Color(Color.CYAN.red, Color.CYAN.green, Color.CYAN.blue, 50))) } } return list //.toList() } override fun getRenderers(): MutableList<TileEntitySpecialRenderer<in TileEntity>> { val list = super.getRenderers() list.add(CropClonerSpecialRenderer) return list } //#endregion //#region storage methods override fun readFromNBT(compound: NBTTagCompound) { super.readFromNBT(compound) if (compound.hasKey("plantDomain") && compound.hasKey("plantPath")) { val location = ResourceLocation( compound.getString("plantDomain"), compound.getString("plantPath")) val block = Block.REGISTRY.getObject(location) if (block != null) { this.plantedThing = block.defaultState this.onPlantedThingChanged() } } if (compound.hasKey("plantAge") && this.plantedThing != null) { val age = compound.getInteger("plantAge") val ageProperty = CropClonerPlantFactory.getPlant(this.plantedThing!!).getAgeProperty(this.plantedThing!!) if (ageProperty != null) { this.plantedThing = this.plantedThing!!.withProperty(ageProperty, age) this.onPlantedThingChanged() } } } override fun writeToNBT(compound: NBTTagCompound): NBTTagCompound { val nbt = super.writeToNBT(compound) if (this.plantedThing != null) { val resource = this.plantedThing!!.block.registryName nbt.setString("plantDomain", resource!!.namespace) nbt.setString("plantPath", resource.path) val ageProperty = CropClonerPlantFactory.getPlant(this.plantedThing!!).getAgeProperty(this.plantedThing!!) if (ageProperty != null) { nbt.setInteger("plantAge", this.plantedThing!!.getValue(ageProperty)) } } return nbt } //#endregion override fun performWork(): Float { var result = 0.0f val planted = this.plantedThing if (planted != null) { val wrapper = CropClonerPlantFactory.getPlant(planted) val ageProperty = wrapper.getAgeProperty(planted) if (ageProperty != null) { val age = planted.getValue(ageProperty) val ages = ageProperty.allowedValues.toTypedArray() if (age == ages[ages.size - 1]) { val input = this.inStackHandler?.getStackInSlot(0) ?: ItemStack.EMPTY val stacks = wrapper.getDrops(this.getWorld(), this.getPos(), planted) .map { if (it.equalsIgnoreSize(input)) it.also { it.shrink(1) } else it } .filter { !it.isEmpty } if (super.outputItems(stacks)) { this.plantedThing = null result += .85f } } else { this.plantedThing = wrapper.grow(planted, ageProperty, this.getWorld().rand) result += .75f } this.onPlantedThingChanged() } } if (this.plantedThing == null && this.waterTank.fluidAmount >= 250) { val stack = this.inStackHandler!!.getStackInSlot(0) if (!stack.isEmpty && (stack.item is IPlantable)) { val plantable = stack.item as IPlantable if (plantable.getPlantType(this.getWorld(), this.getPos()) == EnumPlantType.Crop) { this.plantedThing = plantable.getPlant(this.getWorld(), this.getPos()) this.waterTank.drain(250, true) // TODO: <-- do this better this.onPlantedThingChanged() } } result += .15f } return result } private fun onPlantedThingChanged() { if (null != this.getWorld() && null != this.getPos()) { // <-- weird, but it actually happens!! val state = if (this.plantedThing == null) 0 else 1 val block = this.getWorld().getBlockState(this.getPos()) if (block.getValue(CropClonerBlock.STATE) != state) { CropClonerBlock.setState(block.withProperty(CropClonerBlock.STATE, state), this.getWorld(), this.getPos()) } } this.markDirty() this.forceSync() } }
mit
1f0c974ff4081d9de5aa719fdc80a0fc
38.589041
131
0.607382
4.575198
false
false
false
false
i7c/cfm
server/recorder/src/main/kotlin/org/rliz/cfm/recorder/mbs/api/MbsIdentifiedPlaybackRes.kt
1
1008
package org.rliz.cfm.recorder.mbs.api import org.rliz.cfm.recorder.common.trans.nonEmptyCollection import org.rliz.cfm.recorder.common.trans.nonNullField import java.util.UUID data class MbsIdentifiedPlaybackRes( val releaseId: UUID? = null, val releaseGroupId: UUID? = null, val recordingId: UUID? = null, val recordingArtistIds: List<UUID>? = null, val releaseGroupArtistIds: List<UUID> = emptyList() ) { fun toDto() = MbsIdentifiedPlaybackDto( releaseId = nonNullField(this::releaseId), releaseGroupId = nonNullField(this::releaseGroupId), recordingId = nonNullField(this::recordingId), recordingArtistIds = nonEmptyCollection(this::recordingArtistIds), releaseGroupArtistIds = nonEmptyCollection(this::releaseGroupArtistIds) ) } data class MbsIdentifiedPlaybackDto( val releaseId: UUID, val releaseGroupId: UUID, val recordingId: UUID, val recordingArtistIds: List<UUID>, val releaseGroupArtistIds: List<UUID> )
gpl-3.0
f060cff3b881f5247859b47ef0382841
32.6
79
0.736111
3.9375
false
false
false
false
Mauin/detekt
detekt-api/src/main/kotlin/io/gitlab/arturbosch/detekt/api/Suppressible.kt
1
1700
package io.gitlab.arturbosch.detekt.api import org.jetbrains.kotlin.com.intellij.psi.util.PsiTreeUtil import org.jetbrains.kotlin.psi.KtAnnotated import org.jetbrains.kotlin.psi.KtElement import org.jetbrains.kotlin.psi.KtFile /** * @author Artur Bosch * @author Marvin Ramin */ /** * Checks if this psi element is suppressed by @Suppress or @SuppressWarnings annotations. * If this element cannot have annotations, the first annotative parent is searched. */ fun KtElement.isSuppressedBy(id: String, aliases: Set<String>) = this is KtAnnotated && this.isSuppressedBy(id, aliases) || findAnnotatedSuppressedParent(id, aliases) private fun KtElement.findAnnotatedSuppressedParent(id: String, aliases: Set<String>): Boolean { val parent = PsiTreeUtil.getParentOfType(this, KtAnnotated::class.java, true) var suppressed = false if (parent != null && parent !is KtFile) { suppressed = if (parent.isSuppressedBy(id, aliases)) { true } else { parent.findAnnotatedSuppressedParent(id, aliases) } } return suppressed } private val detektSuppresionPrefixRegex = Regex("(?i)detekt([.:])") private const val QUOTES = "\"" /** * Checks if this kt element is suppressed by @Suppress or @SuppressWarnings annotations. */ fun KtAnnotated.isSuppressedBy(id: String, aliases: Set<String>): Boolean { val valid = mutableSetOf(id, "ALL", "all", "All") valid.addAll(aliases) return annotationEntries.find { it.typeReference?.text.let { it == "Suppress" || it == "SuppressWarnings" } } ?.valueArguments ?.map { it.getArgumentExpression()?.text } ?.map { it?.replace(detektSuppresionPrefixRegex, "") } ?.map { it?.replace(QUOTES, "") } ?.find { it in valid } != null }
apache-2.0
861bd53c67d4bc6adffeed4b4b7084e7
33
110
0.729412
3.71179
false
false
false
false
AgileVentures/MetPlus_resumeCruncher
core/src/main/kotlin/org/metplus/cruncher/rating/CrunchProcess.kt
1
2097
package org.metplus.cruncher.rating import org.slf4j.LoggerFactory import java.util.* import java.util.concurrent.Semaphore abstract class ProcessCruncher<Work> { private val logger = LoggerFactory.getLogger(ProcessCruncher::class.java) private var cruncher: Thread? = null private var workDeque: Deque<Work> = ArrayDeque() private var keepRunning = true private var semaphore: Semaphore = Semaphore(1) fun run() { logger.info("Processor started") do { logger.debug("Going to check workDeque") var work: Work? = nextWork() while (work != null) { logger.debug("Going to process work") try { process(work) } catch (exp: Exception) { logger.error("Unhandled exception on work: $work:$exp") } work = nextWork() } logger.debug("No more work to process, sleep waiting") try { semaphore.acquire() } catch (e: InterruptedException) { e.printStackTrace() } } while (keepRunning) logger.warn("Processor stopped") } protected abstract fun process(work: Work) @Synchronized fun stop() { logger.warn("Requested stop of processor") setKeepRunning(false) semaphore.release() } fun setKeepRunning(keepRunning: Boolean) { this.keepRunning = keepRunning } fun start() { cruncher = object : Thread() { override fun run() { [email protected]() } } cruncher!!.start() } @Synchronized fun addWork(work: Work) { workDeque.add(work) semaphore.release() } @Synchronized protected fun nextWork(): Work? { return try { workDeque.remove() } catch (exp: NoSuchElementException) { null } } @Throws(InterruptedException::class) fun join() { cruncher!!.join() } }
gpl-3.0
faf16f5ad64239db8feff3cb1874b397
24.26506
77
0.549356
4.765909
false
false
false
false
maxxkrakoa/toodledo2todoist
src/main/kotlin/com/github/maxxkrakoa/Toodledo2Todoist.kt
1
6481
package com.github.maxxkrakoa import com.fasterxml.jackson.dataformat.csv.CsvMapper import java.io.File import java.text.SimpleDateFormat import java.util.* import kotlin.system.exitProcess /** * Created by mv on 2017-09-13. */ // Tried to use this instead of ToodledoItemJava.java but data ends up in the wrong fields when using Jackson CSV /* @JsonPropertyOrder("TASK", "FOLDER", "CONTEXT", "GOAL", "LOCATION", "STARTDATE", "STARTTIME", "DUEDATE", "DUETIME", "REPEAT", "LENGTH", "TIMER", "PRIORITY", "TAG", "STATUS", "STAR", "NOTE") class ToodledoItem() { var TASK = "" var FOLDER = "" var CONTEXT = "" var GOAL = "" var LOCATION = "" var STARTDATE = "" var STARTTIME = "" var DUEDATE = "" var DUETIME = "" var REPEAT = "" var LENGTH = "" var TIMER = "" var PRIORITY = "" var TAG = "" var STATUS = "" var STAR = "" var NOTE = "" } */ fun main(args: Array<String>) { if (args.size != 2) { println("Toodledo2Todoist <input-toodledo.csv> <output directory>") exitProcess(0) } println("Loading and converting " + args[0] + " -> " + args[1]) val f = File(args[0]) val toodledoItems = loadToodledoItems(f) val todoistItemsMap = convertToTodoist(toodledoItems) val outDir = File(args[1]) saveTodoistItems(todoistItemsMap, outDir) } private fun saveTodoistItems(todoistItemsMap: MutableMap<String, MutableList<TodoistItem>>, outDir: File) { val mapper = CsvMapper() val schema = mapper.schemaFor(TodoistLineItemJava::class.java).withColumnSeparator(',').withUseHeader(true) val writer = mapper.writerFor(TodoistLineItemJava::class.java).with(schema) for ((folder, todoistItems) in todoistItemsMap) { val lineItems = mutableListOf<TodoistLineItemJava>() for (todoistItem in todoistItems) { lineItems.add(todoistItem.taskLineItem) if (todoistItem.noteLineItem != null) { lineItems.add(todoistItem.noteLineItem!!) } lineItems.add(emptyTodoistLineItem()) } val outF = File(outDir, folder + ".csv") println("Writing " + outF) writer.writeValues(outF).writeAll(lineItems) } } fun emptyTodoistLineItem(): TodoistLineItemJava { val retval = TodoistLineItemJava(); retval.TYPE = "" retval.CONTENT = "" retval.PRIORITY = "" retval.INDENT = "" retval.AUTHOR = "" retval.RESPONSIBLE = "" retval.DATE = "" retval.DATE_LANG = "" retval.TIMEZONE = "" return retval } fun convertToTodoist(toodledoItems: MutableList<ToodledoItemJava>): MutableMap<String, MutableList<TodoistItem>> { val itemsMap = mutableMapOf<String, MutableList<TodoistItem>>() val dateFormatter = SimpleDateFormat("yyyy-MM-dd") val today = Date() var warningDisplayed = false for (toodledoItem in toodledoItems) { val item = TodoistItem(convertToodledoTaskAndTags(toodledoItem.TASK, toodledoItem.TAG), convertToodledoPriority(toodledoItem.PRIORITY), toodledoItem.DUEDATE + " " + convertToodledoRepeat(toodledoItem.REPEAT), toodledoItem.NOTE) if (toodledoItem.REPEAT?.trim() != "") { // check if due date is in the past since Todoist doesn't support repeating events in the past if (dateFormatter.parse(toodledoItem.DUEDATE).before(today)) { if (!warningDisplayed) { println("One or more repeating events have a due date before today. Todoist doesn't handle that and they will import with no date set.") warningDisplayed = true } println(" - " + toodledoItem.TASK + " / " + toodledoItem.DUEDATE + " / " + toodledoItem.REPEAT) } } if (!itemsMap.containsKey(toodledoItem.FOLDER)) { itemsMap.put(toodledoItem.FOLDER, mutableListOf<TodoistItem>()) } itemsMap.get(toodledoItem.FOLDER)?.add(item) } return itemsMap } /** * Map from Toodledo repeat strings to something Todoist can parse */ fun convertToodledoRepeat(repeat: String?): String { var retval = repeat if (repeat == "Yearly") { retval = "every year" } if (repeat == "Semiannually") { retval = "every 6 months" } if (retval == null) { retval = "" } return retval } fun convertToodledoTaskAndTags(task: String?, tag: String?): String { var retval = "" retval += task if (tag != null) { val tags = tag.split(",") for (currentTag in tags) { if (currentTag.trim() != "") { retval += " @" + currentTag.trim() } } } return retval } fun convertToodledoPriority(priority: String?): String { var retval = "4" if (priority == "1") { retval = "3" } if (priority == "2") { retval = "2" } if (priority == "3") { retval = "1" } return retval } class TodoistItem(content: String, priority: String, date: String, note: String) { val taskLineItem = TodoistLineItemJava() var noteLineItem: TodoistLineItemJava? = null init { taskLineItem.TYPE = "task" taskLineItem.CONTENT = content taskLineItem.PRIORITY = priority taskLineItem.INDENT = "1" taskLineItem.AUTHOR = "" taskLineItem.RESPONSIBLE = "" taskLineItem.DATE = date taskLineItem.DATE_LANG = "en" taskLineItem.TIMEZONE = "Europe/Copenhagen" if (note != "") { noteLineItem = TodoistLineItemJava() noteLineItem!!.TYPE = "note" noteLineItem!!.CONTENT = note noteLineItem!!.PRIORITY = "" noteLineItem!!.INDENT = "" noteLineItem!!.AUTHOR = "" noteLineItem!!.RESPONSIBLE = "" noteLineItem!!.DATE = "" noteLineItem!!.DATE_LANG = "" noteLineItem!!.TIMEZONE = "" } } } private fun loadToodledoItems(f: File): MutableList<ToodledoItemJava> { val mapper = CsvMapper() val schema = mapper.schemaFor(ToodledoItemJava::class.java).withColumnSeparator(',').withUseHeader(true) val iter: Iterator<ToodledoItemJava> = mapper.readerFor(ToodledoItemJava::class.java).with(schema).readValues(f) val items: MutableList<ToodledoItemJava> = mutableListOf() for (value in iter) { items.add(value) } return items }
apache-2.0
da4310445388c2342ddbb03ebd7262e9
29.144186
156
0.612405
3.798945
false
false
false
false
schaal/ocreader
app/src/main/java/email/schaal/ocreader/service/SyncWorker.kt
1
1758
package email.schaal.ocreader.service import android.content.Context import androidx.lifecycle.LiveData import androidx.preference.PreferenceManager import androidx.work.* import email.schaal.ocreader.Preferences import email.schaal.ocreader.api.API import email.schaal.ocreader.util.LoginError class SyncWorker(context: Context, workerParams: WorkerParameters) : CoroutineWorker(context, workerParams) { companion object { const val KEY_SYNC_TYPE = "KEY_SYNC_TYPE" const val KEY_EXCEPTION = "KEY_EXCEPTION" const val WORK_ID = "WORK_ID_SYNC" fun sync(context: Context, syncType: SyncType): LiveData<WorkInfo> { val workManager = WorkManager.getInstance(context) val syncWork = OneTimeWorkRequestBuilder<SyncWorker>() .setInputData(workDataOf(KEY_SYNC_TYPE to syncType.action)) .build() workManager.enqueueUniqueWork(WORK_ID, ExistingWorkPolicy.KEEP, syncWork) return workManager.getWorkInfoByIdLiveData(syncWork.id) } fun getLiveData(context: Context): LiveData<List<WorkInfo>> { return WorkManager.getInstance(context).getWorkInfosForUniqueWorkLiveData(WORK_ID) } } override suspend fun doWork(): Result { val syncType: SyncType = SyncType[inputData.getString(KEY_SYNC_TYPE)] ?: SyncType.FULL_SYNC return try { API(applicationContext).sync(syncType) Result.success() } catch (e: Throwable) { e.printStackTrace() Result.failure( workDataOf( KEY_EXCEPTION to LoginError.getError( applicationContext, e).message ) ) } } }
gpl-3.0
97cf4fbad235ae448ffb2e515adb783d
36.425532
109
0.653584
4.896936
false
false
false
false
GeoffreyMetais/vlc-android
application/vlc-android/src/org/videolan/vlc/StoragesMonitor.kt
1
3098
package org.videolan.vlc import android.content.BroadcastReceiver import android.content.ComponentName import android.content.Context import android.content.Intent import android.content.pm.PackageManager import android.net.Uri import android.text.TextUtils import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.channels.actor import kotlinx.coroutines.delay import org.videolan.medialibrary.interfaces.Medialibrary import org.videolan.tools.AppScope import org.videolan.vlc.gui.DialogActivity import org.videolan.resources.util.getFromMl import org.videolan.tools.isAppStarted import org.videolan.vlc.util.scanAllowed private const val TAG = "VLC/StoragesMonitor" class StoragesMonitor : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { val action = intent.action ?: return if (!isAppStarted()) when (action) { Intent.ACTION_MEDIA_MOUNTED -> intent.data?.let { actor.offer(Mount(context, it)) } Intent.ACTION_MEDIA_UNMOUNTED -> intent.data?.let { actor.offer(Unmount(context, it)) } else -> return } } private val actor = AppScope.actor<MediaEvent>(capacity = Channel.UNLIMITED) { for (action in channel) when (action){ is Mount -> { if (TextUtils.isEmpty(action.uuid)) return@actor if (action.path.scanAllowed()) { val isNew = action.ctx.getFromMl { val isNewForML = !isDeviceKnown(action.uuid, action.path, true) addDevice(action.uuid, action.path, true) isNewForML } if (isNew) { val intent = Intent(action.ctx, DialogActivity::class.java).apply { setAction(DialogActivity.KEY_DEVICE) putExtra(DialogActivity.EXTRA_PATH, action.path) putExtra(DialogActivity.EXTRA_UUID, action.uuid) putExtra(DialogActivity.EXTRA_SCAN, isNew) addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) } action.ctx.startActivity(intent) } } } is Unmount -> { delay(100L) Medialibrary.getInstance().removeDevice(action.uuid, action.path) } } } } private sealed class MediaEvent(val ctx: Context) private class Mount(ctx: Context, val uri : Uri, val path : String = uri.path!!, val uuid : String = uri.lastPathSegment!!) : MediaEvent(ctx) private class Unmount(ctx: Context, val uri : Uri, val path : String = uri.path!!, val uuid : String = uri.lastPathSegment!!) : MediaEvent(ctx) fun Context.enableStorageMonitoring() { val componentName = ComponentName(applicationContext, StoragesMonitor::class.java) applicationContext.packageManager.setComponentEnabledSetting(componentName, PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP) }
gpl-2.0
1230e1635ce4355840b85bcefc2d2046
41.452055
143
0.63428
4.665663
false
false
false
false
cbeust/kobalt
modules/kobalt-plugin-api/src/main/kotlin/com/beust/kobalt/internal/JvmCompiler.kt
2
1886
package com.beust.kobalt.internal import com.beust.kobalt.KobaltException import com.beust.kobalt.TaskResult import com.beust.kobalt.api.CompilerActionInfo import com.beust.kobalt.api.KobaltContext import com.beust.kobalt.api.Project import com.beust.kobalt.maven.DependencyManager import com.google.inject.Inject import java.io.File import java.util.* /** * Abstract the compilation process by running an ICompilerAction parameterized by a CompilerActionInfo. * Also validates the classpath and run all the contributors. */ class JvmCompiler @Inject constructor(val dependencyManager: DependencyManager) { /** * Take the given CompilerActionInfo and enrich it with all the applicable contributors and * then pass it to the ICompilerAction. */ fun doCompile(project: Project?, context: KobaltContext?, action: ICompilerAction, info: CompilerActionInfo, flags: List<String>): TaskResult { // Dependencies val allDependencies = (info.dependencies + dependencyManager.calculateDependencies(project, context!!, passedDependencies = info.dependencies)) .distinct() // Plugins that add flags to the compiler val contributorFlags : List<String> = if (project != null) flags else emptyList() val addedFlags = contributorFlags + ArrayList(info.compilerArgs) validateClasspath(allDependencies.map { it.jarFile.get().absolutePath }) return action.compile(project, info.copy(dependencies = allDependencies, compilerArgs = addedFlags)) } private fun validateClasspath(cp: List<String>) { cp.forEach { if (! File(it).exists()) { throw KobaltException("Invalid classpath: couldn't find $it") } } } } interface ICompilerAction { fun compile(project: Project?, info: CompilerActionInfo): TaskResult }
apache-2.0
3029b910823d6579eefc3994ef46c21f
36.74
112
0.71421
4.715
false
false
false
false
REBOOTERS/AndroidAnimationExercise
game/src/main/java/com/engineer/android/game/ui/Game2048Activity.kt
1
6415
package com.engineer.android.game.ui import android.annotation.SuppressLint import android.content.pm.ActivityInfo import android.content.res.Configuration import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.preference.PreferenceManager import android.provider.Settings import android.util.Log import android.view.MotionEvent import android.view.Window import android.view.WindowManager import android.webkit.WebSettings import android.webkit.WebView import android.widget.Toast import com.engineer.android.game.R import java.util.* class Game2048Activity : AppCompatActivity() { private val MAIN_ACTIVITY_TAG = "2048_MainActivity" private lateinit var mWebView: WebView private var mLastBackPress: Long = 0 private val mBackPressThreshold: Long = 3500 private val IS_FULLSCREEN_PREF = "is_fullscreen_pref" private var mLastTouch: Long = 0 private val mTouchThreshold: Long = 2000 private var pressBackToast: Toast? = null @SuppressLint("SetJavaScriptEnabled", "ShowToast", "ClickableViewAccessibility") override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) // Don't show an action bar or title requestWindowFeature(Window.FEATURE_NO_TITLE) // Enable hardware acceleration window.setFlags( WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED, WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED ) // Apply previous setting about showing status bar or not applyFullScreen(isFullScreen()) // Check if screen rotation is locked in settings var isOrientationEnabled = false try { isOrientationEnabled = Settings.System.getInt( contentResolver, Settings.System.ACCELEROMETER_ROTATION ) == 1 } catch (e: Settings.SettingNotFoundException) { Log.d(MAIN_ACTIVITY_TAG, "Settings could not be loaded") } // If rotation isn't locked and it's a LARGE screen then add orientation changes based on sensor val screenLayout = resources.configuration.screenLayout and Configuration.SCREENLAYOUT_SIZE_MASK if ((screenLayout == Configuration.SCREENLAYOUT_SIZE_LARGE || screenLayout == Configuration.SCREENLAYOUT_SIZE_XLARGE) && isOrientationEnabled) { requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_SENSOR } setContentView(R.layout.activity_game2048) // val changeLog = DialogChangeLog.newInstance(this) // if (changeLog.isFirstRun()) { // changeLog.getLogDialog().show() // } // Load webview with game mWebView = findViewById(R.id.mainWebView) val settings = mWebView.settings settings.javaScriptEnabled = true settings.domStorageEnabled = true settings.databaseEnabled = true settings.setRenderPriority(WebSettings.RenderPriority.HIGH) settings.databasePath = filesDir.parentFile.path + "/databases" // If there is a previous instance restore it in the webview if (savedInstanceState != null) { mWebView.restoreState(savedInstanceState) } else { // Load webview with current Locale language mWebView.loadUrl("file:///android_asset/2048/index.html?lang=" + Locale.getDefault().language) } // Toast.makeText(application, R.string.toggle_fullscreen, Toast.LENGTH_SHORT).show() // Set fullscreen toggle on webview LongClick mWebView.setOnTouchListener { v, event -> // Implement a long touch action by comparing // time between action up and action down val currentTime = System.currentTimeMillis() if (event.action == MotionEvent.ACTION_UP && Math.abs(currentTime - mLastTouch) > mTouchThreshold) { val toggledFullScreen = !isFullScreen() saveFullScreen(toggledFullScreen) applyFullScreen(toggledFullScreen) } else if (event.action == MotionEvent.ACTION_DOWN) { mLastTouch = currentTime } // return so that the event isn't consumed but used // by the webview as well false } pressBackToast = Toast.makeText( applicationContext, R.string.press_back_again_to_exit, Toast.LENGTH_SHORT ) } override fun onResume() { super.onResume() mWebView.loadUrl("file:///android_asset/2048/index.html?lang=" + Locale.getDefault().language) } override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) mWebView.saveState(outState) } /** * Saves the full screen setting in the SharedPreferences * * @param isFullScreen boolean value */ private fun saveFullScreen(isFullScreen: Boolean) { // save in preferences val editor = PreferenceManager.getDefaultSharedPreferences(this).edit() editor.putBoolean(IS_FULLSCREEN_PREF, isFullScreen) editor.apply() } private fun isFullScreen(): Boolean { return PreferenceManager.getDefaultSharedPreferences(this).getBoolean( IS_FULLSCREEN_PREF, true ) } /** * Toggles the activity's fullscreen mode by setting the corresponding window flag * * @param isFullScreen boolean value */ private fun applyFullScreen(isFullScreen: Boolean) { if (isFullScreen) { window.clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN) } else { window.setFlags( WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN ) } } /** * Prevents app from closing on pressing back button accidentally. * mBackPressThreshold specifies the maximum delay (ms) between two consecutive backpress to * quit the app. */ override fun onBackPressed() { val currentTime = System.currentTimeMillis() if (Math.abs(currentTime - mLastBackPress) > mBackPressThreshold) { pressBackToast!!.show() mLastBackPress = currentTime } else { pressBackToast!!.cancel() super.onBackPressed() } } }
apache-2.0
7f72e0f376d4b66d89e5f7b880aa074b
35.448864
152
0.66173
5.144346
false
false
false
false
hewking/HUILibrary
app/src/main/java/com/hewking/custom/CircleView.kt
1
2310
package com.hewking.custom import android.content.Context import android.graphics.Canvas import android.graphics.Color import android.graphics.Paint import android.util.AttributeSet import android.view.View import com.hewking.custom.util.dp2px /** * 类的描述: * 创建人员:hewking * 创建时间:2018/4/6 * 修改人员:hewking * 修改时间:2018/4/6 * 修改备注: * Version: 1.0.0 */ class CircleView(ctx : Context, attrs : AttributeSet) : View(ctx,attrs) { private var mCircleColor : Int = 0 private var mRadius = 0f private val mPaint by lazy { Paint().apply { isAntiAlias = true style = Paint.Style.FILL } } init { val style = ctx.obtainStyledAttributes(attrs,R.styleable.CircleView) mCircleColor = style.getColor(R.styleable.CircleView_color,Color.RED) mRadius = style.getDimension(R.styleable.CircleView_raduis,dp2px(20f).toFloat()) style.recycle() mPaint.color = mCircleColor } override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { /** * 处理 wrap_content 否则 wrap_content 的大小 与 match_parent 一样 * 父view 的可利用空间大小 */ val widthMode = MeasureSpec.getMode(widthMeasureSpec) val heightMode = MeasureSpec.getMode(heightMeasureSpec) val widthSpecSize = MeasureSpec.getSize(widthMeasureSpec) val heightSpecSize = MeasureSpec.getSize(heightMeasureSpec) val defaultHeight = paddingLeft * 2 + 2 * mRadius.toInt() super.onMeasure(widthMeasureSpec, heightMeasureSpec) if (widthMode == MeasureSpec.AT_MOST && heightMode == MeasureSpec.AT_MOST) { setMeasuredDimension(defaultHeight,defaultHeight) } else if (widthMode == MeasureSpec.AT_MOST) { setMeasuredDimension(defaultHeight,heightSpecSize) } else if (heightMode == MeasureSpec.AT_MOST) { setMeasuredDimension(widthSpecSize,defaultHeight) } } override fun onDraw(canvas: Canvas?) { // 处理 padding canvas?.translate(paddingLeft + mRadius,paddingLeft + mRadius) canvas?.drawCircle(0f,0f,mRadius,mPaint) } }
mit
aa14366c9e8c8d49ccea66327fbb0500
30.028986
88
0.649909
4.389662
false
false
false
false
is00hcw/anko
dsl/testData/functional/sdk21/ViewTest.kt
2
52802
public object `$$Anko$Factories$Sdk21View` { public val MEDIA_ROUTE_BUTTON = { ctx: Context -> android.app.MediaRouteButton(ctx) } public val GESTURE_OVERLAY_VIEW = { ctx: Context -> android.gesture.GestureOverlayView(ctx) } public val EXTRACT_EDIT_TEXT = { ctx: Context -> android.inputmethodservice.ExtractEditText(ctx) } public val TV_VIEW = { ctx: Context -> android.media.tv.TvView(ctx) } public val G_L_SURFACE_VIEW = { ctx: Context -> android.opengl.GLSurfaceView(ctx) } public val SURFACE_VIEW = { ctx: Context -> android.view.SurfaceView(ctx) } public val TEXTURE_VIEW = { ctx: Context -> android.view.TextureView(ctx) } public val VIEW = { ctx: Context -> android.view.View(ctx) } public val VIEW_STUB = { ctx: Context -> android.view.ViewStub(ctx) } public val ADAPTER_VIEW_FLIPPER = { ctx: Context -> android.widget.AdapterViewFlipper(ctx) } public val ANALOG_CLOCK = { ctx: Context -> android.widget.AnalogClock(ctx) } public val AUTO_COMPLETE_TEXT_VIEW = { ctx: Context -> android.widget.AutoCompleteTextView(ctx) } public val BUTTON = { ctx: Context -> android.widget.Button(ctx) } public val CALENDAR_VIEW = { ctx: Context -> android.widget.CalendarView(ctx) } public val CHECK_BOX = { ctx: Context -> android.widget.CheckBox(ctx) } public val CHECKED_TEXT_VIEW = { ctx: Context -> android.widget.CheckedTextView(ctx) } public val CHRONOMETER = { ctx: Context -> android.widget.Chronometer(ctx) } public val DATE_PICKER = { ctx: Context -> android.widget.DatePicker(ctx) } public val DIALER_FILTER = { ctx: Context -> android.widget.DialerFilter(ctx) } public val DIGITAL_CLOCK = { ctx: Context -> android.widget.DigitalClock(ctx) } public val EDIT_TEXT = { ctx: Context -> android.widget.EditText(ctx) } public val EXPANDABLE_LIST_VIEW = { ctx: Context -> android.widget.ExpandableListView(ctx) } public val IMAGE_BUTTON = { ctx: Context -> android.widget.ImageButton(ctx) } public val IMAGE_VIEW = { ctx: Context -> android.widget.ImageView(ctx) } public val LIST_VIEW = { ctx: Context -> android.widget.ListView(ctx) } public val MULTI_AUTO_COMPLETE_TEXT_VIEW = { ctx: Context -> android.widget.MultiAutoCompleteTextView(ctx) } public val NUMBER_PICKER = { ctx: Context -> android.widget.NumberPicker(ctx) } public val PROGRESS_BAR = { ctx: Context -> android.widget.ProgressBar(ctx) } public val QUICK_CONTACT_BADGE = { ctx: Context -> android.widget.QuickContactBadge(ctx) } public val RADIO_BUTTON = { ctx: Context -> android.widget.RadioButton(ctx) } public val RATING_BAR = { ctx: Context -> android.widget.RatingBar(ctx) } public val SEARCH_VIEW = { ctx: Context -> android.widget.SearchView(ctx) } public val SEEK_BAR = { ctx: Context -> android.widget.SeekBar(ctx) } public val SLIDING_DRAWER = { ctx: Context -> android.widget.SlidingDrawer(ctx, null) } public val SPACE = { ctx: Context -> android.widget.Space(ctx) } public val SPINNER = { ctx: Context -> android.widget.Spinner(ctx) } public val STACK_VIEW = { ctx: Context -> android.widget.StackView(ctx) } public val SWITCH = { ctx: Context -> android.widget.Switch(ctx) } public val TAB_HOST = { ctx: Context -> android.widget.TabHost(ctx) } public val TAB_WIDGET = { ctx: Context -> android.widget.TabWidget(ctx) } public val TEXT_CLOCK = { ctx: Context -> android.widget.TextClock(ctx) } public val TEXT_VIEW = { ctx: Context -> android.widget.TextView(ctx) } public val TIME_PICKER = { ctx: Context -> android.widget.TimePicker(ctx) } public val TOGGLE_BUTTON = { ctx: Context -> android.widget.ToggleButton(ctx) } public val TWO_LINE_LIST_ITEM = { ctx: Context -> android.widget.TwoLineListItem(ctx) } public val VIDEO_VIEW = { ctx: Context -> android.widget.VideoView(ctx) } public val VIEW_FLIPPER = { ctx: Context -> android.widget.ViewFlipper(ctx) } public val ZOOM_BUTTON = { ctx: Context -> android.widget.ZoomButton(ctx) } public val ZOOM_CONTROLS = { ctx: Context -> android.widget.ZoomControls(ctx) } } public inline fun ViewManager.mediaRouteButton(): android.app.MediaRouteButton = mediaRouteButton({}) public inline fun ViewManager.mediaRouteButton(init: android.app.MediaRouteButton.() -> Unit): android.app.MediaRouteButton { return ankoView(`$$Anko$Factories$Sdk21View`.MEDIA_ROUTE_BUTTON) { init() } } public inline fun ViewManager.gestureOverlayView(): android.gesture.GestureOverlayView = gestureOverlayView({}) public inline fun ViewManager.gestureOverlayView(init: android.gesture.GestureOverlayView.() -> Unit): android.gesture.GestureOverlayView { return ankoView(`$$Anko$Factories$Sdk21View`.GESTURE_OVERLAY_VIEW) { init() } } public inline fun Context.gestureOverlayView(): android.gesture.GestureOverlayView = gestureOverlayView({}) public inline fun Context.gestureOverlayView(init: android.gesture.GestureOverlayView.() -> Unit): android.gesture.GestureOverlayView { return ankoView(`$$Anko$Factories$Sdk21View`.GESTURE_OVERLAY_VIEW) { init() } } public inline fun Activity.gestureOverlayView(): android.gesture.GestureOverlayView = gestureOverlayView({}) public inline fun Activity.gestureOverlayView(init: android.gesture.GestureOverlayView.() -> Unit): android.gesture.GestureOverlayView { return ankoView(`$$Anko$Factories$Sdk21View`.GESTURE_OVERLAY_VIEW) { init() } } public inline fun ViewManager.extractEditText(): android.inputmethodservice.ExtractEditText = extractEditText({}) public inline fun ViewManager.extractEditText(init: android.inputmethodservice.ExtractEditText.() -> Unit): android.inputmethodservice.ExtractEditText { return ankoView(`$$Anko$Factories$Sdk21View`.EXTRACT_EDIT_TEXT) { init() } } public inline fun ViewManager.tvView(): android.media.tv.TvView = tvView({}) public inline fun ViewManager.tvView(init: android.media.tv.TvView.() -> Unit): android.media.tv.TvView { return ankoView(`$$Anko$Factories$Sdk21View`.TV_VIEW) { init() } } public inline fun Context.tvView(): android.media.tv.TvView = tvView({}) public inline fun Context.tvView(init: android.media.tv.TvView.() -> Unit): android.media.tv.TvView { return ankoView(`$$Anko$Factories$Sdk21View`.TV_VIEW) { init() } } public inline fun Activity.tvView(): android.media.tv.TvView = tvView({}) public inline fun Activity.tvView(init: android.media.tv.TvView.() -> Unit): android.media.tv.TvView { return ankoView(`$$Anko$Factories$Sdk21View`.TV_VIEW) { init() } } public inline fun ViewManager.gLSurfaceView(): android.opengl.GLSurfaceView = gLSurfaceView({}) public inline fun ViewManager.gLSurfaceView(init: android.opengl.GLSurfaceView.() -> Unit): android.opengl.GLSurfaceView { return ankoView(`$$Anko$Factories$Sdk21View`.G_L_SURFACE_VIEW) { init() } } public inline fun ViewManager.surfaceView(): android.view.SurfaceView = surfaceView({}) public inline fun ViewManager.surfaceView(init: android.view.SurfaceView.() -> Unit): android.view.SurfaceView { return ankoView(`$$Anko$Factories$Sdk21View`.SURFACE_VIEW) { init() } } public inline fun ViewManager.textureView(): android.view.TextureView = textureView({}) public inline fun ViewManager.textureView(init: android.view.TextureView.() -> Unit): android.view.TextureView { return ankoView(`$$Anko$Factories$Sdk21View`.TEXTURE_VIEW) { init() } } public inline fun ViewManager.view(): android.view.View = view({}) public inline fun ViewManager.view(init: android.view.View.() -> Unit): android.view.View { return ankoView(`$$Anko$Factories$Sdk21View`.VIEW) { init() } } public inline fun ViewManager.viewStub(): android.view.ViewStub = viewStub({}) public inline fun ViewManager.viewStub(init: android.view.ViewStub.() -> Unit): android.view.ViewStub { return ankoView(`$$Anko$Factories$Sdk21View`.VIEW_STUB) { init() } } public inline fun ViewManager.adapterViewFlipper(): android.widget.AdapterViewFlipper = adapterViewFlipper({}) public inline fun ViewManager.adapterViewFlipper(init: android.widget.AdapterViewFlipper.() -> Unit): android.widget.AdapterViewFlipper { return ankoView(`$$Anko$Factories$Sdk21View`.ADAPTER_VIEW_FLIPPER) { init() } } public inline fun Context.adapterViewFlipper(): android.widget.AdapterViewFlipper = adapterViewFlipper({}) public inline fun Context.adapterViewFlipper(init: android.widget.AdapterViewFlipper.() -> Unit): android.widget.AdapterViewFlipper { return ankoView(`$$Anko$Factories$Sdk21View`.ADAPTER_VIEW_FLIPPER) { init() } } public inline fun Activity.adapterViewFlipper(): android.widget.AdapterViewFlipper = adapterViewFlipper({}) public inline fun Activity.adapterViewFlipper(init: android.widget.AdapterViewFlipper.() -> Unit): android.widget.AdapterViewFlipper { return ankoView(`$$Anko$Factories$Sdk21View`.ADAPTER_VIEW_FLIPPER) { init() } } public inline fun ViewManager.analogClock(): android.widget.AnalogClock = analogClock({}) public inline fun ViewManager.analogClock(init: android.widget.AnalogClock.() -> Unit): android.widget.AnalogClock { return ankoView(`$$Anko$Factories$Sdk21View`.ANALOG_CLOCK) { init() } } public inline fun ViewManager.autoCompleteTextView(): android.widget.AutoCompleteTextView = autoCompleteTextView({}) public inline fun ViewManager.autoCompleteTextView(init: android.widget.AutoCompleteTextView.() -> Unit): android.widget.AutoCompleteTextView { return ankoView(`$$Anko$Factories$Sdk21View`.AUTO_COMPLETE_TEXT_VIEW) { init() } } public inline fun ViewManager.button(): android.widget.Button = button({}) public inline fun ViewManager.button(init: android.widget.Button.() -> Unit): android.widget.Button { return ankoView(`$$Anko$Factories$Sdk21View`.BUTTON) { init() } } public inline fun ViewManager.button(text: CharSequence?): android.widget.Button { return ankoView(`$$Anko$Factories$Sdk21View`.BUTTON) { setText(text) } } public inline fun ViewManager.button(text: CharSequence?, init: android.widget.Button.() -> Unit): android.widget.Button { return ankoView(`$$Anko$Factories$Sdk21View`.BUTTON) { init() setText(text) } } public inline fun ViewManager.button(text: Int): android.widget.Button { return ankoView(`$$Anko$Factories$Sdk21View`.BUTTON) { setText(text) } } public inline fun ViewManager.button(text: Int, init: android.widget.Button.() -> Unit): android.widget.Button { return ankoView(`$$Anko$Factories$Sdk21View`.BUTTON) { init() setText(text) } } public inline fun ViewManager.calendarView(): android.widget.CalendarView = calendarView({}) public inline fun ViewManager.calendarView(init: android.widget.CalendarView.() -> Unit): android.widget.CalendarView { return ankoView(`$$Anko$Factories$Sdk21View`.CALENDAR_VIEW) { init() } } public inline fun Context.calendarView(): android.widget.CalendarView = calendarView({}) public inline fun Context.calendarView(init: android.widget.CalendarView.() -> Unit): android.widget.CalendarView { return ankoView(`$$Anko$Factories$Sdk21View`.CALENDAR_VIEW) { init() } } public inline fun Activity.calendarView(): android.widget.CalendarView = calendarView({}) public inline fun Activity.calendarView(init: android.widget.CalendarView.() -> Unit): android.widget.CalendarView { return ankoView(`$$Anko$Factories$Sdk21View`.CALENDAR_VIEW) { init() } } public inline fun ViewManager.checkBox(): android.widget.CheckBox = checkBox({}) public inline fun ViewManager.checkBox(init: android.widget.CheckBox.() -> Unit): android.widget.CheckBox { return ankoView(`$$Anko$Factories$Sdk21View`.CHECK_BOX) { init() } } public inline fun ViewManager.checkBox(text: CharSequence?): android.widget.CheckBox { return ankoView(`$$Anko$Factories$Sdk21View`.CHECK_BOX) { setText(text) } } public inline fun ViewManager.checkBox(text: CharSequence?, init: android.widget.CheckBox.() -> Unit): android.widget.CheckBox { return ankoView(`$$Anko$Factories$Sdk21View`.CHECK_BOX) { init() setText(text) } } public inline fun ViewManager.checkBox(text: Int): android.widget.CheckBox { return ankoView(`$$Anko$Factories$Sdk21View`.CHECK_BOX) { setText(text) } } public inline fun ViewManager.checkBox(text: Int, init: android.widget.CheckBox.() -> Unit): android.widget.CheckBox { return ankoView(`$$Anko$Factories$Sdk21View`.CHECK_BOX) { init() setText(text) } } public inline fun ViewManager.checkBox(text: CharSequence?, checked: Boolean): android.widget.CheckBox { return ankoView(`$$Anko$Factories$Sdk21View`.CHECK_BOX) { setText(text) setChecked(checked) } } public inline fun ViewManager.checkBox(text: CharSequence?, checked: Boolean, init: android.widget.CheckBox.() -> Unit): android.widget.CheckBox { return ankoView(`$$Anko$Factories$Sdk21View`.CHECK_BOX) { init() setText(text) setChecked(checked) } } public inline fun ViewManager.checkBox(text: Int, checked: Boolean): android.widget.CheckBox { return ankoView(`$$Anko$Factories$Sdk21View`.CHECK_BOX) { setText(text) setChecked(checked) } } public inline fun ViewManager.checkBox(text: Int, checked: Boolean, init: android.widget.CheckBox.() -> Unit): android.widget.CheckBox { return ankoView(`$$Anko$Factories$Sdk21View`.CHECK_BOX) { init() setText(text) setChecked(checked) } } public inline fun ViewManager.checkedTextView(): android.widget.CheckedTextView = checkedTextView({}) public inline fun ViewManager.checkedTextView(init: android.widget.CheckedTextView.() -> Unit): android.widget.CheckedTextView { return ankoView(`$$Anko$Factories$Sdk21View`.CHECKED_TEXT_VIEW) { init() } } public inline fun ViewManager.chronometer(): android.widget.Chronometer = chronometer({}) public inline fun ViewManager.chronometer(init: android.widget.Chronometer.() -> Unit): android.widget.Chronometer { return ankoView(`$$Anko$Factories$Sdk21View`.CHRONOMETER) { init() } } public inline fun ViewManager.datePicker(): android.widget.DatePicker = datePicker({}) public inline fun ViewManager.datePicker(init: android.widget.DatePicker.() -> Unit): android.widget.DatePicker { return ankoView(`$$Anko$Factories$Sdk21View`.DATE_PICKER) { init() } } public inline fun Context.datePicker(): android.widget.DatePicker = datePicker({}) public inline fun Context.datePicker(init: android.widget.DatePicker.() -> Unit): android.widget.DatePicker { return ankoView(`$$Anko$Factories$Sdk21View`.DATE_PICKER) { init() } } public inline fun Activity.datePicker(): android.widget.DatePicker = datePicker({}) public inline fun Activity.datePicker(init: android.widget.DatePicker.() -> Unit): android.widget.DatePicker { return ankoView(`$$Anko$Factories$Sdk21View`.DATE_PICKER) { init() } } public inline fun ViewManager.dialerFilter(): android.widget.DialerFilter = dialerFilter({}) public inline fun ViewManager.dialerFilter(init: android.widget.DialerFilter.() -> Unit): android.widget.DialerFilter { return ankoView(`$$Anko$Factories$Sdk21View`.DIALER_FILTER) { init() } } public inline fun Context.dialerFilter(): android.widget.DialerFilter = dialerFilter({}) public inline fun Context.dialerFilter(init: android.widget.DialerFilter.() -> Unit): android.widget.DialerFilter { return ankoView(`$$Anko$Factories$Sdk21View`.DIALER_FILTER) { init() } } public inline fun Activity.dialerFilter(): android.widget.DialerFilter = dialerFilter({}) public inline fun Activity.dialerFilter(init: android.widget.DialerFilter.() -> Unit): android.widget.DialerFilter { return ankoView(`$$Anko$Factories$Sdk21View`.DIALER_FILTER) { init() } } public inline fun ViewManager.digitalClock(): android.widget.DigitalClock = digitalClock({}) public inline fun ViewManager.digitalClock(init: android.widget.DigitalClock.() -> Unit): android.widget.DigitalClock { return ankoView(`$$Anko$Factories$Sdk21View`.DIGITAL_CLOCK) { init() } } public inline fun ViewManager.editText(): android.widget.EditText = editText({}) public inline fun ViewManager.editText(init: android.widget.EditText.() -> Unit): android.widget.EditText { return ankoView(`$$Anko$Factories$Sdk21View`.EDIT_TEXT) { init() } } public inline fun ViewManager.editText(text: CharSequence?): android.widget.EditText { return ankoView(`$$Anko$Factories$Sdk21View`.EDIT_TEXT) { setText(text) } } public inline fun ViewManager.editText(text: CharSequence?, init: android.widget.EditText.() -> Unit): android.widget.EditText { return ankoView(`$$Anko$Factories$Sdk21View`.EDIT_TEXT) { init() setText(text) } } public inline fun ViewManager.editText(text: Int): android.widget.EditText { return ankoView(`$$Anko$Factories$Sdk21View`.EDIT_TEXT) { setText(text) } } public inline fun ViewManager.editText(text: Int, init: android.widget.EditText.() -> Unit): android.widget.EditText { return ankoView(`$$Anko$Factories$Sdk21View`.EDIT_TEXT) { init() setText(text) } } public inline fun ViewManager.expandableListView(): android.widget.ExpandableListView = expandableListView({}) public inline fun ViewManager.expandableListView(init: android.widget.ExpandableListView.() -> Unit): android.widget.ExpandableListView { return ankoView(`$$Anko$Factories$Sdk21View`.EXPANDABLE_LIST_VIEW) { init() } } public inline fun Context.expandableListView(): android.widget.ExpandableListView = expandableListView({}) public inline fun Context.expandableListView(init: android.widget.ExpandableListView.() -> Unit): android.widget.ExpandableListView { return ankoView(`$$Anko$Factories$Sdk21View`.EXPANDABLE_LIST_VIEW) { init() } } public inline fun Activity.expandableListView(): android.widget.ExpandableListView = expandableListView({}) public inline fun Activity.expandableListView(init: android.widget.ExpandableListView.() -> Unit): android.widget.ExpandableListView { return ankoView(`$$Anko$Factories$Sdk21View`.EXPANDABLE_LIST_VIEW) { init() } } public inline fun ViewManager.imageButton(): android.widget.ImageButton = imageButton({}) public inline fun ViewManager.imageButton(init: android.widget.ImageButton.() -> Unit): android.widget.ImageButton { return ankoView(`$$Anko$Factories$Sdk21View`.IMAGE_BUTTON) { init() } } public inline fun ViewManager.imageButton(imageDrawable: android.graphics.drawable.Drawable?): android.widget.ImageButton { return ankoView(`$$Anko$Factories$Sdk21View`.IMAGE_BUTTON) { setImageDrawable(imageDrawable) } } public inline fun ViewManager.imageButton(imageDrawable: android.graphics.drawable.Drawable?, init: android.widget.ImageButton.() -> Unit): android.widget.ImageButton { return ankoView(`$$Anko$Factories$Sdk21View`.IMAGE_BUTTON) { init() setImageDrawable(imageDrawable) } } public inline fun ViewManager.imageButton(imageResource: Int): android.widget.ImageButton { return ankoView(`$$Anko$Factories$Sdk21View`.IMAGE_BUTTON) { setImageResource(imageResource) } } public inline fun ViewManager.imageButton(imageResource: Int, init: android.widget.ImageButton.() -> Unit): android.widget.ImageButton { return ankoView(`$$Anko$Factories$Sdk21View`.IMAGE_BUTTON) { init() setImageResource(imageResource) } } public inline fun ViewManager.imageView(): android.widget.ImageView = imageView({}) public inline fun ViewManager.imageView(init: android.widget.ImageView.() -> Unit): android.widget.ImageView { return ankoView(`$$Anko$Factories$Sdk21View`.IMAGE_VIEW) { init() } } public inline fun ViewManager.imageView(imageDrawable: android.graphics.drawable.Drawable?): android.widget.ImageView { return ankoView(`$$Anko$Factories$Sdk21View`.IMAGE_VIEW) { setImageDrawable(imageDrawable) } } public inline fun ViewManager.imageView(imageDrawable: android.graphics.drawable.Drawable?, init: android.widget.ImageView.() -> Unit): android.widget.ImageView { return ankoView(`$$Anko$Factories$Sdk21View`.IMAGE_VIEW) { init() setImageDrawable(imageDrawable) } } public inline fun ViewManager.imageView(imageResource: Int): android.widget.ImageView { return ankoView(`$$Anko$Factories$Sdk21View`.IMAGE_VIEW) { setImageResource(imageResource) } } public inline fun ViewManager.imageView(imageResource: Int, init: android.widget.ImageView.() -> Unit): android.widget.ImageView { return ankoView(`$$Anko$Factories$Sdk21View`.IMAGE_VIEW) { init() setImageResource(imageResource) } } public inline fun ViewManager.listView(): android.widget.ListView = listView({}) public inline fun ViewManager.listView(init: android.widget.ListView.() -> Unit): android.widget.ListView { return ankoView(`$$Anko$Factories$Sdk21View`.LIST_VIEW) { init() } } public inline fun Context.listView(): android.widget.ListView = listView({}) public inline fun Context.listView(init: android.widget.ListView.() -> Unit): android.widget.ListView { return ankoView(`$$Anko$Factories$Sdk21View`.LIST_VIEW) { init() } } public inline fun Activity.listView(): android.widget.ListView = listView({}) public inline fun Activity.listView(init: android.widget.ListView.() -> Unit): android.widget.ListView { return ankoView(`$$Anko$Factories$Sdk21View`.LIST_VIEW) { init() } } public inline fun ViewManager.multiAutoCompleteTextView(): android.widget.MultiAutoCompleteTextView = multiAutoCompleteTextView({}) public inline fun ViewManager.multiAutoCompleteTextView(init: android.widget.MultiAutoCompleteTextView.() -> Unit): android.widget.MultiAutoCompleteTextView { return ankoView(`$$Anko$Factories$Sdk21View`.MULTI_AUTO_COMPLETE_TEXT_VIEW) { init() } } public inline fun ViewManager.numberPicker(): android.widget.NumberPicker = numberPicker({}) public inline fun ViewManager.numberPicker(init: android.widget.NumberPicker.() -> Unit): android.widget.NumberPicker { return ankoView(`$$Anko$Factories$Sdk21View`.NUMBER_PICKER) { init() } } public inline fun Context.numberPicker(): android.widget.NumberPicker = numberPicker({}) public inline fun Context.numberPicker(init: android.widget.NumberPicker.() -> Unit): android.widget.NumberPicker { return ankoView(`$$Anko$Factories$Sdk21View`.NUMBER_PICKER) { init() } } public inline fun Activity.numberPicker(): android.widget.NumberPicker = numberPicker({}) public inline fun Activity.numberPicker(init: android.widget.NumberPicker.() -> Unit): android.widget.NumberPicker { return ankoView(`$$Anko$Factories$Sdk21View`.NUMBER_PICKER) { init() } } public inline fun ViewManager.progressBar(): android.widget.ProgressBar = progressBar({}) public inline fun ViewManager.progressBar(init: android.widget.ProgressBar.() -> Unit): android.widget.ProgressBar { return ankoView(`$$Anko$Factories$Sdk21View`.PROGRESS_BAR) { init() } } public inline fun ViewManager.quickContactBadge(): android.widget.QuickContactBadge = quickContactBadge({}) public inline fun ViewManager.quickContactBadge(init: android.widget.QuickContactBadge.() -> Unit): android.widget.QuickContactBadge { return ankoView(`$$Anko$Factories$Sdk21View`.QUICK_CONTACT_BADGE) { init() } } public inline fun ViewManager.radioButton(): android.widget.RadioButton = radioButton({}) public inline fun ViewManager.radioButton(init: android.widget.RadioButton.() -> Unit): android.widget.RadioButton { return ankoView(`$$Anko$Factories$Sdk21View`.RADIO_BUTTON) { init() } } public inline fun ViewManager.ratingBar(): android.widget.RatingBar = ratingBar({}) public inline fun ViewManager.ratingBar(init: android.widget.RatingBar.() -> Unit): android.widget.RatingBar { return ankoView(`$$Anko$Factories$Sdk21View`.RATING_BAR) { init() } } public inline fun ViewManager.searchView(): android.widget.SearchView = searchView({}) public inline fun ViewManager.searchView(init: android.widget.SearchView.() -> Unit): android.widget.SearchView { return ankoView(`$$Anko$Factories$Sdk21View`.SEARCH_VIEW) { init() } } public inline fun Context.searchView(): android.widget.SearchView = searchView({}) public inline fun Context.searchView(init: android.widget.SearchView.() -> Unit): android.widget.SearchView { return ankoView(`$$Anko$Factories$Sdk21View`.SEARCH_VIEW) { init() } } public inline fun Activity.searchView(): android.widget.SearchView = searchView({}) public inline fun Activity.searchView(init: android.widget.SearchView.() -> Unit): android.widget.SearchView { return ankoView(`$$Anko$Factories$Sdk21View`.SEARCH_VIEW) { init() } } public inline fun ViewManager.seekBar(): android.widget.SeekBar = seekBar({}) public inline fun ViewManager.seekBar(init: android.widget.SeekBar.() -> Unit): android.widget.SeekBar { return ankoView(`$$Anko$Factories$Sdk21View`.SEEK_BAR) { init() } } public inline fun ViewManager.slidingDrawer(): android.widget.SlidingDrawer = slidingDrawer({}) public inline fun ViewManager.slidingDrawer(init: android.widget.SlidingDrawer.() -> Unit): android.widget.SlidingDrawer { return ankoView(`$$Anko$Factories$Sdk21View`.SLIDING_DRAWER) { init() } } public inline fun Context.slidingDrawer(): android.widget.SlidingDrawer = slidingDrawer({}) public inline fun Context.slidingDrawer(init: android.widget.SlidingDrawer.() -> Unit): android.widget.SlidingDrawer { return ankoView(`$$Anko$Factories$Sdk21View`.SLIDING_DRAWER) { init() } } public inline fun Activity.slidingDrawer(): android.widget.SlidingDrawer = slidingDrawer({}) public inline fun Activity.slidingDrawer(init: android.widget.SlidingDrawer.() -> Unit): android.widget.SlidingDrawer { return ankoView(`$$Anko$Factories$Sdk21View`.SLIDING_DRAWER) { init() } } public inline fun ViewManager.space(): android.widget.Space = space({}) public inline fun ViewManager.space(init: android.widget.Space.() -> Unit): android.widget.Space { return ankoView(`$$Anko$Factories$Sdk21View`.SPACE) { init() } } public inline fun ViewManager.spinner(): android.widget.Spinner = spinner({}) public inline fun ViewManager.spinner(init: android.widget.Spinner.() -> Unit): android.widget.Spinner { return ankoView(`$$Anko$Factories$Sdk21View`.SPINNER) { init() } } public inline fun Context.spinner(): android.widget.Spinner = spinner({}) public inline fun Context.spinner(init: android.widget.Spinner.() -> Unit): android.widget.Spinner { return ankoView(`$$Anko$Factories$Sdk21View`.SPINNER) { init() } } public inline fun Activity.spinner(): android.widget.Spinner = spinner({}) public inline fun Activity.spinner(init: android.widget.Spinner.() -> Unit): android.widget.Spinner { return ankoView(`$$Anko$Factories$Sdk21View`.SPINNER) { init() } } public inline fun ViewManager.stackView(): android.widget.StackView = stackView({}) public inline fun ViewManager.stackView(init: android.widget.StackView.() -> Unit): android.widget.StackView { return ankoView(`$$Anko$Factories$Sdk21View`.STACK_VIEW) { init() } } public inline fun Context.stackView(): android.widget.StackView = stackView({}) public inline fun Context.stackView(init: android.widget.StackView.() -> Unit): android.widget.StackView { return ankoView(`$$Anko$Factories$Sdk21View`.STACK_VIEW) { init() } } public inline fun Activity.stackView(): android.widget.StackView = stackView({}) public inline fun Activity.stackView(init: android.widget.StackView.() -> Unit): android.widget.StackView { return ankoView(`$$Anko$Factories$Sdk21View`.STACK_VIEW) { init() } } public inline fun ViewManager.switch(): android.widget.Switch = switch({}) public inline fun ViewManager.switch(init: android.widget.Switch.() -> Unit): android.widget.Switch { return ankoView(`$$Anko$Factories$Sdk21View`.SWITCH) { init() } } public inline fun ViewManager.tabHost(): android.widget.TabHost = tabHost({}) public inline fun ViewManager.tabHost(init: android.widget.TabHost.() -> Unit): android.widget.TabHost { return ankoView(`$$Anko$Factories$Sdk21View`.TAB_HOST) { init() } } public inline fun Context.tabHost(): android.widget.TabHost = tabHost({}) public inline fun Context.tabHost(init: android.widget.TabHost.() -> Unit): android.widget.TabHost { return ankoView(`$$Anko$Factories$Sdk21View`.TAB_HOST) { init() } } public inline fun Activity.tabHost(): android.widget.TabHost = tabHost({}) public inline fun Activity.tabHost(init: android.widget.TabHost.() -> Unit): android.widget.TabHost { return ankoView(`$$Anko$Factories$Sdk21View`.TAB_HOST) { init() } } public inline fun ViewManager.tabWidget(): android.widget.TabWidget = tabWidget({}) public inline fun ViewManager.tabWidget(init: android.widget.TabWidget.() -> Unit): android.widget.TabWidget { return ankoView(`$$Anko$Factories$Sdk21View`.TAB_WIDGET) { init() } } public inline fun Context.tabWidget(): android.widget.TabWidget = tabWidget({}) public inline fun Context.tabWidget(init: android.widget.TabWidget.() -> Unit): android.widget.TabWidget { return ankoView(`$$Anko$Factories$Sdk21View`.TAB_WIDGET) { init() } } public inline fun Activity.tabWidget(): android.widget.TabWidget = tabWidget({}) public inline fun Activity.tabWidget(init: android.widget.TabWidget.() -> Unit): android.widget.TabWidget { return ankoView(`$$Anko$Factories$Sdk21View`.TAB_WIDGET) { init() } } public inline fun ViewManager.textClock(): android.widget.TextClock = textClock({}) public inline fun ViewManager.textClock(init: android.widget.TextClock.() -> Unit): android.widget.TextClock { return ankoView(`$$Anko$Factories$Sdk21View`.TEXT_CLOCK) { init() } } public inline fun ViewManager.textView(): android.widget.TextView = textView({}) public inline fun ViewManager.textView(init: android.widget.TextView.() -> Unit): android.widget.TextView { return ankoView(`$$Anko$Factories$Sdk21View`.TEXT_VIEW) { init() } } public inline fun ViewManager.textView(text: CharSequence?): android.widget.TextView { return ankoView(`$$Anko$Factories$Sdk21View`.TEXT_VIEW) { setText(text) } } public inline fun ViewManager.textView(text: CharSequence?, init: android.widget.TextView.() -> Unit): android.widget.TextView { return ankoView(`$$Anko$Factories$Sdk21View`.TEXT_VIEW) { init() setText(text) } } public inline fun ViewManager.textView(text: Int): android.widget.TextView { return ankoView(`$$Anko$Factories$Sdk21View`.TEXT_VIEW) { setText(text) } } public inline fun ViewManager.textView(text: Int, init: android.widget.TextView.() -> Unit): android.widget.TextView { return ankoView(`$$Anko$Factories$Sdk21View`.TEXT_VIEW) { init() setText(text) } } public inline fun ViewManager.timePicker(): android.widget.TimePicker = timePicker({}) public inline fun ViewManager.timePicker(init: android.widget.TimePicker.() -> Unit): android.widget.TimePicker { return ankoView(`$$Anko$Factories$Sdk21View`.TIME_PICKER) { init() } } public inline fun Context.timePicker(): android.widget.TimePicker = timePicker({}) public inline fun Context.timePicker(init: android.widget.TimePicker.() -> Unit): android.widget.TimePicker { return ankoView(`$$Anko$Factories$Sdk21View`.TIME_PICKER) { init() } } public inline fun Activity.timePicker(): android.widget.TimePicker = timePicker({}) public inline fun Activity.timePicker(init: android.widget.TimePicker.() -> Unit): android.widget.TimePicker { return ankoView(`$$Anko$Factories$Sdk21View`.TIME_PICKER) { init() } } public inline fun ViewManager.toggleButton(): android.widget.ToggleButton = toggleButton({}) public inline fun ViewManager.toggleButton(init: android.widget.ToggleButton.() -> Unit): android.widget.ToggleButton { return ankoView(`$$Anko$Factories$Sdk21View`.TOGGLE_BUTTON) { init() } } public inline fun ViewManager.twoLineListItem(): android.widget.TwoLineListItem = twoLineListItem({}) public inline fun ViewManager.twoLineListItem(init: android.widget.TwoLineListItem.() -> Unit): android.widget.TwoLineListItem { return ankoView(`$$Anko$Factories$Sdk21View`.TWO_LINE_LIST_ITEM) { init() } } public inline fun Context.twoLineListItem(): android.widget.TwoLineListItem = twoLineListItem({}) public inline fun Context.twoLineListItem(init: android.widget.TwoLineListItem.() -> Unit): android.widget.TwoLineListItem { return ankoView(`$$Anko$Factories$Sdk21View`.TWO_LINE_LIST_ITEM) { init() } } public inline fun Activity.twoLineListItem(): android.widget.TwoLineListItem = twoLineListItem({}) public inline fun Activity.twoLineListItem(init: android.widget.TwoLineListItem.() -> Unit): android.widget.TwoLineListItem { return ankoView(`$$Anko$Factories$Sdk21View`.TWO_LINE_LIST_ITEM) { init() } } public inline fun ViewManager.videoView(): android.widget.VideoView = videoView({}) public inline fun ViewManager.videoView(init: android.widget.VideoView.() -> Unit): android.widget.VideoView { return ankoView(`$$Anko$Factories$Sdk21View`.VIDEO_VIEW) { init() } } public inline fun ViewManager.viewFlipper(): android.widget.ViewFlipper = viewFlipper({}) public inline fun ViewManager.viewFlipper(init: android.widget.ViewFlipper.() -> Unit): android.widget.ViewFlipper { return ankoView(`$$Anko$Factories$Sdk21View`.VIEW_FLIPPER) { init() } } public inline fun Context.viewFlipper(): android.widget.ViewFlipper = viewFlipper({}) public inline fun Context.viewFlipper(init: android.widget.ViewFlipper.() -> Unit): android.widget.ViewFlipper { return ankoView(`$$Anko$Factories$Sdk21View`.VIEW_FLIPPER) { init() } } public inline fun Activity.viewFlipper(): android.widget.ViewFlipper = viewFlipper({}) public inline fun Activity.viewFlipper(init: android.widget.ViewFlipper.() -> Unit): android.widget.ViewFlipper { return ankoView(`$$Anko$Factories$Sdk21View`.VIEW_FLIPPER) { init() } } public inline fun ViewManager.zoomButton(): android.widget.ZoomButton = zoomButton({}) public inline fun ViewManager.zoomButton(init: android.widget.ZoomButton.() -> Unit): android.widget.ZoomButton { return ankoView(`$$Anko$Factories$Sdk21View`.ZOOM_BUTTON) { init() } } public inline fun ViewManager.zoomControls(): android.widget.ZoomControls = zoomControls({}) public inline fun ViewManager.zoomControls(init: android.widget.ZoomControls.() -> Unit): android.widget.ZoomControls { return ankoView(`$$Anko$Factories$Sdk21View`.ZOOM_CONTROLS) { init() } } public inline fun Context.zoomControls(): android.widget.ZoomControls = zoomControls({}) public inline fun Context.zoomControls(init: android.widget.ZoomControls.() -> Unit): android.widget.ZoomControls { return ankoView(`$$Anko$Factories$Sdk21View`.ZOOM_CONTROLS) { init() } } public inline fun Activity.zoomControls(): android.widget.ZoomControls = zoomControls({}) public inline fun Activity.zoomControls(init: android.widget.ZoomControls.() -> Unit): android.widget.ZoomControls { return ankoView(`$$Anko$Factories$Sdk21View`.ZOOM_CONTROLS) { init() } } public object `$$Anko$Factories$Sdk21ViewGroup` { public val APP_WIDGET_HOST_VIEW = { ctx: Context -> _AppWidgetHostView(ctx) } public val WEB_VIEW = { ctx: Context -> _WebView(ctx) } public val ABSOLUTE_LAYOUT = { ctx: Context -> _AbsoluteLayout(ctx) } public val ACTION_MENU_VIEW = { ctx: Context -> _ActionMenuView(ctx) } public val FRAME_LAYOUT = { ctx: Context -> _FrameLayout(ctx) } public val GALLERY = { ctx: Context -> _Gallery(ctx) } public val GRID_LAYOUT = { ctx: Context -> _GridLayout(ctx) } public val GRID_VIEW = { ctx: Context -> _GridView(ctx) } public val HORIZONTAL_SCROLL_VIEW = { ctx: Context -> _HorizontalScrollView(ctx) } public val IMAGE_SWITCHER = { ctx: Context -> _ImageSwitcher(ctx) } public val LINEAR_LAYOUT = { ctx: Context -> _LinearLayout(ctx) } public val RADIO_GROUP = { ctx: Context -> _RadioGroup(ctx) } public val RELATIVE_LAYOUT = { ctx: Context -> _RelativeLayout(ctx) } public val SCROLL_VIEW = { ctx: Context -> _ScrollView(ctx) } public val TABLE_LAYOUT = { ctx: Context -> _TableLayout(ctx) } public val TABLE_ROW = { ctx: Context -> _TableRow(ctx) } public val TEXT_SWITCHER = { ctx: Context -> _TextSwitcher(ctx) } public val TOOLBAR = { ctx: Context -> _Toolbar(ctx) } public val VIEW_ANIMATOR = { ctx: Context -> _ViewAnimator(ctx) } public val VIEW_SWITCHER = { ctx: Context -> _ViewSwitcher(ctx) } } public inline fun ViewManager.appWidgetHostView(): android.appwidget.AppWidgetHostView = appWidgetHostView({}) public inline fun ViewManager.appWidgetHostView(init: _AppWidgetHostView.() -> Unit): android.appwidget.AppWidgetHostView { return ankoView(`$$Anko$Factories$Sdk21ViewGroup`.APP_WIDGET_HOST_VIEW) { init() } } public inline fun Context.appWidgetHostView(): android.appwidget.AppWidgetHostView = appWidgetHostView({}) public inline fun Context.appWidgetHostView(init: _AppWidgetHostView.() -> Unit): android.appwidget.AppWidgetHostView { return ankoView(`$$Anko$Factories$Sdk21ViewGroup`.APP_WIDGET_HOST_VIEW) { init() } } public inline fun Activity.appWidgetHostView(): android.appwidget.AppWidgetHostView = appWidgetHostView({}) public inline fun Activity.appWidgetHostView(init: _AppWidgetHostView.() -> Unit): android.appwidget.AppWidgetHostView { return ankoView(`$$Anko$Factories$Sdk21ViewGroup`.APP_WIDGET_HOST_VIEW) { init() } } public inline fun ViewManager.webView(): android.webkit.WebView = webView({}) public inline fun ViewManager.webView(init: _WebView.() -> Unit): android.webkit.WebView { return ankoView(`$$Anko$Factories$Sdk21ViewGroup`.WEB_VIEW) { init() } } public inline fun Context.webView(): android.webkit.WebView = webView({}) public inline fun Context.webView(init: _WebView.() -> Unit): android.webkit.WebView { return ankoView(`$$Anko$Factories$Sdk21ViewGroup`.WEB_VIEW) { init() } } public inline fun Activity.webView(): android.webkit.WebView = webView({}) public inline fun Activity.webView(init: _WebView.() -> Unit): android.webkit.WebView { return ankoView(`$$Anko$Factories$Sdk21ViewGroup`.WEB_VIEW) { init() } } public inline fun ViewManager.absoluteLayout(): android.widget.AbsoluteLayout = absoluteLayout({}) public inline fun ViewManager.absoluteLayout(init: _AbsoluteLayout.() -> Unit): android.widget.AbsoluteLayout { return ankoView(`$$Anko$Factories$Sdk21ViewGroup`.ABSOLUTE_LAYOUT) { init() } } public inline fun Context.absoluteLayout(): android.widget.AbsoluteLayout = absoluteLayout({}) public inline fun Context.absoluteLayout(init: _AbsoluteLayout.() -> Unit): android.widget.AbsoluteLayout { return ankoView(`$$Anko$Factories$Sdk21ViewGroup`.ABSOLUTE_LAYOUT) { init() } } public inline fun Activity.absoluteLayout(): android.widget.AbsoluteLayout = absoluteLayout({}) public inline fun Activity.absoluteLayout(init: _AbsoluteLayout.() -> Unit): android.widget.AbsoluteLayout { return ankoView(`$$Anko$Factories$Sdk21ViewGroup`.ABSOLUTE_LAYOUT) { init() } } public inline fun ViewManager.actionMenuView(): android.widget.ActionMenuView = actionMenuView({}) public inline fun ViewManager.actionMenuView(init: _ActionMenuView.() -> Unit): android.widget.ActionMenuView { return ankoView(`$$Anko$Factories$Sdk21ViewGroup`.ACTION_MENU_VIEW) { init() } } public inline fun Context.actionMenuView(): android.widget.ActionMenuView = actionMenuView({}) public inline fun Context.actionMenuView(init: _ActionMenuView.() -> Unit): android.widget.ActionMenuView { return ankoView(`$$Anko$Factories$Sdk21ViewGroup`.ACTION_MENU_VIEW) { init() } } public inline fun Activity.actionMenuView(): android.widget.ActionMenuView = actionMenuView({}) public inline fun Activity.actionMenuView(init: _ActionMenuView.() -> Unit): android.widget.ActionMenuView { return ankoView(`$$Anko$Factories$Sdk21ViewGroup`.ACTION_MENU_VIEW) { init() } } public inline fun ViewManager.frameLayout(): android.widget.FrameLayout = frameLayout({}) public inline fun ViewManager.frameLayout(init: _FrameLayout.() -> Unit): android.widget.FrameLayout { return ankoView(`$$Anko$Factories$Sdk21ViewGroup`.FRAME_LAYOUT) { init() } } public inline fun Context.frameLayout(): android.widget.FrameLayout = frameLayout({}) public inline fun Context.frameLayout(init: _FrameLayout.() -> Unit): android.widget.FrameLayout { return ankoView(`$$Anko$Factories$Sdk21ViewGroup`.FRAME_LAYOUT) { init() } } public inline fun Activity.frameLayout(): android.widget.FrameLayout = frameLayout({}) public inline fun Activity.frameLayout(init: _FrameLayout.() -> Unit): android.widget.FrameLayout { return ankoView(`$$Anko$Factories$Sdk21ViewGroup`.FRAME_LAYOUT) { init() } } public inline fun ViewManager.gallery(): android.widget.Gallery = gallery({}) public inline fun ViewManager.gallery(init: _Gallery.() -> Unit): android.widget.Gallery { return ankoView(`$$Anko$Factories$Sdk21ViewGroup`.GALLERY) { init() } } public inline fun Context.gallery(): android.widget.Gallery = gallery({}) public inline fun Context.gallery(init: _Gallery.() -> Unit): android.widget.Gallery { return ankoView(`$$Anko$Factories$Sdk21ViewGroup`.GALLERY) { init() } } public inline fun Activity.gallery(): android.widget.Gallery = gallery({}) public inline fun Activity.gallery(init: _Gallery.() -> Unit): android.widget.Gallery { return ankoView(`$$Anko$Factories$Sdk21ViewGroup`.GALLERY) { init() } } public inline fun ViewManager.gridLayout(): android.widget.GridLayout = gridLayout({}) public inline fun ViewManager.gridLayout(init: _GridLayout.() -> Unit): android.widget.GridLayout { return ankoView(`$$Anko$Factories$Sdk21ViewGroup`.GRID_LAYOUT) { init() } } public inline fun Context.gridLayout(): android.widget.GridLayout = gridLayout({}) public inline fun Context.gridLayout(init: _GridLayout.() -> Unit): android.widget.GridLayout { return ankoView(`$$Anko$Factories$Sdk21ViewGroup`.GRID_LAYOUT) { init() } } public inline fun Activity.gridLayout(): android.widget.GridLayout = gridLayout({}) public inline fun Activity.gridLayout(init: _GridLayout.() -> Unit): android.widget.GridLayout { return ankoView(`$$Anko$Factories$Sdk21ViewGroup`.GRID_LAYOUT) { init() } } public inline fun ViewManager.gridView(): android.widget.GridView = gridView({}) public inline fun ViewManager.gridView(init: _GridView.() -> Unit): android.widget.GridView { return ankoView(`$$Anko$Factories$Sdk21ViewGroup`.GRID_VIEW) { init() } } public inline fun Context.gridView(): android.widget.GridView = gridView({}) public inline fun Context.gridView(init: _GridView.() -> Unit): android.widget.GridView { return ankoView(`$$Anko$Factories$Sdk21ViewGroup`.GRID_VIEW) { init() } } public inline fun Activity.gridView(): android.widget.GridView = gridView({}) public inline fun Activity.gridView(init: _GridView.() -> Unit): android.widget.GridView { return ankoView(`$$Anko$Factories$Sdk21ViewGroup`.GRID_VIEW) { init() } } public inline fun ViewManager.horizontalScrollView(): android.widget.HorizontalScrollView = horizontalScrollView({}) public inline fun ViewManager.horizontalScrollView(init: _HorizontalScrollView.() -> Unit): android.widget.HorizontalScrollView { return ankoView(`$$Anko$Factories$Sdk21ViewGroup`.HORIZONTAL_SCROLL_VIEW) { init() } } public inline fun Context.horizontalScrollView(): android.widget.HorizontalScrollView = horizontalScrollView({}) public inline fun Context.horizontalScrollView(init: _HorizontalScrollView.() -> Unit): android.widget.HorizontalScrollView { return ankoView(`$$Anko$Factories$Sdk21ViewGroup`.HORIZONTAL_SCROLL_VIEW) { init() } } public inline fun Activity.horizontalScrollView(): android.widget.HorizontalScrollView = horizontalScrollView({}) public inline fun Activity.horizontalScrollView(init: _HorizontalScrollView.() -> Unit): android.widget.HorizontalScrollView { return ankoView(`$$Anko$Factories$Sdk21ViewGroup`.HORIZONTAL_SCROLL_VIEW) { init() } } public inline fun ViewManager.imageSwitcher(): android.widget.ImageSwitcher = imageSwitcher({}) public inline fun ViewManager.imageSwitcher(init: _ImageSwitcher.() -> Unit): android.widget.ImageSwitcher { return ankoView(`$$Anko$Factories$Sdk21ViewGroup`.IMAGE_SWITCHER) { init() } } public inline fun Context.imageSwitcher(): android.widget.ImageSwitcher = imageSwitcher({}) public inline fun Context.imageSwitcher(init: _ImageSwitcher.() -> Unit): android.widget.ImageSwitcher { return ankoView(`$$Anko$Factories$Sdk21ViewGroup`.IMAGE_SWITCHER) { init() } } public inline fun Activity.imageSwitcher(): android.widget.ImageSwitcher = imageSwitcher({}) public inline fun Activity.imageSwitcher(init: _ImageSwitcher.() -> Unit): android.widget.ImageSwitcher { return ankoView(`$$Anko$Factories$Sdk21ViewGroup`.IMAGE_SWITCHER) { init() } } public inline fun ViewManager.linearLayout(): android.widget.LinearLayout = linearLayout({}) public inline fun ViewManager.linearLayout(init: _LinearLayout.() -> Unit): android.widget.LinearLayout { return ankoView(`$$Anko$Factories$Sdk21ViewGroup`.LINEAR_LAYOUT) { init() } } public inline fun Context.linearLayout(): android.widget.LinearLayout = linearLayout({}) public inline fun Context.linearLayout(init: _LinearLayout.() -> Unit): android.widget.LinearLayout { return ankoView(`$$Anko$Factories$Sdk21ViewGroup`.LINEAR_LAYOUT) { init() } } public inline fun Activity.linearLayout(): android.widget.LinearLayout = linearLayout({}) public inline fun Activity.linearLayout(init: _LinearLayout.() -> Unit): android.widget.LinearLayout { return ankoView(`$$Anko$Factories$Sdk21ViewGroup`.LINEAR_LAYOUT) { init() } } public inline fun ViewManager.radioGroup(): android.widget.RadioGroup = radioGroup({}) public inline fun ViewManager.radioGroup(init: _RadioGroup.() -> Unit): android.widget.RadioGroup { return ankoView(`$$Anko$Factories$Sdk21ViewGroup`.RADIO_GROUP) { init() } } public inline fun Context.radioGroup(): android.widget.RadioGroup = radioGroup({}) public inline fun Context.radioGroup(init: _RadioGroup.() -> Unit): android.widget.RadioGroup { return ankoView(`$$Anko$Factories$Sdk21ViewGroup`.RADIO_GROUP) { init() } } public inline fun Activity.radioGroup(): android.widget.RadioGroup = radioGroup({}) public inline fun Activity.radioGroup(init: _RadioGroup.() -> Unit): android.widget.RadioGroup { return ankoView(`$$Anko$Factories$Sdk21ViewGroup`.RADIO_GROUP) { init() } } public inline fun ViewManager.relativeLayout(): android.widget.RelativeLayout = relativeLayout({}) public inline fun ViewManager.relativeLayout(init: _RelativeLayout.() -> Unit): android.widget.RelativeLayout { return ankoView(`$$Anko$Factories$Sdk21ViewGroup`.RELATIVE_LAYOUT) { init() } } public inline fun Context.relativeLayout(): android.widget.RelativeLayout = relativeLayout({}) public inline fun Context.relativeLayout(init: _RelativeLayout.() -> Unit): android.widget.RelativeLayout { return ankoView(`$$Anko$Factories$Sdk21ViewGroup`.RELATIVE_LAYOUT) { init() } } public inline fun Activity.relativeLayout(): android.widget.RelativeLayout = relativeLayout({}) public inline fun Activity.relativeLayout(init: _RelativeLayout.() -> Unit): android.widget.RelativeLayout { return ankoView(`$$Anko$Factories$Sdk21ViewGroup`.RELATIVE_LAYOUT) { init() } } public inline fun ViewManager.scrollView(): android.widget.ScrollView = scrollView({}) public inline fun ViewManager.scrollView(init: _ScrollView.() -> Unit): android.widget.ScrollView { return ankoView(`$$Anko$Factories$Sdk21ViewGroup`.SCROLL_VIEW) { init() } } public inline fun Context.scrollView(): android.widget.ScrollView = scrollView({}) public inline fun Context.scrollView(init: _ScrollView.() -> Unit): android.widget.ScrollView { return ankoView(`$$Anko$Factories$Sdk21ViewGroup`.SCROLL_VIEW) { init() } } public inline fun Activity.scrollView(): android.widget.ScrollView = scrollView({}) public inline fun Activity.scrollView(init: _ScrollView.() -> Unit): android.widget.ScrollView { return ankoView(`$$Anko$Factories$Sdk21ViewGroup`.SCROLL_VIEW) { init() } } public inline fun ViewManager.tableLayout(): android.widget.TableLayout = tableLayout({}) public inline fun ViewManager.tableLayout(init: _TableLayout.() -> Unit): android.widget.TableLayout { return ankoView(`$$Anko$Factories$Sdk21ViewGroup`.TABLE_LAYOUT) { init() } } public inline fun Context.tableLayout(): android.widget.TableLayout = tableLayout({}) public inline fun Context.tableLayout(init: _TableLayout.() -> Unit): android.widget.TableLayout { return ankoView(`$$Anko$Factories$Sdk21ViewGroup`.TABLE_LAYOUT) { init() } } public inline fun Activity.tableLayout(): android.widget.TableLayout = tableLayout({}) public inline fun Activity.tableLayout(init: _TableLayout.() -> Unit): android.widget.TableLayout { return ankoView(`$$Anko$Factories$Sdk21ViewGroup`.TABLE_LAYOUT) { init() } } public inline fun ViewManager.tableRow(): android.widget.TableRow = tableRow({}) public inline fun ViewManager.tableRow(init: _TableRow.() -> Unit): android.widget.TableRow { return ankoView(`$$Anko$Factories$Sdk21ViewGroup`.TABLE_ROW) { init() } } public inline fun Context.tableRow(): android.widget.TableRow = tableRow({}) public inline fun Context.tableRow(init: _TableRow.() -> Unit): android.widget.TableRow { return ankoView(`$$Anko$Factories$Sdk21ViewGroup`.TABLE_ROW) { init() } } public inline fun Activity.tableRow(): android.widget.TableRow = tableRow({}) public inline fun Activity.tableRow(init: _TableRow.() -> Unit): android.widget.TableRow { return ankoView(`$$Anko$Factories$Sdk21ViewGroup`.TABLE_ROW) { init() } } public inline fun ViewManager.textSwitcher(): android.widget.TextSwitcher = textSwitcher({}) public inline fun ViewManager.textSwitcher(init: _TextSwitcher.() -> Unit): android.widget.TextSwitcher { return ankoView(`$$Anko$Factories$Sdk21ViewGroup`.TEXT_SWITCHER) { init() } } public inline fun Context.textSwitcher(): android.widget.TextSwitcher = textSwitcher({}) public inline fun Context.textSwitcher(init: _TextSwitcher.() -> Unit): android.widget.TextSwitcher { return ankoView(`$$Anko$Factories$Sdk21ViewGroup`.TEXT_SWITCHER) { init() } } public inline fun Activity.textSwitcher(): android.widget.TextSwitcher = textSwitcher({}) public inline fun Activity.textSwitcher(init: _TextSwitcher.() -> Unit): android.widget.TextSwitcher { return ankoView(`$$Anko$Factories$Sdk21ViewGroup`.TEXT_SWITCHER) { init() } } public inline fun ViewManager.toolbar(): android.widget.Toolbar = toolbar({}) public inline fun ViewManager.toolbar(init: _Toolbar.() -> Unit): android.widget.Toolbar { return ankoView(`$$Anko$Factories$Sdk21ViewGroup`.TOOLBAR) { init() } } public inline fun Context.toolbar(): android.widget.Toolbar = toolbar({}) public inline fun Context.toolbar(init: _Toolbar.() -> Unit): android.widget.Toolbar { return ankoView(`$$Anko$Factories$Sdk21ViewGroup`.TOOLBAR) { init() } } public inline fun Activity.toolbar(): android.widget.Toolbar = toolbar({}) public inline fun Activity.toolbar(init: _Toolbar.() -> Unit): android.widget.Toolbar { return ankoView(`$$Anko$Factories$Sdk21ViewGroup`.TOOLBAR) { init() } } public inline fun ViewManager.viewAnimator(): android.widget.ViewAnimator = viewAnimator({}) public inline fun ViewManager.viewAnimator(init: _ViewAnimator.() -> Unit): android.widget.ViewAnimator { return ankoView(`$$Anko$Factories$Sdk21ViewGroup`.VIEW_ANIMATOR) { init() } } public inline fun Context.viewAnimator(): android.widget.ViewAnimator = viewAnimator({}) public inline fun Context.viewAnimator(init: _ViewAnimator.() -> Unit): android.widget.ViewAnimator { return ankoView(`$$Anko$Factories$Sdk21ViewGroup`.VIEW_ANIMATOR) { init() } } public inline fun Activity.viewAnimator(): android.widget.ViewAnimator = viewAnimator({}) public inline fun Activity.viewAnimator(init: _ViewAnimator.() -> Unit): android.widget.ViewAnimator { return ankoView(`$$Anko$Factories$Sdk21ViewGroup`.VIEW_ANIMATOR) { init() } } public inline fun ViewManager.viewSwitcher(): android.widget.ViewSwitcher = viewSwitcher({}) public inline fun ViewManager.viewSwitcher(init: _ViewSwitcher.() -> Unit): android.widget.ViewSwitcher { return ankoView(`$$Anko$Factories$Sdk21ViewGroup`.VIEW_SWITCHER) { init() } } public inline fun Context.viewSwitcher(): android.widget.ViewSwitcher = viewSwitcher({}) public inline fun Context.viewSwitcher(init: _ViewSwitcher.() -> Unit): android.widget.ViewSwitcher { return ankoView(`$$Anko$Factories$Sdk21ViewGroup`.VIEW_SWITCHER) { init() } } public inline fun Activity.viewSwitcher(): android.widget.ViewSwitcher = viewSwitcher({}) public inline fun Activity.viewSwitcher(init: _ViewSwitcher.() -> Unit): android.widget.ViewSwitcher { return ankoView(`$$Anko$Factories$Sdk21ViewGroup`.VIEW_SWITCHER) { init() } }
apache-2.0
b98cd99214074322c77aa598edee5e29
52.825688
168
0.742377
4.309312
false
false
false
false
apixandru/intellij-community
python/src/com/jetbrains/python/console/PyConsoleEnterHandler.kt
13
6078
/* * Copyright 2000-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jetbrains.python.console import com.intellij.ide.DataManager import com.intellij.openapi.actionSystem.IdeActions import com.intellij.openapi.application.Result import com.intellij.openapi.command.WriteCommandAction import com.intellij.openapi.editor.Document import com.intellij.openapi.editor.actionSystem.EditorActionManager import com.intellij.openapi.editor.ex.EditorEx import com.intellij.openapi.project.Project import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiDocumentManager import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import com.intellij.psi.PsiWhiteSpace import com.intellij.psi.util.PsiTreeUtil import com.intellij.util.DocumentUtil import com.jetbrains.python.PyTokenTypes import com.jetbrains.python.psi.PyStatementListContainer import com.jetbrains.python.psi.PyStringLiteralExpression import com.jetbrains.python.psi.PyTryPart import com.jetbrains.python.psi.impl.PyPsiUtils import com.jetbrains.python.psi.impl.PyStringLiteralExpressionImpl class PyConsoleEnterHandler { fun handleEnterPressed(editor: EditorEx): Boolean { val project = editor.project ?: throw IllegalArgumentException() val lineCount = editor.document.lineCount if (lineCount > 0) { // move to end of line editor.selectionModel.removeSelection() val caretPosition = editor.caretModel.logicalPosition if (caretPosition.line == lineCount - 1) { // we can move caret if only it's on the last line of command val lineEndOffset = editor.document.getLineEndOffset(caretPosition.line) editor.caretModel.moveToOffset(lineEndOffset) } else { // otherwise just process enter action executeEnterHandler(project, editor) return false; } } else { return true; } val psiMgr = PsiDocumentManager.getInstance(project) psiMgr.commitDocument(editor.document) val caretOffset = editor.expectedCaretOffset val atElement = findFirstNoneSpaceElement(psiMgr.getPsiFile(editor.document)!!, caretOffset) if (atElement == null) { executeEnterHandler(project, editor) return false } val firstLine = getLineAtOffset(editor.document, DocumentUtil.getFirstNonSpaceCharOffset(editor.document, 0)) val isCellMagic = firstLine.trim().startsWith("%%") && !firstLine.trimEnd().endsWith("?") val prevLine = getLineAtOffset(editor.document, caretOffset) val isLineContinuation = prevLine.trim().endsWith('\\') val insideDocString = isElementInsideDocString(atElement, caretOffset) val isMultiLineCommand = PsiTreeUtil.getParentOfType(atElement, PyStatementListContainer::class.java) != null || isCellMagic val isAtTheEndOfCommand = editor.document.getLineNumber(caretOffset) == editor.document.lineCount - 1 val hasCompleteStatement = !insideDocString && !isLineContinuation && checkComplete(atElement) executeEnterHandler(project, editor) return isAtTheEndOfCommand && hasCompleteStatement && ((isMultiLineCommand && prevLine.isBlank()) || (!isMultiLineCommand)) } private fun executeEnterHandler(project: Project, editor:EditorEx) { val enterHandler = EditorActionManager.getInstance().getActionHandler(IdeActions.ACTION_EDITOR_ENTER) object : WriteCommandAction<Nothing>(project) { @Throws(Throwable::class) override fun run(result: Result<Nothing>) { enterHandler.execute(editor, null, DataManager.getInstance().getDataContext(editor.component)) } }.execute() } private fun isElementInsideDocString(atElement: PsiElement, caretOffset: Int): Boolean { return atElement.context is PyStringLiteralExpression && (PyTokenTypes.TRIPLE_NODES.contains(atElement.node.elementType) || atElement.node.elementType === PyTokenTypes.DOCSTRING) && isMultilineString(atElement.text) && (atElement.textRange.endOffset > caretOffset || !isCompleteDocString(atElement.text)) } private fun checkComplete(el: PsiElement): Boolean { val compoundStatement = PsiTreeUtil.getParentOfType(el, PyStatementListContainer::class.java) if (compoundStatement != null && compoundStatement !is PyTryPart) { return compoundStatement.statementList.statements.size != 0 } val topLevel = PyPsiUtils.getParentRightBefore(el, el.containingFile) return topLevel != null && !PsiTreeUtil.hasErrorElements(topLevel) } private fun findFirstNoneSpaceElement(psiFile: PsiFile, offset: Int): PsiElement? { for (i in offset downTo 0) { val el = psiFile.findElementAt(i) if (el != null && el !is PsiWhiteSpace) { return el } } return null } private fun getLineAtOffset(doc: Document, offset: Int): String { val line = doc.getLineNumber(offset) val start = doc.getLineStartOffset(line) val end = doc.getLineEndOffset(line) return doc.getText(TextRange(start, end)) } private fun isMultilineString(str: String): Boolean { val text = str.substring(PyStringLiteralExpressionImpl.getPrefixLength(str)) return text.startsWith("\"\"\"") || text.startsWith("'''") } private fun isCompleteDocString(str: String): Boolean { val prefixLen = PyStringLiteralExpressionImpl.getPrefixLength(str) val text = str.substring(prefixLen) for (token in arrayOf("\"\"\"", "'''")) { if (text.length >= 2 * token.length && text.startsWith(token) && text.endsWith(token)) { return true } } return false } }
apache-2.0
52d35f00e845db968b67ef3cb104cfc5
40.074324
128
0.741691
4.462555
false
false
false
false
Ztiany/Repository
Kotlin/Kotlin-Basic/src/main/kotlin/me/ztiany/generic/KotlinGeneric.kt
2
9994
package me.ztiany.generic import java.util.* /** *Kotlin泛型 * * 1,泛型 * 2,声明处型变 * 3,类型投影 * 4,星投影 * 5,@UnsafeVariance * 6,泛型函数 * 7,泛型约束与where子句 * 8,Kotlin集合中的泛型 * * https://www.kotlincn.net/docs/reference/generics.html * https://blog.kotliner.cn/2017/06/26/kotlin-generics/ * https://kymjs.com/code/2017/06/06/01/ */ //1 泛型:与Java 类似,Kotlin 中的类也可以有类型参数 private class Box<T>(t: T) { var value = t } private val box1: Box<Int> = Box<Int>(1) // 1 具有类型 Int,所以编译器知道我们说的是 Box<Int>。则可以省略掉返现说明 private val box2 = Box(1) /** * 2 声明处型变——in和out: * * 一般原则是:当一个类 C 的类型参数 T 被声明为 out 时,它就只能出现在 C 的成员的输出-位置, * 但回报是 C<Base> 可以安全地作为 C<Derived>的超类。 * * 简而言之,现在类 C 是在参数 T 上是协变的,或者说 T 是一个协变的类型参数。 可以认为 C 是 T 的生产者,而不是 T 的消费者。 * * out修饰符称为型变注解,并且由于它在类型参数声明处提供,所以我们讲声明处型变。 * 这与 Java 的使用处型变相反,其类型用途通配符使得类型协变。 * * 另外除了 out,Kotlin 又补充了一个型变注释:in。它使得一个类型参数逆变: * 只可以被消费而不可以被生产。逆变类的一个很好的例子是 Comparable: * * in 和 out 两词是自解释的(因为它们已经在 C# 中成功使用很长时间了) * * 总结:out,输出,表示生产者;in,进入,表示消费者 * * 可以看出Kotlin 抛弃了Java的extend和supuer,引用了生产者和消费者的概念 */ private abstract class Source<out T> { abstract fun nextT(): T } //T extend String private fun testSource(source: Source<String>) { val sourceAny: Source<Any> = source } private abstract class TComparable<in T> { abstract fun compareTo(other: T): Int } private fun testTComparable(x: TComparable<Number>) { // 1.0 拥有类型 Double,它是 Number 的子类型 x.compareTo(1.0) // 因此,我们可以将 x 赋给类型为 Comparable <Double> 的变量 val y: TComparable<Double> = x // OK! } /* * 3 类型投影 * * 将类型参数 T 声明为 out 非常方便,并且能避免使用处子类型化的麻烦,但是有些类实际上不能限制为只返回 T! * * 比如Array,该类在 T 上既不能是协变的也不能是逆变的。这造成了一些不灵活性。 * * private class Array<T>(val size: Int) { * abstract fun get(index: Int): T * abstract fun set(index: Int, value: T) * } */ //这个函数应该将项目从一个数组复制到另一个数组。让我们尝试在实践中应用它 private fun copyArray1(from: Array<Any>, to: Array<Any>) { assert(from.size == to.size) for (i in from.indices) { to[i] = from[i] } } private fun testCopyArray1() { val ints: Array<Int> = arrayOf(1, 2, 3) val any = Array<Any>(3) { "" } //copyArray1(ints, any) // 错误:期望 (Array<Any>, Array<Any>) } //Array <T> 在 T 上是不型变的,因此 Array <Int> 和 Array <Any> 都不是另一个的子类型。为什么? // 因为 copy 可能做坏事, 也就是说,例如它可能尝试写一个 String 到 from, 并且如果我们实际上传递一个 Int 的数组, // 一段时间后将会抛出一个 ClassCastException 异常。 //那么,我们唯一要确保的是 copy() 不会做任何坏事。我们想阻止它写到 from,我们可以: private fun copyArray2(from: Array<out Any>, to: Array<Any>) { assert(from.size == to.size) for (i in from.indices) { to[i] = from[i] } //from[3] = 3 //错误,无法使用,只能调用get类方法 } private fun testCopyArray2() { val ints: Array<Int> = arrayOf(1, 2, 3) val any = Array<Any>(3) { "" } copyArray2(ints, any) //现在我们可以以这种形式调用了 //这里发生的事情称为类型投影:我们说from不仅仅是一个数组,而是一个受限制的(投影的)数组:我们只可以调用返回类型为类型参数 T 的方法 //如copyArray2方法中,这意味着我们只能调用 get()。这就是我们的使用处型变的用法,并且是对应于 Java 的 Array<? extends Object>、 但使用更简单些的方式。 } //也可以使用 in 投影一个类型: //Array<in String> 对应于 Java 的 Array<? super String>,也就是说,你可以传递一个 CharSequence 数组或一个 Object 数组给 fill() 函数。 private fun fill(dest: Array<in String>, value: String) { } /** * 星投影: * * 有时你想说,你对类型参数一无所知,但仍然希望以安全的方式使用它。 这里的安全方式是定义泛型类型的这种投影, * 该泛型类型的每个具体实例化将是该投影的子类型。 * * Kotlin 为此提供了所谓的星投影语法: * * 1,对于 Foo <out T>,其中 T 是一个具有上界 TUpper 的协变类型参数,Foo <*> 等价于 Foo <out TUpper>。 * 这意味着当 T 未知时,你可以安全地从 Foo <*> 读取 TUpper 的值。 * 2,对于 Foo <in T>,其中 T 是一个逆变类型参数,Foo <*> 等价于 Foo <in Nothing>。 这意味着当 T 未知时, * 没有什么可以以安全的方式写入 Foo <*>。 * 3,对于 Foo <T>,其中 T 是一个具有上界 TUpper 的不型变类型参数,Foo<*> 对于读取值时等价于 Foo<out TUpper> * 而对于写值时等价于 Foo<in Nothing>。 * * 如果泛型类型具有多个类型参数,则每个类型参数都可以单独投影。 例如,如果类型被声明为 interface Function <in T, out U>, * 我们可以想象以下星投影: * * Function<*, String> 表示 Function<in Nothing, String>; * Function<Int, *> 表示 Function<Int, out Any?>; * Function<*, *> 表示 Function<in Nothing, out Any?>。 */ private interface Foo<T> private class Bar : Foo<Foo<*>> // 5 @UnsafeVariance注解,用于协变类型的内部方法参数上的注解 //考虑下面代码,add方法的不允许定义T类型参数 private class MyCollection<out T> { // ERROR!,为什么?因为 T 是协变的 //fun add(t: T) { //} } //如果上面add编译通过,考虑下面代码,原本只能存入Int类型的集合现在可以存入浮点类型了 private fun test() { var myList: MyCollection<Number> = MyCollection<Int>() //myList.add(3.0) } //对于协变的类型,通常我们是不允许将泛型类型作为传入参数的类型的, // 或者说,对于协变类型,我们通常是不允许其涉及泛型参数的部分被改变的。 //逆变的情形正好相反,即不可以将泛型参数作为方法的返回值。 //但实际上有些情况下,我们不得已需要在协变的情况下使用泛型参数类型作为方法参数的类型: /* public interface Collection<out E> : Iterable<E> { ... public operator fun contains(element: @UnsafeVariance E): Boolean ... } */ private class MyCollection2<out T> { //为了让编译器放过一马,我们就可以用 @UnsafeVariance 来告诉编译器:“我知道我在干啥,保证不会出错,你不用担心”。 fun add(t: @UnsafeVariance T) { } } /** * 6 泛型函数 * 不仅类可以有类型参数。函数也可以有。类型参数要放在函数名称之前: */ private fun <T> singletonList(item: T): List<T> { return Collections.singletonList(item) } private fun <E> E.basicToString(): String { // 扩展函数 println(this.toString()) return "abc" } //要调用泛型函数,在调用处函数名之后指定类型参数即可: private fun testFunctionGeneric() { singletonList<String>("A") singletonList("A")//如果编译器可以推断出,实际泛型参数可以省略 1.basicToString() } /* * 7 泛型约束 * 能够替换给定类型参数的所有可能类型的集合可以由泛型约束限制。 */ //上界:最常见的约束类型是与 Java 的 extends 关键字对应的 上界 //冒号之后指定的类型是上界:只有 Comparable<T> 的子类型可以替代 T //翻译成java中的泛型就是:T extends Comparable<T> private fun <T : Comparable<T>> sort(list: List<T>) { } private fun testSort() { sort(listOf(1, 2, 3)) // OK。Int 是 Comparable<Int> 的子类型 // 错误:HashMap<Int, String> 不是 Comparable<HashMap<Int, String>> 的子类型 // sort(listOf(HashMap<Int, String>())) } //默认的上界(如果没有声明)是 Any?。在尖括号中只能指定一个上界。 如果同一类型参数需要多个上界,我们需要一个单独的 where-子句: private fun <T> cloneWhenGreater(list: List<T>, threshold: T): List<T> where T : Comparable<T>, T : Cloneable { return list.filter { it > threshold } } /** 8 Kotlin集合中的泛型 public interface Iterable<out T> public interface ListIterator<out T> : Iterator<T> public interface Collection<out E> : Iterable<E> public interface MutableIterable<out T> : Iterable<T> public interface List<out E> : Collection<E> public interface Set<out E> : Collection<E> public interface MutableCollection<E> : Collection<E>, MutableIterable<E> public interface MutableList<E> : List<E>, MutableCollection<E> public interface MutableSet<E> : Set<E>, MutableCollection<E> */
apache-2.0
a886c92d091d63d0639055b88d23a4e5
25.07393
111
0.639403
2.397138
false
false
false
false
panpf/sketch
sketch/src/androidTest/java/com/github/panpf/sketch/test/util/SizeTest.kt
1
3845
/* * Copyright (C) 2022 panpf <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.panpf.sketch.test.util import androidx.test.ext.junit.runners.AndroidJUnit4 import com.github.panpf.sketch.util.Size import com.github.panpf.sketch.util.isNotEmpty import com.github.panpf.sketch.util.isSameAspectRatio import org.junit.Assert import org.junit.Test import org.junit.runner.RunWith @RunWith(AndroidJUnit4::class) class SizeTest { @Test fun testWidthHeight() { Size(13, 56).apply { Assert.assertEquals(13, width) Assert.assertEquals(56, height) } Size(684, 4234).apply { Assert.assertEquals(684, width) Assert.assertEquals(4234, height) } } @Test fun testEmptyNotEmpty() { Size(0, 0).apply { Assert.assertTrue(isEmpty) Assert.assertFalse(isNotEmpty) } Size(0, 45).apply { Assert.assertTrue(isEmpty) Assert.assertFalse(isNotEmpty) } Size(45, 0).apply { Assert.assertTrue(isEmpty) Assert.assertFalse(isNotEmpty) } Size(684, 4234).apply { Assert.assertFalse(isEmpty) Assert.assertTrue(isNotEmpty) } } @Test fun testComponent() { val (width, height) = Size(13, 56) Assert.assertEquals(13, width) Assert.assertEquals(56, height) val (width1, height1) = Size(684, 4234) Assert.assertEquals(684, width1) Assert.assertEquals(4234, height1) } @Test fun testIsSameAspectRatio() { Assert.assertTrue(Size(400, 200).isSameAspectRatio(Size(400, 200))) Assert.assertTrue(Size(400, 200).isSameAspectRatio(Size(200, 100))) Assert.assertFalse(Size(400, 200).isSameAspectRatio(Size(200, 99))) Assert.assertTrue(Size(400, 200).isSameAspectRatio(Size(200, 99), delta = 0.1f)) Assert.assertFalse(Size(400, 200).isSameAspectRatio(Size(200, 92), delta = 0.1f)) } @Test fun testToString() { Size(13, 56).apply { Assert.assertEquals("13x56", toString()) } Size(684, 4234).apply { Assert.assertEquals("684x4234", toString()) } } @Test fun testEquals() { val size1 = Size(13, 56) val size11 = Size(13, 56) val size2 = Size(684, 4234) val size21 = Size(684, 4234) Assert.assertNotSame(size1, size11) Assert.assertNotSame(size2, size21) Assert.assertEquals(size1, size11) Assert.assertEquals(size2, size21) Assert.assertNotEquals(size1, size2) } @Test fun testHashCode() { val size1 = Size(13, 56) val size11 = Size(13, 56) val size2 = Size(684, 4234) val size21 = Size(684, 4234) Assert.assertEquals(size1.hashCode(), size11.hashCode()) Assert.assertEquals(size2.hashCode(), size21.hashCode()) Assert.assertNotEquals(size1.hashCode(), size2.hashCode()) } @Test fun testParseSize() { Size.parseSize("13x56").apply { Assert.assertEquals("13x56", toString()) } Size.parseSize("684x4234").apply { Assert.assertEquals("684x4234", toString()) } } }
apache-2.0
caa4f40ef13fc43f64b8a76113dc5d34
28.584615
89
0.621066
3.931493
false
true
false
false
bl-lia/kktAPK
app/src/main/kotlin/com/bl_lia/kirakiratter/data/repository/datasource/status/StatusService.kt
1
903
package com.bl_lia.kirakiratter.data.repository.datasource.status import com.bl_lia.kirakiratter.domain.entity.Status import com.bl_lia.kirakiratter.domain.value_object.Media import io.reactivex.Single import okhttp3.MultipartBody import retrofit2.http.* interface StatusService { @FormUrlEncoded @POST("api/v1/statuses") fun post( @Field("status") text: String, @Field("spoiler_text") warning: String? = null, @Field("in_reply_to_id") inReplyToId: Int? = null, @Field("sensitive") sensitive: Boolean? = null, @Field("visibility") visibility: String? = null, @Field("media_ids[]") mediaIds: List<String>? = null ): Single<Status> @Multipart @POST("api/v1/media") fun uploadMedia(@Part file: MultipartBody.Part): Single<Media> }
mit
f35854f2b8a442c4009ace1b2e7f073f
28.16129
66
0.613511
4.049327
false
false
false
false
stripe/stripe-android
payments-ui-core/src/main/java/com/stripe/android/ui/core/address/TransformAddressToElement.kt
1
10496
package com.stripe.android.ui.core.address import androidx.annotation.StringRes import androidx.compose.ui.text.input.KeyboardCapitalization import androidx.compose.ui.text.input.KeyboardType import com.stripe.android.ui.core.R import com.stripe.android.ui.core.elements.AdministrativeAreaConfig import com.stripe.android.ui.core.elements.AdministrativeAreaElement import com.stripe.android.ui.core.elements.DropdownFieldController import com.stripe.android.ui.core.elements.IdentifierSpec import com.stripe.android.ui.core.elements.PostalCodeConfig import com.stripe.android.ui.core.elements.RowController import com.stripe.android.ui.core.elements.RowElement import com.stripe.android.ui.core.elements.SectionFieldElement import com.stripe.android.ui.core.elements.SectionSingleFieldElement import com.stripe.android.ui.core.elements.SimpleTextElement import com.stripe.android.ui.core.elements.SimpleTextFieldConfig import com.stripe.android.ui.core.elements.SimpleTextFieldController import com.stripe.android.ui.core.elements.TextFieldConfig import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable import kotlinx.serialization.decodeFromString import kotlinx.serialization.json.Json import java.io.InputStream import java.util.UUID @Serializable internal enum class FieldType( val serializedValue: String, val identifierSpec: IdentifierSpec, @StringRes val defaultLabel: Int ) { @SerialName("addressLine1") AddressLine1( "addressLine1", IdentifierSpec.Line1, R.string.address_label_address_line1 ), @SerialName("addressLine2") AddressLine2( "addressLine2", IdentifierSpec.Line2, R.string.address_label_address_line2 ), @SerialName("locality") Locality( "locality", IdentifierSpec.City, R.string.address_label_city ), @SerialName("dependentLocality") DependentLocality( "dependentLocality", IdentifierSpec.DependentLocality, R.string.address_label_city ), @SerialName("postalCode") PostalCode( "postalCode", IdentifierSpec.PostalCode, R.string.address_label_postal_code ) { override fun capitalization() = KeyboardCapitalization.None }, @SerialName("sortingCode") SortingCode( "sortingCode", IdentifierSpec.SortingCode, R.string.address_label_postal_code ) { override fun capitalization() = KeyboardCapitalization.None }, @SerialName("administrativeArea") AdministrativeArea( "administrativeArea", IdentifierSpec.State, NameType.State.stringResId ), @SerialName("name") Name( "name", IdentifierSpec.Name, R.string.address_label_full_name ); open fun capitalization() = KeyboardCapitalization.Words companion object { fun from(value: String) = values().firstOrNull { it.serializedValue == value } } } @Serializable internal enum class NameType(@StringRes val stringResId: Int) { @SerialName("area") Area(R.string.address_label_hk_area), @SerialName("cedex") Cedex(R.string.address_label_cedex), @SerialName("city") City(R.string.address_label_city), @SerialName("country") Country(R.string.address_label_country_or_region), @SerialName("county") County(R.string.address_label_county), @SerialName("department") Department(R.string.address_label_department), @SerialName("district") District(R.string.address_label_district), @SerialName("do_si") DoSi(R.string.address_label_kr_do_si), @SerialName("eircode") Eircode(R.string.address_label_ie_eircode), @SerialName("emirate") Emirate(R.string.address_label_ae_emirate), @SerialName("island") Island(R.string.address_label_island), @SerialName("neighborhood") Neighborhood(R.string.address_label_neighborhood), @SerialName("oblast") Oblast(R.string.address_label_oblast), @SerialName("parish") Parish(R.string.address_label_bb_jm_parish), @SerialName("pin") Pin(R.string.address_label_in_pin), @SerialName("post_town") PostTown(R.string.address_label_post_town), @SerialName("postal") Postal(R.string.address_label_postal_code), @SerialName("prefecture") Perfecture(R.string.address_label_jp_prefecture), @SerialName("province") Province(R.string.address_label_province), @SerialName("state") State(R.string.address_label_state), @SerialName("suburb") Suburb(R.string.address_label_suburb), @SerialName("suburb_or_city") SuburbOrCity(R.string.address_label_au_suburb_or_city), @SerialName("townland") Townload(R.string.address_label_ie_townland), @SerialName("village_township") VillageTownship(R.string.address_label_village_township), @SerialName("zip") Zip(R.string.address_label_zip_code) } @Serializable internal class StateSchema( @SerialName("key") val key: String, // abbreviation @SerialName("name") val name: String // display name ) @Serializable internal class FieldSchema( @SerialName("isNumeric") val isNumeric: Boolean = false, @SerialName("examples") val examples: ArrayList<String> = arrayListOf(), @SerialName("nameType") val nameType: NameType // label, ) @Serializable internal class CountryAddressSchema( @SerialName("type") val type: FieldType?, @SerialName("required") val required: Boolean, @SerialName("schema") val schema: FieldSchema? = null ) private val format = Json { ignoreUnknownKeys = true } internal fun parseAddressesSchema(inputStream: InputStream?) = getJsonStringFromInputStream(inputStream)?.let { format.decodeFromString<ArrayList<CountryAddressSchema>>( it ) } private fun getJsonStringFromInputStream(inputStream: InputStream?) = inputStream?.bufferedReader().use { it?.readText() } internal fun List<CountryAddressSchema>.transformToElementList( countryCode: String ): List<SectionFieldElement> { val countryAddressElements = this .filterNot { it.type == FieldType.SortingCode || it.type == FieldType.DependentLocality } .mapNotNull { addressField -> addressField.type?.toElement( identifierSpec = addressField.type.identifierSpec, label = addressField.schema?.nameType?.stringResId ?: addressField.type.defaultLabel, capitalization = addressField.type.capitalization(), keyboardType = getKeyboard(addressField.schema), countryCode = countryCode, showOptionalLabel = !addressField.required ) } // Put it in a single row return combineCityAndPostal(countryAddressElements) } private fun FieldType.toElement( identifierSpec: IdentifierSpec, label: Int, capitalization: KeyboardCapitalization, keyboardType: KeyboardType, countryCode: String, showOptionalLabel: Boolean ): SectionSingleFieldElement { val simpleTextElement = SimpleTextElement( identifierSpec, SimpleTextFieldController( textFieldConfig = toConfig( label = label, capitalization = capitalization, keyboardType = keyboardType, countryCode = countryCode ), showOptionalLabel = showOptionalLabel ) ) return when (this) { FieldType.AdministrativeArea -> { val supportsAdministrativeAreaDropdown = listOf( "CA", "US" ).contains(countryCode) if (supportsAdministrativeAreaDropdown) { val country = when (countryCode) { "CA" -> AdministrativeAreaConfig.Country.Canada() "US" -> AdministrativeAreaConfig.Country.US() else -> throw IllegalArgumentException() } AdministrativeAreaElement( identifierSpec, DropdownFieldController( AdministrativeAreaConfig(country) ) ) } else { simpleTextElement } } else -> simpleTextElement } } private fun FieldType.toConfig( label: Int, capitalization: KeyboardCapitalization, keyboardType: KeyboardType, countryCode: String ): TextFieldConfig { return when (this) { FieldType.PostalCode -> PostalCodeConfig( label = label, capitalization = capitalization, keyboard = keyboardType, country = countryCode ) else -> SimpleTextFieldConfig( label = label, capitalization = capitalization, keyboard = keyboardType ) } } private fun combineCityAndPostal(countryAddressElements: List<SectionSingleFieldElement>) = countryAddressElements.foldIndexed( listOf<SectionFieldElement?>() ) { index, acc, sectionSingleFieldElement -> if (index + 1 < countryAddressElements.size && isPostalNextToCity( countryAddressElements[index], countryAddressElements[index + 1] ) ) { val rowFields = listOf(countryAddressElements[index], countryAddressElements[index + 1]) acc.plus( RowElement( IdentifierSpec.Generic("row_" + UUID.randomUUID().leastSignificantBits), rowFields, RowController(rowFields) ) ) } else if (acc.lastOrNull() is RowElement) { // skip this it is in a row acc.plus(null) } else { acc.plus(sectionSingleFieldElement) } }.filterNotNull() private fun isPostalNextToCity( element1: SectionSingleFieldElement, element2: SectionSingleFieldElement ) = isCityOrPostal(element1.identifier) && isCityOrPostal(element2.identifier) private fun isCityOrPostal(identifierSpec: IdentifierSpec) = identifierSpec == IdentifierSpec.PostalCode || identifierSpec == IdentifierSpec.City private fun getKeyboard(fieldSchema: FieldSchema?) = if (fieldSchema?.isNumeric == true) { KeyboardType.NumberPassword } else { KeyboardType.Text }
mit
e8813f4a6a9cf51a181136dd02b4b233
29.074499
100
0.661585
4.472092
false
false
false
false
borgesgabriel/password
src/main/kotlin/es/gabrielborg/keystroke/Benchmark.kt
1
3058
package es.gabrielborg.keystroke import es.gabrielborg.keystroke.core.EnrolmentService import es.gabrielborg.keystroke.core.LoginService import es.gabrielborg.keystroke.utility.DataSet import es.gabrielborg.keystroke.utility.IO import es.gabrielborg.keystroke.utility.kNumberOfFeatures import es.gabrielborg.keystroke.utility.kPassword import org.apache.commons.csv.CSVFormat import java.io.FileReader import java.util.* import kotlin.util.measureTimeMillis fun main(args: Array<String>) { val records = CSVFormat.EXCEL.withHeader().parse(FileReader("./assets/dataset/dataset.csv")) for (record in records) { val featureArray = Array(kNumberOfFeatures) { record.get(it + 3).toDouble() }.toDoubleArray() DataSet[record.get("subject").toInt(), record.get("sessionIndex").toInt(), record.get("rep").toInt()] = featureArray } val confusion = Array(2) { Array(2) { 0 } } println("Time elapsed: " + measureTimeMillis { for (i in 1..51) { val username = "user$i" println("$username being tested") EnrolmentService.enroll(username, kPassword) for (j in 1..50) assert(LoginService.login(username, kPassword, DataSet[i, 1, j])) val loginSequence = ArrayList<DoubleArray>() for (j in 1..50) for (k in 2..8) loginSequence.add(DataSet[i, k, j]) // called 350 times for (j in 1..51) { if (i == j) continue for (k in 1..7) { loginSequence.add(DataSet[j, k, k]) // called 350 times } } for (j in 0..349) { // authentic login var result = LoginService.login(username, kPassword, loginSequence[j]) if (result) ++confusion[0][0] else ++confusion[0][1] // non-authentic login result = LoginService.login(username, kPassword, loginSequence[350 + j]) if (result) ++confusion[1][0] else ++confusion[1][1] } IO.deleteUser(username) } } / 1000.0) println("Results:") println("Confusion matrix:\n${confusion[0][0]} ${confusion[0][1]}\n${confusion[1][0]} ${confusion[1][1]}") val total = (confusion[0][0] + confusion[0][1] + confusion[1][0] + confusion[1][1]).toDouble() / 100 println("Normalised confusion matrix:\n${confusion[0][0] / total} ${confusion[0][1] / total}\n" + "${confusion[1][0] / total} ${confusion[1][1] / total}") val sum = { a: Int, b: Int -> a + b } println("Distinguishing features:\n" + "${DataSet.distinguishing.joinToString()}\n" + "${DataSet.nonDistinguishing.joinToString()}\n" + "${DataSet.distinguishing.reduce(sum)}/${DataSet.nonDistinguishing.reduce(sum)} = " + "${100 * DataSet.distinguishing.reduce(sum) / (DataSet.distinguishing.reduce(sum) + DataSet.nonDistinguishing.reduce(sum))}") }
gpl-3.0
7851b012e372616aa8c8f8ed3f8abb3d
41.472222
137
0.589274
3.779975
false
false
false
false
exponent/exponent
android/versioned-abis/expoview-abi44_0_0/src/main/java/abi44_0_0/expo/modules/imagepicker/ImagePickerModule.kt
2
16833
package abi44_0_0.expo.modules.imagepicker import android.Manifest import android.app.Activity import android.content.Context import android.content.Intent import android.graphics.Bitmap import android.media.MediaMetadataRetriever import android.net.Uri import android.os.Bundle import android.provider.MediaStore import android.util.Log import com.theartofdev.edmodo.cropper.CropImage import abi44_0_0.expo.modules.core.ExportedModule import abi44_0_0.expo.modules.core.ModuleRegistry import abi44_0_0.expo.modules.core.ModuleRegistryDelegate import abi44_0_0.expo.modules.core.Promise import abi44_0_0.expo.modules.core.errors.ModuleDestroyedException import abi44_0_0.expo.modules.core.interfaces.ActivityEventListener import abi44_0_0.expo.modules.core.interfaces.ActivityProvider import abi44_0_0.expo.modules.core.interfaces.ExpoMethod import abi44_0_0.expo.modules.core.interfaces.LifecycleEventListener import abi44_0_0.expo.modules.core.interfaces.services.UIManager import abi44_0_0.expo.modules.core.utilities.FileUtilities.generateOutputPath import abi44_0_0.expo.modules.core.utilities.ifNull import abi44_0_0.expo.modules.imagepicker.ImagePickerOptions.Companion.optionsFromMap import abi44_0_0.expo.modules.imagepicker.exporters.CompressionImageExporter import abi44_0_0.expo.modules.imagepicker.exporters.CropImageExporter import abi44_0_0.expo.modules.imagepicker.exporters.ImageExporter import abi44_0_0.expo.modules.imagepicker.exporters.RawImageExporter import abi44_0_0.expo.modules.imagepicker.fileproviders.CacheFileProvider import abi44_0_0.expo.modules.imagepicker.fileproviders.CropFileProvider import abi44_0_0.expo.modules.imagepicker.tasks.ImageResultTask import abi44_0_0.expo.modules.imagepicker.tasks.VideoResultTask import abi44_0_0.expo.modules.interfaces.imageloader.ImageLoaderInterface import abi44_0_0.expo.modules.interfaces.permissions.Permissions import abi44_0_0.expo.modules.interfaces.permissions.PermissionsResponse import abi44_0_0.expo.modules.interfaces.permissions.PermissionsResponseListener import abi44_0_0.expo.modules.interfaces.permissions.PermissionsStatus import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.cancel import java.io.IOException import java.lang.ref.WeakReference class ImagePickerModule( private val mContext: Context, private val moduleRegistryDelegate: ModuleRegistryDelegate = ModuleRegistryDelegate(), private val pickerResultStore: PickerResultsStore = PickerResultsStore(mContext) ) : ExportedModule(mContext), ActivityEventListener, LifecycleEventListener { private var mCameraCaptureURI: Uri? = null private var mPromise: Promise? = null private var mPickerOptions: ImagePickerOptions? = null private val moduleCoroutineScope = CoroutineScope(Dispatchers.IO) private var exifDataHandler: ExifDataHandler? = null override fun onDestroy() { try { mUIManager.unregisterLifecycleEventListener(this) moduleCoroutineScope.cancel(ModuleDestroyedException(ImagePickerConstants.PROMISES_CANCELED)) } catch (e: IllegalStateException) { Log.e(ImagePickerConstants.TAG, "The scope does not have a job in it") } } /** * Android system sometimes kills the `MainActivity` after the `ImagePicker` finishes. * Moreover, the react context will be reloaded again in such a case. We need to handle this situation. * To do it we track if the current activity was destroyed. */ private var mWasHostDestroyed = false private val mImageLoader: ImageLoaderInterface by moduleRegistry() private val mUIManager: UIManager by moduleRegistry() private val mPermissions: Permissions by moduleRegistry() private val mActivityProvider: ActivityProvider by moduleRegistry() private lateinit var _experienceActivity: WeakReference<Activity> private val experienceActivity: Activity? get() { if (!this::_experienceActivity.isInitialized) { _experienceActivity = WeakReference(mActivityProvider.currentActivity) } return _experienceActivity.get() } private inline fun <reified T> moduleRegistry() = moduleRegistryDelegate.getFromModuleRegistry<T>() override fun onCreate(moduleRegistry: ModuleRegistry) { moduleRegistryDelegate.onCreate(moduleRegistry) mUIManager.registerLifecycleEventListener(this) } override fun getName() = "ExponentImagePicker" //region expo methods @ExpoMethod fun requestMediaLibraryPermissionsAsync(writeOnly: Boolean, promise: Promise) { Permissions.askForPermissionsWithPermissionsManager(mPermissions, promise, *getMediaLibraryPermissions(writeOnly)) } @ExpoMethod fun getMediaLibraryPermissionsAsync(writeOnly: Boolean, promise: Promise) { Permissions.getPermissionsWithPermissionsManager(mPermissions, promise, *getMediaLibraryPermissions(writeOnly)) } @ExpoMethod fun requestCameraPermissionsAsync(promise: Promise) { Permissions.askForPermissionsWithPermissionsManager(mPermissions, promise, Manifest.permission.CAMERA) } @ExpoMethod fun getCameraPermissionsAsync(promise: Promise) { Permissions.getPermissionsWithPermissionsManager(mPermissions, promise, Manifest.permission.CAMERA) } @ExpoMethod fun getPendingResultAsync(promise: Promise) { promise.resolve(pickerResultStore.getAllPendingResults()) } // NOTE: Currently not reentrant / doesn't support concurrent requests @ExpoMethod fun launchCameraAsync(options: Map<String, Any?>, promise: Promise) { val pickerOptions = optionsFromMap(options, promise) ?: return val activity = experienceActivity.ifNull { promise.reject(ImagePickerConstants.ERR_MISSING_ACTIVITY, ImagePickerConstants.MISSING_ACTIVITY_MESSAGE) return } val intentType = if (pickerOptions.mediaTypes == MediaTypes.VIDEOS) MediaStore.ACTION_VIDEO_CAPTURE else MediaStore.ACTION_IMAGE_CAPTURE val cameraIntent = Intent(intentType) cameraIntent.resolveActivity(activity.application.packageManager).ifNull { promise.reject(IllegalStateException("Error resolving activity")) return } val permissionsResponseHandler = PermissionsResponseListener { permissionsResponse: Map<String, PermissionsResponse> -> if (permissionsResponse[Manifest.permission.WRITE_EXTERNAL_STORAGE]?.status == PermissionsStatus.GRANTED && permissionsResponse[Manifest.permission.CAMERA]?.status == PermissionsStatus.GRANTED ) { launchCameraWithPermissionsGranted(promise, cameraIntent, pickerOptions) } else { promise.reject(SecurityException("User rejected permissions")) } } mPermissions.askForPermissions(permissionsResponseHandler, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA) } // NOTE: Currently not reentrant / doesn't support concurrent requests @ExpoMethod fun launchImageLibraryAsync(options: Map<String, Any?>, promise: Promise) { val pickerOptions = optionsFromMap(options, promise) ?: return val libraryIntent = Intent().apply { when (pickerOptions.mediaTypes) { MediaTypes.IMAGES -> type = "image/*" MediaTypes.VIDEOS -> type = "video/*" MediaTypes.ALL -> { type = "*/*" putExtra(Intent.EXTRA_MIME_TYPES, arrayOf("image/*", "video/*")) } } action = Intent.ACTION_GET_CONTENT } startActivityOnResult(libraryIntent, ImagePickerConstants.REQUEST_LAUNCH_IMAGE_LIBRARY, promise, pickerOptions) } //endregion //region helpers private fun getMediaLibraryPermissions(writeOnly: Boolean): Array<String> { return if (writeOnly) { arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE) } else { arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE) } } private fun launchCameraWithPermissionsGranted(promise: Promise, cameraIntent: Intent, pickerOptions: ImagePickerOptions) { val imageFile = createOutputFile( mContext.cacheDir, if (pickerOptions.mediaTypes == MediaTypes.VIDEOS) ".mp4" else ".jpg" ).ifNull { promise.reject(IOException("Could not create image file.")) return } mCameraCaptureURI = uriFromFile(imageFile) val activity = experienceActivity.ifNull { promise.reject(ImagePickerConstants.ERR_MISSING_ACTIVITY, ImagePickerConstants.MISSING_ACTIVITY_MESSAGE) return } mPromise = promise mPickerOptions = pickerOptions if (pickerOptions.videoMaxDuration > 0) { cameraIntent.putExtra(MediaStore.EXTRA_DURATION_LIMIT, pickerOptions.videoMaxDuration) } // camera intent needs a content URI but we need a file one cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, contentUriFromFile(imageFile, activity.application)) startActivityOnResult(cameraIntent, ImagePickerConstants.REQUEST_LAUNCH_CAMERA, promise, pickerOptions) } /** * Starts the crop intent. * * @param promise Promise which will be rejected if something goes wrong * @param uri Uri to file which will be cropped * @param type Media type of source file * @param needGenerateFile Tells if generating a new file is needed * @param pickerOptions Additional options */ private fun startCropIntent(promise: Promise, uri: Uri, type: String, needGenerateFile: Boolean, pickerOptions: ImagePickerOptions) { var extension = ".jpg" var compressFormat = Bitmap.CompressFormat.JPEG // if the image is created by camera intent we don't need a new path - it's been already saved when { type.contains("png") -> { compressFormat = Bitmap.CompressFormat.PNG extension = ".png" } type.contains("gif") -> { // If we allow editing, the result image won't ever be a GIF as the cropper doesn't support it. // Let's convert to PNG in such case. extension = ".png" compressFormat = Bitmap.CompressFormat.PNG } type.contains("bmp") -> { // If we allow editing, the result image won't ever be a BMP as the cropper doesn't support it. // Let's convert to PNG in such case. extension = ".png" compressFormat = Bitmap.CompressFormat.PNG } !type.contains("jpeg") -> { Log.w(ImagePickerConstants.TAG, "Image type not supported. Falling back to JPEG instead.") extension = ".jpg" } } val fileUri: Uri = try { if (needGenerateFile) { uriFromFilePath(generateOutputPath(mContext.cacheDir, ImagePickerConstants.CACHE_DIR_NAME, extension)) } else { uri } } catch (e: IOException) { promise.reject(ImagePickerConstants.ERR_CAN_NOT_OPEN_CROP, ImagePickerConstants.CAN_NOT_OPEN_CROP_MESSAGE, e) return } val cropImageBuilder = CropImage.activity(uri).apply { pickerOptions.forceAspect?.let { (x, y) -> setAspectRatio((x as Number).toInt(), (y as Number).toInt()) setFixAspectRatio(true) setInitialCropWindowPaddingRatio(0f) } setOutputUri(fileUri) setOutputCompressFormat(compressFormat) setOutputCompressQuality(pickerOptions.quality) } exifDataHandler = ExifDataHandler(uri) startActivityOnResult(cropImageBuilder.getIntent(context), CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE, promise, pickerOptions) } //endregion // region ActivityEventListener override fun onNewIntent(intent: Intent) = Unit override fun onActivityResult(activity: Activity, requestCode: Int, resultCode: Int, data: Intent?) { if (shouldHandleOnActivityResult(activity, requestCode)) { mUIManager.unregisterActivityEventListener(this) var pickerOptions = mPickerOptions!! val promise = if (mWasHostDestroyed && mPromise !is PendingPromise) { if (pickerOptions.isBase64) { // we know that the activity was killed and we don't want to store // base64 into `SharedPreferences`... pickerOptions = ImagePickerOptions( pickerOptions.quality, pickerOptions.isAllowsEditing, pickerOptions.forceAspect, false, pickerOptions.mediaTypes, pickerOptions.isExif, pickerOptions.videoMaxDuration ) // ...but we need to remember to add it later. PendingPromise(pickerResultStore, isBase64 = true) } else { PendingPromise(pickerResultStore) } } else { mPromise!! } mPromise = null mPickerOptions = null handleOnActivityResult(promise, activity, requestCode, resultCode, data, pickerOptions) } } //endregion //region activity for result private fun startActivityOnResult(intent: Intent, requestCode: Int, promise: Promise, pickerOptions: ImagePickerOptions) { experienceActivity .ifNull { promise.reject(ImagePickerConstants.ERR_MISSING_ACTIVITY, ImagePickerConstants.MISSING_ACTIVITY_MESSAGE) return } .also { mUIManager.registerActivityEventListener(this) mPromise = promise mPickerOptions = pickerOptions } .startActivityForResult(intent, requestCode) } private fun shouldHandleOnActivityResult(activity: Activity, requestCode: Int): Boolean { return experienceActivity != null && mPromise != null && mPickerOptions != null && // When we launched the crop tool and the android kills current activity, the references can be different. // So, we fallback to the requestCode in this case. (activity === experienceActivity || mWasHostDestroyed && requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) } private fun handleOnActivityResult(promise: Promise, activity: Activity, requestCode: Int, resultCode: Int, intent: Intent?, pickerOptions: ImagePickerOptions) { if (resultCode != Activity.RESULT_OK) { promise.resolve( Bundle().apply { putBoolean("cancelled", true) } ) return } val contentResolver = activity.application.contentResolver if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) { val result = CropImage.getActivityResult(intent) val exporter = CropImageExporter(result.rotation, result.cropRect, pickerOptions.isBase64) ImageResultTask( promise, result.uri, contentResolver, CropFileProvider(result.uri), pickerOptions.isAllowsEditing, pickerOptions.isExif, exporter, exifDataHandler, moduleCoroutineScope ).execute() return } val uri = (if (requestCode == ImagePickerConstants.REQUEST_LAUNCH_CAMERA) mCameraCaptureURI else intent?.data) .ifNull { promise.reject(ImagePickerConstants.ERR_MISSING_URL, ImagePickerConstants.MISSING_URL_MESSAGE) return } val type = getType(contentResolver, uri).ifNull { promise.reject(ImagePickerConstants.ERR_CAN_NOT_DEDUCE_TYPE, ImagePickerConstants.CAN_NOT_DEDUCE_TYPE_MESSAGE) return } if (type.contains("image")) { if (pickerOptions.isAllowsEditing) { // if the image is created by camera intent we don't need a new file - it's been already saved val needGenerateFile = requestCode != ImagePickerConstants.REQUEST_LAUNCH_CAMERA startCropIntent(promise, uri, type, needGenerateFile, pickerOptions) return } val exporter: ImageExporter = if (pickerOptions.quality == ImagePickerConstants.DEFAULT_QUALITY) { RawImageExporter(contentResolver, pickerOptions.isBase64) } else { CompressionImageExporter(mImageLoader, pickerOptions.quality, pickerOptions.isBase64) } ImageResultTask( promise, uri, contentResolver, CacheFileProvider(mContext.cacheDir, deduceExtension(type)), pickerOptions.isAllowsEditing, pickerOptions.isExif, exporter, exifDataHandler, moduleCoroutineScope ).execute() return } try { val metadataRetriever = MediaMetadataRetriever().apply { setDataSource(mContext, uri) } VideoResultTask(promise, uri, contentResolver, CacheFileProvider(mContext.cacheDir, ".mp4"), metadataRetriever, moduleCoroutineScope).execute() } catch (e: RuntimeException) { e.printStackTrace() promise.reject(ImagePickerConstants.ERR_CAN_NOT_EXTRACT_METADATA, ImagePickerConstants.CAN_NOT_EXTRACT_METADATA_MESSAGE, e) return } } //endregion //region LifecycleEventListener override fun onHostDestroy() { mWasHostDestroyed = true } override fun onHostResume() { if (mWasHostDestroyed) { _experienceActivity = WeakReference(mActivityProvider.currentActivity) mWasHostDestroyed = false } } override fun onHostPause() = Unit //endregion }
bsd-3-clause
f1901f6c889364ebd9b49cf2084b4fa1
36.997743
163
0.731599
4.653857
false
false
false
false
Undin/intellij-rust
src/main/kotlin/org/rust/ide/annotator/RsAnnotationHolder.kt
2
2193
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.ide.annotator import com.intellij.codeInsight.intention.IntentionAction import com.intellij.codeInspection.util.InspectionMessage import com.intellij.lang.annotation.AnnotationBuilder import com.intellij.lang.annotation.AnnotationHolder import com.intellij.lang.annotation.AnnotationSession import com.intellij.lang.annotation.HighlightSeverity import com.intellij.psi.PsiElement import org.rust.lang.core.psi.ext.existsAfterExpansion class RsAnnotationHolder(val holder: AnnotationHolder) { fun createErrorAnnotation(element: PsiElement, @InspectionMessage message: String?, vararg fixes: IntentionAction) { newErrorAnnotation(element, message, *fixes)?.create() } fun createWeakWarningAnnotation(element: PsiElement, @InspectionMessage message: String?, vararg fixes: IntentionAction) { newWeakWarningAnnotation(element, message, *fixes)?.create() } fun newErrorAnnotation( element: PsiElement, @InspectionMessage message: String?, vararg fixes: IntentionAction ): AnnotationBuilder? = newAnnotation(element, HighlightSeverity.ERROR, message, *fixes) fun newWeakWarningAnnotation( element: PsiElement, @InspectionMessage message: String?, vararg fixes: IntentionAction ): AnnotationBuilder? = newAnnotation(element, HighlightSeverity.WEAK_WARNING, message, *fixes) fun newAnnotation( element: PsiElement, severity: HighlightSeverity, @InspectionMessage message: String?, vararg fixes: IntentionAction ): AnnotationBuilder? { if (!element.existsAfterExpansion(currentAnnotationSession.currentCrate())) return null val builder = if (message == null) { holder.newSilentAnnotation(severity) } else { holder.newAnnotation(severity, message) } builder.range(element) for (fix in fixes) { builder.withFix(fix) } return builder } val currentAnnotationSession: AnnotationSession = holder.currentAnnotationSession }
mit
ee49171f36e625ecbabff94782a2c394
35.55
126
0.725034
4.961538
false
false
false
false
Undin/intellij-rust
src/main/kotlin/org/rust/ide/actions/ToggleExternalLinterOnTheFlyAction.kt
4
970
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.ide.actions import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.ToggleAction import org.rust.cargo.project.settings.rustSettings class ToggleExternalLinterOnTheFlyAction : ToggleAction() { override fun isSelected(e: AnActionEvent): Boolean { val project = e.project ?: return false return project.rustSettings.runExternalLinterOnTheFly } override fun setSelected(e: AnActionEvent, state: Boolean) { val project = e.project ?: return project.rustSettings.modify { it.runExternalLinterOnTheFly = state } } override fun update(e: AnActionEvent) { super.update(e) val externalLinterName = e.project?.rustSettings?.externalLinter?.title ?: "External Linter" e.presentation.text = "Run $externalLinterName on the Fly" } }
mit
d5f33f5068a7f73f94c6f61d6e72eb82
32.448276
100
0.725773
4.235808
false
false
false
false
Undin/intellij-rust
src/main/kotlin/org/rust/ide/formatter/settings/RsCodeStyleSettings.kt
3
980
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.ide.formatter.settings import com.intellij.psi.codeStyle.CodeStyleSettings import com.intellij.psi.codeStyle.CustomCodeStyleSettings @Suppress("PropertyName") class RsCodeStyleSettings(container: CodeStyleSettings) : CustomCodeStyleSettings(RsCodeStyleSettings::class.java.simpleName, container) { @JvmField var ALIGN_RET_TYPE: Boolean = true @JvmField var ALIGN_WHERE_CLAUSE: Boolean = false @JvmField var ALIGN_TYPE_PARAMS: Boolean = false @JvmField var ALIGN_WHERE_BOUNDS: Boolean = true @JvmField var INDENT_WHERE_CLAUSE: Boolean = true @JvmField var ALLOW_ONE_LINE_MATCH: Boolean = false @JvmField var MIN_NUMBER_OF_BLANKS_BETWEEN_ITEMS: Int = 1 @JvmField var PRESERVE_PUNCTUATION: Boolean = false @JvmField var SPACE_AROUND_ASSOC_TYPE_BINDING: Boolean = false }
mit
19fac13c4fbe1bf22199f1954880c5a7
22.902439
84
0.72449
4.135021
false
false
false
false
HabitRPG/habitrpg-android
Habitica/src/main/java/com/habitrpg/android/habitica/ui/adapter/social/ChallengesListViewAdapter.kt
1
4407
package com.habitrpg.android.habitica.ui.adapter.social import android.view.View import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import com.habitrpg.android.habitica.R import com.habitrpg.android.habitica.databinding.ChallengeItemBinding import com.habitrpg.android.habitica.extensions.inflate import com.habitrpg.android.habitica.models.social.Challenge import com.habitrpg.android.habitica.models.social.ChallengeMembership import com.habitrpg.android.habitica.ui.adapter.BaseRecyclerViewAdapter import com.habitrpg.android.habitica.ui.fragments.social.challenges.ChallengeFilterOptions import com.habitrpg.android.habitica.ui.helpers.EmojiParser import com.habitrpg.android.habitica.ui.views.HabiticaIconsHelper import io.reactivex.rxjava3.core.BackpressureStrategy import io.reactivex.rxjava3.core.Flowable import io.reactivex.rxjava3.subjects.PublishSubject import io.realm.OrderedRealmCollection class ChallengesListViewAdapter(private val viewUserChallengesOnly: Boolean, private val userId: String) : BaseRecyclerViewAdapter<Challenge, ChallengesListViewAdapter.ChallengeViewHolder>() { private var unfilteredData: List<Challenge>? = null private var challengeMemberships: List<ChallengeMembership>? = null private val openChallengeFragmentEvents = PublishSubject.create<String>() override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ChallengeViewHolder { return ChallengeViewHolder(parent.inflate(R.layout.challenge_item), viewUserChallengesOnly) } override fun onBindViewHolder(holder: ChallengeViewHolder, position: Int) { data[position].let { challenge -> holder.bind(challenge, challengeMemberships?.first { challenge.id == it.challengeID } != null) holder.itemView.setOnClickListener { if (challenge.isManaged && challenge.isValid) { challenge.id?.let { openChallengeFragmentEvents.onNext(it) } } } } } fun updateUnfilteredData(data: List<Challenge>?) { this.data = data ?: emptyList() unfilteredData = data } fun filter(filterOptions: ChallengeFilterOptions) { val unfilteredData = unfilteredData as? OrderedRealmCollection ?: return var query = unfilteredData.where() if (filterOptions.showByGroups != null && filterOptions.showByGroups.size > 0) { val groupIds = arrayOfNulls<String>(filterOptions.showByGroups.size) var index = 0 for (group in filterOptions.showByGroups) { groupIds[index] = group.id index += 1 } query = query?.`in`("groupId", groupIds) } if (filterOptions.showOwned != filterOptions.notOwned) { query = if (filterOptions.showOwned) { query?.equalTo("leaderId", userId) } else { query?.notEqualTo("leaderId", userId) } } query?.let { data = it.findAll() } } fun getOpenDetailFragmentFlowable(): Flowable<String> { return openChallengeFragmentEvents.toFlowable(BackpressureStrategy.DROP) } class ChallengeViewHolder internal constructor(itemView: View, private val viewUserChallengesOnly: Boolean) : RecyclerView.ViewHolder(itemView) { private val binding = ChallengeItemBinding.bind(itemView) private var challenge: Challenge? = null init { binding.gemIcon.setImageBitmap(HabiticaIconsHelper.imageOfGem()) } fun bind(challenge: Challenge, isParticipating: Boolean) { this.challenge = challenge binding.challengeName.text = EmojiParser.parseEmojis(challenge.name?.trim { it <= ' ' }) binding.challengeShorttext.text = challenge.summary binding.officialChallengeView.visibility = if (challenge.official) View.VISIBLE else View.GONE if (viewUserChallengesOnly) { binding.isJoinedLabel.visibility = View.GONE } else { binding.isJoinedLabel.visibility = if (isParticipating) View.VISIBLE else View.GONE } binding.participantCount.text = challenge.memberCount.toString() binding.gemPrizeTextView.text = challenge.prize.toString() } } }
gpl-3.0
7258d351e59721df36e1d7bf30ec2cd5
40.186916
192
0.689131
4.951685
false
false
false
false
kiruto/debug-bottle
blockcanary/src/main/kotlin/com/exyui/android/debugbottle/ui/layout/__Notifier.kt
1
2793
package com.exyui.android.debugbottle.ui.layout import android.annotation.TargetApi import android.app.Notification import android.app.NotificationManager import android.app.PendingIntent import android.content.Context import android.content.Intent import com.exyui.android.debugbottle.core.__OnBlockEventInterceptor import com.exyui.android.debugbottle.ui.R import android.app.PendingIntent.FLAG_UPDATE_CURRENT import android.os.Build.VERSION.SDK_INT import android.os.Build.VERSION_CODES.HONEYCOMB import android.os.Build.VERSION_CODES.JELLY_BEAN /** * Created by yuriel on 8/9/16. */ internal class __Notifier : __OnBlockEventInterceptor { override fun onBlockEvent(context: Context, timeStart: String) { val intent = Intent(context, __DisplayBlockActivity::class.java) intent.putExtra("show_latest", timeStart) intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP val pendingIntent = PendingIntent.getActivity(context, 1, intent, FLAG_UPDATE_CURRENT) val contentTitle = context.getString(R.string.__block_canary_class_has_blocked, timeStart) val contentText = context.getString(R.string.__block_canary_notification_message) show(context, contentTitle, contentText, pendingIntent) } @Suppress("DEPRECATION") @TargetApi(HONEYCOMB) private fun show(context: Context, contentTitle: String, contentText: String, pendingIntent: PendingIntent) { val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager val notification: Notification // if (SDK_INT < HONEYCOMB) { // notification = Notification() // notification.icon = R.drawable.__block_canary_notification // notification.`when` = System.currentTimeMillis() // notification.flags = notification.flags or Notification.FLAG_AUTO_CANCEL // notification.defaults = Notification.DEFAULT_SOUND // notification.setLatestEventInfo(context, contentTitle, contentText, pendingIntent) // } else { val builder = Notification.Builder(context) .setSmallIcon(R.drawable.__block_canary_notification) .setWhen(System.currentTimeMillis()) .setContentTitle(contentTitle) .setContentText(contentText) .setAutoCancel(true) .setContentIntent(pendingIntent) .setDefaults(Notification.DEFAULT_SOUND) if (SDK_INT < JELLY_BEAN) { notification = builder.notification } else { notification = builder.build() } // } notificationManager.notify(0xDEAFBEEF.toInt(), notification) } }
apache-2.0
b7b28a694658b871cd6863a9e593b10c
44.786885
113
0.688507
4.686242
false
false
false
false
androidx/androidx
compose/material3/material3/src/commonMain/kotlin/androidx/compose/material3/AlertDialog.kt
3
8432
/* * 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.compose.material3 import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.sizeIn import androidx.compose.material3.tokens.DialogTokens import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.Shape import androidx.compose.ui.layout.Layout import androidx.compose.ui.layout.Placeable import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import kotlin.math.max @Composable internal fun AlertDialogContent( buttons: @Composable () -> Unit, modifier: Modifier = Modifier, icon: (@Composable () -> Unit)?, title: (@Composable () -> Unit)?, text: @Composable (() -> Unit)?, shape: Shape, containerColor: Color, tonalElevation: Dp, buttonContentColor: Color, iconContentColor: Color, titleContentColor: Color, textContentColor: Color, ) { Surface( modifier = modifier, shape = shape, color = containerColor, tonalElevation = tonalElevation, ) { Column( modifier = Modifier .sizeIn(minWidth = MinWidth, maxWidth = MaxWidth) .padding(DialogPadding) ) { icon?.let { CompositionLocalProvider(LocalContentColor provides iconContentColor) { Box( Modifier .padding(IconPadding) .align(Alignment.CenterHorizontally) ) { icon() } } } title?.let { CompositionLocalProvider(LocalContentColor provides titleContentColor) { val textStyle = MaterialTheme.typography.fromToken(DialogTokens.HeadlineFont) ProvideTextStyle(textStyle) { Box( // Align the title to the center when an icon is present. Modifier .padding(TitlePadding) .align( if (icon == null) { Alignment.Start } else { Alignment.CenterHorizontally } ) ) { title() } } } } text?.let { CompositionLocalProvider(LocalContentColor provides textContentColor) { val textStyle = MaterialTheme.typography.fromToken(DialogTokens.SupportingTextFont) ProvideTextStyle(textStyle) { Box( Modifier .weight(weight = 1f, fill = false) .padding(TextPadding) .align(Alignment.Start) ) { text() } } } } Box(modifier = Modifier.align(Alignment.End)) { CompositionLocalProvider(LocalContentColor provides buttonContentColor) { val textStyle = MaterialTheme.typography.fromToken(DialogTokens.ActionLabelTextFont) ProvideTextStyle(value = textStyle, content = buttons) } } } } } /** * Simple clone of FlowRow that arranges its children in a horizontal flow with limited * customization. */ @Composable internal fun AlertDialogFlowRow( mainAxisSpacing: Dp, crossAxisSpacing: Dp, content: @Composable () -> Unit ) { Layout(content) { measurables, constraints -> val sequences = mutableListOf<List<Placeable>>() val crossAxisSizes = mutableListOf<Int>() val crossAxisPositions = mutableListOf<Int>() var mainAxisSpace = 0 var crossAxisSpace = 0 val currentSequence = mutableListOf<Placeable>() var currentMainAxisSize = 0 var currentCrossAxisSize = 0 // Return whether the placeable can be added to the current sequence. fun canAddToCurrentSequence(placeable: Placeable) = currentSequence.isEmpty() || currentMainAxisSize + mainAxisSpacing.roundToPx() + placeable.width <= constraints.maxWidth // Store current sequence information and start a new sequence. fun startNewSequence() { if (sequences.isNotEmpty()) { crossAxisSpace += crossAxisSpacing.roundToPx() } sequences += currentSequence.toList() crossAxisSizes += currentCrossAxisSize crossAxisPositions += crossAxisSpace crossAxisSpace += currentCrossAxisSize mainAxisSpace = max(mainAxisSpace, currentMainAxisSize) currentSequence.clear() currentMainAxisSize = 0 currentCrossAxisSize = 0 } for (measurable in measurables) { // Ask the child for its preferred size. val placeable = measurable.measure(constraints) // Start a new sequence if there is not enough space. if (!canAddToCurrentSequence(placeable)) startNewSequence() // Add the child to the current sequence. if (currentSequence.isNotEmpty()) { currentMainAxisSize += mainAxisSpacing.roundToPx() } currentSequence.add(placeable) currentMainAxisSize += placeable.width currentCrossAxisSize = max(currentCrossAxisSize, placeable.height) } if (currentSequence.isNotEmpty()) startNewSequence() val mainAxisLayoutSize = max(mainAxisSpace, constraints.minWidth) val crossAxisLayoutSize = max(crossAxisSpace, constraints.minHeight) val layoutWidth = mainAxisLayoutSize val layoutHeight = crossAxisLayoutSize layout(layoutWidth, layoutHeight) { sequences.forEachIndexed { i, placeables -> val childrenMainAxisSizes = IntArray(placeables.size) { j -> placeables[j].width + if (j < placeables.lastIndex) mainAxisSpacing.roundToPx() else 0 } val arrangement = Arrangement.Bottom // TODO(soboleva): rtl support // Handle vertical direction val mainAxisPositions = IntArray(childrenMainAxisSizes.size) { 0 } with(arrangement) { arrange(mainAxisLayoutSize, childrenMainAxisSizes, mainAxisPositions) } placeables.forEachIndexed { j, placeable -> placeable.place( x = mainAxisPositions[j], y = crossAxisPositions[i] ) } } } } } // Paddings for each of the dialog's parts. private val DialogPadding = PaddingValues(all = 24.dp) private val IconPadding = PaddingValues(bottom = 16.dp) private val TitlePadding = PaddingValues(bottom = 16.dp) private val TextPadding = PaddingValues(bottom = 24.dp) private val MinWidth = 280.dp private val MaxWidth = 560.dp
apache-2.0
78dfe9b9850d9adf02b7b2dac41aba81
36.642857
97
0.579222
5.803166
false
false
false
false
androidx/androidx
room/room-compiler/src/main/kotlin/androidx/room/writer/EntityCursorConverterWriter.kt
3
3374
/* * Copyright (C) 2016 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.writer import androidx.room.compiler.codegen.CodeLanguage import androidx.room.compiler.codegen.XCodeBlock import androidx.room.compiler.codegen.XFunSpec import androidx.room.compiler.codegen.XTypeName import androidx.room.ext.AndroidTypeNames.CURSOR import androidx.room.ext.RoomMemberNames import androidx.room.ext.capitalize import androidx.room.ext.stripNonJava import androidx.room.solver.CodeGenScope import androidx.room.vo.Entity import androidx.room.vo.FieldWithIndex import java.util.Locale class EntityCursorConverterWriter(val entity: Entity) : TypeWriter.SharedFunctionSpec( "entityCursorConverter_${entity.typeName.toString(CodeLanguage.JAVA).stripNonJava()}" ) { override fun getUniqueKey(): String { return "generic_entity_converter_of_${entity.element.qualifiedName}" } override fun prepare(methodName: String, writer: TypeWriter, builder: XFunSpec.Builder) { builder.apply { val cursorParamName = "cursor" addParameter(CURSOR, cursorParamName) returns(entity.typeName) addCode(buildConvertMethodBody(writer, cursorParamName)) } } private fun buildConvertMethodBody(writer: TypeWriter, cursorParamName: String): XCodeBlock { val scope = CodeGenScope(writer) val entityVar = scope.getTmpVar("_entity") scope.builder.apply { addLocalVariable( entityVar, entity.typeName ) val fieldsWithIndices = entity.fields.map { val indexVar = scope.getTmpVar( "_cursorIndexOf${it.name.stripNonJava().capitalize(Locale.US)}" ) addLocalVariable( name = indexVar, typeName = XTypeName.PRIMITIVE_INT, assignExpr = XCodeBlock.of( language, "%M(%N, %S)", RoomMemberNames.CURSOR_UTIL_GET_COLUMN_INDEX, cursorParamName, it.columnName ) ) FieldWithIndex( field = it, indexVar = indexVar, alwaysExists = false ) } FieldReadWriteWriter.readFromCursor( outVar = entityVar, outPojo = entity, cursorVar = cursorParamName, fieldsWithIndices = fieldsWithIndices, relationCollectors = emptyList(), // no relationship for entities scope = scope ) addStatement("return %L", entityVar) } return scope.generate() } }
apache-2.0
e9ad465eda1f4fcab6cf60c980e9ab13
36.910112
97
0.621221
4.918367
false
false
false
false
mikrobi/TransitTracker_android
app/src/main/java/de/jakobclass/transittracker/factories/Bitmap+Stop.kt
1
2360
package de.jakobclass.transittracker.factories import android.graphics.* import de.jakobclass.transittracker.models.Stop fun Bitmap(stop: Stop, scale: Float): Bitmap { val typeRectHeight = (12 * scale).toInt() val typeRectHeightPadding = (3 * scale).toInt() val containerWidth = stop.vehicleTypes.size * (typeRectHeight + typeRectHeightPadding) + typeRectHeightPadding val containerHeight = typeRectHeight + 2 * typeRectHeightPadding val pinHeight = (15 * scale).toInt() val height = containerHeight + pinHeight val bitmap = android.graphics.Bitmap.createBitmap(containerWidth, containerHeight + pinHeight, android.graphics.Bitmap.Config.ARGB_8888) val canvas = Canvas(bitmap) val container = Rect(0, 0, containerWidth, containerHeight) val cornerRadius = 4.0f * scale var style = Paint() style.style = Paint.Style.FILL style.color = Color.WHITE style.alpha = 191 canvas.drawRoundRect(RectF(container), cornerRadius, cornerRadius, style) style = Paint() style.style = Paint.Style.STROKE style.color = Color.LTGRAY canvas.drawRoundRect(RectF(container), cornerRadius, cornerRadius, style) style = Paint() style.strokeWidth = 1.0f * scale style.color = Color.DKGRAY canvas.drawLine(containerWidth.toFloat() / 2, containerHeight.toFloat(), containerWidth.toFloat() / 2, height.toFloat(), style) style = Paint() style.textSize = 12.0f * scale style.typeface = Typeface.DEFAULT_BOLD for ((index, vehicleType) in stop.vehicleTypes.withIndex()) { val x = index * (typeRectHeight + typeRectHeightPadding) + typeRectHeightPadding val typeRect = Rect(x, typeRectHeightPadding, x + typeRectHeight, typeRectHeightPadding + typeRectHeight) style.color = vehicleType.color canvas.drawRect(typeRect, style) style.color = Color.WHITE val text = vehicleType.abbreviation val textWidth = style.measureText(text) val textBounds = Rect() style.getTextBounds(text, 0, text.length, textBounds) val textX = typeRect.left + (typeRect.width() - textWidth).toFloat() / 2 val textY = typeRect.bottom - (typeRect.height() - textBounds.height()).toFloat() / 2 canvas.drawText(text, textX, textY, style) } return bitmap }
gpl-3.0
9f5fd4590a21f5d57366a396ffbd17f9
39.689655
140
0.689831
4.176991
false
false
false
false
smichel17/simpletask-android
app/src/main/java/nl/mpcjanssen/simpletask/adapters/DrawerAdapter.kt
1
2981
package nl.mpcjanssen.simpletask.adapters import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.BaseAdapter import android.widget.ListAdapter import android.widget.ListView import android.widget.TextView import nl.mpcjanssen.simpletask.R import nl.mpcjanssen.simpletask.util.alfaSort import java.util.* class DrawerAdapter(private val m_inflater: LayoutInflater, contextHeader: String, contexts: List<String>, projectHeader: String, projects: List<String>) : BaseAdapter(), ListAdapter { internal var items: ArrayList<String> var contextHeaderPosition: Int = 0 internal set var projectsHeaderPosition: Int = 0 internal set init { this.items = ArrayList() this.items.add(contextHeader) contextHeaderPosition = 0 this.items.addAll(alfaSort(contexts)) projectsHeaderPosition = items.size this.items.add(projectHeader) this.items.addAll(alfaSort(projects)) } private fun isHeader(position: Int): Boolean { return position == contextHeaderPosition || position == projectsHeaderPosition } override fun getCount(): Int { return items.size } override fun getItem(position: Int): String { return items[position] } override fun getItemId(position: Int): Long { return position.toLong() } override fun hasStableIds(): Boolean { return true // To change body of implemented methods use File | // Settings | File Templates. } override fun getView(position: Int, convertView: View?, parent: ViewGroup): View { var view = convertView val tv: TextView if (isHeader(position)) { view = m_inflater.inflate(R.layout.drawer_list_header, parent, false) tv = view as TextView val lv = parent as ListView if (lv.isItemChecked(position)) { tv.text = items[position] + " inverted" } else { tv.text = items[position] } } else { if (view == null) { view = m_inflater.inflate(R.layout.drawer_list_item_checked, parent, false) } tv = view as TextView tv.text = items[position].substring(1) } return view } override fun getItemViewType(position: Int): Int { if (isHeader(position)) { return 0 } else { return 1 } } override fun getViewTypeCount(): Int { return 2 } override fun isEmpty(): Boolean { return items.size == 0 } override fun areAllItemsEnabled(): Boolean { return true } override fun isEnabled(position: Int): Boolean { return true } fun getIndexOf(item: String): Int { return items.indexOf(item) } }
gpl-3.0
e6ea7325bbb1409773c4299abba4b6b9
26.1
91
0.605502
4.701893
false
false
false
false
Tvede-dk/CommonsenseAndroidKotlin
base/src/main/kotlin/com/commonsense/android/kotlin/base/extensions/GeneralExtensions.kt
1
7048
@file:Suppress("unused", "NOTHING_TO_INLINE", "MemberVisibilityCanBePrivate") package com.commonsense.android.kotlin.base.extensions import android.support.annotation.IntRange import com.commonsense.android.kotlin.base.* import com.commonsense.android.kotlin.base.extensions.collections.map import com.commonsense.android.kotlin.base.time.* import java.lang.ref.* import java.util.* import kotlin.system.* /** * Measure time in seconds * * @param function EmptyFunction the function to measure the time of * @return Long the number of seconds it took to execute * */ inline fun measureSecondTime(crossinline function: EmptyFunction): Long { return TimeUnit.NanoSeconds(measureNanoTime(function)).toSeconds().value } /** * Measure the time of some occurrence with a timeout. * the function waits (coroutine delay) until the given timeout. * * @param waitingTimeUnit the time to wait for the response to come. * @param signalAsync the schedule to measure the time, supplies the time back it was called. * @return the delta time for the start of the operation to the "optional" ending, * if the ending have not occurred then it returns null */ suspend inline fun measureOptAsyncCallback(waitingTimeUnit: TimeUnit, crossinline signalAsync: FunctionUnit<FunctionUnit<TimeUnit>>) : TimeUnit.MilliSeconds? { var optionalEnd: Long = 0 var didSet = false val start = System.currentTimeMillis() signalAsync { optionalEnd = it.toMilliSeconds().value didSet = true } waitingTimeUnit.delay() return didSet.map( ifTrue = TimeUnit.MilliSeconds(optionalEnd - start), ifFalse = null) } /** * returns true if this is null */ inline val Any?.isNull get() = this == null /** * returns true if this is not null. */ inline val Any?.isNotNull get() = this != null /** * returns true if this is null or equal to the given argument. * does not return true if we are not null but the argument is null. * @receiver T? * @param other T? the value to compare to * @return Boolean true this is null or is equal to the other object (equals) */ inline fun <T> T?.isNullOrEqualTo(other: T?): Boolean = this == null || this == other /** * Creates a weak reference of this object. * @receiver T the object to create a weak reference of * @return WeakReference<T> a weak reference to the given object */ inline fun <T> T.weakReference(): WeakReference<T> = WeakReference(this) /** * Will use the value if the weak reference is not pointing to null * This differes from `use` where we cannot use it on an optional value inside of a WeakReference */ inline fun <T> WeakReference<T?>.useOpt(crossinline action: T.() -> Unit) { get()?.let(action) } /** * Performs the given action iff this weak reference is not null * @receiver WeakReference<T> the weak reference we want to unpack * @param action T.() -> Unit the action to run if the reference is not null */ inline fun <T> WeakReference<T>.use(crossinline action: T.() -> Unit) { get()?.let(action) } /** * Uses the given weak reaference if available or does the other action * @receiver WeakReference<T> * @param ifAvailable T.() -> Unit the action to perform iff the weak reference did contain something (not null) * @param ifNotAvailable EmptyFunction if the weakreference gave null,this action will be performed */ inline fun <T> WeakReference<T>.useRefOr(crossinline ifAvailable: T.() -> Unit, crossinline ifNotAvailable: EmptyFunction) { get().useOr(ifAvailable, ifNotAvailable) } /** * Uses this value iff not null or another if it is. * the first function (argument) will receive the value iff it is not null, the second is witout any parameters * * @receiver T? * @param ifNotNull T.() -> Unit the action to perform iff this is not null * @param ifNull EmptyFunction if the this is null this action will be performed */ inline fun <T> T?.useOr(crossinline ifNotNull: T.() -> Unit, crossinline ifNull: EmptyFunction) { if (this != null) { ifNotNull(this) } else { ifNull() } } /** * invokes the function ( wrapped in a weakReference) with the input, if the weakreference is not pointing to null * @receiver WeakReference<FunctionUnit<T>?> the weak reference * @param input T the type of wrapped object */ inline fun <T> WeakReference<FunctionUnit<T>?>.use(input: T) { get()?.let { it(input) } } /** * Creates a weak reference, if this is not null. otherwise returns null. * @receiver T? the potential not null object * @return WeakReference<T>? the weak reference of the object, or null if this parameter was null */ inline fun <T> T?.weakReference(): WeakReference<T>? where T : Optional<*> = this?.let(::WeakReference) /** * Allows us to call a function iff all is not null (the sender / receiver). * @receiver T? * @param receiver ((T) -> Unit)? * @return T? */ fun <T> T?.parseTo(receiver: ((T) -> Unit)?): T? { if (this != null && receiver != null) { receiver(this) } return this } /** * Maps an optional value into another value * @param ifNotNull the value if 'this' is not null * @param ifNull the value if 'this' is null * @return the value depending on 'this' value */ inline fun <U> Any?.map(ifNotNull: U, ifNull: U): U { return this.isNotNull.map(ifNotNull, ifNull) } /** * Maps an optional value into another value * @param ifNotNull the value if 'this' is not null * @param ifNull the value if 'this' is null * @return the value depending on 'this' value */ inline fun <U, T : Any> T?.mapNullLazy(crossinline ifNotNull: Function1<T, U>, crossinline ifNull: EmptyFunctionResult<U>): U { return if (this != null) { ifNotNull(this) } else { ifNull() } } /** * Performs the given action from 0 until this value times. * @receiver Int * @param action FunctionUnit<Int> The action to invoke each time */ inline fun Int.forEach(crossinline action: FunctionUnit<Int>) { for (i in 0 until this) { action(i) } } /** * Creates a safer cast than regular due to the reified type T. * @receiver Any * @return T? the casted value iff possible to cast, null otherwise. */ inline fun <reified T> Any.cast(): T? = this as? T /** * gets the class type of a given type. * this can replace "mytype::class" with a simple "type()", which also makes it possible to * refactor and a lot without ever depending on the type. * @return Class<T> The requested class type. */ inline fun <reified T> type(): Class<T> = T::class.java /** * For each value in [0; value] we create U and put that into a list * @receiver @receiver:IntRange(from = 1) Int * @param function Function1<Int, U> the mapper function * @return List<U> the resulting list */ fun <U> @receiver:IntRange(from = 1) Int.mapEach(function: Function1<Int, U>): List<U> { return List(this, function) }
mit
80b19db1a5fd4608bdbc4b32a8a5de8e
30.895928
114
0.680193
3.872527
false
false
false
false
inorichi/tachiyomi-extensions
multisrc/overrides/madara/ichirinnohanayuri/src/IchirinNoHanaYuri.kt
1
1194
package eu.kanade.tachiyomi.extension.pt.ichirinnohanayuri import eu.kanade.tachiyomi.lib.ratelimit.RateLimitInterceptor import eu.kanade.tachiyomi.multisrc.madara.Madara import okhttp3.Headers import okhttp3.OkHttpClient import java.io.IOException import java.text.SimpleDateFormat import java.util.Locale import java.util.concurrent.TimeUnit class IchirinNoHanaYuri : Madara( "Ichirin No Hana Yuri", "https://ichirinnohanayuri.com.br", "pt-BR", SimpleDateFormat("dd/MM/yyyy", Locale("pt", "BR")) ) { override val client: OkHttpClient = super.client.newBuilder() .addInterceptor(RateLimitInterceptor(1, 2, TimeUnit.SECONDS)) .addInterceptor { chain -> val response = chain.proceed(chain.request()) if (response.code == 403) { response.close() throw IOException(BLOCKING_MESSAGE) } response } .build() override fun headersBuilder(): Headers.Builder = Headers.Builder() companion object { private const val BLOCKING_MESSAGE = "O site está bloqueando o Tachiyomi. " + "Migre para outra fonte caso o problema persistir." } }
apache-2.0
0a8a37f592e25043e5378ee81e743ef1
29.589744
85
0.676446
4.057823
false
false
false
false
SiimKinks/sqlitemagic
sqlitemagic-tests/app-kotlin/src/main/kotlin/com/siimkinks/sqlitemagic/model/Magazine.kt
1
369
package com.siimkinks.sqlitemagic.model import com.siimkinks.sqlitemagic.annotation.Column import com.siimkinks.sqlitemagic.annotation.Id import com.siimkinks.sqlitemagic.annotation.Table @Table class Magazine { @Id var id: Long? = null var name: String? = null @Column(onDeleteCascade = true) var author: Author? = null var nrOfReleases: Int? = null }
apache-2.0
0043f89dca5cdb92daa85e9838d58a81
19.555556
50
0.761518
3.727273
false
false
false
false