repo_name
stringlengths
7
81
path
stringlengths
4
242
copies
stringclasses
95 values
size
stringlengths
1
6
content
stringlengths
3
991k
license
stringclasses
15 values
vovagrechka/fucking-everything
attic/photlin-dev-tools/src/photlin/devtools/photlin-devtools.kt
1
14385
package photlin.devtools import com.intellij.codeInsight.highlighting.TooltipLinkHandler import com.intellij.codeInsight.hint.HintManager import com.intellij.codeInsight.hint.HintUtil import com.intellij.codeInsight.navigation.actions.GotoDeclarationHandler import com.intellij.codeInsight.navigation.actions.GotoDeclarationHandlerBase import com.intellij.codeInsight.preview.PreviewHintProvider import com.intellij.execution.actions.ChooseRunConfigurationPopupAction import com.intellij.execution.filters.HyperlinkInfo import com.intellij.execution.impl.ConsoleViewImpl import com.intellij.execution.ui.ConsoleViewContentType import com.intellij.ide.IdeBundle import com.intellij.lang.ASTNode import com.intellij.lang.Language import com.intellij.lang.ParserDefinition import com.intellij.lang.PsiParser import com.intellij.lang.documentation.DocumentationProvider import com.intellij.lexer.FlexAdapter import com.intellij.lexer.Lexer import com.intellij.openapi.actionSystem.* import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.ApplicationNamesInfo import com.intellij.openapi.components.ApplicationComponent import com.intellij.openapi.editor.* import com.intellij.openapi.fileEditor.FileEditorManager import com.intellij.openapi.fileEditor.OpenFileDescriptor import com.intellij.openapi.fileEditor.ex.FileEditorProviderManager import com.intellij.openapi.fileEditor.impl.NonProjectFileWritingAccessProvider import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.progress.Task import com.intellij.openapi.project.Project import com.intellij.openapi.project.ProjectManager import com.intellij.openapi.project.ProjectManagerListener import com.intellij.openapi.ui.Messages import com.intellij.openapi.util.IconLoader import com.intellij.openapi.vfs.LocalFileSystem import com.intellij.openapi.wm.IdeFocusManager import com.intellij.psi.tree.IElementType import com.intellij.psi.tree.IFileElementType import com.intellij.psi.tree.TokenSet import com.intellij.util.lang.UrlClassLoader import org.eclipse.jetty.server.Server import org.eclipse.jetty.servlet.ServletHandler import org.eclipse.jetty.servlet.ServletHolder import photlin.devtools.psi.* import vgrechka.* import vgrechka.idea.* import java.io.File import javax.servlet.http.HttpServlet import javax.servlet.http.HttpServletRequest import javax.servlet.http.HttpServletResponse import javax.swing.Icon import kotlin.concurrent.thread import com.intellij.openapi.editor.colors.TextAttributesKey import com.intellij.openapi.editor.event.EditorMouseEvent import com.intellij.openapi.editor.event.EditorMouseListener import com.intellij.openapi.editor.impl.EditorImpl import com.intellij.openapi.fileTypes.* import com.intellij.openapi.vfs.VirtualFile import com.intellij.psi.* import com.intellij.psi.impl.source.tree.LeafPsiElement import com.intellij.psi.util.PsiUtil import vgrechka.idea.hripos.* import vgrechka.ideabackdoor.* import javax.swing.JComponent import javax.swing.JLabel import javax.swing.event.HyperlinkEvent private var bs by notNullOnce<Bullshitter>() object PhotlinDevToolsGlobal { val rpcServerPort = 12321 } fun openFile(path: String, line: Int) { val projects = ProjectManager.getInstance().openProjects check(projects.size == 1) {"e5469c93-424d-4eef-81de-41c190b7f188"} val project = projects.first() if (openFile(project, path, line)) return Messages.showErrorDialog("File not fucking found", "Fuck You") } @Ser class PDTRemoteCommand_TestResult( val rawResponseFromPHPScript: String ) : Servant { override fun serve(): Any { bs.mumble("\n------------------- TEST RESULT ------------------\n") val re = Regex("<b>([^<]*?)</b> on line <b>([^<]*?)</b>") var searchStart = 0 while (true) { val mr = re.find(rawResponseFromPHPScript, searchStart) ?: break val filePath = mr.groupValues[1] val lineNumber = mr.groupValues[2].toInt() bs.mumbleNoln(rawResponseFromPHPScript.substring(searchStart, mr.range.start)) bs.mumbleNoln("$filePath on line ") bs.consoleView.printHyperlink("$lineNumber") { openFile(filePath, lineNumber) } bs.mumbleNoln("(") bs.consoleView.printHyperlink("@") { openFile("$filePath--tagged", lineNumber) } bs.mumbleNoln(")") searchStart = mr.range.endInclusive + 1 if (searchStart > rawResponseFromPHPScript.lastIndex) break } if (searchStart < rawResponseFromPHPScript.lastIndex) bs.mumbleNoln(rawResponseFromPHPScript.substring(searchStart)) bs.mumble("") (bs.consoleView as ConsoleViewImpl).scrollToEnd() return "Cool" } } class PhotlinDevToolsPlugin : ApplicationComponent { override fun getComponentName(): String { return this::class.qualifiedName!! } override fun disposeComponent() { } override fun initComponent() { EditorFactory.getInstance().eventMulticaster.addEditorMouseListener(object : EditorMouseListener { override fun mouseReleased(e: EditorMouseEvent?) { } override fun mouseEntered(e: EditorMouseEvent?) { } override fun mouseClicked(e: EditorMouseEvent) { val virtualFile = (e.editor as EditorImpl).virtualFile ?: return val psiFile = PsiUtil.getPsiFile(e.editor.project!!, virtualFile) if (psiFile is PHPTaggedFile) { val el = psiFile.findElementAt(e.editor.caretModel.offset) if (el is LeafPsiElement && el.elementType == PHPTaggedTypes.AT_TOKEN) { check(el.text.last() == '@') {"0ba8fb8b-4800-4cb8-b136-f4ce2106c39b"} val debugTag = el.text.dropLast(1) HintManager.getInstance().showInformationHint(e.editor, HintUtil.createInformationLabel( "<a href='fuck'>Debug $debugTag</a>", {linkEvent-> if (linkEvent.eventType == HyperlinkEvent.EventType.ACTIVATED) { breakOnDebugTag(e.editor.project, debugTag) } }, null, null)) } } } override fun mouseExited(e: EditorMouseEvent?) { } override fun mousePressed(e: EditorMouseEvent?) { } }) val pm = ProjectManager.getInstance() pm.addProjectManagerListener(object : ProjectManagerListener { override fun projectOpened(project: Project) { clog("Opened project", project.name) bs = Bullshitter(project) bs.mumble("Hello, sweetheart. I am Photlin Development Tools. Now use me") } }) val am = ActionManager.getInstance() val group = am.getAction("ToolsMenu") as DefaultActionGroup group.addSeparator() run { val action = object : AnAction("PDT: _Mess Around") { override fun actionPerformed(event: AnActionEvent) { messAroundAction(event) } } group.add(action) } // run { // val action = object : AnAction("Backdoor: Bullshit Something") { // override fun actionPerformed(event: AnActionEvent) { // val bs = Bullshitter(event.project!!) // bs.mumble("Something? How about fuck you?") // } // } // group.add(action) // } // run { // val action = object : AnAction("Backdoor: _Mess Around") { // override fun actionPerformed(event: AnActionEvent) { // val title = "Fucking through backdoor" // object : Task.Backgroundable(event.project, title, true) { // var rawResponse by notNullOnce<String>() // // override fun run(indicator: ProgressIndicator) { // indicator.text = title // indicator.fraction = 0.5 // val json = "{projectName: '${event.project!!.name}'}" // rawResponse = HTTPClient.postJSON("http://localhost:${BackdoorGlobal.rpcServerPort}?proc=MessAround", json) // indicator.fraction = 1.0 // } // // override fun onFinished() { // // Messages.showInfoMessage(rawResponse, "Response") // } // }.queue() // } // } // group.add(action) // } startRPCServer() } inner class startRPCServer { init { thread { try { Server(PhotlinDevToolsGlobal.rpcServerPort)-{o-> o.handler = ServletHandler() -{o-> o.addServletWithMapping(ServletHolder(FuckingServlet()), "/*") } o.start() clog("Shit is spinning") o.join() } } catch(e: Exception) { e.printStackTrace() } } } inner class FuckingServlet : HttpServlet() { override fun service(req: HttpServletRequest, res: HttpServletResponse) { req.characterEncoding = "UTF-8" req.queryString val rawRequest = req.reader.readText() clog("Got request:", rawRequest) val requestClass = Class.forName(this::class.java.`package`.name + ".PDTRemoteCommand_" + req.getParameter("proc")) val servant = relaxedObjectMapper.readValue(rawRequest, requestClass) as Servant var response by notNullOnce<Any>() ApplicationManager.getApplication().invokeAndWait { response = servant.serve() } val rawResponse = relaxedObjectMapper.writeValueAsString(response) res.contentType = "application/json; charset=utf-8" res.writer.println(rawResponse) res.status = HttpServletResponse.SC_OK } } } } private interface Servant { fun serve(): Any } private class messAroundAction(val event: AnActionEvent) { init { fuck1() } fun fuck2() { breakOnDebugTag(event.project, "234") } fun fuck1() { PDTRemoteCommand_TestResult(rawResponseFromPHPScript = """<br /> <b>Notice</b>: Use of undefined constant aps - assumed 'aps' in <b>C:\opt\xampp\htdocs\TryPhotlin\aps-back\aps-back.php</b> on line <b>16392</b><br /> <br /> <b>Fatal error</b>: Call to undefined function back_main() in <b>C:\opt\xampp\htdocs\TryPhotlin\aps-back\aps-back.php</b> on line <b>16392</b><br /> """).serve() } } object PHPTaggedLanguage : Language("PHPTagged") { } object PDTIcons { val phpTagged = IconLoader.getIcon("/photlin/devtools/php--tagged.png") } object PHPTaggedFileType : LanguageFileType(PHPTaggedLanguage) { override fun getIcon(): Icon? { return PDTIcons.phpTagged } override fun getName(): String { return "PHPTagged file" } override fun getDefaultExtension(): String { return "php--tagged" } override fun getDescription(): String { return name } } class PHPTaggedFileTypeFactory : FileTypeFactory() { override fun createFileTypes(consumer: FileTypeConsumer) { consumer.consume(PHPTaggedFileType, PHPTaggedFileType.defaultExtension) } } class PHPTaggedLexerAdapter : FlexAdapter(PHPTaggedLexer()) class PHPTaggedParserDefinition : ParserDefinition { override fun createParser(project: Project): PsiParser { return PHPTaggedParser() } override fun createFile(viewProvider: FileViewProvider): PsiFile { return PHPTaggedFile(viewProvider) } override fun spaceExistanceTypeBetweenTokens(left: ASTNode?, right: ASTNode?): ParserDefinition.SpaceRequirements { return ParserDefinition.SpaceRequirements.MAY } override fun getStringLiteralElements(): TokenSet { return TokenSet.EMPTY } val FILE = IFileElementType(PHPTaggedLanguage) override fun getFileNodeType(): IFileElementType { return FILE } override fun getWhitespaceTokens(): TokenSet { return TokenSet.create(PHPTaggedTypes.NL) // return TokenSet.EMPTY } override fun createLexer(project: Project?): Lexer { return PHPTaggedLexerAdapter() } override fun createElement(node: ASTNode): PsiElement { return PHPTaggedTypes.Factory.createElement(node) } override fun getCommentTokens(): TokenSet { return TokenSet.EMPTY } } class PHPTaggedSyntaxHighlighter : SyntaxHighlighterBase() { override fun getHighlightingLexer(): Lexer { return PHPTaggedLexerAdapter() } override fun getTokenHighlights(tokenType: IElementType): Array<TextAttributesKey> { // clog("tokenType: $tokenType") if (tokenType == PHPTaggedTypes.AT_TOKEN) { return VALUE_KEYS } else { return EMPTY_KEYS } } companion object { val VALUE = TextAttributesKey.createTextAttributesKey("SIMPLE_VALUE", DefaultLanguageHighlighterColors.STRING) private val VALUE_KEYS = arrayOf(VALUE) private val EMPTY_KEYS = arrayOf<TextAttributesKey>() } } class PHPTaggedSyntaxHighlighterFactory : SyntaxHighlighterFactory() { override fun getSyntaxHighlighter(project: Project?, virtualFile: VirtualFile?): SyntaxHighlighter { return PHPTaggedSyntaxHighlighter() } } private fun breakOnDebugTag(localProject: Project?, debugTag: String) { rubRemoteIdeaTits(localProject, Command_Photlin_BreakOnDebugTag(debugTag = debugTag), onError = { Messages.showErrorDialog(it, "Fuck You") }) }
apache-2.0
androidx/androidx
annotation/annotation-experimental-lint/integration-tests/src/main/java/sample/kotlin/ExperimentalKotlinAnnotation.kt
3
775
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package sample.kotlin @RequiresOptIn(level = RequiresOptIn.Level.ERROR) @Retention(AnnotationRetention.BINARY) annotation class ExperimentalKotlinAnnotation
apache-2.0
androidx/androidx
paging/paging-common/src/test/kotlin/androidx/paging/DataSourceTest.kt
3
1692
/* * 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.paging import com.google.common.truth.Truth.assertThat import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.JUnit4 @RunWith(JUnit4::class) class DataSourceTest { @Test fun addInvalidatedCallback_triggersImmediatelyIfAlreadyInvalid() { val pagingSource = TestPositionalDataSource(listOf()) var invalidateCalls = 0 pagingSource.invalidate() pagingSource.addInvalidatedCallback { invalidateCalls++ } assertThat(invalidateCalls).isEqualTo(1) } @Test fun addInvalidatedCallback_avoidsRetriggeringWhenCalledRecursively() { val pagingSource = TestPositionalDataSource(listOf()) var invalidateCalls = 0 pagingSource.addInvalidatedCallback { pagingSource.addInvalidatedCallback { invalidateCalls++ } pagingSource.invalidate() pagingSource.addInvalidatedCallback { invalidateCalls++ } invalidateCalls++ } pagingSource.invalidate() assertThat(invalidateCalls).isEqualTo(3) } }
apache-2.0
google/playhvz
Android/ghvzApp/app/src/main/java/com/app/playhvz/screens/gamedashboard/GameDashboardFragment.kt
1
5054
/* * Copyright 2020 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.app.playhvz.screens.gamedashboard import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.appcompat.app.AppCompatActivity import androidx.fragment.app.Fragment import androidx.lifecycle.ViewModelProvider import androidx.navigation.fragment.findNavController import com.app.playhvz.R import com.app.playhvz.common.globals.SharedPreferencesConstants import com.app.playhvz.firebase.classmodels.Game import com.app.playhvz.firebase.classmodels.Player import com.app.playhvz.firebase.viewmodels.GameViewModel import com.app.playhvz.navigation.NavigationUtil import com.app.playhvz.screens.gamedashboard.cards.* import com.app.playhvz.utils.PlayerUtils import com.app.playhvz.utils.SystemUtils /** Fragment for showing a list of Games the user is registered for.*/ class GameDashboardFragment : Fragment() { companion object { private val TAG = GameDashboardFragment::class.qualifiedName } private lateinit var firestoreViewModel: GameViewModel private lateinit var declareAllegianceCard: DeclareAllegianceCard private lateinit var infectCard: InfectCard private lateinit var leaderboardCard: LeaderboardCard private lateinit var lifeCodeCard: LifeCodeCard private lateinit var missionCard: MissionCard var gameId: String? = null var playerId: String? = null var game: Game? = null var player: Player? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) firestoreViewModel = ViewModelProvider(requireActivity()).get(GameViewModel::class.java) val sharedPrefs = activity?.getSharedPreferences( SharedPreferencesConstants.PREFS_FILENAME, 0 )!! gameId = sharedPrefs.getString(SharedPreferencesConstants.CURRENT_GAME_ID, null) playerId = sharedPrefs.getString(SharedPreferencesConstants.CURRENT_PLAYER_ID, null) if (gameId == null || playerId == null) { SystemUtils.clearSharedPrefs(requireActivity()) NavigationUtil.navigateToGameList(findNavController(), requireActivity()) } } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { setupObservers() setupCards() val view = inflater.inflate(R.layout.fragment_game_dashboard, container, false) declareAllegianceCard.onCreateView(view) infectCard.onCreateView(view) leaderboardCard.onCreateView(view) lifeCodeCard.onCreateView(view) missionCard.onCreateView(view) setupToolbar() return view } fun setupToolbar() { val toolbar = (activity as AppCompatActivity).supportActionBar if (toolbar != null) { toolbar.title = if (game == null || game?.name.isNullOrEmpty()) requireContext().getString(R.string.app_name) else game?.name } } private fun setupObservers() { if (gameId == null || playerId == null) { return } firestoreViewModel.getGame(this, gameId!!) .observe(viewLifecycleOwner, androidx.lifecycle.Observer { serverGame: Game -> updateGame(serverGame) }) PlayerUtils.getPlayer(gameId!!, playerId!!) .observe(viewLifecycleOwner, androidx.lifecycle.Observer { serverPlayer -> updatePlayer(serverPlayer) }) } private fun setupCards() { declareAllegianceCard = DeclareAllegianceCard(this, gameId!!, playerId!!) infectCard = InfectCard(this, gameId!!, playerId!!) leaderboardCard = LeaderboardCard(this, gameId!!, playerId!!) lifeCodeCard = LifeCodeCard(this, gameId!!, playerId!!) missionCard = MissionCard(this, findNavController(), gameId!!, playerId!!) } private fun updateGame(serverGame: Game?) { game = serverGame setupToolbar() } private fun updatePlayer(serverPlayer: Player?) { if (serverPlayer == null) { NavigationUtil.navigateToGameList(findNavController(), requireActivity()) } declareAllegianceCard.onPlayerUpdated(serverPlayer!!) infectCard.onPlayerUpdated(serverPlayer) leaderboardCard.onPlayerUpdated(serverPlayer) lifeCodeCard.onPlayerUpdated(serverPlayer) } }
apache-2.0
androidx/androidx
compose/compiler/compiler-hosted/src/main/java/androidx/compose/compiler/plugins/kotlin/lower/LiveLiteralTransformer.kt
3
38740
/* * Copyright 2019 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.compiler.plugins.kotlin.lower import androidx.compose.compiler.plugins.kotlin.ComposeCallableIds import androidx.compose.compiler.plugins.kotlin.ComposeClassIds import androidx.compose.compiler.plugins.kotlin.ModuleMetrics import org.jetbrains.kotlin.backend.common.extensions.IrPluginContext import org.jetbrains.kotlin.backend.common.lower.DeclarationIrBuilder import org.jetbrains.kotlin.descriptors.ClassKind import org.jetbrains.kotlin.descriptors.DescriptorVisibilities import org.jetbrains.kotlin.ir.IrStatement import org.jetbrains.kotlin.ir.UNDEFINED_OFFSET import org.jetbrains.kotlin.ir.builders.declarations.IrFunctionBuilder import org.jetbrains.kotlin.ir.builders.declarations.addConstructor import org.jetbrains.kotlin.ir.builders.declarations.addFunction import org.jetbrains.kotlin.ir.builders.declarations.addGetter import org.jetbrains.kotlin.ir.builders.declarations.addProperty import org.jetbrains.kotlin.ir.builders.declarations.addValueParameter import org.jetbrains.kotlin.ir.builders.declarations.buildClass import org.jetbrains.kotlin.ir.builders.declarations.buildField import org.jetbrains.kotlin.ir.builders.irBlock import org.jetbrains.kotlin.ir.builders.irBlockBody import org.jetbrains.kotlin.ir.builders.irCall import org.jetbrains.kotlin.ir.builders.irDelegatingConstructorCall import org.jetbrains.kotlin.ir.builders.irGet import org.jetbrains.kotlin.ir.builders.irGetField import org.jetbrains.kotlin.ir.builders.irIfNull import org.jetbrains.kotlin.ir.builders.irReturn import org.jetbrains.kotlin.ir.builders.irSet import org.jetbrains.kotlin.ir.builders.irSetField import org.jetbrains.kotlin.ir.builders.irString import org.jetbrains.kotlin.ir.builders.irTemporary import org.jetbrains.kotlin.ir.declarations.IrAnnotationContainer import org.jetbrains.kotlin.ir.declarations.IrClass import org.jetbrains.kotlin.ir.declarations.IrDeclarationOrigin import org.jetbrains.kotlin.ir.declarations.IrEnumEntry import org.jetbrains.kotlin.ir.declarations.IrFactory import org.jetbrains.kotlin.ir.declarations.IrFile import org.jetbrains.kotlin.ir.declarations.IrModuleFragment import org.jetbrains.kotlin.ir.declarations.IrProperty import org.jetbrains.kotlin.ir.declarations.IrSimpleFunction import org.jetbrains.kotlin.ir.declarations.IrValueParameter import org.jetbrains.kotlin.ir.declarations.IrVariable import org.jetbrains.kotlin.ir.expressions.IrBlock import org.jetbrains.kotlin.ir.expressions.IrBlockBody import org.jetbrains.kotlin.ir.expressions.IrBody import org.jetbrains.kotlin.ir.expressions.IrBranch import org.jetbrains.kotlin.ir.expressions.IrCall import org.jetbrains.kotlin.ir.expressions.IrComposite import org.jetbrains.kotlin.ir.expressions.IrConst import org.jetbrains.kotlin.ir.expressions.IrConstKind import org.jetbrains.kotlin.ir.expressions.IrConstructorCall import org.jetbrains.kotlin.ir.expressions.IrDelegatingConstructorCall import org.jetbrains.kotlin.ir.expressions.IrElseBranch import org.jetbrains.kotlin.ir.expressions.IrEnumConstructorCall import org.jetbrains.kotlin.ir.expressions.IrExpression import org.jetbrains.kotlin.ir.expressions.IrLoop import org.jetbrains.kotlin.ir.expressions.IrSetField import org.jetbrains.kotlin.ir.expressions.IrSetValue import org.jetbrains.kotlin.ir.expressions.IrStatementOrigin import org.jetbrains.kotlin.ir.expressions.IrStringConcatenation import org.jetbrains.kotlin.ir.expressions.IrTry import org.jetbrains.kotlin.ir.expressions.IrVararg import org.jetbrains.kotlin.ir.expressions.IrVarargElement import org.jetbrains.kotlin.ir.expressions.IrWhen import org.jetbrains.kotlin.ir.expressions.impl.IrBranchImpl import org.jetbrains.kotlin.ir.expressions.impl.IrCallImpl import org.jetbrains.kotlin.ir.expressions.impl.IrConstructorCallImpl import org.jetbrains.kotlin.ir.expressions.impl.IrElseBranchImpl import org.jetbrains.kotlin.ir.expressions.impl.IrExpressionBodyImpl import org.jetbrains.kotlin.ir.expressions.impl.IrGetObjectValueImpl import org.jetbrains.kotlin.ir.expressions.impl.IrStringConcatenationImpl import org.jetbrains.kotlin.ir.expressions.impl.IrVarargImpl import org.jetbrains.kotlin.ir.expressions.impl.copyWithOffsets import org.jetbrains.kotlin.ir.symbols.IrSimpleFunctionSymbol import org.jetbrains.kotlin.ir.symbols.impl.IrSimpleFunctionSymbolImpl import org.jetbrains.kotlin.ir.types.IrType import org.jetbrains.kotlin.ir.types.defaultType import org.jetbrains.kotlin.ir.types.makeNullable import org.jetbrains.kotlin.ir.types.typeWith import org.jetbrains.kotlin.ir.util.DeepCopySymbolRemapper import org.jetbrains.kotlin.ir.util.SYNTHETIC_OFFSET import org.jetbrains.kotlin.ir.util.addChild import org.jetbrains.kotlin.ir.util.constructors import org.jetbrains.kotlin.ir.util.copyTo import org.jetbrains.kotlin.ir.util.createParameterDeclarations import org.jetbrains.kotlin.ir.util.defaultType import org.jetbrains.kotlin.ir.util.getPropertyGetter import org.jetbrains.kotlin.ir.util.isAnnotationClass import org.jetbrains.kotlin.ir.util.parentAsClass import org.jetbrains.kotlin.ir.util.primaryConstructor import org.jetbrains.kotlin.ir.visitors.transformChildrenVoid import org.jetbrains.kotlin.load.kotlin.PackagePartClassUtils import org.jetbrains.kotlin.name.Name /** * This transformer transforms constant literal expressions into expressions which read a * MutableState instance so that changes to the source code of the constant literal can be * communicated to the runtime without a recompile. This transformation is intended to improve * developer experience and should never be enabled in a release build as it will significantly * slow down performance-conscious code. * * The nontrivial piece of this transform is to create a stable "durable" unique key for every * single constant in the module. It does this by creating a path-based key which roughly maps to * the semantic structure of the code, and uses an incrementing index on sibling constants as a * last resort. The constant expressions in the IR will be transformed into property getter calls * to a synthetic "Live Literals" class that is generated per file. The class is an object * singleton where each property is lazily backed by a MutableState instance which is accessed * using the runtime's `liveLiteral(String,T)` top level API. * * Roughly speaking, the transform will turn the following: * * // file: Foo.kt * fun Foo() { * print("Hello World") * } * * into the following equivalent representation: * * // file: Foo.kt * fun Foo() { * print(LiveLiterals$FooKt.`getString$arg-0$call-print$fun-Foo`()) * } * object LiveLiterals$FooKt { * var `String$arg-0$call-print$fun-Foo`: String = "Hello World" * var `State$String$arg-0$call-print$fun-Foo`: MutableState<String>? = null * fun `getString$arg-0$call-print$fun-Foo`(): String { * val field = this.`String$arg-0$call-print$fun-Foo` * val state = if (field == null) { * val tmp = liveLiteral( * "String$arg-0$call-print$fun-Foo", * this.`String$arg-0$call-print$fun-Foo` * ) * this.`String$arg-0$call-print$fun-Foo` = tmp * tmp * } else field * return field.value * } * } * * @see DurableKeyVisitor */ open class LiveLiteralTransformer( private val liveLiteralsEnabled: Boolean, private val usePerFileEnabledFlag: Boolean, private val keyVisitor: DurableKeyVisitor, context: IrPluginContext, symbolRemapper: DeepCopySymbolRemapper, metrics: ModuleMetrics, ) : AbstractComposeLowering(context, symbolRemapper, metrics), ModuleLoweringPass { override fun lower(module: IrModuleFragment) { module.transformChildrenVoid(this) } private val liveLiteral = getTopLevelFunction(ComposeCallableIds.liveLiteral) private val isLiveLiteralsEnabled = getTopLevelPropertyGetter(ComposeCallableIds.isLiveLiteralsEnabled) private val liveLiteralInfoAnnotation = getTopLevelClass(ComposeClassIds.LiveLiteralInfo) private val liveLiteralFileInfoAnnotation = getTopLevelClass(ComposeClassIds.LiveLiteralFileInfo) private val stateInterface = getTopLevelClass(ComposeClassIds.State) private val NoLiveLiteralsAnnotation = getTopLevelClass(ComposeClassIds.NoLiveLiterals) private fun IrAnnotationContainer.hasNoLiveLiteralsAnnotation(): Boolean = annotations.any { it.symbol.owner == NoLiveLiteralsAnnotation.owner.primaryConstructor } private fun <T> enter(key: String, block: () -> T) = keyVisitor.enter(key, block) private fun <T> siblings(key: String, block: () -> T) = keyVisitor.siblings(key, block) private fun <T> siblings(block: () -> T) = keyVisitor.siblings(block) private var liveLiteralsClass: IrClass? = null private var liveLiteralsEnabledSymbol: IrSimpleFunctionSymbol? = null private var currentFile: IrFile? = null private fun irGetLiveLiteralsClass(startOffset: Int, endOffset: Int): IrExpression { return IrGetObjectValueImpl( startOffset = startOffset, endOffset = endOffset, type = liveLiteralsClass!!.defaultType, symbol = liveLiteralsClass!!.symbol ) } private fun Name.asJvmFriendlyString(): String { return if (!isSpecial) identifier else asString().replace('<', '$').replace('>', '$').replace(' ', '-') } private fun irLiveLiteralInfoAnnotation( key: String, offset: Int ): IrConstructorCall = IrConstructorCallImpl( UNDEFINED_OFFSET, UNDEFINED_OFFSET, liveLiteralInfoAnnotation.defaultType, liveLiteralInfoAnnotation.constructors.single(), 0, 0, 2 ).apply { putValueArgument(0, irConst(key)) putValueArgument(1, irConst(offset)) } private fun irLiveLiteralFileInfoAnnotation( file: String ): IrConstructorCall = IrConstructorCallImpl( UNDEFINED_OFFSET, UNDEFINED_OFFSET, liveLiteralFileInfoAnnotation.defaultType, liveLiteralFileInfoAnnotation.constructors.single(), 0, 0, 1 ).apply { putValueArgument(0, irConst(file)) } private fun irLiveLiteralGetter( key: String, literalValue: IrExpression, literalType: IrType, startOffset: Int ): IrSimpleFunction { val clazz = liveLiteralsClass!! val stateType = stateInterface.owner.typeWith(literalType).makeNullable() val stateGetValue = stateInterface.getPropertyGetter("value")!! val defaultProp = clazz.addProperty { name = Name.identifier(key) visibility = DescriptorVisibilities.PRIVATE }.also { p -> p.backingField = context.irFactory.buildField { name = Name.identifier(key) isStatic = true type = literalType visibility = DescriptorVisibilities.PRIVATE }.also { f -> f.correspondingPropertySymbol = p.symbol f.parent = clazz f.initializer = IrExpressionBodyImpl( SYNTHETIC_OFFSET, SYNTHETIC_OFFSET, literalValue ) } p.addGetter { returnType = literalType visibility = DescriptorVisibilities.PRIVATE origin = IrDeclarationOrigin.DEFAULT_PROPERTY_ACCESSOR }.also { fn -> fn.correspondingPropertySymbol = p.symbol val thisParam = clazz.thisReceiver!!.copyTo(fn) fn.dispatchReceiverParameter = thisParam fn.body = DeclarationIrBuilder(context, fn.symbol).irBlockBody { +irReturn(irGetField(irGet(thisParam), p.backingField!!)) } } } val stateProp = clazz.addProperty { name = Name.identifier("State\$$key") visibility = DescriptorVisibilities.PRIVATE isVar = true }.also { p -> p.backingField = context.irFactory.buildField { name = Name.identifier("State\$$key") type = stateType visibility = DescriptorVisibilities.PRIVATE isStatic = true }.also { f -> f.correspondingPropertySymbol = p.symbol f.parent = clazz } p.addGetter { returnType = stateType visibility = DescriptorVisibilities.PRIVATE origin = IrDeclarationOrigin.DEFAULT_PROPERTY_ACCESSOR }.also { fn -> fn.correspondingPropertySymbol = p.symbol val thisParam = clazz.thisReceiver!!.copyTo(fn) fn.dispatchReceiverParameter = thisParam fn.body = DeclarationIrBuilder(context, fn.symbol).irBlockBody { +irReturn(irGetField(irGet(thisParam), p.backingField!!)) } } p.addSetter { returnType = context.irBuiltIns.unitType visibility = DescriptorVisibilities.PRIVATE origin = IrDeclarationOrigin.DEFAULT_PROPERTY_ACCESSOR }.also { fn -> fn.correspondingPropertySymbol = p.symbol val thisParam = clazz.thisReceiver!!.copyTo(fn) fn.dispatchReceiverParameter = thisParam val valueParam = fn.addValueParameter("value", stateType) fn.body = DeclarationIrBuilder(context, fn.symbol).irBlockBody { +irSetField(irGet(thisParam), p.backingField!!, irGet(valueParam)) } } } return clazz.addFunction( name = key, returnType = literalType ).also { fn -> val thisParam = fn.dispatchReceiverParameter!! fn.annotations += irLiveLiteralInfoAnnotation(key, startOffset) fn.body = DeclarationIrBuilder(context, fn.symbol).irBlockBody { // if (!isLiveLiteralsEnabled) return defaultValueField // val a = stateField // val b = if (a == null) { // val c = liveLiteralState("key", defaultValueField) // stateField = c // c // } else a // return b.value val condition = if (usePerFileEnabledFlag) irNot( irGet(builtIns.booleanType, irGet(thisParam), liveLiteralsEnabledSymbol!!) ) else irNot(irCall(isLiveLiteralsEnabled)) +irIf( condition = condition, body = irReturn( irGet( literalType, irGet(thisParam), defaultProp.getter!!.symbol ) ) ) val a = irTemporary(irGet(stateType, irGet(thisParam), stateProp.getter!!.symbol)) val b = irIfNull( type = stateType, subject = irGet(a), thenPart = irBlock(resultType = stateType) { val liveLiteralCall = irCall(liveLiteral).apply { putValueArgument(0, irString(key)) putValueArgument( 1, irGet( literalType, irGet(thisParam), defaultProp.getter!!.symbol ) ) putTypeArgument(0, literalType) } val c = irTemporary(liveLiteralCall) +irSet( stateType, irGet(thisParam), stateProp.setter!!.symbol, irGet(c) ) +irGet(c) }, elsePart = irGet(a) ) val call = IrCallImpl( UNDEFINED_OFFSET, UNDEFINED_OFFSET, literalType, stateGetValue, stateGetValue.owner.typeParameters.size, stateGetValue.owner.valueParameters.size, IrStatementOrigin.FOR_LOOP_ITERATOR ).apply { dispatchReceiver = b } +irReturn(call) } } } override fun visitConst(expression: IrConst<*>): IrExpression { when (expression.kind) { IrConstKind.Null -> return expression else -> { /* Continue visiting expression */ } } val (key, success) = keyVisitor.buildPath( prefix = expression.kind.asString, pathSeparator = "\$", siblingSeparator = "-" ) // NOTE: Even if `liveLiteralsEnabled` is false, we are still going to throw an exception // here because the presence of a duplicate key represents a bug in this transform since // it should be impossible. By checking this always, we are making it so that bugs in // this transform will get caught _early_ and that there will be implicitly high coverage // of the key generation algorithm despite this transform only being used by tooling. // Developers have the ability to "silence" this exception by marking the surrounding // class/file/function with the `@NoLiveLiterals` annotation. if (!success) { val file = currentFile ?: return expression val src = file.fileEntry.getSourceRangeInfo( expression.startOffset, expression.endOffset ) error( "Duplicate live literal key found: $key\n" + "Caused by element at: " + "${src.filePath}:${src.startLineNumber}:${src.startColumnNumber}\n" + "If you encounter this error, please file a bug at " + "https://issuetracker.google.com/issues?q=componentid:610764\n" + "Try adding the `@NoLiveLiterals` annotation around the surrounding code to " + "avoid this exception." ) } // If live literals are enabled, don't do anything if (!liveLiteralsEnabled) return expression // create the getter function on the live literals class val getter = irLiveLiteralGetter( key = key, // Move the start/endOffsets to the call of the getter since we don't // want to step into <clinit> in the debugger. literalValue = expression.copyWithOffsets(UNDEFINED_OFFSET, UNDEFINED_OFFSET), literalType = expression.type, startOffset = expression.startOffset ) // return a call to the getter in place of the constant return IrCallImpl( expression.startOffset, expression.endOffset, expression.type, getter.symbol, getter.symbol.owner.typeParameters.size, getter.symbol.owner.valueParameters.size ).apply { dispatchReceiver = irGetLiveLiteralsClass(expression.startOffset, expression.endOffset) } } override fun visitClass(declaration: IrClass): IrStatement { if (declaration.hasNoLiveLiteralsAnnotation()) return declaration // constants in annotations need to be compile-time values, so we can never transform them if (declaration.isAnnotationClass) return declaration return siblings("class-${declaration.name.asJvmFriendlyString()}") { super.visitClass(declaration) } } open fun makeKeySet(): MutableSet<String> { return mutableSetOf() } override fun visitFile(declaration: IrFile): IrFile { includeFileNameInExceptionTrace(declaration) { if (declaration.hasNoLiveLiteralsAnnotation()) return declaration val filePath = declaration.fileEntry.name val fileName = filePath.split('/').last() val keys = makeKeySet() return keyVisitor.root(keys) { val prevEnabledSymbol = liveLiteralsEnabledSymbol var nextEnabledSymbol: IrSimpleFunctionSymbol? = null val prevClass = liveLiteralsClass val nextClass = context.irFactory.buildClass { kind = ClassKind.OBJECT visibility = DescriptorVisibilities.INTERNAL val shortName = PackagePartClassUtils.getFilePartShortName(fileName) // the name of the LiveLiterals class is per-file, so we use the same name that // the kotlin file class lowering produces, prefixed with `LiveLiterals$`. name = Name.identifier("LiveLiterals${"$"}$shortName") }.also { it.createParameterDeclarations() // store the full file path to the file that this class is associated with in an // annotation on the class. This will be used by tooling to associate the keys // inside of this class with actual PSI in the editor. it.annotations += irLiveLiteralFileInfoAnnotation(declaration.fileEntry.name) it.addConstructor { isPrimary = true }.also { ctor -> ctor.body = DeclarationIrBuilder(context, it.symbol).irBlockBody { +irDelegatingConstructorCall( context .irBuiltIns .anyClass .owner .primaryConstructor!! ) } } if (usePerFileEnabledFlag) { val enabledProp = it.addProperty { name = Name.identifier("enabled") visibility = DescriptorVisibilities.PRIVATE }.also { p -> p.backingField = context.irFactory.buildField { name = Name.identifier("enabled") isStatic = true type = builtIns.booleanType visibility = DescriptorVisibilities.PRIVATE }.also { f -> f.correspondingPropertySymbol = p.symbol f.parent = it f.initializer = IrExpressionBodyImpl( SYNTHETIC_OFFSET, SYNTHETIC_OFFSET, irConst(false) ) } p.addGetter { returnType = builtIns.booleanType visibility = DescriptorVisibilities.PRIVATE origin = IrDeclarationOrigin.DEFAULT_PROPERTY_ACCESSOR }.also { fn -> val thisParam = it.thisReceiver!!.copyTo(fn) fn.dispatchReceiverParameter = thisParam fn.body = DeclarationIrBuilder(context, fn.symbol).irBlockBody { +irReturn(irGetField(irGet(thisParam), p.backingField!!)) } } } nextEnabledSymbol = enabledProp.getter?.symbol } } try { liveLiteralsClass = nextClass currentFile = declaration liveLiteralsEnabledSymbol = nextEnabledSymbol val file = super.visitFile(declaration) // if there were no constants found in the entire file, then we don't need to // create this class at all if (liveLiteralsEnabled && keys.isNotEmpty()) { file.addChild(nextClass) } file } finally { liveLiteralsClass = prevClass liveLiteralsEnabledSymbol = prevEnabledSymbol } } } } override fun visitTry(aTry: IrTry): IrExpression { aTry.tryResult = enter("try") { aTry.tryResult.transform(this, null) } siblings { aTry.catches.forEach { it.result = enter("catch") { it.result.transform(this, null) } } } aTry.finallyExpression = enter("finally") { aTry.finallyExpression?.transform(this, null) } return aTry } override fun visitDelegatingConstructorCall( expression: IrDelegatingConstructorCall ): IrExpression { val owner = expression.symbol.owner // annotations are represented as constructor calls in IR, but the parameters need to be // compile-time values only, so we can't transform them at all. if (owner.parentAsClass.isAnnotationClass) return expression val name = owner.name.asJvmFriendlyString() return enter("call-$name") { expression.dispatchReceiver = enter("\$this") { expression.dispatchReceiver?.transform(this, null) } expression.extensionReceiver = enter("\$\$this") { expression.extensionReceiver?.transform(this, null) } for (i in 0 until expression.valueArgumentsCount) { val arg = expression.getValueArgument(i) if (arg != null) { enter("arg-$i") { expression.putValueArgument(i, arg.transform(this, null)) } } } expression } } override fun visitEnumConstructorCall(expression: IrEnumConstructorCall): IrExpression { val owner = expression.symbol.owner val name = owner.name.asJvmFriendlyString() return enter("call-$name") { expression.dispatchReceiver = enter("\$this") { expression.dispatchReceiver?.transform(this, null) } expression.extensionReceiver = enter("\$\$this") { expression.extensionReceiver?.transform(this, null) } for (i in 0 until expression.valueArgumentsCount) { val arg = expression.getValueArgument(i) if (arg != null) { enter("arg-$i") { expression.putValueArgument(i, arg.transform(this, null)) } } } expression } } override fun visitConstructorCall(expression: IrConstructorCall): IrExpression { val owner = expression.symbol.owner // annotations are represented as constructor calls in IR, but the parameters need to be // compile-time values only, so we can't transform them at all. if (owner.parentAsClass.isAnnotationClass) return expression val name = owner.name.asJvmFriendlyString() return enter("call-$name") { expression.dispatchReceiver = enter("\$this") { expression.dispatchReceiver?.transform(this, null) } expression.extensionReceiver = enter("\$\$this") { expression.extensionReceiver?.transform(this, null) } for (i in 0 until expression.valueArgumentsCount) { val arg = expression.getValueArgument(i) if (arg != null) { enter("arg-$i") { expression.putValueArgument(i, arg.transform(this, null)) } } } expression } } override fun visitCall(expression: IrCall): IrExpression { val owner = expression.symbol.owner val name = owner.name.asJvmFriendlyString() return enter("call-$name") { expression.dispatchReceiver = enter("\$this") { expression.dispatchReceiver?.transform(this, null) } expression.extensionReceiver = enter("\$\$this") { expression.extensionReceiver?.transform(this, null) } for (i in 0 until expression.valueArgumentsCount) { val arg = expression.getValueArgument(i) if (arg != null) { enter("arg-$i") { expression.putValueArgument(i, arg.transform(this, null)) } } } expression } } override fun visitEnumEntry(declaration: IrEnumEntry): IrStatement { return enter("entry-${declaration.name.asJvmFriendlyString()}") { super.visitEnumEntry(declaration) } } override fun visitVararg(expression: IrVararg): IrExpression { if (expression !is IrVarargImpl) return expression return enter("vararg") { expression.elements.forEachIndexed { i, arg -> expression.elements[i] = enter("$i") { arg.transform(this, null) as IrVarargElement } } expression } } override fun visitSimpleFunction(declaration: IrSimpleFunction): IrStatement { if (declaration.hasNoLiveLiteralsAnnotation()) return declaration val name = declaration.name.asJvmFriendlyString() val path = if (name == "<anonymous>") "lambda" else "fun-$name" return enter(path) { super.visitSimpleFunction(declaration) } } override fun visitLoop(loop: IrLoop): IrExpression { return when (loop.origin) { // in these cases, the compiler relies on a certain structure for the condition // expression, so we only touch the body IrStatementOrigin.WHILE_LOOP, IrStatementOrigin.FOR_LOOP_INNER_WHILE -> enter("loop") { loop.body = enter("body") { loop.body?.transform(this, null) } loop } else -> enter("loop") { loop.condition = enter("cond") { loop.condition.transform(this, null) } loop.body = enter("body") { loop.body?.transform(this, null) } loop } } } override fun visitStringConcatenation(expression: IrStringConcatenation): IrExpression { if (expression !is IrStringConcatenationImpl) return expression return enter("str") { siblings { expression.arguments.forEachIndexed { index, expr -> expression.arguments[index] = enter("$index") { expr.transform(this, null) } } expression } } } override fun visitWhen(expression: IrWhen): IrExpression { return when (expression.origin) { // ANDAND needs to have an 'if true then false' body on its second branch, so only // transform the first branch IrStatementOrigin.ANDAND -> { expression.branches[0] = expression.branches[0].transform(this, null) expression } // OROR condition should have an 'if a then true' body on its first branch, so only // transform the second branch IrStatementOrigin.OROR -> { expression.branches[1] = expression.branches[1].transform(this, null) expression } IrStatementOrigin.IF -> siblings("if") { super.visitWhen(expression) } else -> siblings("when") { super.visitWhen(expression) } } } override fun visitValueParameter(declaration: IrValueParameter): IrStatement { return enter("param-${declaration.name.asJvmFriendlyString()}") { super.visitValueParameter(declaration) } } override fun visitElseBranch(branch: IrElseBranch): IrElseBranch { return IrElseBranchImpl( startOffset = branch.startOffset, endOffset = branch.endOffset, // the condition of an else branch is a constant boolean but we don't want // to convert it into a live literal, so we don't transform it condition = branch.condition, result = enter("else") { branch.result.transform(this, null) } ) } override fun visitBranch(branch: IrBranch): IrBranch { return IrBranchImpl( startOffset = branch.startOffset, endOffset = branch.endOffset, condition = enter("cond") { branch.condition.transform(this, null) }, // only translate the result, as the branch is a constant boolean but we don't want // to convert it into a live literal result = enter("branch") { branch.result.transform(this, null) } ) } override fun visitComposite(expression: IrComposite): IrExpression { return siblings { super.visitComposite(expression) } } override fun visitBlock(expression: IrBlock): IrExpression { return when (expression.origin) { // The compiler relies on a certain structure for the "iterator" instantiation in For // loops, so we avoid transforming the first statement in this case IrStatementOrigin.FOR_LOOP, IrStatementOrigin.FOR_LOOP_INNER_WHILE -> { expression.statements[1] = expression.statements[1].transform(this, null) as IrStatement expression } // IrStatementOrigin.SAFE_CALL // IrStatementOrigin.WHEN // IrStatementOrigin.IF // IrStatementOrigin.ELVIS // IrStatementOrigin.ARGUMENTS_REORDERING_FOR_CALL else -> siblings { super.visitBlock(expression) } } } override fun visitSetValue(expression: IrSetValue): IrExpression { val owner = expression.symbol.owner val name = owner.name return when (owner.origin) { // for these synthetic variable declarations we want to avoid transforming them since // the compiler will rely on their compile time value in some cases. IrDeclarationOrigin.FOR_LOOP_IMPLICIT_VARIABLE -> expression IrDeclarationOrigin.IR_TEMPORARY_VARIABLE -> expression IrDeclarationOrigin.FOR_LOOP_VARIABLE -> expression else -> enter("set-$name") { super.visitSetValue(expression) } } } override fun visitSetField(expression: IrSetField): IrExpression { val name = expression.symbol.owner.name return enter("set-$name") { super.visitSetField(expression) } } override fun visitBlockBody(body: IrBlockBody): IrBody { return siblings { super.visitBlockBody(body) } } override fun visitVariable(declaration: IrVariable): IrStatement { return enter("val-${declaration.name.asJvmFriendlyString()}") { super.visitVariable(declaration) } } override fun visitProperty(declaration: IrProperty): IrStatement { if (declaration.hasNoLiveLiteralsAnnotation()) return declaration val backingField = declaration.backingField val getter = declaration.getter val setter = declaration.setter val name = declaration.name.asJvmFriendlyString() return enter("val-$name") { // turn them into live literals. We should consider transforming some simple cases like // `val foo = 123`, but in general turning this initializer into a getter is not a // safe operation. We should figure out a way to do this for "static" expressions // though such as `val foo = 16.dp`. declaration.backingField = backingField declaration.getter = enter("get") { getter?.transform(this, null) as? IrSimpleFunction } declaration.setter = enter("set") { setter?.transform(this, null) as? IrSimpleFunction } declaration } } inline fun IrProperty.addSetter(builder: IrFunctionBuilder.() -> Unit = {}): IrSimpleFunction = IrFunctionBuilder().run { name = Name.special("<set-${[email protected]}>") builder() context.irFactory.buildFunction(this).also { setter -> [email protected] = setter setter.parent = [email protected] } } fun IrFactory.buildFunction(builder: IrFunctionBuilder): IrSimpleFunction = with(builder) { createFunction( startOffset, endOffset, origin, IrSimpleFunctionSymbolImpl(), name, visibility, modality, returnType, isInline, isExternal, isTailrec, isSuspend, isOperator, isInfix, isExpect, isFakeOverride, containerSource, ) } }
apache-2.0
androidx/androidx
buildSrc/private/src/main/kotlin/androidx/build/metalava/GenerateApiTask.kt
3
3074
/* * Copyright 2018 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.build.metalava import androidx.build.checkapi.ApiBaselinesLocation import androidx.build.checkapi.ApiLocation import androidx.build.java.JavaCompileInputs import org.gradle.api.provider.Property import org.gradle.api.tasks.CacheableTask import org.gradle.api.tasks.Input import org.gradle.api.tasks.InputFile import org.gradle.api.tasks.Internal import org.gradle.api.tasks.Optional import org.gradle.api.tasks.OutputFiles import org.gradle.api.tasks.PathSensitive import org.gradle.api.tasks.PathSensitivity import org.gradle.api.tasks.TaskAction import org.gradle.workers.WorkerExecutor import java.io.File import javax.inject.Inject /** Generate an API signature text file from a set of source files. */ @CacheableTask abstract class GenerateApiTask @Inject constructor( workerExecutor: WorkerExecutor ) : MetalavaTask(workerExecutor) { @get:Internal // already expressed by getApiLintBaseline() abstract val baselines: Property<ApiBaselinesLocation> @Optional @PathSensitive(PathSensitivity.NONE) @InputFile fun getApiLintBaseline(): File? { val baseline = baselines.get().apiLintFile return if (baseline.exists()) baseline else null } @get:Input var targetsJavaConsumers: Boolean = true @get:Input var generateRestrictToLibraryGroupAPIs = true /** Text file to which API signatures will be written. */ @get:Internal // already expressed by getTaskOutputs() abstract val apiLocation: Property<ApiLocation> @OutputFiles fun getTaskOutputs(): List<File> { val prop = apiLocation.get() return listOfNotNull( prop.publicApiFile, prop.removedApiFile, prop.experimentalApiFile, prop.restrictedApiFile ) } @TaskAction fun exec() { check(bootClasspath.files.isNotEmpty()) { "Android boot classpath not set." } check(sourcePaths.files.isNotEmpty()) { "Source paths not set." } val inputs = JavaCompileInputs( sourcePaths, dependencyClasspath, bootClasspath ) generateApi( metalavaClasspath, inputs, apiLocation.get(), ApiLintMode.CheckBaseline(baselines.get().apiLintFile, targetsJavaConsumers), generateRestrictToLibraryGroupAPIs, workerExecutor, manifestPath.orNull?.asFile?.absolutePath ) } }
apache-2.0
androidx/androidx
compose/ui/ui/src/androidAndroidTest/kotlin/androidx/compose/ui/layout/PlacementLayoutCoordinatesTest.kt
3
25330
/* * 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.layout import android.view.Gravity import android.view.View import android.view.ViewGroup import android.widget.FrameLayout import androidx.activity.ComponentActivity import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.offset import androidx.compose.foundation.layout.size import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.movableContentOf import androidx.compose.runtime.mutableStateListOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.AbsoluteAlignment import androidx.compose.ui.Alignment import androidx.compose.ui.ExperimentalComposeUiApi import androidx.compose.ui.Modifier import androidx.compose.ui.geometry.Offset import androidx.compose.ui.graphics.graphicsLayer import androidx.compose.ui.platform.ComposeView import androidx.compose.ui.test.junit4.createAndroidComposeRule import androidx.compose.ui.unit.DpOffset import androidx.compose.ui.unit.IntOffset import androidx.compose.ui.unit.IntSize import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.round import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.filters.MediumTest import org.junit.Assert.assertEquals import org.junit.Assert.assertNotEquals import org.junit.Assert.assertNotNull import org.junit.Assert.assertNull import org.junit.Assert.assertTrue import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith @OptIn(ExperimentalComposeUiApi::class) @MediumTest @RunWith(AndroidJUnit4::class) class PlacementLayoutCoordinatesTest { @get:Rule val rule = createAndroidComposeRule<ComponentActivity>() /** * The [Placeable.PlacementScope.coordinates] should not be `null` during normal placement * and should have the position of the parent that is placing. */ @Test fun coordinatesWhilePlacing() { val locations = mutableStateListOf<LayoutCoordinates?>() var locationAtPlace: IntOffset? by mutableStateOf(null) var boxSize by mutableStateOf(IntSize.Zero) var alignment by mutableStateOf(Alignment.Center) rule.setContent { Box(Modifier.fillMaxSize()) { Box( Modifier .align(alignment) .layout { measurable, constraints -> val p = measurable.measure(constraints) layout(p.width, p.height) { locations += coordinates locationAtPlace = coordinates ?.positionInRoot() ?.round() boxSize = IntSize(p.width, p.height) p.place(0, 0) } } .size(10.dp, 10.dp) ) } } rule.waitForIdle() assertNotNull(locationAtPlace) assertNotEquals(IntOffset.Zero, locationAtPlace) assertEquals(1, locations.size) locationAtPlace = null locations.clear() alignment = AbsoluteAlignment.TopLeft rule.waitForIdle() assertNotNull(locationAtPlace) assertEquals(IntOffset.Zero, locationAtPlace) assertEquals(1, locations.size) locationAtPlace = null locations.clear() alignment = AbsoluteAlignment.BottomRight rule.waitForIdle() assertNotNull(locationAtPlace) assertEquals(1, locations.size) val content = rule.activity.findViewById<View>(android.R.id.content) val bottomRight = IntOffset(content.width - boxSize.width, content.height - boxSize.height) assertEquals(bottomRight, locationAtPlace) } /** * The [Placeable.PlacementScope.coordinates] should not be `null` during normal placement * and should have the position of the parent that is placing. */ @OptIn(ExperimentalComposeUiApi::class) @Test fun coordinatesWhilePlacingWithLookaheadLayout() { val locations = mutableStateListOf<LayoutCoordinates?>() var locationAtPlace: IntOffset? by mutableStateOf(null) var boxSize by mutableStateOf(IntSize.Zero) var alignment by mutableStateOf(Alignment.Center) rule.setContent { SimpleLookaheadLayout { Box(Modifier.fillMaxSize()) { Box( Modifier .align(alignment) .layout { measurable, constraints -> val p = measurable.measure(constraints) layout(p.width, p.height) { locations += coordinates locationAtPlace = coordinates ?.positionInRoot() ?.round() boxSize = IntSize(p.width, p.height) p.place(0, 0) } } .size(10.dp, 10.dp) ) } } } rule.waitForIdle() locationAtPlace = null locations.clear() alignment = AbsoluteAlignment.TopLeft rule.waitForIdle() assertNotNull(locationAtPlace) assertEquals(IntOffset.Zero, locationAtPlace) assertEquals(2, locations.size) locationAtPlace = null locations.clear() alignment = AbsoluteAlignment.BottomRight rule.waitForIdle() assertNotNull(locationAtPlace) assertEquals(2, locations.size) val content = rule.activity.findViewById<View>(android.R.id.content) val bottomRight = IntOffset(content.width - boxSize.width, content.height - boxSize.height) assertEquals(bottomRight, locationAtPlace) } /** * The [Placeable.PlacementScope.coordinates] should be `null` while calculating the alignment, * but should be non-null after the alignment has been calculated. */ @Test fun coordinatesWhileAligning() { val locations = mutableStateListOf<LayoutCoordinates?>() rule.setContent { Row(Modifier.fillMaxSize()) { Box(Modifier.alignByBaseline()) { Text("Hello") } Box( Modifier .alignByBaseline() .layout { measurable, constraints -> val p = measurable.measure(constraints) layout(p.width, p.height) { locations += coordinates p.place(0, 0) } }) { Text("World") } } } rule.waitForIdle() assertTrue(locations.size > 1) assertNull(locations[0]) assertNotNull(locations.last()) } /** * The [Placeable.PlacementScope.coordinates] should be `null` while calculating the alignment, * but should be non-null after the alignment has been calculated. */ @OptIn(ExperimentalComposeUiApi::class) @Test fun coordinatesWhileAligningWithLookaheadLayout() { val locations = mutableStateListOf<LayoutCoordinates?>() rule.setContent { SimpleLookaheadLayout { Row(Modifier.fillMaxSize()) { Box(Modifier.alignByBaseline()) { Text("Hello") } Box( Modifier .alignByBaseline() .layout { measurable, constraints -> val p = measurable.measure(constraints) layout(p.width, p.height) { locations += coordinates p.place(0, 0) } }) { Text("World") } } } } rule.waitForIdle() // There may be a way to make this only 2 invocations for the first pass rather than 3. assertEquals(4, locations.size) assertNull(locations[0]) // Lookahead pass assertNull(locations[1]) // Lookahead pass - second look at alignment line assertNotNull(locations[2]) // Lookahead pass placement assertNotNull(locations[3]) // Measure pass } /** * The [Placeable.PlacementScope.coordinates] should be `null` while calculating the alignment, * but should be non-null after the alignment has been calculated. */ @Test fun coordinatesWhileAligningInLayout() { val locations = mutableStateListOf<LayoutCoordinates?>() rule.setContent { Row(Modifier.fillMaxSize()) { Box(Modifier.alignByBaseline()) { Text("Hello") } val content = @Composable { Text("World") } Layout(content, Modifier.alignByBaseline()) { measurables, constraints -> val p = measurables[0].measure(constraints) layout(p.width, p.height) { locations += coordinates p.place(0, 0) } } } } rule.waitForIdle() assertEquals(2, locations.size) assertNull(locations[0]) assertNotNull(locations[1]) } /** * The [Placeable.PlacementScope.coordinates] should be `null` while calculating the alignment, * but should be non-null after the alignment has been calculated. */ @OptIn(ExperimentalComposeUiApi::class) @Test fun coordinatesWhileAligningInLookaheadLayout() { val locations = mutableStateListOf<LayoutCoordinates?>() rule.setContent { SimpleLookaheadLayout { Row(Modifier.fillMaxSize()) { Box(Modifier.alignByBaseline()) { Text("Hello") } val content = @Composable { Text("World") } Layout(content, Modifier.alignByBaseline()) { measurables, constraints -> val p = measurables[0].measure(constraints) layout(p.width, p.height) { locations += coordinates p.place(0, 0) } } } } } rule.waitForIdle() assertEquals(3, locations.size) assertNull(locations[0]) // Lookahead pass assertNotNull(locations[1]) // Lookahead pass assertNotNull(locations[2]) // Measure pass } @Test fun coordinatesInNestedAlignmentLookup() { val locations = mutableStateListOf<LayoutCoordinates?>() var textLayoutInvocations = 0 rule.setContent { Row(Modifier.fillMaxSize()) { Box(Modifier.alignByBaseline()) { Text("Hello", modifier = Modifier.layout { measurable, constraints -> val p = measurable.measure(constraints) layout(p.width, p.height) { textLayoutInvocations++ p.place(0, 0) } }) } val content = @Composable { Text("World") } Layout(content, Modifier .alignByBaseline() .layout { measurable, constraints -> val p = measurable.measure(constraints) layout(p.width, p.height + 10) { p[LastBaseline] // invoke alignment p.place(0, 10) } }) { measurables, constraints -> val p = measurables[0].measure(constraints) layout(p.width, p.height) { locations += coordinates p.place(0, 0) } } } } rule.waitForIdle() assertEquals(1, textLayoutInvocations) assertTrue(locations.size > 1) assertNull(locations[0]) assertNotNull(locations.last()) } @Test fun parentCoordateChangeCausesRelayout() { val locations = mutableStateListOf<LayoutCoordinates?>() var offset by mutableStateOf(DpOffset(0.dp, 0.dp)) rule.setContent { Box(Modifier.fillMaxSize()) { Box(Modifier.offset(offset.x, offset.y)) { Box( Modifier .layout { measurable, constraints -> val p = measurable.measure(constraints) layout(p.width, p.height) { locations += coordinates p.place(0, 0) } } .size(10.dp, 10.dp) ) } } } rule.waitForIdle() assertEquals(1, locations.size) locations.clear() offset = DpOffset(1.dp, 2.dp) rule.waitForIdle() assertEquals(1, locations.size) } @Test fun grandParentCoordateChangeCausesRelayout() { val locations = mutableStateListOf<LayoutCoordinates?>() var offset by mutableStateOf(DpOffset(0.dp, 0.dp)) rule.setContent { Box(Modifier.fillMaxSize()) { Box(Modifier.offset(offset.x, offset.y)) { Box { Box( Modifier .layout { measurable, constraints -> val p = measurable.measure(constraints) layout(p.width, p.height) { locations += coordinates p.place(0, 0) } } .size(10.dp, 10.dp) ) } } } } rule.waitForIdle() assertEquals(1, locations.size) locations.clear() offset = DpOffset(1.dp, 2.dp) rule.waitForIdle() assertEquals(1, locations.size) } @Test fun newlyAddedStillUpdated() { val locations = mutableStateListOf<LayoutCoordinates?>() var offset by mutableStateOf(DpOffset(0.dp, 0.dp)) var showContent2 by mutableStateOf(false) rule.setContent { Box(Modifier.fillMaxSize()) { Box(Modifier.offset(offset.x, offset.y)) { Box { Box(Modifier.fillMaxSize()) if (showContent2) { Box( Modifier .layout { measurable, constraints -> val p = measurable.measure(constraints) layout(p.width, p.height) { locations += coordinates p.place(0, 0) } } .size(10.dp, 10.dp) ) } } } } } rule.waitForIdle() showContent2 = true rule.waitForIdle() assertEquals(1, locations.size) locations.clear() offset = DpOffset(1.dp, 2.dp) rule.waitForIdle() assertEquals(1, locations.size) } @Test fun removedStopsUpdating() { var readCoordinates by mutableStateOf(true) val layoutCalls = mutableStateListOf<LayoutCoordinates?>() var offset by mutableStateOf(DpOffset.Zero) rule.setContent { Box(Modifier.fillMaxSize()) { Box(Modifier.offset(offset.x, offset.y)) { Box { Box( Modifier .layout { measurable, constraints -> val p = measurable.measure(constraints) layout(p.width, p.height) { layoutCalls += if (readCoordinates) coordinates else null p.place(0, 0) } } .size(10.dp, 10.dp) ) } } } } rule.waitForIdle() assertEquals(1, layoutCalls.size) layoutCalls.clear() offset = DpOffset(10.dp, 5.dp) rule.waitForIdle() assertEquals(1, layoutCalls.size) layoutCalls.clear() readCoordinates = false rule.waitForIdle() assertEquals(1, layoutCalls.size) layoutCalls.clear() offset = DpOffset.Zero rule.waitForIdle() assertEquals(0, layoutCalls.size) } /** * When a LayoutNode is moved, its usage of coordinates should follow. */ @Test fun movedContentNotifies() { val locations = mutableStateListOf<LayoutCoordinates?>() var offset1 by mutableStateOf(DpOffset.Zero) var offset2 by mutableStateOf(DpOffset.Zero) var showInOne by mutableStateOf(true) rule.setContent { val usingCoordinates = remember { movableContentOf { Box( Modifier .layout { measurable, constraints -> val p = measurable.measure(constraints) layout(p.width, p.height) { locations += coordinates p.place(0, 0) } } .size(10.dp, 10.dp) ) } } Box(Modifier.fillMaxSize()) { Box( Modifier .size(50.dp) .offset(offset1.x, offset1.y) ) { if (showInOne) { usingCoordinates() } } Box( Modifier .size(50.dp) .offset(offset2.x, offset2.y) ) { if (!showInOne) { usingCoordinates() } } } } rule.waitForIdle() assertEquals(1, locations.size) offset1 = DpOffset(1.dp, 1.dp) rule.waitForIdle() assertEquals(2, locations.size) showInOne = false rule.waitForIdle() assertEquals(3, locations.size) offset2 = DpOffset(1.dp, 1.dp) rule.waitForIdle() assertEquals(4, locations.size) } /** * When [Placeable.PlacementScope.coordinates] is accessed during placement then changing the * layer properties on an ancestor should cause relayout. */ @Test fun ancestorLayerChangesCausesPlacement() { val locations = mutableStateListOf<LayoutCoordinates?>() var offset by mutableStateOf(Offset.Zero) rule.setContent { Box(Modifier.fillMaxSize()) { Box(Modifier.graphicsLayer { translationX = offset.x translationY = offset.y }) { Box( Modifier .layout { measurable, constraints -> val p = measurable.measure(constraints) layout(p.width, p.height) { locations += coordinates p.place(0, 0) } } .size(10.dp, 10.dp) ) } } } rule.waitForIdle() assertEquals(1, locations.size) offset = Offset(1f, 2f) rule.waitForIdle() assertEquals(2, locations.size) } /** * When [Placeable.PlacementScope.coordinates] is accessed during placement then changing the * layer properties of the LayoutNode should cause relayout. */ @Test fun layerChangesCausesPlacement() { val locations = mutableStateListOf<LayoutCoordinates?>() var offset by mutableStateOf(Offset.Zero) rule.setContent { Box(Modifier.fillMaxSize()) { Box( Modifier .graphicsLayer { translationX = offset.x translationY = offset.y } .layout { measurable, constraints -> val p = measurable.measure(constraints) layout(p.width, p.height) { locations += coordinates p.place(0, 0) } } .size(10.dp, 10.dp) ) } } rule.waitForIdle() assertEquals(1, locations.size) offset = Offset(1f, 2f) rule.waitForIdle() assertEquals(2, locations.size) } @Test fun viewPositionChangeCausesPlacement() { val locations = mutableStateListOf<LayoutCoordinates?>() lateinit var composeView: ComposeView rule.runOnUiThread { val container = FrameLayout(rule.activity) composeView = ComposeView(rule.activity).apply { setContent { Box( Modifier .layout { measurable, constraints -> val p = measurable.measure(constraints) layout(p.width, p.height) { locations += coordinates p.place(0, 0) } } .size(10.dp) ) } } container.addView( composeView, FrameLayout.LayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, Gravity.TOP or Gravity.LEFT ) ) container.layoutParams = ViewGroup.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT ) rule.activity.setContentView(container) } rule.waitForIdle() locations.clear() rule.runOnUiThread { val lp = composeView.layoutParams as FrameLayout.LayoutParams lp.gravity = Gravity.CENTER composeView.layoutParams = lp } rule.waitForIdle() assertEquals(1, locations.size) } } @OptIn(ExperimentalComposeUiApi::class) @Composable private fun SimpleLookaheadLayout(content: @Composable LookaheadLayoutScope.() -> Unit) { LookaheadLayout( content = content, measurePolicy = { measurables, constraints -> val p = measurables[0].measure(constraints) layout(p.width, p.height) { p.place(0, 0) } } ) }
apache-2.0
androidx/androidx
room/room-compiler/src/test/kotlin/androidx/room/processor/PojoProcessorTest.kt
3
70833
/* * 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.room.processor import COMMON import androidx.room.Embedded import androidx.room.compiler.codegen.toJavaPoet import androidx.room.compiler.processing.XFieldElement import androidx.room.compiler.processing.util.Source import androidx.room.compiler.processing.util.XTestInvocation import androidx.room.compiler.processing.util.runProcessorTest import androidx.room.parser.SQLTypeAffinity import androidx.room.processor.ProcessorErrors.CANNOT_FIND_GETTER_FOR_FIELD import androidx.room.processor.ProcessorErrors.MISSING_POJO_CONSTRUCTOR import androidx.room.processor.ProcessorErrors.POJO_FIELD_HAS_DUPLICATE_COLUMN_NAME import androidx.room.processor.ProcessorErrors.junctionColumnWithoutIndex import androidx.room.processor.ProcessorErrors.relationCannotFindEntityField import androidx.room.processor.ProcessorErrors.relationCannotFindJunctionEntityField import androidx.room.processor.ProcessorErrors.relationCannotFindJunctionParentField import androidx.room.processor.ProcessorErrors.relationCannotFindParentEntityField import androidx.room.testing.context import androidx.room.vo.CallType import androidx.room.vo.Constructor import androidx.room.vo.EmbeddedField import androidx.room.vo.Field import androidx.room.vo.FieldGetter import androidx.room.vo.FieldSetter import androidx.room.vo.Pojo import androidx.room.vo.RelationCollector import com.google.common.truth.Truth import com.squareup.javapoet.ClassName import com.squareup.javapoet.TypeName import java.io.File import org.hamcrest.CoreMatchers.instanceOf import org.hamcrest.CoreMatchers.`is` import org.hamcrest.CoreMatchers.not import org.hamcrest.CoreMatchers.notNullValue import org.hamcrest.CoreMatchers.nullValue import org.hamcrest.CoreMatchers.sameInstance import org.hamcrest.MatcherAssert.assertThat import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.JUnit4 import org.mockito.Mockito.doReturn import org.mockito.Mockito.mock /** * Some of the functionality is tested via TableEntityProcessor. */ @RunWith(JUnit4::class) class PojoProcessorTest { companion object { val MY_POJO: ClassName = ClassName.get("foo.bar", "MyPojo") val HEADER = """ package foo.bar; import androidx.room.*; import java.util.*; public class MyPojo { """ val FOOTER = "\n}" } @Test fun inheritedPrivate() { val parent = """ package foo.bar.x; import androidx.room.*; public class BaseClass { private String baseField; public String getBaseField(){ return baseField; } public void setBaseField(String baseField){ } } """ runProcessorTest( sources = listOf( Source.java( MY_POJO.toString(), """ package foo.bar; import androidx.room.*; public class ${MY_POJO.simpleName()} extends foo.bar.x.BaseClass { public String myField; } """ ), Source.java("foo.bar.x.BaseClass", parent) ) ) { invocation -> val pojo = PojoProcessor.createFor( context = invocation.context, element = invocation.processingEnv.requireTypeElement(MY_POJO), bindingScope = FieldProcessor.BindingScope.READ_FROM_CURSOR, parent = null ).process() assertThat(pojo.fields.find { it.name == "myField" }, notNullValue()) assertThat(pojo.fields.find { it.name == "baseField" }, notNullValue()) } } @Test fun transient_ignore() { singleRun( """ transient int foo; int bar; """ ) { pojo, _ -> assertThat(pojo.fields.size, `is`(1)) assertThat(pojo.fields[0].name, `is`("bar")) } } @Test fun transient_withColumnInfo() { singleRun( """ @ColumnInfo transient int foo; int bar; """ ) { pojo, _ -> assertThat(pojo.fields.map { it.name }.toSet(), `is`(setOf("bar", "foo"))) } } @Test fun transient_embedded() { singleRun( """ @Embedded transient Foo foo; int bar; static class Foo { int x; } """ ) { pojo, _ -> assertThat(pojo.fields.map { it.name }.toSet(), `is`(setOf("x", "bar"))) } } @Test fun transient_insideEmbedded() { singleRun( """ @Embedded Foo foo; int bar; static class Foo { transient int x; int y; } """ ) { pojo, _ -> assertThat(pojo.fields.map { it.name }.toSet(), `is`(setOf("bar", "y"))) } } @Test fun transient_relation() { singleRun( """ int id; @Relation(parentColumn = "id", entityColumn = "uid") public transient List<User> user; """, COMMON.USER, ) { pojo, invocation -> assertThat(pojo.relations.size, `is`(1)) assertThat(pojo.relations.first().entityField.name, `is`("uid")) assertThat(pojo.relations.first().parentField.name, `is`("id")) invocation.assertCompilationResult { hasNoWarnings() } } } @Test fun embedded() { singleRun( """ int id; @Embedded Point myPoint; static class Point { int x; int y; } """ ) { pojo, _ -> assertThat(pojo.fields.size, `is`(3)) assertThat(pojo.fields[1].name, `is`("x")) assertThat(pojo.fields[2].name, `is`("y")) assertThat(pojo.fields[0].parent, nullValue()) assertThat(pojo.fields[1].parent, notNullValue()) assertThat(pojo.fields[2].parent, notNullValue()) val parent = pojo.fields[2].parent!! assertThat(parent.prefix, `is`("")) assertThat(parent.field.name, `is`("myPoint")) assertThat( parent.pojo.typeName.toJavaPoet(), `is`(ClassName.get("foo.bar.MyPojo", "Point") as TypeName) ) } } @Test fun embeddedWithPrefix() { singleRun( """ int id; @Embedded(prefix = "foo") Point myPoint; static class Point { int x; @ColumnInfo(name = "y2") int y; } """ ) { pojo, _ -> assertThat(pojo.fields.size, `is`(3)) assertThat(pojo.fields[1].name, `is`("x")) assertThat(pojo.fields[2].name, `is`("y")) assertThat(pojo.fields[1].columnName, `is`("foox")) assertThat(pojo.fields[2].columnName, `is`("fooy2")) val parent = pojo.fields[2].parent!! assertThat(parent.prefix, `is`("foo")) } } @Test fun nestedEmbedded() { singleRun( """ int id; @Embedded(prefix = "foo") Point myPoint; static class Point { int x; @ColumnInfo(name = "y2") int y; @Embedded(prefix = "bar") Coordinate coordinate; } static class Coordinate { double lat; double lng; @Ignore String ignored; } """ ) { pojo, _ -> assertThat(pojo.fields.size, `is`(5)) assertThat( pojo.fields.map { it.columnName }, `is`( listOf("id", "foox", "fooy2", "foobarlat", "foobarlng") ) ) } } @Test fun embedded_generic() { val point = Source.java( "foo.bar.Point", """ package foo.bar; public class Point { public int x; public int y; } """ ) val base = Source.java( "foo.bar.BaseClass", """ package foo.bar; import ${Embedded::class.java.canonicalName}; public class BaseClass<T> { @Embedded public T genericField; } """ ) singleRunFullClass( """ package foo.bar; public class MyPojo extends BaseClass<Point> { public int normalField; } """, point, base ) { pojo, _ -> assertThat(pojo.fields.size, `is`(3)) assertThat( pojo.fields.map { it.columnName }.toSet(), `is`( setOf("x", "y", "normalField") ) ) val pointField = pojo.embeddedFields.first { it.field.name == "genericField" } assertThat( pointField.pojo.typeName.toJavaPoet(), `is`(ClassName.get("foo.bar", "Point") as TypeName) ) } } @Test fun embedded_badType() { singleRun( """ int id; @Embedded int embeddedPrimitive; """ ) { _, invocation -> invocation.assertCompilationResult { hasErrorContaining(ProcessorErrors.EMBEDDED_TYPES_MUST_BE_A_CLASS_OR_INTERFACE) } } } @Test fun duplicateColumnNames() { singleRun( """ int id; @ColumnInfo(name = "id") int another; """ ) { _, invocation -> invocation.assertCompilationResult { hasErrorContaining( ProcessorErrors.pojoDuplicateFieldNames( "id", listOf("id", "another") ) ) hasErrorContaining(POJO_FIELD_HAS_DUPLICATE_COLUMN_NAME) hasErrorCount(3) } } } @Test fun duplicateColumnNamesFromEmbedded() { singleRun( """ int id; @Embedded Foo foo; static class Foo { @ColumnInfo(name = "id") int x; } """ ) { _, invocation -> invocation.assertCompilationResult { hasErrorContaining( ProcessorErrors.pojoDuplicateFieldNames( "id", listOf("id", "foo > x") ) ) hasErrorContaining(POJO_FIELD_HAS_DUPLICATE_COLUMN_NAME) hasErrorCount(3) } } } @Test fun dropSubPrimaryKeyNoWarningForPojo() { singleRun( """ @PrimaryKey int id; @Embedded Point myPoint; static class Point { @PrimaryKey int x; int y; } """ ) { _, invocation -> invocation.assertCompilationResult { hasNoWarnings() } } } @Test fun relation_view() { singleRun( """ int id; @Relation(parentColumn = "id", entityColumn = "uid") public List<UserSummary> user; """, COMMON.USER_SUMMARY ) { _, _ -> } } @Test fun relation_notCollection() { singleRun( """ int id; @Relation(parentColumn = "id", entityColumn = "uid") public User user; """, COMMON.USER ) { _, _ -> } } @Test fun relation_columnInfo() { singleRun( """ int id; @ColumnInfo @Relation(parentColumn = "id", entityColumn = "uid") public List<User> user; """, COMMON.USER ) { _, invocation -> invocation.assertCompilationResult { hasErrorContaining(ProcessorErrors.CANNOT_USE_MORE_THAN_ONE_POJO_FIELD_ANNOTATION) } } } @Test fun relation_notEntity() { singleRun( """ int id; @Relation(parentColumn = "id", entityColumn = "uid") public List<NotAnEntity> user; """, COMMON.NOT_AN_ENTITY ) { _, invocation -> invocation.assertCompilationResult { hasErrorContaining(ProcessorErrors.NOT_ENTITY_OR_VIEW) } } } @Test fun relation_notDeclared() { singleRun( """ int id; @Relation(parentColumn = "id", entityColumn = "uid") public long user; """ ) { _, invocation -> invocation.assertCompilationResult { hasErrorContaining(ProcessorErrors.RELATION_TYPE_MUST_BE_A_CLASS_OR_INTERFACE) } } } @Test fun relation_missingParent() { singleRun( """ int id; @Relation(parentColumn = "idk", entityColumn = "uid") public List<User> user; """, COMMON.USER ) { _, invocation -> invocation.assertCompilationResult { hasErrorContaining( relationCannotFindParentEntityField("foo.bar.MyPojo", "idk", listOf("id")) ) } } } @Test fun relation_missingEntityField() { singleRun( """ int id; @Relation(parentColumn = "id", entityColumn = "idk") public List<User> user; """, COMMON.USER ) { _, invocation -> invocation.assertCompilationResult { hasErrorContaining( relationCannotFindEntityField( "foo.bar.User", "idk", listOf("uid", "name", "lastName", "age") ) ) } } } @Test fun relation_missingType() { singleRun( """ int id; @Relation(parentColumn = "id", entityColumn = "uid") public List<User> user; """ ) { _, invocation -> if (invocation.isKsp) { // TODO https://github.com/google/ksp/issues/371 // KSP is losing `isError` information in some cases. Compilation should still // fail (as class does not exist) but it will fail with a different error invocation.assertCompilationResult { compilationDidFail() } } else { invocation.assertCompilationResult { hasErrorContaining( "Element 'foo.bar.MyPojo' references a type that is not present" ) } } } } @Test fun relation_nestedField() { singleRun( """ static class Nested { @ColumnInfo(name = "foo") public int id; } @Embedded Nested nested; @Relation(parentColumn = "foo", entityColumn = "uid") public List<User> user; """, COMMON.USER ) { pojo, _ -> assertThat(pojo.relations.first().parentField.columnName, `is`("foo")) } } @Test fun relation_nestedRelation() { singleRun( """ static class UserWithNested { @Embedded public User user; @Relation(parentColumn = "uid", entityColumn = "uid") public List<User> selfs; } int id; @Relation(parentColumn = "id", entityColumn = "uid", entity = User.class) public List<UserWithNested> user; """, COMMON.USER ) { pojo, invocation -> assertThat(pojo.relations.first().parentField.name, `is`("id")) invocation.assertCompilationResult { hasNoWarnings() } } } @Test fun relation_affinityMismatch() { singleRun( """ String id; @Relation(parentColumn = "id", entityColumn = "uid") public List<User> user; """, COMMON.USER ) { pojo, invocation -> // trigger assignment evaluation RelationCollector.createCollectors(invocation.context, pojo.relations) assertThat(pojo.relations.size, `is`(1)) assertThat(pojo.relations.first().entityField.name, `is`("uid")) assertThat(pojo.relations.first().parentField.name, `is`("id")) invocation.assertCompilationResult { hasWarningContaining( ProcessorErrors.relationAffinityMismatch( parentAffinity = SQLTypeAffinity.TEXT, childAffinity = SQLTypeAffinity.INTEGER, parentColumn = "id", childColumn = "uid" ) ) } } } @Test fun relation_simple() { singleRun( """ int id; @Relation(parentColumn = "id", entityColumn = "uid") public List<User> user; """, COMMON.USER ) { pojo, invocation -> assertThat(pojo.relations.size, `is`(1)) assertThat(pojo.relations.first().entityField.name, `is`("uid")) assertThat(pojo.relations.first().parentField.name, `is`("id")) invocation.assertCompilationResult { hasNoWarnings() } } } @Test fun relation_badProjection() { singleRun( """ int id; @Relation(parentColumn = "id", entityColumn = "uid", projection={"i_dont_exist"}) public List<User> user; """, COMMON.USER ) { _, invocation -> invocation.assertCompilationResult { hasErrorContaining( ProcessorErrors.relationBadProject( "foo.bar.User", listOf("i_dont_exist"), listOf("uid", "name", "lastName", "ageColumn") ) ) } } } @Test fun relation_badReturnTypeInGetter() { singleRun( """ int id; @Relation(parentColumn = "id", entityColumn = "uid") private List<User> user; public void setUser(List<User> user){ this.user = user;} public User getUser(){return null;} """, COMMON.USER ) { _, invocation -> invocation.assertCompilationResult { hasErrorContaining(CANNOT_FIND_GETTER_FOR_FIELD) } } } @Test fun relation_primitiveList() { singleRun( """ int id; @Relation(parentColumn = "id", entityColumn = "uid", projection={"uid"}, entity = User.class) public List<Integer> userIds; """, COMMON.USER ) { pojo, _ -> assertThat(pojo.relations.size, `is`(1)) val rel = pojo.relations.first() assertThat(rel.projection, `is`(listOf("uid"))) assertThat(rel.entity.typeName, `is`(COMMON.USER_TYPE_NAME)) } } @Test fun relation_stringList() { singleRun( """ int id; @Relation(parentColumn = "id", entityColumn = "uid", projection={"name"}, entity = User.class) public List<String> userNames; """, COMMON.USER ) { pojo, _ -> assertThat(pojo.relations.size, `is`(1)) val rel = pojo.relations.first() assertThat(rel.projection, `is`(listOf("name"))) assertThat(rel.entity.typeName, `is`(COMMON.USER_TYPE_NAME)) } } @Test fun relation_extendsBounds() { singleRun( """ int id; @Relation(parentColumn = "id", entityColumn = "uid") public List<? extends User> user; """, COMMON.USER ) { pojo, invocation -> assertThat(pojo.relations.size, `is`(1)) assertThat(pojo.relations.first().entityField.name, `is`("uid")) assertThat(pojo.relations.first().parentField.name, `is`("id")) invocation.assertCompilationResult { hasNoWarnings() } } } @Test fun relation_associateBy() { val junctionEntity = Source.java( "foo.bar.UserFriendsXRef", """ package foo.bar; import androidx.room.*; @Entity( primaryKeys = {"uid","friendId"}, foreignKeys = { @ForeignKey( entity = User.class, parentColumns = "uid", childColumns = "uid", onDelete = ForeignKey.CASCADE), @ForeignKey( entity = User.class, parentColumns = "uid", childColumns = "friendId", onDelete = ForeignKey.CASCADE), }, indices = { @Index("uid"), @Index("friendId") } ) public class UserFriendsXRef { public int uid; public int friendId; } """ ) singleRun( """ int id; @Relation( parentColumn = "id", entityColumn = "uid", associateBy = @Junction( value = UserFriendsXRef.class, parentColumn = "uid", entityColumn = "friendId") ) public List<User> user; """, COMMON.USER, junctionEntity ) { pojo, invocation -> assertThat(pojo.relations.size, `is`(1)) assertThat(pojo.relations.first().junction, notNullValue()) assertThat( pojo.relations.first().junction!!.parentField.columnName, `is`("uid") ) assertThat( pojo.relations.first().junction!!.entityField.columnName, `is`("friendId") ) invocation.assertCompilationResult { hasNoWarnings() } } } @Test fun relation_associateBy_withView() { val junctionEntity = Source.java( "foo.bar.UserFriendsXRefView", """ package foo.bar; import androidx.room.*; @DatabaseView("SELECT 1, 2, FROM User") public class UserFriendsXRefView { public int uid; public int friendId; } """ ) singleRun( """ int id; @Relation( parentColumn = "id", entityColumn = "uid", associateBy = @Junction( value = UserFriendsXRefView.class, parentColumn = "uid", entityColumn = "friendId") ) public List<User> user; """, COMMON.USER, junctionEntity ) { _, invocation -> invocation.assertCompilationResult { hasNoWarnings() } } } @Test fun relation_associateBy_defaultColumns() { val junctionEntity = Source.java( "foo.bar.UserFriendsXRef", """ package foo.bar; import androidx.room.*; @Entity( primaryKeys = {"uid","friendId"}, foreignKeys = { @ForeignKey( entity = User.class, parentColumns = "uid", childColumns = "uid", onDelete = ForeignKey.CASCADE), @ForeignKey( entity = User.class, parentColumns = "uid", childColumns = "friendId", onDelete = ForeignKey.CASCADE), }, indices = { @Index("uid"), @Index("friendId") } ) public class UserFriendsXRef { public int uid; public int friendId; } """ ) singleRun( """ int friendId; @Relation( parentColumn = "friendId", entityColumn = "uid", associateBy = @Junction(UserFriendsXRef.class)) public List<User> user; """, COMMON.USER, junctionEntity ) { _, invocation -> invocation.assertCompilationResult { hasNoWarnings() } } } @Test fun relation_associateBy_missingParentColumn() { val junctionEntity = Source.java( "foo.bar.UserFriendsXRef", """ package foo.bar; import androidx.room.*; @Entity(primaryKeys = {"friendFrom","uid"}) public class UserFriendsXRef { public int friendFrom; public int uid; } """ ) singleRun( """ int id; @Relation( parentColumn = "id", entityColumn = "uid", associateBy = @Junction(UserFriendsXRef.class) ) public List<User> user; """, COMMON.USER, junctionEntity ) { _, invocation -> invocation.assertCompilationResult { hasErrorContaining( relationCannotFindJunctionParentField( "foo.bar.UserFriendsXRef", "id", listOf("friendFrom", "uid") ) ) } } } @Test fun relation_associateBy_missingEntityColumn() { val junctionEntity = Source.java( "foo.bar.UserFriendsXRef", """ package foo.bar; import androidx.room.*; @Entity(primaryKeys = {"friendA","friendB"}) public class UserFriendsXRef { public int friendA; public int friendB; } """ ) singleRun( """ int friendA; @Relation( parentColumn = "friendA", entityColumn = "uid", associateBy = @Junction(UserFriendsXRef.class) ) public List<User> user; """, COMMON.USER, junctionEntity ) { _, invocation -> invocation.assertCompilationResult { hasErrorContaining( relationCannotFindJunctionEntityField( "foo.bar.UserFriendsXRef", "uid", listOf("friendA", "friendB") ) ) } } } @Test fun relation_associateBy_missingSpecifiedParentColumn() { val junctionEntity = Source.java( "foo.bar.UserFriendsXRef", """ package foo.bar; import androidx.room.*; @Entity(primaryKeys = {"friendA","friendB"}) public class UserFriendsXRef { public int friendA; public int friendB; } """ ) singleRun( """ int friendA; @Relation( parentColumn = "friendA", entityColumn = "uid", associateBy = @Junction( value = UserFriendsXRef.class, parentColumn = "bad_col") ) public List<User> user; """, COMMON.USER, junctionEntity ) { _, invocation -> invocation.assertCompilationResult { hasErrorContaining( relationCannotFindJunctionParentField( "foo.bar.UserFriendsXRef", "bad_col", listOf("friendA", "friendB") ) ) } } } @Test fun relation_associateBy_missingSpecifiedEntityColumn() { val junctionEntity = Source.java( "foo.bar.UserFriendsXRef", """ package foo.bar; import androidx.room.*; @Entity(primaryKeys = {"friendA","friendB"}) public class UserFriendsXRef { public int friendA; public int friendB; } """ ) singleRun( """ int friendA; @Relation( parentColumn = "friendA", entityColumn = "uid", associateBy = @Junction( value = UserFriendsXRef.class, entityColumn = "bad_col") ) public List<User> user; """, COMMON.USER, junctionEntity ) { _, invocation -> invocation.assertCompilationResult { hasErrorContaining( relationCannotFindJunctionEntityField( "foo.bar.UserFriendsXRef", "bad_col", listOf("friendA", "friendB") ) ) } } } @Test fun relation_associateBy_warnIndexOnJunctionColumn() { val junctionEntity = Source.java( "foo.bar.UserFriendsXRef", """ package foo.bar; import androidx.room.*; @Entity public class UserFriendsXRef { @PrimaryKey(autoGenerate = true) public long rowid; public int uid; public int friendId; } """ ) singleRun( """ int friendId; @Relation( parentColumn = "friendId", entityColumn = "uid", associateBy = @Junction(UserFriendsXRef.class)) public List<User> user; """, COMMON.USER, junctionEntity ) { _, invocation -> invocation.assertCompilationResult { hasWarningCount(2) hasWarningContaining( junctionColumnWithoutIndex("foo.bar.UserFriendsXRef", "uid") ) } } } @Test fun cache() { val pojo = Source.java( MY_POJO.toString(), """ $HEADER int id; $FOOTER """ ) runProcessorTest(sources = listOf(pojo)) { invocation -> val element = invocation.processingEnv.requireTypeElement(MY_POJO) val pojo1 = PojoProcessor.createFor( invocation.context, element, FieldProcessor.BindingScope.BIND_TO_STMT, null ).process() assertThat(pojo1, notNullValue()) val pojo2 = PojoProcessor.createFor( invocation.context, element, FieldProcessor.BindingScope.BIND_TO_STMT, null ).process() assertThat(pojo2, sameInstance(pojo1)) val pojo3 = PojoProcessor.createFor( invocation.context, element, FieldProcessor.BindingScope.READ_FROM_CURSOR, null ).process() assertThat(pojo3, notNullValue()) assertThat(pojo3, not(sameInstance(pojo1))) val pojo4 = PojoProcessor.createFor( invocation.context, element, FieldProcessor.BindingScope.TWO_WAY, null ).process() assertThat(pojo4, notNullValue()) assertThat(pojo4, not(sameInstance(pojo1))) assertThat(pojo4, not(sameInstance(pojo3))) val pojo5 = PojoProcessor.createFor( invocation.context, element, FieldProcessor.BindingScope.TWO_WAY, null ).process() assertThat(pojo5, sameInstance(pojo4)) val type = invocation.context.COMMON_TYPES.STRING val mockElement = mock(XFieldElement::class.java) doReturn(type).`when`(mockElement).type val fakeField = Field( element = mockElement, name = "foo", type = type, affinity = SQLTypeAffinity.TEXT, columnName = "foo", parent = null, indexed = false ) val fakeEmbedded = EmbeddedField(fakeField, "", null) val pojo6 = PojoProcessor.createFor( invocation.context, element, FieldProcessor.BindingScope.TWO_WAY, fakeEmbedded ).process() assertThat(pojo6, notNullValue()) assertThat(pojo6, not(sameInstance(pojo1))) assertThat(pojo6, not(sameInstance(pojo3))) assertThat(pojo6, not(sameInstance(pojo4))) val pojo7 = PojoProcessor.createFor( invocation.context, element, FieldProcessor.BindingScope.TWO_WAY, fakeEmbedded ).process() assertThat(pojo7, sameInstance(pojo6)) } } @Test fun constructor_empty() { val pojoCode = """ public String mName; """ singleRun(pojoCode) { pojo, _ -> assertThat(pojo.constructor, notNullValue()) assertThat(pojo.constructor?.params, `is`(emptyList())) } } @Test fun constructor_ambiguous_twoFieldsExactMatch() { val pojoCode = """ public String mName; public String _name; public MyPojo(String mName) { } """ singleRun(pojoCode) { pojo, _ -> val param = pojo.constructor?.params?.first() assertThat(param, instanceOf(Constructor.Param.FieldParam::class.java)) assertThat((param as Constructor.Param.FieldParam).field.name, `is`("mName")) assertThat( pojo.fields.find { it.name == "mName" }?.setter?.callType, `is`(CallType.CONSTRUCTOR) ) } } @Test fun constructor_ambiguous_oneTypeMatches() { val pojoCode = """ public String mName; public int _name; public MyPojo(String name) { } """ singleRun(pojoCode) { pojo, _ -> val param = pojo.constructor?.params?.first() assertThat(param, instanceOf(Constructor.Param.FieldParam::class.java)) assertThat((param as Constructor.Param.FieldParam).field.name, `is`("mName")) assertThat( pojo.fields.find { it.name == "mName" }?.setter?.callType, `is`(CallType.CONSTRUCTOR) ) } } @Test fun constructor_ambiguous_twoFields() { val pojo = """ String mName; String _name; public MyPojo(String name) { } """ singleRun(pojo) { _, invocation -> invocation.assertCompilationResult { hasErrorContaining( ProcessorErrors.ambiguousConstructor( MY_POJO.toString(), "name", listOf("mName", "_name") ) ) } } } @Test fun constructor_noMatchBadType() { singleRun( """ int foo; public MyPojo(String foo) { } """ ) { _, invocation -> invocation.assertCompilationResult { hasErrorContaining(MISSING_POJO_CONSTRUCTOR) } } } @Test fun constructor_noMatch() { singleRun( """ String mName; String _name; public MyPojo(String foo) { } """ ) { _, invocation -> invocation.assertCompilationResult { hasErrorContaining(MISSING_POJO_CONSTRUCTOR) } } } @Test fun constructor_noMatchMultiArg() { singleRun( """ String mName; int bar; public MyPojo(String foo, String name) { } """ ) { _, invocation -> invocation.assertCompilationResult { hasErrorContaining(MISSING_POJO_CONSTRUCTOR) } } } @Test fun constructor_multipleMatching() { singleRun( """ String mName; String mLastName; public MyPojo(String name) { } public MyPojo(String name, String lastName) { } """ ) { _, invocation -> invocation.assertCompilationResult { hasErrorContaining(ProcessorErrors.TOO_MANY_POJO_CONSTRUCTORS) } } } @Test fun constructor_multipleMatchingWithIgnored() { singleRun( """ String mName; String mLastName; @Ignore public MyPojo(String name) { } public MyPojo(String name, String lastName) { } """ ) { pojo, _ -> assertThat(pojo.constructor, notNullValue()) assertThat(pojo.constructor?.params?.size, `is`(2)) assertThat( pojo.fields.find { it.name == "mName" }?.setter?.callType, `is`(CallType.CONSTRUCTOR) ) assertThat( pojo.fields.find { it.name == "mLastName" }?.setter?.callType, `is`(CallType.CONSTRUCTOR) ) } } @Test fun constructor_dontTryForBindToScope() { singleRun( """ String mName; String mLastName; """ ) { _, invocation -> val process2 = PojoProcessor.createFor( context = invocation.context, element = invocation.processingEnv.requireTypeElement(MY_POJO), bindingScope = FieldProcessor.BindingScope.BIND_TO_STMT, parent = null ).process() assertThat(process2.constructor, nullValue()) } } @Test fun constructor_bindForTwoWay() { singleRun( """ String mName; String mLastName; """ ) { _, invocation -> val process2 = PojoProcessor.createFor( context = invocation.context, element = invocation.processingEnv.requireTypeElement(MY_POJO), bindingScope = FieldProcessor.BindingScope.TWO_WAY, parent = null ).process() assertThat(process2.constructor, notNullValue()) } } @Test fun constructor_multipleMatching_withNoArg() { singleRun( """ String mName; String mLastName; public MyPojo() { } public MyPojo(String name, String lastName) { } """ ) { pojo, invocation -> assertThat(pojo.constructor?.params?.size ?: -1, `is`(0)) invocation.assertCompilationResult { hasWarningContaining(ProcessorErrors.TOO_MANY_POJO_CONSTRUCTORS_CHOOSING_NO_ARG) } } } @Test // added for b/69562125 fun constructor_withNullabilityAnnotation() { singleRun( """ String mName; public MyPojo(@androidx.annotation.NonNull String name) {} """ ) { pojo, _ -> val constructor = pojo.constructor assertThat(constructor, notNullValue()) assertThat(constructor!!.params.size, `is`(1)) } } @Test fun constructor_relationParameter() { singleRun( """ @Relation(entity = foo.bar.User.class, parentColumn = "uid", entityColumn="uid", projection = "name") public List<String> items; public String uid; public MyPojo(String uid, List<String> items) { } """, COMMON.USER ) { _, _ -> } } @Test fun recursion_1Level_embedded() { singleRun( """ @Embedded MyPojo myPojo; """ ) { _, invocation -> invocation.assertCompilationResult { hasErrorContaining( ProcessorErrors.RECURSIVE_REFERENCE_DETECTED.format( "foo.bar.MyPojo -> foo.bar.MyPojo" ) ) } } } @Test fun recursion_1Level_relation() { singleRun( """ long id; long parentId; @Relation(parentColumn = "id", entityColumn = "parentId") Set<MyPojo> children; """ ) { _, invocation -> invocation.assertCompilationResult { hasErrorContaining( ProcessorErrors.RECURSIVE_REFERENCE_DETECTED.format( "foo.bar.MyPojo -> foo.bar.MyPojo" ) ) } } } @Test fun recursion_1Level_relation_specifyEntity() { singleRun( """ @Embedded A a; static class A { long id; long parentId; @Relation(entity = A.class, parentColumn = "id", entityColumn = "parentId") Set<AWithB> children; } static class B { long id; } static class AWithB { @Embedded A a; @Embedded B b; } """ ) { _, invocation -> invocation.assertCompilationResult { hasErrorContaining( ProcessorErrors.RECURSIVE_REFERENCE_DETECTED.format( "foo.bar.MyPojo.A -> foo.bar.MyPojo.A" ) ) } } } @Test fun recursion_2Levels_relationToEmbed() { singleRun( """ int pojoId; @Relation(parentColumn = "pojoId", entityColumn = "entityId") List<MyEntity> myEntity; @Entity static class MyEntity { int entityId; @Embedded MyPojo myPojo; } """ ) { _, invocation -> invocation.assertCompilationResult { hasErrorContaining( ProcessorErrors.RECURSIVE_REFERENCE_DETECTED.format( "foo.bar.MyPojo -> foo.bar.MyPojo.MyEntity -> foo.bar.MyPojo" ) ) } } } @Test fun recursion_2Levels_onlyEmbeds_pojoToEntity() { singleRun( """ @Embedded A a; @Entity static class A { @Embedded MyPojo myPojo; } """ ) { _, invocation -> invocation.assertCompilationResult { hasErrorContaining( ProcessorErrors.RECURSIVE_REFERENCE_DETECTED.format( "foo.bar.MyPojo -> foo.bar.MyPojo.A -> foo.bar.MyPojo" ) ) } } } @Test fun recursion_2Levels_onlyEmbeds_onlyPojos() { singleRun( """ @Embedded A a; static class A { @Embedded MyPojo myPojo; } """ ) { _, invocation -> invocation.assertCompilationResult { hasErrorContaining( ProcessorErrors.RECURSIVE_REFERENCE_DETECTED.format( "foo.bar.MyPojo -> foo.bar.MyPojo.A -> foo.bar.MyPojo" ) ) } } } @Test fun recursion_2Level_relationToEmbed() { singleRun( """ @Embedded A a; static class A { long id; long parentId; @Relation(parentColumn = "id", entityColumn = "parentId") Set<AWithB> children; } static class B { long id; } static class AWithB { @Embedded A a; @Embedded B b; } """ ) { _, invocation -> invocation.assertCompilationResult { hasErrorContaining( ProcessorErrors.RECURSIVE_REFERENCE_DETECTED.format( "foo.bar.MyPojo.A -> foo.bar.MyPojo.AWithB -> foo.bar.MyPojo.A" ) ) } } } @Test fun recursion_3Levels() { singleRun( """ @Embedded A a; public static class A { @Embedded B b; } public static class B { @Embedded MyPojo myPojo; } """ ) { _, invocation -> invocation.assertCompilationResult { hasErrorContaining( ProcessorErrors.RECURSIVE_REFERENCE_DETECTED.format( "foo.bar.MyPojo -> foo.bar.MyPojo.A -> foo.bar.MyPojo.B -> foo.bar.MyPojo" ) ) } } } @Test fun recursion_1Level_1LevelDown() { singleRun( """ @Embedded A a; static class A { @Embedded B b; } static class B { @Embedded A a; } """ ) { _, invocation -> invocation.assertCompilationResult { hasErrorContaining( ProcessorErrors.RECURSIVE_REFERENCE_DETECTED.format( "foo.bar.MyPojo.A -> foo.bar.MyPojo.B -> foo.bar.MyPojo.A" ) ) } } } @Test fun recursion_branchAtLevel0_afterBackTrack() { singleRun( """ @PrimaryKey int id; @Embedded A a; @Embedded C c; static class A { @Embedded B b; } static class B { } static class C { @Embedded MyPojo myPojo; } """ ) { _, invocation -> invocation.assertCompilationResult { hasErrorContaining( ProcessorErrors.RECURSIVE_REFERENCE_DETECTED.format( "foo.bar.MyPojo -> foo.bar.MyPojo.C -> foo.bar.MyPojo" ) ) } } } @Test fun recursion_branchAtLevel1_afterBackTrack() { singleRun( """ @PrimaryKey int id; @Embedded A a; static class A { @Embedded B b; @Embedded MyPojo myPojo; } static class B { @Embedded C c; } static class C { } """ ) { _, invocation -> invocation.assertCompilationResult { hasErrorContaining( ProcessorErrors.RECURSIVE_REFERENCE_DETECTED.format( "foo.bar.MyPojo -> foo.bar.MyPojo.A -> foo.bar.MyPojo" ) ) } } } @Test fun dataClass_primaryConstructor() { listOf( TestData.AllDefaultVals::class.java.canonicalName!!, TestData.AllDefaultVars::class.java.canonicalName!!, TestData.SomeDefaultVals::class.java.canonicalName!!, TestData.SomeDefaultVars::class.java.canonicalName!!, TestData.WithJvmOverloads::class.java.canonicalName!! ).forEach { runProcessorTest { invocation -> PojoProcessor.createFor( context = invocation.context, element = invocation.processingEnv.requireTypeElement(it), bindingScope = FieldProcessor.BindingScope.READ_FROM_CURSOR, parent = null ).process() invocation.assertCompilationResult { hasNoWarnings() } } } } @Test fun dataClass_withJvmOverloads_primaryConstructor() { runProcessorTest { invocation -> PojoProcessor.createFor( context = invocation.context, element = invocation.processingEnv.requireTypeElement( TestData.WithJvmOverloads::class ), bindingScope = FieldProcessor.BindingScope.READ_FROM_CURSOR, parent = null ).process() invocation.assertCompilationResult { hasNoWarnings() } } } @Test fun ignoredColumns() { val source = Source.java( MY_POJO.toString(), """ package foo.bar; import androidx.room.*; @Entity(ignoredColumns = {"bar"}) public class ${MY_POJO.simpleName()} { public String foo; public String bar; } """ ) runProcessorTest( sources = listOf(source) ) { invocation -> val pojo = PojoProcessor.createFor( context = invocation.context, element = invocation.processingEnv.requireTypeElement(MY_POJO), bindingScope = FieldProcessor.BindingScope.READ_FROM_CURSOR, parent = null ).process() assertThat(pojo.fields.find { it.name == "foo" }, notNullValue()) assertThat(pojo.fields.find { it.name == "bar" }, nullValue()) } } @Test fun ignoredColumns_noConstructor() { runProcessorTest( listOf( Source.java( MY_POJO.toString(), """ package foo.bar; import androidx.room.*; @Entity(ignoredColumns = {"bar"}) public class ${MY_POJO.simpleName()} { private final String foo; private final String bar; public ${MY_POJO.simpleName()}(String foo) { this.foo = foo; this.bar = null; } public String getFoo() { return this.foo; } } """ ) ) ) { invocation -> val pojo = PojoProcessor.createFor( context = invocation.context, element = invocation.processingEnv.requireTypeElement(MY_POJO), bindingScope = FieldProcessor.BindingScope.READ_FROM_CURSOR, parent = null ).process() assertThat(pojo.fields.find { it.name == "foo" }, notNullValue()) assertThat(pojo.fields.find { it.name == "bar" }, nullValue()) } } @Test fun ignoredColumns_noSetterGetter() { runProcessorTest( listOf( Source.java( MY_POJO.toString(), """ package foo.bar; import androidx.room.*; @Entity(ignoredColumns = {"bar"}) public class ${MY_POJO.simpleName()} { private String foo; private String bar; public String getFoo() { return this.foo; } public void setFoo(String foo) { this.foo = foo; } } """ ) ) ) { invocation -> val pojo = PojoProcessor.createFor( context = invocation.context, element = invocation.processingEnv.requireTypeElement(MY_POJO), bindingScope = FieldProcessor.BindingScope.READ_FROM_CURSOR, parent = null ).process() assertThat(pojo.fields.find { it.name == "foo" }, notNullValue()) assertThat(pojo.fields.find { it.name == "bar" }, nullValue()) } } @Test fun ignoredColumns_columnInfo() { runProcessorTest( listOf( Source.java( MY_POJO.toString(), """ package foo.bar; import androidx.room.*; @Entity(ignoredColumns = {"my_bar"}) public class ${MY_POJO.simpleName()} { public String foo; @ColumnInfo(name = "my_bar") public String bar; } """ ) ) ) { invocation -> val pojo = PojoProcessor.createFor( context = invocation.context, element = invocation.processingEnv.requireTypeElement(MY_POJO), bindingScope = FieldProcessor.BindingScope.READ_FROM_CURSOR, parent = null ).process() assertThat(pojo.fields.find { it.name == "foo" }, notNullValue()) assertThat(pojo.fields.find { it.name == "bar" }, nullValue()) } } @Test fun ignoredColumns_missing() { runProcessorTest( listOf( Source.java( MY_POJO.toString(), """ package foo.bar; import androidx.room.*; @Entity(ignoredColumns = {"no_such_column"}) public class ${MY_POJO.simpleName()} { public String foo; public String bar; } """ ) ) ) { invocation -> val pojo = PojoProcessor.createFor( context = invocation.context, element = invocation.processingEnv.requireTypeElement(MY_POJO), bindingScope = FieldProcessor.BindingScope.READ_FROM_CURSOR, parent = null ).process() assertThat(pojo.fields.find { it.name == "foo" }, notNullValue()) assertThat(pojo.fields.find { it.name == "bar" }, notNullValue()) invocation.assertCompilationResult { hasErrorContaining( ProcessorErrors.missingIgnoredColumns(listOf("no_such_column")) ) } } } @Test fun noSetter_scopeBindStmt() { runProcessorTest( listOf( Source.java( MY_POJO.toString(), """ package foo.bar; import androidx.room.*; public class ${MY_POJO.simpleName()} { private String foo; private String bar; public String getFoo() { return foo; } public String getBar() { return bar; } } """ ) ) ) { invocation -> PojoProcessor.createFor( context = invocation.context, element = invocation.processingEnv.requireTypeElement(MY_POJO), bindingScope = FieldProcessor.BindingScope.BIND_TO_STMT, parent = null ).process() } } @Test fun noSetter_scopeTwoWay() { runProcessorTest( listOf( Source.java( MY_POJO.toString(), """ package foo.bar; import androidx.room.*; public class ${MY_POJO.simpleName()} { private String foo; private String bar; public String getFoo() { return foo; } public String getBar() { return bar; } } """ ) ) ) { invocation -> PojoProcessor.createFor( context = invocation.context, element = invocation.processingEnv.requireTypeElement(MY_POJO), bindingScope = FieldProcessor.BindingScope.TWO_WAY, parent = null ).process() invocation.assertCompilationResult { hasErrorContaining( "Cannot find setter for field." ) } } } @Test fun noSetter_scopeReadFromCursor() { runProcessorTest( listOf( Source.java( MY_POJO.toString(), """ package foo.bar; import androidx.room.*; public class ${MY_POJO.simpleName()} { private String foo; private String bar; public String getFoo() { return foo; } public String getBar() { return bar; } } """ ) ) ) { invocation -> PojoProcessor.createFor( context = invocation.context, element = invocation.processingEnv.requireTypeElement(MY_POJO), bindingScope = FieldProcessor.BindingScope.READ_FROM_CURSOR, parent = null ).process() invocation.assertCompilationResult { hasErrorContaining( "Cannot find setter for field." ) } } } @Test fun noGetter_scopeBindStmt() { runProcessorTest( listOf( Source.java( MY_POJO.toString(), """ package foo.bar; import androidx.room.*; public class ${MY_POJO.simpleName()} { private String foo; private String bar; public void setFoo(String foo) { this.foo = foo; } public void setBar(String bar) { this.bar = bar; } } """ ) ) ) { invocation -> PojoProcessor.createFor( context = invocation.context, element = invocation.processingEnv.requireTypeElement(MY_POJO), bindingScope = FieldProcessor.BindingScope.BIND_TO_STMT, parent = null ).process() invocation.assertCompilationResult { hasErrorContaining("Cannot find getter for field.") } } } @Test fun noGetter_scopeTwoWay() { runProcessorTest( listOf( Source.java( MY_POJO.toString(), """ package foo.bar; import androidx.room.*; public class ${MY_POJO.simpleName()} { private String foo; private String bar; public void setFoo(String foo) { this.foo = foo; } public void setBar(String bar) { this.bar = bar; } } """ ) ) ) { invocation -> PojoProcessor.createFor( context = invocation.context, element = invocation.processingEnv.requireTypeElement(MY_POJO), bindingScope = FieldProcessor.BindingScope.TWO_WAY, parent = null ).process() invocation.assertCompilationResult { hasErrorContaining("Cannot find getter for field.") } } } @Test fun noGetter_scopeReadCursor() { runProcessorTest( listOf( Source.java( MY_POJO.toString(), """ package foo.bar; import androidx.room.*; public class ${MY_POJO.simpleName()} { private String foo; private String bar; public void setFoo(String foo) { this.foo = foo; } public void setBar(String bar) { this.bar = bar; } } """ ) ) ) { invocation -> PojoProcessor.createFor( context = invocation.context, element = invocation.processingEnv.requireTypeElement(MY_POJO), bindingScope = FieldProcessor.BindingScope.READ_FROM_CURSOR, parent = null ).process() } } @Test fun setterStartsWithIs() { runProcessorTest( listOf( Source.kotlin( "Book.kt", """ package foo.bar; data class Book( var isbn: String ) { var isbn2: String? = null } """ ) ) ) { invocation -> val result = PojoProcessor.createFor( context = invocation.context, element = invocation.processingEnv.requireTypeElement("foo.bar.Book"), bindingScope = FieldProcessor.BindingScope.READ_FROM_CURSOR, parent = null ).process() val fields = result.fields.associateBy { it.name } val stringType = invocation.context.COMMON_TYPES.STRING Truth.assertThat( fields["isbn"]?.getter ).isEqualTo( FieldGetter( fieldName = "isbn", jvmName = "getIsbn", type = stringType, callType = CallType.SYNTHETIC_METHOD, isMutableField = true ) ) Truth.assertThat( fields["isbn"]?.setter ).isEqualTo( FieldSetter( fieldName = "isbn", jvmName = "isbn", type = stringType, callType = CallType.CONSTRUCTOR ) ) Truth.assertThat( fields["isbn2"]?.getter ).isEqualTo( FieldGetter( fieldName = "isbn2", jvmName = "getIsbn2", type = stringType.makeNullable(), callType = CallType.SYNTHETIC_METHOD, isMutableField = true ) ) Truth.assertThat( fields["isbn2"]?.setter ).isEqualTo( FieldSetter( fieldName = "isbn2", jvmName = "setIsbn2", type = stringType.makeNullable(), callType = CallType.SYNTHETIC_METHOD ) ) } } @Test fun embedded_nullability() { listOf( TestData.SomeEmbeddedVals::class.java.canonicalName!! ).forEach { runProcessorTest { invocation -> val result = PojoProcessor.createFor( context = invocation.context, element = invocation.processingEnv.requireTypeElement(it), bindingScope = FieldProcessor.BindingScope.READ_FROM_CURSOR, parent = null ).process() val embeddedFields = result.embeddedFields assertThat(embeddedFields.size, `is`(2)) assertThat(embeddedFields[0].nonNull, `is`(true)) assertThat(embeddedFields[1].nonNull, `is`(false)) } } } private fun singleRun( code: String, vararg sources: Source, classpath: List<File> = emptyList(), handler: (Pojo, XTestInvocation) -> Unit ) { val pojoCode = """ $HEADER $code $FOOTER """ @Suppress("CHANGING_ARGUMENTS_EXECUTION_ORDER_FOR_NAMED_VARARGS") singleRunFullClass( code = pojoCode, sources = sources, classpath = classpath, handler = handler ) } private fun singleRunFullClass( code: String, vararg sources: Source, classpath: List<File> = emptyList(), handler: (Pojo, XTestInvocation) -> Unit ) { val pojoSource = Source.java(MY_POJO.toString(), code) val all = sources.toList() + pojoSource runProcessorTest( sources = all, classpath = classpath ) { invocation -> handler.invoke( PojoProcessor.createFor( context = invocation.context, element = invocation.processingEnv.requireTypeElement(MY_POJO), bindingScope = FieldProcessor.BindingScope.TWO_WAY, parent = null ).process(), invocation ) } } // Kotlin data classes to verify the PojoProcessor. private class TestData { data class AllDefaultVals( val name: String = "", val number: Int = 0, val bit: Boolean = false ) data class AllDefaultVars( var name: String = "", var number: Int = 0, var bit: Boolean = false ) data class SomeDefaultVals( val name: String, val number: Int = 0, val bit: Boolean ) data class SomeDefaultVars( var name: String, var number: Int = 0, var bit: Boolean ) data class WithJvmOverloads @JvmOverloads constructor( val name: String, val lastName: String = "", var number: Int = 0, var bit: Boolean ) data class AllNullableVals( val name: String?, val number: Int?, val bit: Boolean? ) data class SomeEmbeddedVals( val id: String, @Embedded(prefix = "non_nullable_") val nonNullableVal: AllNullableVals, @Embedded(prefix = "nullable_") val nullableVal: AllNullableVals? ) } }
apache-2.0
cthi/KotChat
KotChat-Android/app/src/main/java/com/geomorphology/kotchat/ui/ChannelsActivity.kt
1
4614
package com.geomorphology.kotchat.ui import android.content.res.Configuration import android.graphics.PorterDuff import android.os.Bundle import android.support.design.widget.NavigationView import android.support.v4.widget.DrawerLayout import android.support.v7.app.ActionBarDrawerToggle import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.RecyclerView import android.support.v7.widget.Toolbar import android.util.Log import android.view.Menu import android.widget.EditText import android.widget.ImageButton import com.geomorphology.kotchat.R import com.geomorphology.kotchat.adapter.MessageAdapter import com.geomorphology.kotchat.model.Message import com.geomorphology.kotchat.model.Room import com.geomorphology.kotchat.transport.MessageListObservable import org.json.JSONObject import java.util.ArrayList import kotlin.properties.Delegates public class ChannelsActivity : BaseServiceActivity() { private var mToolbar: Toolbar by Delegates.notNull() private var mNavView: NavigationView by Delegates.notNull() private var mDrawerLayout: DrawerLayout by Delegates.notNull() private var mDrawerToggle: ActionBarDrawerToggle by Delegates.notNull() private var mRecyclerView: RecyclerView by Delegates.notNull() private var mSendText: EditText by Delegates.notNull() private val mMessages = ArrayList<Message>() override fun onCreate(savedInstanceState: Bundle?) { super<BaseServiceActivity>.onCreate(savedInstanceState) setContentView(R.layout.activity_channel) bindViews() setupToolbar() setupRecyclerView() setupNavView() subscribeForMessages() registerSendClick() } private fun bindViews() { mToolbar = findViewById(R.id.toolbar) as Toolbar mNavView = findViewById(R.id.drawer_list) as NavigationView mDrawerLayout = findViewById(R.id.drawer_layout) as DrawerLayout mRecyclerView = findViewById(R.id.channel_rv) as RecyclerView mSendText = findViewById(R.id.item_message_sent) as EditText } private fun setupToolbar() { setSupportActionBar(mToolbar) getSupportActionBar().setDisplayHomeAsUpEnabled(true) } private fun setupRecyclerView() { mRecyclerView.setLayoutManager(LinearLayoutManager(this)) mRecyclerView.setAdapter(MessageAdapter(this, mMessages)) val con = findViewById(R.id.enter_text_container) con?.getBackground()?.setColorFilter(getResources().getColor(R.color.reply_grey), PorterDuff.Mode.MULTIPLY) } private fun setupNavView() { mDrawerToggle = ActionBarDrawerToggle(this, mDrawerLayout, mToolbar, R.string.app_name, R.string.app_name) mDrawerToggle.setDrawerIndicatorEnabled(true) mDrawerLayout.setDrawerListener(mDrawerToggle) val roomsAsJsonList = JSONObject(getIntent().getStringExtra("rooms")).getJSONArray("rooms") val rooms = Array(roomsAsJsonList.length(), {i -> Room(roomsAsJsonList.getJSONObject(i).getString("room"), roomsAsJsonList.getJSONObject(i).getInt("id")) }) val menu = mNavView.getMenu() for (i in rooms.indices) { menu.add(Menu.NONE, i, Menu.NONE, rooms[i].room) } mNavView.setNavigationItemSelectedListener { menuItem -> mService.joinRoom(rooms.get(menuItem.getItemId()).roomId) mDrawerLayout.closeDrawers() true } } override fun onPostCreate(savedInstanceState: Bundle?) { super<BaseServiceActivity>.onPostCreate(savedInstanceState) mDrawerToggle.syncState() } override fun onConfigurationChanged(newConfig: Configuration?) { super<BaseServiceActivity>.onConfigurationChanged(newConfig) mDrawerToggle.onConfigurationChanged(newConfig) } private fun subscribeForMessages() { MessageListObservable.getObservable().subscribe { message -> runOnUiThread { mMessages.add(message) mRecyclerView.getAdapter().notifyItemInserted(mMessages.count()) mRecyclerView.scrollToPosition(mMessages.count() - 1) } } } private fun registerSendClick() { val sendButton = findViewById(R.id.item_message_send_btn) as ImageButton sendButton.setOnClickListener { val content = mSendText.getText().toString() if (!content.isEmpty()) { mService.sendMessage(mSendText.getText().toString()) mSendText.setText("") } } } }
mit
GunoH/intellij-community
plugins/kotlin/idea/tests/testData/codeInsight/overrideImplement/typeAliasNotExpanded.kt
10
119
// FIR_IDENTICAL typealias Foo = Int interface Bar { fun test(foo: Foo) = Unit } class Bar2 : Bar { <caret> }
apache-2.0
GunoH/intellij-community
plugins/kotlin/base/project-structure/src/org/jetbrains/kotlin/idea/UserDataModuleInfoUtils.kt
4
1047
// 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. @file:JvmName("UserDataModuleInfoKt") package org.jetbrains.kotlin.idea import com.intellij.openapi.projectRoots.Sdk import com.intellij.openapi.roots.libraries.Library import com.intellij.openapi.util.Key import org.jetbrains.jps.model.module.JpsModuleSourceRootType // WARNING, this API is used by AS3.3+ @JvmField @Deprecated("Use 'customSourceRootType' instead.") val MODULE_ROOT_TYPE_KEY = getOrCreateKey<JpsModuleSourceRootType<*>>("Kt_SourceRootType") @JvmField @Deprecated("Use 'customSdk' instead.") val SDK_KEY = getOrCreateKey<Sdk>("Kt_Sdk") @JvmField @Deprecated("Use 'customLibrary' instead.") val LIBRARY_KEY = getOrCreateKey<Library>("Kt_Library") private inline fun <reified T> getOrCreateKey(name: String): Key<T> { @Suppress("DEPRECATION", "UNCHECKED_CAST") val existingKey = Key.findKeyByName(name) as Key<T>? return existingKey ?: Key.create(name) }
apache-2.0
980f/droid
android/src/main/kotlin/pers/hal42/android/Logger.kt
1
682
package pers.hal42.android import android.util.Log /** * Copyright (C) by andyh created on 1/9/13 at 10:57 AM * convenience wrapper on android Log usage, not having to type a tag at each place of use. * Also serves as a nice place to set breakpoints to trap otherwise discarded exception messages. */ class Logger(val logTag: String?) { fun i(format: String, vararg args: Any) { Log.i(logTag?:"?", String.format(format, *args)) } fun d(format: String, vararg args: Any) { Log.d(logTag?:"?", String.format(format, *args)) } fun e(format: String, vararg args: Any) { Log.e(logTag?:"?", String.format(format, *args)) } } val Dbg=Logger("Application")
mit
jwren/intellij-community
plugins/kotlin/idea/tests/testData/quickfix/autoImports/nestedClass.before.Main.kt
7
98
// "Import" "true" // ERROR: Unresolved reference: Nested val a = <caret>Nested /* IGNORE_FIR */
apache-2.0
JetBrains/kotlin-native
backend.native/tests/compilerChecks/t27.kt
3
170
import kotlinx.cinterop.* import platform.darwin.* import platform.Foundation.* class Zzz : NSAssertionHandler() { @ObjCAction fun foo(x: String) = println(x) }
apache-2.0
GunoH/intellij-community
plugins/kotlin/code-insight/line-markers/testData/suspend/simple.kt
2
116
suspend fun test() { <lineMarker text="Suspend function call 'foo()'">foo</lineMarker>() } suspend fun foo() {}
apache-2.0
GunoH/intellij-community
plugins/kotlin/jvm-debugger/test/testData/evaluation/singleBreakpoint/capturedVariablesInSamLambda.kt
3
672
package capturedVariablesInSamLambda fun invoke(runnable: Runnable) { runnable.run() } class A { val a = 1 } class B { val b = 1 } fun main() { val a = A() val b = B() invoke { // EXPRESSION: a // RESULT: instance of capturedVariablesInSamLambda.A(id=ID): LcapturedVariablesInSamLambda/A; // EXPRESSION: b // RESULT: instance of capturedVariablesInSamLambda.B(id=ID): LcapturedVariablesInSamLambda/B; // EXPRESSION: a.a // RESULT: 1: I // EXPRESSION: b.b // RESULT: 1: I //Breakpoint! println(a) println(b) } } // PRINT_FRAME // SHOW_KOTLIN_VARIABLES
apache-2.0
smmribeiro/intellij-community
plugins/kotlin/idea/tests/testData/intentions/convertToConcatenatedString/interpolateConstants.kt
9
172
// AFTER-WARNING: Parameter 'args' is never used // AFTER-WARNING: Variable 'x' is never used fun main(args: Array<String>){ val x = "<caret>abc${1}${2}${'a'}${3.2}" }
apache-2.0
smmribeiro/intellij-community
plugins/kotlin/idea/tests/testData/quickfix/addJvmNameAnnotation/hasAnnotation2.kt
4
337
// "Change JVM name" "true" // WITH_STDLIB class Foo { @JvmName fun <caret>bar(foo: List<String>): String { return "1" } fun bar(foo: List<Int>): String { return "2" } fun bar1(foo: List<Int>): String { return "3" } fun bar2(foo: List<Int>): String { return "4" } }
apache-2.0
smmribeiro/intellij-community
plugins/kotlin/idea/tests/testData/quickfix/createFromUsage/createFunction/call/smartCastWithIs.kt
13
91
// "Create function 'foo'" "true" fun test(o: Any) { if (o is String) <caret>foo(o) }
apache-2.0
smmribeiro/intellij-community
plugins/gradle/java/src/service/project/MavenRepositoriesProjectResolver.kt
13
2377
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.gradle.service.project import com.intellij.externalSystem.MavenRepositoryData import com.intellij.openapi.externalSystem.model.DataNode import com.intellij.openapi.externalSystem.model.ProjectKeys import com.intellij.openapi.externalSystem.model.project.ModuleData import com.intellij.openapi.externalSystem.model.project.ProjectData import com.intellij.openapi.externalSystem.util.ExternalSystemApiUtil import org.gradle.tooling.model.idea.IdeaModule import org.gradle.tooling.model.idea.IdeaProject import org.jetbrains.plugins.gradle.model.RepositoriesModel import org.jetbrains.plugins.gradle.util.GradleConstants import java.util.* class MavenRepositoriesProjectResolver: AbstractProjectResolverExtension() { override fun populateProjectExtraModels(gradleProject: IdeaProject, ideProject: DataNode<ProjectData>) { val repositories = resolverCtx.getExtraProject(RepositoriesModel::class.java) addRepositoriesToProject(ideProject, repositories) super.populateProjectExtraModels(gradleProject, ideProject) } override fun populateModuleExtraModels(gradleModule: IdeaModule, ideModule: DataNode<ModuleData>) { val repositories = resolverCtx.getExtraProject(gradleModule, RepositoriesModel::class.java) val ideProject = ExternalSystemApiUtil.findParent(ideModule, ProjectKeys.PROJECT) ideProject?.let { addRepositoriesToProject(it, repositories) } super.populateModuleExtraModels(gradleModule, ideModule) } override fun getExtraProjectModelClasses(): MutableSet<Class<*>> { return Collections.singleton(RepositoriesModel::class.java) } private fun addRepositoriesToProject(ideProject: DataNode<ProjectData>, repositories: RepositoriesModel?) { if (repositories != null) { val knownRepositories = ExternalSystemApiUtil.getChildren(ideProject, MavenRepositoryData.KEY) .asSequence() .map { it.data } .toSet() repositories.all.asSequence() .map { MavenRepositoryData(GradleConstants.SYSTEM_ID, it.name, it.url) } .filter { !knownRepositories.contains(it) } .forEach { ideProject.addChild(DataNode(MavenRepositoryData.KEY, it, ideProject)) } } } }
apache-2.0
smmribeiro/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/AddFunctionParametersFix.kt
2
12816
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.quickfix import com.intellij.codeInsight.intention.IntentionAction import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.psi.PsiElement import com.intellij.psi.PsiNamedElement import com.intellij.psi.search.GlobalSearchScope import com.intellij.psi.search.PsiSearchHelper import com.intellij.psi.search.searches.ReferencesSearch import org.jetbrains.kotlin.builtins.isKFunctionType import org.jetbrains.kotlin.builtins.isKSuspendFunctionType import org.jetbrains.kotlin.descriptors.ConstructorDescriptor import org.jetbrains.kotlin.descriptors.FunctionDescriptor import org.jetbrains.kotlin.diagnostics.Diagnostic import org.jetbrains.kotlin.diagnostics.DiagnosticFactory import org.jetbrains.kotlin.diagnostics.Errors import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.core.CollectingNameValidator import org.jetbrains.kotlin.idea.intentions.reflectToRegularFunctionType import org.jetbrains.kotlin.idea.refactoring.changeSignature.* import org.jetbrains.kotlin.idea.util.application.runReadAction import org.jetbrains.kotlin.idea.util.getDataFlowAwareTypes import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.getParentOfType import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.calls.callUtil.getCall import org.jetbrains.kotlin.resolve.calls.callUtil.getResolvedCall import org.jetbrains.kotlin.resolve.descriptorUtil.builtIns import org.jetbrains.kotlin.types.KotlinType import org.jetbrains.kotlin.types.checker.KotlinTypeChecker class AddFunctionParametersFix( callElement: KtCallElement, functionDescriptor: FunctionDescriptor, private val kind: Kind ) : ChangeFunctionSignatureFix(callElement, functionDescriptor) { sealed class Kind { object ChangeSignature : Kind() object AddParameterGeneric : Kind() class AddParameter(val argumentIndex: Int) : Kind() } private val argumentIndex: Int? get() = (kind as? Kind.AddParameter)?.argumentIndex private val callElement: KtCallElement? get() = element as? KtCallElement private val typesToShorten = ArrayList<KotlinType>() override fun getText(): String { val callElement = callElement ?: return "" val parameters = functionDescriptor.valueParameters val arguments = callElement.valueArguments val newParametersCnt = arguments.size - parameters.size assert(newParametersCnt > 0) val declarationName = when { isConstructor() -> functionDescriptor.containingDeclaration.name.asString() else -> functionDescriptor.name.asString() } return when (kind) { is Kind.ChangeSignature -> { if (isConstructor()) { KotlinBundle.message("fix.add.function.parameters.change.signature.constructor", declarationName) } else { KotlinBundle.message("fix.add.function.parameters.change.signature.function", declarationName) } } is Kind.AddParameterGeneric -> { if (isConstructor()) { KotlinBundle.message("fix.add.function.parameters.add.parameter.generic.constructor", newParametersCnt, declarationName) } else { KotlinBundle.message("fix.add.function.parameters.add.parameter.generic.function", newParametersCnt, declarationName) } } is Kind.AddParameter -> { if (isConstructor()) { KotlinBundle.message( "fix.add.function.parameters.add.parameter.constructor", kind.argumentIndex + 1, newParametersCnt, declarationName ) } else { KotlinBundle.message( "fix.add.function.parameters.add.parameter.function", kind.argumentIndex + 1, newParametersCnt, declarationName ) } } } } override fun isAvailable(project: Project, editor: Editor?, file: KtFile): Boolean { if (!super.isAvailable(project, editor, file)) return false val callElement = callElement ?: return false // newParametersCnt <= 0: psi for this quickfix is no longer valid val newParametersCnt = callElement.valueArguments.size - functionDescriptor.valueParameters.size if (argumentIndex != null && newParametersCnt != 1) return false return newParametersCnt > 0 } override fun invoke(project: Project, editor: Editor?, file: KtFile) { val callElement = callElement ?: return runChangeSignature(project, editor, functionDescriptor, addParameterConfiguration(), callElement, text) } private fun addParameterConfiguration(): KotlinChangeSignatureConfiguration { return object : KotlinChangeSignatureConfiguration { override fun configure(originalDescriptor: KotlinMethodDescriptor): KotlinMethodDescriptor { val argumentIndex = [email protected] return originalDescriptor.modify(fun(descriptor: KotlinMutableMethodDescriptor) { val callElement = callElement ?: return val arguments = callElement.valueArguments val parameters = functionDescriptor.valueParameters val validator = CollectingNameValidator() val receiverCount = if (descriptor.receiver != null) 1 else 0 if (argumentIndex != null) { parameters.forEach { validator.addName(it.name.asString()) } val argument = arguments[argumentIndex] val parameterInfo = getNewParameterInfo( originalDescriptor.baseDescriptor as FunctionDescriptor, argument, validator, ) descriptor.addParameter(argumentIndex + receiverCount, parameterInfo) return } val call = callElement.getCall(callElement.analyze()) ?: return for (i in arguments.indices) { val argument = arguments[i] val expression = argument.getArgumentExpression() if (i < parameters.size) { validator.addName(parameters[i].name.asString()) val argumentType = expression?.let { val bindingContext = it.analyze() val smartCasts = bindingContext[BindingContext.SMARTCAST, it] smartCasts?.defaultType ?: smartCasts?.type(call) ?: bindingContext.getType(it) } val parameterType = parameters[i].type if (argumentType != null && !KotlinTypeChecker.DEFAULT.isSubtypeOf(argumentType, parameterType)) { descriptor.parameters[i + receiverCount].currentTypeInfo = KotlinTypeInfo(false, argumentType) typesToShorten.add(argumentType) } } else { val parameterInfo = getNewParameterInfo( originalDescriptor.baseDescriptor as FunctionDescriptor, argument, validator, ) descriptor.addParameter(parameterInfo) } } }) } override fun performSilently(affectedFunctions: Collection<PsiElement>): Boolean { val onlyFunction = affectedFunctions.singleOrNull() ?: return false return kind != Kind.ChangeSignature && !isConstructor() && !hasOtherUsages(onlyFunction) } } } private fun getNewParameterInfo( functionDescriptor: FunctionDescriptor, argument: ValueArgument, validator: (String) -> Boolean ): KotlinParameterInfo { val name = getNewArgumentName(argument, validator) val expression = argument.getArgumentExpression() val type = (expression?.let { getDataFlowAwareTypes(it).firstOrNull() } ?: functionDescriptor.builtIns.nullableAnyType).let { if (it.isKFunctionType || it.isKSuspendFunctionType) it.reflectToRegularFunctionType() else it } return KotlinParameterInfo(functionDescriptor, -1, name, KotlinTypeInfo(false, null)).apply { currentTypeInfo = KotlinTypeInfo(false, type) originalTypeInfo.type?.let { typesToShorten.add(it) } if (expression != null) defaultValueForCall = expression } } private fun hasOtherUsages(function: PsiElement): Boolean { (function as? PsiNamedElement)?.let { val name = it.name ?: return false val project = runReadAction { it.project } val psiSearchHelper = PsiSearchHelper.getInstance(project) val globalSearchScope = GlobalSearchScope.projectScope(project) val cheapEnoughToSearch = psiSearchHelper.isCheapEnoughToSearch(name, globalSearchScope, null, null) if (cheapEnoughToSearch == PsiSearchHelper.SearchCostResult.TOO_MANY_OCCURRENCES) return false } return ReferencesSearch.search(function).any { val call = it.element.getParentOfType<KtCallElement>(false) call != null && callElement != call } } private fun isConstructor() = functionDescriptor is ConstructorDescriptor companion object TypeMismatchFactory : KotlinSingleIntentionActionFactoryWithDelegate<KtCallElement, Pair<FunctionDescriptor, Int>>() { override fun getElementOfInterest(diagnostic: Diagnostic): KtCallElement? { val (_, valueArgumentList) = diagnostic.valueArgument() ?: return null return valueArgumentList.getStrictParentOfType() } override fun extractFixData(element: KtCallElement, diagnostic: Diagnostic): Pair<FunctionDescriptor, Int>? { val (valueArgument, valueArgumentList) = diagnostic.valueArgument() ?: return null val arguments = valueArgumentList.arguments + element.lambdaArguments val argumentIndex = arguments.indexOfFirst { it == valueArgument } val context = element.analyze() val functionDescriptor = element.getResolvedCall(context)?.resultingDescriptor as? FunctionDescriptor ?: return null val parameters = functionDescriptor.valueParameters if (arguments.size - 1 != parameters.size) return null if ((arguments - valueArgument).zip(parameters).any { (argument, parameter) -> val argumentType = argument.getArgumentExpression()?.let { context.getType(it) } argumentType == null || !KotlinTypeChecker.DEFAULT.isSubtypeOf(argumentType, parameter.type) }) return null return functionDescriptor to argumentIndex } override fun createFix(originalElement: KtCallElement, data: Pair<FunctionDescriptor, Int>): IntentionAction? { val (functionDescriptor, argumentIndex) = data val parameters = functionDescriptor.valueParameters val arguments = originalElement.valueArguments return if (arguments.size > parameters.size) { AddFunctionParametersFix(originalElement, functionDescriptor, Kind.AddParameter(argumentIndex)) } else { null } } private fun Diagnostic.valueArgument(): Pair<KtValueArgument, KtValueArgumentList>? { val element = DiagnosticFactory.cast( this, Errors.TYPE_MISMATCH, Errors.CONSTANT_EXPECTED_TYPE_MISMATCH, Errors.NULL_FOR_NONNULL_TYPE, ).psiElement val valueArgument = element.getStrictParentOfType<KtValueArgument>() ?: return null val valueArgumentList = valueArgument.getStrictParentOfType<KtValueArgumentList>() ?: return null return valueArgument to valueArgumentList } } }
apache-2.0
smmribeiro/intellij-community
plugins/kotlin/idea/tests/testData/inspectionsLocal/conventionNameCalls/replaceCallWithBinaryOperator/equalsCompareTo.kt
14
52
// PROBLEM: none val x = 2.compareTo<caret>(2) == 0
apache-2.0
smmribeiro/intellij-community
plugins/kotlin/jvm-debugger/sequence/src/org/jetbrains/kotlin/idea/debugger/sequence/trace/dsl/KotlinIfBranch.kt
6
1100
// 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.sequence.trace.dsl import com.intellij.debugger.streams.trace.dsl.CodeBlock import com.intellij.debugger.streams.trace.dsl.Expression import com.intellij.debugger.streams.trace.dsl.StatementFactory import com.intellij.debugger.streams.trace.dsl.impl.common.IfBranchBase class KotlinIfBranch(condition: Expression, thenBlock: CodeBlock, statementFactory: StatementFactory) : IfBranchBase(condition, thenBlock, statementFactory) { override fun toCode(indent: Int): String { val elseBlockVar = elseBlock val ifThen = "if (${condition.toCode(0)}) {\n".withIndent(indent) + thenBlock.toCode(indent + 1) + "}".withIndent(indent) if (elseBlockVar != null) { return ifThen + " else { \n" + elseBlockVar.toCode(indent + 1) + "}".withIndent(indent) } return ifThen } }
apache-2.0
smmribeiro/intellij-community
plugins/kotlin/idea/tests/testData/intentions/replaceSizeCheckWithIsNotEmpty/listCountWithPredicate.kt
9
134
// IS_APPLICABLE: false // WITH_STDLIB fun test(list: List<String>) { val x = list.<caret>count { it.startsWith("prefix_") } > 0 }
apache-2.0
smmribeiro/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/ReplaceExplicitFunctionLiteralParamWithItIntention.kt
2
5995
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.intentions import com.intellij.codeInsight.intention.PsiElementBaseIntentionAction import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.psi.PsiDocumentManager import com.intellij.psi.PsiElement import com.intellij.psi.codeStyle.CodeStyleManager import com.intellij.refactoring.rename.RenameProcessor import com.intellij.usageView.UsageInfo import org.jetbrains.kotlin.descriptors.ParameterDescriptor import org.jetbrains.kotlin.descriptors.impl.AnonymousFunctionDescriptor import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.analysis.analyzeAsReplacement import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.core.copied import org.jetbrains.kotlin.idea.references.resolveMainReferenceToDescriptors import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.* import org.jetbrains.kotlin.resolve.DescriptorToSourceUtils import org.jetbrains.kotlin.resolve.calls.callUtil.getResolvedCall import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.utils.addToStdlib.safeAs class ReplaceExplicitFunctionLiteralParamWithItIntention : PsiElementBaseIntentionAction() { override fun getFamilyName() = KotlinBundle.message("replace.explicit.lambda.parameter.with.it") override fun isAvailable(project: Project, editor: Editor, element: PsiElement): Boolean { val functionLiteral = targetFunctionLiteral(element, editor.caretModel.offset) ?: return false val parameter = functionLiteral.valueParameters.singleOrNull() ?: return false if (parameter.typeReference != null) return false if (parameter.destructuringDeclaration != null) return false if (functionLiteral.anyDescendantOfType<KtFunctionLiteral> { literal -> literal.usesName(element.text) && (!literal.hasParameterSpecification() || literal.usesName("it")) }) return false val lambda = functionLiteral.parent as? KtLambdaExpression ?: return false val lambdaParent = lambda.parent if (lambdaParent is KtWhenEntry || lambdaParent is KtContainerNodeForControlStructureBody) return false val call = lambda.getStrictParentOfType<KtCallExpression>() if (call != null) { val argumentIndex = call.valueArguments.indexOfFirst { it.getArgumentExpression() == lambda } val callOrQualified = call.getQualifiedExpressionForSelectorOrThis() val newCallOrQualified = callOrQualified.copied() val newCall = newCallOrQualified.safeAs<KtQualifiedExpression>()?.callExpression ?: newCallOrQualified.safeAs() ?: return false val newArgument = newCall.valueArguments.getOrNull(argumentIndex) ?: newCall.lambdaArguments.singleOrNull() ?: return false newArgument.replace(KtPsiFactory(element).createLambdaExpression("", "TODO()")) val newContext = newCallOrQualified.analyzeAsReplacement(callOrQualified, callOrQualified.analyze(BodyResolveMode.PARTIAL)) if (newCallOrQualified.getResolvedCall(newContext)?.resultingDescriptor == null) return false } text = KotlinBundle.message("replace.explicit.parameter.0.with.it", parameter.name.toString()) return true } private fun KtFunctionLiteral.usesName(name: String): Boolean = anyDescendantOfType<KtSimpleNameExpression> { nameExpr -> nameExpr.getReferencedName() == name } override fun startInWriteAction(): Boolean = false override fun invoke(project: Project, editor: Editor, element: PsiElement) { val caretOffset = editor.caretModel.offset val functionLiteral = targetFunctionLiteral(element, editor.caretModel.offset) ?: return val cursorInParameterList = functionLiteral.valueParameterList?.textRange?.containsOffset(caretOffset) ?: return ParamRenamingProcessor(editor, functionLiteral, cursorInParameterList).run() } private fun targetFunctionLiteral(element: PsiElement, caretOffset: Int): KtFunctionLiteral? { val expression = element.getParentOfType<KtNameReferenceExpression>(true) if (expression != null) { val target = expression.resolveMainReferenceToDescriptors().singleOrNull() as? ParameterDescriptor ?: return null val functionDescriptor = target.containingDeclaration as? AnonymousFunctionDescriptor ?: return null return DescriptorToSourceUtils.descriptorToDeclaration(functionDescriptor) as? KtFunctionLiteral } val functionLiteral = element.getParentOfType<KtFunctionLiteral>(true) ?: return null val arrow = functionLiteral.arrow ?: return null if (caretOffset > arrow.endOffset) return null return functionLiteral } private class ParamRenamingProcessor( val editor: Editor, val functionLiteral: KtFunctionLiteral, val cursorWasInParameterList: Boolean ) : RenameProcessor( editor.project!!, functionLiteral.valueParameters.single(), "it", false, false ) { override fun performRefactoring(usages: Array<out UsageInfo>) { super.performRefactoring(usages) functionLiteral.deleteChildRange(functionLiteral.valueParameterList, functionLiteral.arrow ?: return) if (cursorWasInParameterList) { editor.caretModel.moveToOffset(functionLiteral.bodyExpression?.textOffset ?: return) } val project = functionLiteral.project PsiDocumentManager.getInstance(project).doPostponedOperationsAndUnblockDocument(editor.document) CodeStyleManager.getInstance(project).adjustLineIndent(functionLiteral.containingFile, functionLiteral.textRange) } } }
apache-2.0
smmribeiro/intellij-community
plugins/kotlin/idea/tests/testData/formatter/FunctionReferenceOperator.kt
13
65
class Foo { fun bar() {} } fun baz() { Foo :: bar }
apache-2.0
zielu/GitToolBox
src/main/kotlin/zielu/gittoolbox/ui/config/v1/PrjV1ConfigurableProvider.kt
1
594
package zielu.gittoolbox.ui.config.v1 import com.intellij.openapi.options.Configurable import com.intellij.openapi.options.ConfigurableProvider import com.intellij.openapi.project.Project import zielu.gittoolbox.GitToolBoxRegistry import zielu.gittoolbox.ui.config.prj.GtProjectConfigurable internal class PrjV1ConfigurableProvider(private val project: Project) : ConfigurableProvider() { override fun createConfigurable(): Configurable { return GtProjectConfigurable(project) } override fun canCreateConfigurable(): Boolean { return GitToolBoxRegistry.useLegacyConfig() } }
apache-2.0
paul58914080/ff4j-spring-boot-starter-parent
ff4j-spring-boot-autoconfigure/src/main/kotlin/org/ff4j/spring/boot/autoconfigure/FF4JConfiguration.kt
1
1404
/*- * #%L * ff4j-spring-boot-autoconfigure * %% * Copyright (C) 2013 - 2019 FF4J * %% * 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. * #L% */ package org.ff4j.spring.boot.autoconfigure import org.ff4j.FF4j import org.springframework.boot.autoconfigure.condition.ConditionalOnClass import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean import org.springframework.context.annotation.Bean import org.springframework.context.annotation.ComponentScan import org.springframework.context.annotation.Configuration /** * Created by Paul * * @author [Paul Williams](mailto:[email protected]) */ @Configuration @ConditionalOnClass(FF4j::class) @ComponentScan(value = ["org.ff4j.spring.boot.web.api", "org.ff4j.services", "org.ff4j.aop", "org.ff4j.spring"]) class FF4JConfiguration { @Bean @ConditionalOnMissingBean fun getFF4J(): FF4j = FF4j() }
apache-2.0
GluigiPP/KotlinChat
src/test/kotlin/com/gluigip/kotlin/KotlinChat/KotlinChatApplicationTests.kt
1
331
package com.gluigip.kotlin.KotlinChat import org.junit.Test import org.junit.runner.RunWith import org.springframework.boot.test.context.SpringBootTest import org.springframework.test.context.junit4.SpringRunner @RunWith(SpringRunner::class) @SpringBootTest class KotlinChatApplicationTests { @Test fun contextLoads() { } }
apache-2.0
NlRVANA/Unity
app/src/test/java/com/zwq65/unity/kotlin/Coroutine/6Channels.kt
1
13028
package com.zwq65.unity.kotlin.Coroutine import kotlinx.coroutines.* import kotlinx.coroutines.channels.* import org.junit.Test /** * ================================================ * 通道 * * 递延值提供了在协程之间传递单个值的便捷方法. * 通道提供了一种传输值流的方法. * <p> * Created by NIRVANA on 2020/1/8. * Contact with <[email protected]> * ================================================ */ @ObsoleteCoroutinesApi @ExperimentalCoroutinesApi class `6Channels` { /** * 通道 * * 延期的值提供了一种便捷的方法使单个值在多个协程之间进行相互传输. 通道提供了一种在流中传输值的方法. * * 通道基础:一个[Channel]是一个和 BlockingQueue 非常相似的概念. * 其中一个不同是它代替了阻塞的 put 操作并提供了挂起的[Channel.send],还替代了阻塞的 take 操作并提供了挂起的[Channel.receive]. */ @Test fun test1() = runBlocking<Unit>() { val channel = Channel<Int>() launch { // 这里可能是消耗大量 CPU 运算的异步逻辑,我们将仅仅做 5 次整数的平方并发送 for (x in 1..5) channel.send(x * x) } // 这里我们打印了 5 次被接收的整数: repeat(5) { println(channel.receive()) } println("Done!") } /** * 关闭与迭代通道 * * 和队列不同,一个通道可以通过被关闭来表明没有更多的元素将会进入通道. * 在接收者中可以定期的使用 for 循环来从通道中接收元素. * 从概念上来说,一个 [Channel.close] 操作就像向通道发送了一个特殊的关闭指令. * 这个迭代停止就说明关闭指令已经被接收了.所以这里保证所有先前发送出去的元素都在通道关闭前被接收到. */ @Test fun test2() = runBlocking<Unit>() { val channel = Channel<Int>() launch { for (x in 1..5) channel.send(x * x) channel.close() // 我们结束发送 } // 这里我们使用 `for` 循环来打印所有被接收到的元素(直到通道被关闭) for (y in channel) println(y) println("Done!") } /** * 构建通道生产者 * * 协程生成一系列元素的模式很常见. 这是 生产者——消费者 模式的一部分,并且经常能在并发的代码中看到它. * 你可以将生产者抽象成一个函数,并且使通道作为它的参数,但这与必须从函数中返回结果的常识相违悖. * 这里有一个名为[produce]的便捷的协程构建器,可以很容易的在生产者端正确工作, 并且我们使用扩展函数[consumeEach]在消费者端替代for循环 */ @Test fun test3() = runBlocking { val squares = produceSquares() squares.consumeEach { println(it) } println("Done!") } private fun CoroutineScope.produceSquares(): ReceiveChannel<Int> = produce { for (x in 1..5) send(x * x) } /** * 管道 * * 管道是一种一个协程在流中开始生产可能无穷多个元素的模式 * 并且另一个或多个协程开始消费这些流,做一些操作,并生产了一些额外的结果. 在下面的例子中,对这些数字仅仅做了平方操作 * 所有创建了协程的函数被定义在了[CoroutineScope]的扩展上, 所以我们可以依靠结构化并发来确保没有常驻在我们的应用程序中的全局协程. */ @Test fun test4() = runBlocking { //启动并连接了整个管道 // 从 1 开始生产整数 val numbers = produceNumbers() // 对整数做平方 val squares = square(numbers) // 打印前 5 个数字 for (i in 1..5) println(squares.receive()) // 我们的操作已经结束了 println("Done!") // 取消子协程 coroutineContext.cancelChildren() } private fun CoroutineScope.produceNumbers() = produce<Int> { var x = 1 while (true) send(x++) // 从 1 开始的无限的整数流 } private fun CoroutineScope.square(numbers: ReceiveChannel<Int>): ReceiveChannel<Int> = produce { for (x in numbers) send(x * x) } /** * 在协程中使用一个管道来生成素数.我们开启了一个数字的无限序列. * 下面的例子打印了前十个素数, 在主线程的上下文中运行整个管道. * 直到所有的协程在该主协[runBlocking]的作用域中被启动完成. * 我们不必使用一个显式的列表来保存所有被我们已经启动的协程.我们使用[cancelChildren]扩展函数在我们打印了前十个素数以后来取消所有的子协程. * */ @Test fun test5() = runBlocking { var cur = numbersFrom(2) /** * 现在我们开启了一个从 2 开始的数字流管道,从当前的通道中取一个素数, 并为每一个我们发现的素数启动一个流水线阶段: * numbersFrom(2) -> filter(2) -> filter(3) -> filter(5) -> filter(7) …… */ for (i in 1..10) { val prime = cur.receive() println("prime:$prime") cur = filter(cur, prime) } // 取消所有的子协程来让主协程结束 coroutineContext.cancelChildren() } /** * 在下面的管道阶段中过滤了来源于流中的数字,删除了所有可以被给定素数整除的数字. */ private fun CoroutineScope.numbersFrom(start: Int) = produce<Int> { var x = start // 从 start 开始过滤整数流 while (true) send(x++) } private fun CoroutineScope.filter(numbers: ReceiveChannel<Int>, prime: Int) = produce<Int> { for (x in numbers) if (x % prime != 0) send(x) } /** * 扇出 * * 多个协程也许会接收相同的管道,在它们之间进行分布式工作. * 注意,取消生产者协程会关闭它的通道,因此通过正在执行的生产者协程通道来终止迭代. * 还有,注意我们如何使用 for 循环显式迭代通道以在[launchProcessor]代码中执行扇出. * 与[consumeEach]不同,这个 for 循环是安全完美地使用多个协程的.如果其中一个生产者协程执行失败,其它的生产者协程仍然会继续处理通道; * 而通过[consumeEach]编写的生产者始终在正常或非正常完成时消耗(取消)底层通道. */ @Test fun test6() = runBlocking { val producer = produceNumbers2() repeat(5) { launchProcessor(it, producer) } delay(950) producer.cancel() // 取消协程生产者从而将它们全部杀死 } /** * start with a producer coroutine that is periodically producing integers (ten numbers per second) */ private fun CoroutineScope.produceNumbers2() = produce<Int> { var x = 1 // start from 1 while (true) { send(x++) // 产生下一个数字 delay(100) // 等待 0.1 秒 } } /** * Then we can have several processor coroutines. In this example, they just print their id and received number. */ private fun CoroutineScope.launchProcessor(id: Int, channel: ReceiveChannel<Int>) = launch { for (msg in channel) { println("Processor #$id received $msg") } } /** * 扇入 * * 多个协程可以发送到同一个通道. * 比如说,让我们创建一个字符串的通道,和一个在这个通道中以指定的延迟反复发送一个指定字符串的挂起函数: */ @Test fun test7() = runBlocking { val channel = Channel<String>() launch { sendString(channel, "foo", 200L) } launch { sendString(channel, "BAR!", 500L) } repeat(6) { // 接收前六个 println(channel.receive()) } // 取消所有子协程来让主协程结束 coroutineContext.cancelChildren() } private suspend fun sendString(channel: SendChannel<String>, s: String, time: Long) { while (true) { delay(time) channel.send(s) } } /** * 带缓冲的通道 * * 到目前为止展示的通道都是没有缓冲区的.无缓冲的通道在发送者和接收者相遇时传输元素. * 如果发送先被调用,则它将被挂起直到接收被调用, 如果接收先被调用,它将被挂起直到发送被调用. */ @Test fun test8() = runBlocking { /** * [Channel]工厂函数与[produce]建造器通过一个可选的参数capacity来指定 缓冲区大小 . * 缓冲允许发送者在被挂起前发送多个元素, 就像 BlockingQueue 有指定的容量一样,当缓冲区被占满的时候将会引起阻塞. */ val channel = Channel<Int>(4) // 启动带缓冲的通道 val sender = launch { // 启动发送者协程 repeat(10) { println("Sending $it") // 将在缓冲区被占满时挂起,前四个元素被加入到了缓冲区并且发送者在试图发送第五个元素的时候被挂起. channel.send(it) } } // 没有接收到东西……只是等待…… delay(1000) // 取消发送者协程 sender.cancel() } /** * 通道是公平的 * * 发送和接收操作是 公平的 并且尊重调用它们的多个协程. * 它们遵守先进先出原则,可以看到第一个协程调用 receive 并得到了元素. * 在下面的例子中两个协程“乒”和“乓”都从共享的“桌子”通道接收到这个“球”元素. */ @Test fun test9() = runBlocking { // 一个共享的 table(桌子) val table = Channel<Ball>() /** * “乒”协程首先被启动,所以它首先接收到了球. * 甚至虽然“乒” 协程在将球发送会桌子以后立即开始接收,但是球还是被“乓” 协程接收了,因为它一直在等待着接收球; * 注意,有时候通道执行时由于执行者的性质而看起来不那么公平.点击这个[https://github.com/Kotlin/kotlinx.coroutines/issues/111]来查看更多细节. */ launch { player("ping", table) } launch { player("pong", table) } // 发球 table.send(Ball(0)) delay(1000) // 延迟 1 秒钟 coroutineContext.cancelChildren() } suspend fun player(name: String, table: Channel<Ball>) { for (ball in table) { // 在循环中接收球 ball.hits++ println("$name $ball") delay(300) // 等待一段时间 table.send(ball) // 将球发送回去 } } data class Ball(var hits: Int) /** * 计时器通道 * * 计时器通道是一种特别的会合通道,每次经过特定的延迟都会从该通道进行消费并产生[Unit]. * 虽然它看起来似乎没用,它被用来构建分段来创建复杂的基于时间的[produce]管道和进行窗口化操作以及其它时间相关的处理. */ @Test fun test10() = runBlocking <Unit>{ //创建计时器通道 val tickerChannel = ticker(delayMillis = 1000, initialDelayMillis = 0) var nextElement = withTimeoutOrNull(1) { tickerChannel.receive() } // 初始尚未经过的延迟 println("Initial element is available immediately: $nextElement") // 所有随后到来的元素都经过了 100 毫秒的延迟 nextElement = withTimeoutOrNull(500) { tickerChannel.receive() } println("Next element is not ready in 500 ms: $nextElement") nextElement = withTimeoutOrNull(600) { tickerChannel.receive() } println("Next element is ready in 1000 ms: $nextElement") // 模拟大量消费延迟 println("Consumer pauses for 1500ms") delay(1500) /** * 请注意,[ticker]可能知道消费者的暂停,默认情况下,如果发生暂停,则调整下一个生成的元素的延迟时间,尝试保持固定的生成元素速率. * 给可选的 mode 参数传入[TickerMode.FIXED_DELAY]可以保持固定元素之间的延迟. */ // 下一个元素立即可用 nextElement = withTimeoutOrNull(1) { tickerChannel.receive() } println("Next element is available immediately after large consumer delay: $nextElement") // 请注意,`receive` 调用之间的暂停被考虑在内,下一个元素的到达速度更快 nextElement = withTimeoutOrNull(600) { tickerChannel.receive() } println("Next element is ready in 500ms after consumer pause in 150ms: $nextElement") // 表明不再需要更多的元素 tickerChannel.cancel() } }
apache-2.0
fkorotkov/k8s-kotlin-dsl
DSLs/kubernetes/dsl/src/main/kotlin-gen/com/fkorotkov/openshift/supplementalGroups.kt
1
549
// GENERATED package com.fkorotkov.openshift import io.fabric8.openshift.api.model.SecurityContextConstraints as model_SecurityContextConstraints import io.fabric8.openshift.api.model.SupplementalGroupsStrategyOptions as model_SupplementalGroupsStrategyOptions fun model_SecurityContextConstraints.`supplementalGroups`(block: model_SupplementalGroupsStrategyOptions.() -> Unit = {}) { if(this.`supplementalGroups` == null) { this.`supplementalGroups` = model_SupplementalGroupsStrategyOptions() } this.`supplementalGroups`.block() }
mit
hsz/idea-gitignore
src/test/kotlin/mobi/hsz/idea/gitignore/refactoring/RenameTest.kt
1
1476
// 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 mobi.hsz.idea.gitignore.refactoring import com.intellij.testFramework.fixtures.BasePlatformTestCase import mobi.hsz.idea.gitignore.file.type.IgnoreFileType import java.io.IOException class RenameTest : BasePlatformTestCase() { override fun isWriteActionRequired() = true @Throws(IOException::class) fun testRenameFile() { myFixture.apply { tempDirFixture.findOrCreateDir("dir").createChildData(this, "file.txt") } doTest("*/fil<caret>e.txt", "newFile.txt", "dir/newFile.txt") } @Throws(IOException::class) fun testRenameDirectory() { myFixture.apply { tempDirFixture.findOrCreateDir("dir").createChildData(this, "file.txt") } doTest("di<caret>r/file.txt", "newDir", "newDir/file.txt") } @Throws(IOException::class) fun testRenameInNegationEntry() { myFixture.apply { tempDirFixture.findOrCreateDir("dir").createChildData(this, "file.txt") } doTest("!di<caret>r/file.txt", "newDir", "!newDir/file.txt") } private fun doTest(beforeText: String, newName: String, afterText: String) { myFixture.apply { configureByText(IgnoreFileType.INSTANCE, beforeText) renameElementAtCaret(newName) checkResult(afterText) } } }
mit
TachiWeb/TachiWeb-Server
TachiServer/src/main/java/xyz/nulldev/ts/api/v3/models/catalogue/WCataloguePageRequest.kt
1
163
package xyz.nulldev.ts.api.v3.models.catalogue data class WCataloguePageRequest( val filters: String?, val page: Int, val query: String? )
apache-2.0
filipproch/reactor-android
library-extras/src/main/kotlin/cz/filipproch/reactor/extras/ui/views/activity/ToolbarReactorActivity.kt
1
274
package cz.filipproch.reactor.extras.ui.views.activity import cz.filipproch.reactor.base.translator.IReactorTranslator @Deprecated("Renamed to ExtendedReactorCompatActivity") abstract class ToolbarReactorActivity<T : IReactorTranslator> : ToolbarReactorCompatActivity<T>()
mit
dam5s/kspec
libraries/aspen/src/test/kotlin/aspen/examples/ControllerTestExampleUsingInit.kt
1
1662
package aspen.examples import io.damo.aspen.Test import org.assertj.core.api.Assertions.assertThat import org.mockito.Mockito.* /** * If you prefer having fields that get initialized in your #before, * you can follow this example. * Unfortunately you will need to describe your tests in the #init. */ class BusinessControllerTestExample : Test() { lateinit var mockRepo: BusinessRepository lateinit var controller: BusinessController init { before { mockRepo = mock(BusinessRepository::class.java) controller = BusinessController(mockRepo) } describe("#create") { test { val business = Business(name = "Wayne Enterprises") doReturn(business).`when`(mockRepo).create(anyString()) val response = controller.create("Wayne Ent.") assertThat(response).isEqualTo(BusinessResponse(business, true)) verify(mockRepo).create("Wayne Ent.") } test("repository creation error") { doReturn(null).`when`(mockRepo).create(anyString()) val response = controller.create("Wayne Ent.") assertThat(response).isEqualTo(BusinessResponse(null as Business?, false)) } } } } class BusinessController(val repository: BusinessRepository) { fun create(businessName: String) = BusinessResponse(repository.create(businessName), true) } interface BusinessRepository { fun create(businessName: String): Business? } data class BusinessResponse<T>(val value: T?, val success: Boolean) data class Business(val name: String)
mit
Archinamon/AndroidGradleSwagger
src/main/kotlin/com/archinamon/lang/kotlin/GroovyInteroperability.kt
1
2317
/* * Copyright 2016 the original author or 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 com.archinamon.lang.kotlin import groovy.lang.Closure import org.gradle.internal.Cast.uncheckedCast /** * Adapts a Kotlin function to a single argument Groovy [Closure]. * * @param T the expected type of the single argument to the closure. * @param action the function to be adapted. * * @see KotlinClosure */ fun <T : Any> Any.closureOf(action: T.() -> Unit): Closure<Any?> = KotlinClosure(action, this, this) /** * Adapts a Kotlin function to a Groovy [Closure] that operates on the * configured Closure delegate. * * @param T the expected type of the delegate argument to the closure. * @param function the function to be adapted. * * @see KotlinClosure */ fun <T> Any.delegateClosureOf(action: T.() -> Unit) = object : Closure<Unit>(this, this) { @Suppress("unused") // to be called dynamically by Groovy fun doCall() = uncheckedCast<T>(delegate).action() } /** * Adapts a Kotlin function to a single argument Groovy [Closure]. * * @param T the type of the single argument to the closure. * @param V the return type. * @param function the function to be adapted. * @param owner optional owner of the Closure. * @param thisObject optional _this Object_ of the Closure. * * @see Closure */ class KotlinClosure<in T : Any, V : Any>( private val function: T.() -> V?, owner: Any? = null, thisObject: Any? = null) : Closure<V?>(owner, thisObject) { @Suppress("unused") // to be called dynamically by Groovy fun doCall(it: T): V? = it.function() } operator fun <T> Closure<T>.invoke(): T = call() operator fun <T> Closure<T>.invoke(x: Any?): T = call(x) operator fun <T> Closure<T>.invoke(vararg xs: Any?): T = call(*xs)
apache-2.0
aosp-mirror/platform_frameworks_support
jetifier/jetifier/core/src/main/kotlin/com/android/tools/build/jetifier/core/proguard/ProGuardTypesMap.kt
1
3283
/* * Copyright 2018 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.tools.build.jetifier.core.proguard import com.android.tools.build.jetifier.core.utils.Log /** * Contains custom mappings to map support library types referenced in ProGuard to new ones. */ data class ProGuardTypesMap(private val rules: Map<ProGuardType, Set<ProGuardType>>) { companion object { const val TAG = "ProGuardTypesMap" val EMPTY = ProGuardTypesMap(emptyMap()) } private val expandedRules: Map<ProGuardType, Set<ProGuardType>> by lazy { val expandedMap = mutableMapOf<ProGuardType, Set<ProGuardType>>() rules.forEach { (from, to) -> if (from.needsExpansion() || to.any { it.needsExpansion() }) { ProGuardType.EXPANSION_TOKENS.forEach { t -> expandedMap.put(from.expandWith(t), to.map { it.expandWith(t) }.toSet()) } } else { expandedMap.put(from, to) } } expandedMap } constructor(vararg rules: Pair<ProGuardType, ProGuardType>) : this(rules.map { it.first to setOf(it.second) }.toMap()) /** Returns JSON data model of this class */ fun toJson(): JsonData { return JsonData(rules.map { it.key.value to it.value.map { it.value }.toList() }.toMap()) } fun mapType(type: ProGuardType): Set<ProGuardType>? { return expandedRules[type] } /** * JSON data model for [ProGuardTypesMap]. */ data class JsonData(val rules: Map<String, List<String>>) { /** Creates instance of [ProGuardTypesMap] */ fun toMappings(): ProGuardTypesMap { return ProGuardTypesMap(rules .map { ProGuardType(it.key) to it.value.map { ProGuardType(it) }.toSet() } .toMap()) } } /** * Creates reversed version of this map (values become keys). If there are multiple keys mapped * to the same value only the first value is used and warning message is printed. */ fun reverseMap(): ProGuardTypesMap { val reversed = mutableMapOf<ProGuardType, ProGuardType>() for ((from, to) in rules) { if (to.size > 1) { // Skip reversal of a set continue } val conflictFrom = reversed[to.single()] if (conflictFrom != null) { // Conflict - skip Log.w(TAG, "Conflict: %s -> (%s, %s)", to, from, conflictFrom) continue } reversed[to.single()] = from } return ProGuardTypesMap(reversed .map { it.key to setOf(it.value) } .toMap()) } }
apache-2.0
kerubistan/kerub
src/test/kotlin/com/github/kerubistan/kerub/planner/steps/storage/lvm/mirror/MirrorVolumeTest.kt
2
7680
package com.github.kerubistan.kerub.planner.steps.storage.lvm.mirror import com.github.kerubistan.kerub.hostUp import com.github.kerubistan.kerub.model.LvmStorageCapability import com.github.kerubistan.kerub.model.dynamic.CompositeStorageDeviceDynamic import com.github.kerubistan.kerub.model.dynamic.VirtualStorageDeviceDynamic import com.github.kerubistan.kerub.model.dynamic.VirtualStorageLvmAllocation import com.github.kerubistan.kerub.model.hardware.BlockDevice import com.github.kerubistan.kerub.planner.OperationalState import com.github.kerubistan.kerub.planner.steps.AbstractOperationalStep import com.github.kerubistan.kerub.planner.steps.OperationalStepVerifications import com.github.kerubistan.kerub.testDisk import com.github.kerubistan.kerub.testHost import com.github.kerubistan.kerub.testHostCapabilities import com.github.kerubistan.kerub.testLvmCapability import io.github.kerubistan.kroki.size.GB import io.github.kerubistan.kroki.size.TB import org.junit.Test import org.junit.jupiter.api.assertThrows import java.util.UUID import kotlin.test.assertTrue @ExperimentalUnsignedTypes class MirrorVolumeTest : OperationalStepVerifications() { override val step: AbstractOperationalStep get() { val lvmStorageCapability = LvmStorageCapability( physicalVolumes = mapOf( "/dev/sdb" to 1.TB, "/dev/sdc" to 1.TB ), volumeGroupName = "vg-1", size = 2.TB, id = UUID.randomUUID() ) val host = testHost.copy( capabilities = testHostCapabilities.copy( storageCapabilities = listOf(lvmStorageCapability) ) ) return MirrorVolume( host = host, mirrors = 1.toShort(), allocation = VirtualStorageLvmAllocation( capabilityId = lvmStorageCapability.id, path = "", mirrors = 0, vgName = lvmStorageCapability.volumeGroupName, actualSize = 1.GB, hostId = host.id ), capability = lvmStorageCapability, vStorage = testDisk ) } @Test fun take() { val lvmStorageCapability = LvmStorageCapability( size = 8.TB, volumeGroupName = "vg-1", physicalVolumes = mapOf( "/dev/sda" to 1.TB, "/dev/sdb" to 1.TB ) ) val host = testHost.copy( capabilities = testHostCapabilities.copy( blockDevices = listOf( BlockDevice("/dev/sda", 1.TB), BlockDevice("/dev/sdb", 1.TB) ), storageCapabilities = listOf( lvmStorageCapability ) ) ) val hostDynamic = hostUp(testHost).copy( storageStatus = listOf( CompositeStorageDeviceDynamic( id = lvmStorageCapability.id, reportedFreeCapacity = 1.TB ) ) ) val newState = MirrorVolume( host = host, vStorage = testDisk, capability = lvmStorageCapability, mirrors = 1.toShort(), allocation = VirtualStorageLvmAllocation( capabilityId = lvmStorageCapability.id, mirrors = 0, hostId = host.id, vgName = lvmStorageCapability.volumeGroupName, path = "", actualSize = 1.GB ) ).take( OperationalState.fromLists( hosts = listOf(testHost), hostDyns = listOf( hostDynamic ), vStorage = listOf(testDisk), vStorageDyns = listOf( VirtualStorageDeviceDynamic( id = testDisk.id, allocations = listOf( VirtualStorageLvmAllocation( capabilityId = lvmStorageCapability.id, actualSize = testDisk.size, path = "", vgName = lvmStorageCapability.volumeGroupName, hostId = host.id, mirrors = 0 ) ) ) ) ) ) assertTrue("number of mirrors set") { (newState.vStorage.getValue(testDisk.id).dynamic!!.allocations.single() as VirtualStorageLvmAllocation).mirrors == 1.toByte() } assertTrue("Storage size decreased by the mirrors") { newState.hosts.getValue(host.id).dynamic!!.storageStatus.single { it.id == lvmStorageCapability.id }.freeCapacity < 1.TB } } @Test fun validation() { assertThrows<IllegalStateException>("Not registered LVM volume") { MirrorVolume( host = testHost, vStorage = testDisk, capability = testLvmCapability, mirrors = 1.toShort(), allocation = VirtualStorageLvmAllocation( capabilityId = testLvmCapability.id, mirrors = 0, hostId = testHost.id, vgName = testLvmCapability.volumeGroupName, path = "", actualSize = 1.GB ) ) } assertThrows<IllegalStateException>("Too many mirrors") { val lvmStorageCapability = LvmStorageCapability( size = 8.TB, volumeGroupName = "vg-1", physicalVolumes = mapOf( "/dev/sda" to 1.TB, "/dev/sdb" to 1.TB, "/dev/sdc" to 1.TB, "/dev/sdd" to 1.TB, "/dev/sde" to 1.TB, "/dev/sdf" to 1.TB, "/dev/sdg" to 1.TB, "/dev/sdh" to 1.TB ) ) val host = testHost.copy( capabilities = testHostCapabilities.copy( blockDevices = listOf( BlockDevice("/dev/sda", 1.TB), BlockDevice("/dev/sdb", 1.TB), BlockDevice("/dev/sdc", 1.TB), BlockDevice("/dev/sdd", 1.TB), BlockDevice("/dev/sde", 1.TB), BlockDevice("/dev/sdf", 1.TB), BlockDevice("/dev/sdg", 1.TB), BlockDevice("/dev/sdh", 1.TB) ), storageCapabilities = listOf( lvmStorageCapability ) ) ) MirrorVolume( host = host, vStorage = testDisk, capability = lvmStorageCapability, mirrors = 6.toShort(), allocation = VirtualStorageLvmAllocation( capabilityId = lvmStorageCapability.id, mirrors = 0, hostId = host.id, vgName = lvmStorageCapability.volumeGroupName, path = "", actualSize = 1.GB ) ) } assertThrows<IllegalStateException>("not enough mirrors") { val lvmStorageCapability = LvmStorageCapability( size = 8.TB, volumeGroupName = "vg-1", physicalVolumes = mapOf( "/dev/sda" to 1.TB, "/dev/sdb" to 1.TB ) ) val host = testHost.copy( capabilities = testHostCapabilities.copy( blockDevices = listOf( BlockDevice("/dev/sda", 1.TB), BlockDevice("/dev/sdb", 1.TB) ), storageCapabilities = listOf( lvmStorageCapability ) ) ) MirrorVolume( host = host, vStorage = testDisk, capability = lvmStorageCapability, mirrors = 2.toShort(), allocation = VirtualStorageLvmAllocation( capabilityId = lvmStorageCapability.id, mirrors = -1, hostId = host.id, vgName = lvmStorageCapability.volumeGroupName, path = "", actualSize = 1.GB ) ) } assertThrows<IllegalStateException>("Not enough devices to mirror") { val lvmStorageCapability = LvmStorageCapability( size = 8.TB, volumeGroupName = "vg-1", physicalVolumes = mapOf( "/dev/sda" to 1.TB, "/dev/sdb" to 1.TB ) ) val host = testHost.copy( capabilities = testHostCapabilities.copy( blockDevices = listOf( BlockDevice("/dev/sda", 1.TB), BlockDevice("/dev/sdb", 1.TB) ), storageCapabilities = listOf( lvmStorageCapability ) ) ) MirrorVolume( host = host, vStorage = testDisk, capability = lvmStorageCapability, mirrors = 2.toShort(), allocation = VirtualStorageLvmAllocation( capabilityId = lvmStorageCapability.id, mirrors = 0, hostId = host.id, vgName = lvmStorageCapability.volumeGroupName, path = "", actualSize = 1.GB ) ) } } }
apache-2.0
koma-im/koma
src/main/kotlin/koma/util/matrix/util.kt
1
278
package koma.util.matrix import koma.koma_app.appState import koma.matrix.UserId import koma.matrix.user.presence.PresenceMessage import koma.model.user.UserState fun PresenceMessage.getUserState(): UserState? { return appState.store.userStore.getOrCreateUserId(sender) }
gpl-3.0
aosp-mirror/platform_frameworks_support
jetifier/jetifier/processor/src/main/kotlin/com/android/tools/build/jetifier/processor/transform/pom/XmlUtils.kt
1
4685
/* * Copyright 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 com.android.tools.build.jetifier.processor.transform.pom import com.android.tools.build.jetifier.core.pom.PomDependency import com.android.tools.build.jetifier.core.utils.Log import org.jdom2.Document import org.jdom2.Element import org.jdom2.input.SAXBuilder import org.jdom2.output.Format import org.jdom2.output.XMLOutputter import java.io.ByteArrayOutputStream import java.util.regex.Pattern /** * Utilities for handling XML documents. */ class XmlUtils { companion object { private val variablePattern = Pattern.compile("\\$\\{([^}]*)}") /** Saves the given [Document] to a new byte array */ fun convertDocumentToByteArray(document: Document): ByteArray { val xmlOutput = XMLOutputter() ByteArrayOutputStream().use { xmlOutput.format = Format.getPrettyFormat() xmlOutput.output(document, it) return it.toByteArray() } } /** Creates a new [Document] from the given [ByteArray] */ fun createDocumentFromByteArray(data: ByteArray): Document { val builder = SAXBuilder() data.inputStream().use { return builder.build(it) } } /** * Creates a new XML element with the given [id] and text given in [value] and puts it under * the given [parent]. Nothing is created if the [value] argument is null or empty. */ fun addStringNodeToNode(parent: Element, id: String, value: String?) { if (value.isNullOrEmpty()) { return } val element = Element(id) element.text = value element.namespace = parent.namespace parent.children.add(element) } fun resolveValue(value: String?, properties: Map<String, String>): String? { if (value == null) { return null } val matcher = variablePattern.matcher(value) if (matcher.matches()) { val variableName = matcher.group(1) val varValue = properties[variableName] if (varValue == null) { Log.e("TAG", "Failed to resolve variable '%s'", value) return value } return varValue } return value } /** * Creates a new [PomDependency] from the given XML [Element]. */ fun createDependencyFrom(node: Element, properties: Map<String, String>): PomDependency { var groupId: String? = null var artifactId: String? = null var version: String? = null var classifier: String? = null var type: String? = null var scope: String? = null var systemPath: String? = null var optional: String? = null for (childNode in node.children) { when (childNode.name) { "groupId" -> groupId = resolveValue(childNode.value, properties) "artifactId" -> artifactId = resolveValue(childNode.value, properties) "version" -> version = resolveValue(childNode.value, properties) "classifier" -> classifier = resolveValue(childNode.value, properties) "type" -> type = resolveValue(childNode.value, properties) "scope" -> scope = resolveValue(childNode.value, properties) "systemPath" -> systemPath = resolveValue(childNode.value, properties) "optional" -> optional = resolveValue(childNode.value, properties) } } return PomDependency( groupId = groupId, artifactId = artifactId, version = version, classifier = classifier, type = type, scope = scope, systemPath = systemPath, optional = optional) } } }
apache-2.0
slisson/intellij-community
plugins/settings-repository/testSrc/RespositoryHelper.kt
13
2371
/* * Copyright 2000-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.settingsRepository.test import com.intellij.mock.MockVirtualFileSystem import com.intellij.openapi.vfs.VfsUtilCore import com.intellij.openapi.vfs.VirtualFile import com.intellij.testFramework.LightVirtualFile import com.intellij.testFramework.isFile import gnu.trove.THashSet import org.assertj.core.api.Assertions.assertThat import org.eclipse.jgit.lib.Constants import java.nio.file.Files import java.nio.file.Path data class FileInfo(val name: String, val data: ByteArray) fun fs() = MockVirtualFileSystem() private fun getChildrenStream(path: Path, excludes: Array<out String>? = null) = Files.list(path) .filter { !it.endsWith(Constants.DOT_GIT) && (excludes == null || !excludes.contains(it.getFileName().toString())) } .sorted() private fun compareFiles(path1: Path, path2: Path, path3: VirtualFile? = null, vararg localExcludes: String) { assertThat(path1).isDirectory() assertThat(path2).isDirectory() if (path3 != null) { assertThat(path3.isDirectory()).isTrue() } val notFound = THashSet<Path>() for (path in getChildrenStream(path1, localExcludes)) { notFound.add(path) } for (child2 in getChildrenStream(path2)) { val fileName = child2.getFileName() val child1 = path1.resolve(fileName) val child3 = path3?.findChild(fileName.toString()) if (child1.isFile()) { assertThat(child2).hasSameContentAs(child1) if (child3 != null) { assertThat(child3.isDirectory()).isFalse() assertThat(child1).hasContent(if (child3 is LightVirtualFile) child3.getContent().toString() else VfsUtilCore.loadText(child3)) } } else { compareFiles(child1, child2, child3, *localExcludes) } notFound.remove(child1) } assertThat(notFound).isEmpty() }
apache-2.0
seventhroot/elysium
bukkit/rpk-languages-bukkit/src/main/kotlin/com/rpkit/languages/bukkit/language/RPKLanguageProviderImpl.kt
1
2797
/* * Copyright 2020 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.languages.bukkit.language import com.rpkit.languages.bukkit.RPKLanguagesBukkit class RPKLanguageProviderImpl(private val plugin: RPKLanguagesBukkit): RPKLanguageProvider { override val languages = plugin.config .getConfigurationSection("languages") ?.getKeys(false) ?.map { languageName -> RPKLanguageImpl( languageName, plugin.config.getConfigurationSection("languages.$languageName.default-race-understanding") ?.getKeys(false) ?.map { race -> Pair(race, plugin.config.getDouble("languages.$languageName.default-race-understanding.$race").toFloat()) } ?.toMap() ?: emptyMap(), plugin.config.getConfigurationSection("languages.$languageName.understanding-increment") ?.getKeys(false) ?.map { race -> Pair(race, plugin.config.getDouble("languages.$languageName.understanding-increment.$race.minimum").toFloat()) } ?.toMap() ?: emptyMap(), plugin.config.getConfigurationSection("languages.$languageName.understanding-increment") ?.getKeys(false) ?.map { race -> Pair(race, plugin.config.getDouble("languages.$languageName.understanding-increment.$race.maximum").toFloat()) } ?.toMap() ?: emptyMap(), plugin.config.getConfigurationSection("languages.$languageName.cypher") ?.getKeys(false) ?.map { key -> Pair(key, plugin.config.getString("languages.$languageName.cypher.$key") ?: key) } ?.toMap() ?: emptyMap() ) } ?: emptyList() override fun getLanguage(name: String): RPKLanguage? { return languages.firstOrNull { it.name == name } } }
apache-2.0
JetBrains/teamcity-azure-plugin
plugin-azure-server/src/main/kotlin/jetbrains/buildServer/clouds/azure/arm/AzureCloudImage.kt
1
19077
/* * Copyright 2000-2021 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 jetbrains.buildServer.clouds.azure.arm import com.intellij.openapi.diagnostic.Logger import jetbrains.buildServer.clouds.CloudException import jetbrains.buildServer.clouds.CloudInstanceUserData import jetbrains.buildServer.clouds.InstanceStatus import jetbrains.buildServer.clouds.QuotaException import jetbrains.buildServer.clouds.azure.AzureUtils import jetbrains.buildServer.clouds.azure.arm.connector.AzureApiConnector import jetbrains.buildServer.clouds.azure.arm.connector.AzureInstance import jetbrains.buildServer.clouds.azure.arm.types.* import jetbrains.buildServer.clouds.base.AbstractCloudImage import jetbrains.buildServer.clouds.base.connector.AbstractInstance import jetbrains.buildServer.clouds.base.errors.TypedCloudErrorInfo import jetbrains.buildServer.serverSide.TeamCityProperties import kotlinx.coroutines.* import java.lang.StringBuilder import java.util.* import java.util.concurrent.atomic.AtomicReference /** * Azure cloud image. */ class AzureCloudImage(private val myImageDetails: AzureCloudImageDetails, private val myApiConnector: AzureApiConnector, private val myScope: CoroutineScope) : AbstractCloudImage<AzureCloudInstance, AzureCloudImageDetails>(myImageDetails.sourceId, myImageDetails.sourceId) { private val myImageHandlers = mapOf( AzureCloudImageType.Vhd to AzureVhdHandler(myApiConnector), AzureCloudImageType.Image to AzureImageHandler(myApiConnector), AzureCloudImageType.GalleryImage to AzureImageHandler(myApiConnector), AzureCloudImageType.Template to AzureTemplateHandler(myApiConnector), AzureCloudImageType.Container to AzureContainerHandler(myApiConnector) ) private val myInstanceHandler = AzureInstanceHandler(myApiConnector) private val myActiveStatuses = setOf( InstanceStatus.SCHEDULED_TO_START, InstanceStatus.STARTING, InstanceStatus.RUNNING, InstanceStatus.RESTARTING, InstanceStatus.SCHEDULED_TO_STOP, InstanceStatus.STOPPING, InstanceStatus.ERROR ) private var azureCpuQuotaExceeded: Set<String>? = null private val overlimitInstanceToDelete = AtomicReference<AzureCloudInstance?>(null) override fun getImageDetails(): AzureCloudImageDetails = myImageDetails override fun createInstanceFromReal(realInstance: AbstractInstance): AzureCloudInstance { return AzureCloudInstance(this, realInstance.name).apply { properties = realInstance.properties } } override fun detectNewInstances(realInstances: MutableMap<String, out AbstractInstance>?) { super.detectNewInstances(realInstances) if (realInstances == null) { return } // Update properties instances.forEach { instance -> realInstances[instance.instanceId]?.let { instance.properties = it.properties } } } override fun canStartNewInstance(): Boolean { if (activeInstances.size >= myImageDetails.maxInstances) return false // Check Azure CPU quota state azureCpuQuotaExceeded?.let { instances -> if (instances == getInstanceIds()) { return false } else { azureCpuQuotaExceeded = null LOG.info("Azure CPU quota limit has been reset due to change in the number of active instances for image ${imageDetails.sourceId}.") } } if (imageDetails.deployTarget == AzureCloudDeployTarget.Instance && stoppedInstances.isEmpty()) { return false } return true } override fun startNewInstance(userData: CloudInstanceUserData) = runBlocking { if (!canStartNewInstance()) { throw QuotaException("Unable to start more instances. Limit has reached") } val instance = if (myImageDetails.deployTarget == AzureCloudDeployTarget.Instance) { startStoppedInstance() } else { tryToStartStoppedInstance(userData) ?: createInstance(userData) } instance.apply { setStartDate(Date()) } } /** * Creates a new virtual machine. * * @param userData info about server. * @return created instance. */ private fun createInstance(userData: CloudInstanceUserData): AzureCloudInstance { val instance = createAzureCloudInstance() val data = AzureUtils.setVmNameForTag(userData, instance.name) val image = this myScope.launch { val hash = handler!!.getImageHash(imageDetails) instance.properties[AzureConstants.TAG_PROFILE] = userData.profileId instance.properties[AzureConstants.TAG_SOURCE] = imageDetails.sourceId instance.properties[AzureConstants.TAG_DATA_HASH] = getDataHash(data) instance.properties[AzureConstants.TAG_IMAGE_HASH] = hash parseCustomTags(myImageDetails.customTags).forEach { instance.properties[it.first] = it.second } try { instance.provisioningInProgress = true instance.status = InstanceStatus.STARTING LOG.info("Creating new virtual machine ${instance.name}") myApiConnector.createInstance(instance, data) updateInstanceStatus(image, instance) } catch (e: Throwable) { LOG.warnAndDebugDetails(e.message, e) handleDeploymentError(e) instance.status = InstanceStatus.ERROR instance.updateErrors(TypedCloudErrorInfo.fromException(e)) if (TeamCityProperties.getBooleanOrTrue(AzureConstants.PROP_DEPLOYMENT_DELETE_FAILED)) { LOG.info("Removing allocated resources for virtual machine ${instance.name}") try { myApiConnector.deleteInstance(instance) LOG.info("Allocated resources for virtual machine ${instance.name} have been removed") } catch (e: Throwable) { val message = "Failed to delete allocated resources for virtual machine ${instance.name}: ${e.message}" LOG.warnAndDebugDetails(message, e) } } else { LOG.info("Allocated resources for virtual machine ${instance.name} would not be deleted. Cleanup them manually.") } } finally { instance.provisioningInProgress = false } } return instance } private fun createAzureCloudInstance(): AzureCloudInstance { do { val instance = AzureCloudInstance(this, getInstanceName()) instance.status = InstanceStatus.SCHEDULED_TO_START if (addInstanceIfAbsent(instance)) { while(activeInstances.size > myImageDetails.maxInstances) { val lastStartingInstance = instances.filter { it.status == InstanceStatus.SCHEDULED_TO_START }.sortedBy { it.name }.lastOrNull() if (lastStartingInstance == null) { throw QuotaException("Unable to start more instances. Limit has reached") } if (overlimitInstanceToDelete.compareAndSet(null, instance)) { removeInstance(instance.instanceId) overlimitInstanceToDelete.set(null) throw QuotaException("Unable to start more instances. Limit has reached") } } return instance }; } while (true); } /** * Tries to find and start stopped instance. * * @return instance if it found. */ private suspend fun tryToStartStoppedInstance(userData: CloudInstanceUserData): AzureCloudInstance? { val image = this return coroutineScope { if (myImageDetails.behaviour.isDeleteAfterStop && myImageDetails.spotVm != true) return@coroutineScope null if (stoppedInstances.isEmpty()) return@coroutineScope null val instances = stoppedInstances val validInstances = instances.filter { if (!isSameImageInstance(it)) { LOG.info("Will remove virtual machine ${it.name} due to changes in image source") return@filter false } val data = AzureUtils.setVmNameForTag(userData, it.name) if (it.properties[AzureConstants.TAG_DATA_HASH] != getDataHash(data)) { LOG.info("Will remove virtual machine ${it.name} due to changes in cloud profile") return@filter false } return@filter true } val invalidInstances = instances - validInstances val instance = validInstances.firstOrNull() instance?.status = InstanceStatus.SCHEDULED_TO_START myScope.launch { invalidInstances.forEach { val instanceToRemove = removeInstance(it.instanceId) if (instanceToRemove != null) { try { LOG.info("Removing virtual machine ${it.name}") it.provisioningInProgress = true myApiConnector.deleteInstance(it) } catch (e: Throwable) { LOG.warnAndDebugDetails(e.message, e) it.status = InstanceStatus.ERROR it.updateErrors(TypedCloudErrorInfo.fromException(e)) addInstance(instanceToRemove) } finally { it.provisioningInProgress = false } } } instance?.let { try { instance.provisioningInProgress = true it.status = InstanceStatus.STARTING LOG.info("Starting stopped virtual machine ${it.name}") myApiConnector.startInstance(it) updateInstanceStatus(image, it) } catch (e: Throwable) { LOG.warnAndDebugDetails(e.message, e) handleDeploymentError(e) it.status = InstanceStatus.ERROR it.updateErrors(TypedCloudErrorInfo.fromException(e)) } finally { instance.provisioningInProgress = false } } } return@coroutineScope instance } } /** * Starts stopped instance. * * @return instance. */ private fun startStoppedInstance(): AzureCloudInstance { val instance = stoppedInstances.singleOrNull() ?: throw CloudException("Instance ${imageDetails.vmNamePrefix ?: imageDetails.sourceId} was not found") instance.status = InstanceStatus.SCHEDULED_TO_START val image = this myScope.launch { try { instance.provisioningInProgress = true instance.status = InstanceStatus.STARTING LOG.info("Starting virtual machine ${instance.name}") myApiConnector.startInstance(instance) updateInstanceStatus(image, instance) } catch (e: Throwable) { LOG.warnAndDebugDetails(e.message, e) handleDeploymentError(e) instance.status = InstanceStatus.ERROR instance.updateErrors(TypedCloudErrorInfo.fromException(e)) } finally { instance.provisioningInProgress = false } } return instance } private fun updateInstanceStatus(image: AzureCloudImage, instance: AzureCloudInstance) { val instances = myApiConnector.fetchInstances<AzureInstance>(image) instances.get(instance.name)?.let { it.startDate?.let { instance.setStartDate(it) } it.ipAddress?.let { instance.setNetworkIdentify(it) } instance.status = it.instanceStatus } } private suspend fun isSameImageInstance(instance: AzureCloudInstance) = coroutineScope { if (imageDetails.deployTarget == AzureCloudDeployTarget.Instance) { return@coroutineScope true } handler?.let { val hash = it.getImageHash(imageDetails) return@coroutineScope hash == instance.properties[AzureConstants.TAG_IMAGE_HASH] } false } private fun getDataHash(userData: CloudInstanceUserData): String { val dataHash = StringBuilder(userData.agentName) .append(userData.profileId) .append(userData.serverAddress) .toString() .hashCode() return Integer.toHexString(dataHash) } override fun restartInstance(instance: AzureCloudInstance) { instance.status = InstanceStatus.RESTARTING val image = this myScope.launch { try { instance.provisioningInProgress = true instance.status = InstanceStatus.STARTING LOG.info("Restarting virtual machine ${instance.name}") myApiConnector.restartInstance(instance) updateInstanceStatus(image, instance) } catch (e: Throwable) { LOG.warnAndDebugDetails(e.message, e) instance.status = InstanceStatus.ERROR instance.updateErrors(TypedCloudErrorInfo.fromException(e)) } finally { instance.provisioningInProgress = false } } } override fun terminateInstance(instance: AzureCloudInstance) { if (instance.properties.containsKey(AzureConstants.TAG_INVESTIGATION)) { LOG.info("Could not stop virtual machine ${instance.name} under investigation. To do that remove ${AzureConstants.TAG_INVESTIGATION} tag from it.") return } val image = this instance.status = InstanceStatus.SCHEDULED_TO_STOP myScope.launch { try { instance.provisioningInProgress = true instance.status = InstanceStatus.STOPPING val sameVhdImage = isSameImageInstance(instance) if (myImageDetails.behaviour.isDeleteAfterStop) { LOG.info("Removing virtual machine ${instance.name} due to cloud image settings") myApiConnector.deleteInstance(instance) instance.status = InstanceStatus.STOPPED } else if (!sameVhdImage) { LOG.info("Removing virtual machine ${instance.name} due to cloud image retention policy") myApiConnector.deleteInstance(instance) instance.status = InstanceStatus.STOPPED } else { LOG.info("Stopping virtual machine ${instance.name}") myApiConnector.stopInstance(instance) updateInstanceStatus(image, instance) } LOG.info("Virtual machine ${instance.name} has been successfully terminated") } catch (e: Throwable) { LOG.warnAndDebugDetails(e.message, e) instance.status = InstanceStatus.ERROR instance.updateErrors(TypedCloudErrorInfo.fromException(e)) } finally { instance.provisioningInProgress = false } } } override fun getAgentPoolId(): Int? = myImageDetails.agentPoolId val handler: AzureHandler? get() = if (imageDetails.deployTarget == AzureCloudDeployTarget.Instance) { myInstanceHandler } else { myImageHandlers[imageDetails.type] } private fun getInstanceName(): String { val keys = instances.map { it.instanceId.toLowerCase() } val sourceName = myImageDetails.sourceId.toLowerCase() var i = 1 while (keys.contains(sourceName + i)) i++ return sourceName + i } /** * Returns active instances. * * @return instances. */ private val activeInstances: List<AzureCloudInstance> get() = instances.filter { instance -> myActiveStatuses.contains(instance.status) } /** * Returns stopped instances. * * @return instances. */ private val stoppedInstances: List<AzureCloudInstance> get() = instances.filter { instance -> instance.status == InstanceStatus.STOPPED && !instance.properties.containsKey(AzureConstants.TAG_INVESTIGATION) } private fun handleDeploymentError(e: Throwable) { if (AZURE_CPU_QUOTA_EXCEEDED.containsMatchIn(e.message!!)) { azureCpuQuotaExceeded = getInstanceIds() LOG.info("Exceeded Azure CPU quota limit for image ${imageDetails.sourceId}. Would not start new cloud instances until active instances termination.") } } private fun getInstanceIds() = activeInstances.asSequence().map { it.instanceId }.toSortedSet() companion object { private val LOG = Logger.getInstance(AzureCloudImage::class.java.name) private val AZURE_CPU_QUOTA_EXCEEDED = Regex("Operation results in exceeding quota limits of Core\\. Maximum allowed: \\d+, Current in use: \\d+, Additional requested: \\d+\\.") fun parseCustomTags(rawString: String?): List<Pair<String, String>> { return if (rawString != null && rawString.isNotEmpty()) { rawString.lines().map { it.trim() }.filter { it.isNotEmpty() }.mapNotNull { val tag = it val equalsSignIndex = tag.indexOf("=") if (equalsSignIndex >= 1) { Pair(tag.substring(0, equalsSignIndex), tag.substring(equalsSignIndex + 1)) } else { null } } } else { Collections.emptyList() } } } }
apache-2.0
timakden/advent-of-code
src/main/kotlin/ru/timakden/aoc/year2015/day17/Input.kt
1
133
package ru.timakden.aoc.year2015.day17 val input = listOf(11, 30, 47, 31, 32, 36, 3, 1, 5, 3, 32, 36, 15, 11, 46, 26, 28, 1, 19, 3)
apache-2.0
kpspemu/kpspemu
src/commonMain/kotlin/com/soywiz/kpspemu/util/NullExt.kt
1
124
package com.soywiz.kpspemu.util inline fun <T> T.nullIf(callback: T.() -> Boolean): T? = if (callback(this)) null else this
mit
dtretyakov/teamcity-rust
plugin-rust-agent/src/main/kotlin/jetbrains/buildServer/rust/CargoBuildSessionFactory.kt
1
1360
/* * Copyright 2000-2021 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"). * See LICENSE in the project root for license information. */ package jetbrains.buildServer.rust import jetbrains.buildServer.agent.AgentBuildRunnerInfo import jetbrains.buildServer.agent.BuildAgentConfiguration import jetbrains.buildServer.agent.BuildRunnerContext import jetbrains.buildServer.agent.BuildRunnerContextEx import jetbrains.buildServer.agent.inspections.InspectionReporter import jetbrains.buildServer.agent.runner.MultiCommandBuildSessionFactory import jetbrains.buildServer.rust.inspections.ClippyInspectionsParser /** * Cargo runner service factory. */ class CargoBuildSessionFactory( private val inspectionReporter: InspectionReporter ) : MultiCommandBuildSessionFactory { override fun createSession(runnerContext: BuildRunnerContext) = CargoCommandBuildSession(runnerContext as BuildRunnerContextEx, inspectionReporter, ClippyInspectionsParser()) override fun getBuildRunnerInfo(): AgentBuildRunnerInfo { return object : AgentBuildRunnerInfo { override fun getType(): String { return CargoConstants.RUNNER_TYPE } override fun canRun(config: BuildAgentConfiguration): Boolean { return true } } } }
apache-2.0
Litote/kmongo
kmongo-core-tests/src/main/kotlin/org/litote/kmongo/session/MapReduceWithSessionTest.kt
1
1922
/* * Copyright (C) 2016/2022 Litote * * 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.litote.kmongo.session import com.mongodb.client.ClientSession import kotlinx.serialization.Serializable import org.junit.After import org.junit.Before import org.junit.Test import org.litote.kmongo.AllCategoriesKMongoBaseTest import org.litote.kmongo.mapReduce import org.litote.kmongo.model.Friend import org.litote.kmongo.oldestMongoTestVersion import kotlin.test.assertEquals /** * */ class MapReduceWithSessionTest : AllCategoriesKMongoBaseTest<Friend>(oldestMongoTestVersion) { lateinit var session: ClientSession @Before fun setup() { session = mongoClient.startSession() } @After fun tearDown() { session.close() } @Serializable data class KeyValue(val _id: String, val value: Double) @Test fun `mapReduce works as expected`() { col.insertMany(session, listOf(Friend("John"), Friend("Ernesto"))) val sumNameLength = col.mapReduce<KeyValue>( session, """ function() { emit("name", this.name.length); }; """, """ function(name, l) { return Array.sum(l); }; """ ).first() assertEquals(11.0, sumNameLength?.value) } }
apache-2.0
RSDT/Japp
app/src/main/java/nl/rsdt/japp/jotial/auth/AeSimpleSHA1.kt
1
1329
package nl.rsdt.japp.jotial.auth import android.util.Log import java.io.UnsupportedEncodingException import java.security.MessageDigest import java.security.NoSuchAlgorithmException /** * @author ? * @version 1.0 * @since 15-1-2016 * Tool for SHA1. */ object AeSimpleSHA1 { private fun convertToHex(data: ByteArray): String { val buf = StringBuilder() for (b in data) { var halfbyte = (b.toInt() ushr 4) and 0x0F var two_halfs = 0 do { buf.append(if (0 <= halfbyte && halfbyte <= 9) ('0'.toInt() + halfbyte).toChar() else ('a'.toInt() + (halfbyte - 10)).toChar()) halfbyte = b.toInt() and 0x0F } while (two_halfs++ < 1) } return buf.toString() } @Throws(NoSuchAlgorithmException::class, UnsupportedEncodingException::class) fun SHA1(text: String): String { val md = MessageDigest.getInstance("SHA-1") md.update(text.toByteArray(charset("iso-8859-1")), 0, text.length) val sha1hash = md.digest() return convertToHex(sha1hash) } fun trySHA1(text: String): String { try { return SHA1(text) } catch (e: Exception) { Log.e("AeSImpleSHA1", e.localizedMessage, e) } return "error-in-trySHA1" } }
apache-2.0
EMResearch/EvoMaster
core/src/main/kotlin/org/evomaster/core/search/service/ExtraHeuristicsLogger.kt
1
3001
package org.evomaster.core.search.service import com.google.inject.Inject import net.sf.jsqlparser.JSQLParserException import net.sf.jsqlparser.parser.CCJSqlParserUtil import net.sf.jsqlparser.util.deparser.SelectDeParser import net.sf.jsqlparser.util.deparser.StatementDeParser import org.evomaster.client.java.controller.api.dto.HeuristicEntryDto import org.evomaster.core.EMConfig import org.evomaster.core.database.ReplaceValuesDeParser import java.nio.file.Files import java.nio.file.Path import java.nio.file.Paths import javax.annotation.PostConstruct /** * Service used to write to disk info on the extra heuristics */ class ExtraHeuristicsLogger { @Inject private lateinit var config: EMConfig @Inject private lateinit var time: SearchTimeController @PostConstruct private fun postConstruct() { if (config.writeExtraHeuristicsFile) { val extraHeuristicsFilePath = getExtraHeuristicsFilePath() setUpFilePath(extraHeuristicsFilePath) extraHeuristicsFilePath.toFile().appendText("testCounter,actionId,value,id,type,objective,group\n") } } /** * Creates parent path if it is not exists. * And deletes the file if the file already exists. */ private fun setUpFilePath(filePath: Path) { Files.createDirectories(filePath.parent) Files.deleteIfExists(filePath) Files.createFile(filePath) } private fun getExtraHeuristicsFilePath() = Paths.get(config.extraHeuristicsFile).toAbsolutePath() fun writeHeuristics(list: List<HeuristicEntryDto>, actionId: Int) { if (!config.writeExtraHeuristicsFile) { return } val counter = time.evaluatedIndividuals val lines = list.map { val group = if (it.type == HeuristicEntryDto.Type.SQL) { try { "\"${removeAllConstants(it.id)}\"" } catch (ex: JSQLParserException) { "JSQLParserException: ${ex.message}" } } else "-" "$counter,$actionId,${it.value},\"${it.id}\",${it.type},${it.objective},$group\n" }.joinToString("") getExtraHeuristicsFilePath().toFile().appendText(lines) } /** * Remove all constants from the SQL commands (eg, strings and numbers), * to group together command with same structure, regardless of the used variables. * */ fun removeAllConstants(sql: String): String { val buffer = StringBuilder() val expressionDeParser = ReplaceValuesDeParser() val selectDeparser = SelectDeParser(expressionDeParser, buffer) expressionDeParser.selectVisitor = selectDeparser expressionDeParser.buffer = buffer val stmtDeparser = StatementDeParser(expressionDeParser, selectDeparser, buffer) val stmt = CCJSqlParserUtil.parse(sql) stmt.accept(stmtDeparser) return stmtDeparser.buffer.toString() } }
lgpl-3.0
artjimlop/clean-architecture-kotlin
domain/src/test/java/com/example/usecases/GetComicByIdUseCaseTest.kt
1
1639
package com.example.usecases import com.example.bos.Comic import com.example.callback.ComicCallback import com.example.executor.TestExecutionThread import com.example.executor.TestThreadExecutor import com.example.repositories.LocalComicsRepository import com.nhaarman.mockito_kotlin.any import com.nhaarman.mockito_kotlin.verify import org.junit.Before import org.junit.Test import org.mockito.Mockito import java.util.* class GetComicByIdUseCaseTest { private val FAKE_COMIC_ID = 0 lateinit var localComicsRepository: LocalComicsRepository lateinit var comicCallback: ComicCallback private lateinit var useCase: GetComicByIdUseCase @Before fun setUp() { localComicsRepository = Mockito.mock(LocalComicsRepository::class.java) comicCallback = Mockito.mock(ComicCallback::class.java) val postExecutionThread = TestExecutionThread() val threadExecutor = TestThreadExecutor() useCase = GetComicByIdUseCase(threadExecutor, postExecutionThread, localComicsRepository) } @Test fun comicObtainedFromLocalRepository() { useCase.execute(FAKE_COMIC_ID, comicCallback) verify(localComicsRepository).getComic(FAKE_COMIC_ID) } @Test fun comicObtainedFromLocalRepositoryIsNotified() { Mockito.`when`(localComicsRepository.getComic(FAKE_COMIC_ID)).thenReturn(comic()) useCase.execute(FAKE_COMIC_ID, comicCallback) verify(comicCallback).onComicLoaded(any()) } private fun comic(): Comic? { return Comic(FAKE_COMIC_ID, "", "", 0, "", Collections.emptyList()) } }
apache-2.0
cloudbearings/contentful-management.java
src/test/kotlin/com/contentful/java/cma/SpaceTests.kt
1
8499
/* * Copyright (C) 2014 Contentful GmbH * * 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.contentful.java.cma import com.contentful.java.cma.lib.ModuleTestUtils import com.contentful.java.cma.lib.TestCallback import com.contentful.java.cma.lib.TestUtils import com.contentful.java.cma.model.CMASpace import com.squareup.okhttp.mockwebserver.MockResponse import kotlin.test.assertEquals import kotlin.test.assertNotNull import kotlin.test.assertTrue import org.junit.Test as test class SpaceTests : BaseTest() { test fun testCreate() { val requestBody = TestUtils.fileToString("space_create_request.json") val responseBody = TestUtils.fileToString("space_create_response.json") server!!.enqueue(MockResponse().setResponseCode(200).setBody(responseBody)) val result = assertTestCallback(client!!.spaces().async().create( "xxx", TestCallback()) as TestCallback) assertEquals("spaceid", result.getSys()["id"]) assertEquals("xxx", result.getName()) // Request val recordedRequest = server!!.takeRequest() assertEquals("POST", recordedRequest.getMethod()) assertEquals("/spaces", recordedRequest.getPath()) assertEquals(requestBody, recordedRequest.getUtf8Body()) } test fun testCreateInOrg() { server!!.enqueue(MockResponse().setResponseCode(200).setBody("{}")) assertTestCallback(client!!.spaces().async().create( "whatever", "org", TestCallback()) as TestCallback) // Request val recordedRequest = server!!.takeRequest() assertEquals("POST", recordedRequest.getMethod()) assertEquals("/spaces", recordedRequest.getPath()) assertEquals("org", recordedRequest.getHeader("X-Contentful-Organization")) } test fun testDelete() { server!!.enqueue(MockResponse().setResponseCode(200)) assertTestCallback(client!!.spaces().async().delete( "spaceid", TestCallback()) as TestCallback) // Request val recordedRequest = server!!.takeRequest() assertEquals("DELETE", recordedRequest.getMethod()) assertEquals("/spaces/spaceid", recordedRequest.getPath()) } test fun testFetchAll() { val responseBody = TestUtils.fileToString("space_fetch_all_response.json") server!!.enqueue(MockResponse().setResponseCode(200).setBody(responseBody)) val result = assertTestCallback(client!!.spaces().async() .fetchAll(TestCallback()) as TestCallback) val items = result.getItems() assertEquals("Array", result.getSys()["type"]) assertEquals(2, items.size()) assertEquals(2, result.getTotal()) assertEquals(0, result.getSkip()) assertEquals(25, result.getLimit()) // Space #1 var sys = items[0].getSys() assertEquals("Space", sys["type"]) assertEquals("id1", sys["id"]) assertEquals(1.toDouble(), sys["version"]) assertEquals("2014-03-21T08:43:52Z", sys["createdAt"]) assertEquals("2014-04-27T18:16:10Z", sys["updatedAt"]) assertEquals("space1", items[0].getName()) // Created By var map = (items[0].getSys()["createdBy"] as Map<*, *>)["sys"] as Map<*, *> assertEquals("Link", map["type"]) assertEquals("User", map["linkType"]) assertEquals("user1", map["id"]) // Updated By map = (items[0].getSys()["updatedBy"] as Map<*, *>)["sys"] as Map<*, *> assertEquals("Link", map["type"]) assertEquals("User", map["linkType"]) assertEquals("user1", map["id"]) // Space #2 sys = items[1].getSys() assertEquals("Space", sys["type"]) assertEquals("id2", sys["id"]) assertEquals(2.toDouble(), sys["version"]) assertEquals("2014-05-19T09:00:27Z", sys["createdAt"]) assertEquals("2014-07-09T07:48:24Z", sys["updatedAt"]) assertEquals("space2", items[1].getName()) // Created By map = (sys["createdBy"] as Map<*, *>)["sys"] as Map<*, *> assertEquals("Link", map["type"]) assertEquals("User", map["linkType"]) assertEquals("user2", map["id"]) // Updated By map = (sys["updatedBy"] as Map<*, *>)["sys"] as Map<*, *> assertEquals("Link", map["type"]) assertEquals("User", map["linkType"]) assertEquals("user2", map["id"]) // Request val request = server!!.takeRequest() assertEquals("GET", request.getMethod()) assertEquals("/spaces", request.getPath()) } test fun testFetchWithId() { val responseBody = TestUtils.fileToString("space_fetch_one_response.json") server!!.enqueue(MockResponse().setResponseCode(200).setBody(responseBody)) val result = assertTestCallback(client!!.spaces().async().fetchOne( "spaceid", TestCallback()) as TestCallback) val sys = result.getSys() assertEquals("Space", sys["type"]) assertEquals("id1", sys["id"]) assertEquals(1.toDouble(), sys["version"]) assertEquals("2014-03-21T08:43:52Z", sys["createdAt"]) assertEquals("2014-04-27T18:16:10Z", sys["updatedAt"]) assertEquals("space1", result.getName()) // Created By var map = (sys["createdBy"] as Map<*, *>)["sys"] as Map<*, *> assertEquals("Link", map["type"]) assertEquals("User", map["linkType"]) assertEquals("user1", map["id"]) // Updated By map = (sys["updatedBy"] as Map<*, *>)["sys"] as Map<*, *> assertEquals("Link", map["type"]) assertEquals("User", map["linkType"]) assertEquals("user1", map["id"]) // Request val request = server!!.takeRequest() assertEquals("GET", request.getMethod()) assertEquals("/spaces/spaceid", request.getPath()) } test fun testFetchLocales() { val responseBody = TestUtils.fileToString("space_fetch_locales_response.json") server!!.enqueue(MockResponse().setResponseCode(200).setBody(responseBody)) val result = assertTestCallback(client!!.spaces().async().fetchLocales( "spaceid", TestCallback()) as TestCallback) val item = result.getItems()[0] assertEquals("U.S. English", item.getName()) assertEquals("en-US", item.getCode()) assertTrue(item.isDefault()) assertTrue(item.isPublished()) // Request val recordedRequest = server!!.takeRequest() assertEquals("GET", recordedRequest.getMethod()) assertEquals("/spaces/spaceid/locales", recordedRequest.getPath()) } test fun testUpdate() { val requestBody = TestUtils.fileToString("space_update_request.json") val responseBody = TestUtils.fileToString("space_update_response.json") server!!.enqueue(MockResponse().setResponseCode(200).setBody(responseBody)) var space = gson!!.fromJson( TestUtils.fileToString("space_update_object.json"), javaClass<CMASpace>()) space.setName("newname") space = assertTestCallback(client!!.spaces().async().update( space, TestCallback()) as TestCallback) assertEquals(2.toDouble(), space.getSys()["version"]) assertEquals("newname", space.getName()) // Request val recordedRequest = server!!.takeRequest() assertEquals("PUT", recordedRequest.getMethod()) assertEquals("/spaces/spaceid", recordedRequest.getPath()) assertNotNull(recordedRequest.getHeader("X-Contentful-Version")) assertEquals(requestBody, recordedRequest.getUtf8Body()) } test(expected = Exception::class) fun testUpdateFailsWithoutVersion() { ModuleTestUtils.assertUpdateWithoutVersion { val space: CMASpace = CMASpace().setName("name").setId("id") client!!.spaces().update(space) } } }
apache-2.0
OpenConference/OpenConference-android
app/src/main/java/com/openconference/model/screen/MyScheduleScreen.kt
1
273
package com.openconference.model.screen import com.openconference.R /** * * * @author Hannes Dorfmann */ class MyScheduleScreen : Screen { override fun titleRes(): Int = R.string.screen_title_my_schedule override fun iconRes(): Int = R.drawable.ic_my_schedule }
apache-2.0
encodeering/conflate
modules/conflate-api/src/main/kotlin/com/encodeering/conflate/experimental/api/Completable.kt
1
1501
package com.encodeering.conflate.experimental.api import kotlin.coroutines.experimental.suspendCoroutine /** * A Completable wraps a computational process, whose final state can be inspected using callbacks. * * The invocation order for callbacks is unspecified and may not stay in the perceived order. * * @param Scope specifies a convenience runtime scope * @param V specifies a convenience success value * @author Michael Clausen - [email protected] */ interface Completable<out Scope, out V> { /** * Registers callbacks at this completable that get notified, as soon as the computation reaches a final state. * * A callback can be registered at any time, even if the process has already finished. * Lately registered callback will be invoked immediately with the known outcome of the completable. * * @param fail specifies a mandatory callback to observe the error state * @param ok specifies an optional callback to observer the success state; a noop by default */ fun then (fail : Scope.(Throwable) -> Unit, ok : Scope.(V) -> Unit = {}) } /** * Suspends this coroutine until the final state of this completable has been reached, which will then resume this coroutine in * either case. */ suspend fun <Scope, V> Completable<Scope, V>.await () { suspendCoroutine<V> { continuation -> then ( { continuation.resumeWithException (it) }, { continuation.resume (it) } ) } }
apache-2.0
jrenner/kotlin-voxel
test/src/kotlin/org/jrenner/learngl/test/CubeDataGridTest.kt
1
15516
package org.jrenner.learngl.test import org.junit.Test import org.junit.Assert.* import org.jrenner.learngl.cube.CubeDataGrid import com.badlogic.gdx.utils.Array as Arr import com.badlogic.gdx.math.Vector3 import org.jrenner.learngl.utils.IntVector3 import com.badlogic.gdx.math.MathUtils import com.badlogic.gdx.utils.GdxRuntimeException import com.badlogic.gdx.utils.ObjectSet import org.jrenner.learngl.gameworld.Chunk import org.jrenner.learngl.gameworld.CubeData import org.jrenner.learngl.gameworld.CubeType import org.jrenner.learngl.gameworld.World import org.jrenner.learngl.utils.calculateHiddenFaces import org.jrenner.learngl.utils.threeIntegerHashCode import org.jrenner.learngl.world class CubeDataGridTest { fun basicCDG(): CubeDataGrid { val origin = Vector3(0f, 0f, 0f) return CubeDataGrid.create(origin.x, origin.y, origin.z) } val expectedNumElements = CubeDataGrid.width * CubeDataGrid.height * CubeDataGrid.depth @Test fun constructor() { val cdg = basicCDG() assertEquals(expectedNumElements, cdg.numElements) } @Test fun hashCodeTest() { val set = ObjectSet<Int>() val size = 100 for (x in 0..size) { //println("hashCodeTest, x: $x") for (y in 0..size) { for (z in 0..size) { //val cdg = CubeDataGrid() //cdg.init(x.toFloat(), y.toFloat(), z.toFloat()) //val hash = cdg.hashCode() val hash = threeIntegerHashCode(x, y, z) assertFalse("duplicate hash codes must not exist for CubeDataGrid\n(xyz: $x, $y, $z) hash: $hash", set.contains(hash)) set.add(hash) } } } } @Test fun iteration() { // test multiple times to test reset() method val cdg = basicCDG() for (n in 1..3) { var count = 0 for (item in cdg) { count++ } assertEquals(expectedNumElements, count) } } /** test iteration order of Y, then X, then Z */ @Test fun iterationOrder() { val cdg = basicCDG() val grid = cdg.grid val manualCollection = Arr<CubeData>() for (y in grid.indices) { for (x in grid[y].indices) { for (z in grid[y][x].indices) { val cubeData = grid[y][x][z] manualCollection.add(cubeData) } } } val iteratorCollection = Arr<CubeData>() for (cubeData in cdg) { iteratorCollection.add(cubeData) } assertEquals(manualCollection.size, iteratorCollection.size) val manualPos = Vector3() val iteratorPos = Vector3() for (i in 0 until manualCollection.size) { manualPos.set(manualCollection.get(i).getPositionTempVec()) iteratorPos.set(iteratorCollection.get(i).getPositionTempVec()) assertEquals(manualPos, iteratorPos) } } @Test fun hasCube() { val width = CubeDataGrid.width val height = CubeDataGrid.height val depth = CubeDataGrid.depth val cdg = basicCDG() val under = 0.99f for (x in 0 until width) { for (y in 0 until height) { for (z in 0 until depth) { assertTrue(cdg.hasCubeAt(x.toFloat(), y.toFloat(), z.toFloat())) assertTrue(cdg.hasCubeAt(x + under, y + under, z + under)) } } } assertTrue(cdg.hasCubeAt(0f, 0f, 0f)) assertFalse(cdg.hasCubeAt(-0.01f, -0.01f, -0.01f)) assertFalse(cdg.hasCubeAt(-0.01f, 1f, 1f)) assertFalse(cdg.hasCubeAt(width.toFloat(), height.toFloat(), depth.toFloat())) assertFalse(cdg.hasCubeAt(width + 0.01f, height + 0.01f, depth + 0.01f)) } @Test fun getNeighbor() { val width = CubeDataGrid.width val height = CubeDataGrid.height val depth = CubeDataGrid.depth val origin = Vector3(50f, 25f, 12f) val grid = CubeDataGrid.create(origin.x, origin.y, origin.z) assertTrue(grid.hasCubeAt(origin)) assertTrue(grid.hasCubeAt(origin.x + width-1, origin.y + height-1, origin.z + depth-1)) assertFalse(grid.hasCubeAt(-100f, -100f, -100f)) assertFalse(grid.hasCubeAt(0f, 0f, 0f)) assertFalse(grid.hasCubeAt(origin.x + width, origin.y + height, origin.z + depth)) assertFalse(grid.hasCubeAt(origin.x - 1, origin.y - 1, origin.z - 1)) val iv = IntVector3().set(origin) for (x in iv.x..iv.x+width-1) { for (y in iv.y..iv.y+height-1) { for (z in iv.z..iv.z+depth-1) { assertTrue(grid.hasCubeAt(x.toFloat(), y.toFloat(), z.toFloat())) assertNotNull(grid.getCubeAt(x.toFloat(), y.toFloat(), z.toFloat())) } } } } @Test fun chunkElevation() { val cdg = basicCDG() val maxElevation = 5 for (cube in cdg) { if(cube.yf > maxElevation) { cube.cubeType = CubeType.Void } else { cube.cubeType = CubeType.Grass } } fun CubeDataGrid.test(x: Float, z: Float, expected: Int) { assertEquals(expected, this.getElevation(x, z)) } val sz = Chunk.chunkSize println("chunk size: $sz") cdg.test(0f, 0f, maxElevation) cdg.test(0f, sz-1f, maxElevation) cdg.test(sz-1f, 0f, maxElevation) cdg.test(sz/2f, sz/2f, maxElevation) for (x in 0..sz-1) { for (z in 0..sz-1) { cdg.test(x.toFloat(), z.toFloat(), expected = maxElevation) } } val cdg2 = basicCDG() cdg2.forEach { it.cubeType = CubeType.Grass } cdg2.getCubeAt(0f, 5f, 0f).cubeType = CubeType.Void cdg2.test(0f, 0f, expected = sz-1) cdg2.getCubeAt(0f, 3f, 0f).cubeType = CubeType.Void cdg2.test(0f, 0f, expected = sz-1) } } class WorldTest { fun createWorld(w: Int, h: Int, d: Int): World { val w = World(w, h, d) world = w w.updatesEnabled = false w.createAllChunks() return w } @Test fun chunkDivisionCubeCount() { fun testCubeCount(szMult: Int) { val sz = szMult * Chunk.chunkSize if (sz % Chunk.chunkSize != 0) { throw GdxRuntimeException("Invalid world size, world size must be divisible by chunk size") } val world = createWorld(sz, sz, sz) val expectedTotalCubes = sz * sz * sz var ct = 0 world.chunks.forEach { ct += it.dataGrid.numElements } val totalCubes = ct //val totalCubes = world.chunks.fold(0, {(value: Int, chunk: Chunk!) -> value + chunk.dataGrid.numElements }) assertEquals(expectedTotalCubes, totalCubes) } for (worldSize in 1..4) { testCubeCount(worldSize) } } @Test fun chunkDivisionChunkCount() { fun assertCounts(world: World, xCount: Int, yCount: Int, zCount: Int) { //println("world: ${world.width}, ${world.height}, ${world.depth}") assertEquals(world.numChunksX, xCount) assertEquals(world.numChunksY, yCount) assertEquals(world.numChunksZ, zCount) } val sz = Chunk.chunkSize var w = createWorld(sz, sz, sz) assertCounts(w, 1, 1, 1) w = createWorld(sz*2, sz, sz) assertCounts(w, 2, 1, 1) w = createWorld(sz, sz*2, sz) assertCounts(w, 1, 2, 1) w = createWorld(sz, sz, sz*2) assertCounts(w, 1, 1, 2) w = createWorld(sz*10, sz*5, sz*3) assertCounts(w, 10, 5, 3) } @Test fun crossChunkGetNeighbor() { val sz = Chunk.chunkSize var world = createWorld(sz, sz, sz) fun testNeighbor(x: Float, y: Float, z: Float) { assertTrue(world.hasCubeAt(x, y, z)) assertNotNull(world.getCubeAt(x, y, z)) } testNeighbor(0f, 0f, 0f) testNeighbor(0.1f, 0.1f, 0.1f) testNeighbor(7f, 7f, 7f) val lo = sz-0.01f testNeighbor(lo, lo, lo) assertFalse(world.hasCubeAt(sz+0.1f, 0f, 0f)) assertFalse(world.hasCubeAt(0f, sz+0.1f, 0f)) assertFalse(world.hasCubeAt(0f, 0f, sz+0.1f)) assertFalse(world.hasCubeAt(-0.1f, -0.1f, -0.1f)) world = createWorld(17, 17, 17) for (y in 0..16) { for (x in 0..16) { for (z in 0..16) { testNeighbor(x.toFloat(), y.toFloat(), z.toFloat()) } } } } @Test fun hiddenFaces() { fun createTestWorld(w: Int, h: Int, d: Int): World { val wor = createWorld(w, h, d) wor.calculateHiddenFaces() return wor } fun World.testHiddenFaces(x: Float, y: Float, z: Float, expected: Int) { val cube = this.getCubeAt(x, y, z) //println("CUBE AT ${cube.getPositionTempVec()}") //println(cube.debugHiddenFaces) assertEquals(expected, this.getCubeAt(x, y, z).hiddenFacesCount) } val sz = 32 val max = sz-1.toFloat() val testWorld = createTestWorld(sz, sz, sz) //println("world chunks: ${testWorld.chunks.size}") var total = 0 //print("hidden faces per chunk: ") for (chunk in testWorld.chunks) { chunk.dataGrid.calculateHiddenFaces(testWorld) var subTotal = chunk.dataGrid.numberOfHiddenFaces() //print(", $subTotal") total += subTotal } //println("\ntotal hidden faces in world: $total") testWorld.testHiddenFaces(0f, 0f, 0f, expected = 3) testWorld.testHiddenFaces(1f, 0f, 0f, expected = 4) testWorld.testHiddenFaces(0f, 1f, 0f, expected = 4) testWorld.testHiddenFaces(0f, 0f, 1f, expected = 4) testWorld.testHiddenFaces(1f, 1f, 0f, expected = 5) testWorld.testHiddenFaces(1f, 1f, 1f, expected = 6) testWorld.testHiddenFaces(max-1, max-1, max-1, expected = 6) testWorld.testHiddenFaces(max, max, max, expected = 3) val world2 = createTestWorld(128, 16, 16) world2.testHiddenFaces(0f, 0f, 0f, expected = 3) world2.testHiddenFaces(127.5f, 0f, 0f, expected = 3) world2.testHiddenFaces(127.5f, 15.5f, 15.5f, expected = 3) world2.testHiddenFaces(15.5f, 15.5f, 15.5f, expected = 3) world2.testHiddenFaces(15.0f, 15.0f, 8.0f, expected = 4) } @Test fun testChunkSnapping() { // world size is actually irrelvant to this test, see world.snapToChunkCenter method contents for details val w = createWorld(8, 8, 8) val v = Vector3() val sz = Chunk.chunkSize val szf = sz.toFloat() val origin = Vector3() val delta = 0.00001f fun test() { assertEquals(origin.x, w.snapToChunkOrigin(v.x), delta) assertEquals(origin.y, w.snapToChunkOrigin(v.y), delta) assertEquals(origin.z, w.snapToChunkOrigin(v.z), delta) val centerOffset = Chunk.chunkSize / 2f assertEquals(centerOffset + origin.x, w.snapToChunkCenter(v.x), delta) assertEquals(centerOffset + origin.y, w.snapToChunkCenter(v.y), delta) assertEquals(centerOffset + origin.z, w.snapToChunkCenter(v.z), delta) } if (sz < 4) { throw GdxRuntimeException("this test depends on chunk size being >= 8") } origin.set(0f, 0f, 0f) v.set(1.12f, 2.98f, 3.84f) test() origin.set(0f, 0f, 0f) v.set(sz-0.1f, sz-0.1f, sz-0.1f) test() origin.set(szf, szf, szf) v.set(szf, szf, szf) test() origin.set(szf, szf, szf) v.set(szf+0.01f, szf+0.01f, szf+0.01f) test() origin.set(0f, 0f, 0f) v.set(szf-0.01f, szf-0.01f, szf-0.01f) test() origin.set(128f, 128f, 128f) v.set(129f, 129f, 130f) test() } @Test fun hasCube_and_hasChunk() { val sz = 32 val w = createWorld(sz, sz, sz) val max = sz-1 fun testHas(x: Float, y: Float, z: Float) { assertTrue("xyz: $x, $y, $z", w.hasChunkAt(x, y, z)) assertTrue("xyz: $x, $y, $z", w.hasCubeAt(x, y, z)) } fun testHasNot(x: Float, y: Float, z: Float) { assertFalse("xyz: $x, $y, $z", w.hasChunkAt(x, y, z)) assertFalse("xyz: $x, $y, $z", w.hasCubeAt(x, y, z)) } for (xi in 0..max) { for (yi in 0..max) { for (zi in 0..max) { val x = xi.toFloat() val y = yi.toFloat() val z = zi.toFloat() testHas(x, y, z) } } } testHas(0f, 0f, 0f) testHasNot(-0.01f, -0.01f, -0.01f) testHas(0.05f, 0.05f, 0.05f) testHasNot(max + 1.1f, max + 1.1f, max + 1.1f) val fsz = sz.toFloat() testHasNot(fsz, fsz, fsz) } @Test fun getCube() { val sz = 32 val max = sz-1 val w = createWorld(sz, sz, sz) val tmp = Vector3() fun Float.i(): Int = MathUtils.floor(this) // snap float values to integer before comparing fun equivalentAsIntegers(v1: Vector3, v2: Vector3) { assertTrue(v1.x.i() == v2.x.i()) assertTrue(v1.y.i() == v2.y.i()) assertTrue(v1.z.i() == v2.z.i()) } fun test(x: Float, y: Float, z: Float) { val cube = w.getCubeAt(x, y, z) tmp.set(x, y, z) equivalentAsIntegers(tmp, cube.getPositionTempVec()) } for (x in 0..max) { for (y in 0..max) { for (z in 0..max) { test(x + 0f, y + 0f, z + 0f) test(x + 0.95f, y + 0.95f, z + 0.95f) test(x + 0.01f, y + 0.01f, z + 0.01f) } } } } @Test fun getChunk() { val sz = 32 val max = sz-1 val w = createWorld(sz, sz, sz) fun test(x: Float, y: Float, z: Float) { val chunk = w.getChunkAt(x, y, z) val worldCube = w.getCubeAt(x, y, z) val chunkCube = chunk.dataGrid.getCubeAt(x, y, z) assertEquals(worldCube, chunkCube) assertTrue(worldCube == chunkCube) } for (x in 0..max) { for (y in 0..max) { for (z in 0..max) { test(x + 0f, y + 0f, z + 0f) test(x + 0.95f, y + 0.95f, z + 0.95f) test(x + 0.01f, y + 0.01f, z + 0.01f) } } } } }
apache-2.0
NephyProject/Penicillin
src/main/kotlin/jp/nephy/penicillin/endpoints/WelcomeMessageRules.kt
1
2007
/* * The MIT License (MIT) * * Copyright (c) 2017-2019 Nephy Project Team * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ @file:Suppress("UNUSED") package jp.nephy.penicillin.endpoints import jp.nephy.penicillin.core.session.ApiClient import jp.nephy.penicillin.core.session.ApiClientDsl /** * Returns [WelcomeMessageRules] endpoint instance. * [Twitter API reference](https://developer.twitter.com/en/docs/direct-messages/welcome-messages/overview) * * @return New [WelcomeMessageRules] endpoint instance. * @receiver Current [ApiClient] instance. */ @ApiClientDsl val ApiClient.welcomeMessageRules: WelcomeMessageRules get() = WelcomeMessageRules(this) /** * Collection of api endpoints related to Welcome Message Rules. * * @constructor Creates new [WelcomeMessageRules] endpoint instance. * @param client Current [ApiClient] instance. * @see ApiClient.welcomeMessageRules */ class WelcomeMessageRules(override val client: ApiClient): Endpoint
mit
oxoooo/excited-android
app/src/main/java/ooo/oxo/excited/database/QuerySQL.kt
1
1280
package ooo.oxo.excited.database /** * Created by seasonyuu on 2016/12/20. */ class QuerySQL { companion object { val createFavorite = """ create table favorite( user_id text, token text, id text, title text, cover text, head_icon text, head_name text, author_name text, description text, source text, link text, remains integer, sum integer, timestamp integer, type text, uuid text, refined integer, distance text, ratio text, primary key(user_id,token,id) ) """ @JvmStatic fun selectFavorite(token: String, id: String): String { return """ select * from favorite where token = "$token" and user_id = "$id" order by timestamp desc """ } @JvmStatic fun createFavorite(): String { return createFavorite } } }
gpl-3.0
Camano/CoolKotlin
games/rps.kt
1
3356
import java.util.* /********************************************** * Simple game made by Frekvens1 * - Version 1.1 * - Self explaining code * - Made for newer developers to learn more * Changelog * 1.1: * - Bug fixes * - Added more inputs * - Increased readability * - Optimized some functions * - Added changelog and credits * Credits - Thanks for testing my code! * Shlvam Rawat & Sasha_Kuprii * - Shortened the inputs to "r, p, s" * Ivan * - Made me convert to switch, as its more correct usage. * Gabriel Carvalho * - Bug hunter: "NoSuchElementException" when input was null * Alexandre da Costa Leite * - Bug hunter: Changing from && to || in function check for win * - Important change if converting this to multiplayer * Uploaded 19.07.2016 (DDMMYYYY) * Last updated 04.02.2017 (DDMMYYYY) */ fun main(args: Array<String>) { try { val sc = Scanner(System.`in`) if (sc.hasNext()) { //Checks for null values val userInput = quickFormat(sc.next()) sc.close() if (isValid(userInput)) { game(userInput) } else { displayInputs() } } else { displayInputs() //Null value, displaying correct inputs } } catch (e: Exception) { e.printStackTrace() } } fun game(user: String) { val computer = computerResults() print("$user vs $computer\n") if (user.equals(computer, ignoreCase = true)) { print("Stalemate! No winners.") } else { if (checkWin(user, computer)) { print("You won against the computer!") } else { print("You lost against the computer!") } } } fun computerResults(): String { val types = arrayOf("rock", "paper", "scissors") val rand = Random() val computerChoice = rand.nextInt(3) return types[computerChoice] } fun isValid(input: String): Boolean { when (input.toLowerCase()) { "rock" -> return true "paper" -> return true "scissors" -> return true else -> return false } } fun checkWin(user: String, opponent: String): Boolean { if (!isValid(user) || !isValid(opponent)) { return false } val rock = "rock" val paper = "paper" val scissors = "scissors" if (user.equals(rock, ignoreCase = true) && opponent.equals(scissors, ignoreCase = true)) { return true } if (user.equals(scissors, ignoreCase = true) && opponent.equals(paper, ignoreCase = true)) { return true } if (user.equals(paper, ignoreCase = true) && opponent.equals(rock, ignoreCase = true)) { return true } return false //If no possible win, assume loss. } /********************************************** * Libraries */ fun displayInputs() { //One place to edit it all! print("Invalid user input!\nWrite rock, paper or scissors!") } fun print(text: String) { //Makes printing text easier println(text) } fun quickFormat(input: String): String { //Just some quick function to shorten inputs. var output = input when (input.toLowerCase()) { "r" -> output = "rock" "p" -> output = "paper" "s" -> output = "scissors" "scissor" -> output = "scissors" } return output }
apache-2.0
google/private-compute-libraries
java/com/google/android/libraries/pcc/chronicle/api/DataTypeDescriptorSet.kt
1
3440
/* * Copyright 2022 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.libraries.pcc.chronicle.api import kotlin.reflect.KClass /** Collection of [DataTypeDescriptors][DataTypeDescriptor]. */ interface DataTypeDescriptorSet { /** * Returns the [DataTypeDescriptor] with the given [name], throws [IllegalArgumentException] if * none is found. */ operator fun get(name: String): DataTypeDescriptor = requireNotNull(getOrNull(name)) { "Could not find a DataTypeDescriptor for name: \"$name\"" } /** Returns the [DataTypeDescriptor] with the given [name], or `null` if none is found. */ fun getOrNull(name: String): DataTypeDescriptor? /** * Returns the [FieldType] for a field within the [DataTypeDescriptor] with the given [dtdName], * accessed via the provided [accessPath]. */ fun findFieldTypeOrThrow(dtdName: String, accessPath: List<String>): FieldType = findFieldTypeOrThrow(get(dtdName), accessPath) /** * Returns the [FieldType] for a field within the given [DataTypeDescriptor] accessed via the * provided [accessPath]. */ fun findFieldTypeOrThrow(dtd: DataTypeDescriptor, accessPath: List<String>): FieldType /** * Returns the [DataTypeDescriptor] associated with the provided [FieldType]. * * If the [FieldType] is a primitive or opaque value (or is yet otherwise unsupported), `null` is * returned. */ fun findDataTypeDescriptor(fieldType: FieldType): DataTypeDescriptor? /** Returns the [DataTypeDescriptor] for the given [KClass], or null if one is not known. */ fun findDataTypeDescriptor(cls: KClass<*>): DataTypeDescriptor? /** * Returns the [Class] associated with the provided [FieldType]. * * If the [FieldType] represents a primitive, array, or list a constant type is returned. * * If it is a [FieldType.Reference] or [FieldType.Nested] type, its name is used to find the * [DataTypeDescriptor.cls] value of the [DataTypeDescriptor] with that name. * * If it's [FieldType.Opaque], its name is used in conjunction with [Class.forName] * - which has a possibility of throwing a [ClassNotFoundException] if the name is not present in * the classloader. * * If it's [FieldType.Nullable], the value of [findClass] for the non-nullable `itemFieldType` * value is returned. * * [IllegalArgumentException] is thrown for [FieldTypes][FieldType] not yet supported for * Cantrips. */ fun fieldTypeAsClass(fieldType: FieldType): Class<*> /** * Returns the [Class] associated with the [FieldType] located within the given * [DataTypeDescriptor] accessed via the provided [accessPath]. */ fun findFieldTypeAsClass(dtd: DataTypeDescriptor, accessPath: List<String>): Class<*> = fieldTypeAsClass(findFieldTypeOrThrow(dtd, accessPath)) /** Returns a representation as a regular Set. */ fun toSet(): Set<DataTypeDescriptor> }
apache-2.0
VerifAPS/verifaps-lib
exec/src/main/kotlin/edu/kit/iti/formal/automation/Flycheck.kt
1
6562
package edu.kit.iti.formal.automation import com.github.ajalt.clikt.core.CliktCommand import com.github.ajalt.clikt.parameters.arguments.argument import com.github.ajalt.clikt.parameters.arguments.multiple import com.github.ajalt.clikt.parameters.options.flag import com.github.ajalt.clikt.parameters.options.multiple import com.github.ajalt.clikt.parameters.options.option import com.github.ajalt.clikt.parameters.types.file import edu.kit.iti.formal.automation.analysis.ReportCategory import edu.kit.iti.formal.automation.analysis.ReportLevel import edu.kit.iti.formal.automation.analysis.Reporter import edu.kit.iti.formal.automation.analysis.ReporterMessage import edu.kit.iti.formal.automation.builtin.BuiltinLoader import edu.kit.iti.formal.automation.parser.IEC61131Lexer import edu.kit.iti.formal.automation.parser.IEC61131Parser import edu.kit.iti.formal.automation.parser.IECParseTreeToAST import edu.kit.iti.formal.automation.st.ast.PouElements import edu.kit.iti.formal.util.info import org.antlr.v4.runtime.* import org.antlr.v4.runtime.atn.ATNConfigSet import org.antlr.v4.runtime.dfa.DFA import java.io.File import java.util.* object Check { @JvmStatic fun main(args: Array<String>) = CheckApp().main(args) } object Flycheck { @JvmStatic fun main(args: Array<String>) { //println("{version:\"0.9\"}") val reader = System.`in`.bufferedReader() do { val line = reader.readLine() ?: break if (line.isEmpty()) continue CheckApp().main(parseArgs(line)) } while (true) } /** * from https://stackoverflow.com/questions/1082953/shlex-alternative-for-java * license. unlicense/public domain */ @JvmStatic fun parseArgs(argString: CharSequence): List<String> { val tokens = ArrayList<String>() var escaping = false var quoteChar = ' ' var quoting = false var current = StringBuilder() for (i in 0 until argString.length) { val c = argString[i] if (escaping) { current.append(c) escaping = false } else if (c == '\\' && !(quoting && quoteChar == '\'')) { escaping = true } else if (quoting && c == quoteChar) { quoting = false } else if (!quoting && (c == '\'' || c == '"')) { quoting = true quoteChar = c } else if (!quoting && Character.isWhitespace(c)) { if (current.length > 0) { tokens.add(current.toString()) current = StringBuilder() } } else { current.append(c) } } if (current.isNotEmpty()) { tokens.add(current.toString()) } return tokens } } class CheckApp : CliktCommand() { val verbose by option(help = "enable verbose mode").flag() val format by option("--json", help = "Flag for enabling json, line based format").flag() val include by option("-L", help = "folder for looking includes") .file() .multiple() val includeBuiltIn by option("-b", help = "") .flag("-B") val files by argument(name = "FILE", help = "Files to check") .file() .multiple() override fun run() { val base = if (includeBuiltIn) BuiltinLoader.loadDefault() else PouElements() val r = FlycheckRunner( files.map { CharStreams.fromFileName(it.absolutePath) }, base, verbose, format, include ) r.run() } } class FlycheckRunner( val streams: List<CharStream>, val library: PouElements = PouElements(), val verbose: Boolean = false, val json: Boolean = false, val includeStubs: List<File> = arrayListOf()) { val underInvestigation: PouElements = PouElements() private val reporter = Reporter() val messages: MutableList<ReporterMessage> get() = reporter.messages private val errorListener = MyAntlrErrorListener(reporter) fun run() { info("Start with parsing") streams.forEach { parse(it) } info("Resolving...") resolve() info("Checking...") check() info("Print.") printMessages() } fun parse(stream: CharStream) { val lexer = IEC61131Lexer(stream) val parser = IEC61131Parser(CommonTokenStream(lexer)) lexer.removeErrorListeners() parser.removeErrorListeners() parser.addErrorListener(errorListener) val ctx = parser.start() val tles = ctx.accept(IECParseTreeToAST()) as PouElements library.addAll(tles) underInvestigation.addAll(tles) } private fun resolve() { IEC61131Facade.resolveDataTypes(library) } fun check() { messages.addAll(IEC61131Facade.check(underInvestigation)) } private fun printMessages() { if (messages.isEmpty()) { if (json) { println("{ok:true}") } else { info("Everything is fine.") } } else { if (json) { val msg = messages.joinToString(",") { it.toJson() } print("[$msg]\n") System.out.flush() } else { messages.forEach { info(it.toHuman()) } } } } private fun printMessage(message: ReporterMessage) { } class MyAntlrErrorListener(private val reporter: Reporter) : ANTLRErrorListener { override fun syntaxError(recognizer: Recognizer<*, *>?, offendingSymbol: Any?, line: Int, charPositionInLine: Int, msg: String?, e: RecognitionException?) { val token = (offendingSymbol as Token) reporter.report(token, msg!!, ReportCategory.SYNTAX, ReportLevel.ERROR) } override fun reportAttemptingFullContext(recognizer: Parser?, dfa: DFA?, startIndex: Int, stopIndex: Int, conflictingAlts: BitSet?, configs: ATNConfigSet?) {} override fun reportAmbiguity(recognizer: Parser?, dfa: DFA?, startIndex: Int, stopIndex: Int, exact: Boolean, ambigAlts: BitSet?, configs: ATNConfigSet?) {} override fun reportContextSensitivity(recognizer: Parser?, dfa: DFA?, startIndex: Int, stopIndex: Int, prediction: Int, configs: ATNConfigSet?) {} } }
gpl-3.0
UweTrottmann/SeriesGuide
app/src/main/java/com/battlelancer/seriesguide/shows/overview/SeasonTools.kt
1
617
package com.battlelancer.seriesguide.shows.overview import android.content.Context import com.battlelancer.seriesguide.R object SeasonTools { fun hasSkippedTag(tags: String?): Boolean { return SeasonTags.SKIPPED == tags } /** * Builds a localized string like "Season 5" or if the number is 0 "Special Episodes". */ fun getSeasonString(context: Context, seasonNumber: Int): String { return if (seasonNumber == 0) { context.getString(R.string.specialseason) } else { context.getString(R.string.season_number, seasonNumber) } } }
apache-2.0
MaridProject/marid
marid-moans/src/main/kotlin/org/marid/moan/Prop.kt
1
932
/* * MARID, the visual component programming environment. * Copyright (C) 2020 Dzmitry Auchynnikau * * This program 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. * * 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package org.marid.moan @Target(AnnotationTarget.VALUE_PARAMETER) @Retention(AnnotationRetention.RUNTIME) annotation class Prop( val value: String = "" )
agpl-3.0
AlmasB/FXGL
fxgl-controllerinput/src/main/kotlin/com/almasb/fxgl/controllerinput/ControllerInputService.kt
1
4047
/* * FXGL - JavaFX Game Library. The MIT License (MIT). * Copyright (c) AlmasB ([email protected]). * See LICENSE for details. */ package com.almasb.fxgl.controllerinput import com.almasb.fxgl.controllerinput.impl.GameControllerImpl import com.almasb.fxgl.core.EngineService import com.almasb.fxgl.core.Inject import com.almasb.fxgl.core.util.Platform import com.almasb.fxgl.core.util.Platform.* import com.almasb.fxgl.logging.Logger import javafx.collections.FXCollections import javafx.collections.ObservableList import java.nio.file.Files import java.nio.file.Paths /** * Provides access to game controllers. Currently support is limited: no hot-swaps/reloads and * the controller(s) must be plugged in before the start of the engine. * * @author Almas Baimagambetov ([email protected]) */ class ControllerInputService : EngineService() { private val log = Logger.get(javaClass) @Inject("platform") private lateinit var platform: Platform private var isNativeLibLoaded = false private val resourceDirNames = hashMapOf( WINDOWS to "windows64", LINUX to "linux64", MAC to "mac64" ) private val nativeLibNames = hashMapOf( WINDOWS to listOf("SDL2.dll", "fxgl_controllerinput.dll"), LINUX to listOf("libSDL2.so", "libfxgl_controllerinput.so") ) private val controllers = FXCollections.observableArrayList<GameController>() val gameControllers: ObservableList<GameController> by lazy { FXCollections.unmodifiableObservableList(controllers) } override fun onInit() { try { log.debug("Loading nativeLibs for $platform") // copy native libs to cache if needed // use openjfx dir since we know it is (will be) there val fxglCacheDir = Paths.get(System.getProperty("user.home")).resolve(".openjfx").resolve("cache").resolve("fxgl-11") if (Files.notExists(fxglCacheDir)) { log.debug("Creating FXGL native libs cache: $fxglCacheDir") Files.createDirectories(fxglCacheDir) } nativeLibNames[platform]?.forEach { libName -> val nativeLibPath = fxglCacheDir.resolve(libName) if (Files.notExists(nativeLibPath)) { log.debug("Copying $libName into cache") val dirName = resourceDirNames[platform]!! javaClass.getResource("/nativeLibs/$dirName/$libName").openStream().use { Files.copy(it, nativeLibPath) } } log.debug("Loading $nativeLibPath") System.load(nativeLibPath.toAbsolutePath().toString()) } isNativeLibLoaded = true log.debug("Successfully loaded nativeLibs. Calling to check back-end version.") val version = GameControllerImpl.getBackendVersion() log.info("Controller back-end version: $version") log.debug("Connecting to plugged-in controllers") val numControllers = GameControllerImpl.connectControllers() if (numControllers > 0) { log.debug("Successfully connected to $numControllers controller(s)") } else { log.debug("No controllers found") } for (id in 0 until numControllers) { controllers += GameController(id) } } catch (e: Exception) { log.warning("Loading nativeLibs for controller support failed", e) log.warning("Printing stacktrace:") e.printStackTrace() } } override fun onUpdate(tpf: Double) { if (!isNativeLibLoaded || controllers.isEmpty()) return GameControllerImpl.updateState(0); controllers.forEach { it.update() } } override fun onExit() { if (!isNativeLibLoaded || controllers.isEmpty()) return GameControllerImpl.disconnectControllers() } }
mit
joseph-roque/BowlingCompanion
app/src/main/java/ca/josephroque/bowlingcompanion/statistics/impl/firstball/SplitsStatistic.kt
1
1313
package ca.josephroque.bowlingcompanion.statistics.impl.firstball import android.content.SharedPreferences import android.os.Parcel import ca.josephroque.bowlingcompanion.R import ca.josephroque.bowlingcompanion.common.interfaces.parcelableCreator import ca.josephroque.bowlingcompanion.games.lane.Deck import ca.josephroque.bowlingcompanion.games.lane.isSplit import ca.josephroque.bowlingcompanion.settings.Settings /** * Copyright (C) 2018 Joseph Roque * * Percentage of shots which are splits. */ class SplitsStatistic(numerator: Int = 0, denominator: Int = 0) : FirstBallStatistic(numerator, denominator) { companion object { @Suppress("unused") @JvmField val CREATOR = parcelableCreator(::SplitsStatistic) const val Id = R.string.statistic_splits } override val titleId = Id override val id = Id.toLong() private var countS2asS: Boolean = Settings.BooleanSetting.CountS2AsS.default // MARK: Statistic override fun isModifiedBy(deck: Deck) = deck.isSplit(countS2asS) override fun updatePreferences(preferences: SharedPreferences) { countS2asS = Settings.BooleanSetting.CountS2AsS.getValue(preferences) } // MARK: Constructors private constructor(p: Parcel): this(numerator = p.readInt(), denominator = p.readInt()) }
mit
AsynkronIT/protoactor-kotlin
proto-mailbox/src/main/kotlin/actor/proto/mailbox/MailboxProducers.kt
1
2333
package actor.proto.mailbox import org.jctools.queues.MpscArrayQueue import org.jctools.queues.MpscGrowableArrayQueue import org.jctools.queues.MpscLinkedQueue8 import org.jctools.queues.MpscUnboundedArrayQueue import org.jctools.queues.QueueFactory.newQueue import org.jctools.queues.atomic.MpscAtomicArrayQueue import org.jctools.queues.atomic.MpscGrowableAtomicArrayQueue import org.jctools.queues.atomic.MpscUnboundedAtomicArrayQueue import org.jctools.queues.spec.ConcurrentQueueSpec import java.util.concurrent.ConcurrentLinkedQueue private val emptyStats : Array<MailboxStatistics> = arrayOf() fun newUnboundedMailbox(stats: Array<MailboxStatistics> = emptyStats): Mailbox = DefaultMailbox(ConcurrentLinkedQueue<Any>(), ConcurrentLinkedQueue<Any>(), stats) fun newMpscAtomicArrayMailbox(capacity: Int = 1000, stats: Array<MailboxStatistics> = emptyStats): Mailbox = DefaultMailbox(ConcurrentLinkedQueue<Any>(), MpscAtomicArrayQueue(capacity), stats) fun newMpscArrayMailbox(capacity: Int = 1000, stats: Array<MailboxStatistics> = emptyStats): Mailbox = DefaultMailbox(ConcurrentLinkedQueue<Any>(), MpscArrayQueue(capacity), stats) fun newMpscUnboundedArrayMailbox(chunkSize: Int = 5, stats: Array<MailboxStatistics> = emptyStats): Mailbox = DefaultMailbox(ConcurrentLinkedQueue<Any>(), MpscUnboundedArrayQueue(chunkSize), stats) fun newMpscUnboundedAtomicArrayMailbox(chunkSize: Int = 5, stats: Array<MailboxStatistics> = emptyStats): Mailbox = DefaultMailbox(ConcurrentLinkedQueue<Any>(), MpscUnboundedAtomicArrayQueue(chunkSize), stats) fun newMpscGrowableArrayMailbox(initialCapacity: Int = 5, stats: Array<MailboxStatistics> = emptyStats): Mailbox = DefaultMailbox(ConcurrentLinkedQueue<Any>(), MpscGrowableArrayQueue(initialCapacity, 2 shl 11), stats) fun newMpscGrowableAtomicArrayMailbox(initialCapacity: Int = 5, stats: Array<MailboxStatistics> = emptyStats): Mailbox = DefaultMailbox(ConcurrentLinkedQueue<Any>(), MpscGrowableAtomicArrayQueue(initialCapacity, 2 shl 11), stats) fun newMpscLinkedMailbox(stats: Array<MailboxStatistics> = emptyStats): Mailbox = DefaultMailbox(ConcurrentLinkedQueue<Any>(), MpscLinkedQueue8(), stats) fun newSpecifiedMailbox(spec:ConcurrentQueueSpec, stats: Array<MailboxStatistics> = emptyStats): Mailbox = DefaultMailbox(ConcurrentLinkedQueue<Any>(), newQueue(spec) , stats)
apache-2.0
AsynkronIT/protoactor-kotlin
proto-remote/src/main/kotlin/actor/proto/remote/EndpointManager.kt
1
2120
package actor.proto.remote import actor.proto.Actor import actor.proto.Context import actor.proto.PID import actor.proto.Props import actor.proto.RestartStatistics import actor.proto.Started import actor.proto.Supervisor import actor.proto.SupervisorStrategy import actor.proto.fromProducer import mu.KotlinLogging private val logger = KotlinLogging.logger {} class EndpointManager(private val config: RemoteConfig) : Actor, SupervisorStrategy { private val _connections: HashMap<String, Endpoint> = HashMap() suspend override fun Context.receive(msg: Any) { when (msg) { is Started -> logger.info("Started EndpointManager") is EndpointTerminatedEvent -> ensureConnected(msg.address).watcher.let { send(it,msg) } is RemoteTerminate -> ensureConnected(msg.watchee.address).watcher.let {send(it,msg) } is RemoteWatch -> ensureConnected(msg.watchee.address).watcher.let { send(it,msg) } is RemoteUnwatch -> ensureConnected(msg.watchee.address).watcher.let { send(it,msg) } is RemoteDeliver -> ensureConnected(msg.target.address).writer.let { send(it,msg) } else -> { } } } override fun handleFailure(supervisor: Supervisor, child: PID, rs: RestartStatistics, reason: Exception) { supervisor.restartChildren(reason, child) } private fun Context.ensureConnected(address: String): Endpoint = _connections.getOrPut(address, { val writer: PID = spawnWriter(address) val watcher: PID = spawnWatcher(address) Endpoint(writer, watcher) }) private fun Context.spawnWriter(address: String): PID { val writerProps: Props = fromProducer { EndpointWriter(address, config) }.withMailbox { EndpointWriterMailbox(config.endpointWriterBatchSize) } val writer: PID = spawnChild(writerProps) return writer } private fun Context.spawnWatcher(address: String): PID { val watcherProps: Props = fromProducer { EndpointWatcher(address) } val watcher: PID = spawnChild(watcherProps) return watcher } }
apache-2.0
RP-Kit/RPKit
bukkit/rpk-characters-bukkit/src/main/kotlin/com/rpkit/characters/bukkit/listener/PlayerMoveListener.kt
1
2042
/* * Copyright 2021 Ren Binden * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.rpkit.characters.bukkit.listener import com.rpkit.characters.bukkit.RPKCharactersBukkit import com.rpkit.characters.bukkit.character.RPKCharacterService import com.rpkit.core.service.Services import com.rpkit.players.bukkit.profile.minecraft.RPKMinecraftProfileService import org.bukkit.Location import org.bukkit.event.EventHandler import org.bukkit.event.Listener import org.bukkit.event.player.PlayerMoveEvent /** * Player move listener for preventing players from moving about with a dead character. */ class PlayerMoveListener(private val plugin: RPKCharactersBukkit) : Listener { @EventHandler fun onPlayerMove(event: PlayerMoveEvent) { val minecraftProfileService = Services[RPKMinecraftProfileService::class.java] ?: return val characterService = Services[RPKCharacterService::class.java] ?: return val minecraftProfile = minecraftProfileService.getPreloadedMinecraftProfile(event.player) ?: return val character = characterService.getPreloadedActiveCharacter(minecraftProfile) if (character == null || !character.isDead) return if (event.from.blockX == event.to?.blockX && event.from.blockZ == event.to?.blockZ) return event.player.teleport(Location(event.from.world, event.from.blockX + 0.5, event.from.blockY + 0.5, event.from.blockZ.toDouble(), event.from.yaw, event.from.pitch)) event.player.sendMessage(plugin.messages["dead-character"]) } }
apache-2.0
cketti/k-9
backend/testing/src/main/java/app/k9mail/backend/testing/InMemoryBackendStorage.kt
1
2254
package app.k9mail.backend.testing import com.fsck.k9.backend.api.BackendFolderUpdater import com.fsck.k9.backend.api.BackendStorage import com.fsck.k9.backend.api.FolderInfo import com.fsck.k9.mail.FolderType class InMemoryBackendStorage : BackendStorage { val folders: MutableMap<String, InMemoryBackendFolder> = mutableMapOf() val extraStrings: MutableMap<String, String> = mutableMapOf() val extraNumbers: MutableMap<String, Long> = mutableMapOf() override fun getFolder(folderServerId: String): InMemoryBackendFolder { return folders[folderServerId] ?: error("Folder $folderServerId not found") } override fun getFolderServerIds(): List<String> { return folders.keys.toList() } override fun createFolderUpdater(): BackendFolderUpdater { return InMemoryBackendFolderUpdater() } override fun getExtraString(name: String): String? = extraStrings[name] override fun setExtraString(name: String, value: String) { extraStrings[name] = value } override fun getExtraNumber(name: String): Long? = extraNumbers[name] override fun setExtraNumber(name: String, value: Long) { extraNumbers[name] = value } private inner class InMemoryBackendFolderUpdater : BackendFolderUpdater { override fun createFolders(folders: List<FolderInfo>) { folders.forEach { folder -> if ([email protected](folder.serverId)) { error("Folder ${folder.serverId} already present") } [email protected][folder.serverId] = InMemoryBackendFolder(folder.name, folder.type) } } override fun deleteFolders(folderServerIds: List<String>) { for (folderServerId in folderServerIds) { folders.remove(folderServerId) ?: error("Folder $folderServerId not found") } } override fun changeFolder(folderServerId: String, name: String, type: FolderType) { val folder = folders[folderServerId] ?: error("Folder $folderServerId not found") folder.name = name folder.type = type } override fun close() = Unit } }
apache-2.0
nickthecoder/tickle
tickle-core/src/main/kotlin/uk/co/nickthecoder/tickle/resources/Resources.kt
1
5096
/* Tickle Copyright (C) 2017 Nick Robinson This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package uk.co.nickthecoder.tickle.resources import uk.co.nickthecoder.tickle.* import uk.co.nickthecoder.tickle.events.CompoundInput import uk.co.nickthecoder.tickle.graphics.Texture import uk.co.nickthecoder.tickle.sound.Sound import java.io.File import java.lang.IllegalStateException open class Resources { var file: File = File("") val resourceDirectory: File get() = file.parentFile ?: File(".").absoluteFile val gameInfo = GameInfo("Tickle", "ticklegame", 600, 400, fullScreen = false, resizable = false) val preferences = EditorPreferences() val textures = ResourceMap<Texture>(this) val poses = ResourceMap<Pose>(this) val costumes = ResourceMap<Costume>(this) val costumeGroups = ResourceMap<CostumeGroup>(this) val inputs = ResourceMap<CompoundInput>(this) val layouts = ResourceMap<Layout>(this) val fontResources = ResourceMap<FontResource>(this) val sounds = ResourceMap<Sound>(this) val sceneDirectory: File get() = File(file.parentFile, "scenes").absoluteFile val texturesDirectory: File get() = File(file.parentFile, "images").absoluteFile val listeners = mutableListOf<ResourcesListener>() init { instance = this } open fun save() { throw IllegalStateException("Resources are read-only") } open fun createAttributes(): Attributes { return RuntimeAttributes() } fun findName(resource: Any): String? { return when (resource) { is Texture -> textures.findName(resource) is Pose -> poses.findName(resource) is Costume -> costumes.findName(resource) is CostumeGroup -> costumeGroups.findName(resource) is CompoundInput -> inputs.findName(resource) is Layout -> layouts.findName(resource) is FontResource -> fontResources.findName(resource) is SceneStub -> resource.name else -> null } } fun findCostumeGroup(costumeName: String): CostumeGroup? { costumeGroups.items().values.forEach { costumeGroup -> if (costumeGroup.find(costumeName) != null) { return costumeGroup } } return null } fun toPath(file: File): String { try { return file.absoluteFile.toRelativeString(resourceDirectory) } catch(e: Exception) { return file.absolutePath } } fun fromPath(path: String): File { return resourceDirectory.resolve(path).absoluteFile } fun scenePathToFile(path: String): File { return sceneDirectory.resolve(path + ".scene") } fun sceneFileToPath(file: File): String { val path = if (file.isAbsolute) { file.relativeToOrSelf(sceneDirectory).path } else { file.path } if (path.endsWith(".scene")) { return path.substring(0, path.length - 6) } else { return path } } fun fireAdded(resource: Any, name: String) { listeners.toList().forEach { it.resourceAdded(resource, name) } } fun fireRemoved(resource: Any, name: String) { listeners.toList().forEach { it.resourceRemoved(resource, name) } } fun fireRenamed(resource: Any, oldName: String, newName: String) { listeners.toList().forEach { it.resourceRenamed(resource, oldName, newName) } } fun fireChanged(resource: Any) { listeners.toList().forEach { it.resourceChanged(resource) } } /** * Reloads the textures, sounds and fonts. */ fun reload() { textures.items().values.forEach { it.reload() } sounds.items().values.forEach { it.reload() } fontResources.items().values.forEach { it.reload() } } fun scriptDirectory() = File(file.parentFile.absoluteFile, "scripts") fun fxcoderDirectory() = File(file.parentFile.absoluteFile, "fxcoder") fun destroy() { textures.items().values.forEach { it.destroy() } fontResources.items().values.forEach { it.destroy() } sounds.items().values.forEach { it.destroy() } } companion object { /** * A convenience, so that game scripts can easily get access to the resources. */ lateinit var instance: Resources } }
gpl-3.0
takuji31/Koreference
koreference/src/main/java/jp/takuji31/koreference/type/Preference.kt
1
310
package jp.takuji31.koreference.type import android.content.SharedPreferences /** * Created by takuji on 2015/08/14. */ interface Preference<T : Any?> { operator fun get(pref: SharedPreferences, key: String, default: T): T operator fun set(editor: SharedPreferences.Editor, key: String, value: T) }
apache-2.0
nickthecoder/tickle
tickle-editor/src/main/kotlin/uk/co/nickthecoder/tickle/editor/scene/Layers.kt
1
6449
/* Tickle Copyright (C) 2017 Nick Robinson This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package uk.co.nickthecoder.tickle.editor.scene import javafx.event.EventHandler import javafx.scene.control.CheckMenuItem import javafx.scene.control.MenuButton import javafx.scene.control.MenuItem import javafx.scene.control.SeparatorMenuItem import javafx.scene.image.ImageView import javafx.scene.input.MouseEvent import javafx.scene.layout.StackPane import uk.co.nickthecoder.tickle.editor.EditorAction import uk.co.nickthecoder.tickle.editor.resources.DesignJsonScene import uk.co.nickthecoder.tickle.editor.resources.DesignSceneResource import uk.co.nickthecoder.tickle.resources.LayoutView import uk.co.nickthecoder.tickle.resources.NoStageConstraint import uk.co.nickthecoder.tickle.resources.Resources import uk.co.nickthecoder.tickle.resources.StageConstraint import uk.co.nickthecoder.tickle.stage.StageView import uk.co.nickthecoder.tickle.stage.View import uk.co.nickthecoder.tickle.stage.ZOrderStageView /** */ class Layers(val sceneEditor: SceneEditor) { val stack = StackPane() private val allLayers = mutableListOf<Layer>() private val stageLayers = mutableListOf<StageLayer>() private val includedLayers = mutableMapOf<String, List<StageLayer>>() val glass = GlassLayer(sceneEditor) private val map = mutableMapOf<String, StageLayer>() val stageButton = MenuButton("no stage selected") var scale: Double = 1.0 set(v) { field = v allLayers.forEach { it.scale(v) } } var currentLayer: StageLayer? = null set(v) { field = v if (v == null) { stageButton.text = "<no stage selected>" } else { stageButton.text = v.stageName if (singleLayerMode.isSelected) { stageLayers.forEach { it.isLocked = true } } v.isLocked = false v.isVisible = true } } val singleLayerMode = CheckMenuItem("Single Layer Mode") init { stageButton.graphic = ImageView(EditorAction.imageResource("layers.png")) stageButton.items.add(singleLayerMode) stageButton.items.add(SeparatorMenuItem()) loadIncludes() val layout = Resources.instance.layouts.find(sceneEditor.sceneResource.layoutName) createStageLayers(sceneEditor.sceneResource).forEach { layer: StageLayer -> add(layer) stageLayers.add(layer) map[layer.stageName] = layer stageButton.items.add(createMenuItem(layer)) if (layout?.layoutStages?.get(layer.stageName)?.isDefault == true) { currentLayer = layer } } // If no stage was set as default, the use the first layer. if (currentLayer == null) { currentLayer = stageLayers.firstOrNull() } add(glass) } private fun createStageLayers(sceneResource: DesignSceneResource): List<StageLayer> { val result = mutableListOf<StageLayer>() sceneResource.stageResources.forEach { stageName, stageResource -> val layout = Resources.instance.layouts.find(sceneResource.layoutName)!! val constraintName = layout.layoutStages[stageName]?.stageConstraintString var constraint: StageConstraint = NoStageConstraint() try { constraint = Class.forName(constraintName).newInstance() as StageConstraint } catch(e: Exception) { System.err.println("WARNING : Failed to create the StageConstraint for stage $stageName. Using NoStageConstraint") } constraint.forStage(stageName, stageResource) val layoutView: LayoutView? = layout.layoutViews.values.firstOrNull() { it.stageName == stageName } val view: View? = layoutView?.createView() val stageView: StageView = if (view is StageView) view else ZOrderStageView() val layer = StageLayer(sceneResource, stageName, stageResource, stageView, constraint) result.add(layer) } return result } private fun loadIncludes() { sceneEditor.sceneResource.includes.forEach { include -> val includedSR = DesignJsonScene(include).sceneResource as DesignSceneResource val layers = mutableListOf<StageLayer>() includedLayers.put(include.nameWithoutExtension, layers) createStageLayers(includedSR).forEach { layer -> layer.isLocked = true layers.add(layer) add(layer) } } } fun names(): Collection<String> = map.keys fun stageLayer(name: String): StageLayer? = map[name] fun stageLayers(): List<StageLayer> = stageLayers fun editableLayers() = stageLayers.filter { it.isVisible && !it.isLocked } fun visibleLayers() = stageLayers.filter { it.isVisible } fun add(layer: Layer) { allLayers.add(layer) stack.children.add(layer.canvas) } fun createMenuItem(layer: StageLayer): MenuItem { val menuItem = MenuItem(layer.stageName) menuItem.onAction = EventHandler { stageButton.text = layer.stageName currentLayer = layer } return menuItem } fun viewX(event: MouseEvent): Double { return glass.centerX + (event.x - glass.canvas.width / 2) / scale } fun viewY(event: MouseEvent): Double { return glass.centerY + (glass.canvas.height / 2 - event.y) / scale } fun panBy(dx: Double, dy: Double) { allLayers.forEach { it.panBy(dx, dy) } } fun draw() { allLayers.forEach { it.draw() } } fun currentLayer(): StageLayer? { return currentLayer } }
gpl-3.0
coil-kt/coil
coil-base/src/main/java/coil/util/Calls.kt
1
1172
@file:JvmName("-Calls") package coil.util import java.io.IOException import kotlin.coroutines.resume import kotlin.coroutines.resumeWithException import kotlinx.coroutines.CancellableContinuation import kotlinx.coroutines.CompletionHandler import kotlinx.coroutines.suspendCancellableCoroutine import okhttp3.Call import okhttp3.Callback import okhttp3.Response internal suspend fun Call.await(): Response { return suspendCancellableCoroutine { continuation -> val callback = ContinuationCallback(this, continuation) enqueue(callback) continuation.invokeOnCancellation(callback) } } private class ContinuationCallback( private val call: Call, private val continuation: CancellableContinuation<Response> ) : Callback, CompletionHandler { override fun onResponse(call: Call, response: Response) { continuation.resume(response) } override fun onFailure(call: Call, e: IOException) { if (!call.isCanceled()) { continuation.resumeWithException(e) } } override fun invoke(cause: Throwable?) { try { call.cancel() } catch (_: Throwable) {} } }
apache-2.0
waicool20/SKrypton
src/main/kotlin/com/waicool20/skrypton/enums/KeyboardModifiers.kt
1
1768
/* * The MIT License (MIT) * * Copyright (c) SKrypton by waicool20 * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.waicool20.skrypton.enums // Extracted from qnamespace.h /** * Represents a keyboard modifier, see [here](http://doc.qt.io/qt-5/qt.html#KeyboardModifier-enum) * for more information. * * @property value A unique value assigned to the enum */ enum class KeyboardModifiers(val value: Long) { NoModifier(0x00000000), ShiftModifier(0x02000000), ControlModifier(0x04000000), AltModifier(0x08000000), MetaModifier(0x10000000), KeypadModifier(0x20000000), GroupSwitchModifier(0x40000000), // Do not extend the mask to include 0x01000000 KeyboardModifierMask(0xfe000000) }
mit
LorittaBot/Loritta
discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/morenitta/utils/extensions/LocaleExtensions.kt
1
540
package net.perfectdreams.loritta.morenitta.utils.extensions import net.perfectdreams.loritta.common.locale.BaseLocale import java.util.* /** * Returns the Java Locale (used for dates, etc) for the specified [BaseLocale] */ fun BaseLocale.toJavaLocale(): Locale { val localeId = this.id return Locale( when (localeId) { "default" -> "pt_BR" "pt-pt" -> "pt_PT" "en-us" -> "en_US" "es-es" -> "es_ES" else -> "pt_BR" } ) }
agpl-3.0
LorittaBot/Loritta
discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/cinnamon/discord/interactions/commands/options/LocalizedCommandOptions.kt
1
3957
package net.perfectdreams.loritta.cinnamon.discord.interactions.commands.options import dev.kord.common.Locale import dev.kord.common.entity.ChannelType import dev.kord.core.entity.Role import dev.kord.core.entity.User import dev.kord.core.entity.channel.Channel import net.perfectdreams.discordinteraktions.common.autocomplete.AutocompleteHandler import net.perfectdreams.discordinteraktions.common.commands.options.* import net.perfectdreams.i18nhelper.core.keydata.StringI18nData import net.perfectdreams.loritta.common.locale.LanguageManager import net.perfectdreams.loritta.common.utils.text.TextUtils.shortenWithEllipsis import net.perfectdreams.loritta.cinnamon.discord.utils.DiscordResourceLimits import net.perfectdreams.loritta.cinnamon.discord.utils.SlashTextUtils abstract class LocalizedCommandOption<T>( val languageManager: LanguageManager, val descriptionI18n: StringI18nData, ) : NameableCommandOption<T> { override val description = languageManager.defaultI18nContext.get(descriptionI18n).shortenWithEllipsis(DiscordResourceLimits.Command.Options.Description.Length) override val descriptionLocalizations = SlashTextUtils.createShortenedLocalizedStringMapExcludingDefaultLocale(languageManager, descriptionI18n) override val nameLocalizations: Map<Locale, String> = emptyMap() } // ===[ STRING ]=== class LocalizedStringCommandOption( languageManager: LanguageManager, override val name: String, descriptionI18n: StringI18nData, override val required: Boolean, override val choices: List<CommandChoice<String>>?, override val minLength: Int?, override val maxLength: Int?, override val autocompleteExecutor: AutocompleteHandler<String>? ) : LocalizedCommandOption<String>(languageManager, descriptionI18n), StringCommandOption // ===[ INTEGER ]=== class LocalizedIntegerCommandOption( languageManager: LanguageManager, override val name: String, descriptionI18n: StringI18nData, override val required: Boolean, override val choices: List<CommandChoice<Long>>?, override val minValue: Long?, override val maxValue: Long?, override val autocompleteExecutor: AutocompleteHandler<Long>? ) : LocalizedCommandOption<Long>(languageManager, descriptionI18n), IntegerCommandOption // ===[ NUMBER ]=== class LocalizedNumberCommandOption( languageManager: LanguageManager, override val name: String, descriptionI18n: StringI18nData, override val required: Boolean, override val choices: List<CommandChoice<Double>>?, override val minValue: Double?, override val maxValue: Double?, override val autocompleteExecutor: AutocompleteHandler<Double>? ) : LocalizedCommandOption<Double>(languageManager, descriptionI18n), NumberCommandOption // ===[ BOOLEAN ]=== class LocalizedBooleanCommandOption( languageManager: LanguageManager, override val name: String, descriptionI18n: StringI18nData, override val required: Boolean ) : LocalizedCommandOption<Boolean>(languageManager, descriptionI18n), BooleanCommandOption // ===[ USER ]=== class LocalizedUserCommandOption( languageManager: LanguageManager, override val name: String, descriptionI18n: StringI18nData, override val required: Boolean ) : LocalizedCommandOption<User>(languageManager, descriptionI18n), UserCommandOption // ===[ CHANNEL ]=== class LocalizedChannelCommandOption( languageManager: LanguageManager, override val name: String, descriptionI18n: StringI18nData, override val required: Boolean, override val channelTypes: List<ChannelType>? ) : LocalizedCommandOption<Channel>(languageManager, descriptionI18n), ChannelCommandOption // ===[ ROLE ]=== class LocalizedRoleCommandOption( languageManager: LanguageManager, override val name: String, descriptionI18n: StringI18nData, override val required: Boolean ) : LocalizedCommandOption<Role>(languageManager, descriptionI18n), RoleCommandOption
agpl-3.0
ericberman/MyFlightbookAndroid
app/src/main/java/com/myflightbook/android/ActNewFlight.kt
1
83584
/* MyFlightbook for Android - provides native access to MyFlightbook pilot's logbook Copyright (C) 2017-2022 MyFlightbook, LLC 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.myflightbook.android import android.Manifest import android.app.Activity import android.app.AlertDialog import android.content.Context import android.content.DialogInterface import android.content.Intent import android.graphics.Bitmap import android.graphics.BitmapFactory import android.location.Location import android.os.Bundle import android.os.Handler import android.os.Looper import android.text.format.DateFormat import android.util.Log import android.view.* import android.view.ContextMenu.ContextMenuInfo import android.view.View.OnFocusChangeListener import android.widget.* import androidx.activity.result.ActivityResult import androidx.activity.result.ActivityResultLauncher import androidx.activity.result.contract.ActivityResultContracts.RequestPermission import androidx.activity.result.contract.ActivityResultContracts.StartActivityForResult import androidx.core.app.ShareCompat.IntentBuilder import androidx.lifecycle.lifecycleScope import com.myflightbook.android.ActMFBForm.GallerySource import com.myflightbook.android.ActOptions.AltitudeUnits import com.myflightbook.android.ActOptions.SpeedUnits import com.myflightbook.android.DlgDatePicker.DateTimeUpdate import com.myflightbook.android.MFBMain.Invalidatable import com.myflightbook.android.webservices.* import com.myflightbook.android.webservices.AuthToken.Companion.isValid import com.myflightbook.android.webservices.CustomPropertyTypesSvc.Companion.cachedPropertyTypes import com.myflightbook.android.webservices.MFBSoap.Companion.isOnline import com.myflightbook.android.webservices.RecentFlightsSvc.Companion.clearCachedFlights import com.myflightbook.android.webservices.UTCDate.isNullDate import kotlinx.coroutines.launch import model.* import model.Aircraft.Companion.getAircraftById import model.Aircraft.Companion.getHighWaterHobbsForAircraft import model.Aircraft.Companion.getHighWaterTachForAircraft import model.Airport.Companion.appendCodeToRoute import model.Airport.Companion.appendNearestToRoute import model.CustomPropertyType.Companion.getPinnedProperties import model.CustomPropertyType.Companion.isPinnedProperty import model.DecimalEdit.CrossFillDelegate import model.FlightProperty.Companion.crossProduct import model.FlightProperty.Companion.distillList import model.FlightProperty.Companion.rewritePropertiesForFlight import model.GPSSim.Companion.autoFill import model.LogbookEntry.SigStatus import model.MFBConstants.nightParam import model.MFBFlightListener.ListenerFragmentDelegate import model.MFBImageInfo.PictureDestination import model.MFBLocation.AutoFillOptions import model.MFBLocation.Companion.getMainLocation import model.MFBLocation.Companion.hasGPS import model.MFBLocation.GPSQuality import model.MFBUtil.alert import model.MFBUtil.getForKey import model.MFBUtil.nowWith0Seconds import model.MFBUtil.removeForKey import model.MFBUtil.removeSeconds import model.PropertyTemplate.Companion.anonTemplate import model.PropertyTemplate.Companion.defaultTemplates import model.PropertyTemplate.Companion.getSharedTemplates import model.PropertyTemplate.Companion.mergeTemplates import model.PropertyTemplate.Companion.simTemplate import model.PropertyTemplate.Companion.templatesWithIDs import java.io.UnsupportedEncodingException import java.net.URL import java.net.URLEncoder import java.text.SimpleDateFormat import java.util.* import kotlin.math.abs import kotlin.math.roundToInt class ActNewFlight : ActMFBForm(), View.OnClickListener, ListenerFragmentDelegate, DateTimeUpdate, PropertyEdit.PropertyListener, GallerySource, CrossFillDelegate, Invalidatable { private var mRgac: Array<Aircraft>? = null private var mle: LogbookEntry? = null private var mActivetemplates: HashSet<PropertyTemplate?>? = HashSet() private var needsDefaultTemplates = true private var txtQuality: TextView? = null private var txtStatus: TextView? = null private var txtSpeed: TextView? = null private var txtAltitude: TextView? = null private var txtSunrise: TextView? = null private var txtSunset: TextView? = null private var txtLatitude: TextView? = null private var txtLongitude: TextView? = null private var imgRecording: ImageView? = null private var mHandlerupdatetimer: Handler? = null private var mUpdateelapsedtimetask: Runnable? = null private var mTimeCalcLauncher: ActivityResultLauncher<Intent>? = null private var mApproachHelperLauncher: ActivityResultLauncher<Intent>? = null private var mMapRouteLauncher: ActivityResultLauncher<Intent>? = null private var mTemplateLauncher: ActivityResultLauncher<Intent>? = null private var mPropertiesLauncher: ActivityResultLauncher<Intent>? = null private var mAppendAdhocLauncher: ActivityResultLauncher<String>? = null private var mAppendNearestLauncher: ActivityResultLauncher<String>? = null private var mAddAircraftLauncher: ActivityResultLauncher<Intent>? = null private fun deleteFlight(le : LogbookEntry?) { if (le == null) return val soapCall = when { (le is PendingFlight) -> PendingFlightSvc() else -> DeleteFlightSvc() } val pf = le as? PendingFlight lifecycleScope.launch { doAsync<MFBSoap, Boolean?>( requireActivity(), soapCall, getString(R.string.prgDeletingFlight), { s -> if (pf != null && pf.getPendingID().isNotEmpty()) ActRecentsWS.cachedPendingFlights = (s as PendingFlightSvc).deletePendingFlight(AuthToken.m_szAuthToken, pf.getPendingID(), requireContext()) else (s as DeleteFlightSvc).deleteFlightForUser(AuthToken.m_szAuthToken, le.idFlight, requireContext()) s.lastError.isEmpty() }, { _, result -> if (result!!) { clearCachedFlights() MFBMain.invalidateCachedTotals() finish() } } ) } } private fun submitFlight(le : LogbookEntry?) { if (le == null) return val fIsNew = le.isNewFlight() val pf = le as? PendingFlight lifecycleScope.launch { doAsync<MFBSoap, Boolean?>( requireActivity(), if (le.fForcePending || (pf != null && pf.getPendingID().isNotEmpty())) PendingFlightSvc() else CommitFlightSvc(), getString(R.string.prgSavingFlight), { s -> submitFlightWorker(le, s) }, { _, result -> if (result!!) { MFBMain.invalidateCachedTotals() // success, so we our cached recents are invalid clearCachedFlights() val ocl: DialogInterface.OnClickListener // the flight was successfully saved, so delete any local copy regardless le.deleteUnsubmittedFlightFromLocalDB() if (fIsNew) { // Reset the flight and we stay on this page resetFlight(true) ocl = DialogInterface.OnClickListener { d: DialogInterface, _: Int -> d.cancel() } } else { // no need to reset the current flight because we will finish. ocl = DialogInterface.OnClickListener { d: DialogInterface, _: Int -> d.cancel() finish() } mle = null // so that onPause won't cause it to be saved on finish() call. } AlertDialog.Builder(requireActivity(), R.style.MFBDialog) .setMessage(getString(R.string.txtSavedFlight)) .setTitle(getString(R.string.txtSuccess)) .setNegativeButton("OK", ocl) .create().show() } else alert(requireContext(), getString(R.string.txtError), le.szError) }) } } private fun submitFlightWorker(le : LogbookEntry, s : MFBSoap) : Boolean { /* Scenarios: - fForcePending is false, Regular flight, new or existing: call CommitFlightWithOptions - fForcePending is false, Pending flight without a pending ID call CommitFlightWithOptions. Shouldn't happen, but no big deal if it does - fForcePending is false, Pending flight with a Pending ID: call CommitPendingFlight to commit it - fForcePending is false, Pending flight without a pending ID: THROW EXCEPTION, how did this happen? - fForcePending is true, Regular flight that is not new/pending (sorry about ambiguous "pending"): THROW EXCEPTION; this is an error - fForcePending is true, Regular flight that is NEW: call CreatePendingFlight - fForcePending is true, PendingFlight without a PendingID: call CreatePendingFlight. Shouldn't happen, but no big deal if it does - fForcePending is true, PendingFlight with a PendingID: call UpdatePendingFlight */ val pf = le as? PendingFlight if (le.fForcePending) { val pfs = s as PendingFlightSvc check(!le.isExistingFlight()) { "Attempt to save an existing flight as a pending flight" } if (pf == null || pf.getPendingID().isEmpty()) { pfs.createPendingFlight(AuthToken.m_szAuthToken, le, requireContext()) .also { ActRecentsWS.cachedPendingFlights = it } le.szError = pfs.lastError } else { // existing pending flight but still force pending - call updatependingflight pfs.updatePendingFlight(AuthToken.m_szAuthToken, pf, requireContext()) .also { ActRecentsWS.cachedPendingFlights = it } le.szError = pfs.lastError } } else { // Not force pending. // If regular flight (new or existing), or pending without a pendingID if (pf == null || pf.getPendingID().isEmpty()) { val cf = s as CommitFlightSvc cf.fCommitFlightForUser(AuthToken.m_szAuthToken, le, requireContext()) le.szError = cf.lastError } else { // By definition, here pf is non-null and it has a pending ID so it is a valid pending flight and we are not forcing - call commitpendingflight val pfs = s as PendingFlightSvc val rgpf = pfs.commitPendingFlight(AuthToken.m_szAuthToken, pf, requireContext()) ActRecentsWS.cachedPendingFlights = rgpf pf.szError = pfs.lastError } } return le.szError.isEmpty() } private fun fetchDigitizedSig(url : String?, iv : ImageView) { if (url == null || url.isEmpty()) return lifecycleScope.launch { doAsync<String, Bitmap?>( requireActivity(), url, null, { url -> try { val str = URL(url).openStream() BitmapFactory.decodeStream(str) } catch (e: Exception) { Log.e(MFBConstants.LOG_TAG, e.message!!) null } }, { _, result -> if (result != null) iv.setImageBitmap(result) } ) } } private fun refreshAircraft() { lifecycleScope.launch { doAsync<AircraftSvc, Array<Aircraft>?>( requireActivity(), AircraftSvc(), getString(R.string.prgAircraft), { s -> s.getAircraftForUser(AuthToken.m_szAuthToken, requireContext()) }, { s, result -> if (result == null) alert(requireActivity(),getString(R.string.txtError), s.lastError) else refreshAircraft(result, false) } ) } } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { setHasOptionsMenu(true) return inflater.inflate(R.layout.newflight, container, false) } override fun onStop() { super.onStop() if (mle == null || mle!!.isNewFlight()) MFBMain.setInProgressFlightActivity(context, null) } private fun setUpActivityLaunchers() { mApproachHelperLauncher = registerForActivityResult( StartActivityForResult() ) { result: ActivityResult -> if (result.resultCode == Activity.RESULT_OK) { val approachDesc = result.data!!.getStringExtra(ActAddApproach.APPROACHDESCRIPTIONRESULT) if (approachDesc!!.isNotEmpty()) { mle!!.addApproachDescription(approachDesc) val cApproachesToAdd = result.data!!.getIntExtra(ActAddApproach.APPROACHADDTOTOTALSRESULT, 0) if (cApproachesToAdd > 0) { mle!!.cApproaches += cApproachesToAdd setIntForField(R.id.txtApproaches, mle!!.cApproaches) } toView() } } } mTimeCalcLauncher = registerForActivityResult( StartActivityForResult() ) { result: ActivityResult -> if (result.resultCode == Activity.RESULT_OK) { setDoubleForField( R.id.txtTotal, result.data!!.getDoubleExtra(ActTimeCalc.COMPUTED_TIME, mle!!.decTotal) .also { mle!!.decTotal = it }) } } mMapRouteLauncher = registerForActivityResult( StartActivityForResult() ) { result: ActivityResult -> if (result.resultCode == Activity.RESULT_OK) { mle!!.szRoute = result.data!!.getStringExtra(ActFlightMap.ROUTEFORFLIGHT)!! setStringForField(R.id.txtRoute, mle!!.szRoute) findViewById(R.id.txtRoute)!!.requestFocus() } } mTemplateLauncher = registerForActivityResult( StartActivityForResult() ) { result: ActivityResult -> if (result.resultCode == Activity.RESULT_OK) { val b = result.data!!.extras try { val o = b!!.getSerializable(ActViewTemplates.ACTIVE_PROPERTYTEMPLATES) mActivetemplates = o as HashSet<PropertyTemplate?>? updateTemplatesForAircraft(true) toView() } catch (ex: ClassCastException) { Log.e(MFBConstants.LOG_TAG, ex.message!!) } } } mPropertiesLauncher = registerForActivityResult( StartActivityForResult() ) { setUpPropertiesForFlight() if (MFBLocation.fPrefAutoFillTime === AutoFillOptions.BlockTime) doAutoTotals() } mAppendAdhocLauncher = registerForActivityResult( RequestPermission() ) { result: Boolean -> if (result) { val loc = getMainLocation()!! if (loc.currentLoc() == null) return@registerForActivityResult val szAdHoc = LatLong(loc.currentLoc()!!).toAdHocLocString() val txtRoute = findViewById(R.id.txtRoute) as TextView? mle!!.szRoute = appendCodeToRoute(txtRoute!!.text.toString(), szAdHoc) txtRoute.text = mle!!.szRoute } } mAppendNearestLauncher = registerForActivityResult( RequestPermission() ) { result: Boolean -> if (result) { val txtRoute = findViewById(R.id.txtRoute) as TextView? mle!!.szRoute = appendNearestToRoute( txtRoute!!.text.toString(), getMainLocation()!!.currentLoc() ) txtRoute.text = mle!!.szRoute } } mAddAircraftLauncher = registerForActivityResult( StartActivityForResult() ) { val rgac = AircraftSvc().cachedAircraft mRgac = rgac refreshAircraft(mRgac, false) } } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) setUpActivityLaunchers() addListener(R.id.btnFlightSet) addListener(R.id.btnFlightStartSet) addListener(R.id.btnEngineStartSet) addListener(R.id.btnFlightEndSet) addListener(R.id.btnEngineEndSet) addListener(R.id.btnBlockOut) addListener(R.id.btnBlockIn) addListener(R.id.btnProps) addListener(R.id.btnAppendNearest) addListener(R.id.btnAddAircraft) findViewById(R.id.btnAppendNearest)!!.setOnLongClickListener { appendAdHoc() true } // Expand/collapse addListener(R.id.txtViewInTheCockpit) addListener(R.id.txtImageHeader) addListener(R.id.txtPinnedPropertiesHeader) addListener(R.id.txtSignatureHeader) enableCrossFill(R.id.txtNight) enableCrossFill(R.id.txtSimIMC) enableCrossFill(R.id.txtIMC) enableCrossFill(R.id.txtXC) enableCrossFill(R.id.txtDual) enableCrossFill(R.id.txtGround) enableCrossFill(R.id.txtCFI) enableCrossFill(R.id.txtSIC) enableCrossFill(R.id.txtPIC) enableCrossFill(R.id.txtHobbsStart) enableCrossFill(R.id.txtTachStart) findViewById(R.id.txtTotal)!!.setOnLongClickListener { val i = Intent(requireActivity(), ActTimeCalc::class.java) i.putExtra(ActTimeCalc.INITIAL_TIME, doubleFromField(R.id.txtTotal)) mTimeCalcLauncher!!.launch(i) true } findViewById(R.id.btnFlightSet)!!.setOnLongClickListener { resetDateOfFlight() true } var b = findViewById(R.id.btnPausePlay) as ImageButton? b!!.setOnClickListener(this) b = findViewById(R.id.btnViewOnMap) as ImageButton? b!!.setOnClickListener(this) b = findViewById(R.id.btnAddApproach) as ImageButton? b!!.setOnClickListener(this) // cache these views for speed. txtQuality = findViewById(R.id.txtFlightGPSQuality) as TextView? txtStatus = findViewById(R.id.txtFlightStatus) as TextView? txtSpeed = findViewById(R.id.txtFlightSpeed) as TextView? txtAltitude = findViewById(R.id.txtFlightAltitude) as TextView? txtSunrise = findViewById(R.id.txtSunrise) as TextView? txtSunset = findViewById(R.id.txtSunset) as TextView? txtLatitude = findViewById(R.id.txtLatitude) as TextView? txtLongitude = findViewById(R.id.txtLongitude) as TextView? imgRecording = findViewById(R.id.imgRecording) as ImageView? // get notification of hobbs changes, or at least focus changes val s = OnFocusChangeListener { v: View, hasFocus: Boolean -> if (!hasFocus) onHobbsChanged(v) } findViewById(R.id.txtHobbsStart)!!.onFocusChangeListener = s findViewById(R.id.txtHobbsEnd)!!.onFocusChangeListener = s val i = requireActivity().intent val keyForLeToView = i.getStringExtra(ActRecentsWS.VIEWEXISTINGFLIGHT) val leToView = if (keyForLeToView == null) null else getForKey(keyForLeToView) as LogbookEntry? removeForKey(keyForLeToView) val fIsNewFlight = leToView == null if (!fIsNewFlight && mRgac == null) mRgac = AircraftSvc().cachedAircraft val sp = findViewById(R.id.spnAircraft) as Spinner? sp!!.onItemSelectedListener = object : AdapterView.OnItemSelectedListener { override fun onItemSelected( parent: AdapterView<*>, view: View?, position: Int, id: Long ) { val ac = parent.selectedItem as Aircraft if (mle != null && mle!!.idAircraft != ac.aircraftID) { if (ac.aircraftID == -1) { // show all! refreshAircraft(mRgac, true) sp.performClick() } else { fromView() mle!!.idAircraft = ac.aircraftID updateTemplatesForAircraft(false) toView() } } } override fun onNothingSelected(parent: AdapterView<*>?) {} } // set for no focus. findViewById(R.id.btnFlightSet)!!.requestFocus() if (fIsNewFlight) { // re-use the existing in-progress flight mle = MFBMain.newFlightListener?.getInProgressFlight(requireActivity()) MFBMain.registerNotifyResetAll(this) val pref = requireActivity().getPreferences(Context.MODE_PRIVATE) val fExpandCockpit = pref.getBoolean(m_KeyShowInCockpit, true) setExpandedState( (findViewById(R.id.txtViewInTheCockpit) as TextView?)!!, findViewById(R.id.sectInTheCockpit)!!, fExpandCockpit, false ) } else { // view an existing flight mle = leToView if (mle!!.isExistingFlight() || mle is PendingFlight) { mle!!.toDB() // ensure that this is in the database - above call could have pulled from cache rewritePropertiesForFlight(mle!!.idLocalDB, mle!!.rgCustomProperties) } setUpPropertiesForFlight() } if (mle != null && mle!!.rgFlightImages == null) mle!!.imagesForFlight // Refresh aircraft on create if (isValid() && (mRgac == null || mRgac!!.isEmpty())) refreshAircraft() Log.w( MFBConstants.LOG_TAG, String.format( "ActNewFlight - created, m_le is %s", if (mle == null) "null" else "non-null" ) ) } private fun enableCrossFill(id: Int) { val de = findViewById(id) as DecimalEdit? de!!.setDelegate(this) } override fun crossFillRequested(sender: DecimalEdit?) { fromView() if (sender!!.id == R.id.txtHobbsStart) { val d = getHighWaterHobbsForAircraft(mle!!.idAircraft) if (d > 0) sender.doubleValue = d } else if (sender.id == R.id.txtTachStart) { val d = getHighWaterTachForAircraft(mle!!.idAircraft) if (d > 0) sender.doubleValue = d } else if (mle!!.decTotal > 0) sender.doubleValue = mle!!.decTotal fromView() } private fun selectibleAircraft(): Array<Aircraft>? { if (mRgac == null) return null val lst: MutableList<Aircraft> = ArrayList() for (ac in mRgac!!) { if (!ac.hideFromSelection || mle != null && ac.aircraftID == mle!!.idAircraft) lst.add( ac ) } if (lst.size == 0) return mRgac if (lst.size != mRgac!!.size) { // some aircraft are filtered // Issue #202 - add a "Show all Aircraft" option val ac = Aircraft() ac.aircraftID = -1 ac.modelDescription = getString(R.string.fqShowAllAircraft) ac.tailNumber = "#" lst.add(ac) } return lst.toTypedArray() } private fun refreshAircraft(rgac: Array<Aircraft>?, fShowAll: Boolean) { mRgac = rgac val spnAircraft = findViewById(R.id.spnAircraft) as Spinner? val rgFilteredAircraft = if (fShowAll) rgac else selectibleAircraft() if (rgFilteredAircraft != null && rgFilteredAircraft.isNotEmpty()) { var pos = 0 for (i in rgFilteredAircraft.indices) { if (mle == null || mle!!.idAircraft == rgFilteredAircraft[i].aircraftID) { pos = i break } } // Create a list of the aircraft to show, which are the ones that are not hidden OR the active one for the flight val adapter = ArrayAdapter( requireActivity(), R.layout.mfbsimpletextitem, rgFilteredAircraft ) spnAircraft!!.adapter = adapter spnAircraft.setSelection(pos) // need to notifydatasetchanged or else setselection doesn't // update correctly. adapter.notifyDataSetChanged() } else { spnAircraft!!.prompt = getString(R.string.errNoAircraftFoundShort) alert(this, getString(R.string.txtError), getString(R.string.errMustCreateAircraft)) } } override fun onResume() { // refresh the aircraft list (will be cached if we already have it) // in case a new aircraft has been added. super.onResume() if (!isValid()) { val d = DlgSignIn(requireActivity()) d.show() } val rgac = AircraftSvc().cachedAircraft mRgac = rgac if (mRgac != null) refreshAircraft(mRgac, false) // Not sure why le can sometimes be empty here... if (mle == null) mle = MFBMain.newFlightListener?.getInProgressFlight(requireActivity()) // show/hide GPS controls based on whether this is a new flight or existing. val fIsNewFlight = mle!!.isNewFlight() val l = findViewById(R.id.sectGPS) as LinearLayout? l!!.visibility = if (fIsNewFlight) View.VISIBLE else View.GONE findViewById(R.id.btnAppendNearest)!!.visibility = if (fIsNewFlight && hasGPS(requireContext())) View.VISIBLE else View.GONE val btnViewFlight = findViewById(R.id.btnViewOnMap) as ImageButton? btnViewFlight!!.visibility = if (MFBMain.hasMaps()) View.VISIBLE else View.GONE if (fIsNewFlight) { // ensure that we keep the elapsed time up to date updatePausePlayButtonState() mHandlerupdatetimer = Handler(Looper.getMainLooper()) val elapsedTimeTask = object : Runnable { override fun run() { updateElapsedTime() mHandlerupdatetimer!!.postDelayed(this, 1000) } } mUpdateelapsedtimetask = elapsedTimeTask mHandlerupdatetimer!!.postDelayed(elapsedTimeTask, 1000) } setUpGalleryForFlight() restoreState() // set the ensure that we are following the right numerical format setDecimalEditMode(R.id.txtCFI) setDecimalEditMode(R.id.txtDual) setDecimalEditMode(R.id.txtGround) setDecimalEditMode(R.id.txtIMC) setDecimalEditMode(R.id.txtNight) setDecimalEditMode(R.id.txtPIC) setDecimalEditMode(R.id.txtSIC) setDecimalEditMode(R.id.txtSimIMC) setDecimalEditMode(R.id.txtTotal) setDecimalEditMode(R.id.txtXC) // Make sure the date of flight is up-to-date if (mle!!.isKnownEngineStart || mle!!.isKnownFlightStart) resetDateOfFlight() // First resume after create should pull in default templates; // subsequent resumes should NOT. updateTemplatesForAircraft(!needsDefaultTemplates) needsDefaultTemplates = false // reset this. toView() // do this last to start GPS service if (fIsNewFlight) MFBMain.setInProgressFlightActivity(context, this) } private fun setUpGalleryForFlight() { if (mle!!.rgFlightImages == null) mle!!.imagesForFlight setUpImageGallery(getGalleryID(), mle!!.rgFlightImages, getGalleryHeader()) } override fun onPause() { super.onPause() // should only happen when we are returning from viewing an existing/queued/pending flight, may have been submitted // either way, no need to save this if (mle == null) return fromView() saveCurrentFlight() Log.w(MFBConstants.LOG_TAG, String.format("Paused, landings are %d", mle!!.cLandings)) saveState() // free up some scheduling resources. if (mHandlerupdatetimer != null) mHandlerupdatetimer!!.removeCallbacks( mUpdateelapsedtimetask!! ) } private fun restoreState() { try { val mPrefs = requireActivity().getPreferences(Activity.MODE_PRIVATE) fPaused = mPrefs.getBoolean(m_KeysIsPaused, false) dtPauseTime = mPrefs.getLong(m_KeysPausedTime, 0) dtTimeOfLastPause = mPrefs.getLong(m_KeysTimeOfLastPause, 0) accumulatedNight = mPrefs.getFloat(m_KeysAccumulatedNight, 0.0.toFloat()).toDouble() } catch (e: Exception) { Log.e(MFBConstants.LOG_TAG, Log.getStackTraceString(e)) } } private fun saveState() { // Save UI state changes to the savedInstanceState. // This bundle will be passed to onCreate if the process is // killed and restarted. val ed = requireActivity().getPreferences(Activity.MODE_PRIVATE).edit() ed.putBoolean(m_KeysIsPaused, fPaused) ed.putLong(m_KeysPausedTime, dtPauseTime) ed.putLong(m_KeysTimeOfLastPause, dtTimeOfLastPause) ed.putFloat(m_KeysAccumulatedNight, accumulatedNight.toFloat()) ed.apply() } override fun saveCurrentFlight() { if (!mle!!.isExistingFlight()) mle!!.toDB() if (activity == null) // sometimes not yet set up return // and we only want to save the current flightID if it is a new (not queued!) flight if (mle!!.isNewFlight()) MFBMain.newFlightListener?.saveCurrentFlightId(activity) } private fun setLogbookEntry(le: LogbookEntry) { mle = le saveCurrentFlight() if (view == null) return setUpGalleryForFlight() toView() } override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { val idMenu: Int if (mle != null) { idMenu = if (mle!!.isExistingFlight()) R.menu.mfbexistingflightmenu else if (mle!!.isNewFlight()) R.menu.mfbnewflightmenu else if (mle is PendingFlight) R.menu.mfbpendingflightmenu else if (mle!!.isQueuedFlight()) R.menu.mfbqueuedflightmenu else R.menu.mfbqueuedflightmenu inflater.inflate(idMenu, menu) } super.onCreateOptionsMenu(menu, inflater) } override fun onCreateContextMenu(menu: ContextMenu, v: View, menuInfo: ContextMenuInfo?) { super.onCreateContextMenu(menu, v, menuInfo) val inflater = requireActivity().menuInflater inflater.inflate(R.menu.imagemenu, menu) } override fun onOptionsItemSelected(item: MenuItem): Boolean { // Should never happen. if (mle == null) return false // Handle item selection when (val menuId = item.itemId) { R.id.menuUploadLater -> submitFlight(true) R.id.menuResetFlight -> { if (mle!!.idLocalDB > 0) mle!!.deleteUnsubmittedFlightFromLocalDB() resetFlight(false) } R.id.menuSignFlight -> { try { ActWebView.viewURL( requireActivity(), String.format( Locale.US, MFBConstants.urlSign, MFBConstants.szIP, mle!!.idFlight, URLEncoder.encode(AuthToken.m_szAuthToken, "UTF-8"), nightParam(context) ) ) } catch (ignored: UnsupportedEncodingException) { } } R.id.btnDeleteFlight -> AlertDialog.Builder( requireActivity(), R.style.MFBDialog ) .setIcon(android.R.drawable.ic_dialog_alert) .setTitle(R.string.lblConfirm) .setMessage(R.string.lblConfirmFlightDelete) .setPositiveButton(R.string.lblOK) { _: DialogInterface?, _: Int -> if (mle!!.isAwaitingUpload()) { mle!!.deleteUnsubmittedFlightFromLocalDB() mle = null // clear this out since we're going to finish(). clearCachedFlights() finish() } else if (mle!!.isExistingFlight() || mle is PendingFlight) deleteFlight(mle) } .setNegativeButton(R.string.lblCancel, null) .show() R.id.btnSubmitFlight, R.id.btnUpdateFlight -> submitFlight( false ) R.id.btnSavePending -> { mle!!.fForcePending = true submitFlight(false) } R.id.menuTakePicture -> takePictureClicked() R.id.menuTakeVideo -> takeVideoClicked() R.id.menuChoosePicture -> choosePictureClicked() R.id.menuChooseTemplate -> { val i = Intent(requireActivity(), ViewTemplatesActivity::class.java) val b = Bundle() b.putSerializable(ActViewTemplates.ACTIVE_PROPERTYTEMPLATES, mActivetemplates) i.putExtras(b) mTemplateLauncher!!.launch(i) } R.id.menuRepeatFlight, R.id.menuReverseFlight -> { assert(mle != null) val leNew = if (menuId == R.id.menuRepeatFlight) mle!!.clone() else mle!!.cloneAndReverse() leNew!!.idFlight = LogbookEntry.ID_QUEUED_FLIGHT_UNSUBMITTED leNew.toDB() rewritePropertiesForFlight(leNew.idLocalDB, leNew.rgCustomProperties) leNew.syncProperties() clearCachedFlights() AlertDialog.Builder(requireActivity(), R.style.MFBDialog) .setMessage(getString(R.string.txtRepeatFlightComplete)) .setTitle(getString(R.string.txtSuccess)) .setNegativeButton("OK") { d: DialogInterface, _: Int -> d.cancel() finish() } .create().show() return true } R.id.menuSendFlight -> sendFlight() R.id.menuShareFlight -> shareFlight() R.id.btnAutoFill -> { assert(mle != null) fromView() autoFill(requireContext(), mle) toView() } else -> return super.onOptionsItemSelected(item) } return true } private fun sendFlight() { if (mle == null || mle!!.sendLink.isEmpty()) { alert(this, getString(R.string.txtError), getString(R.string.errCantSend)) return } IntentBuilder(requireActivity()) .setType("message/rfc822") .setSubject(getString(R.string.sendFlightSubject)) .setText( String.format( Locale.getDefault(), getString(R.string.sendFlightBody), mle!!.sendLink ) ) .setChooserTitle(getString(R.string.menuSendFlight)) .startChooser() } private fun shareFlight() { if (mle == null || mle!!.shareLink.isEmpty()) { alert(this, getString(R.string.txtError), getString(R.string.errCantShare)) return } val intent = Intent(Intent.ACTION_SEND) intent.type = "text/plain" intent.putExtra( Intent.EXTRA_SUBJECT, String.format(Locale.getDefault(), "%s %s", mle!!.szComments, mle!!.szRoute) .trim { it <= ' ' }) intent.putExtra(Intent.EXTRA_TEXT, mle!!.shareLink) startActivity(Intent.createChooser(intent, getString(R.string.menuShareFlight))) } override fun onContextItemSelected(item: MenuItem): Boolean { val menuID = item.itemId return if (menuID == R.id.menuAddComment || menuID == R.id.menuDeleteImage || menuID == R.id.menuViewImage) onImageContextItemSelected( item, this ) else true } //region append to route // NOTE: I had been doing this with an AsyncTask, but it // wasn't thread safe with the database. DB is pretty fast, // so we can just make sure we do all DB stuff on the main thread. private fun appendNearest() { assert(getMainLocation() != null) mAppendNearestLauncher!!.launch(Manifest.permission.ACCESS_FINE_LOCATION) } private fun appendAdHoc() { assert(getMainLocation() != null) mAppendAdhocLauncher!!.launch(Manifest.permission.ACCESS_FINE_LOCATION) } //endregion private fun takePictureClicked() { saveCurrentFlight() takePicture() } private fun takeVideoClicked() { saveCurrentFlight() takeVideo() } private fun choosePictureClicked() { saveCurrentFlight() choosePicture() } override fun onClick(v: View) { fromView() when (val id = v.id) { R.id.btnEngineStartSet -> { if (!mle!!.isKnownEngineStart) { mle!!.dtEngineStart = nowWith0Seconds() engineStart() } else setDateTime( id, mle!!.dtEngineStart, this, DlgDatePicker.DatePickMode.UTCDATETIME ) } R.id.btnEngineEndSet -> { if (!mle!!.isKnownEngineEnd) { mle!!.dtEngineEnd = nowWith0Seconds() engineStop() } else setDateTime(id, mle!!.dtEngineEnd, this, DlgDatePicker.DatePickMode.UTCDATETIME) } R.id.btnBlockOut -> { val dtBlockOut = mle!!.propDateForID(CustomPropertyType.idPropTypeBlockOut) if (dtBlockOut == null) { mle!!.addOrSetPropertyDate(CustomPropertyType.idPropTypeBlockOut, nowWith0Seconds()) resetDateOfFlight() } else setDateTime(id, dtBlockOut, this, DlgDatePicker.DatePickMode.UTCDATETIME) } R.id.btnBlockIn -> { val dtBlockIn = mle!!.propDateForID(CustomPropertyType.idPropTypeBlockIn) if (dtBlockIn == null) mle!!.addOrSetPropertyDate(CustomPropertyType.idPropTypeBlockIn, nowWith0Seconds()) else setDateTime(id, dtBlockIn, this, DlgDatePicker.DatePickMode.UTCDATETIME) } R.id.btnFlightStartSet -> { if (!mle!!.isKnownFlightStart) { mle!!.dtFlightStart = nowWith0Seconds() flightStart() } else setDateTime( id, mle!!.dtFlightStart, this, DlgDatePicker.DatePickMode.UTCDATETIME ) } R.id.btnFlightEndSet -> { if (!mle!!.isKnownFlightEnd) { mle!!.dtFlightEnd = nowWith0Seconds() flightStop() } else setDateTime(id, mle!!.dtFlightEnd, this, DlgDatePicker.DatePickMode.UTCDATETIME) } R.id.btnFlightSet -> { val dlg = DlgDatePicker( requireActivity(), DlgDatePicker.DatePickMode.LOCALDATEONLY, mle!!.dtFlight ) dlg.mDelegate = this dlg.mId = id dlg.show() } R.id.btnProps -> viewPropsForFlight() R.id.btnAppendNearest -> appendNearest() R.id.btnAddAircraft -> mAddAircraftLauncher!!.launch( Intent( activity, NewAircraftActivity::class.java ) ) R.id.btnAddApproach -> { val i = Intent(requireActivity(), ActAddApproach::class.java) i.putExtra(ActAddApproach.AIRPORTSFORAPPROACHES, mle!!.szRoute) mApproachHelperLauncher!!.launch(i) } R.id.btnViewOnMap -> { val i = Intent(requireActivity(), ActFlightMap::class.java) i.putExtra(ActFlightMap.ROUTEFORFLIGHT, mle!!.szRoute) i.putExtra( ActFlightMap.EXISTINGFLIGHTID, if (mle!!.isExistingFlight()) mle!!.idFlight else 0 ) i.putExtra( ActFlightMap.PENDINGFLIGHTID, if (mle!!.isAwaitingUpload()) mle!!.idLocalDB else 0 ) i.putExtra( ActFlightMap.NEWFLIGHTID, if (mle!!.isNewFlight()) LogbookEntry.ID_NEW_FLIGHT else 0 ) i.putExtra(ActFlightMap.ALIASES, "") mMapRouteLauncher!!.launch(i) } R.id.btnPausePlay -> toggleFlightPause() R.id.txtViewInTheCockpit -> { val target = findViewById(R.id.sectInTheCockpit) val fExpandCockpit = target!!.visibility != View.VISIBLE if (mle != null && mle!!.isNewFlight()) { val e = requireActivity().getPreferences(Context.MODE_PRIVATE).edit() e.putBoolean(m_KeyShowInCockpit, fExpandCockpit) e.apply() } setExpandedState((v as TextView), target, fExpandCockpit) } R.id.txtImageHeader -> { val target = findViewById(R.id.tblImageTable) setExpandedState((v as TextView), target!!, target.visibility != View.VISIBLE) } R.id.txtSignatureHeader -> { val target = findViewById(R.id.sectSignature) setExpandedState((v as TextView), target!!, target.visibility != View.VISIBLE) } R.id.txtPinnedPropertiesHeader -> { val target = findViewById(R.id.sectPinnedProperties) setExpandedState((v as TextView), target!!, target.visibility != View.VISIBLE) } } toView() } //region Image support override fun chooseImageCompleted(result: ActivityResult?) { addGalleryImage(result!!.data!!) } override fun takePictureCompleted(result: ActivityResult?) { addCameraImage(mTempfilepath, false) } override fun takeVideoCompleted(result: ActivityResult?) { addCameraImage(mTempfilepath, true) } //endregion private fun viewPropsForFlight() { val i = Intent(requireActivity(), ActViewProperties::class.java) i.putExtra(PROPSFORFLIGHTID, mle!!.idLocalDB) i.putExtra(PROPSFORFLIGHTEXISTINGID, mle!!.idFlight) i.putExtra(PROPSFORFLIGHTCROSSFILLVALUE, mle!!.decTotal) i.putExtra( TACHFORCROSSFILLVALUE, getHighWaterTachForAircraft( mle!!.idAircraft ) ) mPropertiesLauncher!!.launch(i) } private fun onHobbsChanged(v: View) { if (mle != null && MFBLocation.fPrefAutoFillTime === AutoFillOptions.HobbsTime) { val txtHobbsStart = findViewById(R.id.txtHobbsStart) as EditText? val txtHobbsEnd = findViewById(R.id.txtHobbsEnd) as EditText? val newHobbsStart = doubleFromField(R.id.txtHobbsStart) val newHobbsEnd = doubleFromField(R.id.txtHobbsEnd) if (v === txtHobbsStart && newHobbsStart != mle!!.hobbsStart || v === txtHobbsEnd && newHobbsEnd != mle!!.hobbsEnd ) doAutoTotals() } } override fun updateDate(id: Int, dt: Date?) { var dt2 = dt fromView() var fEngineChanged = false var fFlightChanged = false var fBlockChanged = false dt2 = removeSeconds(dt2!!) when (id) { R.id.btnEngineStartSet -> { mle!!.dtEngineStart = dt2 fEngineChanged = true resetDateOfFlight() } R.id.btnEngineEndSet -> { mle!!.dtEngineEnd = dt2 fEngineChanged = true showRecordingIndicator() } R.id.btnBlockOut -> { handlePotentiallyDefaultedProperty(mle!!.addOrSetPropertyDate(CustomPropertyType.idPropTypeBlockOut, dt2)) resetDateOfFlight() fBlockChanged = true } R.id.btnBlockIn -> { handlePotentiallyDefaultedProperty(mle!!.addOrSetPropertyDate(CustomPropertyType.idPropTypeBlockIn, dt2)) fBlockChanged = true } R.id.btnFlightStartSet -> { mle!!.dtFlightStart = dt2 resetDateOfFlight() fFlightChanged = true } R.id.btnFlightEndSet -> { mle!!.dtFlightEnd = dt2 fFlightChanged = true } R.id.btnFlightSet -> { mle!!.dtFlight = dt2 } } toView() when (MFBLocation.fPrefAutoFillHobbs) { AutoFillOptions.EngineTime -> if (fEngineChanged) doAutoHobbs() AutoFillOptions.FlightTime -> if (fFlightChanged) doAutoHobbs() else -> {} } when (MFBLocation.fPrefAutoFillTime) { AutoFillOptions.EngineTime -> if (fEngineChanged) doAutoTotals() AutoFillOptions.FlightTime -> if (fFlightChanged) doAutoTotals() AutoFillOptions.BlockTime -> if (fBlockChanged) doAutoTotals() AutoFillOptions.HobbsTime -> {} AutoFillOptions.FlightStartToEngineEnd -> doAutoTotals() else -> {} } } private fun validateAircraftID(id: Int): Int { var idAircraftToUse = -1 if (mRgac != null) { for (ac in mRgac!!) if (ac.aircraftID == id) { idAircraftToUse = id break } } return idAircraftToUse } private fun resetFlight(fCarryHobbs: Boolean) { // start up a new flight with the same aircraft ID and public setting. // first, validate that the aircraft is still OK for the user val hobbsEnd = mle!!.hobbsEnd val leNew = LogbookEntry(validateAircraftID(mle!!.idAircraft), mle!!.fPublic) if (fCarryHobbs) leNew.hobbsStart = hobbsEnd mActivetemplates!!.clear() mle!!.idAircraft = leNew.idAircraft // so that updateTemplatesForAircraft works updateTemplatesForAircraft(false) setLogbookEntry(leNew) MFBMain.newFlightListener?.setInProgressFlight(leNew) saveCurrentFlight() // flush any pending flight data getMainLocation()!!.resetFlightData() // and flush any pause/play data fPaused = false dtPauseTime = 0 dtTimeOfLastPause = 0 accumulatedNight = 0.0 } private fun submitFlight(forceQueued: Boolean) { val le = mle!! if (le.isNewFlight() || le.signatureStatus != SigStatus.Valid) submitFlightConfirmed(forceQueued) else { AlertDialog.Builder( requireActivity(), R.style.MFBDialog ) .setIcon(android.R.drawable.ic_dialog_alert) .setTitle(R.string.lblConfirm) .setMessage(R.string.lblConfirmModifySignedFlight) .setPositiveButton(R.string.lblOK) { _: DialogInterface?, _: Int -> submitFlightConfirmed(forceQueued) } .setNegativeButton(R.string.lblCancel, null) .show() } } private fun submitFlightConfirmed(forceQueued: Boolean) { fromView() val a: Activity = requireActivity() if (a.currentFocus != null) a.currentFocus!!.clearFocus() // force any in-progress edit to commit, particularly for properties. val fIsNew = mle!!.isNewFlight() // hold onto this because we can change the status. if (fIsNew) { getMainLocation()?.isRecording = false showRecordingIndicator() } // load any pending properties from the DB into the logbookentry object itself. mle!!.syncProperties() // load the telemetry string, if it's a first submission. if (mle!!.isNewFlight()) mle!!.szFlightData = getMainLocation()!!.flightDataString // Save for later if offline or if forceQueued val fIsOnline = isOnline(context) if (forceQueued || !fIsOnline) { // save the flight with id of -2 if it's a new flight if (fIsNew) mle!!.idFlight = if (forceQueued) LogbookEntry.ID_QUEUED_FLIGHT_UNSUBMITTED else LogbookEntry.ID_UNSUBMITTED_FLIGHT // Existing flights can't be saved for later. No good reason for that except work. if (mle!!.isExistingFlight()) { AlertDialog.Builder(requireActivity(), R.style.MFBDialog) .setMessage(getString(R.string.errNoInternetNoSave)) .setTitle(getString(R.string.txtError)) .setNegativeButton(getString(R.string.lblOK)) { d: DialogInterface, _: Int -> d.cancel() finish() } .create().show() return } // now save it - but check for success if (!mle!!.toDB()) { // Failure! // Try saving it without the flight data string, in case that was the issue mle!!.szFlightData = "" if (!mle!!.toDB()) { // still didn't work. give an error message and, if necessary, // restore to being a new flight. alert(this, getString(R.string.txtError), mle!!.szError) // restore the previous idFlight if we were saving a new flight. if (fIsNew) { mle!!.idFlight = LogbookEntry.ID_NEW_FLIGHT saveCurrentFlight() } return } // if we're here, then phew - saved without the string } // if we're here, save was successful (even if flight data was dropped) clearCachedFlights() MFBMain.invalidateCachedTotals() if (fIsNew) { resetFlight(true) alert(this, getString(R.string.txtSuccess), getString(R.string.txtFlightQueued)) } else { AlertDialog.Builder(requireActivity(), R.style.MFBDialog) .setMessage(getString(R.string.txtFlightQueued)) .setTitle(getString(R.string.txtSuccess)) .setNegativeButton("OK") { d: DialogInterface, _: Int -> d.cancel() finish() } .create().show() } } else { val le = mle submitFlight(le) } } private fun setVisibilityForRow(rowID: Int, visible : Boolean) { val v = findViewById(rowID) v!!.visibility = if (visible) View.VISIBLE else View.GONE } override fun toView() { if (view == null) return setStringForField(R.id.txtComments, mle!!.szComments) setStringForField(R.id.txtRoute, mle!!.szRoute) setIntForField(R.id.txtApproaches, mle!!.cApproaches) setIntForField(R.id.txtLandings, mle!!.cLandings) setIntForField(R.id.txtFSNightLandings, mle!!.cNightLandings) setIntForField(R.id.txtDayLandings, mle!!.cFullStopLandings) setCheckState(R.id.ckMyFlightbook, mle!!.fPublic) setCheckState(R.id.ckHold, mle!!.fHold) setLocalDateForField(R.id.btnFlightSet, mle!!.dtFlight) // Engine/Flight dates val tachStart = mle!!.propDoubleForID(CustomPropertyType.idPropTypeTachStart) val tachEnd = mle!!.propDoubleForID(CustomPropertyType.idPropTypeTachEnd) val blockOut = mle!!.propDateForID(CustomPropertyType.idPropTypeBlockOut) val blockIn = mle!!.propDateForID(CustomPropertyType.idPropTypeBlockIn) setUTCDateForField(R.id.btnEngineStartSet, mle!!.dtEngineStart) setUTCDateForField(R.id.btnEngineEndSet, mle!!.dtEngineEnd) setUTCDateForField(R.id.btnFlightStartSet, mle!!.dtFlightStart) setUTCDateForField(R.id.btnFlightEndSet, mle!!.dtFlightEnd) setDoubleForField(R.id.txtHobbsStart, mle!!.hobbsStart) setDoubleForField(R.id.txtHobbsEnd, mle!!.hobbsEnd) setDoubleForField(R.id.txtTachStart, tachStart) setDoubleForField(R.id.txtTachEnd, tachEnd) setUTCDateForField(R.id.btnBlockOut, blockOut) setUTCDateForField(R.id.btnBlockIn, blockIn) // show tach/block in "In the cockpit" only if the options are selected (will otherwise show in properties)... val showTach = fShowTach val showBlock = fShowBlock //...but hobbs/engine/flight must be shown if they have values, since they won't show anywhere else. val showHobbs = fShowHobbs || mle!!.hobbsStart > 0 || mle!!.hobbsEnd > 0 val showEngine = fShowEngine || mle!!.isKnownEngineStart || mle!!.isKnownEngineEnd val showFlight = fShowFlight || mle!!.isKnownFlightStart || mle!!.isKnownFlightEnd setVisibilityForRow(R.id.rowTachStart, showTach) setVisibilityForRow(R.id.rowTachEnd, showTach) setVisibilityForRow(R.id.rowHobbsStart, showHobbs) setVisibilityForRow(R.id.rowHobbsEnd, showHobbs) setVisibilityForRow(R.id.rowEngineStart, showEngine) setVisibilityForRow(R.id.rowEngineEnd, showEngine) setVisibilityForRow(R.id.rowBlockOut, showBlock) setVisibilityForRow(R.id.rowBlockIn, showBlock) setVisibilityForRow(R.id.rowFlightStart, showFlight) setVisibilityForRow(R.id.rowFlightEnd, showFlight) setDoubleForField(R.id.txtCFI, mle!!.decCFI) setDoubleForField(R.id.txtDual, mle!!.decDual) setDoubleForField(R.id.txtGround, mle!!.decGrndSim) setDoubleForField(R.id.txtIMC, mle!!.decIMC) setDoubleForField(R.id.txtNight, mle!!.decNight) setDoubleForField(R.id.txtPIC, mle!!.decPIC) setDoubleForField(R.id.txtSIC, mle!!.decSIC) setDoubleForField(R.id.txtSimIMC, mle!!.decSimulatedIFR) setDoubleForField(R.id.txtTotal, mle!!.decTotal) setDoubleForField(R.id.txtXC, mle!!.decXC) val fIsSigned = mle!!.signatureStatus !== SigStatus.None findViewById(R.id.sectSignature)!!.visibility = if (fIsSigned) View.VISIBLE else View.GONE findViewById(R.id.txtSignatureHeader)!!.visibility = if (fIsSigned) View.VISIBLE else View.GONE if (fIsSigned) { val imgSigStatus = findViewById(R.id.imgSigState) as ImageView? when (mle!!.signatureStatus) { SigStatus.None -> {} SigStatus.Valid -> { imgSigStatus!!.setImageResource(R.drawable.sigok) imgSigStatus.contentDescription = getString(R.string.cdIsSignedValid) (findViewById(R.id.txtSigState) as TextView?)!!.text = getString(R.string.cdIsSignedValid) } SigStatus.Invalid -> { imgSigStatus!!.setImageResource(R.drawable.siginvalid) imgSigStatus.contentDescription = getString(R.string.cdIsSignedInvalid) (findViewById(R.id.txtSigState) as TextView?)!!.text = getString(R.string.cdIsSignedInvalid) } } val szSigInfo1 = if (isNullDate(mle!!.signatureDate)) "" else String.format( Locale.getDefault(), getString(R.string.lblSignatureTemplate1), DateFormat.getDateFormat(requireActivity()).format(mle!!.signatureDate!!), mle!!.signatureCFIName ) val szSigInfo2 = if (isNullDate(mle!!.signatureCFIExpiration)) String.format( Locale.getDefault(), getString(R.string.lblSignatureTemplate2NoExp), mle!!.signatureCFICert ) else String.format( Locale.getDefault(), getString(R.string.lblSignatureTemplate2), mle!!.signatureCFICert, DateFormat.getDateFormat(requireActivity()).format( mle!!.signatureCFIExpiration!! ) ) (findViewById(R.id.txtSigInfo1) as TextView?)!!.text = szSigInfo1 (findViewById(R.id.txtSigInfo2) as TextView?)!!.text = szSigInfo2 (findViewById(R.id.txtSigComment) as TextView?)!!.text = mle!!.signatureComments val ivDigitizedSig = findViewById(R.id.imgDigitizedSig) as ImageView? if (mle!!.signatureHasDigitizedSig) { if (ivDigitizedSig!!.drawable == null) { val szURL = String.format( Locale.US, "https://%s/Logbook/Public/ViewSig.aspx?id=%d", MFBConstants.szIP, mle!!.idFlight ) fetchDigitizedSig(szURL, ivDigitizedSig) } } else ivDigitizedSig!!.visibility = View.GONE } // Aircraft spinner val rgSelectibleAircraft = selectibleAircraft() if (rgSelectibleAircraft != null) { val sp = findViewById(R.id.spnAircraft) as Spinner? // Pick the first selectible aircraft, if no aircraft is selected if (mle!!.idAircraft == -1 && rgSelectibleAircraft.isNotEmpty()) mle!!.idAircraft = rgSelectibleAircraft[0].aircraftID // Issue #188 set the spinner, but ONLY if it's not currently set to the correct tail. val ac = sp!!.selectedItem as Aircraft? if (ac == null || ac.aircraftID != mle!!.idAircraft) { for (i in rgSelectibleAircraft.indices) { if (mle!!.idAircraft == rgSelectibleAircraft[i].aircraftID) { sp.setSelection(i) sp.prompt = "Current Aircraft: " + rgSelectibleAircraft[i].tailNumber break } } } } // Current properties if (!mle!!.isExistingFlight() && mle!!.rgCustomProperties.isEmpty()) mle!!.syncProperties() setUpPropertiesForFlight() updateElapsedTime() updatePausePlayButtonState() } override fun fromView() { if (view == null || mle == null) return // Integer fields mle!!.cApproaches = intFromField(R.id.txtApproaches) mle!!.cFullStopLandings = intFromField(R.id.txtDayLandings) mle!!.cLandings = intFromField(R.id.txtLandings) mle!!.cNightLandings = intFromField(R.id.txtFSNightLandings) // Double fields mle!!.decCFI = doubleFromField(R.id.txtCFI) mle!!.decDual = doubleFromField(R.id.txtDual) mle!!.decGrndSim = doubleFromField(R.id.txtGround) mle!!.decIMC = doubleFromField(R.id.txtIMC) mle!!.decNight = doubleFromField(R.id.txtNight) mle!!.decPIC = doubleFromField(R.id.txtPIC) mle!!.decSIC = doubleFromField(R.id.txtSIC) mle!!.decSimulatedIFR = doubleFromField(R.id.txtSimIMC) mle!!.decTotal = doubleFromField(R.id.txtTotal) mle!!.decXC = doubleFromField(R.id.txtXC) mle!!.hobbsStart = doubleFromField(R.id.txtHobbsStart) mle!!.hobbsEnd = doubleFromField(R.id.txtHobbsEnd) // Date - no-op because it should be in sync // Flight/Engine times - ditto // But tach, if shown, isn't coming from props, so load it here. if (fShowTach) { handlePotentiallyDefaultedProperty(mle!!.addOrSetPropertyDouble(CustomPropertyType.idPropTypeTachStart, doubleFromField(R.id.txtTachStart))) handlePotentiallyDefaultedProperty(mle!!.addOrSetPropertyDouble(CustomPropertyType.idPropTypeTachEnd, doubleFromField(R.id.txtTachEnd))) } // checkboxes mle!!.fHold = checkState(R.id.ckHold) mle!!.fPublic = checkState(R.id.ckMyFlightbook) // And strings mle!!.szComments = stringFromField(R.id.txtComments) mle!!.szRoute = stringFromField(R.id.txtRoute) // Aircraft spinner mle!!.idAircraft = selectedAircraftID() } private fun selectedAircraftID(): Int { val rgSelectibleAircraft = selectibleAircraft() if (rgSelectibleAircraft != null && rgSelectibleAircraft.isNotEmpty()) { val sp = findViewById(R.id.spnAircraft) as Spinner? val ac = sp!!.selectedItem as Aircraft return ac.aircraftID } return -1 } private fun doAutoTotals() { fromView() val sp = findViewById(R.id.spnAircraft) as Spinner? if (mle!!.autoFillTotal( if (mle!!.idAircraft > 0 && sp!!.selectedItem != null) sp.selectedItem as Aircraft else null, totalTimePaused() ) > 0 ) toView() } private fun doAutoHobbs() { fromView() if (mle!!.autoFillHobbs(totalTimePaused()) > 0) { toView() // sync the view to the change we just made - especially since autototals can read it. // if total is linked to hobbs, need to do autotime too if (MFBLocation.fPrefAutoFillTime === AutoFillOptions.HobbsTime) doAutoTotals() } } private fun resetDateOfFlight() { if (mle != null && mle!!.isNewFlight()) { // set the date of the flight to now in local time. var dt = Date() if (mle!!.isKnownEngineStart && mle!!.dtEngineStart < dt) dt = mle!!.dtEngineStart if (mle!!.isKnownFlightStart && mle!!.dtFlightStart < dt) dt = mle!!.dtFlightStart val dtBlockOut = mle!!.propDateForID(CustomPropertyType.idPropTypeBlockOut) if (dtBlockOut != null && !isNullDate(dtBlockOut) && dtBlockOut < dt) dt = dtBlockOut mle!!.dtFlight = dt setLocalDateForField(R.id.btnFlightSet, mle!!.dtFlight) } } private fun engineStart() { // don't do any GPS stuff unless this is a new flight if (!mle!!.isNewFlight()) return resetDateOfFlight() if (MFBLocation.fPrefAutoDetect) appendNearest() getMainLocation()?.isRecording = true // will respect preference showRecordingIndicator() if (MFBConstants.fFakeGPS) { getMainLocation()!!.stopListening(requireContext()) getMainLocation()?.isRecording = true // will respect preference val gpss = GPSSim(getMainLocation()!!) gpss.feedEvents() } } private fun engineStop() { // don't do any GPS stuff unless this is a new flight if (!mle!!.isNewFlight()) return if (MFBLocation.fPrefAutoDetect) appendNearest() getMainLocation()?.isRecording = false doAutoHobbs() doAutoTotals() showRecordingIndicator() unPauseFlight() } private fun flightStart() { // don't do any GPS stuff unless this is a new flight if (!mle!!.isNewFlight()) return if (!mle!!.isKnownEngineStart) resetDateOfFlight() getMainLocation()?.isRecording = true if (MFBLocation.fPrefAutoDetect) appendNearest() unPauseFlight() // don't pause in flight } private fun flightStop() { // don't do any GPS stuff unless this is a new flight if (!mle!!.isNewFlight()) return if (MFBLocation.fPrefAutoDetect) appendNearest() } private fun showRecordingIndicator() { imgRecording!!.visibility = if (getMainLocation() != null && getMainLocation()?.isRecording!!) View.VISIBLE else View.INVISIBLE } private var dfSunriseSunset: SimpleDateFormat? = null private fun displaySpeed(s: Double): String { val res = resources return if (s < 1) res.getString(R.string.strEmpty) else when (ActOptions.speedUnits) { SpeedUnits.Knots -> String.format( Locale.getDefault(), res.getString(R.string.lblSpeedFormatKts), s * MFBConstants.MPS_TO_KNOTS ) SpeedUnits.KmPerHour -> String.format( Locale.getDefault(), res.getString(R.string.lblSpeedFormatKph), s * MFBConstants.MPS_TO_KPH ) SpeedUnits.MilesPerHour -> String.format( Locale.getDefault(), res.getString(R.string.lblSpeedFormatMph), s * MFBConstants.MPS_TO_MPH ) } } private fun displayAlt(a: Double): String { val res = resources return when (ActOptions.altitudeUnits) { AltitudeUnits.Feet -> String.format( Locale.getDefault(), res.getString(R.string.lblAltFormatFt), (a * MFBConstants.METERS_TO_FEET).roundToInt() ) AltitudeUnits.Meters -> String.format( Locale.getDefault(), res.getString(R.string.lblAltFormatMeters), a.roundToInt() ) } } override fun updateStatus( quality: GPSQuality, fAirborne: Boolean?, loc: Location?, fRecording: Boolean? ) { if (!isAdded || isDetached) { return } else { requireActivity() } showRecordingIndicator() val res = resources val idSzQuality: Int = when (quality) { GPSQuality.Excellent -> R.string.lblGPSExcellent GPSQuality.Good -> R.string.lblGPSGood GPSQuality.Poor -> R.string.lblGPSPoor else -> R.string.lblGPSUnknown } if (loc != null) { txtQuality!!.text = res.getString(idSzQuality) txtSpeed!!.text = displaySpeed(loc.speed.toDouble()) txtAltitude!!.text = displayAlt(loc.altitude) val lat = loc.latitude val lon = loc.longitude txtLatitude!!.text = String.format( Locale.getDefault(), "%.5f°%s", abs(lat), if (lat > 0) "N" else "S" ) txtLongitude!!.text = String.format( Locale.getDefault(), "%.5f°%s", abs(lon), if (lon > 0) "E" else "W" ) val sst = SunriseSunsetTimes(Date(loc.time), lat, lon) if (dfSunriseSunset == null) dfSunriseSunset = SimpleDateFormat("hh:mm a z", Locale.getDefault()) txtSunrise!!.text = dfSunriseSunset!!.format(sst.sunrise) txtSunset!!.text = dfSunriseSunset!!.format(sst.sunset) } // don't show in-air/on-ground if we aren't actually detecting these if (MFBLocation.fPrefAutoDetect) txtStatus!!.text = res.getString(if (fAirborne!!) R.string.lblFlightInAir else R.string.lblFlightOnGround) else txtStatus!!.text = res.getString(R.string.lblGPSUnknown) if (fAirborne!!) unPauseFlight() } // Pause/play functionality private fun timeSinceLastPaused(): Long { return if (fPaused) Date().time - dtTimeOfLastPause else 0 } private fun totalTimePaused(): Long { return dtPauseTime + timeSinceLastPaused() } private fun pauseFlight() { dtTimeOfLastPause = Date().time fPaused = true } override fun unPauseFlight() { if (fPaused) { dtPauseTime += timeSinceLastPaused() fPaused = false // do this AFTER calling [self timeSinceLastPaused] } } override fun isPaused(): Boolean { return fPaused } override fun togglePausePlay() { if (fPaused) unPauseFlight() else pauseFlight() updatePausePlayButtonState() } override fun startEngine() { if (mle != null && !mle!!.isKnownEngineStart) { mle!!.dtEngineStart = nowWith0Seconds() engineStart() toView() } } override fun stopEngine() { if (mle != null && !mle!!.isKnownEngineEnd) { mle!!.dtEngineEnd = nowWith0Seconds() engineStop() toView() } } private fun updateElapsedTime() { // update the button state val ib = findViewById(R.id.btnPausePlay) as ImageButton? // pause/play should only be visible on ground with engine running (or flight start known but engine end unknown) if (mle == null) // should never happen! return val fShowPausePlay = !MFBLocation.IsFlying && (mle!!.isKnownEngineStart || mle!!.isKnownFlightStart) && !mle!!.isKnownEngineEnd ib!!.visibility = if (fShowPausePlay) View.VISIBLE else View.INVISIBLE val txtElapsed = findViewById(R.id.txtElapsedTime) as TextView? if (txtElapsed != null) { var dtTotal: Long var dtFlight: Long = 0 var dtEngine: Long = 0 val fIsKnownFlightStart = mle!!.isKnownFlightStart val fIsKnownEngineStart = mle!!.isKnownEngineStart if (fIsKnownFlightStart) { dtFlight = if (!mle!!.isKnownFlightEnd) // in flight Date().time - mle!!.dtFlightStart.time else mle!!.dtFlightEnd.time - mle!!.dtFlightStart.time } if (fIsKnownEngineStart) { dtEngine = if (!mle!!.isKnownEngineEnd) Date().time - mle!!.dtEngineStart.time else mle!!.dtEngineEnd.time - mle!!.dtEngineStart.time } // if totals mode is FLIGHT TIME, then elapsed time is based on flight time if/when it is known. // OTHERWISE, we use engine time (if known) or else flight time. dtTotal = if (MFBLocation.fPrefAutoFillTime === AutoFillOptions.FlightTime) if (fIsKnownFlightStart) dtFlight else 0 else if (fIsKnownEngineStart) dtEngine else dtFlight dtTotal -= totalTimePaused() if (dtTotal <= 0) dtTotal = 0 // should never happen // dtTotal is in milliseconds - convert it to seconds for ease of reading dtTotal = (dtTotal / 1000.0).toLong() val sTime = String.format( Locale.US, "%02d:%02d:%02d", (dtTotal / 3600).toInt(), dtTotal.toInt() % 3600 / 60, dtTotal.toInt() % 60 ) txtElapsed.text = sTime } showRecordingIndicator() } private fun updatePausePlayButtonState() { // update the button state val ib = findViewById(R.id.btnPausePlay) as ImageButton? ib!!.setImageResource(if (fPaused) R.drawable.play else R.drawable.pause) } private fun toggleFlightPause() { // don't pause or play if we're not flying/engine started if (mle!!.isKnownFlightStart || mle!!.isKnownEngineStart) { if (fPaused) unPauseFlight() else pauseFlight() } else { unPauseFlight() dtPauseTime = 0 } updateElapsedTime() updatePausePlayButtonState() } /* * (non-Javadoc) * @see com.myflightbook.android.ActMFBForm.GallerySource#getGalleryID() * GallerySource protocol */ override fun getGalleryID(): Int { return R.id.tblImageTable } override fun getGalleryHeader(): View { return findViewById(R.id.txtImageHeader)!! } override fun getImages(): Array<MFBImageInfo> { return if (mle == null || mle!!.rgFlightImages == null) arrayOf() else mle!!.rgFlightImages!! } override fun setImages(rgmfbii: Array<MFBImageInfo>?) { if (mle == null) { throw NullPointerException("m_le is null in setImages") } mle!!.rgFlightImages = rgmfbii } override fun newImage(mfbii: MFBImageInfo?) { Log.w( MFBConstants.LOG_TAG, String.format("newImage called. m_le is %s", if (mle == null) "null" else "not null") ) mle!!.addImageForflight(mfbii!!) } override fun refreshGallery() { setUpGalleryForFlight() } override fun getPictureDestination(): PictureDestination { return PictureDestination.FlightImage } override fun invalidate() { resetFlight(false) } private fun updateIfChanged(id: Int, value: Int) { if (intFromField(id) != value) setIntForField(id, value) } // Update the fields which could possibly have changed via auto-detect override fun refreshDetectedFields() { setUTCDateForField(R.id.btnFlightStartSet, mle!!.dtFlightStart) setUTCDateForField(R.id.btnFlightEndSet, mle!!.dtFlightEnd) updateIfChanged(R.id.txtLandings, mle!!.cLandings) updateIfChanged(R.id.txtFSNightLandings, mle!!.cNightLandings) updateIfChanged(R.id.txtDayLandings, mle!!.cFullStopLandings) setDoubleForField(R.id.txtNight, mle!!.decNight) setStringForField(R.id.txtRoute, mle!!.szRoute) } private fun setUpPropertiesForFlight() { val a: Activity = requireActivity() val l = a.layoutInflater val tl = findViewById(R.id.tblPinnedProperties) as TableLayout? ?: return tl.removeAllViews() if (mle == null) return // Handle block Out having been specified by viewprops var fHadBlockOut = false for (fp in mle!!.rgCustomProperties) if (fp.idPropType == CustomPropertyType.idPropTypeBlockOut) { fHadBlockOut = true break } mle!!.syncProperties() val pinnedProps = getPinnedProperties( requireActivity().getSharedPreferences( CustomPropertyType.prefSharedPinnedProps, Activity.MODE_PRIVATE ) ) val templateProps = mergeTemplates( mActivetemplates!!.toTypedArray() ) val rgcptAll = cachedPropertyTypes Arrays.sort(rgcptAll) val rgProps = crossProduct(mle!!.rgCustomProperties, rgcptAll) var fHasBlockOutAdded = false for (fp in rgProps) { // should never happen, but does - not sure why if (fp.getCustomPropertyType() == null) fp.refreshPropType() if (fp.idPropType == CustomPropertyType.idPropTypeBlockOut && !fp.isDefaultValue()) fHasBlockOutAdded = true // Don't show any properties that are: // a) unpinned and default value, or // b) "hoisted" into the "in the cockpit" section val fIsPinned = isPinnedProperty(pinnedProps, fp.idPropType) if (!fIsPinned && !templateProps.contains(fp.idPropType) && fp.isDefaultValue()) continue if (fShowTach && (fp.idPropType == CustomPropertyType.idPropTypeTachStart || fp.idPropType == CustomPropertyType.idPropTypeTachEnd)) continue if (fShowBlock && (fp.idPropType == CustomPropertyType.idPropTypeBlockOut || fp.idPropType == CustomPropertyType.idPropTypeBlockIn)) continue val tr = l.inflate(R.layout.cpttableitem, tl, false) as TableRow tr.id = View.generateViewId() val pe: PropertyEdit = tr.findViewById(R.id.propEdit) val onCrossFill = object : CrossFillDelegate { override fun crossFillRequested(sender: DecimalEdit?) { val d = getHighWaterTachForAircraft(selectedAircraftID()) if (d > 0 && sender != null) sender.doubleValue = d } } pe.initForProperty( fp, tr.id, this, if (fp.getCustomPropertyType()!!.idPropType == CustomPropertyType.idPropTypeTachStart) onCrossFill else this) tr.findViewById<View>(R.id.imgFavorite).visibility = if (fIsPinned) View.VISIBLE else View.INVISIBLE tl.addView( tr, TableLayout.LayoutParams( TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.WRAP_CONTENT ) ) } if (!fHadBlockOut && fHasBlockOutAdded) resetDateOfFlight() } //region in-line property editing private fun deleteProperty(fp : FlightProperty) { lifecycleScope.launch { doAsync<FlightPropertiesSvc, Any?>( requireActivity(), FlightPropertiesSvc(), getString(R.string.prgDeleteProp), { s -> s.deletePropertyForFlight(AuthToken.m_szAuthToken, fp.idFlight, fp.idProp,requireContext()) }, { _, _ -> setUpPropertiesForFlight() } ) } } private fun deleteDefaultedProperty(fp: FlightProperty) { if (fp.idProp > 0 && fp.isDefaultValue()) { deleteProperty(fp) return } // Otherwise, save it val rgProps = crossProduct(mle!!.rgCustomProperties, cachedPropertyTypes) val rgfpUpdated = distillList(rgProps) rewritePropertiesForFlight(mle!!.idLocalDB, rgfpUpdated) } private fun handlePotentiallyDefaultedProperty(fp : FlightProperty?) { if (mle!!.idFlight > 0 && fp != null && fp.idProp > 0 && fp.isDefaultValue()) { fp.idFlight = mle!!.idFlight // this is pointing to the LOCAL db ID of the flight, so we need to point it instead to the server-based flight id2 deleteProperty(fp) } } override fun updateProperty(id: Int, fp: FlightProperty) { if (mle == null) { // this can get called by PropertyEdit as it loses focus. return } val rgProps = crossProduct(mle!!.rgCustomProperties, cachedPropertyTypes) for (i in rgProps.indices) { if (rgProps[i].idPropType == fp.idPropType) { rgProps[i] = fp deleteDefaultedProperty(fp) rewritePropertiesForFlight(mle!!.idLocalDB, distillList(rgProps)) mle!!.syncProperties() break } } if (MFBLocation.fPrefAutoFillTime === AutoFillOptions.BlockTime && (fp.idPropType == CustomPropertyType.idPropTypeBlockOut || fp.idPropType == CustomPropertyType.idPropTypeBlockIn) ) doAutoTotals() } override fun dateOfFlightShouldReset(dt: Date) { resetDateOfFlight() } //endregion // region Templates private fun updateTemplatesForAircraft(noDefault: Boolean) { val a = activity ?: return // this can be called via invalidate, which can be called before everything is set up, so check for null if (PropertyTemplate.sharedTemplates == null && getSharedTemplates( a.getSharedPreferences( PropertyTemplate.PREF_KEY_TEMPLATES, Activity.MODE_PRIVATE ) ) == null ) return val rgDefault = defaultTemplates val ptAnon = anonTemplate val ptSim = simTemplate val ac = getAircraftById(mle!!.idAircraft, mRgac) if (ac != null && ac.defaultTemplates.size > 0) mActivetemplates!!.addAll( listOf( *templatesWithIDs( ac.defaultTemplates ) ) ) else if (rgDefault.isNotEmpty() && !noDefault) mActivetemplates!!.addAll( listOf(*rgDefault) ) mActivetemplates!!.remove(ptAnon) mActivetemplates!!.remove(ptSim) // Always add in sims or anon as appropriate if (ac != null) { if (ac.isAnonymous() && ptAnon != null) mActivetemplates!!.add(ptAnon) if (!ac.isReal() && ptSim != null) mActivetemplates!!.add(ptSim) } } // endregion companion object { const val PROPSFORFLIGHTID = "com.myflightbook.android.FlightPropsID" const val PROPSFORFLIGHTEXISTINGID = "com.myflightbook.android.FlightPropsIDExisting" const val PROPSFORFLIGHTCROSSFILLVALUE = "com.myflightbook.android.FlightPropsXFill" const val TACHFORCROSSFILLVALUE = "com.myflightbook.android.TachStartXFill" // current state of pause/play and accumulated night var fPaused = false private var dtPauseTime: Long = 0 private var dtTimeOfLastPause: Long = 0 var accumulatedNight = 0.0 // pause/play state private const val m_KeysIsPaused = "flightIsPaused" private const val m_KeysPausedTime = "totalPauseTime" private const val m_KeysTimeOfLastPause = "timeOfLastPause" private const val m_KeysAccumulatedNight = "accumulatedNight" // Expand state of "in the cockpit" private const val m_KeyShowInCockpit = "inTheCockpit" // Display options var fShowTach = false var fShowHobbs = true var fShowEngine = true var fShowBlock = false var fShowFlight = true const val prefKeyShowTach = "cockpitShowTach" const val prefKeyShowHobbs = "cockpitShowHobbs" const val prefKeyShowEngine = "cockpitShowEngine" const val prefKeyShowBlock = "cockpitShowBlock" const val prefKeyShowFlight = "cockpitShowFlight" } }
gpl-3.0
NoodleMage/tachiyomi
app/src/main/java/eu/kanade/tachiyomi/ui/library/LibraryHolder.kt
3
855
package eu.kanade.tachiyomi.ui.library import android.view.View import eu.davidea.flexibleadapter.FlexibleAdapter import eu.kanade.tachiyomi.ui.base.holder.BaseFlexibleViewHolder /** * Generic class used to hold the displayed data of a manga in the library. * @param view the inflated view for this holder. * @param adapter the adapter handling this holder. * @param listener a listener to react to the single tap and long tap events. */ abstract class LibraryHolder( view: View, adapter: FlexibleAdapter<*> ) : BaseFlexibleViewHolder(view, adapter) { /** * Method called from [LibraryCategoryAdapter.onBindViewHolder]. It updates the data for this * holder with the given manga. * * @param item the manga item to bind. */ abstract fun onSetValues(item: LibraryItem) }
apache-2.0
stokito/IdeaSingletonInspection
src/main/java/com/github/stokito/IdeaSingletonInspection/quickFixes/QuickFixes.kt
1
377
package com.github.stokito.IdeaSingletonInspection.quickFixes object QuickFixes { val INSTANCE_GETTERS_MODIFIERS = InstanceGettersModifiersFix() val INSTANCE_GETTERS_RETURN_TYPE = InstanceGettersReturnTypeFix() val CONSTRUCTOR_MODIFIERS = ConstructorModifiersFix() val CREATE_CONSTRUCTOR = CreateConstructorFix() val SET_CLASS_FINAL = SetClassFinalFix() }
apache-2.0
YaroslavHavrylovych/android_playground
ex_sqlite/app/src/main/kotlin/ex/android/yaroslavlancelot/com/sql/activeandroid/Contact.kt
1
936
package ex.android.yaroslavlancelot.com.sql.activeandroid import com.activeandroid.Model import com.activeandroid.annotation.Column import com.activeandroid.annotation.Table import ex.android.yaroslavlancelot.com.sql.DBConstants /** * Represent row in the database. * * @author Yaroslav Havrylovych */ @Table(name = DBConstants.TABLE_NAME, id = DBConstants.COLUMN_NAME_ID) class Contact : Model { @Column(notNull = true, name = DBConstants.COLUMN_NAME_NAME) var name: String? = null @Column(notNull = true, name = DBConstants.COLUMN_NAME_SURNAME) var surname: String? = null @Column(notNull = true, name = DBConstants.COLUMN_NAME_PHONE_NUMBER) var phoneNumber: String? = null constructor() { //just for Ormlite } constructor(name: String, surname: String, phoneNumber: String) { this.name = name this.surname = surname this.phoneNumber = phoneNumber } }
apache-2.0
STUDIO-apps/GeoShare_Android
mobile/src/main/java/uk/co/appsbystudio/geoshare/friends/profile/friends/pages/mutual/ProfileFriendsMutualPresenter.kt
1
164
package uk.co.appsbystudio.geoshare.friends.profile.friends.pages.mutual interface ProfileFriendsMutualPresenter { fun friends(uid: String) fun stop() }
apache-2.0
skydoves/WaterDrink
app/src/main/java/com/skydoves/waterdays/ui/customViews/NumberPicker.kt
1
1584
/* * Copyright (C) 2016 skydoves * * 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.skydoves.waterdays.ui.customViews import android.content.Context import android.graphics.Color import android.util.AttributeSet import android.view.View import android.widget.EditText /** * Created by skydoves on 2016-10-15. * Updated by skydoves on 2017-08-17. * Copyright (c) 2017 skydoves rights reserved. */ class NumberPicker(context: Context, attrs: AttributeSet) : android.widget.NumberPicker(context, attrs) { override fun addView(child: View) { super.addView(child) updateView(child) } override fun addView(child: View, index: Int, params: android.view.ViewGroup.LayoutParams) { super.addView(child, index, params) updateView(child) } override fun addView(child: View, params: android.view.ViewGroup.LayoutParams) { super.addView(child, params) updateView(child) } private fun updateView(view: View) { if (view is EditText) { view.textSize = 18f view.setTextColor(Color.parseColor("#ffffff")) } } }
apache-2.0
carlphilipp/chicago-commutes
android-app/src/main/kotlin/fr/cph/chicago/repository/entity/PositionDb.kt
1
777
/** * Copyright 2021 Carl-Philipp Harmant * * * 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 fr.cph.chicago.repository.entity import io.realm.RealmObject open class PositionDb(var latitude: Double = 0.0, var longitude: Double = 0.0) : RealmObject()
apache-2.0
RyanAndroidTaylor/Rapido
rapidosqlite/src/main/java/com/izeni/rapidosqlite/DataConnection.kt
1
8583
package com.izeni.rapidosqlite import android.annotation.SuppressLint import android.database.Cursor import android.database.sqlite.SQLiteConstraintException import android.database.sqlite.SQLiteDatabase import android.database.sqlite.SQLiteException import android.database.sqlite.SQLiteOpenHelper import android.util.Log import com.izeni.rapidosqlite.item_builder.ItemBuilder import com.izeni.rapidosqlite.query.Query import com.izeni.rapidosqlite.query.RawQuery import com.izeni.rapidosqlite.table.DataTable import com.izeni.rapidosqlite.table.ParentDataTable import io.reactivex.BackpressureStrategy import io.reactivex.Flowable import io.reactivex.Single import io.reactivex.schedulers.Schedulers import io.reactivex.subjects.PublishSubject import java.util.* import java.util.concurrent.Executors import java.util.concurrent.atomic.AtomicInteger /** * Created by ryantaylor on 9/22/16. */ class DataConnection private constructor(val database: SQLiteDatabase) { companion object { private val connectionCount = AtomicInteger() private val databaseExecutor = Executors.newSingleThreadExecutor() private val databaseSubject: PublishSubject<DataAction<*>> by lazy { PublishSubject.create<DataAction<*>>() } private lateinit var sqliteOpenHelper: SQLiteOpenHelper fun init(databaseHelper: SQLiteOpenHelper) { this.sqliteOpenHelper = databaseHelper } @Suppress("UNCHECKED_CAST") fun <T : DataTable> watchTableSaves(tableName: String): Flowable<SaveAction<T>> { return databaseSubject.filter { it is SaveAction<*> && it.tableName == tableName } .map { it as SaveAction<T> } .toFlowable(BackpressureStrategy.BUFFER) } @Suppress("UNCHECKED_CAST") fun <T : DataTable> watchTableUpdates(tableName: String): Flowable<UpdateAction<T>> { return databaseSubject.filter { it is UpdateAction<*> && it.tableName == tableName } .map { it as UpdateAction<T> } .toFlowable(BackpressureStrategy.BUFFER) } @Suppress("UNCHECKED_CAST") fun <T : DataTable> watchTableDeletes(tableName: String): Flowable<DeleteAction<T>> { return databaseSubject.filter { it is DeleteAction<*> && it.tableName == tableName } .map { it as DeleteAction<T> } .toFlowable(BackpressureStrategy.BUFFER) } fun <T> asyncGetAndClose(block: (DataConnection) -> T): Single<T> { Log.i("DataConnection", "Called on thread: ${Thread.currentThread().name}") return Single.just(Unit) .subscribeOn(Schedulers.from(databaseExecutor)) .map { Log.i("DataConnection", "Executed on thread: ${Thread.currentThread().name}") val connection = openConnection() val items = block(connection) connection.close() items } } fun <T> getAndClose(block: (DataConnection) -> T): T { val connection = openConnection() val items = block(connection) connection.close() return items } fun asyncDoAndClose(block: (DataConnection) -> Unit) { Single.just(Unit) .subscribeOn(Schedulers.from(databaseExecutor)) .map { val connection = openConnection() block(connection) connection.close() }.subscribe({}, {}) } fun doAndClose(block: (DataConnection) -> Unit) { val connection = openConnection() block(connection) connection.close() } private fun openConnection(): DataConnection { connectionCount.incrementAndGet() return DataConnection(sqliteOpenHelper.writableDatabase) } } var conflictAlgorithm = SQLiteDatabase.CONFLICT_REPLACE private fun close() { if (connectionCount.decrementAndGet() < 1) database.close() } fun insert(item: DataTable) { database.transaction { insert(item, it) } } fun insertAll(items: List<DataTable>) { database.transaction { database -> items.forEach { insert(it, database) } } } private fun insert(item: DataTable, database: SQLiteDatabase) { if (item is ParentDataTable) { item.getChildren().forEach { insert(it, database) } } database.insertWithOnConflict(item.tableName(), null, item.contentValues(), conflictAlgorithm) databaseSubject.onNext(SaveAction(item.tableName(), item)) } fun upsert(item: DataTable) { database.transaction { upsert(item, it) } } fun upsertAll(items: List<DataTable>) { database.transaction { database -> items.forEach { upsert(it, database) } } } private fun upsert(item: DataTable, database: SQLiteDatabase) { if (item is ParentDataTable) { item.getChildren().forEach { upsert(it, database) } } try { database.insertOrThrow(item.tableName(), null, item.contentValues()) } catch (exception: SQLiteException) { if (exception is SQLiteConstraintException) { val rowsUpdated = database.update(item.tableName(), item.contentValues(), "${item.idColumn().name}=?", arrayOf(item.id())) if (rowsUpdated < 1) throw exception } else { throw exception } } databaseSubject.onNext(SaveAction(item.tableName(), item)) } fun update(item: DataTable) { database.transaction { val rowsUpdated = it.update(item.tableName(), item.contentValues(), "${item.idColumn().name}=?", arrayOf(item.id())) if (rowsUpdated < 1) Log.d("DataConnection", "Failed to update any rows while updating item: \n$item") } } /** * Delete all items from the database */ fun deleteAll(items: List<DataTable>) { database.transaction { database -> items.forEach { delete(it, database) } } } /** * Deletes the item fro the database */ fun delete(item: DataTable) { database.transaction { delete(item, it) } } private fun delete(item: DataTable, database: SQLiteDatabase) { database.delete(item.tableName(), "${item.idColumn().name}=?", arrayOf(item.id())) databaseSubject.onNext(DeleteAction(item.tableName(), item)) } /** * Clears all data in the database for this table * WARNING!!! Data watchers will not be notified when using this method */ fun clear(tableName: String) { database.transaction { it.delete(tableName, null, null) } } fun <T> findFirst(builder: ItemBuilder<T>, query: Query): T? { var cursor: Cursor? = null var item: T? = null database.transaction { cursor = getCursor(database, query).also { if (it.moveToFirst()) item = builder.buildItem(it, this) } } cursor?.close() return item } fun <T> findAll(builder: ItemBuilder<T>, query: Query): List<T> { var cursor: Cursor? = null val items = ArrayList<T>() database.transaction { cursor = getCursor(database, query).also { while (it.moveToNext()) items.add(builder.buildItem(it, this)) } } cursor?.close() return items } // Cursor should be closed in the block that calls this method @SuppressLint("Recycle") private fun getCursor(database: SQLiteDatabase, query: Query): Cursor { if (query is RawQuery) { return database.rawQuery(query.query, query.selectionArgs) } else { return database.query(query.tableName, query.columns, query.selection, query.selectionArgs, query.groupBy, null, query.order, query.limit) } } abstract class DataAction<out T>(val tableName: String) class SaveAction<out T : DataTable>(tableName: String, val item: T) : DataAction<T>(tableName) class UpdateAction<out T : DataTable>(tableName: String, val item: T) : DataAction<T>(tableName) class DeleteAction<out T : DataTable>(tableName: String, val item: T) : DataAction<T>(tableName) }
mit
kotlintest/kotlintest
kotest-assertions/src/commonMain/kotlin/io/kotest/matchers/regex/RegexMatchers.kt
2
5206
package io.kotest.matchers.regex import io.kotest.matchers.Matcher import io.kotest.matchers.MatcherResult import io.kotest.matchers.should import io.kotest.matchers.shouldNot /** * Assert that [Regex] is equal to [anotherRegex] by comparing their pattern and options([RegexOption]). * @see [shouldNotBeRegex] * @see [beRegex] * */ infix fun Regex.shouldBeRegex(anotherRegex: Regex) = this should beRegex(anotherRegex) /** * Assert that [Regex] is not equal to [anotherRegex] by comparing their pattern and options([RegexOption]). * @see [shouldBeRegex] * @see [beRegex] * */ infix fun Regex.shouldNotBeRegex(anotherRegex: Regex) = this shouldNot beRegex(anotherRegex) fun beRegex(regex: Regex) = areEqualRegexMatcher(regex) fun areEqualRegexMatcher(regex: Regex) = object : Matcher<Regex> { override fun test(value: Regex): MatcherResult { val patternMatchingResult = haveSamePatternMatcher(regex.pattern).test(value) val optionMatchingResult = haveSameRegexOptionsMatcher(regex.options).test(value) return MatcherResult( patternMatchingResult.passed() && optionMatchingResult.passed(), { "Regex should have pattern ${regex.pattern} and regex options ${regex.options}, but has pattern ${value.pattern} and regex options ${value.options}." }, { "Regex should not have pattern ${value.pattern} and regex options ${value.options}." } ) } } /** * Assert that [Regex] have pattern [regexPattern]. * @see [shouldNotHavePattern] * @see [havePattern] * */ infix fun Regex.shouldHavePattern(regexPattern: String) = this should havePattern(regexPattern) /** * Assert that [Regex] does not have [regexPattern]. * @see [shouldHavePattern] * @see [havePattern] * */ infix fun Regex.shouldNotHavePattern(regexPattern: String) = this shouldNot havePattern(regexPattern) fun havePattern(pattern: String) = haveSamePatternMatcher(pattern) fun haveSamePatternMatcher(pattern: String) = object : Matcher<Regex> { override fun test(value: Regex): MatcherResult { return MatcherResult( value.pattern == pattern, { "Regex should have pattern $pattern but has pattern ${value.pattern}" }, { "Regex should not have pattern ${value.pattern}" } ) } } /** * Assert that [Regex] have exact regex options as [regexOptions] * @see [shouldNotHaveExactRegexOptions] * @see [haveExactOptions] * */ infix fun Regex.shouldHaveExactRegexOptions(regexOptions: Set<RegexOption>) = this should haveExactOptions(regexOptions) /** * Assert that [Regex] does not have exact regex options as [regexOptions] * @see [shouldHaveExactRegexOptions] * @see [haveExactOptions] * */ infix fun Regex.shouldNotHaveExactRegexOptions(regexOptions: Set<RegexOption>) = this shouldNot haveExactOptions(regexOptions) fun haveExactOptions(options: Set<RegexOption>) = haveSameRegexOptionsMatcher(options) fun haveSameRegexOptionsMatcher(options: Set<RegexOption>) = object : Matcher<Regex> { override fun test(value: Regex): MatcherResult { return MatcherResult( value.options == options, { "Regex should have options $options but has options ${value.options}" }, { "Regex should not have pattern ${value.options}" } ) } } /** * Assert that [Regex] regex options include [regexOption] * @see [shouldNotIncludeRegexOption] * @see [includeOption] * */ infix fun Regex.shouldIncludeRegexOption(regexOption: RegexOption) = this should includeOption(regexOption) /** * Assert that [Regex] regex options does not include [regexOption] * @see [shouldIncludeRegexOption] * @see [includeOption] * */ infix fun Regex.shouldNotIncludeRegexOption(regexOption: RegexOption) = this shouldNot includeOption(regexOption) fun includeOption(option: RegexOption) = haveRegexOptionMatcher(option) fun haveRegexOptionMatcher(option: RegexOption) = object : Matcher<Regex> { override fun test(value: Regex): MatcherResult { return MatcherResult( value.options.contains(option), { "Regex options should contains $option" }, { "Regex options should not contains $option" } ) } } /** * Assert that [Regex] regex options include [regexOptions] * @see [shouldNotIncludeRegexOptions] * @see [includeOptions] * */ infix fun Regex.shouldIncludeRegexOptions(regexOptions: Set<RegexOption>) = this should includeOptions(regexOptions) /** * Assert that [Regex] regex options does not include [regexOptions] * @see [shouldIncludeRegexOptions] * @see [includeOptions] * */ infix fun Regex.shouldNotIncludeRegexOptions(regexOptions: Set<RegexOption>) = this shouldNot includeOptions(regexOptions) fun includeOptions(options: Set<RegexOption>) = haveRegexOptionMatcher(options) fun haveRegexOptionMatcher(options: Set<RegexOption>) = object : Matcher<Regex> { override fun test(value: Regex): MatcherResult { return MatcherResult( value.options.containsAll(options), { "Regex options should contains $options, but missing ${options.filterNot { value.options.contains(it) }}." }, { "Regex options should not contains $options, but containing ${options.filter { value.options.contains(it) }}." } ) } }
apache-2.0
Magneticraft-Team/Magneticraft
ignore/test/tileentity/electric/connectors/ElectricPoleAdapterConnector.kt
2
1344
package tileentity.electric.connectors import com.cout970.magneticraft.api.energy.IElectricNode import com.cout970.magneticraft.api.energy.IWireConnector import com.cout970.magneticraft.api.internal.energy.ElectricNode import com.cout970.magneticraft.block.BlockElectricPoleAdapter import com.cout970.magneticraft.block.ELECTRIC_POLE_PLACE import com.cout970.magneticraft.misc.block.get import com.google.common.collect.ImmutableList import net.minecraft.util.math.Vec3d /** * Created by cout970 on 06/07/2016. */ class ElectricPoleAdapterConnector(val node: ElectricNode) : IElectricNode by node, IWireConnector { override fun getConnectors(): ImmutableList<Vec3d> { val state = world.getBlockState(pos) if (state.block != BlockElectricPoleAdapter) return ImmutableList.of() val offset = state[ELECTRIC_POLE_PLACE].offset.rotateYaw(Math.toRadians(-90.0).toFloat()) val vec = Vec3d(0.5, 1.0 - 0.0625 * 6.5, 0.5).add(offset * 0.5) return ImmutableList.of(vec) } override fun getConnectorsSize(): Int = 1 override fun equals(other: Any?): Boolean { return super.equals(other) || if (other is ElectricNode) node.equals(other) else false } override fun hashCode(): Int { return node.hashCode() } override fun toString() = node.toString() }
gpl-2.0
Shynixn/PetBlocks
petblocks-api/src/main/kotlin/com/github/shynixn/petblocks/api/persistence/entity/AIParticle.kt
1
354
package com.github.shynixn.petblocks.api.persistence.entity interface AIParticle : AIBase { /** * Particle. */ var particle: Particle /** * Offset from the pet source position. */ var offset: Position /** * Amount of seconds until the next particle is played. */ var delayBetweenPlaying: Double }
apache-2.0
ceduliocezar/android-labs
KoinTesting/app/src/main/java/com/ceduliocezar/koin/presentation/viewmodel/MyViewModel.kt
1
765
package com.ceduliocezar.koin.presentation.viewmodel import androidx.lifecycle.MutableLiveData import com.ceduliocezar.koin.base.BaseViewModel import com.ceduliocezar.koin.domain.HelloRepository import com.ceduliocezar.koin.threading.AsyncProvider class MyViewModel( private val repository: HelloRepository, asyncProvider: AsyncProvider ) : BaseViewModel(asyncProvider) { val liveDataString: MutableLiveData<String> = MutableLiveData() val displayGeneralErrorMessage: MutableLiveData<Boolean> = MutableLiveData() init { onBackground { repository.giveSlowHello() }.onSuccess { liveDataString.value = it }.onError { displayGeneralErrorMessage.value = true }.execute() } }
gpl-3.0
Ph1b/MaterialAudiobookPlayer
scanner/src/main/kotlin/de/ph1b/audiobook/scanner/MediaScanner.kt
1
3489
package de.ph1b.audiobook.scanner import androidx.documentfile.provider.DocumentFile import de.ph1b.audiobook.common.comparator.NaturalOrderComparator import de.ph1b.audiobook.data.Book2 import de.ph1b.audiobook.data.BookContent2 import de.ph1b.audiobook.data.Chapter2 import de.ph1b.audiobook.data.repo.BookContentRepo import de.ph1b.audiobook.data.repo.BookRepo2 import de.ph1b.audiobook.data.repo.ChapterRepo import de.ph1b.audiobook.data.toUri import java.time.Instant import javax.inject.Inject class MediaScanner @Inject constructor( private val bookContentRepo: BookContentRepo, private val chapterRepo: ChapterRepo, private val mediaAnalyzer: MediaAnalyzer, private val bookRepo: BookRepo2, ) { suspend fun scan(folders: List<DocumentFile>) { val allFiles = folders.flatMap { it.listFiles().toList() } bookRepo.setAllInactiveExcept(allFiles.map { Book2.Id(it.uri) }) allFiles.forEach { scan(it) } } private suspend fun scan(file: DocumentFile) { val fileName = file.name ?: return val chapters = file.parseChapters() if (chapters.isEmpty()) return val chapterIds = chapters.map { it.id } val id = Book2.Id(file.uri) val content = bookContentRepo.getOrPut(id) { val content = BookContent2( id = id, isActive = true, addedAt = Instant.now(), author = mediaAnalyzer.analyze(chapterIds.first().toUri())?.author, lastPlayedAt = Instant.EPOCH, name = fileName, playbackSpeed = 1F, skipSilence = false, chapters = chapterIds, positionInChapter = 0L, currentChapter = chapters.first().id, cover = null ) validateIntegrity(content, chapters) content } val currentChapterGone = content.currentChapter !in chapterIds val currentChapter = if (currentChapterGone) chapterIds.first() else content.currentChapter val positionInChapter = if (currentChapterGone) 0 else content.positionInChapter val updated = content.copy( chapters = chapterIds, currentChapter = currentChapter, positionInChapter = positionInChapter, isActive = true, ) if (content != updated) { validateIntegrity(updated, chapters) bookContentRepo.put(updated) } } private fun validateIntegrity(content: BookContent2, chapters: List<Chapter2>) { // the init block performs integrity validation Book2(content, chapters) } private suspend fun DocumentFile.parseChapters(): List<Chapter2> { val result = mutableListOf<Chapter2>() parseChapters(file = this, result = result) return result } private suspend fun parseChapters(file: DocumentFile, result: MutableList<Chapter2>) { if (file.isFile && file.type?.startsWith("audio/") == true) { val id = Chapter2.Id(file.uri) val chapter = chapterRepo.getOrPut(id, Instant.ofEpochMilli(file.lastModified())) { val metaData = mediaAnalyzer.analyze(file.uri) ?: return@getOrPut null Chapter2( id = id, duration = metaData.duration, fileLastModified = Instant.ofEpochMilli(file.lastModified()), name = metaData.chapterName, markData = metaData.chapters ) } if (chapter != null) { result.add(chapter) } } else if (file.isDirectory) { file.listFiles().sortedWith(NaturalOrderComparator.documentFileComparator) .forEach { parseChapters(it, result) } } } }
lgpl-3.0
square/leakcanary
leakcanary-android-instrumentation/src/main/java/leakcanary/TestDescriptionHolder.kt
2
1887
package leakcanary import leakcanary.TestDescriptionHolder.testDescription import org.junit.rules.TestRule import org.junit.runner.Description import org.junit.runners.model.Statement import shark.SharkLog /** * A [TestRule] that holds onto the test [Description] in a thread local while evaluating, making * it possible to retrieve that test [Description] from the test thread via [testDescription]. * * This rule is automatically applied by [DetectLeaksAfterTestSuccess]. */ object TestDescriptionHolder : TestRule { private val descriptionThreadLocal = ThreadLocal<Description>() fun isEvaluating() = descriptionThreadLocal.get() != null val testDescription: Description get() { return descriptionThreadLocal.get() ?: error( "Test description is null, either you forgot to add the TestDescriptionHolder rule around" + "the current code or you did not call testDescription from the test thread." ) } override fun apply(base: Statement, description: Description): Statement { return wrap(base, description) } fun wrap(base: Statement, description: Description) = object : Statement() { override fun evaluate() { val previousDescription = descriptionThreadLocal.get() val descriptionNotAlreadySet = previousDescription == null if (descriptionNotAlreadySet) { descriptionThreadLocal.set(description) } else { SharkLog.d { "Test description already set, you should remove the TestDescriptionHolder rule." } } try { base.evaluate() } finally { if (descriptionNotAlreadySet) { val currentDescription = descriptionThreadLocal.get() check(currentDescription != null) { "Test description should not be null after the rule evaluates." } descriptionThreadLocal.remove() } } } } }
apache-2.0
denysnovoa/radarrsonarr
app/src/main/java/com/denysnovoa/nzbmanager/radarr/movie/release/view/presenter/MovieReleasePresenter.kt
1
2734
package com.denysnovoa.nzbmanager.radarr.movie.release.view.presenter import com.denysnovoa.nzbmanager.common.framework.ErrorLog import com.denysnovoa.nzbmanager.radarr.movie.release.domain.DownloadReleaseUseCase import com.denysnovoa.nzbmanager.radarr.movie.release.view.MovieReleaseView import com.denysnovoa.nzbmanager.radarr.movie.release.view.domain.GetMovieReleaseUseCase import com.denysnovoa.nzbmanager.radarr.movie.release.view.mapper.MovieReleaseViewMapper import com.denysnovoa.nzbmanager.radarr.movie.release.view.model.MovieReleaseViewModel import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.disposables.CompositeDisposable import io.reactivex.schedulers.Schedulers class MovieReleasePresenter(val view: MovieReleaseView, val errorLog: ErrorLog, val getMovieReleaseUseCase: GetMovieReleaseUseCase, val downloadReleaseUseCase: DownloadReleaseUseCase, val movieReleaseViewMapper: MovieReleaseViewMapper) { val compositeDisposable = CompositeDisposable() var callApi = false fun onStop() { compositeDisposable.clear() } fun onResume(id: Int) { view.showLoading() if (!callApi) { callApi = true compositeDisposable.add( getMovieReleaseUseCase .get(id) .doOnError(errorLog::log) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .doOnNext { callApi = false view.hideLoading() } .subscribe( { movieReleases -> view.showMovieReleases(movieReleaseViewMapper.transform(movieReleases)) }, { view.showErrorSearchReleases() } ) ) } } fun onReleaseClicked(releaseViewModel: MovieReleaseViewModel) { compositeDisposable.add( downloadReleaseUseCase .download(movieReleaseViewMapper.transform(releaseViewModel)) .doOnError(errorLog::log) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe({ view.showDownloadOk() }, { view.showErrorDownload() }) ) } }
apache-2.0
google/horologist
media-ui/src/debug/java/com/google/android/horologist/media/ui/components/TextMediaDisplayPreview.kt
1
1404
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ @file:OptIn(ExperimentalHorologistMediaUiApi::class) package com.google.android.horologist.media.ui.components import androidx.compose.runtime.Composable import androidx.compose.ui.tooling.preview.Preview import com.google.android.horologist.compose.tools.WearPreview import com.google.android.horologist.media.ui.ExperimentalHorologistMediaUiApi @WearPreview @Composable fun TextMediaDisplayPreview() { TextMediaDisplay( title = "Song title", artist = "Artist name" ) } @Preview( "With long text", backgroundColor = 0xff000000, showBackground = true ) @Composable fun TextMediaDisplayPreviewLongText() { TextMediaDisplay( title = "I Predict That You Look Good In A Riot", artist = "Arctic Monkeys feat Kaiser Chiefs" ) }
apache-2.0
epabst/kotlin-showcase
src/jsMain/kotlin/bootstrap/CardDeck.kt
1
327
@file:Suppress("INTERFACE_WITH_SUPERCLASS", "OVERRIDING_FINAL_MEMBER", "RETURN_TYPE_MISMATCH_ON_OVERRIDE", "CONFLICTING_OVERLOADS", "EXTERNAL_DELEGATION", "unused") @file:JsModule("react-bootstrap") package bootstrap import react.RProps abstract external class CardDeck<As : React.ElementType> : BsPrefixComponent<As, RProps>
apache-2.0
Zhuinden/simple-stack
samples/scoping-samples/simple-stack-example-scoping-kotlin/src/main/java/com/zhuinden/simplestackexamplescoping/features/words/WordListFragment.kt
1
2129
package com.zhuinden.simplestackexamplescoping.features.words import android.os.Bundle import android.view.View import androidx.lifecycle.LiveData import androidx.recyclerview.widget.LinearLayoutManager import com.zhuinden.fragmentviewbindingdelegatekt.viewBinding import com.zhuinden.liveevent.observe import com.zhuinden.simplestackexamplescoping.R import com.zhuinden.simplestackexamplescoping.databinding.WordListViewBinding import com.zhuinden.simplestackexamplescoping.utils.onClick import com.zhuinden.simplestackexamplescoping.utils.safe import com.zhuinden.simplestackexamplescoping.utils.showToast import com.zhuinden.simplestackextensions.fragments.KeyedFragment import com.zhuinden.simplestackextensions.fragmentsktx.lookup /** * Created by Zhuinden on 2018.09.17. */ class WordListFragment : KeyedFragment(R.layout.word_list_view) { private val binding by viewBinding(WordListViewBinding::bind) interface ActionHandler { fun onAddNewWordClicked() } interface DataProvider { val wordList: LiveData<List<String>> } private val actionHandler by lazy { lookup<ActionHandler>() } private val dataProvider by lazy { lookup<DataProvider>() } private val wordList by lazy { dataProvider.wordList } private val controllerEvents by lazy { lookup<WordEventEmitter>() } val adapter = WordListAdapter() @Suppress("NAME_SHADOWING") override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) binding.recyclerView.layoutManager = LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false) binding.recyclerView.adapter = adapter binding.buttonGoToAddNewWord.onClick { view -> actionHandler.onAddNewWordClicked() } wordList.observe(viewLifecycleOwner) { words -> adapter.updateWords(words) } controllerEvents.observe(viewLifecycleOwner) { event -> when (event) { is WordController.Events.NewWordAdded -> showToast("Added ${event.word}") }.safe() } } }
apache-2.0
Constantinuous/Angus
infrastructure/src/main/kotlin/de/constantinuous/angus/sql/impl/AntlrTsqlContextExtensions.kt
1
1921
package de.constantinuous.angus.sql.impl import org.antlr.v4.runtime.RuleContext /** * Created by RichardG on 25.11.2016. */ fun tsqlParser.Select_statementContext.getTableName(): String { val tableSource = this.query_expression().query_specification().table_sources().table_source(0) val table = tableSource.table_source_item_joined().table_source_item().table_name_with_hint().table_name().table val tableName = table.simple_id().getChild(0).text ?: "" return tableName } fun tsqlParser.Select_statementContext.getSelectedColumnNames(): List<String> { val selectedColumnNames = mutableListOf<String>() val selectList = this.query_expression().query_specification().select_list().select_list_elem() for(selectListElement in selectList){ val columnName = selectListElement.expression().getChild(0).text selectedColumnNames.add(columnName) } return selectedColumnNames } fun tsqlParser.Delete_statementContext.getTableName(): String{ val tableName = this.delete_statement_from().table_alias().id().simple_id().getChild(0).text ?: "" return tableName } fun tsqlParser.Insert_statementContext.getTableName(): String{ val tableName = this.ddl_object().full_table_name().getChild(0).text return tableName } fun tsqlParser.Insert_statementContext.getColumnNames(): List<String>{ val columnNames = mutableListOf<String>() val columnNameList = this.column_name_list() if(columnNameList != null){ for(id in columnNameList.id()){ columnNames.add(id.simple_id().getChild(0).text) } } return columnNames } fun tsqlParser.Execute_statementContext.getProcedureNames(): List<String>{ val procedureNames = mutableListOf<String>() val procedures = this.func_proc_name().id() for(procedure in procedures){ procedureNames.add(procedure.simple_id().text) } return procedureNames }
mit
angryziber/picasa-gallery
src/web/SiteMapServlet.kt
1
857
package web import integration.OAuth import photos.LocalContent import photos.Picasa import views.sitemap import javax.servlet.ServletConfig import javax.servlet.annotation.WebServlet import javax.servlet.http.HttpServlet import javax.servlet.http.HttpServletRequest import javax.servlet.http.HttpServletResponse @WebServlet("/sitemap.xml") class SiteMapServlet : HttpServlet() { lateinit var content: LocalContent override fun init(config: ServletConfig) { content = LocalContent(config.servletContext) } override fun doGet(req: HttpServletRequest, resp: HttpServletResponse) { resp.writer.use { out -> resp.contentType = "text/xml" resp.setHeader("Cache-Control", "public") val picasa = Picasa(OAuth.default, content) out.write(sitemap(req.getHeader("Host"), OAuth.default.profile, picasa.gallery)) } } }
gpl-3.0
googlecodelabs/tv-watchnext
step_final/src/androidTest/java/com/example/android/watchnextcodelab/MockDataUtil.kt
4
1833
/* * 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. */ @file:JvmName("MockDataUtil") package com.example.android.watchnextcodelab import android.media.tv.TvContentRating import android.support.media.tv.TvContractCompat import com.example.android.watchnextcodelab.model.Movie /** * Contains helper method for generating mock data to test with. */ fun createMovieWithTitle(id: Long, title: String): Movie = Movie( movieId = id, title = title, description = "Description...", duration = 1, previewVideoUrl = "preview url", videoUrl = "video url", posterArtAspectRatio = TvContractCompat.PreviewPrograms.ASPECT_RATIO_1_1, aspectRatio = TvContractCompat.PreviewPrograms.ASPECT_RATIO_1_1, thumbnailUrl = "thumb url", cardImageUrl = "card image url", contentRating = TvContentRating.UNRATED, genre = "action", isLive = false, releaseDate = "2001", rating = "3", ratingStyle = TvContractCompat.WatchNextPrograms.REVIEW_RATING_STYLE_STARS, startingPrice = "$1.99", offerPrice = "$0.99", width = 1, height = 1, weight = 1)
apache-2.0
Commit451/LabCoat
app/src/main/java/com/commit451/gitlab/widget/ProjectFeedWidgetProvider.kt
2
2477
package com.commit451.gitlab.widget import android.app.PendingIntent import android.appwidget.AppWidgetManager import android.appwidget.AppWidgetProvider import android.content.Context import android.content.Intent import android.net.Uri import android.widget.RemoteViews import com.commit451.gitlab.R import com.commit451.gitlab.navigation.DeepLinker class ProjectFeedWidgetProvider : AppWidgetProvider() { companion object { const val ACTION_FOLLOW_LINK = "com.commit451.gitlab.ACTION_FOLLOW_LINK" const val EXTRA_LINK = "com.commit451.gitlab.EXTRA_LINK" } override fun onReceive(context: Context, intent: Intent) { if (intent.action == ACTION_FOLLOW_LINK) { val uri = intent.getStringExtra(EXTRA_LINK) val launchIntent = DeepLinker.generateDeeplinkIntentFromUri(context, Uri.parse(uri)) launchIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) context.startActivity(launchIntent) } super.onReceive(context, intent) } override fun onUpdate(context: Context, appWidgetManager: AppWidgetManager, appWidgetIds: IntArray) { for (widgetId in appWidgetIds) { val account = ProjectFeedWidgetPrefs.getAccount(context, widgetId) val feedUrl = ProjectFeedWidgetPrefs.getFeedUrl(context, widgetId) if (account != null && feedUrl != null) { val intent = FeedWidgetService.newIntent(context, widgetId, account, feedUrl) intent.data = Uri.parse(intent.toUri(Intent.URI_INTENT_SCHEME)) val rv = RemoteViews(context.packageName, R.layout.widget_layout_entry) rv.setRemoteAdapter(R.id.list_view, intent) rv.setEmptyView(R.id.list_view, R.id.empty_view) val toastIntent = Intent(context, ProjectFeedWidgetProvider::class.java) toastIntent.action = ACTION_FOLLOW_LINK toastIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, widgetId) intent.data = Uri.parse(intent.toUri(Intent.URI_INTENT_SCHEME)) val toastPendingIntent = PendingIntent.getBroadcast(context, 0, toastIntent, PendingIntent.FLAG_UPDATE_CURRENT) rv.setPendingIntentTemplate(R.id.list_view, toastPendingIntent) appWidgetManager.updateAppWidget(widgetId, rv) } } super.onUpdate(context, appWidgetManager, appWidgetIds) } }
apache-2.0
felipecsl/walkman
okreplay-junit/src/main/kotlin/okreplay/Ascii.kt
3
2888
/* * Copyright (C) 2010 The Guava 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 okreplay internal object Ascii { /** * Returns a copy of the input string in which all [uppercase ASCII][.isUpperCase] have been * converted to lowercase. All other characters are copied without modification. */ fun toLowerCase(string: String): String { val length = string.length var i = 0 while (i < length) { if (isUpperCase(string[i])) { val chars = string.toCharArray() while (i < length) { val c = chars[i] if (isUpperCase(c)) { chars[i] = (c.toInt() xor 0x20).toChar() } i++ } return String(chars) } i++ } return string } /** * Returns a copy of the input string in which all [lowercase ASCII][.isLowerCase] have been * converted to uppercase. All other characters are copied without modification. */ fun toUpperCase(string: String): String { val length = string.length var i = 0 while (i < length) { if (isLowerCase(string[i])) { val chars = string.toCharArray() while (i < length) { val c = chars[i] if (isLowerCase(c)) { chars[i] = (c.toInt() and 0x5f).toChar() } i++ } return String(chars) } i++ } return string } /** * If the argument is a [lowercase ASCII character][.isLowerCase] returns the * uppercase equivalent. Otherwise returns the argument. */ fun toUpperCase(c: Char): Char { return if (isLowerCase(c)) (c.toInt() and 0x5f).toChar() else c } /** * Indicates whether `c` is one of the twenty-six lowercase ASCII alphabetic characters * between `'a'` and `'z'` inclusive. All others (including non-ASCII characters) * return `false`. */ private fun isLowerCase(c: Char): Boolean { // Note: This was benchmarked against the alternate expression "(char)(c - 'a') < 26" (Nov '13) // and found to perform at least as well, or better. return c in 'a'..'z' } /** * Indicates whether `c` is one of the twenty-six uppercase ASCII alphabetic characters * between `'A'` and `'Z'` inclusive. All others (including non-ASCII characters) * return `false`. */ private fun isUpperCase(c: Char): Boolean { return c in 'A'..'Z' } }
apache-2.0
wuan/rest-demo-jersey-kotlin
src/main/java/com/tngtech/demo/weather/resources/stations/StationLinkCreator.kt
1
890
package com.tngtech.demo.weather.resources.stations import com.mercateo.common.rest.schemagen.link.LinkFactory import com.mercateo.common.rest.schemagen.link.relation.Rel import com.mercateo.common.rest.schemagen.util.OptionalUtil.collect import com.tngtech.demo.weather.forCall import org.springframework.stereotype.Component import java.util.* import javax.inject.Inject import javax.inject.Named import javax.ws.rs.core.Link @Component class StationLinkCreator @Inject constructor(@param:Named("stationLinkFactory") private val stationLinkFactory: LinkFactory<StationResource>) { fun createFor(stationId: UUID): List<Link> { return collect( stationLinkFactory.forCall(Rel.SELF) { r: StationResource -> r.getStation(stationId) }, stationLinkFactory.forCall(Rel.DELETE) { r: StationResource -> r.deleteStation(stationId) } ) } }
apache-2.0
OurFriendIrony/MediaNotifier
app/src/main/kotlin/uk/co/ourfriendirony/medianotifier/mediaitem/artist/Artist.kt
1
3374
package uk.co.ourfriendirony.medianotifier.mediaitem.artist import android.database.Cursor import android.util.Log import uk.co.ourfriendirony.medianotifier.clients.musicbrainz.artist.get.ArtistGet import uk.co.ourfriendirony.medianotifier.clients.musicbrainz.artist.search.ArtistSearchArtist import uk.co.ourfriendirony.medianotifier.db.artist.ArtistDatabaseDefinition import uk.co.ourfriendirony.medianotifier.general.Helper.getColumnValue import uk.co.ourfriendirony.medianotifier.general.Helper.stringToDate import uk.co.ourfriendirony.medianotifier.mediaitem.MediaItem import java.text.SimpleDateFormat import java.util.* class Artist : MediaItem { override val id: String override val title: String? override val subtitle = "" // TODO: fully implement played as an item override val played = false private var subid = "" override var description: String? = "" private set override var releaseDate: Date? = null private set override val externalLink: String? = null override var children: List<MediaItem> = ArrayList() constructor(artist: ArtistGet) { id = artist.id!! title = artist.name if (artist.disambiguation != null) { description = artist.disambiguation } else if (artist.area!!.name != null && artist.type != null) { description = artist.type + " from " + artist.area!!.name } if (artist.lifeSpan != null && artist.lifeSpan!!.begin != null) { releaseDate = artist.lifeSpan!!.begin } } constructor(artist: ArtistSearchArtist) { id = artist.id!! title = artist.name if (artist.disambiguation != null) { description = artist.disambiguation } else if (artist.area != null && artist.area!!.name != null && artist.type != null) { description = artist.type + " from " + artist.area!!.name } if (artist.lifeSpan != null && artist.lifeSpan!!.begin != null) { releaseDate = artist.lifeSpan!!.begin } Log.d("[API SEARCH]", this.toString()) } @JvmOverloads constructor(cursor: Cursor?, releases: List<MediaItem> = ArrayList()) { // Build Artist from DB with children id = getColumnValue(cursor!!, ArtistDatabaseDefinition.ID) subid = getColumnValue(cursor, ArtistDatabaseDefinition.SUBID) title = getColumnValue(cursor, ArtistDatabaseDefinition.TITLE) description = getColumnValue(cursor, ArtistDatabaseDefinition.DESCRIPTION) releaseDate = stringToDate(getColumnValue(cursor, ArtistDatabaseDefinition.RELEASE_DATE)) children = releases Log.d("[DB READ]", this.toString()) } override val subId: String get() = subid override val releaseDateFull: String get() = if (releaseDate != null) { SimpleDateFormat("dd/MM/yyyy", Locale.UK).format(releaseDate!!) } else MediaItem.NO_DATE override val releaseDateYear: String get() = if (releaseDate != null) { SimpleDateFormat("yyyy", Locale.UK).format(releaseDate!!) } else MediaItem.NO_DATE override fun countChildren(): Int { return children.size } override fun toString(): String { return "Artist: " + title + " > " + releaseDateFull + " > Releases " + countChildren() } }
apache-2.0
vsch/idea-multimarkdown
src/main/java/com/vladsch/md/nav/psi/element/MdJekyllFrontMatterBlockImpl.kt
1
5306
// Copyright (c) 2015-2020 Vladimir Schneider <[email protected]> Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.vladsch.md.nav.psi.element import com.intellij.lang.ASTNode import com.intellij.navigation.ItemPresentation import com.intellij.openapi.util.TextRange import com.intellij.psi.ElementManipulators import com.intellij.psi.LiteralTextEscaper import com.intellij.psi.PsiElement import com.intellij.psi.stubs.IStubElementType import com.intellij.psi.tree.IElementType import com.vladsch.md.nav.parser.MdFactoryContext import com.vladsch.md.nav.psi.util.BasicTextMapElementTypeProvider import com.vladsch.md.nav.psi.util.MdPsiImplUtil import com.vladsch.md.nav.psi.util.MdTypes import com.vladsch.md.nav.psi.util.TextMapElementType import com.vladsch.plugin.util.ifElse import icons.MdIcons import javax.swing.Icon //class MultiMarkdownJekyllFrontMatterBlockImpl(node: ASTNode) : ASTWrapperPsiElement(node), MultiMarkdownJekyllFrontMatterBlock { class MdJekyllFrontMatterBlockImpl(stub: MdJekyllFrontMatterBlockStub?, nodeType: IStubElementType<MdJekyllFrontMatterBlockStub, MdJekyllFrontMatterBlock>?, node: ASTNode?) : MdStubPlainTextImpl<MdJekyllFrontMatterBlockStub>(stub, nodeType, node), MdJekyllFrontMatterBlock { constructor(stub: MdJekyllFrontMatterBlockStub, nodeType: IStubElementType<MdJekyllFrontMatterBlockStub, MdJekyllFrontMatterBlock>) : this(stub, nodeType, null) constructor(node: ASTNode) : this(null, null, node) override fun getTextMapType(): TextMapElementType { return BasicTextMapElementTypeProvider.JEKYLL_FRONT_MATTER } val referenceableTextType: IElementType = MdTypes.JEKYLL_FRONT_MATTER_BLOCK override fun getReferenceableOffsetInParent(): Int { return MdPlainTextStubElementType.getReferenceableOffsetInParent(node, referenceableTextType) } override fun getReferenceableText(): String { return content } override fun replaceReferenceableText(text: String, startOffset: Int, endOffset: Int): PsiElement { val content = content val sb = StringBuilder(content.length - (endOffset - startOffset) + text.length) sb.append(content, 0, startOffset).append(text).append(content, endOffset, content.length) return setContent(sb.toString()) } override fun getContentElement(): ASTNode? = node.findChildByType(referenceableTextType) override fun getContent(): String { val content = getContentElement() return content?.text ?: "" } override fun setContent(blockText: String): PsiElement { return MdPsiImplUtil.setContent(this, blockText) } override fun getContentRange(inDocument: Boolean): TextRange { val startMarker = node.findChildByType(MdTypes.JEKYLL_FRONT_MATTER_OPEN) val content = node.findChildByType(referenceableTextType) if (startMarker != null && content != null) { return TextRange(startMarker.textLength + 1, startMarker.textLength + 1 + content.textLength).shiftRight(inDocument.ifElse(0, startMarker.startOffset)) } return TextRange(0, 0) } override fun getPresentation(): ItemPresentation { return object : ItemPresentation { override fun getPresentableText(): String? { if (!isValid) return null return "Jekyll front matter block" } override fun getLocationString(): String? { if (!isValid) return null // create a shortened version that is still good to look at return MdPsiImplUtil.truncateStringForDisplay(text, 50, false, true, true) } override fun getIcon(unused: Boolean): Icon? { return MdIcons.getDocumentIcon() } } } override fun isValidHost(): Boolean { return isValid } override fun updateText(text: String): MdPsiLanguageInjectionHost { return ElementManipulators.handleContentChange(this, text) } override fun createLiteralTextEscaper(): LiteralTextEscaper<out MdPsiLanguageInjectionHost> { return object : LiteralTextEscaper<MdPsiLanguageInjectionHost>(this) { override fun decode(rangeInsideHost: TextRange, outChars: StringBuilder): Boolean { outChars.append(rangeInsideHost.substring(myHost.text)) return true } override fun getOffsetInHost(offsetInDecoded: Int, rangeInsideHost: TextRange): Int { return rangeInsideHost.startOffset + offsetInDecoded } override fun getRelevantTextRange(): TextRange { return contentRange } override fun isOneLine(): Boolean { return false } } } companion object { @Suppress("UNUSED_PARAMETER") fun getElementText(factoryContext: MdFactoryContext, content: String?): String { val useContent = content ?: "" if (useContent.isEmpty() || useContent[useContent.length - 1] != '\n') { return "---\n$useContent\n---\n" } else { return "---\n$useContent---\n" } } } }
apache-2.0