repo_name
stringlengths
7
79
path
stringlengths
8
206
copies
stringclasses
36 values
size
stringlengths
2
6
content
stringlengths
55
523k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
7.18
99.5
line_max
int64
16
979
alpha_frac
float64
0.3
0.87
ratio
float64
2.01
8.07
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
aosp-mirror/platform_frameworks_support
core/ktx/src/main/java/androidx/core/graphics/Color.kt
1
10788
/* * 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:Suppress("NOTHING_TO_INLINE", "WRONG_ANNOTATION_TARGET_WITH_USE_SITE_TARGET_ON_TYPE") package androidx.core.graphics import android.graphics.Color import android.graphics.ColorSpace import androidx.annotation.ColorInt import androidx.annotation.ColorLong import androidx.annotation.RequiresApi /** * Returns the first component of the color. For instance, when the color model * of the color is [android.graphics.ColorSpace.Model.RGB], the first component * is "red". * * This method allows to use destructuring declarations when working with colors, * for example: * ``` * val (red, green, blue) = myColor * ``` */ @RequiresApi(26) inline operator fun Color.component1() = getComponent(0) /** * Returns the second component of the color. For instance, when the color model * of the color is [android.graphics.ColorSpace.Model.RGB], the second component * is "green". * * This method allows to use destructuring declarations when working with colors, * for example: * ``` * val (red, green, blue) = myColor * ``` */ @RequiresApi(26) inline operator fun Color.component2() = getComponent(1) /** * Returns the third component of the color. For instance, when the color model * of the color is [android.graphics.ColorSpace.Model.RGB], the third component * is "blue". = * * This method allows to use destructuring declarations when working with colors, * for example: * ``` * val (red, green, blue) = myColor * ``` */ @RequiresApi(26) inline operator fun Color.component3() = getComponent(2) /** * Returns the fourth component of the color. For instance, when the color model * of the color is [android.graphics.ColorSpace.Model.RGB], the fourth component * is "alpha". * * This method allows to use destructuring declarations when working with colors, * for example: * ``` * val (red, green, blue, alpha) = myColor * ``` */ @RequiresApi(26) inline operator fun Color.component4() = getComponent(3) /** * Composites two translucent colors together. More specifically, adds two colors using * the [source over][android.graphics.PorterDuff.Mode.SRC_OVER] blending mode. The colors * must not be pre-multiplied and the result is a non pre-multiplied color. * * If the two colors have different color spaces, the color in the right-hand part * of the expression is converted to the color space of the color in left-hand part * of the expression. * * The following example creates a purple color by blending opaque blue with * semi-translucent red: * * ``` * val purple = Color.valueOf(0f, 0f, 1f) + Color.valueOf(1f, 0f, 0f, 0.5f) * ``` * * @throws IllegalArgumentException if the [color models][android.graphics.Color.getModel] * of the colors do not match */ @RequiresApi(26) operator fun Color.plus(c: Color): Color = ColorUtils.compositeColors(c, this) /** * Return the alpha component of a color int. This is equivalent to calling: * ``` * Color.alpha(myInt) * ``` */ inline val @receiver:ColorInt Int.alpha get() = (this shr 24) and 0xff /** * Return the red component of a color int. This is equivalent to calling: * ``` * Color.red(myInt) * ``` */ inline val @receiver:ColorInt Int.red get() = (this shr 16) and 0xff /** * Return the green component of a color int. This is equivalent to calling: * ``` * Color.green(myInt) * ``` */ inline val @receiver:ColorInt Int.green get() = (this shr 8) and 0xff /** * Return the blue component of a color int. This is equivalent to calling: * ``` * Color.blue(myInt) * ``` */ inline val @receiver:ColorInt Int.blue get() = this and 0xff /** * Return the alpha component of a color int. This is equivalent to calling: * ``` * Color.alpha(myInt) * ``` * * This method allows to use destructuring declarations when working with colors, * for example: * ``` * val (alpha, red, green, blue) = myColor * ``` */ inline operator fun @receiver:ColorInt Int.component1() = (this shr 24) and 0xff /** * Return the red component of a color int. This is equivalent to calling: * ``` * Color.red(myInt) * ``` * * This method allows to use destructuring declarations when working with colors, * for example: * ``` * val (alpha, red, green, blue) = myColor * ``` */ inline operator fun @receiver:ColorInt Int.component2() = (this shr 16) and 0xff /** * Return the green component of a color int. This is equivalent to calling: * ``` * Color.green(myInt) * ``` * * This method allows to use destructuring declarations when working with colors, * for example: * ``` * val (alpha, red, green, blue) = myColor * ``` */ inline operator fun @receiver:ColorInt Int.component3() = (this shr 8) and 0xff /** * Return the blue component of a color int. This is equivalent to calling: * ``` * Color.blue(myInt) * ``` * * This method allows to use destructuring declarations when working with colors, * for example: * ``` * val (alpha, red, green, blue) = myColor * ``` */ inline operator fun @receiver:ColorInt Int.component4() = this and 0xff /** * Returns the relative luminance of a color int, assuming sRGB encoding. * Based on the formula for relative luminance defined in WCAG 2.0, * W3C Recommendation 11 December 2008. */ @get:RequiresApi(26) inline val @receiver:ColorInt Int.luminance get() = Color.luminance(this) /** * Creates a new [Color] instance from a color int. The resulting color * is in the [sRGB][android.graphics.ColorSpace.Named.SRGB] color space. */ @RequiresApi(26) inline fun @receiver:ColorInt Int.toColor(): Color = Color.valueOf(this) /** * Converts the specified ARGB [color int][Color] to an RGBA [color long][Color] * in the [sRGB][android.graphics.ColorSpace.Named.SRGB] color space. */ @RequiresApi(26) @ColorLong inline fun @receiver:ColorInt Int.toColorLong() = Color.pack(this) /** * Returns the first component of the color. For instance, when the color model * of the color is [android.graphics.ColorSpace.Model.RGB], the first component * is "red". * * This method allows to use destructuring declarations when working with colors, * for example: * ``` * val (red, green, blue, alpha) = myColorLong * ``` */ @RequiresApi(26) inline operator fun @receiver:ColorLong Long.component1() = Color.red(this) /** * Returns the second component of the color. For instance, when the color model * of the color is [android.graphics.ColorSpace.Model.RGB], the second component * is "green". * * This method allows to use destructuring declarations when working with colors, * for example: * ``` * val (red, green, blue, alpha) = myColorLong * ``` */ @RequiresApi(26) inline operator fun @receiver:ColorLong Long.component2() = Color.green(this) /** * Returns the third component of the color. For instance, when the color model * of the color is [android.graphics.ColorSpace.Model.RGB], the third component * is "blue". * * This method allows to use destructuring declarations when working with colors, * for example: * ``` * val (red, green, blue, alpha) = myColorLong * ``` */ @RequiresApi(26) inline operator fun @receiver:ColorLong Long.component3() = Color.blue(this) /** * Returns the fourth component of the color. For instance, when the color model * of the color is [android.graphics.ColorSpace.Model.RGB], the fourth component * is "alpha". * * This method allows to use destructuring declarations when working with colors, * for example: * ``` * val (red, green, blue, alpha) = myColorLong * ``` */ @RequiresApi(26) inline operator fun @receiver:ColorLong Long.component4() = Color.alpha(this) /** * Return the alpha component of a color long. This is equivalent to calling: * ``` * Color.alpha(myLong) * ``` */ @get:RequiresApi(26) inline val @receiver:ColorLong Long.alpha get() = Color.alpha(this) /** * Return the red component of a color long. This is equivalent to calling: * ``` * Color.red(myLong) * ``` */ @get:RequiresApi(26) inline val @receiver:ColorLong Long.red get() = Color.red(this) /** * Return the green component of a color long. This is equivalent to calling: * ``` * Color.green(myLong) * ``` */ @get:RequiresApi(26) inline val @receiver:ColorLong Long.green get() = Color.green(this) /** * Return the blue component of a color long. This is equivalent to calling: * ``` * Color.blue(myLong) * ``` */ @get:RequiresApi(26) inline val @receiver:ColorLong Long.blue get() = Color.blue(this) /** * Returns the relative luminance of a color. Based on the formula for * relative luminance defined in WCAG 2.0, W3C Recommendation 11 December 2008. */ @get:RequiresApi(26) inline val @receiver:ColorLong Long.luminance get() = Color.luminance(this) /** * Creates a new [Color] instance from a [color long][Color]. */ @RequiresApi(26) inline fun @receiver:ColorLong Long.toColor(): Color = Color.valueOf(this) /** * Converts the specified [color long][Color] to an ARGB [color int][Color]. */ @RequiresApi(26) @ColorInt inline fun @receiver:ColorLong Long.toColorInt() = Color.toArgb(this) /** * Indicates whether the color is in the [sRGB][android.graphics.ColorSpace.Named.SRGB] * color space. */ @get:RequiresApi(26) inline val @receiver:ColorLong Long.isSrgb get() = Color.isSrgb(this) /** * Indicates whether the color is in a [wide-gamut][android.graphics.ColorSpace] color space. */ @get:RequiresApi(26) inline val @receiver:ColorLong Long.isWideGamut get() = Color.isWideGamut(this) /** * Returns the color space encoded in the specified color long. */ @get:RequiresApi(26) inline val @receiver:ColorLong Long.colorSpace: ColorSpace get() = Color.colorSpace(this) /** * Return a corresponding [Int] color of this [String]. * * Supported formats are: * ``` * #RRGGBB * #AARRGGBB * ``` * * The following names are also accepted: "red", "blue", "green", "black", "white", * "gray", "cyan", "magenta", "yellow", "lightgray", "darkgray", * "grey", "lightgrey", "darkgrey", "aqua", "fuchsia", "lime", * "maroon", "navy", "olive", "purple", "silver", "teal". * * @throws IllegalArgumentException if this [String] cannot be parsed. */ @ColorInt inline fun String.toColorInt(): Int = Color.parseColor(this)
apache-2.0
fe6d6900139ebc29f7cfe72083a67a66
28.637363
93
0.701428
3.616493
false
false
false
false
deltadak/plep
src/main/kotlin/nl/deltadak/plep/ui/taskcell/contextmenu/ContextMenuCreator.kt
1
3740
package nl.deltadak.plep.ui.taskcell.contextmenu import javafx.scene.control.* import javafx.scene.layout.GridPane import nl.deltadak.plep.database.DatabaseFacade import nl.deltadak.plep.database.tables.Colors import nl.deltadak.plep.ui.taskcell.TaskCell import nl.deltadak.plep.ui.taskcell.subtasks.SubtasksCreator import nl.deltadak.plep.ui.taskcell.util.setBackgroundColor import nl.deltadak.plep.ui.util.LABEL_COLOR_CONTEXT_MENU_ITEMS import nl.deltadak.plep.ui.util.converters.toHomeworkTaskList import nl.deltadak.plep.ui.util.repeatTask import java.time.LocalDate /** * Every TaskCell has a context menu behind a right-click. */ class ContextMenuCreator( /** The main UI element. */ val gridPane: GridPane, /** The current focused day. */ private val focusDay: LocalDate, /** For user feedback. */ val progressIndicator: ProgressIndicator, /** The TaskCell to set a context menu on. */ private val taskCell: TaskCell, /** The day to which this TreeView (and thus TreeCell) belongs. */ private val day: LocalDate) { /** The number of weeks to show in the menu for repeating tasks. */ private val numberOfWeeksToRepeat = 8 /** * Creates a context menu, which gives options to: * - add a subtask * - repeat a task for a certain number of weeks * - change the colour of a task. * * @return The ContextMenu. */ fun create(): ContextMenu { // Get the tree which contains the TaskCell. val tree = taskCell.tree // Create the context menu. val contextMenu = ContextMenu() // Add a menu item to add a subtask. val addSubTaskMenuItem = MenuItem("Add subtask") addSubTaskMenuItem.setOnAction { SubtasksCreator(tree).create(taskCell.treeItem) } contextMenu.items.add(addSubTaskMenuItem) // Add a menu item for repetition of tasks. val repeatTasksMenu: Menu = createRepeatMenu(gridPane, focusDay) contextMenu.items.add(repeatTasksMenu) // Add a horizontal line as separator. val separatorItem = SeparatorMenuItem() contextMenu.items.add(separatorItem) val colors = Colors.getAll() for (colorID in 0..4) { // Initialize the color menu items with a certain number of spaces. val colorItem = MenuItem(LABEL_COLOR_CONTEXT_MENU_ITEMS) colorItem.style = "-fx-background-color: #" + colors[colorID] // Add the on-click action. colorItem.setOnAction { taskCell.setBackgroundColor(colorID) taskCell.treeItem.value.colorID = colorID DatabaseFacade(progressIndicator).pushData(day, tree.toHomeworkTaskList()) } contextMenu.items.add(colorItem) } return contextMenu } /** * Creates the Menu which provides an option to repeat a task weekly, for the next x weeks. * * @param gridPane Needed for repeatTask to refresh the UI. * @param focusDay Needed for repeatTask to refresh the UI. * * @return A drop down Menu. */ private fun createRepeatMenu(gridPane: GridPane, focusDay: LocalDate): Menu { // Initialize the numbers as menu items. val repeatTasksMenu = Menu("Repeat for x weeks") for (i in 1..numberOfWeeksToRepeat) { val menuItem = MenuItem("$i") menuItem.setOnAction { repeatTask(gridPane, repeatNumber = i, task = taskCell.item, day = day, focusDay = focusDay, progressIndicator = progressIndicator) } repeatTasksMenu.items.add(menuItem) } return repeatTasksMenu } }
mit
a378d179120d9e358e8c77e490971328
34.628571
147
0.655348
4.384525
false
false
false
false
JetBrains/teamcity-azure-plugin
plugin-azure-server/src/main/kotlin/jetbrains/buildServer/clouds/azure/arm/connector/tasks/FetchVirtualMachinesTaskImpl.kt
1
3209
/* * 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.connector.tasks import com.intellij.openapi.diagnostic.Logger import com.microsoft.azure.management.Azure import com.microsoft.azure.management.compute.OperatingSystemTypes import jetbrains.buildServer.clouds.azure.arm.throttler.AzureThrottlerCacheableTaskBaseImpl import rx.Single data class FetchVirtualMachinesTaskVirtualMachineDescriptor( val id: String, val name: String, val groupName: String, val isManagedDiskEnabled: Boolean, val osUnmanagedDiskVhdUri: String?, val osType: String?) class FetchVirtualMachinesTaskImpl : AzureThrottlerCacheableTaskBaseImpl<Unit, List<FetchVirtualMachinesTaskVirtualMachineDescriptor>>() { override fun createQuery(api: Azure, parameter: Unit): Single<List<FetchVirtualMachinesTaskVirtualMachineDescriptor>> { return api .virtualMachines() .listAsync() .toList() .last() .map { list -> val result = mutableListOf<FetchVirtualMachinesTaskVirtualMachineDescriptor>() for(vm in list) { try { result.add( FetchVirtualMachinesTaskVirtualMachineDescriptor( vm.id(), vm.name(), vm.resourceGroupName(), vm.isManagedDiskEnabled, if (vm.isManagedDiskEnabled) null else vm.inner().storageProfile().osDisk()?.vhd()?.uri(), when (vm.osType()) { OperatingSystemTypes.LINUX -> "Linux" OperatingSystemTypes.WINDOWS -> "Windows" else -> vm.osType()?.name } ) ) } catch (exception: Throwable) { LOG.warnAndDebugDetails("Could not read VirtualMachine. Id=${vm.id()}, Name=${vm.name()}, ResourceGroup=${vm.resourceGroupName()}", exception) } } result.toList() } .toSingle() } companion object { private val LOG = Logger.getInstance(FetchVirtualMachinesTaskImpl::class.java.name) } }
apache-2.0
1f2c597e1e220159a2b08a8f05303b14
44.842857
170
0.55095
5.61014
false
false
false
false
Bambooin/trime
app/src/main/java/com/osfans/trime/ime/core/EditorInstance.kt
1
9700
package com.osfans.trime.ime.core import android.inputmethodservice.InputMethodService import android.os.SystemClock import android.view.InputDevice import android.view.KeyCharacterMap import android.view.KeyEvent import android.view.inputmethod.EditorInfo import android.view.inputmethod.ExtractedTextRequest import android.view.inputmethod.InputConnection import com.osfans.trime.core.Rime import com.osfans.trime.data.AppPrefs import com.osfans.trime.ime.enums.InlineModeType import com.osfans.trime.ime.text.TextInputManager import timber.log.Timber class EditorInstance(private val ims: InputMethodService) { val prefs get() = AppPrefs.defaultInstance() val inputConnection: InputConnection? get() = ims.currentInputConnection val editorInfo: EditorInfo? get() = ims.currentInputEditorInfo val cursorCapsMode: Int get() { val ic = inputConnection ?: return 0 val ei = editorInfo ?: return 0 return if (ei.inputType != EditorInfo.TYPE_NULL) { ic.getCursorCapsMode(ei.inputType) } else 0 } val textInputManager: TextInputManager get() = (ims as Trime).textInputManager var lastCommittedText: CharSequence = "" var draftCache: String = "" fun commitText(text: CharSequence, dispatchToRime: Boolean = true): Boolean { val ic = inputConnection ?: return false ic.commitText(text, 1) lastCommittedText = text // Fix pressing Delete key will clear the input box issue on BlackBerry ic.clearMetaKeyStates(KeyEvent.getModifierMetaStateMask()) cacheDraft() return true } // 直接commit不做任何处理 fun commitText(text: CharSequence): Boolean { val ic = inputConnection ?: return false ic.commitText(text, 1) return true } /** * Commits the text got from Rime. */ fun commitRimeText(): Boolean { val ret = Rime.getCommit() if (ret) { commitText(Rime.getCommitText()) } Timber.i("\t<TrimeInput>\tcommitRimeText()\tupdateComposing") (ims as Trime).updateComposing() return ret } fun updateComposingText() { val ic = inputConnection ?: return val composingText = when (prefs.keyboard.inlinePreedit) { InlineModeType.INLINE_PREVIEW -> Rime.getComposingText() InlineModeType.INLINE_COMPOSITION -> Rime.getCompositionText() InlineModeType.INLINE_INPUT -> Rime.RimeGetInput() else -> "" } if (ic.getSelectedText(0).isNullOrEmpty() || !composingText.isNullOrEmpty()) { ic.setComposingText(composingText, 1) } } fun cacheDraft(): String { if (prefs.other.draftLimit.equals("0") || inputConnection == null) return "" val et = inputConnection!!.getExtractedText(ExtractedTextRequest(), 0) if (et == null) { Timber.e("cacheDraft() et==null") return "" } val cs = et.text ?: return "" if (cs.isNullOrBlank()) return "" draftCache = cs as String Timber.d("cacheDraft() $draftCache") return draftCache } /** * Gets [n] characters after the cursor's current position. The resulting string may be any * length ranging from 0 to n. * * @param n The number of characters to get after the cursor. Must be greater than 0 or this * method will fail. * @return [n] or less characters after the cursor. */ fun getTextAfterCursor(n: Int): String { val ic = inputConnection if (ic == null || n < 1) { return "" } return ic.getTextAfterCursor(n, 0)?.toString() ?: "" } /** * Gets [n] characters before the cursor's current position. The resulting string may be any * length ranging from 0 to n. * * @param n The number of characters to get before the cursor. Must be greater than 0 or this * method will fail. * @return [n] or less characters before the cursor. */ fun getTextBeforeCursor(n: Int): String { val ic = inputConnection if (ic == null || n < 1) { return "" } return ic.getTextBeforeCursor(n.coerceAtMost(1024), 0)?.toString() ?: "" } /** * Constructs a meta state integer flag which can be used for setting the `metaState` field when sending a KeyEvent * to the input connection. If this method is called without a meta modifier set to true, the default value `0` is * returned. * * @param ctrl Set to true to enable the CTRL meta modifier. Defaults to false. * @param alt Set to true to enable the ALT meta modifier. Defaults to false. * @param shift Set to true to enable the SHIFT meta modifier. Defaults to false. * * @return An integer containing all meta flags passed and formatted for use in a [KeyEvent]. */ fun meta( ctrl: Boolean = false, alt: Boolean = false, shift: Boolean = false, meta: Boolean = false, sym: Boolean = false, ): Int { var metaState = 0 if (ctrl) { metaState = metaState or KeyEvent.META_CTRL_ON or KeyEvent.META_CTRL_LEFT_ON } if (alt) { metaState = metaState or KeyEvent.META_ALT_ON or KeyEvent.META_ALT_LEFT_ON } if (shift) { metaState = metaState or KeyEvent.META_SHIFT_ON or KeyEvent.META_SHIFT_LEFT_ON } if (meta) { metaState = metaState or KeyEvent.META_META_ON or KeyEvent.META_META_LEFT_ON } if (sym) { metaState = metaState or KeyEvent.META_SYM_ON } return metaState } private fun sendDownKeyEvent(eventTime: Long, keyEventCode: Int, metaState: Int): Boolean { val ic = inputConnection ?: return false return ic.sendKeyEvent( KeyEvent( eventTime, eventTime, KeyEvent.ACTION_DOWN, keyEventCode, 0, metaState, KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_SOFT_KEYBOARD or KeyEvent.FLAG_KEEP_TOUCH_MODE, InputDevice.SOURCE_KEYBOARD ) ) } private fun sendUpKeyEvent(eventTime: Long, keyEventCode: Int, metaState: Int): Boolean { val ic = inputConnection ?: return false return ic.sendKeyEvent( KeyEvent( eventTime, SystemClock.uptimeMillis(), KeyEvent.ACTION_UP, keyEventCode, 0, metaState, KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_SOFT_KEYBOARD or KeyEvent.FLAG_KEEP_TOUCH_MODE, InputDevice.SOURCE_KEYBOARD ) ) } /** * Same as [InputMethodService.sendDownUpKeyEvents] but also allows to set meta state. * * @param keyEventCode The key code to send, use a key code defined in Android's [KeyEvent]. * @param metaState Flags indicating which meta keys are currently pressed. * @param count How often the key is pressed while the meta keys passed are down. Must be greater than or equal to * `1`, else this method will immediately return false. * * @return True on success, false if an error occurred or the input connection is invalid. */ fun sendDownUpKeyEvent(keyEventCode: Int, metaState: Int = meta(), count: Int = 1): Boolean { if (count < 1) return false val ic = inputConnection ?: return false ic.clearMetaKeyStates( KeyEvent.META_FUNCTION_ON or KeyEvent.META_SHIFT_MASK or KeyEvent.META_ALT_MASK or KeyEvent.META_CTRL_MASK or KeyEvent.META_META_MASK or KeyEvent.META_SYM_ON ) ic.beginBatchEdit() val eventTime = SystemClock.uptimeMillis() if (metaState and KeyEvent.META_CTRL_ON != 0) { sendDownKeyEvent(eventTime, KeyEvent.KEYCODE_CTRL_LEFT, 0) } if (metaState and KeyEvent.META_ALT_ON != 0) { sendDownKeyEvent(eventTime, KeyEvent.KEYCODE_ALT_LEFT, 0) } if (metaState and KeyEvent.META_SHIFT_ON != 0) { sendDownKeyEvent(eventTime, KeyEvent.KEYCODE_SHIFT_LEFT, 0) } if (metaState and KeyEvent.META_META_ON != 0) { sendDownKeyEvent(eventTime, KeyEvent.KEYCODE_META_LEFT, 0) } if (metaState and KeyEvent.META_SYM_ON != 0) { sendDownKeyEvent(eventTime, KeyEvent.KEYCODE_SYM, 0) } for (n in 0 until count) { sendDownKeyEvent(eventTime, keyEventCode, metaState) sendUpKeyEvent(eventTime, keyEventCode, metaState) } if (metaState and KeyEvent.META_SHIFT_ON != 0) { sendUpKeyEvent(eventTime, KeyEvent.KEYCODE_SHIFT_LEFT, 0) } if (metaState and KeyEvent.META_ALT_ON != 0) { sendUpKeyEvent(eventTime, KeyEvent.KEYCODE_ALT_LEFT, 0) } if (metaState and KeyEvent.META_CTRL_ON != 0) { sendUpKeyEvent(eventTime, KeyEvent.KEYCODE_CTRL_LEFT, 0) } if (metaState and KeyEvent.META_META_ON != 0) { sendUpKeyEvent(eventTime, KeyEvent.KEYCODE_META_LEFT, 0) } if (metaState and KeyEvent.META_SYM_ON != 0) { sendUpKeyEvent(eventTime, KeyEvent.KEYCODE_SYM, 0) } ic.endBatchEdit() return true } }
gpl-3.0
790ae694100e3597750b6a280a60ced6
35.134328
119
0.605225
4.379919
false
false
false
false
juanavelez/crabzilla
crabzilla-core/src/test/java/io/github/crabzilla/example1/customer/CustomerCommandAware.kt
1
1349
package io.github.crabzilla.example1.customer import io.github.crabzilla.framework.* class CustomerCommandAware : EntityCommandAware<Customer> { override val initialState: Customer = Customer() override val applyEvent: (event: DomainEvent, state: Customer) -> Customer = { event: DomainEvent, customer: Customer -> when (event) { is CustomerCreated -> customer.copy(customerId = event.customerId, name = event.name, isActive = false) is CustomerActivated -> customer.copy(isActive = true, reason = event.reason) is CustomerDeactivated -> customer.copy(isActive = false, reason = event.reason) else -> customer } } override val validateCmd: (command: Command) -> List<String> = { command -> when (command) { is CreateCustomer -> if (command.name == "a bad name") listOf("Invalid name: ${command.name}") else listOf() else -> listOf() // all other commands are valid } } override val cmdHandlerFactory: (cmdMetadata: CommandMetadata, command: Command, snapshot: Snapshot<Customer>) -> EntityCommandHandler<Customer> = { cmdMetadata: CommandMetadata, command: Command, snapshot: Snapshot<Customer> -> CustomerCmdHandler(cmdMetadata, command, snapshot, applyEvent) } }
apache-2.0
f2a895d60d13b72a12eb0e7e7ac75932
36.472222
109
0.657524
4.572881
false
false
false
false
proxer/ProxerLibAndroid
library/src/main/kotlin/me/proxer/library/internal/adapter/EpisodeInfoAdapter.kt
1
3273
package me.proxer.library.internal.adapter import com.squareup.moshi.FromJson import com.squareup.moshi.Json import com.squareup.moshi.JsonClass import com.squareup.moshi.ToJson import me.proxer.library.entity.info.AnimeEpisode import me.proxer.library.entity.info.EpisodeInfo import me.proxer.library.entity.info.MangaEpisode import me.proxer.library.enums.Category import me.proxer.library.enums.MediaLanguage import me.proxer.library.internal.adapter.EpisodeInfoAdapter.IntermediateEpisodeInfo.IntermediateEpisode /** * @author Ruben Gees */ internal class EpisodeInfoAdapter { private companion object { private const val DELIMITER = "," } @FromJson fun fromJson(json: IntermediateEpisodeInfo): EpisodeInfo { val episodes = when (json.category) { Category.ANIME -> json.episodes.map { episode -> val hosters = requireNotNull(episode.hosters).split(DELIMITER).toSet() val hosterImages = requireNotNull(episode.hosterImages).split(DELIMITER) AnimeEpisode(episode.number, episode.language, hosters, hosterImages) } Category.MANGA, Category.NOVEL -> json.episodes.map { episode -> val title = requireNotNull(episode.title) MangaEpisode(episode.number, episode.language, title) } } return EpisodeInfo( json.firstEpisode, json.lastEpisode, json.category, json.availableLanguages, json.userProgress, episodes ) } @ToJson fun toJson(value: EpisodeInfo?): IntermediateEpisodeInfo? { if (value == null) return null val episodes = value.episodes.map { when (it) { is AnimeEpisode -> { val joinedHosters = it.hosters.joinToString(DELIMITER) val joinedHosterImages = it.hosterImages.joinToString(DELIMITER) IntermediateEpisode(it.number, it.language, null, joinedHosters, joinedHosterImages) } is MangaEpisode -> IntermediateEpisode(it.number, it.language, it.title, null, null) else -> error("Unknown Episode type: ${it.javaClass.name}") } } return IntermediateEpisodeInfo( value.firstEpisode, value.lastEpisode, value.category, value.availableLanguages, value.userProgress, episodes ) } @JsonClass(generateAdapter = true) internal data class IntermediateEpisodeInfo( @Json(name = "start") val firstEpisode: Int, @Json(name = "end") val lastEpisode: Int, @Json(name = "kat") val category: Category, @Json(name = "lang") val availableLanguages: Set<MediaLanguage>, @Json(name = "state") val userProgress: Int?, @Json(name = "episodes") val episodes: List<IntermediateEpisode> ) { @JsonClass(generateAdapter = true) internal data class IntermediateEpisode( @Json(name = "no") val number: Int, @Json(name = "typ") val language: MediaLanguage, @Json(name = "title") val title: String?, @Json(name = "types") val hosters: String?, @Json(name = "typeimg") val hosterImages: String? ) } }
gpl-3.0
8d768fcb6ffb2e3ea98c5d57bd5bfefd
36.62069
104
0.641002
4.520718
false
false
false
false
jayrave/falkon
falkon-sql-builder-test-common/src/main/kotlin/com/jayrave/falkon/sqlBuilders/test/DataSourceExtn.kt
1
2402
package com.jayrave.falkon.sqlBuilders.test import java.sql.PreparedStatement import java.sql.ResultSet import javax.sql.DataSource fun DataSource.execute(sql: List<String>) { sql.forEach { execute(it) } } fun DataSource.execute(sql: String) { val connection = connection val preparedStatement = connection.prepareStatement(sql) try { preparedStatement.execute() } finally { preparedStatement.close() connection.close() } } fun DataSource.execute(sql: String, argsBinder: (PreparedStatement) -> Any?) { privateExecute(sql, argsBinder) { it.execute() } } fun DataSource.executeUpdate(sql: String, argsBinder: (PreparedStatement) -> Any?): Int { return privateExecute(sql, argsBinder, PreparedStatement::executeUpdate) } fun DataSource.executeDelete(sql: String, argsBinder: (PreparedStatement) -> Any?): Int { return executeUpdate(sql, argsBinder) } fun <R> DataSource.executeQuery( sql: String, argsBinder: (PreparedStatement) -> Any?, op: (ResultSet) -> R): R { return privateExecute(sql, {}) { ps -> argsBinder.invoke(ps) val resultSet = ps.executeQuery() resultSet.next() // To point to the first row in the result set val result = op.invoke(resultSet) resultSet.close() result } } fun DataSource.findRecordCountInTable(tableName: String): Int { val countColumnName = "count" return executeQuery("SELECT COUNT(*) AS $countColumnName FROM $tableName", {}) { it.getInt(it.findColumn(countColumnName)) } } fun DataSource.findAllRecordsInTable( tableName: String, columnNames: List<String>): List<Map<String, String?>> { val columnsSelector = when { columnNames.isEmpty() -> "*" else -> columnNames.joinToString() } return executeQuery("SELECT $columnsSelector FROM $tableName", {}) { resultSet -> resultSet.extractRecordsAsMap(columnNames) } } private fun <R> DataSource.privateExecute( sql: String, argsBinder: (PreparedStatement) -> Any?, executor: (PreparedStatement) -> R): R { val connection = connection val preparedStatement = connection.prepareStatement(sql) return try { argsBinder.invoke(preparedStatement) executor.invoke(preparedStatement) } finally { preparedStatement.close() connection.close() } }
apache-2.0
51caf2fc87e97f2f36acd50a35ac7913
26
89
0.674438
4.351449
false
false
false
false
premnirmal/StockTicker
app/src/main/kotlin/com/github/premnirmal/ticker/analytics/Analytics.kt
1
1289
package com.github.premnirmal.ticker.analytics import android.app.Activity import com.github.premnirmal.ticker.model.StocksProvider import com.github.premnirmal.ticker.widget.WidgetDataProvider import javax.inject.Inject interface Analytics { fun trackScreenView(screenName: String, activity: Activity) {} fun trackClickEvent(event: ClickEvent) {} fun trackGeneralEvent(event: GeneralEvent) {} } sealed class AnalyticsEvent(val name: String) { val properties: Map<String, String> get() = _properties private val _properties = HashMap<String, String>() open fun addProperty(key: String, value: String) = apply { _properties[key] = value } } class GeneralEvent(name: String): AnalyticsEvent(name) { override fun addProperty(key: String, value: String) = apply { super.addProperty(key, value) } } class ClickEvent(name: String): AnalyticsEvent(name) { override fun addProperty(key: String, value: String) = apply { super.addProperty(key, value) } } class GeneralProperties @Inject constructor( private val widgetDataProvider: WidgetDataProvider, private val stocksProvider: StocksProvider ) { val widgetCount: Int get() = widgetDataProvider.getAppWidgetIds().size val tickerCount: Int get() = stocksProvider.tickers.value.size }
gpl-3.0
39c86e1a1118199d4fb47928d9168abd
26.446809
64
0.752521
4.040752
false
false
false
false
AlmasB/FXGL
fxgl-tools/src/main/kotlin/com/almasb/fxgl/tools/dialogues/DialoguePane.kt
1
21338
/* * FXGL - JavaFX Game Library. The MIT License (MIT). * Copyright (c) AlmasB ([email protected]). * See LICENSE for details. */ package com.almasb.fxgl.tools.dialogues import com.almasb.fxgl.animation.Interpolators import com.almasb.fxgl.core.collection.PropertyChangeListener import com.almasb.fxgl.core.math.FXGLMath import com.almasb.fxgl.cutscene.dialogue.* import com.almasb.fxgl.cutscene.dialogue.DialogueNodeType.* import com.almasb.fxgl.dsl.* import com.almasb.fxgl.tools.dialogues.ui.FXGLContextMenu import com.almasb.fxgl.logging.Logger import com.almasb.fxgl.texture.toImage import com.almasb.fxgl.tools.dialogues.DialogueEditorVars.IS_SNAP_TO_GRID import com.almasb.fxgl.tools.dialogues.ui.SelectionRectangle import javafx.beans.property.SimpleBooleanProperty import javafx.beans.property.SimpleIntegerProperty import javafx.collections.FXCollections import javafx.collections.ListChangeListener import javafx.collections.MapChangeListener import javafx.geometry.Point2D import javafx.scene.Cursor import javafx.scene.Group import javafx.scene.effect.Glow import javafx.scene.input.MouseButton import javafx.scene.layout.* import javafx.scene.paint.Color import javafx.scene.shape.Circle import javafx.scene.shape.Rectangle import javafx.scene.transform.Scale import javafx.util.Duration import kotlin.math.* /** * * * @author Almas Baimagambetov ([email protected]) */ class DialoguePane(graph: DialogueGraph = DialogueGraph()) : Pane() { companion object { private val log = Logger.get<DialoguePane>() private val branch: (DialogueNode) -> NodeView = { BranchNodeView(it) } private val end: (DialogueNode) -> NodeView = { EndNodeView(it) } private val start: (DialogueNode) -> NodeView = { StartNodeView(it) } private val function: (DialogueNode) -> NodeView = { FunctionNodeView(it) } private val text: (DialogueNode) -> NodeView = { TextNodeView(it) } private val subdialogue: (DialogueNode) -> NodeView = { SubDialogueNodeView(it) } private val choice: (DialogueNode) -> NodeView = { ChoiceNodeView(it) } val nodeConstructors = linkedMapOf<DialogueNodeType, () -> DialogueNode>( TEXT to { TextNode("") }, CHOICE to { ChoiceNode("") }, BRANCH to { BranchNode("") }, FUNCTION to { FunctionNode("") }, END to { EndNode("") }, START to { StartNode("") } //SUBDIALOGUE to { SubDialogueNode("") } ) val nodeViewConstructors = linkedMapOf<DialogueNodeType, (DialogueNode) -> NodeView>( TEXT to text, CHOICE to choice, BRANCH to branch, FUNCTION to function, END to end, START to start //SUBDIALOGUE to subdialogue ) private const val CELL_SIZE = 39.0 private const val MARGIN_CELLS = 3 private const val CELL_DISTANCE = CELL_SIZE + 1.0 } private val contentRoot = Group() private var selectedOutLink: OutLinkPoint? = null var graph = graph private set private val views = Group() private val edgeViews = Group() private val nodeViews = Group() val isDirtyProperty = SimpleBooleanProperty(false) /** * Are all outgoing links connected. */ val isConnectedProperty = SimpleBooleanProperty(true) private val scale = Scale() private val dragScale = 1.35 private var mouseX = 0.0 private var mouseY = 0.0 private val mouseGestures = MouseGestures(contentRoot) private val selectionRect = SelectionRectangle().also { it.cursor = Cursor.MOVE } private var selectionStart = Point2D.ZERO private var isSelectingRectangle = false private val selectedNodeViews = arrayListOf<NodeView>() private val history = FXCollections.observableArrayList<EditorAction>() private val historyIndex = SimpleIntegerProperty(-1) private val contextMenu = FXGLContextMenu() init { val cell = Rectangle(CELL_SIZE - 1, CELL_SIZE - 1, Color.GRAY) cell.stroke = Color.WHITESMOKE cell.strokeWidth = 0.2 val image = toImage(cell) val bgGrid = Region() bgGrid.background = Background(BackgroundImage(image, BackgroundRepeat.REPEAT, BackgroundRepeat.REPEAT, BackgroundPosition.DEFAULT, BackgroundSize.DEFAULT) ) bgGrid.isMouseTransparent = true contentRoot.children.addAll( bgGrid, edgeViews, views, nodeViews, selectionRect ) contentRoot.transforms += scale setOnScroll { val scaleFactor = if (it.deltaY < 0) 0.95 else 1.05 scale.x *= scaleFactor scale.y *= scaleFactor contentRoot.translateX += it.sceneX * (1 - scaleFactor) * scale.x contentRoot.translateY += it.sceneY * (1 - scaleFactor) * scale.y } children.addAll(contentRoot) initContextMenu() mouseGestures.makeDraggable(selectionRect) { selectionStart = Point2D(selectionRect.layoutX, selectionRect.layoutY) performUIAction(BulkAction( selectedNodeViews.map { val layoutX = it.properties["startLayoutX"] as Double val layoutY = it.properties["startLayoutY"] as Double MoveNodeAction(it.node, this::getNodeView, layoutX, layoutY, it.layoutX, it.layoutY) } )) } selectionRect.layoutXProperty().addListener { _, prevX, layoutX -> val dx = layoutX.toDouble() - prevX.toDouble() selectedNodeViews.forEach { it.layoutX += dx } } selectionRect.layoutYProperty().addListener { _, prevY, layoutY -> val dy = layoutY.toDouble() - prevY.toDouble() selectedNodeViews.forEach { it.layoutY += dy } } setOnMouseMoved { mouseX = it.sceneX mouseY = it.sceneY } setOnMouseDragged { if (isSelectingRectangle && it.button == MouseButton.PRIMARY) { val vector = contentRoot.sceneToLocal(it.sceneX, it.sceneY).subtract(selectionStart) selectionRect.width = vector.x selectionRect.height = vector.y return@setOnMouseDragged } if (mouseGestures.isDragging || it.button != MouseButton.SECONDARY) return@setOnMouseDragged contentRoot.translateX += (it.sceneX - mouseX) * dragScale contentRoot.translateY += (it.sceneY - mouseY) * dragScale mouseX = it.sceneX mouseY = it.sceneY } setOnMousePressed { if (it.button == MouseButton.PRIMARY && it.target === this) { isSelectingRectangle = true selectedNodeViews.clear() selectionStart = contentRoot.sceneToLocal(it.sceneX, it.sceneY) selectionRect.layoutX = selectionStart.x selectionRect.layoutY = selectionStart.y selectionRect.width = 0.0 selectionRect.height = 0.0 selectionRect.isVisible = true } if (it.button == MouseButton.SECONDARY) { getGameScene().setCursor(Cursor.CLOSED_HAND) } } setOnMouseReleased { if (it.button == MouseButton.SECONDARY) { getGameScene().setCursor(Cursor.DEFAULT) } if (!isSelectingRectangle) { return@setOnMouseReleased } isSelectingRectangle = false selectedNodeViews.addAll(selectionRect.getSelectedNodesIn(nodeViews, NodeView::class.java)) selectedNodeViews.forEach { it.properties["startLayoutX"] = it.layoutX it.properties["startLayoutY"] = it.layoutY } if (selectedNodeViews.isEmpty()) { selectionRect.isVisible = false } } initGraphListeners() initGridListener(bgGrid) initDefaultNodes() } private fun initDefaultNodes() { val start = StartNode("Sample start text") val mid = TextNode("Sample text") val end = EndNode("Sample end text") graph.addNode(start) graph.addNode(mid) graph.addNode(end) graph.addEdge(start, mid) graph.addEdge(mid, end) getNodeView(start).also { it.relocate(50.0, getAppHeight() / 2.0) snapToGrid(it) } getNodeView(mid).also { it.relocate((getAppWidth() - 370.0 + 50) / 2.0, getAppHeight() / 2.0) snapToGrid(it) } getNodeView(end).also { it.relocate(getAppWidth() - 370.0, getAppHeight() / 2.0) snapToGrid(it) } } private fun initContextMenu() { nodeConstructors .filter { it.key != START } .forEach { (type, ctor) -> contextMenu.addItem(type.toString()) { val node = ctor() performUIAction(AddNodeAction(graph, node)) } } setOnMouseClicked { if (it.isControlDown) { if (it.target !== this) return@setOnMouseClicked contextMenu.show(contentRoot, it.sceneX, it.sceneY) } } } private fun initGraphListeners() { graph.nodes.addListener { c: MapChangeListener.Change<out Int, out DialogueNode> -> if (c.wasAdded()) { val node = c.valueAdded onAdded(node) } else if (c.wasRemoved()) { val node = c.valueRemoved onRemoved(node) } } graph.edges.addListener { c: ListChangeListener.Change<out DialogueEdge> -> while (c.next()) { if (c.wasAdded()) { c.addedSubList.forEach { onAdded(it) } } else if (c.wasRemoved()) { c.removed.forEach { onRemoved(it) } } } } } private fun initGridListener(bg: Region) { run({ var minX = Double.MAX_VALUE var minY = Double.MAX_VALUE var maxX = -Double.MAX_VALUE var maxY = -Double.MAX_VALUE nodeViews.children .map { it as NodeView } .forEach { minX = min(it.layoutX, minX) minY = min(it.layoutY, minY) maxX = max(it.layoutX + it.prefWidth, maxX) maxY = max(it.layoutY + it.prefHeight, maxY) } bg.layoutX = (minX / CELL_DISTANCE).toInt() * CELL_DISTANCE - MARGIN_CELLS * CELL_DISTANCE bg.layoutY = (minY / CELL_DISTANCE).toInt() * CELL_DISTANCE - MARGIN_CELLS * CELL_DISTANCE bg.prefWidth = ((maxX - bg.layoutX) / CELL_DISTANCE).toInt() * CELL_DISTANCE + MARGIN_CELLS * CELL_DISTANCE bg.prefHeight = ((maxY - bg.layoutY) / CELL_DISTANCE).toInt() * CELL_DISTANCE + MARGIN_CELLS * CELL_DISTANCE }, Duration.seconds(0.1)) FXGL.getWorldProperties().addListener<Boolean>(IS_SNAP_TO_GRID, PropertyChangeListener { _, isSnap -> if (isSnap) { nodeViews.children .map { it as NodeView } .forEach { snapToGrid(it) } } }) } private fun onAdded(node: DialogueNode) { val p = contentRoot.sceneToLocal(mouseX, mouseY) onAdded(node, p.x, p.y) } private fun onAdded(node: DialogueNode, x: Double, y: Double) { log.debug("Added node: $node") isDirtyProperty.value = true val nodeViewConstructor = nodeViewConstructors[node.type] ?: throw IllegalArgumentException("View constructor for ${node.type} does not exist") val nodeView = nodeViewConstructor(node) addNodeView(nodeView, x, y) evaluateGraphConnectivity() } private fun onRemoved(node: DialogueNode) { log.debug("Removed node: $node") isDirtyProperty.value = true val nodeView = getNodeView(node) // so that user does not accidentally press it again nodeView.closeButton.isVisible = false animationBuilder() .duration(Duration.seconds(0.56)) .interpolator(Interpolators.EXPONENTIAL.EASE_OUT()) .onFinished(Runnable { nodeViews.children -= nodeView }) .scale(nodeView) .from(Point2D(1.0, 1.0)) .to(Point2D.ZERO) .buildAndPlay() evaluateGraphConnectivity() } private fun onAdded(edge: DialogueEdge) { log.debug("Added edge: $edge") isDirtyProperty.value = true val (outPoint, inPoint) = if (edge is DialogueChoiceEdge) { getNodeView(edge.source).outPoints.find { it.choiceOptionID == edge.optionID }!! to getNodeView(edge.target).inPoint!! } else { getNodeView(edge.source).outPoints.first() to getNodeView(edge.target).inPoint!! } outPoint.connect(inPoint) val edgeView = EdgeView(edge, outPoint, inPoint) edgeViews.children.add(edgeView) evaluateGraphConnectivity() } private fun onRemoved(edge: DialogueEdge) { log.debug("Removed edge: $edge") isDirtyProperty.value = true val edgeView = getEdgeView(edge) val p1 = Point2D(edgeView.startX, edgeView.startY) val p2 = Point2D(edgeView.controlX1, edgeView.controlY1) val p3 = Point2D(edgeView.controlX2, edgeView.controlY2) val p4 = Point2D(edgeView.endX, edgeView.endY) val group = Group() group.effect = Glow(0.7) val numSegments = 350 for (t in 0..numSegments) { val delay = if (graph.findNodeID(edgeView.source.owner.node) == -1) t else (numSegments - t) val p = FXGLMath.bezier(p1, p2, p3, p4, t / numSegments.toDouble()) val c = Circle(p.x, p.y, 2.0, edgeView.stroke) group.children += c animationBuilder() .interpolator(Interpolators.BOUNCE.EASE_OUT()) .delay(Duration.millis(delay * 2.0)) .duration(Duration.seconds(0.35)) .fadeOut(c) .buildAndPlay() } views.children += group runOnce({ views.children -= group }, Duration.seconds(7.0)) edgeView.source.disconnect() edgeViews.children -= edgeView evaluateGraphConnectivity() } /** * Checks that all outgoing links are connected. */ private fun evaluateGraphConnectivity() { isConnectedProperty.value = nodeViews.children .map { it as NodeView } .flatMap { it.outPoints } .all { it.isConnected } } private fun getNodeView(node: DialogueNode): NodeView { return nodeViews.children .map { it as NodeView } .find { it.node === node } ?: throw IllegalArgumentException("No view found for node $node") } private fun getEdgeView(edge: DialogueEdge): EdgeView { val optionID = if (edge is DialogueChoiceEdge) edge.optionID else -1 return edgeViews.children .map { it as EdgeView } .find { it.source.owner.node === edge.source && it.optionID == optionID && it.target.owner.node === edge.target } ?: throw IllegalArgumentException("No edge view found for edge $edge") } private fun addNodeView(nodeView: NodeView, x: Double, y: Double) { nodeView.relocate(x, y) attachMouseHandler(nodeView) nodeViews.children.add(nodeView) // START node cannot be removed if (nodeView.node.type == START) { nodeView.closeButton.isVisible = false } if (getb(IS_SNAP_TO_GRID)) snapToGrid(nodeView) } private fun attachMouseHandler(nodeView: NodeView) { mouseGestures.makeDraggable(nodeView) { if (getb(IS_SNAP_TO_GRID)) snapToGrid(nodeView) val startLayoutX = nodeView.properties["startLayoutX"] as Double val startLayoutY = nodeView.properties["startLayoutY"] as Double if (startLayoutX != nodeView.layoutX || startLayoutY != nodeView.layoutY) { performUIAction(MoveNodeAction(nodeView.node, this::getNodeView, startLayoutX, startLayoutY, nodeView.layoutX, nodeView.layoutY)) } } nodeView.cursor = Cursor.MOVE nodeView.closeButton.setOnMouseClicked { performUIAction(RemoveNodeAction(graph, nodeView.node, nodeView.layoutX, nodeView.layoutY, this::getNodeView)) } nodeView.outPoints.forEach { outPoint -> attachMouseHandler(outPoint) } nodeView.outPoints.addListener { c: ListChangeListener.Change<out OutLinkPoint> -> while (c.next()) { c.addedSubList.forEach { outPoint -> attachMouseHandler(outPoint) } c.removed.forEach { outPoint -> disconnectOutLink(outPoint) } } } nodeView.inPoint?.let { inPoint -> attachMouseHandler(inPoint) } } private fun attachMouseHandler(outPoint: OutLinkPoint) { outPoint.cursor = Cursor.HAND outPoint.setOnMouseClicked { if (it.button == MouseButton.PRIMARY) { selectedOutLink = outPoint } else { if (outPoint.isConnected) { disconnectOutLink(outPoint) } } } } private fun attachMouseHandler(inPoint: InLinkPoint) { inPoint.cursor = Cursor.HAND inPoint.setOnMouseClicked { if (it.button == MouseButton.PRIMARY) { selectedOutLink?.let { outPoint -> if (outPoint.isConnected) { disconnectOutLink(outPoint) } if (outPoint.choiceOptionID != -1) { performUIAction(AddChoiceEdgeAction(graph, outPoint.owner.node, outPoint.choiceOptionID, inPoint.owner.node)) } else { performUIAction(AddEdgeAction(graph, outPoint.owner.node, inPoint.owner.node)) } // reset selection selectedOutLink = null } } } } private fun snapToGrid(nodeView: NodeView) { nodeView.layoutX = (nodeView.layoutX / CELL_DISTANCE).roundToInt() * CELL_DISTANCE nodeView.layoutY = (nodeView.layoutY / CELL_DISTANCE).roundToInt() * CELL_DISTANCE } private fun disconnectOutLink(outPoint: OutLinkPoint) { outPoint.other?.let { inPoint -> if (outPoint.choiceOptionID != -1) { performUIAction(RemoveChoiceEdgeAction(graph, outPoint.owner.node, outPoint.choiceOptionID, inPoint.owner.node)) } else { performUIAction(RemoveEdgeAction(graph, outPoint.owner.node, inPoint.owner.node)) } } } private fun performUIAction(action: EditorAction) { // if we recently performed undo, then update history if (historyIndex.value < history.size - 1) { history.remove(historyIndex.value + 1, history.size) } history += action historyIndex.value++ action.run() } fun openAddNodeDialog() { contextMenu.show(contentRoot, 0.0, 30.0) } fun undo() { if (historyIndex.value < 0) return history[historyIndex.value].undo() historyIndex.value-- } fun redo() { showMessage("TODO: Sorry, not implemented yet.") } fun save(): SerializableGraph { isDirtyProperty.value = false val serializedGraph = DialogueGraphSerializer.toSerializable(graph) nodeViews.children.map { it as NodeView }.forEach { serializedGraph.uiMetadata[graph.findNodeID(it.node)] = SerializablePoint2D(it.layoutX, it.layoutY) } return serializedGraph } fun load(serializedGraph: SerializableGraph) { log.info("Loaded graph with version=${serializedGraph.version}") graph = DialogueGraphSerializer.fromSerializable(serializedGraph) nodeViews.children.clear() edgeViews.children.clear() graph.nodes.forEach { (id, node) -> val x = serializedGraph.uiMetadata[id]?.x ?: 100.0 val y = serializedGraph.uiMetadata[id]?.y ?: 100.0 onAdded(node, x, y) } graph.edges.forEach { edge -> onAdded(edge) } initGraphListeners() isDirtyProperty.value = false } }
mit
bd22b53b29d9e7e9ad1551bd742e4115
31.331818
151
0.58356
4.473375
false
false
false
false
kishmakov/Kitchen
server/src/io/magnaura/server/compiler/CompilationView.kt
1
1878
package io.magnaura.server.compiler import com.intellij.openapi.vfs.CharsetToolkit import com.intellij.psi.PsiFileFactory import com.intellij.psi.impl.PsiFileFactoryImpl import com.intellij.testFramework.LightVirtualFile import org.jetbrains.kotlin.fir.declarations.FirProperty import org.jetbrains.kotlin.fir.types.ConeKotlinType import org.jetbrains.kotlin.fir.types.FirResolvedTypeRef import org.jetbrains.kotlin.fir.types.classId import org.jetbrains.kotlin.idea.KotlinLanguage import org.jetbrains.kotlin.psi.KtFile class CompilationView( val contextId: String, val commandId: String, val context: String, val command: String) { private val viewProject = KotlinEnvironment.coreEnvironment().project fun compileContext(): String = context fun compileCommand(): String = inferCommandType().classId.toString() private fun inferCommandType(): ConeKotlinType { val content = "$context\n\nval ${CommandProcessor.MOCK_VAL_NAME} = $command".wrapInPackage(commandId) val ktFile = viewKotlinFile("command_type.kt", content) val firFiles = firFilesFor(viewProject, listOf(ktFile)) val property = firFiles[0].declarations.first { it is FirProperty && it.name.toString() == CommandProcessor.MOCK_VAL_NAME } as FirProperty return (property.returnTypeRef as FirResolvedTypeRef).type } private fun viewKotlinFile(name: String, content: String): KtFile = (PsiFileFactory.getInstance(viewProject) as PsiFileFactoryImpl) .trySetupPsiForFile( LightVirtualFile( if (name.endsWith(".kt")) name else "$name.kt", KotlinLanguage.INSTANCE, content ).apply { charset = CharsetToolkit.UTF8_CHARSET }, KotlinLanguage.INSTANCE, true, false ) as KtFile }
gpl-3.0
1936eca8f0a3f79d6d45bd7e3d66c758
37.346939
109
0.706603
4.637037
false
false
false
false
mizukami2005/StockQiita
app/src/main/kotlin/com/mizukami2005/mizukamitakamasa/qiitaclient/fragment/ViewPageListFragment.kt
1
7933
package com.mizukami2005.mizukamitakamasa.qiitaclient.fragment import android.graphics.Color import android.os.Bundle import android.support.v4.app.Fragment import android.support.v4.widget.SwipeRefreshLayout import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.AbsListView import android.widget.ListView import com.mizukami2005.mizukamitakamasa.qiitaclient.* import com.mizukami2005.mizukamitakamasa.qiitaclient.client.ArticleClient import com.mizukami2005.mizukamitakamasa.qiitaclient.model.Article import com.mizukami2005.mizukamitakamasa.qiitaclient.model.RealmArticle import com.mizukami2005.mizukamitakamasa.qiitaclient.model.RealmUser import com.mizukami2005.mizukamitakamasa.qiitaclient.model.User import com.mizukami2005.mizukamitakamasa.qiitaclient.view.activity.ArticleActivity import com.mizukami2005.mizukamitakamasa.qiitaclient.view.adapter.ArticleListAdapter import com.trello.rxlifecycle.kotlin.bindToLifecycle import io.realm.Realm import io.realm.RealmResults import io.realm.Sort import kotlinx.android.synthetic.main.activity_list_tag.* import kotlinx.android.synthetic.main.activity_list_tag.view.* import kotlinx.android.synthetic.main.activity_main.* import kotlinx.android.synthetic.main.fragment_view_page_list.* import kotlinx.android.synthetic.main.fragment_view_page_list.view.* import rx.Observable import rx.android.schedulers.AndroidSchedulers import rx.schedulers.Schedulers import javax.inject.Inject import kotlin.properties.Delegates /** * Created by mizukamitakamasa on 2016/11/03. */ class ViewPageListFragment: Fragment() { @Inject lateinit var articleClient: ArticleClient val listAdapter: ArticleListAdapter by lazy { ArticleListAdapter(context) } var listView: ListView by Delegates.notNull() private set var count = 1 var isLoading = true var isRefresh = false private fun getItems(observable: Observable<List<RealmArticle>>, tag: String) { observable .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .doAfterTerminate { isLoading = true activity.progress_bar.visibility = View.GONE if (swipe_refresh.isRefreshing) { swipe_refresh.isRefreshing = false } listAdapter.articles = loadArticle(tag) listAdapter.notifyDataSetChanged() } .bindToLifecycle(MainActivity()) .subscribe( { article -> Realm.getDefaultInstance().use { realm -> realm.executeTransaction { for (index in article.indices) { article.get(index).type = tag } realm.copyToRealmOrUpdate(article) } } }, { context.toast(getString(R.string.error_message)) }) } private fun getAddItems(observable: Observable<Array<Article>>) { observable .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .doAfterTerminate { isLoading = true activity.progress_bar.visibility = View.GONE } .bindToLifecycle(MainActivity()) .subscribe({ var arrayArticle = emptyArray<Article>() for (index in it.indices) { if (!isExitArticle(it.get(index).id)) { arrayArticle += it.get(index) } } listAdapter.addList(arrayArticle) listAdapter.notifyDataSetChanged() var position = listView.firstVisiblePosition var yOffset = listView.getChildAt(0).top listView.setSelectionFromTop(position, yOffset) }, { context.toast(getString(R.string.error_message)) }) } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { (context.applicationContext as QiitaClientApp).component.inject(this) val view = inflater.inflate(R.layout.fragment_view_page_list, null) view.swipe_refresh.setColorSchemeColors(Color.RED, Color.GREEN, Color.BLUE) view.swipe_refresh.setOnRefreshListener { isRefresh = true deleteSavedArticle() listAdapter.clear() listAdapter.notifyDataSetChanged() count = 1 init() } listView = view.page_list_view init() return view } companion object { fun newInstance(tag: String): ViewPageListFragment { val args = Bundle() args.putString("tag", tag) val fragment = ViewPageListFragment() fragment.arguments = args return fragment } } fun init() { var tag = arguments.getString("tag", "Ruby") val loadArticle = Realm.getDefaultInstance().where(RealmArticle::class.java).equalTo("type", tag).findAll() if (tag == "Recently") { if (isRefresh) { activity.progress_bar.visibility = View.VISIBLE getItems(articleClient.recentlySaveRealm("$count"), tag) } else if (loadArticle.size != 0) { listAdapter.articles = loadArticle(tag) } else { activity.progress_bar.visibility = View.VISIBLE getItems(articleClient.recentlySaveRealm("$count"), tag) } } else { if (isRefresh) { activity.progress_bar.visibility = View.VISIBLE getItems(articleClient.tagItemsSaveRealm(tag, "$count"), tag) } else if (loadArticle.size != 0) { listAdapter.articles = loadArticle(tag) } else { activity.progress_bar.visibility = View.VISIBLE getItems(articleClient.tagItemsSaveRealm(tag, "$count"), tag) } } listView.adapter = listAdapter listView.setOnItemClickListener { adapterView, view, position, id -> val article = listAdapter.articles[position] ArticleActivity.intent(context, article).let { startActivity(it) } } listView.setOnScrollListener(object : AbsListView.OnScrollListener { override fun onScroll(absListView: AbsListView, firstVisibleItem: Int, visibleItemCount: Int, totalItemCount: Int) { if (totalItemCount != 0 && totalItemCount == firstVisibleItem + visibleItemCount && isLoading) { isLoading = false activity.progress_bar.visibility = View.VISIBLE if (tag == "Recently") { count++ getAddItems(articleClient.recently("$count")) } else { count++ getAddItems(articleClient.tagItems(tag, "$count")) } } } override fun onScrollStateChanged(p0: AbsListView?, p1: Int) { } }) } private fun loadArticle(tag: String): Array<Article> { val loadArticle = Realm.getDefaultInstance().where(RealmArticle::class.java).equalTo("type", tag).findAll().sort("createdAt", Sort.DESCENDING) var arrayArticle = emptyArray<Article>() for (index in loadArticle.indices) { var article = Article() article.id = loadArticle.get(index).id as String article.title = loadArticle.get(index).title as String article.url = loadArticle.get(index).url as String article.body = loadArticle.get(index).body as String article.user = User(loadArticle.get(index).user?.id as String, loadArticle.get(index).user?.name as String, loadArticle.get(index).user?.profileImageUrl as String) article.type = loadArticle.get(index).type as String article.createdAt = loadArticle.get(index).createdAt as String arrayArticle += article } return arrayArticle } private fun deleteSavedArticle() { val loadArticle = Realm.getDefaultInstance().where(RealmArticle::class.java).findAll() val loadUser = Realm.getDefaultInstance().where(RealmUser::class.java).findAll() Realm.getDefaultInstance().use { realm -> realm.executeTransaction { loadArticle.deleteAllFromRealm() loadUser.deleteAllFromRealm() } } } private fun isExitArticle(articleId: String): Boolean { val loadArticle = Realm.getDefaultInstance().where(RealmArticle::class.java).findAll() return loadArticle.any { it.id == articleId } } }
mit
741ed3822d03c3c456843d5594585651
34.738739
169
0.703139
4.342091
false
false
false
false
LorittaBot/Loritta
web/showtime/backend/src/main/kotlin/net/perfectdreams/loritta/cinnamon/showtime/backend/views/LegacyCommandsView.kt
1
27660
package net.perfectdreams.loritta.cinnamon.showtime.backend.views import com.mrpowergamerbr.loritta.utils.locale.BaseLocale import kotlinx.html.FlowOrInteractiveContent import kotlinx.html.HTMLTag import kotlinx.html.HtmlBlockTag import kotlinx.html.TagConsumer import kotlinx.html.a import kotlinx.html.b import kotlinx.html.button import kotlinx.html.classes import kotlinx.html.code import kotlinx.html.details import kotlinx.html.div import kotlinx.html.fieldSet import kotlinx.html.hr import kotlinx.html.img import kotlinx.html.input import kotlinx.html.legend import kotlinx.html.p import kotlinx.html.source import kotlinx.html.span import kotlinx.html.style import kotlinx.html.summary import kotlinx.html.unsafe import kotlinx.html.video import kotlinx.html.visit import net.perfectdreams.dokyo.WebsiteTheme import net.perfectdreams.i18nhelper.core.I18nContext import net.perfectdreams.loritta.api.commands.CommandCategory import net.perfectdreams.loritta.api.commands.CommandInfo import net.perfectdreams.loritta.i18n.I18nKeysData import net.perfectdreams.loritta.cinnamon.showtime.backend.ShowtimeBackend import net.perfectdreams.loritta.cinnamon.showtime.backend.utils.ImageUtils import net.perfectdreams.loritta.cinnamon.showtime.backend.utils.NitroPayAdGenerator import net.perfectdreams.loritta.cinnamon.showtime.backend.utils.NitroPayAdSize import net.perfectdreams.loritta.cinnamon.showtime.backend.utils.SVGIconManager import net.perfectdreams.loritta.cinnamon.showtime.backend.utils.WebsiteAssetsHashManager import net.perfectdreams.loritta.cinnamon.showtime.backend.utils.commands.AdditionalCommandInfoConfig import net.perfectdreams.loritta.cinnamon.showtime.backend.utils.generateNitroPayAd import net.perfectdreams.loritta.cinnamon.showtime.backend.utils.imgSrcSetFromResources import net.perfectdreams.loritta.cinnamon.showtime.backend.utils.locale.formatAsHtml import java.awt.Color import java.time.LocalDate import java.time.ZoneId class LegacyCommandsView( showtimeBackend: ShowtimeBackend, websiteTheme: WebsiteTheme, locale: BaseLocale, i18nContext: I18nContext, path: String, val commands: List<CommandInfo>, val filterByCategory: CommandCategory? = null, val additionalCommandInfos: List<AdditionalCommandInfoConfig> ) : SidebarsView( showtimeBackend, websiteTheme, locale, i18nContext, path ) { companion object { // We don't want to show commands in the "MAGIC" category private val PUBLIC_CATEGORIES = CommandCategory.values().filterNot { it == CommandCategory.MAGIC } } override val sidebarAdId = "commands" val publicCommands = commands.filter { it.category in PUBLIC_CATEGORIES } override fun getTitle() = locale["modules.sectionNames.commands"] override fun HtmlBlockTag.leftSidebarContents() { // Add search bar // Yes, you need to wrap it into a div. Setting "width: 100%;" in the input just causes // it to overflow for *some reason*. div(classes = "side-content") { div { style = "text-align: center;" a(href = "/${locale.path}/commands/slash") { attributes["data-preload-link"] = "true" button(classes = "button-discord button-discord-info pure-button") { +i18nContext.get(I18nKeysData.Website.Commands.ViewSlashCommands) } } } div { style = "margin: 6px 10px;\n" + "display: flex;\n" + "align-items: center;\n" + "justify-content: center;\n" + "column-gap: 0.5em;" input(classes = "search-bar") { style = "width: 100%;" } // And we also need to wrap this into a div to avoid the icon resizing automatically due to the column-gap div { iconManager.search.apply(this) } } hr {} } // The first entry is "All" a(href = "/${locale.path}/commands/legacy", classes = "entry") { if (filterByCategory == null) classes = classes + "selected" // Yay workarounds! commandCategory { attributes["data-command-category"] = "ALL" div { +"Todos" } div { +publicCommands.size.toString() } } } for (category in PUBLIC_CATEGORIES.sortedByDescending { category -> commands.count { it.category == category } }) { val commandsInThisCategory = commands.count { it.category == category } // Register a redirect, the frontend will cancel this event if JS is enabled and filter the entries manually a(href = "/${locale.path}/commands/legacy/${category.name.lowercase()}", classes = "entry") { if (filterByCategory == category) classes = classes + "selected" commandCategory { attributes["data-command-category"] = category.name div { +category.getLocalizedName(locale) } div { +"$commandsInThisCategory" } } } } } override fun HtmlBlockTag.rightSidebarContents() { fun generateAllCommandsInfo( visible: Boolean, imagePath: String, sizes: String ) { val categoryName = "ALL" div(classes = "media") { style = "width: 100%;" attributes["data-category-info"] = categoryName if (!visible) style += "display: none;" div(classes = "media-figure") { style = "width: 250px;\n" + "height: 250px;\n" + "display: flex;\n" + "align-items: center; justify-content: center;" imgSrcSetFromResources(imagePath, sizes) { // Lazy load the images, because *for some reason* it loads all images even tho the div is display none. attributes["loading"] = "lazy" style = "max-height: 100%; max-width: 100%;" } } div(classes = "media-body") { for (entry in locale.getList("commands.category.all.description")) { p { formatAsHtml( entry, { if (it == 0) { code { +"+" } } if (it == 1) { code { +"+ping" } } }, { +it } ) } } } } } fun generateCategoryInfo( category: CommandCategory?, visible: Boolean, imagePath: String, sizes: String ) { val categoryName = category?.name ?: "ALL" div(classes = "media") { style = "width: 100%;" attributes["data-category-info"] = categoryName if (!visible) style += "display: none;" div(classes = "media-figure") { style = "width: 250px;\n" + "height: 250px;\n" + "display: flex;\n" + "align-items: center; justify-content: center;" imgSrcSetFromResources(imagePath, sizes) { // Lazy load the images, because *for some reason* it loads all images even tho the div is display none. attributes["loading"] = "lazy" style = "max-height: 100%; max-width: 100%;" } } div(classes = "media-body") { if (category != null) { for (entry in category.getLocalizedDescription(locale)) { p { +entry } } } else { p { +"Todos os comandos" } } } } } generateAllCommandsInfo( filterByCategory == null, "${versionPrefix}/assets/img/support/lori_support.png", "(max-width: 800px) 50vw, 15vw" ) generateCategoryInfo( CommandCategory.IMAGES, filterByCategory == CommandCategory.IMAGES, "/v3/assets/img/categories/images.png", "(max-width: 1366px) 250px" ) generateCategoryInfo( CommandCategory.FUN, filterByCategory == CommandCategory.FUN, "/v3/assets/img/categories/fun.png", "(max-width: 1366px) 250px" ) generateCategoryInfo( CommandCategory.MODERATION, filterByCategory == CommandCategory.MODERATION, "/v3/assets/img/categories/moderation.png", "(max-width: 1366px) 250px" ) generateCategoryInfo( CommandCategory.SOCIAL, filterByCategory == CommandCategory.SOCIAL, "/v3/assets/img/categories/social.png", "(max-width: 1366px) 250px" ) generateCategoryInfo( CommandCategory.DISCORD, filterByCategory == CommandCategory.DISCORD, "/v3/assets/img/categories/loritta_wumpus.png", "(max-width: 1366px) 250px", ) generateCategoryInfo( CommandCategory.UTILS, filterByCategory == CommandCategory.UTILS, "/v3/assets/img/categories/utilities.png", "(max-width: 1366px) 250px" ) generateCategoryInfo( CommandCategory.MISC, filterByCategory == CommandCategory.MISC, "/v3/assets/img/categories/miscellaneous.png", "(max-width: 1366px) 250px" ) generateCategoryInfo( CommandCategory.ACTION, filterByCategory == CommandCategory.ACTION, "/v3/assets/img/categories/hug.png", "(max-width: 1366px) 250px" ) generateCategoryInfo( CommandCategory.UNDERTALE, filterByCategory == CommandCategory.UNDERTALE, "/v3/assets/img/categories/lori_sans.png", "(max-width: 1366px) 250px" ) generateCategoryInfo( CommandCategory.POKEMON, filterByCategory == CommandCategory.POKEMON, "/v3/assets/img/categories/lori_pikachu.png", "(max-width: 1366px) 250px" ) generateCategoryInfo( CommandCategory.ECONOMY, filterByCategory == CommandCategory.ECONOMY, "/v3/assets/img/categories/money.png", "(max-width: 1366px) 250px" ) generateCategoryInfo( CommandCategory.FORTNITE, filterByCategory == CommandCategory.FORTNITE, "/v3/assets/img/categories/loritta_fortnite.png", "(max-width: 1366px) 250px" ) generateCategoryInfo( CommandCategory.VIDEOS, filterByCategory == CommandCategory.VIDEOS, "/v3/assets/img/categories/videos.png", "(max-width: 1366px) 250px" ) generateCategoryInfo( CommandCategory.ANIME, filterByCategory == CommandCategory.ANIME, "/v3/assets/img/categories/anime.png", "(max-width: 1366px) 250px" ) generateCategoryInfo( CommandCategory.MINECRAFT, filterByCategory == CommandCategory.MINECRAFT, "/v3/assets/img/categories/minecraft.png", "(max-width: 1366px) 250px" ) generateCategoryInfo( CommandCategory.ROBLOX, filterByCategory == CommandCategory.ROBLOX, "/v3/assets/img/categories/roblox.png", "(max-width: 1366px) 250px" ) // Generate ads below the <hr> tag // Desktop fieldSet { legend { style = "margin-left: auto;" iconManager.ad.apply(this) } val zoneId = ZoneId.of("America/Sao_Paulo") val now = LocalDate.now(zoneId) // Discords.com // TODO: Proper sponsorship impl if (now.isBefore(LocalDate.of(2021, 9, 10))) { // A kinda weird workaround, but it works unsafe { raw("""<a href="/sponsor/discords" target="_blank" class="sponsor-wrapper"> <div class="sponsor-pc-image"><img src="https://loritta.website/assets/img/sponsors/discords_pc.png?v2" class="sponsor-banner"></div> <div class="sponsor-mobile-image"><img src="https://loritta.website/assets/img/sponsors/discords_mobile.png" class="sponsor-banner"></div> </a>""") } } else { // Desktop Large generateNitroPayAd( "commands-desktop-large", listOf( NitroPayAdSize( 728, 90 ), NitroPayAdSize( 970, 90 ), NitroPayAdSize( 970, 250 ) ), mediaQuery = NitroPayAdGenerator.DESKTOP_LARGE_AD_MEDIA_QUERY ) generateNitroPayAd( "commands-desktop", listOf( NitroPayAdSize( 728, 90 ) ), mediaQuery = NitroPayAdGenerator.RIGHT_SIDEBAR_DESKTOP_MEDIA_QUERY ) // We don't do tablet here because there isn't any sizes that would fit a tablet comfortably generateNitroPayAd( "commands-phone", listOf( NitroPayAdSize( 300, 250 ), NitroPayAdSize( 320, 50 ) ), mediaQuery = NitroPayAdGenerator.RIGHT_SIDEBAR_PHONE_MEDIA_QUERY ) } } hr {} // First we are going to sort by category count // We change the first compare by to negative because we want it in a descending order (most commands in category -> less commands) for (command in publicCommands.sortedWith(compareBy({ -(commands.groupBy { it.category }[it.category]?.size ?: 0) }, CommandInfo::category, CommandInfo::label))) { val commandDescriptionKey = command.description val commandExamplesKey = command.examples val commandLabel = command.label // Additional command info (like images) val additionalInfo = additionalCommandInfos.firstOrNull { it.name == command.name } val color = getCategoryColor(command.category) commandEntry { attributes["data-command-name"] = command.name attributes["data-command-category"] = command.category.name style = if (filterByCategory == null || filterByCategory == command.category) "display: block;" else "display: none;" details(classes = "fancy-details") { style = "line-height: 1.2; position: relative;" summary { commandCategoryTag { style = "background-color: rgb(${color.red}, ${color.green}, ${color.blue});" +(command.category.getLocalizedName(locale)) } div { style = "display: flex;align-items: center;" div { style = "flex-grow: 1; align-items: center;" div { style = "display: flex;" commandLabel { style = "font-size: 1.5em; font-weight: bold; box-shadow: inset 0 0px 0 white, inset 0 -1px 0 rgb(${color.red}, ${color.green}, ${color.blue});" +commandLabel } } commandDescription { style = "word-wrap: anywhere;" if (commandDescriptionKey != null) { +locale.get(commandDescriptionKey) } else { +"???" } } } div(classes = "chevron-icon") { style = "font-size: 1.5em" iconManager.chevronDown.apply(this) } } } div(classes = "details-content") { style = "line-height: 1.4;" if (additionalInfo != null) { // Add additional images, if present if (additionalInfo.imageUrls != null && additionalInfo.imageUrls.isNotEmpty()) { for (imageUrl in additionalInfo.imageUrls) { val imageInfo = ImageUtils.getImageAttributes(imageUrl) img(src = imageInfo.path.removePrefix("static"), classes = "thumbnail") { // So, this is hard... // Because we are "floating" the image, content jumping is inevitable... (because the height is set to 0) // So we need to set a fixed width AND height, oof! // So we calculate it during build time and use it here, yay! // But anyway, this sucks... width = "250" // Lazy load the images, because *for some reason* it loads all images even tho the details tag is closed. attributes["loading"] = "lazy" // The aspect-ratio is used to avoid content reflow style = "aspect-ratio: ${imageInfo.width} / ${imageInfo.height};" } } } // Add additional videos, if present if (additionalInfo.videoUrls != null && additionalInfo.videoUrls.isNotEmpty()) { for (videoUrl in additionalInfo.videoUrls) { video(classes = "thumbnail") { // For videos, we need to use the "preload" attribute to force the video to *not* preload // The video will only start loading after the user clicks the video attributes["preload"] = "none" // The aspect-ratio is used to avoid content reflow style = "aspect-ratio: 16 / 9;" width = "250" controls = true source { src = videoUrl type = "video/mp4" } } } } } if (command.aliases.isNotEmpty()) { div { b { style = "color: rgb(${color.red}, ${color.green}, ${color.blue});" +"Sinônimos: " } for ((index, a) in command.aliases.withIndex()) { if (index != 0) { +", " } code { +a } } } hr {} } if (commandExamplesKey != null) { div { b { style = "color: rgb(${color.red}, ${color.green}, ${color.blue});" +"Exemplos: " } val examples = locale.getList(commandExamplesKey) for (example in examples) { val split = example.split("|-|") .map { it.trim() } div { style = "padding-bottom: 8px;" if (split.size == 2) { // If the command has a extended description // "12 |-| Gira um dado de 12 lados" // A extended description can also contain "nothing", but contains a extended description // "|-| Gira um dado de 6 lados" val (commandExample, explanation) = split div { span { style = "color: rgb(${color.red}, ${color.green}, ${color.blue});" iconManager.smallDiamond.apply(this) } +" " b { +explanation } } div { code { +commandLabel +" " +commandExample } } // examples.add("\uD83D\uDD39 **$explanation**") // examples.add("`" + commandLabelWithPrefix + "`" + (if (commandExample.isEmpty()) "" else "**` $commandExample`**")) } else { val commandExample = split[0] div { +commandLabel +" " +commandExample } } } } } } } } } } } fun getCategoryColor(category: CommandCategory) = when (category) { // Photoshop Logo Color CommandCategory.IMAGES -> Color(49, 197, 240) CommandCategory.FUN -> Color(254, 120, 76) CommandCategory.ECONOMY -> Color(47, 182, 92) // Discord Blurple CommandCategory.DISCORD -> Color(114, 137, 218) // Discord "Ban User" background CommandCategory.MODERATION -> Color(240, 71, 71) // Roblox Logo Color CommandCategory.ROBLOX -> Color(226, 35, 26) CommandCategory.ACTION -> Color(243, 118, 166) CommandCategory.UTILS -> Color(113, 147, 188) // Grass Block CommandCategory.MINECRAFT -> Color(124, 87, 58) // Pokémon (Pikachu) CommandCategory.POKEMON -> Color(244, 172, 0) // Undertale CommandCategory.UNDERTALE -> Color.BLACK // Vídeos CommandCategory.VIDEOS -> Color(163, 108, 253) // Social CommandCategory.SOCIAL -> Color(235, 0, 255) CommandCategory.MISC -> Color(121, 63, 166) CommandCategory.ANIME -> Color(132, 224, 212) else -> Color(0, 193, 223) } class COMMANDCATEGORY(consumer: TagConsumer<*>) : HTMLTag( "lori-command-category", consumer, emptyMap(), inlineTag = false, emptyTag = false ), HtmlBlockTag fun FlowOrInteractiveContent.commandCategory(block: COMMANDCATEGORY.() -> Unit = {}) { COMMANDCATEGORY(consumer).visit(block) } class COMMANDENTRY(consumer: TagConsumer<*>) : HTMLTag( "lori-command-entry", consumer, emptyMap(), inlineTag = false, emptyTag = false ), HtmlBlockTag fun FlowOrInteractiveContent.commandEntry(block: COMMANDENTRY.() -> Unit = {}) { COMMANDENTRY(consumer).visit(block) } fun FlowOrInteractiveContent.commandCategoryTag(block: HtmlBlockTag.() -> Unit = {}) = customHtmlTag("lori-command-category-tag", block) fun FlowOrInteractiveContent.commandLabel(block: HtmlBlockTag.() -> Unit = {}) = customHtmlTag("lori-command-label", block) fun FlowOrInteractiveContent.commandDescription(block: HtmlBlockTag.() -> Unit = {}) = customHtmlTag("lori-command-description", block) }
agpl-3.0
303df3be1a31cbe94a02f7c6b92efbe8
38.342817
180
0.448566
5.655828
false
false
false
false
angcyo/RLibrary
uiview/src/main/java/com/angcyo/uiview/dialog/UIFileSelectorDialog.kt
1
13052
package com.angcyo.uiview.dialog import android.graphics.Color import android.text.TextUtils import android.text.format.Formatter import android.view.Gravity import android.view.LayoutInflater import android.view.View import android.widget.FrameLayout import android.widget.HorizontalScrollView import com.angcyo.github.utilcode.utils.FileUtils import com.angcyo.library.okhttp.Ok import com.angcyo.uiview.R import com.angcyo.uiview.Root import com.angcyo.uiview.base.UIIDialogImpl import com.angcyo.uiview.kotlin.minValue import com.angcyo.uiview.net.RFunc import com.angcyo.uiview.net.RSubscriber import com.angcyo.uiview.net.Rx import com.angcyo.uiview.recycler.RBaseViewHolder import com.angcyo.uiview.recycler.adapter.RBaseAdapter import com.angcyo.uiview.recycler.widget.IShowState import com.angcyo.uiview.skin.SkinHelper import com.angcyo.uiview.utils.RUtils import com.angcyo.uiview.utils.string.MD5 import com.angcyo.uiview.viewgroup.RLinearLayout import java.io.File import java.text.SimpleDateFormat import java.util.* /** * Copyright (C) 2016,深圳市红鸟网络科技股份有限公司 All rights reserved. * 项目名称: * 类的描述:文件选择对话框 * 创建人员:Robi * 创建时间:2017/10/24 18:38 * 修改人员:Robi * 修改时间:2017/10/24 18:38 * 修改备注: * Version: 1.0.0 */ open class UIFileSelectorDialog : UIIDialogImpl { init { setGravity(Gravity.BOTTOM) } /**是否显示隐藏文件*/ var showHideFile = false /**是否显示文件MD5值*/ var showFileMd5 = false /**是否长按显示文件菜单*/ var showFileMenu = false /**最根的目录*/ var storageDirectory = Root.externalStorageDirectory() set(value) { if (File(value).exists()) { field = value targetPath = value } } /**目标路径*/ private var targetPath: String = storageDirectory set(value) { if (value.isNotEmpty() && value.startsWith(storageDirectory)) { if (File(value).isDirectory) { field = value } } else { field = storageDirectory } } private val simpleFormat by lazy { SimpleDateFormat("yyyy/MM/dd", Locale.CHINA) } /*选中的文件*/ private var selectorFilePath: String = "" private var onFileSelector: ((File) -> Unit)? = null constructor(initPath: String = "", onFileSelector: ((File) -> Unit)? = null) { targetPath = initPath this.onFileSelector = onFileSelector } constructor(onFileSelector: ((File) -> Unit)? = null) { this.onFileSelector = onFileSelector } override fun inflateDialogView(dialogRootLayout: FrameLayout, inflater: LayoutInflater): View { return inflate(R.layout.base_dialog_file_selector) } override fun getOffsetScrollTop(): Int { return (resources.displayMetrics.heightPixels) / 2 } override fun enableTouchBack(): Boolean { return true } private fun formatTime(time: Long): String = simpleFormat.format(time) private fun formatFileSize(size: Long): String = Formatter.formatFileSize(mActivity, size) private fun getFileList(path: String, onFileList: (List<FileItem>) -> Unit) { Rx.base(object : RFunc<List<FileItem>>() { override fun onFuncCall(): List<FileItem> { val file = File(path) return if (file.exists() && file.isDirectory && file.canRead()) { val list = file.listFiles().asList() Collections.sort(list) { o1, o2 -> when { (o1.isDirectory && o2.isDirectory) || (o1.isFile && o2.isFile) -> o1.name.toLowerCase().compareTo(o2.name.toLowerCase()) o2.isDirectory -> 1 o1.isDirectory -> -1 else -> o1.name.toLowerCase().compareTo(o2.name.toLowerCase()) } } val items = mutableListOf<FileItem>() val fileList: List<File> fileList = if (showHideFile) { list } else { list.filter { !it.isHidden } } fileList.mapTo(items) { FileItem(it, Ok.ImageType.of(Ok.ImageTypeUtil.getImageType(it)), if (showFileMd5) MD5.getStreamMD5(it.absolutePath) else "") } items } else { emptyList() } } }, object : RSubscriber<List<FileItem>>() { override fun onSucceed(bean: List<FileItem>) { super.onSucceed(bean) onFileList.invoke(bean) } }) } /**获取上一层路径*/ private fun getPrePath(): String = targetPath.substring(0, targetPath.lastIndexOf("/")) private var scrollView: HorizontalScrollView? = null private var selectorItemView: RLinearLayout? = null override fun initDialogContentView() { super.initDialogContentView() mViewHolder.tv(R.id.current_file_path_view).text = targetPath mViewHolder.view(R.id.base_selector_button).isEnabled = false scrollView = mViewHolder.v(R.id.current_file_path_layout) /*上一个路径*/ mViewHolder.click(R.id.current_file_path_layout) { resetPath(getPrePath()) } //选择按钮 mViewHolder.click(R.id.base_selector_button) { //T_.show(selectorFilePath) finishDialog { onFileSelector?.invoke(File(selectorFilePath)) } } mViewHolder.reV(R.id.base_recycler_view).apply { adapter = object : RBaseAdapter<FileItem>(mActivity) { override fun getItemLayoutId(viewType: Int): Int = R.layout.base_dialog_file_selector_item override fun onBindView(holder: RBaseViewHolder, position: Int, item: FileItem) { val bean = item.file holder.tv(R.id.base_name_view).text = bean.name holder.tv(R.id.base_time_view).text = formatTime(bean.lastModified()) //权限信息 holder.tv(R.id.base_auth_view).text = "${if (bean.isDirectory) "d" else "-"}${if (bean.canExecute()) "e" else "-"}${if (bean.canRead()) "r" else "-"}${if (bean.canWrite()) "w" else "-"}" holder.tv(R.id.base_md5_view).visibility = View.GONE //文件/文件夹 提示信息 when { bean.isDirectory -> { holder.glideImgV(R.id.base_image_view).apply { reset() setImageResource(R.drawable.base_floder_32) } if (bean.canRead()) { holder.tv(R.id.base_tip_view).text = "${bean.listFiles().size} 项" } } bean.isFile -> { holder.glideImgV(R.id.base_image_view).apply { reset() if (item.imageType == Ok.ImageType.UNKNOWN) { setImageResource(R.drawable.base_file_32) } else { url = bean.absolutePath } } if (bean.canRead()) { holder.tv(R.id.base_tip_view).text = formatFileSize(bean.length()) } //MD5值 if (showFileMd5) { holder.tv(R.id.base_md5_view).visibility = View.VISIBLE holder.tv(R.id.base_md5_view).text = item.fileMd5 } } else -> { holder.glideImgV(R.id.base_image_view).apply { reset() } if (bean.canRead()) { holder.tv(R.id.base_tip_view).text = "unknown" } } } fun selectorItemView(itemView: RLinearLayout, selector: Boolean) { if (selector) { itemView.setRBackgroundDrawable(SkinHelper.getSkin().getThemeTranColor(0x60)) } else { itemView.setRBackgroundDrawable(Color.TRANSPARENT) } } val itemView: RLinearLayout = holder.itemView as RLinearLayout selectorItemView(itemView, TextUtils.equals(selectorFilePath, bean.absolutePath)) if (bean.canRead()) { //item 点击事件 holder.clickItem { if (bean.isDirectory) { resetPath(bean.absolutePath) } else if (bean.isFile) { setSelectorFilePath(bean.absolutePath) selectorItemView?.let { selectorItemView(it, false) } selectorItemView = itemView selectorItemView(itemView, true) } } } else { //没权限 holder.itemView.setOnClickListener(null) holder.tv(R.id.base_tip_view).text = "无权限操作" } if (showFileMenu) { if (bean.isFile) { itemView.setOnLongClickListener { val file = File(bean.absolutePath) UIBottomItemDialog.build() .addItem("打开") { RUtils.openFile(mActivity, file) } .addItem("删除") { FileUtils.deleteFile(file) resetPath(file.path) setSelectorFilePath("") } .addItem("分享") { RUtils.shareFile(mActivity, bean.absolutePath) } .showDialog(mParentILayout) false } } } } } loadPath(targetPath) } } private fun setSelectorFilePath(path: String) { selectorFilePath = path mViewHolder.view(R.id.base_selector_button).isEnabled = File(selectorFilePath).exists() } private fun resetPath(path: String) { //L.e("call: resetPath -> $path") targetPath = path if (mViewHolder.tv(R.id.current_file_path_view).text.toString() == targetPath) { return } loadPath(path) } private fun loadPath(path: String) { targetPath = path //mViewHolder.view(R.id.base_selector_button).isEnabled = false mViewHolder.tv(R.id.current_file_path_view).text = targetPath scrollView?.let { post { it.scrollTo((it.getChildAt(0).measuredWidth - it.measuredWidth).minValue(0), 0) } } mViewHolder.reV(R.id.base_recycler_view).adapterRaw.setShowState(IShowState.NORMAL) getFileList(targetPath) { mViewHolder.reV(R.id.base_recycler_view).adapterRaw.resetData(it) if (it.isEmpty()) { mViewHolder.reV(R.id.base_recycler_view).adapterRaw.setShowState(IShowState.EMPTY) } } } } data class FileItem(val file: File, val imageType: Ok.ImageType, val fileMd5: String = "")
apache-2.0
f7751f04d922a018583fa9e793334018
36.439759
206
0.476885
4.923611
false
false
false
false
VladRassokhin/intellij-hcl
src/kotlin/org/intellij/plugins/hil/refactoring/ILRefactoringUtil.kt
1
4569
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.intellij.plugins.hil.refactoring import com.intellij.codeInsight.PsiEquivalenceUtil import com.intellij.openapi.util.text.StringUtil import com.intellij.psi.PsiElement import com.intellij.psi.util.PsiTreeUtil import com.intellij.util.containers.ContainerUtil import org.intellij.plugins.hil.psi.ILExpression import org.intellij.plugins.hil.psi.ILRecursiveVisitor import java.util.* import java.util.regex.Pattern object ILRefactoringUtil { fun getSelectedExpression(element1: PsiElement, element2: PsiElement): ILExpression? { var parent = PsiTreeUtil.findCommonParent(element1, element2) if (parent != null && parent !is ILExpression) { parent = PsiTreeUtil.getParentOfType(parent, ILExpression::class.java) } if (parent == null) { return null } if (parent !is ILExpression) { return null } if (element1 === PsiTreeUtil.getDeepestFirst(parent) && element2 === PsiTreeUtil.getDeepestLast(parent)) { return parent } return null } fun getOccurrences(pattern: PsiElement, context: PsiElement?): List<PsiElement> { if (context == null) { return emptyList() } val occurrences = ArrayList<PsiElement>() context.acceptChildren(object : ILRecursiveVisitor() { override fun visitElement(element: PsiElement?) { if (element == null) return if (PsiEquivalenceUtil.areElementsEquivalent(element, pattern)) { occurrences.add(element) return } super.visitElement(element) } }) return occurrences } private fun deleteNonLetterFromString(string: String): String { val pattern = Pattern.compile("[^a-zA-Z_]+") val matcher = pattern.matcher(string) return matcher.replaceAll("_") } fun generateNames(name: String): Collection<String> { @Suppress("NAME_SHADOWING") var name = name name = StringUtil.decapitalize(deleteNonLetterFromString(StringUtil.unquoteString(name.replace('.', '_')))) name = name.removePrefix("get").removePrefix("is") name = name.trim('_') val length = name.length val possibleNames = LinkedHashSet<String>() for (i in Math.max(0, length - 25)..length - 1) { if (name[i].isLetter() && (i == 0 || name[i - 1] == '_' || name[i - 1].isLowerCase() && name[i].isUpperCase())) { possibleNames.add(StringUtil.decapitalize(name.substring(i))) } } // prefer shorter names val reversed = possibleNames.reversed() return ContainerUtil.map(reversed) { var name1 = it if (name1.indexOf('_') == -1) { return@map name1 } name1 = StringUtil.capitalizeWords(name1, "_", true, true) StringUtil.decapitalize(name1.replace("_".toRegex(), "")) } } fun generateNamesByType(name: String): Collection<String> { @Suppress("NAME_SHADOWING") var name = name name = StringUtil.decapitalize(deleteNonLetterFromString(name.replace('.', '_'))) name = toUnderscoreCase(name) return listOf(name.substring(0, 1), name) } fun toUnderscoreCase(name: String): String { val buffer = StringBuilder() val length = name.length for (i in 0..length - 1) { val ch = name[i] if (ch != '-') { buffer.append(Character.toLowerCase(ch)) } else { buffer.append("_") } if (Character.isLetterOrDigit(ch)) { if (Character.isUpperCase(ch)) { if (i + 2 < length) { val chNext = name[i + 1] val chNextNext = name[i + 2] if (Character.isUpperCase(chNext) && Character.isLowerCase(chNextNext)) { buffer.append('_') } } } else if (Character.isLowerCase(ch) || Character.isDigit(ch)) { if (i + 1 < length) { val chNext = name[i + 1] if (Character.isUpperCase(chNext)) { buffer.append('_') } } } } } return buffer.toString() } }
apache-2.0
0abd2cbc2ffd3cc66a51cf3644f1cd46
31.411348
119
0.644123
4.157416
false
false
false
false
YounesRahimi/java-utils
src/main/java/ir/iais/utilities/javautils/jackson/serializers/AsJDurationSerializers.kt
2
1646
package ir.iais.utilities.javautils.jackson.serializers import com.fasterxml.jackson.core.JsonGenerator import com.fasterxml.jackson.databind.JsonSerializer import com.fasterxml.jackson.databind.SerializerProvider import ir.iais.utilities.javautils.utils.abs import ir.iais.utilities.javautils.utils.format import java.time.Duration class AsJDurationSerializer : JsonSerializer<Duration>() { override fun serialize(value: Duration, gen: JsonGenerator, serializers: SerializerProvider) { gen.codec.writeValue(gen, JSerDuration(value)) } } /** * Long value in milliseconds */ class LongAsJDurationSerializer : JsonSerializer<Long>() { override fun serialize(value: Long, gen: JsonGenerator, serializers: SerializerProvider) { gen.codec.writeValue(gen, JSerDuration(value)) } } data class JSerDuration(val hours: Long, val minutes: Long, val seconds: Long, val sign: String) { init { assert(hours >= 0) assert(minutes >= 0) assert(seconds >= 0) } constructor(duration: Duration) : this( duration.toHours().abs, (duration.toMinutes() - duration.toHours() * 60).abs, (duration.seconds - duration.toMinutes() * 60).abs, if (duration.isNegative) "-" else "" ) constructor(millis: Long) : this(Duration.ofMillis(millis)) fun serialize(): String = "$sign${hours.format(2)}:${minutes.format(2)}:${seconds.format(2)}".let { if (it == "${sign}00:00:00") "-" else it } fun serializeAsHourMinute(): String = "$sign${hours.format(2)}:${minutes.format(2)}".let { if (it == "${sign}00:00") "-" else it } }
gpl-3.0
caa0d5551074bf367fb474883a7acac1
36.431818
146
0.6774
4.064198
false
false
false
false
emce/smog
app/src/main/java/mobi/cwiklinski/smog/database/AppDatabase.kt
1
2007
package mobi.cwiklinski.smog.database import android.content.Context import android.database.sqlite.SQLiteDatabase import android.database.sqlite.SQLiteOpenHelper class AppDatabase : SQLiteOpenHelper { public companion object { public val DATABASE_NAME = "smog.sqlite" public val DATABASE_VERSION = 1 } constructor(context: Context) : super(context, DATABASE_NAME, null, DATABASE_VERSION) override fun onCreate(db: SQLiteDatabase?) { db?.execSQL(SqlCommand.CREATE_TABLE_READINGS) } override fun onUpgrade(db: SQLiteDatabase?, oldVersion: Int, newVersion: Int) { var sync: Boolean = false var currentVersion = oldVersion if (sync) { //SynchronizationService.startFullSynchronization(mContext) } if (currentVersion != newVersion) { throw IllegalStateException("error upgrading the database to version " + newVersion) } } fun deleteDatabase(context: Context) { context.deleteDatabase(DATABASE_NAME) } object SqlCommand { val CREATE_TABLE_READINGS = "CREATE TABLE ${AppContract.Readings.TABLE_NAME} (" + "${AppContract.Readings._ID} INTEGER PRIMARY KEY AUTOINCREMENT, " + "${AppContract.Readings.DATE} VARCHAR NOT NULL, " + "${AppContract.Readings.YEAR} INTEGER NOT NULL, " + "${AppContract.Readings.MONTH} INTEGER NOT NULL, " + "${AppContract.Readings.DAY} INTEGER NOT NULL, " + "${AppContract.Readings.HOUR} INTEGER NOT NULL, " + "${AppContract.Readings.AMOUNT} INTEGER NOT NULL, " + "${AppContract.Readings.PLACE} INTEGER NOT NULL, " + "${AppContract.Readings.COLOR} VARCHAR, " + " UNIQUE (${AppContract.Readings.YEAR}, ${AppContract.Readings.MONTH}, " + "${AppContract.Readings.DAY}, ${AppContract.Readings.HOUR}, ${AppContract.Readings.PLACE}) ON CONFLICT REPLACE" + ")" } }
apache-2.0
0c7ebdac1c1a0a6157d9ab37de905d79
36.166667
125
0.638764
4.582192
false
false
false
false
Magneticraft-Team/Magneticraft
src/main/kotlin/com/cout970/magneticraft/api/internal/registries/machines/heatrecipes/IceboxRecipe.kt
2
1382
package com.cout970.magneticraft.api.internal.registries.machines.heatrecipes import com.cout970.magneticraft.api.registries.machines.heatrecipes.IIceboxRecipe import net.minecraft.item.ItemStack import net.minecraftforge.fluids.FluidStack /** * Created by Yurgen on 16/06/2016. */ data class IceboxRecipe( private val input: ItemStack, private val output: FluidStack, private val heat: Long, private val specificHeat: Double, private val minTemp: Double, private val maxTemp: Double, private val reverse: Boolean ) : IIceboxRecipe { override fun getInput(): ItemStack = input.copy() override fun getOutput(): FluidStack = output.copy() override fun getHeat(): Long = heat override fun getSpecificHeat(): Double = specificHeat override fun getMinTemp(): Double = minTemp override fun getMaxTemp(): Double = maxTemp override fun getReverse(): Boolean = reverse override fun getTotalHeat(temp: Double): Long { if (temp < minTemp) return heat if (temp > maxTemp) return (specificHeat * (maxTemp - minTemp)).toLong() + heat return (specificHeat * (temp - minTemp)).toLong() + heat } override fun matches(input: ItemStack): Boolean = input.isItemEqual(this.input) override fun matchesReverse(output: FluidStack?): Boolean = reverse && (output?.isFluidEqual(this.output) ?: false) }
gpl-2.0
e44bf431a59e06ba3c792cf297d088a3
35.368421
119
0.718524
4.200608
false
false
false
false
Ph1b/MaterialAudiobookPlayer
settings/src/main/kotlin/voice/settings/views/contributeDialog.kt
1
1338
package voice.settings.views import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.material.ListItem import androidx.compose.material3.AlertDialog import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource import voice.settings.R @Composable internal fun ContributeDialog( suggestionsClicked: () -> Unit, translationsClicked: () -> Unit, onDismiss: () -> Unit ) { AlertDialog( onDismissRequest = onDismiss, title = { Text(text = stringResource(R.string.pref_support_title)) }, text = { Column { ListItem( modifier = Modifier .clickable { translationsClicked() } .fillMaxWidth(), text = { Text(text = stringResource(R.string.pref_support_translations)) }, ) ListItem( modifier = Modifier .clickable { suggestionsClicked() } .fillMaxWidth(), text = { Text(text = stringResource(R.string.pref_support_contribute)) }, ) } }, confirmButton = {} ) }
lgpl-3.0
64c1be91ff61a8cb838c520c65392ee7
25.235294
75
0.627055
4.727915
false
false
false
false
anthologist/Simple-Gallery
app/src/main/kotlin/com/simplemobiletools/gallery/dialogs/PickDirectoryDialog.kt
1
4557
package com.simplemobiletools.gallery.dialogs import android.support.v7.app.AlertDialog import android.support.v7.widget.GridLayoutManager import com.simplemobiletools.commons.activities.BaseSimpleActivity import com.simplemobiletools.commons.dialogs.FilePickerDialog import com.simplemobiletools.commons.extensions.beGoneIf import com.simplemobiletools.commons.extensions.beVisibleIf import com.simplemobiletools.commons.extensions.setupDialogStuff import com.simplemobiletools.commons.extensions.toast import com.simplemobiletools.commons.views.MyGridLayoutManager import com.simplemobiletools.gallery.R import com.simplemobiletools.gallery.adapters.DirectoryAdapter import com.simplemobiletools.gallery.asynctasks.GetDirectoriesAsynctask import com.simplemobiletools.gallery.extensions.addTempFolderIfNeeded import com.simplemobiletools.gallery.extensions.config import com.simplemobiletools.gallery.extensions.getCachedDirectories import com.simplemobiletools.gallery.extensions.getSortedDirectories import com.simplemobiletools.gallery.helpers.VIEW_TYPE_GRID import com.simplemobiletools.gallery.models.Directory import kotlinx.android.synthetic.main.dialog_directory_picker.view.* class PickDirectoryDialog(val activity: BaseSimpleActivity, val sourcePath: String, val callback: (path: String) -> Unit) { var dialog: AlertDialog var shownDirectories = ArrayList<Directory>() var view = activity.layoutInflater.inflate(R.layout.dialog_directory_picker, null) var isGridViewType = activity.config.viewTypeFolders == VIEW_TYPE_GRID init { (view.directories_grid.layoutManager as MyGridLayoutManager).apply { orientation = if (activity.config.scrollHorizontally && isGridViewType) GridLayoutManager.HORIZONTAL else GridLayoutManager.VERTICAL spanCount = if (isGridViewType) activity.config.dirColumnCnt else 1 } dialog = AlertDialog.Builder(activity) .setPositiveButton(R.string.ok, null) .setNegativeButton(R.string.cancel, null) .setNeutralButton(R.string.other_folder, { dialogInterface, i -> showOtherFolder() }) .create().apply { activity.setupDialogStuff(view, this, R.string.select_destination) } activity.getCachedDirectories { if (it.isNotEmpty()) { gotDirectories(activity.addTempFolderIfNeeded(it)) } } GetDirectoriesAsynctask(activity, false, false) { gotDirectories(activity.addTempFolderIfNeeded(it)) }.execute() } private fun showOtherFolder() { val showHidden = activity.config.shouldShowHidden FilePickerDialog(activity, sourcePath, false, showHidden, true) { callback(it) } } private fun gotDirectories(newDirs: ArrayList<Directory>) { val dirs = activity.getSortedDirectories(newDirs) if (dirs.hashCode() == shownDirectories.hashCode()) return shownDirectories = dirs val adapter = DirectoryAdapter(activity, dirs, null, view.directories_grid, true) { if ((it as Directory).path.trimEnd('/') == sourcePath) { activity.toast(R.string.source_and_destination_same) return@DirectoryAdapter } else { callback(it.path) dialog.dismiss() } } val scrollHorizontally = activity.config.scrollHorizontally && isGridViewType view.apply { directories_grid.adapter = adapter directories_vertical_fastscroller.isHorizontal = false directories_vertical_fastscroller.beGoneIf(scrollHorizontally) directories_horizontal_fastscroller.isHorizontal = true directories_horizontal_fastscroller.beVisibleIf(scrollHorizontally) if (scrollHorizontally) { directories_horizontal_fastscroller.allowBubbleDisplay = activity.config.showInfoBubble directories_horizontal_fastscroller.setViews(directories_grid) { directories_horizontal_fastscroller.updateBubbleText(dirs[it].getBubbleText()) } } else { directories_vertical_fastscroller.allowBubbleDisplay = activity.config.showInfoBubble directories_vertical_fastscroller.setViews(directories_grid) { directories_vertical_fastscroller.updateBubbleText(dirs[it].getBubbleText()) } } } } }
apache-2.0
a2623908be05dbd0727ac0d581027ab9
44.57
144
0.70485
5.080268
false
true
false
false
youlookwhat/CloudReader
app/src/main/java/com/example/jingbin/cloudreader/ui/wan/child/SquareFragment.kt
1
3724
package com.example.jingbin.cloudreader.ui.wan.child import android.app.Activity import android.content.Context import android.os.Bundle import androidx.lifecycle.Observer import com.example.jingbin.cloudreader.R import com.example.jingbin.cloudreader.adapter.WanAndroidAdapter import com.example.jingbin.cloudreader.app.RxCodeConstants import com.example.jingbin.cloudreader.data.UserUtil import com.example.jingbin.cloudreader.databinding.FragmentSquareBinding import com.example.jingbin.cloudreader.utils.RefreshHelper import com.example.jingbin.cloudreader.viewmodel.wan.WanCenterViewModel import io.reactivex.functions.Consumer import me.jingbin.bymvvm.base.BaseFragment import me.jingbin.bymvvm.rxbus.RxBus import me.jingbin.bymvvm.rxbus.RxBusBaseMessage /** * 广场 */ class SquareFragment : BaseFragment<WanCenterViewModel, FragmentSquareBinding>() { private var isFirst = true private lateinit var activity: Activity private lateinit var mAdapter: WanAndroidAdapter override fun setContent(): Int = R.layout.fragment_square companion object { fun newInstance(): SquareFragment { return SquareFragment() } } override fun onAttach(context: Context) { super.onAttach(context) activity = context as Activity } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) viewModel.mPage = 0 } override fun onResume() { super.onResume() if (isFirst) { showLoading() initRv() getWendaData() initRxBus() isFirst = false } } private fun initRv() { RefreshHelper.initLinear(bindingView.xrvAndroid, true, 1) mAdapter = WanAndroidAdapter(activity) mAdapter.isNoShowChapterName = true mAdapter.isNoImage = false bindingView.xrvAndroid.adapter = mAdapter bindingView.xrvAndroid.setOnRefreshListener { viewModel.mPage = 0 getWendaData() } bindingView.xrvAndroid.setOnLoadMoreListener(true) { ++viewModel.mPage getWendaData() } bindingView.tvPublish.setOnClickListener { if (UserUtil.isLogin(activity)) { PublishActivity.start(activity) } } } private fun getWendaData() { viewModel.getUserArticleList().observe(this, Observer { bindingView.xrvAndroid.isRefreshing = false if (it != null && it.isNotEmpty()) { showContentView() if (viewModel.mPage == 0) { mAdapter.setNewData(it) } else { mAdapter.addData(it) bindingView.xrvAndroid.loadMoreComplete() } } else { if (viewModel.mPage == 0) { if (it != null) { showEmptyView("没找到广场里的内容~") } else { showError() if (viewModel.mPage > 1) viewModel.mPage-- } } else { bindingView.xrvAndroid.loadMoreEnd() } } }) } override fun onRefresh() { getWendaData() } private fun initRxBus() { val subscribe = RxBus.getDefault().toObservable(RxCodeConstants.REFRESH_SQUARE_DATA, RxBusBaseMessage::class.java) .subscribe(Consumer { showLoading() viewModel.mPage = 0 getWendaData() }) addSubscription(subscribe) } }
apache-2.0
805282c625a813bf6571081d121bd16f
30.117647
122
0.602377
5.120332
false
false
false
false
Shashi-Bhushan/General
cp-trials/src/test/kotlin/in/shabhushan/cp_trials/string/HelpTheBooksellerKotlinTest.kt
1
783
package `in`.shabhushan.cp_trials.string class HelpTheBooksellerKotlinTest { // private fun testing(lstOfArt: Array<String>, lstOfCat: Array<String>, expect: String) { // val actual: String = `in`.shabhushan.cp_trials.string.stockSummary(lstOfArt, lstOfCat) // assertEquals(expect, actual) // } // @Test // fun basicTests() { // var b = arrayOf("BBAR 150", "CDXE 515", "BKWR 250", "BTSQ 890", "DRTY 600") // var c = arrayOf("A", "B", "C", "D") // var res = "(A : 0) - (B : 1290) - (C : 515) - (D : 600)" // testing(b, c, res) // // b = arrayOf("ABAR 200", "CDXE 500", "BKWR 250", "BTSQ 890", "DRTY 600") // c = arrayOf("A", "B") // res = "(A : 200) - (B : 1140)" // testing(b, c, res) // // } }
gpl-2.0
b0384def4d9e94d09c8ec207a354b2d3
34.590909
96
0.527458
2.747368
false
true
false
false
MichBogus/PINZ-ws
src/main/kotlin/controller/item/UserItemsController.kt
1
4011
package controller.item import controller.base.BaseController import controller.base.WSResponseEntity import model.base.BaseWebserviceResponse import model.base.WSCode import org.springframework.http.HttpStatus import org.springframework.web.bind.annotation.RequestBody import org.springframework.web.bind.annotation.RequestHeader import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.RestController import service.item.ItemService import service.token.TokenValidationService import utils.WSString import workflow.request.AddItemRequest import workflow.request.CompanyCodeItemsRequest import workflow.request.DeleteItemRequest import workflow.request.ItemTokenRequest import javax.validation.Valid @RestController @RequestMapping(value = "/item") class UserItemsController(val itemService: ItemService, val tokenValidationService: TokenValidationService) : BaseController(), UserItemsControllerMappings { override fun addItem(@Valid @RequestHeader(value = "AUTH_TOKEN") authToken: String, @Valid @RequestBody request: AddItemRequest): WSResponseEntity { if (tokenValidationService.validateAndUpdate(authToken).not()) return authTokenInvalid() var response = request.checkIfRequestIsValid() if (response.isOk()) { response = itemService.addItem(authToken, request) return generateResponseEntity(response, response.status) } return generateResponseEntity(response, response.status) } override fun deleteItem(@Valid @RequestHeader(value = "AUTH_TOKEN") authToken: String, @Valid @RequestBody request: DeleteItemRequest): WSResponseEntity { if (tokenValidationService.validateAndUpdate(authToken).not()) return authTokenInvalid() var response = request.checkIfRequestIsValid() if (response.isOk()) { response = itemService.deleteItem(authToken, request.itemToken) return generateResponseEntity(response, response.status) } return generateResponseEntity(response, response.status) } override fun getCompanyItems(@Valid @RequestHeader(value = "AUTH_TOKEN") authToken: String, @Valid @RequestBody request: CompanyCodeItemsRequest): WSResponseEntity { if (tokenValidationService.validateAndUpdate(authToken).not()) return authTokenInvalid() var response = request.checkIfRequestIsValid() if (response.isOk()) { response = itemService.getCompanyItems(authToken, request.companyCode) return generateResponseEntity(response, response.status) } return generateResponseEntity(response, response.status) } override fun getItemByToken(@Valid @RequestHeader(value = "AUTH_TOKEN") authToken: String, @Valid @RequestBody request: ItemTokenRequest): WSResponseEntity { if (tokenValidationService.validateAndUpdate(authToken).not()) return authTokenInvalid() var response = request.checkIfRequestIsValid() if (response.isOk()) { response = itemService.getCompanyItemByToken(authToken, request.itemToken) return generateResponseEntity(response, response.status) } return generateResponseEntity(response, response.status) } override fun getUserItems(@Valid @RequestHeader(value = "AUTH_TOKEN") authToken: String): WSResponseEntity { val response = itemService.getUserItems(authToken) return generateResponseEntity(response, response.status) } private fun authTokenInvalid(): WSResponseEntity = generateResponseEntity(BaseWebserviceResponse(HttpStatus.FORBIDDEN, WSCode.AUTH_TOKEN_INVALID, WSCode.AUTH_TOKEN_INVALID.code, WSString.AUTH_TOKEN_INVALID.tag), HttpStatus.FORBIDDEN) }
apache-2.0
eccdf1d57ec7e5865a1e4000657ae22e
40.791667
127
0.713039
5.26378
false
false
false
false
ScienceYuan/WidgetNote
app/src/main/java/com/rousci/androidapp/widgetnote/viewPresenter/mainActivity/NoteRecycleAdapter.kt
1
1587
package com.rousci.androidapp.widgetnote.viewPresenter.mainActivity import android.content.Context import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageButton import android.widget.TextView import com.rousci.androidapp.widgetnote.R import com.rousci.androidapp.widgetnote.model.Note import com.rousci.androidapp.widgetnote.viewPresenter.noteId import com.rousci.androidapp.widgetnote.viewPresenter.editNote.EditNote import org.jetbrains.anko.find import org.jetbrains.anko.sdk25.coroutines.onClick import org.jetbrains.anko.startActivity /** * Created by rousci on 17-10-11. * customize a adapter */ class NoteRecycleAdapter(val data:List<Note>, val appContext: Context): RecyclerView.Adapter<NoteRecycleAdapter.StrViewHolder>() { override fun getItemCount(): Int = data.size override fun onBindViewHolder(holder: StrViewHolder, position: Int) { holder.textView.text = data[position].content holder.button.onClick { appContext.startActivity<EditNote>(noteId to data[position].id) } } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): StrViewHolder { val view:View = LayoutInflater.from(appContext).inflate(R.layout.note_item, parent, false) return StrViewHolder(view) } class StrViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { val textView = itemView.find<TextView>(R.id.textView1) val button = itemView.find<ImageButton>(R.id.button1) } }
mit
b11260fa8409c1a26990a191b57e2eed
37.731707
130
0.770006
3.987437
false
false
false
false
Shashi-Bhushan/General
cp-trials/src/main/kotlin/in/shabhushan/cp_trials/contest/weekly181/validPath.kt
1
2135
package `in`.shabhushan.cp_trials.contest.weekly181 /** * Kotlin solution for https://leetcode.com/contest/weekly-contest-181/ */ enum class Directions(val direction: Pair<Int, Int>) { DOWN(1 to 0), UP(-1 to 0), RIGHT(0 to 1), LEFT(0 to -1) } typealias CURRENT_DIRECTION = Int typealias NEW_DIRECTION = Directions typealias VALIDSTREETS = Int private val validStreet: Map<CURRENT_DIRECTION, Map<NEW_DIRECTION, List<VALIDSTREETS>>> = mapOf( 1 to mapOf( Directions.RIGHT to listOf(1, 3, 5), Directions.LEFT to listOf(1, 4, 6) ), 2 to mapOf( Directions.DOWN to listOf(2, 5, 6), Directions.UP to listOf(2, 3, 4) ), 3 to mapOf( Directions.DOWN to listOf(5, 6, 2), Directions.LEFT to listOf(1, 4, 6) ), 4 to mapOf( Directions.RIGHT to listOf(1, 3, 5), Directions.DOWN to listOf(2, 5, 6) ), 5 to mapOf( Directions.UP to listOf(2, 3, 4), Directions.LEFT to listOf(1, 4, 6) ), 6 to mapOf( Directions.UP to listOf(2, 3, 4), Directions.RIGHT to listOf(1, 3, 5) ) ) fun hasValidPath( grid: Array<IntArray>, prevRow: Int = -1, prevColumn: Int = -1, currentRow: Int = 0, currentColumn: Int = 0 ): Boolean { if (currentRow == grid.size - 1 && currentColumn == grid[0].size - 1) return true else { // search in all directions Directions.values().forEach { d -> val newRow = currentRow + d.direction.first val newColumn = currentColumn + d.direction.second if (newRow in grid.indices && newColumn in grid[0].indices && !(newRow == prevRow && newColumn == prevColumn) ) { val element = grid[currentRow][currentColumn] val nextElement = grid[newRow][newColumn] validStreet[element]?.let { // get current direction's valid streets from map it[d]?.let { validStreets -> if (nextElement in validStreets) { return hasValidPath( grid, currentRow, currentColumn, newRow, newColumn ) } } } } } return false } }
gpl-2.0
3c1ddf6a7bc36437c8a3e948f7dbacdd
25.358025
96
0.594848
3.546512
false
false
false
false
Deletescape-Media/Lawnchair
lawnchair/src/app/lawnchair/util/FlowUtils.kt
1
1268
package app.lawnchair.util import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.content.IntentFilter import androidx.compose.runtime.Composable import androidx.compose.runtime.collectAsState import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.channels.awaitClose import kotlinx.coroutines.flow.* import kotlinx.coroutines.runBlocking fun <T> Flow<T>.firstBlocking() = runBlocking { first() } @Composable fun <T> Flow<T>.collectAsStateBlocking() = collectAsState(initial = firstBlocking()) fun broadcastReceiverFlow(context: Context, filter: IntentFilter) = callbackFlow<Intent> { val receiver = object : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { trySend(intent) } } context.registerReceiver(receiver, filter) awaitClose { context.unregisterReceiver(receiver) } } fun <T> Flow<T>.dropWhileBusy(): Flow<T> = channelFlow { collect { trySend(it) } }.buffer(0) fun <T> Flow<T>.subscribeBlocking( scope: CoroutineScope, block: (T) -> Unit, ) { block(firstBlocking()) this .onEach { block(it) } .drop(1) .distinctUntilChanged() .launchIn(scope = scope) }
gpl-3.0
90dcb53604438069e8f22886beb4884e
28.488372
90
0.723975
4.171053
false
false
false
false
droibit/chopsticks
sample/src/main/java/com/github/droibit/chopstick/sample/view/BindViewFragmentActivity.kt
1
2191
package com.github.droibit.chopstick.sample.view import android.content.Context import android.content.Intent import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Button import android.widget.TextView import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import com.github.droibit.chopstick.sample.R import com.github.droibit.chopstick.view.Binder import com.github.droibit.chopstick.view.SupportFragmentViewBinder class BindViewFragmentActivity : AppCompatActivity() { companion object { @JvmStatic fun makeIntent(context: Context) = Intent(context, BindViewFragmentActivity::class.java) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_fragment_bind_view) if (savedInstanceState == null) { supportFragmentManager.beginTransaction() .replace(R.id.content, BindViewFragment()) .commit() } } } class BindViewFragment : androidx.fragment.app.Fragment(), Binder<androidx.fragment.app.Fragment> by SupportFragmentViewBinder() { private val textView: TextView by bindView(android.R.id.text1) private val button: Button by bindView(android.R.id.button1) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) retainInstance = true } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { return inflater.inflate(R.layout.fragment_bind_view, container, false) } override fun onViewCreated( view: View, savedInstanceState: Bundle? ) { super.onViewCreated(view, savedInstanceState) textView.text = getString(R.string.bind_fragment_text) button.setOnClickListener { Toast.makeText(context, "Hello, bindView", Toast.LENGTH_SHORT) .show() } } override fun onDestroyView() { unbindViews() super.onDestroyView() } }
apache-2.0
2d626db5f4e75cde776d8b2db485f112
28.608108
96
0.700137
4.661702
false
false
false
false
yshrsmz/monotweety
app/src/main/java/net/yslibrary/monotweety/status/adapter/PreviousStatusAdapterDelegate.kt
1
2461
package net.yslibrary.monotweety.status.adapter import android.view.View import android.view.ViewGroup import android.widget.TextView import androidx.recyclerview.widget.RecyclerView import com.hannesdorfmann.adapterdelegates4.AdapterDelegate import net.yslibrary.monotweety.R import net.yslibrary.monotweety.base.findById import net.yslibrary.monotweety.base.inflate import org.threeten.bp.ZoneId import org.threeten.bp.ZonedDateTime import org.threeten.bp.format.DateTimeFormatter import java.util.* class PreviousStatusAdapterDelegate : AdapterDelegate<List<ComposeStatusAdapter.Item>>() { private val createdAtRawFormatter = DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss Z yyyy", Locale.ENGLISH) private val createdAtFormatter = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss") override fun onBindViewHolder( items: List<ComposeStatusAdapter.Item>, position: Int, holder: RecyclerView.ViewHolder, payloads: MutableList<Any> ) { if (holder is ViewHolder) { val item = items[position] as Item holder.status.text = item.status holder.timestamp.text = getFormattedCreatedAt(item.createdAt) } } override fun onCreateViewHolder(parent: ViewGroup): RecyclerView.ViewHolder { return ViewHolder.create(parent) } override fun isForViewType(items: List<ComposeStatusAdapter.Item>, position: Int): Boolean { return items[position].viewType == ComposeStatusAdapter.ViewType.PREVIOUS_STATUS } fun getFormattedCreatedAt(rawDate: String): String { val createdAtDate = ZonedDateTime.parse(rawDate, createdAtRawFormatter) .withZoneSameInstant(ZoneId.systemDefault()) return createdAtDate.format(createdAtFormatter) } data class Item( val id: Long, val status: String, val createdAt: String, override val viewType: ComposeStatusAdapter.ViewType = ComposeStatusAdapter.ViewType.PREVIOUS_STATUS ) : ComposeStatusAdapter.Item class ViewHolder(view: View) : RecyclerView.ViewHolder(view) { val status = view.findById<TextView>(R.id.status) val timestamp = view.findById<TextView>(R.id.timestamp) companion object { fun create(parent: ViewGroup): ViewHolder { val view = parent.inflate(R.layout.vh_previous_status) return ViewHolder(view) } } } }
apache-2.0
f69d2fef11d0f67f6b7d09b08d44cc69
34.157143
108
0.711499
4.750965
false
false
false
false
xfournet/intellij-community
platform/testGuiFramework/src/com/intellij/testGuiFramework/fixtures/extended/ExtendedTableFixture.kt
1
2273
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.testGuiFramework.fixtures.extended import com.intellij.testGuiFramework.cellReader.ExtendedJTableCellReader import org.fest.swing.core.Robot import org.fest.swing.fixture.JTableFixture import javax.swing.JCheckBox import javax.swing.JTable class ExtendedTableFixture(val myRobot: Robot, val myTable: JTable) : JTableFixture(myRobot, myTable) { init { replaceCellReader(ExtendedJTableCellReader()) } fun row(i: Int): RowFixture = RowFixture(i, this) fun row(value: String): RowFixture = RowFixture(cell(value).row(), this) } class RowFixture(val rowNumber: Int, val tableFixture: ExtendedTableFixture) { val myTable = tableFixture.myTable fun hasCheck(): Boolean = (0 until myTable.columnCount) .map { myTable.prepareRenderer(myTable.getCellRenderer(rowNumber, it), rowNumber, it) } .any { it is JCheckBox } fun isCheck(): Boolean { val checkBox = getCheckBox() return checkBox.isSelected } fun check() { val checkBox = getCheckBox() return checkBox.model.setSelected(true) } fun uncheck() { val checkBox = getCheckBox() return checkBox.model.setSelected(false) } fun values(): List<String> { val cellReader = ExtendedJTableCellReader() return (0 until myTable.columnCount) .map { cellReader.valueAt(myTable, rowNumber, it) ?: "null" } } private fun getCheckBox(): JCheckBox { if (!hasCheck()) throw Exception("Unable to find checkbox cell in row: $rowNumber") return (0 until myTable.columnCount) .map { myTable.prepareRenderer(myTable.getCellRenderer(rowNumber, it), rowNumber, it) } .find { it is JCheckBox } as JCheckBox } }
apache-2.0
43b88e5c325e80f7b49857cffac4ffc8
30.583333
103
0.726793
3.987719
false
false
false
false
charlesmadere/smash-ranks-android
smash-ranks-android/app/src/main/java/com/garpr/android/data/models/HeadToHeadMatch.kt
1
1497
package com.garpr.android.data.models import android.os.Parcel import android.os.Parcelable import com.garpr.android.extensions.createParcel import com.garpr.android.extensions.requireAbsPlayer import com.garpr.android.extensions.requireParcelable import com.garpr.android.extensions.writeAbsPlayer import com.squareup.moshi.Json import com.squareup.moshi.JsonClass import java.util.Objects @JsonClass(generateAdapter = true) class HeadToHeadMatch( @Json(name = "player") val player: AbsPlayer, @Json(name = "opponent") val opponent: AbsPlayer, @Json(name = "result") val result: MatchResult ) : Parcelable { override fun equals(other: Any?): Boolean { return if (other is HeadToHeadMatch) { player == other.player && opponent == other.opponent && result == other.result } else { false } } override fun hashCode(): Int = Objects.hash(player, opponent, result) override fun describeContents(): Int = 0 override fun writeToParcel(dest: Parcel, flags: Int) { dest.writeAbsPlayer(player, flags) dest.writeAbsPlayer(opponent, flags) dest.writeParcelable(result, flags) } companion object { @JvmField val CREATOR = createParcel { HeadToHeadMatch( it.requireAbsPlayer(), it.requireAbsPlayer(), it.requireParcelable(MatchResult::class.java.classLoader) ) } } }
unlicense
137ca57fc766a4ca7aee90d63bbffab0
29.55102
90
0.659319
4.402941
false
false
false
false
pyamsoft/zaptorch
service/src/main/java/com/pyamsoft/zaptorch/service/notification/TorchNotificationDispatcher.kt
1
4126
/* * Copyright 2020 Peter Kenji Yamanaka * * 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.pyamsoft.zaptorch.service.notification import android.app.Notification import android.app.NotificationChannel import android.app.NotificationChannelGroup import android.app.NotificationManager import android.app.PendingIntent import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.os.Build import androidx.annotation.ColorRes import androidx.core.app.NotificationCompat import androidx.core.content.ContextCompat import androidx.core.content.getSystemService import com.pyamsoft.pydroid.core.requireNotNull import com.pyamsoft.pydroid.notify.NotifyChannelInfo import com.pyamsoft.pydroid.notify.NotifyData import com.pyamsoft.pydroid.notify.NotifyDispatcher import com.pyamsoft.pydroid.notify.NotifyId import com.pyamsoft.zaptorch.service.R import timber.log.Timber import javax.inject.Inject import javax.inject.Named import javax.inject.Singleton @Singleton internal class TorchNotificationDispatcher @Inject internal constructor( private val context: Context, receiverClass: Class<out BroadcastReceiver>, @Named("notification_color") @ColorRes notificationColor: Int, ) : NotifyDispatcher<TorchNotification> { private val color = ContextCompat.getColor(context, notificationColor) private val notificationManager by lazy { context.applicationContext.getSystemService<NotificationManager>().requireNotNull() } private val pendingIntent by lazy { PendingIntent.getBroadcast( context, RC, Intent(context, receiverClass), PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE, ) } private fun setupNotificationChannel(channelInfo: NotifyChannelInfo) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) { Timber.d("No channel below Android O") return } val channel: NotificationChannel? = notificationManager.getNotificationChannel(channelInfo.id) if (channel != null) { Timber.d("Channel already exists: ${channel.id}") return } val notificationGroup = NotificationChannelGroup(channelInfo.id, channelInfo.title) val importance = NotificationManager.IMPORTANCE_DEFAULT val notificationChannel = NotificationChannel(channelInfo.id, channelInfo.title, importance).apply { lockscreenVisibility = Notification.VISIBILITY_PUBLIC description = channelInfo.description enableLights(false) enableVibration(false) } Timber.d( "Create notification channel and group ${notificationChannel.id} ${notificationGroup.id}") notificationManager.apply { createNotificationChannelGroup(notificationGroup) createNotificationChannel(notificationChannel) } } override fun build( id: NotifyId, channelInfo: NotifyChannelInfo, notification: TorchNotification ): Notification { setupNotificationChannel(channelInfo) return NotificationCompat.Builder(context, channelInfo.id) .setContentIntent(pendingIntent) .setContentTitle("Torch is On") .setContentText("Click to turn off") .setSmallIcon(R.drawable.ic_light_notification) .setAutoCancel(true) .setWhen(0) .setOngoing(false) .setColor(color) .setPriority(NotificationCompat.PRIORITY_DEFAULT) .build() } override fun canShow(notification: NotifyData): Boolean { return notification is TorchNotification } companion object { private const val RC = 1009 } }
apache-2.0
da9a208d03a317de6f47d9e76eaccaf3
32.819672
98
0.753514
4.764434
false
false
false
false
camdenorrb/KPortals
src/main/kotlin/me/camdenorrb/kportals/commands/PortalCmd.kt
1
1589
package me.camdenorrb.kportals.commands import me.camdenorrb.kportals.KPortals import me.camdenorrb.kportals.messages.Messages import org.bukkit.ChatColor.AQUA import org.bukkit.ChatColor.RED import org.bukkit.command.Command import org.bukkit.command.CommandSender import org.bukkit.command.TabExecutor /** * Created by camdenorrb on 3/20/17. */ class PortalCmd(val plugin: KPortals) : TabExecutor { override fun onTabComplete(sender: CommandSender, command: Command, alias: String, args: Array<out String>): List<String> { if (args.size != 1) { return emptyList() } val arg = args[0] return plugin.subCmds.map { it.arg }.filter { it.startsWith(arg, true) } } override fun onCommand(sender: CommandSender, cmd: Command, label: String, args: Array<out String>): Boolean { if (args.isEmpty()) { sender.sendMessage(*Messages.help) return true } val arguments = args.toMutableList() val subCmdArg = arguments.removeAt(0) val subCmd = plugin.subCmds.find { it.arg.equals(subCmdArg, true) } ?: run { sender.sendMessage(*Messages.help) return true } if (sender.hasPermission(subCmd.permission).not()) { sender.sendMessage("${RED}You don't have the necessary permission node $AQUA\"${subCmd.permission}\"!") } if (subCmd.execute(sender, plugin, arguments).not()) { sender.sendMessage("$RED${subCmd.usage}") } return true } // How this should be, auto registers as it looks for nested classes/objects /* @SubCmd object SelectCmd : Cmd("-select", "kportals.select") { fun execute() = Unit } */ }
mit
6df0e17c61b2837156506ca77ad078ed
22.382353
124
0.704216
3.431965
false
false
false
false
geckour/Egret
app/src/main/java/com/geckour/egret/view/fragment/NewTootCreateFragment.kt
1
29213
package com.geckour.egret.view.fragment import android.Manifest import android.app.Activity import android.content.ClipData import android.content.ContentValues import android.content.DialogInterface import android.content.Intent import android.content.pm.PackageManager import android.databinding.DataBindingUtil import android.net.Uri import android.os.Bundle import android.provider.DocumentsContract import android.provider.MediaStore import android.support.design.widget.Snackbar import android.support.v4.app.ActivityCompat import android.support.v4.content.ContextCompat import android.support.v7.app.AlertDialog import android.text.Editable import android.view.KeyEvent import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ArrayAdapter import android.widget.EditText import com.bumptech.glide.Glide import com.geckour.egret.R import com.geckour.egret.api.MastodonClient import com.geckour.egret.api.model.Attachment import com.geckour.egret.api.service.MastodonService import com.geckour.egret.databinding.FragmentCreateNewTootBinding import com.geckour.egret.model.Draft import com.geckour.egret.util.Common import com.geckour.egret.util.OrmaProvider import com.geckour.egret.view.activity.MainActivity import com.geckour.egret.view.activity.ShareActivity import io.reactivex.Observable import io.reactivex.Single import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.disposables.Disposable import io.reactivex.schedulers.Schedulers import okhttp3.MediaType import okhttp3.MultipartBody import okhttp3.RequestBody import java.io.File class NewTootCreateFragment : BaseFragment(), MainActivity.OnBackPressedListener, SelectDraftDialogFragment.OnSelectDraftItemListener { lateinit private var binding: FragmentCreateNewTootBinding private val postMediaReqs: ArrayList<Disposable> = ArrayList() private val attachments: ArrayList<Attachment> = ArrayList() private var capturedImageUri: Uri? = null lateinit private var initialBody: String lateinit private var initialAlertBody: String private var isSuccessPost = false private val drafts: ArrayList<Draft> = ArrayList() private var draft: Draft? = null companion object { val TAG: String = this::class.java.simpleName private val ARGS_KEY_CURRENT_TOKEN_ID = "currentTokenId" private val ARGS_KEY_POST_TOKEN_ID = "postTokenId" private val ARGS_KEY_REPLY_TO_STATUS_ID = "replyToStatusId" private val ARGS_KEY_REPLY_TO_ACCOUNT_NAME = "replyToAccountName" private val ARGS_KEY_BODY = "argsKeyBody" private val REQUEST_CODE_PICK_MEDIA = 1 private val REQUEST_CODE_CAPTURE_IMAGE = 2 private val REQUEST_CODE_GRANT_READ_STORAGE = 3 private val REQUEST_CODE_GRANT_WRITE_STORAGE = 4 fun newInstance( currentTokenId: Long, postTokenId: Long = currentTokenId, replyToStatusId: Long? = null, replyToAccountName: String? = null, body: String? = null) = NewTootCreateFragment().apply { arguments = Bundle().apply { putLong(ARGS_KEY_CURRENT_TOKEN_ID, currentTokenId) putLong(ARGS_KEY_POST_TOKEN_ID, postTokenId) if (replyToStatusId != null) putLong(ARGS_KEY_REPLY_TO_STATUS_ID, replyToStatusId) if (replyToAccountName != null) putString(ARGS_KEY_REPLY_TO_ACCOUNT_NAME, replyToAccountName) if (body != null) putString(ARGS_KEY_BODY, body) } } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) (activity as? MainActivity)?.supportActionBar?.hide() (activity as? MainActivity)?.binding?.appBarMain?.contentMain?.fab?.hide() } override fun onResume() { super.onResume() (activity as? MainActivity)?.supportActionBar?.hide() (activity as? MainActivity)?.binding?.appBarMain?.contentMain?.fab?.hide() } override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? { binding = DataBindingUtil.inflate(inflater, R.layout.fragment_create_new_toot, container, false) return binding.root } override fun onViewCreated(view: View?, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val token = OrmaProvider.db.selectFromAccessToken().idEq(arguments.getLong(ARGS_KEY_POST_TOKEN_ID)).last() val domain = OrmaProvider.db.selectFromInstanceAuthInfo().idEq(token.instanceId).last().instance OrmaProvider.db.updateAccessToken().isCurrentEq(true).isCurrent(false).executeAsSingle() .flatMap { OrmaProvider.db.updateAccessToken().idEq(token.id).isCurrent(true).executeAsSingle() } .flatMap { MastodonClient(Common.resetAuthInfo() ?: throw IllegalArgumentException()).getOwnAccount() } .subscribeOn(Schedulers.newThread()) .observeOn(AndroidSchedulers.mainThread()) .compose(bindToLifecycle()) .subscribe( { account -> val content = Common.getNewTootIdentifyContent(domain, token, account) binding.content = content Glide.with(binding.icon.context).load(content.avatarUrl).into(binding.icon) }, Throwable::printStackTrace) Common.showSoftKeyBoardOnFocusEditText(binding.tootBody) binding.gallery.setOnClickListener { pickMedia() } binding.camera.setOnClickListener { captureImage() } if (arguments.containsKey(ARGS_KEY_BODY)) binding.tootBody.text = Editable.Factory.getInstance().newEditable(arguments.getString(ARGS_KEY_BODY)) if (arguments.containsKey(ARGS_KEY_REPLY_TO_STATUS_ID) && arguments.containsKey(ARGS_KEY_REPLY_TO_ACCOUNT_NAME) && arguments.getString(ARGS_KEY_REPLY_TO_ACCOUNT_NAME) != null) { binding.replyTo.text = "reply to: ${arguments.getString(ARGS_KEY_REPLY_TO_ACCOUNT_NAME)}" binding.replyTo.visibility = View.VISIBLE val accountName = "${arguments.getString(ARGS_KEY_REPLY_TO_ACCOUNT_NAME)} " binding.tootBody.text = Editable.Factory.getInstance().newEditable(accountName) binding.tootBody.setSelection(accountName.length) } binding.tootBody.setOnKeyListener { v, keyCode, event -> when (event.action) { KeyEvent.ACTION_DOWN -> { when (keyCode) { KeyEvent.KEYCODE_DPAD_LEFT -> { (v as EditText).let { if (it.selectionStart == 0 && it.selectionStart == it.selectionEnd) { it.requestFocusFromTouch() it.requestFocus() it.setSelection(0) true } else false } } KeyEvent.KEYCODE_DPAD_RIGHT -> { (v as EditText).let { if (it.selectionEnd == it.text.length && it.selectionStart == it.selectionEnd) { it.requestFocusFromTouch() it.requestFocus() it.setSelection(it.text.length) true } else false } } else -> false } } else -> false } } binding.switchCw.setOnCheckedChangeListener { _, isChecked -> binding.tootAlertBody.visibility = if (isChecked) View.VISIBLE else View.GONE binding.dividerBody.visibility = if (isChecked) View.VISIBLE else View.GONE } binding.spinnerVisibility.adapter = ArrayAdapter.createFromResource(activity, R.array.spinner_toot_visibility, android.R.layout.simple_spinner_item) .apply { setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item) } binding.buttonToot.setOnClickListener { binding.buttonToot.isEnabled = false postToot(binding.tootBody.text.toString()) } initialBody = binding.tootBody.text.toString() initialAlertBody = binding.tootAlertBody.text.toString() Common.getCurrentAccessToken()?.id?.let { drafts.addAll( OrmaProvider.db.relationOfDraft() .tokenIdEq(it) .orderByCreatedAtAsc() ) } binding.draft.apply { if (drafts.isNotEmpty()) { visibility = View.VISIBLE setOnClickListener { onLoadDraft() } } else { visibility = View.INVISIBLE setOnClickListener(null) } } } override fun onPause() { super.onPause() postMediaReqs.forEach { it.dispose() } } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) when (requestCode) { REQUEST_CODE_PICK_MEDIA -> { if (resultCode == Activity.RESULT_OK) { data?.let { postMedia(it) } } } REQUEST_CODE_CAPTURE_IMAGE -> { if (resultCode == Activity.RESULT_OK) { capturedImageUri?.let { postImage(it) } } } } } override fun onBackPressedInMainActivity(callback: (Boolean) -> Any) { if (isSuccessPost.not() && (initialBody != binding.tootBody.text.toString() || initialAlertBody != binding.tootAlertBody.text.toString())) { AlertDialog.Builder(activity) .setTitle(R.string.dialog_title_confirm_save) .setMessage(R.string.dialog_message_confirm_save) .setPositiveButton(R.string.dialog_button_ok_confirm_save, { dialog, _ -> saveAsDraft(dialog, callback) }) .setNegativeButton(R.string.dialog_button_dismiss_confirm_save, { dialog, _ -> dialog.dismiss() callback(true) }) .setNeutralButton(R.string.dialog_button_cancel_confirm_save, { dialog, _ -> dialog.dismiss() callback(false) }) .show() } else callback(true) } override fun onSelect(draft: Draft) { this.draft = draft OrmaProvider.db.relationOfDraft() .deleter() .idEq(draft.id) .executeAsSingle() .map { Common.getCurrentAccessToken()?.id?.let { OrmaProvider.db.relationOfDraft() .tokenIdEq(it) .orderByCreatedAtAsc() .toList() } ?: arrayListOf() } .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe({ drafts -> this.drafts.apply { clear() addAll(drafts) } if (this.drafts.isEmpty()) binding.draft.apply { visibility = View.INVISIBLE setOnClickListener(null) } var account = "" if (draft.inReplyToId != null && draft.inReplyToName != null) { binding.replyTo.text = "reply to: ${draft.inReplyToName}" binding.replyTo.visibility = View.VISIBLE account = "${draft.inReplyToName} " } val body = "$account${draft.body}" binding.tootBody.setText(body) binding.tootBody.setSelection(body.length) binding.tootAlertBody.setText(draft.alertBody) this.attachments.apply { clear() addAll(draft.attachments.value) } Observable.fromIterable(this.attachments.mapIndexed { i, attachment -> Pair(i, attachment)}) .subscribeOn(Schedulers.newThread()) .observeOn(AndroidSchedulers.mainThread()) .subscribe({ (i, attachment) -> Glide.with(activity).load(attachment.previewImgUrl).into( when (i) { 0 -> binding.media1 1 -> binding.media2 2 -> binding.media3 3 -> binding.media4 else -> throw IndexOutOfBoundsException("There are attachments over 4.") } ) }, Throwable::printStackTrace) binding.switchCw.isChecked = draft.warning binding.switchNsfw.isChecked = draft.sensitive binding.spinnerVisibility.setSelection(draft.visibility) }, Throwable::printStackTrace) } private fun postToot(body: String) { if (body.isBlank()) { Snackbar.make(binding.root, R.string.error_empty_toot, Snackbar.LENGTH_SHORT) return } MastodonClient(Common.resetAuthInfo() ?: return) .postNewToot( body = body, inReplyToId = if (binding.replyTo.visibility == View.VISIBLE) draft?.inReplyToId ?: arguments.getLong(ARGS_KEY_REPLY_TO_STATUS_ID) else null, mediaIds = if (attachments.size > 0) attachments.map { it.id } else null, isSensitive = binding.switchNsfw.isChecked, spoilerText = if (binding.switchCw.isChecked) binding.tootAlertBody.text.toString() else null, visibility = when (binding.spinnerVisibility.selectedItemPosition) { 0 -> MastodonService.Visibility.public 1 -> MastodonService.Visibility.unlisted 2 -> MastodonService.Visibility.private 3 -> MastodonService.Visibility.direct else -> null }) .subscribeOn(Schedulers.newThread()) .observeOn(AndroidSchedulers.mainThread()) .subscribe( { onPostSuccess() }, Throwable::printStackTrace) } private fun saveAsDraft(dialog: DialogInterface, callback: (Boolean) -> Any, draftId: Long? = null) { Common.getCurrentAccessToken()?.let { (id) -> if (draftId == null) { OrmaProvider.db.relationOfDraft() .insertAsSingle { Draft( tokenId = id, body = binding.tootBody.text.toString(), alertBody = binding.tootAlertBody.text.toString(), inReplyToId = if (binding.replyTo.visibility == View.VISIBLE) draft?.inReplyToId ?: arguments.getLong(ARGS_KEY_REPLY_TO_STATUS_ID) else null, inReplyToName = if (binding.replyTo.visibility == View.VISIBLE) draft?.inReplyToName ?: arguments.getString(ARGS_KEY_REPLY_TO_ACCOUNT_NAME) else null, attachments = Draft.Attachments(attachments), warning = binding.switchCw.isChecked, sensitive = binding.switchNsfw.isChecked, visibility = binding.spinnerVisibility.selectedItemPosition ) } .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe({ Snackbar.make(binding.root, R.string.complete_save_draft, Snackbar.LENGTH_SHORT).show() dialog.dismiss() callback(true) }, { throwable -> throwable.printStackTrace() Snackbar.make(binding.root, R.string.failure_save_draft, Snackbar.LENGTH_SHORT).show() dialog.dismiss() callback(false) }) } else { OrmaProvider.db.relationOfDraft() .upsertAsSingle( Draft( id = draftId, tokenId = id, body = binding.tootBody.text.toString(), alertBody = binding.tootAlertBody.text.toString(), inReplyToId = if (binding.replyTo.visibility == View.VISIBLE) arguments.getLong(ARGS_KEY_REPLY_TO_STATUS_ID) else null, attachments = Draft.Attachments(attachments), sensitive = binding.switchNsfw.isChecked, visibility = when (binding.spinnerVisibility.selectedItemPosition) { 0 -> MastodonService.Visibility.public.ordinal 1 -> MastodonService.Visibility.unlisted.ordinal 2 -> MastodonService.Visibility.private.ordinal 3 -> MastodonService.Visibility.direct.ordinal else -> -1 } ) ) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe({ Snackbar.make(binding.root, R.string.complete_save_draft, Snackbar.LENGTH_SHORT).show() dialog.dismiss() callback(true) }, { throwable -> throwable.printStackTrace() Snackbar.make(binding.root, R.string.failure_save_draft, Snackbar.LENGTH_SHORT).show() dialog.dismiss() callback(false) }) } } } private fun onLoadDraft() { SelectDraftDialogFragment.newInstance(drafts) .apply { setTargetFragment(this@NewTootCreateFragment, 0) } .show(activity.supportFragmentManager, SelectDraftDialogFragment.TAG) } private fun pickMedia() { if (ContextCompat.checkSelfPermission(activity, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(activity, arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE), REQUEST_CODE_GRANT_READ_STORAGE) } else { val intent = Intent(Intent.ACTION_GET_CONTENT).apply { type = "image/* video/*" putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true) } startActivityForResult(intent, REQUEST_CODE_PICK_MEDIA) } } private fun captureImage() { if (ContextCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(activity, arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE), REQUEST_CODE_GRANT_WRITE_STORAGE) } else { val values = ContentValues() values.put(MediaStore.Images.Media.TITLE, "${System.currentTimeMillis()}.jpg") capturedImageUri = activity.contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values) val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE).apply { putExtra(MediaStore.EXTRA_OUTPUT, capturedImageUri) } startActivityForResult(intent, REQUEST_CODE_CAPTURE_IMAGE) } } override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) { super.onRequestPermissionsResult(requestCode, permissions, grantResults) when (requestCode) { REQUEST_CODE_GRANT_READ_STORAGE -> { if (grantResults.isNotEmpty() && grantResults.none { it != PackageManager.PERMISSION_GRANTED }) { pickMedia() } else { Snackbar.make(binding.root, R.string.message_necessity_read_storage_grant, Snackbar.LENGTH_SHORT).show() } } REQUEST_CODE_GRANT_WRITE_STORAGE -> { if (grantResults.isNotEmpty() && grantResults.none { it != PackageManager.PERMISSION_GRANTED }) { captureImage() } else { Snackbar.make(binding.root, R.string.message_necessity_write_storage_grant_capture, Snackbar.LENGTH_SHORT).show() } } } } private fun postMedia(data: Intent) { if (attachments.size < 4) { Common.resetAuthInfo()?.let { domain -> if (data.clipData != null) { getMediaPathsFromClipDataAsObservable(data.clipData) .flatMap { (path, uri) -> queryPostImageToAPI(domain, path, uri).toObservable() } .subscribeOn(Schedulers.newThread()) .observeOn(AndroidSchedulers.mainThread()) .compose(bindToLifecycle()) .subscribe({ attachments.add(it) indicateImage(it.previewImgUrl) }, { throwable -> throwable.printStackTrace() Snackbar.make(binding.root, R.string.error_unable_upload_media, Snackbar.LENGTH_SHORT).show() }) } if (data.data != null) { getMediaPathFromUriAsSingle(data.data) .flatMap { (path, uri) -> queryPostImageToAPI(domain, path, uri) } .subscribeOn(Schedulers.newThread()) .observeOn(AndroidSchedulers.mainThread()) .compose(bindToLifecycle()) .subscribe({ attachments.add(it) indicateImage(it.previewImgUrl) }, { throwable -> throwable.printStackTrace() Snackbar.make(binding.root, R.string.error_unable_upload_media, Snackbar.LENGTH_SHORT).show() }) } } } else Snackbar.make(binding.root, R.string.error_too_many_media, Snackbar.LENGTH_SHORT).show() } private fun postImage(uri: Uri) { if (attachments.size < 4) { Common.resetAuthInfo()?.let { domain -> getImagePathFromUriAsSingle(uri) .flatMap { path -> queryPostImageToAPI(domain, path, uri) } .subscribeOn(Schedulers.newThread()) .observeOn(AndroidSchedulers.mainThread()) .compose(bindToLifecycle()) .subscribe({ attachments.add(it) indicateImage(it.url) }, { throwable -> throwable.printStackTrace() Snackbar.make(binding.root, R.string.error_unable_upload_media, Snackbar.LENGTH_SHORT).show() }) } } else { Snackbar.make(binding.root, R.string.error_too_many_media, Snackbar.LENGTH_SHORT).show() } } private fun queryPostImageToAPI(domain: String, path: String, uri: Uri): Single<Attachment> { val file = File(path) val body = MultipartBody.Part.createFormData( "file", file.name, RequestBody.create(MediaType.parse(activity.contentResolver.getType(uri)), file)) return MastodonClient(domain).postNewMedia(body) } private fun indicateImage(url: String, index: Int = attachments.size) { when (index) { 0 -> Glide.with(activity).load(url).into(binding.media1) 1 -> Glide.with(activity).load(url).into(binding.media2) 2 -> Glide.with(activity).load(url).into(binding.media3) 3 -> Glide.with(activity).load(url).into(binding.media4) else -> {} } } private fun getMediaPathFromUriAsSingle(uri: Uri): Single<Pair<String, Uri>> { val projection = MediaStore.Images.Media.DATA return Single.just(DocumentsContract.getDocumentId(uri).split(":").last()) .map { val cursor = activity.contentResolver.query( MediaStore.Images.Media.EXTERNAL_CONTENT_URI, arrayOf(projection), "${MediaStore.Images.Media._ID} = ?", arrayOf(it), null) cursor.moveToFirst() val path = cursor.getString(cursor.getColumnIndexOrThrow(projection)).apply { cursor.close() } Pair(path, uri) } } private fun getMediaPathsFromClipDataAsObservable(clip: ClipData): Observable<Pair<String, Uri>> { val docIds: ArrayList<Pair<String, Uri>> = ArrayList() val projection = MediaStore.Images.Media.DATA (0 until clip.itemCount).mapTo(docIds) { val uri = clip.getItemAt(it).uri Pair(DocumentsContract.getDocumentId(uri).split(":").last(), uri) } return Observable.fromIterable(docIds) .map { val cursor = activity.contentResolver.query( MediaStore.Images.Media.EXTERNAL_CONTENT_URI, arrayOf(projection), "${MediaStore.Images.Media._ID} = ?", arrayOf(it.first), null) cursor.moveToFirst() val path = cursor.getString(cursor.getColumnIndexOrThrow(projection)) Pair(path, it.second).apply { cursor.close() } } } private fun getImagePathFromUriAsSingle(uri: Uri): Single<String> { return Single.just(MediaStore.Images.Media.DATA) .map { projection -> val cursor = activity.contentResolver.query(uri, arrayOf(projection), null, null, null) cursor.moveToFirst() cursor.getString(cursor.getColumnIndexOrThrow(projection)).apply { cursor.close() } } } private fun deleteTempImage() { capturedImageUri?.let { getImagePathFromUriAsSingle(it) .subscribeOn(Schedulers.newThread()) .observeOn(AndroidSchedulers.mainThread()) .compose(bindToLifecycle()) .subscribe({ path -> File(path).apply { if (this.exists()) this.delete() } activity.contentResolver.delete(it, null, null) capturedImageUri = null }) } } private fun onPostSuccess() { isSuccessPost = true (activity as? MainActivity)?.supportFragmentManager?.popBackStack() (activity as? ShareActivity)?.apply { supportFragmentManager?.popBackStack() onBackPressed() } } }
gpl-3.0
62312936d258c615fc8934b122cd3647
45.7424
186
0.534659
5.405811
false
false
false
false
asarkar/spring
touchstone/src/main/kotlin/execution/junit/JUnitProperties.kt
1
1646
package org.abhijitsarkar.touchstone.execution.junit import org.springframework.boot.context.properties.ConfigurationProperties import org.springframework.stereotype.Component import java.nio.file.Files import java.nio.file.Paths import java.time.OffsetDateTime import java.time.ZoneOffset import java.time.format.DateTimeFormatter /** * @author Abhijit Sarkar */ enum class TestOutputDetailsMode { NONE, SUMMARY, FLAT, TREE, VERBOSE } enum class TestOutputDetailsTheme { ASCII, UNICODE } @ConfigurationProperties("touchstone.junit") @Component class JUnitProperties { var help = false var disableAnsiColors = false var details = TestOutputDetailsMode.TREE var detailsTheme = TestOutputDetailsTheme.UNICODE var reportsDir = run { val temp = OffsetDateTime.now(ZoneOffset.UTC) .format(DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmss'Z'")) val dir = Paths.get(System.getProperty("java.io.tmpdir"), "reports", temp) Files.createDirectories(dir).toString() } var selectUri = emptyList<String>() var selectFile = emptyList<String>() var selectDirectory = emptyList<String>() var selectPackage = emptyList<String>() var selectClass = emptyList<String>() var selectMethod = emptyList<String>() var selectResource = emptyList<String>() var includeClassname = listOf("^.*Tests?$") var excludeClassname = emptyList<String>() var includePackage = emptyList<String>() var excludePackage = emptyList<String>() var includeTag = emptyList<String>() var excludeTag = emptyList<String>() var config = emptyMap<String, String>() }
gpl-3.0
232a3a39f4a45faa8c927f7a15bf1c16
31.94
82
0.730863
4.37766
false
true
false
false
rock3r/detekt
detekt-test/src/main/kotlin/io/gitlab/arturbosch/detekt/test/KotlinScriptEnginePool.kt
1
1277
package io.gitlab.arturbosch.detekt.test import org.jetbrains.kotlin.cli.common.environment.setIdeaIoUseFallback import org.jetbrains.kotlin.script.jsr223.KotlinJsr223JvmLocalScriptEngine import javax.script.ScriptEngineManager /** * The object to manage a pool of Kotlin script engines to distribute the load for compiling code. * The load for compiling code is distributed over a number of engines. */ object KotlinScriptEnginePool { private const val NUMBER_OF_ENGINES = 8 private val engines: Array<KotlinJsr223JvmLocalScriptEngine> by lazy { Array(NUMBER_OF_ENGINES) { createEngine() } } private var id = 0 fun getEngine(): KotlinJsr223JvmLocalScriptEngine { id++ if (id == NUMBER_OF_ENGINES) { id = 0 } return engines[id] } fun recoverEngine() { engines[id] = createEngine() } private fun createEngine(): KotlinJsr223JvmLocalScriptEngine { setIdeaIoUseFallback() // To avoid error on Windows val scriptEngineManager = ScriptEngineManager() val engine = scriptEngineManager.getEngineByExtension("kts") as? KotlinJsr223JvmLocalScriptEngine requireNotNull(engine) { "Kotlin script engine not supported" } return engine } }
apache-2.0
b0db4cdcb138a38768fdf8f9945367cd
30.925
105
0.707909
4.373288
false
false
false
false
JetBrains/anko
anko/library/generated/sdk28-listeners/src/main/java/Listeners.kt
2
20745
@file:JvmName("Sdk28ListenersListenersKt") package org.jetbrains.anko.sdk28.listeners inline fun android.view.View.onLayoutChange(noinline l: (v: android.view.View?, left: Int, top: Int, right: Int, bottom: Int, oldLeft: Int, oldTop: Int, oldRight: Int, oldBottom: Int) -> Unit) { addOnLayoutChangeListener(l) } fun android.view.View.onAttachStateChangeListener(init: __View_OnAttachStateChangeListener.() -> Unit) { val listener = __View_OnAttachStateChangeListener() listener.init() addOnAttachStateChangeListener(listener) } class __View_OnAttachStateChangeListener : android.view.View.OnAttachStateChangeListener { private var _onViewAttachedToWindow: ((android.view.View) -> Unit)? = null override fun onViewAttachedToWindow(v: android.view.View) { _onViewAttachedToWindow?.invoke(v) } fun onViewAttachedToWindow(listener: (android.view.View) -> Unit) { _onViewAttachedToWindow = listener } private var _onViewDetachedFromWindow: ((android.view.View) -> Unit)? = null override fun onViewDetachedFromWindow(v: android.view.View) { _onViewDetachedFromWindow?.invoke(v) } fun onViewDetachedFromWindow(listener: (android.view.View) -> Unit) { _onViewDetachedFromWindow = listener } } inline fun android.view.View.onUnhandledKeyEvent(noinline l: (p0: android.view.View?, p1: android.view.KeyEvent?) -> Boolean) { addOnUnhandledKeyEventListener(l) } fun android.widget.TextView.textChangedListener(init: __TextWatcher.() -> Unit) { val listener = __TextWatcher() listener.init() addTextChangedListener(listener) } class __TextWatcher : android.text.TextWatcher { private var _beforeTextChanged: ((CharSequence?, Int, Int, Int) -> Unit)? = null override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) { _beforeTextChanged?.invoke(s, start, count, after) } fun beforeTextChanged(listener: (CharSequence?, Int, Int, Int) -> Unit) { _beforeTextChanged = listener } private var _onTextChanged: ((CharSequence?, Int, Int, Int) -> Unit)? = null override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) { _onTextChanged?.invoke(s, start, before, count) } fun onTextChanged(listener: (CharSequence?, Int, Int, Int) -> Unit) { _onTextChanged = listener } private var _afterTextChanged: ((android.text.Editable?) -> Unit)? = null override fun afterTextChanged(s: android.text.Editable?) { _afterTextChanged?.invoke(s) } fun afterTextChanged(listener: (android.text.Editable?) -> Unit) { _afterTextChanged = listener } } fun android.gesture.GestureOverlayView.onGestureListener(init: __GestureOverlayView_OnGestureListener.() -> Unit) { val listener = __GestureOverlayView_OnGestureListener() listener.init() addOnGestureListener(listener) } class __GestureOverlayView_OnGestureListener : android.gesture.GestureOverlayView.OnGestureListener { private var _onGestureStarted: ((android.gesture.GestureOverlayView?, android.view.MotionEvent?) -> Unit)? = null override fun onGestureStarted(overlay: android.gesture.GestureOverlayView?, event: android.view.MotionEvent?) { _onGestureStarted?.invoke(overlay, event) } fun onGestureStarted(listener: (android.gesture.GestureOverlayView?, android.view.MotionEvent?) -> Unit) { _onGestureStarted = listener } private var _onGesture: ((android.gesture.GestureOverlayView?, android.view.MotionEvent?) -> Unit)? = null override fun onGesture(overlay: android.gesture.GestureOverlayView?, event: android.view.MotionEvent?) { _onGesture?.invoke(overlay, event) } fun onGesture(listener: (android.gesture.GestureOverlayView?, android.view.MotionEvent?) -> Unit) { _onGesture = listener } private var _onGestureEnded: ((android.gesture.GestureOverlayView?, android.view.MotionEvent?) -> Unit)? = null override fun onGestureEnded(overlay: android.gesture.GestureOverlayView?, event: android.view.MotionEvent?) { _onGestureEnded?.invoke(overlay, event) } fun onGestureEnded(listener: (android.gesture.GestureOverlayView?, android.view.MotionEvent?) -> Unit) { _onGestureEnded = listener } private var _onGestureCancelled: ((android.gesture.GestureOverlayView?, android.view.MotionEvent?) -> Unit)? = null override fun onGestureCancelled(overlay: android.gesture.GestureOverlayView?, event: android.view.MotionEvent?) { _onGestureCancelled?.invoke(overlay, event) } fun onGestureCancelled(listener: (android.gesture.GestureOverlayView?, android.view.MotionEvent?) -> Unit) { _onGestureCancelled = listener } } inline fun android.gesture.GestureOverlayView.onGesturePerformed(noinline l: (overlay: android.gesture.GestureOverlayView?, gesture: android.gesture.Gesture?) -> Unit) { addOnGesturePerformedListener(l) } fun android.gesture.GestureOverlayView.onGesturingListener(init: __GestureOverlayView_OnGesturingListener.() -> Unit) { val listener = __GestureOverlayView_OnGesturingListener() listener.init() addOnGesturingListener(listener) } class __GestureOverlayView_OnGesturingListener : android.gesture.GestureOverlayView.OnGesturingListener { private var _onGesturingStarted: ((android.gesture.GestureOverlayView?) -> Unit)? = null override fun onGesturingStarted(overlay: android.gesture.GestureOverlayView?) { _onGesturingStarted?.invoke(overlay) } fun onGesturingStarted(listener: (android.gesture.GestureOverlayView?) -> Unit) { _onGesturingStarted = listener } private var _onGesturingEnded: ((android.gesture.GestureOverlayView?) -> Unit)? = null override fun onGesturingEnded(overlay: android.gesture.GestureOverlayView?) { _onGesturingEnded?.invoke(overlay) } fun onGesturingEnded(listener: (android.gesture.GestureOverlayView?) -> Unit) { _onGesturingEnded = listener } } inline fun android.media.tv.TvView.onUnhandledInputEvent(noinline l: (event: android.view.InputEvent?) -> Boolean) { setOnUnhandledInputEventListener(l) } inline fun android.view.View.onApplyWindowInsets(noinline l: (v: android.view.View?, insets: android.view.WindowInsets?) -> android.view.WindowInsets?) { setOnApplyWindowInsetsListener(l) } inline fun android.view.View.onCapturedPointer(noinline l: (view: android.view.View?, event: android.view.MotionEvent?) -> Boolean) { setOnCapturedPointerListener(l) } inline fun android.view.View.onClick(noinline l: (v: android.view.View?) -> Unit) { setOnClickListener(l) } inline fun android.view.View.onContextClick(noinline l: (v: android.view.View?) -> Boolean) { setOnContextClickListener(l) } inline fun android.view.View.onCreateContextMenu(noinline l: (menu: android.view.ContextMenu?, v: android.view.View?, menuInfo: android.view.ContextMenu.ContextMenuInfo?) -> Unit) { setOnCreateContextMenuListener(l) } inline fun android.view.View.onDrag(noinline l: (v: android.view.View, event: android.view.DragEvent) -> Boolean) { setOnDragListener(l) } inline fun android.view.View.onFocusChange(noinline l: (v: android.view.View, hasFocus: Boolean) -> Unit) { setOnFocusChangeListener(l) } inline fun android.view.View.onGenericMotion(noinline l: (v: android.view.View, event: android.view.MotionEvent) -> Boolean) { setOnGenericMotionListener(l) } inline fun android.view.View.onHover(noinline l: (v: android.view.View, event: android.view.MotionEvent) -> Boolean) { setOnHoverListener(l) } inline fun android.view.View.onKey(noinline l: (v: android.view.View, keyCode: Int, event: android.view.KeyEvent?) -> Boolean) { setOnKeyListener(l) } inline fun android.view.View.onLongClick(noinline l: (v: android.view.View?) -> Boolean) { setOnLongClickListener(l) } inline fun android.view.View.onScrollChange(noinline l: (v: android.view.View?, scrollX: Int, scrollY: Int, oldScrollX: Int, oldScrollY: Int) -> Unit) { setOnScrollChangeListener(l) } inline fun android.view.View.onSystemUiVisibilityChange(noinline l: (visibility: Int) -> Unit) { setOnSystemUiVisibilityChangeListener(l) } inline fun android.view.View.onTouch(noinline l: (v: android.view.View, event: android.view.MotionEvent) -> Boolean) { setOnTouchListener(l) } fun android.view.ViewGroup.onHierarchyChangeListener(init: __ViewGroup_OnHierarchyChangeListener.() -> Unit) { val listener = __ViewGroup_OnHierarchyChangeListener() listener.init() setOnHierarchyChangeListener(listener) } class __ViewGroup_OnHierarchyChangeListener : android.view.ViewGroup.OnHierarchyChangeListener { private var _onChildViewAdded: ((android.view.View?, android.view.View?) -> Unit)? = null override fun onChildViewAdded(parent: android.view.View?, child: android.view.View?) { _onChildViewAdded?.invoke(parent, child) } fun onChildViewAdded(listener: (android.view.View?, android.view.View?) -> Unit) { _onChildViewAdded = listener } private var _onChildViewRemoved: ((android.view.View?, android.view.View?) -> Unit)? = null override fun onChildViewRemoved(parent: android.view.View?, child: android.view.View?) { _onChildViewRemoved?.invoke(parent, child) } fun onChildViewRemoved(listener: (android.view.View?, android.view.View?) -> Unit) { _onChildViewRemoved = listener } } inline fun android.view.ViewStub.onInflate(noinline l: (stub: android.view.ViewStub?, inflated: android.view.View?) -> Unit) { setOnInflateListener(l) } fun android.widget.AbsListView.onScrollListener(init: __AbsListView_OnScrollListener.() -> Unit) { val listener = __AbsListView_OnScrollListener() listener.init() setOnScrollListener(listener) } class __AbsListView_OnScrollListener : android.widget.AbsListView.OnScrollListener { private var _onScrollStateChanged: ((android.widget.AbsListView?, Int) -> Unit)? = null override fun onScrollStateChanged(view: android.widget.AbsListView?, scrollState: Int) { _onScrollStateChanged?.invoke(view, scrollState) } fun onScrollStateChanged(listener: (android.widget.AbsListView?, Int) -> Unit) { _onScrollStateChanged = listener } private var _onScroll: ((android.widget.AbsListView?, Int, Int, Int) -> Unit)? = null override fun onScroll(view: android.widget.AbsListView?, firstVisibleItem: Int, visibleItemCount: Int, totalItemCount: Int) { _onScroll?.invoke(view, firstVisibleItem, visibleItemCount, totalItemCount) } fun onScroll(listener: (android.widget.AbsListView?, Int, Int, Int) -> Unit) { _onScroll = listener } } inline fun android.widget.ActionMenuView.onMenuItemClick(noinline l: (item: android.view.MenuItem?) -> Boolean) { setOnMenuItemClickListener(l) } inline fun android.widget.AdapterView<out android.widget.Adapter>.onItemClick(noinline l: (p0: android.widget.AdapterView<*>?, p1: android.view.View?, p2: Int, p3: Long) -> Unit) { setOnItemClickListener(l) } inline fun android.widget.AdapterView<out android.widget.Adapter>.onItemLongClick(noinline l: (p0: android.widget.AdapterView<*>?, p1: android.view.View?, p2: Int, p3: Long) -> Boolean) { setOnItemLongClickListener(l) } fun android.widget.AdapterView<out android.widget.Adapter>.onItemSelectedListener(init: __AdapterView_OnItemSelectedListener.() -> Unit) { val listener = __AdapterView_OnItemSelectedListener() listener.init() setOnItemSelectedListener(listener) } class __AdapterView_OnItemSelectedListener : android.widget.AdapterView.OnItemSelectedListener { private var _onItemSelected: ((android.widget.AdapterView<*>?, android.view.View?, Int, Long) -> Unit)? = null override fun onItemSelected(p0: android.widget.AdapterView<*>?, p1: android.view.View?, p2: Int, p3: Long) { _onItemSelected?.invoke(p0, p1, p2, p3) } fun onItemSelected(listener: (android.widget.AdapterView<*>?, android.view.View?, Int, Long) -> Unit) { _onItemSelected = listener } private var _onNothingSelected: ((android.widget.AdapterView<*>?) -> Unit)? = null override fun onNothingSelected(p0: android.widget.AdapterView<*>?) { _onNothingSelected?.invoke(p0) } fun onNothingSelected(listener: (android.widget.AdapterView<*>?) -> Unit) { _onNothingSelected = listener } } inline fun android.widget.AutoCompleteTextView.onDismiss(noinline l: () -> Unit) { setOnDismissListener(l) } inline fun android.widget.CalendarView.onDateChange(noinline l: (view: android.widget.CalendarView?, year: Int, month: Int, dayOfMonth: Int) -> Unit) { setOnDateChangeListener(l) } inline fun android.widget.Chronometer.onChronometerTick(noinline l: (chronometer: android.widget.Chronometer?) -> Unit) { setOnChronometerTickListener(l) } inline fun android.widget.CompoundButton.onCheckedChange(noinline l: (buttonView: android.widget.CompoundButton?, isChecked: Boolean) -> Unit) { setOnCheckedChangeListener(l) } inline fun android.widget.DatePicker.onDateChanged(noinline l: (view: android.widget.DatePicker?, year: Int, monthOfYear: Int, dayOfMonth: Int) -> Unit) { setOnDateChangedListener(l) } inline fun android.widget.ExpandableListView.onChildClick(noinline l: (parent: android.widget.ExpandableListView?, v: android.view.View?, groupPosition: Int, childPosition: Int, id: Long) -> Boolean) { setOnChildClickListener(l) } inline fun android.widget.ExpandableListView.onGroupClick(noinline l: (parent: android.widget.ExpandableListView?, v: android.view.View?, groupPosition: Int, id: Long) -> Boolean) { setOnGroupClickListener(l) } inline fun android.widget.ExpandableListView.onGroupCollapse(noinline l: (groupPosition: Int) -> Unit) { setOnGroupCollapseListener(l) } inline fun android.widget.ExpandableListView.onGroupExpand(noinline l: (groupPosition: Int) -> Unit) { setOnGroupExpandListener(l) } inline fun android.widget.NumberPicker.onScroll(noinline l: (view: android.widget.NumberPicker?, scrollState: Int) -> Unit) { setOnScrollListener(l) } inline fun android.widget.NumberPicker.onValueChanged(noinline l: (picker: android.widget.NumberPicker?, oldVal: Int, newVal: Int) -> Unit) { setOnValueChangedListener(l) } inline fun android.widget.RadioGroup.onCheckedChange(noinline l: (group: android.widget.RadioGroup?, checkedId: Int) -> Unit) { setOnCheckedChangeListener(l) } inline fun android.widget.RatingBar.onRatingBarChange(noinline l: (ratingBar: android.widget.RatingBar?, rating: Float, fromUser: Boolean) -> Unit) { setOnRatingBarChangeListener(l) } inline fun android.widget.SearchView.onClose(noinline l: () -> Boolean) { setOnCloseListener(l) } inline fun android.widget.SearchView.onQueryTextFocusChange(noinline l: (v: android.view.View, hasFocus: Boolean) -> Unit) { setOnQueryTextFocusChangeListener(l) } fun android.widget.SearchView.onQueryTextListener(init: __SearchView_OnQueryTextListener.() -> Unit) { val listener = __SearchView_OnQueryTextListener() listener.init() setOnQueryTextListener(listener) } class __SearchView_OnQueryTextListener : android.widget.SearchView.OnQueryTextListener { private var _onQueryTextSubmit: ((String?) -> Boolean)? = null override fun onQueryTextSubmit(query: String?) = _onQueryTextSubmit?.invoke(query) ?: false fun onQueryTextSubmit(listener: (String?) -> Boolean) { _onQueryTextSubmit = listener } private var _onQueryTextChange: ((String?) -> Boolean)? = null override fun onQueryTextChange(newText: String?) = _onQueryTextChange?.invoke(newText) ?: false fun onQueryTextChange(listener: (String?) -> Boolean) { _onQueryTextChange = listener } } inline fun android.widget.SearchView.onSearchClick(noinline l: (v: android.view.View?) -> Unit) { setOnSearchClickListener(l) } fun android.widget.SearchView.onSuggestionListener(init: __SearchView_OnSuggestionListener.() -> Unit) { val listener = __SearchView_OnSuggestionListener() listener.init() setOnSuggestionListener(listener) } class __SearchView_OnSuggestionListener : android.widget.SearchView.OnSuggestionListener { private var _onSuggestionSelect: ((Int) -> Boolean)? = null override fun onSuggestionSelect(position: Int) = _onSuggestionSelect?.invoke(position) ?: false fun onSuggestionSelect(listener: (Int) -> Boolean) { _onSuggestionSelect = listener } private var _onSuggestionClick: ((Int) -> Boolean)? = null override fun onSuggestionClick(position: Int) = _onSuggestionClick?.invoke(position) ?: false fun onSuggestionClick(listener: (Int) -> Boolean) { _onSuggestionClick = listener } } fun android.widget.SeekBar.onSeekBarChangeListener(init: __SeekBar_OnSeekBarChangeListener.() -> Unit) { val listener = __SeekBar_OnSeekBarChangeListener() listener.init() setOnSeekBarChangeListener(listener) } class __SeekBar_OnSeekBarChangeListener : android.widget.SeekBar.OnSeekBarChangeListener { private var _onProgressChanged: ((android.widget.SeekBar?, Int, Boolean) -> Unit)? = null override fun onProgressChanged(seekBar: android.widget.SeekBar?, progress: Int, fromUser: Boolean) { _onProgressChanged?.invoke(seekBar, progress, fromUser) } fun onProgressChanged(listener: (android.widget.SeekBar?, Int, Boolean) -> Unit) { _onProgressChanged = listener } private var _onStartTrackingTouch: ((android.widget.SeekBar?) -> Unit)? = null override fun onStartTrackingTouch(seekBar: android.widget.SeekBar?) { _onStartTrackingTouch?.invoke(seekBar) } fun onStartTrackingTouch(listener: (android.widget.SeekBar?) -> Unit) { _onStartTrackingTouch = listener } private var _onStopTrackingTouch: ((android.widget.SeekBar?) -> Unit)? = null override fun onStopTrackingTouch(seekBar: android.widget.SeekBar?) { _onStopTrackingTouch?.invoke(seekBar) } fun onStopTrackingTouch(listener: (android.widget.SeekBar?) -> Unit) { _onStopTrackingTouch = listener } } inline fun android.widget.SlidingDrawer.onDrawerClose(noinline l: () -> Unit) { setOnDrawerCloseListener(l) } inline fun android.widget.SlidingDrawer.onDrawerOpen(noinline l: () -> Unit) { setOnDrawerOpenListener(l) } fun android.widget.SlidingDrawer.onDrawerScrollListener(init: __SlidingDrawer_OnDrawerScrollListener.() -> Unit) { val listener = __SlidingDrawer_OnDrawerScrollListener() listener.init() setOnDrawerScrollListener(listener) } class __SlidingDrawer_OnDrawerScrollListener : android.widget.SlidingDrawer.OnDrawerScrollListener { private var _onScrollStarted: (() -> Unit)? = null override fun onScrollStarted() { _onScrollStarted?.invoke() } fun onScrollStarted(listener: () -> Unit) { _onScrollStarted = listener } private var _onScrollEnded: (() -> Unit)? = null override fun onScrollEnded() { _onScrollEnded?.invoke() } fun onScrollEnded(listener: () -> Unit) { _onScrollEnded = listener } } inline fun android.widget.TabHost.onTabChanged(noinline l: (tabId: String?) -> Unit) { setOnTabChangedListener(l) } inline fun android.widget.TextView.onEditorAction(noinline l: (v: android.widget.TextView?, actionId: Int, event: android.view.KeyEvent?) -> Boolean) { setOnEditorActionListener(l) } inline fun android.widget.TimePicker.onTimeChanged(noinline l: (view: android.widget.TimePicker?, hourOfDay: Int, minute: Int) -> Unit) { setOnTimeChangedListener(l) } inline fun android.widget.Toolbar.onMenuItemClick(noinline l: (item: android.view.MenuItem?) -> Boolean) { setOnMenuItemClickListener(l) } inline fun android.widget.VideoView.onCompletion(noinline l: (mp: android.media.MediaPlayer?) -> Unit) { setOnCompletionListener(l) } inline fun android.widget.VideoView.onError(noinline l: (mp: android.media.MediaPlayer?, what: Int, extra: Int) -> Boolean) { setOnErrorListener(l) } inline fun android.widget.VideoView.onInfo(noinline l: (mp: android.media.MediaPlayer?, what: Int, extra: Int) -> Boolean) { setOnInfoListener(l) } inline fun android.widget.VideoView.onPrepared(noinline l: (mp: android.media.MediaPlayer?) -> Unit) { setOnPreparedListener(l) } inline fun android.widget.ZoomControls.onZoomInClick(noinline l: (v: android.view.View?) -> Unit) { setOnZoomInClickListener(l) } inline fun android.widget.ZoomControls.onZoomOutClick(noinline l: (v: android.view.View?) -> Unit) { setOnZoomOutClickListener(l) }
apache-2.0
4af2db0461856410b47a71765b7721cf
35.651943
201
0.727886
4.349057
false
false
false
false
tmarsteel/bytecode-fiddle
compiler/src/main/kotlin/com/github/tmarsteel/bytecode/compiler/macro/utils.kt
1
2646
package com.github.tmarsteel.bytecode.compiler.macro import com.github.tmarsteel.bytecode.compiler.Location import com.github.tmarsteel.bytecode.compiler.macro.MacroCommand import com.github.tmarsteel.bytecode.compiler.SyntaxError import com.github.tmarsteel.bytecode.compiler.isRegisterArgument /** * Persists all the memory registers in an 8-QWORD block in memory. Takes one parameter: * - addr: The start address to persist to; a literal is interpreted as a literal memory address; a register is read * and its value is used as the memory address */ val StoreMemoryRegistersMacro = object : MacroCommand { override fun unroll(tokens: List<String>, includeLocation: Location): List<String> { if (tokens.size != 1) { throw SyntaxError("The ${this.javaClass.simpleName} macro requires exactly 1 parameter, ${tokens.size} given", includeLocation) } val targetAddr = tokens[0] val instructions: MutableList<String> = mutableListOf() // assure the target address is loaded into #a2 if (isRegisterArgument(targetAddr)) { if (targetAddr.toUpperCase() != "#A2") { instructions.add("mov $targetAddr #a2") } } else { instructions.add("ldc #a2 $targetAddr") } for (register in 1..8) { instructions.add("sto #m$register #a2") instructions.add("inc #a2") } return instructions } } /** * Fills all the memory registers from an 8-QWORD block in memory. Takes one parameter: * - addr: The start address to recall from; a literal is interpreted as a literal memory address; a register is read * and its value is used as the memory address */ val RecallMemoryRegistersMacro = object : MacroCommand { override fun unroll(tokens: List<String>, includeLocation: Location): List<String> { if (tokens.size != 1) { throw SyntaxError("The ${this.javaClass.simpleName} macro requires exactly 1 parameter, ${tokens.size} given", includeLocation) } val targetAddr = tokens[0] val instructions: MutableList<String> = mutableListOf() // assure the target address is loaded into #a2 if (isRegisterArgument(targetAddr)) { if (targetAddr.toUpperCase() != "#A2") { instructions.add("mov $targetAddr #a2") } } else { instructions.add("ldc #a2 $targetAddr") } for (register in 1..8) { instructions.add("rcl #a2 #m$register") instructions.add("inc #a2") } return instructions } }
lgpl-3.0
de12e07dbf750f18518f8bcd212c6df5
37.362319
139
0.644369
4.173502
false
false
false
false
fossasia/open-event-android
app/src/main/java/org/fossasia/openevent/general/speakercall/Proposal.kt
1
1360
package org.fossasia.openevent.general.speakercall import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.PrimaryKey import com.fasterxml.jackson.databind.PropertyNamingStrategy import com.fasterxml.jackson.databind.annotation.JsonNaming import com.github.jasminb.jsonapi.annotations.Id import com.github.jasminb.jsonapi.annotations.Relationship import com.github.jasminb.jsonapi.annotations.Type import org.fossasia.openevent.general.event.EventId import org.fossasia.openevent.general.sessions.track.Track import org.fossasia.openevent.general.speakers.SpeakerId @Type("session") @JsonNaming(PropertyNamingStrategy.KebabCaseStrategy::class) @Entity data class Proposal( @PrimaryKey @Id val id: Long? = null, val title: String? = null, val language: String? = null, val shortAbstract: String? = null, val comments: String? = null, val startsAt: String? = null, val endsAt: String? = null, val subTitle: String? = null, val longAbstract: String? = null, @ColumnInfo(index = true) @Relationship("track", resolve = true) val track: Track? = null, @ColumnInfo(index = true) @Relationship("event", resolve = true) val event: EventId? = null, @ColumnInfo(index = true) @Relationship("speakers", resolve = true) val speakers: List<SpeakerId> = emptyList() )
apache-2.0
f3b9898e469ac5b6056352acc6d8bbaa
33.871795
60
0.746324
3.930636
false
false
false
false
LanternPowered/LanternServer
src/main/kotlin/org/lanternpowered/server/network/entity/vanilla/SnowmanEntityProtocol.kt
1
1480
/* * Lantern * * Copyright (c) LanternPowered <https://www.lanternpowered.org> * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * This work is licensed under the terms of the MIT License (MIT). For * a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>. */ package org.lanternpowered.server.network.entity.vanilla import org.lanternpowered.api.data.Keys import org.lanternpowered.api.key.NamespacedKey import org.lanternpowered.api.key.minecraftKey import org.lanternpowered.server.entity.LanternEntity import org.lanternpowered.server.network.entity.parameter.ParameterList class SnowmanEntityProtocol<E : LanternEntity>(entity: E) : InsentientEntityProtocol<E>(entity) { companion object { private val TYPE = minecraftKey("snow_golem") } private var lastNoPumpkin = false override val mobType: NamespacedKey get() = TYPE override fun spawn(parameterList: ParameterList) { parameterList.add(EntityParameters.Snowman.FLAGS, (if (this.entity.get(Keys.HAS_PUMPKIN_HEAD).orElse(true)) 0 else 0x10).toByte()) } override fun update(parameterList: ParameterList) { val noPumpkin = !this.entity.get(Keys.HAS_PUMPKIN_HEAD).orElse(true) if (this.lastNoPumpkin != noPumpkin) { parameterList.add(EntityParameters.Snowman.FLAGS, (if (noPumpkin) 0x10 else 0).toByte()) this.lastNoPumpkin = noPumpkin } } }
mit
3ec573f969c33c404bbf4df46039d0c4
34.238095
100
0.718243
3.844156
false
false
false
false
gumil/basamto
app/src/main/kotlin/io/github/gumil/basamto/reddit/comments/CommentsFragment.kt
1
4470
/* * The MIT License (MIT) * * Copyright 2017 Miguel Panelo * * 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 io.github.gumil.basamto.reddit.comments import android.arch.lifecycle.Lifecycle import android.arch.lifecycle.Observer import android.arch.lifecycle.ViewModelProvider import android.arch.lifecycle.ViewModelProviders import android.os.Bundle import android.support.v7.widget.DividerItemDecoration import android.support.v7.widget.LinearLayoutManager import android.view.View import io.github.gumil.basamto.R import io.github.gumil.basamto.common.BaseFragment import io.github.gumil.basamto.common.MviView import io.github.gumil.basamto.common.adapter.ItemAdapter import io.github.gumil.basamto.extensions.load import io.github.gumil.basamto.extensions.setVisible import io.github.gumil.basamto.main.MainActivity import io.github.gumil.basamto.reddit.subreddit.SubmissionItem import io.github.gumil.basamto.widget.html.getBlocks import io.reactivex.Observable import kotlinx.android.synthetic.main.fragment_comments.body import kotlinx.android.synthetic.main.fragment_comments.bodyContainer import kotlinx.android.synthetic.main.fragment_comments.commentsList import kotlinx.android.synthetic.main.fragment_comments.commentsPreview import kotlinx.android.synthetic.main.fragment_comments.swipeRefreshLayout import javax.inject.Inject internal class CommentsFragment : BaseFragment(), MviView<CommentsIntent, CommentsState> { override val layoutId: Int get() = R.layout.fragment_comments @Inject lateinit var viewModelFactory: ViewModelProvider.Factory private val submission by lazy { arguments.getParcelable<SubmissionItem>(ARG_SUBMISSION) } private val adapter = ItemAdapter(CommentViewItem()) override fun onViewCreated(view: View?, savedInstanceState: Bundle?) { (activity as? MainActivity)?.showToolbar(false) val viewModel = ViewModelProviders.of(this, viewModelFactory)[CommentsViewModel::class.java] viewModel.state.observe(this, Observer<CommentsState> { it?.render() }) viewModel.processIntents(intents()) commentsList.layoutManager = LinearLayoutManager(context) commentsList.addItemDecoration(DividerItemDecoration(context, DividerItemDecoration.VERTICAL)) } override fun CommentsState.render() = when (this) { is CommentsState.View -> { swipeRefreshLayout.isRefreshing = isLoading commentsList.adapter ?: let { commentsList.adapter = adapter } adapter.list = comments commentsPreview.setVisible(submissionItem?.preview != null) commentsPreview.load(submissionItem?.preview) submissionItem?.body?.getBlocks()?.let { body.setViews(it) bodyContainer.setVisible(true) } } is CommentsState.Error -> showSnackbarError(message) } override fun intents(): Observable<CommentsIntent> = rxLifecycle.filter { it == Lifecycle.Event.ON_START }.map { CommentsIntent.Load(submission.subreddit, submission.id) } companion object { private const val ARG_SUBMISSION = "comments_submission" fun newInstance(submissionItem: SubmissionItem) = CommentsFragment().apply { arguments = Bundle().apply { putParcelable(ARG_SUBMISSION, submissionItem) } } } }
mit
940b7bf7a51ffcc35f94a6d30cac9cb5
38.566372
102
0.743624
4.551935
false
false
false
false
tasks/tasks
app/src/main/java/org/tasks/preferences/fragments/ScrollableWidget.kt
1
10409
package org.tasks.preferences.fragments import android.app.Activity import android.appwidget.AppWidgetManager import android.content.Intent import android.os.Bundle import androidx.lifecycle.lifecycleScope import androidx.preference.* import com.todoroo.astrid.api.Filter import com.todoroo.astrid.core.SortHelper.* import dagger.hilt.android.AndroidEntryPoint import kotlinx.coroutines.launch import org.tasks.LocalBroadcastManager import org.tasks.R import org.tasks.dialogs.ColorPalettePicker import org.tasks.dialogs.ColorPalettePicker.Companion.newColorPalette import org.tasks.dialogs.ColorPickerAdapter.Palette import org.tasks.dialogs.ColorWheelPicker import org.tasks.dialogs.FilterPicker.Companion.newFilterPicker import org.tasks.dialogs.FilterPicker.Companion.setFilterPickerResultListener import org.tasks.dialogs.SortDialog.newSortDialog import org.tasks.dialogs.ThemePickerDialog.Companion.newThemePickerDialog import org.tasks.injection.InjectingPreferenceFragment import org.tasks.preferences.DefaultFilterProvider import org.tasks.preferences.Preferences import org.tasks.widget.WidgetPreferences import javax.inject.Inject @AndroidEntryPoint class ScrollableWidget : InjectingPreferenceFragment() { companion object { private const val REQUEST_THEME_SELECTION = 1006 private const val REQUEST_COLOR_SELECTION = 1007 private const val REQUEST_SORT = 1008 const val EXTRA_WIDGET_ID = "extra_widget_id" private const val FRAG_TAG_COLOR_PICKER = "frag_tag_color_picker" private const val FRAG_TAG_SORT_DIALOG = "frag_tag_sort_dialog" private const val FRAG_TAG_FILTER_PICKER = "frag_tag_filter_picker" fun newScrollableWidget(appWidgetId: Int): ScrollableWidget { val widget = ScrollableWidget() val args = Bundle() args.putInt(EXTRA_WIDGET_ID, appWidgetId) widget.arguments = args return widget } } @Inject lateinit var defaultFilterProvider: DefaultFilterProvider @Inject lateinit var preferences: Preferences @Inject lateinit var localBroadcastManager: LocalBroadcastManager private lateinit var widgetPreferences: WidgetPreferences private var appWidgetId = 0 override fun getPreferenceXml() = R.xml.preferences_widget override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) childFragmentManager.setFilterPickerResultListener(this) { widgetPreferences.setFilter(defaultFilterProvider.getFilterPreferenceValue(it)) updateFilter() } } override suspend fun setupPreferences(savedInstanceState: Bundle?) { appWidgetId = requireArguments().getInt(EXTRA_WIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID) widgetPreferences = WidgetPreferences(context, preferences, appWidgetId) val row = setupSlider(R.string.p_widget_opacity, 100) val header = setupSlider(R.string.p_widget_header_opacity, row.value) val footer = setupSlider(R.string.p_widget_footer_opacity, row.value) val opacity = findPreference(R.string.opacity) as SeekBarPreference opacity.value = maxOf(header.value, row.value, footer.value) if (header.value != row.value || header.value != footer.value) { (findPreference(R.string.preferences_advanced) as PreferenceCategory).initialExpandedChildrenCount = 4 } opacity.setOnPreferenceChangeListener { _, newValue -> header.value = newValue as Int row.value = newValue footer.value = newValue true } setupSlider(R.string.p_widget_font_size, 16) setupCheckbox(R.string.p_widget_show_checkboxes) setupCheckbox(R.string.p_widget_show_dividers) setupCheckbox(R.string.p_widget_show_subtasks) setupCheckbox(R.string.p_widget_show_start_dates) setupCheckbox(R.string.p_widget_show_places) setupCheckbox(R.string.p_widget_show_lists) setupCheckbox(R.string.p_widget_show_tags) setupCheckbox(R.string.p_widget_show_full_task_title, false) setupCheckbox(R.string.p_widget_disable_groups, false) setupCheckbox(R.string.p_widget_show_hidden, false) setupCheckbox(R.string.p_widget_show_completed, false) val showDescription = setupCheckbox(R.string.p_widget_show_description, true) setupCheckbox(R.string.p_widget_show_full_description, false).dependency = showDescription.key setupList(R.string.p_widget_spacing) setupList(R.string.p_widget_header_spacing) setupList(R.string.p_widget_footer_click) setupList(R.string.p_widget_due_date_click) setupList(R.string.p_widget_due_date_position, widgetPreferences.dueDatePosition.toString()) val showHeader = setupCheckbox(R.string.p_widget_show_header) val showTitle = setupCheckbox(R.string.p_widget_show_title) showTitle.dependency = showHeader.key val showSettings = setupCheckbox(R.string.p_widget_show_settings) showSettings.dependency = showHeader.key val showMenu = setupCheckbox(R.string.p_widget_show_menu) showMenu.dependency = showHeader.key header.dependency = showHeader.key findPreference(R.string.p_widget_sort).setOnPreferenceClickListener { lifecycleScope.launch { newSortDialog(this@ScrollableWidget, REQUEST_SORT, getFilter(), appWidgetId) .show(parentFragmentManager, FRAG_TAG_SORT_DIALOG) } false } findPreference(R.string.p_widget_filter) .setOnPreferenceClickListener { lifecycleScope.launch { newFilterPicker(getFilter()) .show(childFragmentManager, FRAG_TAG_FILTER_PICKER) } false } findPreference(R.string.p_widget_theme) .setOnPreferenceClickListener { newThemePickerDialog(this, REQUEST_THEME_SELECTION, widgetPreferences.themeIndex, true) .show(parentFragmentManager, FRAG_TAG_COLOR_PICKER) false } val colorPreference = findPreference(R.string.p_widget_color_v2) colorPreference.dependency = showHeader.key colorPreference.onPreferenceClickListener = Preference.OnPreferenceClickListener { newColorPalette(this, REQUEST_COLOR_SELECTION, widgetPreferences.color, Palette.WIDGET) .show(parentFragmentManager, FRAG_TAG_COLOR_PICKER) false } updateFilter() updateTheme() updateColor() } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { when (requestCode) { REQUEST_THEME_SELECTION -> if (resultCode == Activity.RESULT_OK) { widgetPreferences.setTheme( data?.getIntExtra( ColorPalettePicker.EXTRA_SELECTED, 0 ) ?: widgetPreferences.themeIndex ) updateTheme() } REQUEST_COLOR_SELECTION -> if (resultCode == Activity.RESULT_OK) { widgetPreferences.color = data!!.getIntExtra( ColorWheelPicker.EXTRA_SELECTED, 0 ) updateColor() } REQUEST_SORT -> if (resultCode == Activity.RESULT_OK) updateSort() else -> super.onActivityResult(requestCode, resultCode, data) } } override fun onPause() { super.onPause() localBroadcastManager.reconfigureWidget(appWidgetId) } private fun updateTheme() { val widgetNames = resources.getStringArray(R.array.widget_themes) findPreference(R.string.p_widget_theme).summary = widgetNames[widgetPreferences.themeIndex] } private fun updateColor() { tintColorPreference(R.string.p_widget_color_v2, widgetPreferences.color) } private fun updateFilter() = lifecycleScope.launch { findPreference(R.string.p_widget_filter).summary = getFilter().listingTitle updateSort() } private fun updateSort() = lifecycleScope.launch { val filter = getFilter() findPreference(R.string.p_widget_sort).setSummary( if (filter.supportsManualSort() && widgetPreferences.isManualSort) { R.string.SSD_sort_my_order } else if (filter.supportsAstridSorting() && widgetPreferences.isAstridSort) { R.string.astrid_sort_order } else { when (widgetPreferences.sortMode) { SORT_DUE -> R.string.SSD_sort_due SORT_START -> R.string.SSD_sort_start SORT_IMPORTANCE -> R.string.SSD_sort_importance SORT_ALPHA -> R.string.SSD_sort_alpha SORT_MODIFIED -> R.string.SSD_sort_modified SORT_CREATED -> R.string.sort_created else -> R.string.SSD_sort_auto } }) } private suspend fun getFilter(): Filter = defaultFilterProvider.getFilterFromPreference(widgetPreferences.filterId) private fun setupSlider(resId: Int, defValue: Int): SeekBarPreference { val preference = findPreference(resId) as SeekBarPreference preference.key = widgetPreferences.getKey(resId) preference.value = preferences.getInt(preference.key, defValue) return preference } private fun setupCheckbox(resId: Int, defaultValue: Boolean = true): SwitchPreferenceCompat { val preference = findPreference(resId) as SwitchPreferenceCompat val key = getString(resId) + appWidgetId preference.key = key preference.isChecked = preferences.getBoolean(key, defaultValue) return preference } private fun setupList(resId: Int, defaultValue: String = "0"): ListPreference { val preference = findPreference(resId) as ListPreference val key = getString(resId) + appWidgetId preference.key = key preference.value = preferences.getStringValue(key) ?: defaultValue return preference } }
gpl-3.0
61dae0742e01a0c08cc3213c8880bff9
42.016529
114
0.665578
4.752968
false
false
false
false
songzhw/AndroidArchitecture
deprecated/MVI/MVI101/MVI_Client/app/src/main/java/ca/six/mvi/biz/home/Todo.kt
1
864
package ca.six.mvi.biz.home import org.json.JSONArray import org.json.JSONObject class Todo { var position: Int var description: String constructor(position: Int, description: String) { this.position = position this.description = description } constructor(json: JSONObject) { this.position = json.optInt("pos") this.description = json.optString("desp") } companion object { fun createWithJsonArray(array: JSONArray): ArrayList<Todo> { val result = ArrayList<Todo>() for (i in 0 until array.length()) { val obj = Todo(array.optJSONObject(i)) result.add(obj) } return result } } override fun toString(): String { return "Todo(position=$position, description='$description')" } }
apache-2.0
2d5dca128287bec12169fa082025c907
20.625
69
0.592593
4.547368
false
false
false
false
tasks/tasks
app/src/main/java/com/todoroo/astrid/core/BuiltInFilterExposer.kt
1
8256
/* * Copyright (c) 2012 Todoroo Inc * * See the file "LICENSE" for the full license governing this code. */ package com.todoroo.astrid.core import android.content.Context import android.content.res.Resources import com.todoroo.andlib.sql.Criterion.Companion.and import com.todoroo.andlib.sql.Criterion.Companion.or import com.todoroo.andlib.sql.Join import com.todoroo.andlib.sql.QueryTemplate import com.todoroo.andlib.utility.AndroidUtilities import com.todoroo.astrid.api.Filter import com.todoroo.astrid.api.PermaSql import com.todoroo.astrid.data.Task import com.todoroo.astrid.timers.TimerPlugin import dagger.hilt.android.qualifiers.ApplicationContext import org.tasks.R import org.tasks.data.* import org.tasks.data.TaskDao.TaskCriteria.activeAndVisible import org.tasks.filters.NotificationsFilter import org.tasks.filters.RecentlyModifiedFilter import org.tasks.filters.SnoozedFilter import org.tasks.filters.SortableFilter import org.tasks.preferences.Preferences import org.tasks.themes.CustomIcons import javax.inject.Inject /** * Exposes Astrid's built in filters to the NavigationDrawerFragment * * @author Tim Su <tim></tim>@todoroo.com> */ class BuiltInFilterExposer @Inject constructor( @param:ApplicationContext private val context: Context, private val preferences: Preferences, private val taskDao: TaskDao) { val myTasksFilter: Filter get() { val myTasksFilter = getMyTasksFilter(context.resources) myTasksFilter.icon = CustomIcons.ALL_INBOX return myTasksFilter } suspend fun filters(): List<Filter> { val r = context.resources val filters: MutableList<Filter> = ArrayList() if (preferences.getBoolean(R.string.p_show_today_filter, true)) { val todayFilter = getTodayFilter(r) todayFilter.icon = CustomIcons.TODAY filters.add(todayFilter) } if (preferences.getBoolean(R.string.p_show_recently_modified_filter, true)) { val recentlyModifiedFilter = getRecentlyModifiedFilter(r) recentlyModifiedFilter.icon = CustomIcons.HISTORY filters.add(recentlyModifiedFilter) } if (taskDao.snoozedReminders() > 0) { val snoozedFilter = getSnoozedFilter(r) snoozedFilter.icon = R.drawable.ic_snooze_white_24dp filters.add(snoozedFilter) } if (taskDao.activeTimers() > 0) { filters.add(TimerPlugin.createFilter(context)) } if (taskDao.hasNotifications() > 0) { val element = NotificationsFilter(context) element.icon = R.drawable.ic_outline_notifications_24px filters.add(element) } return filters } companion object { /** Build inbox filter */ fun getMyTasksFilter(r: Resources): Filter { return SortableFilter( r.getString(R.string.BFE_Active), QueryTemplate().where(activeAndVisible())) } fun getTodayFilter(r: Resources): Filter { val todayTitle = AndroidUtilities.capitalize(r.getString(R.string.today)) val todayValues: MutableMap<String?, Any> = HashMap() todayValues[Task.DUE_DATE.name] = PermaSql.VALUE_NOON return SortableFilter( todayTitle, QueryTemplate() .where( and( activeAndVisible(), Task.DUE_DATE.gt(0), Task.DUE_DATE.lte(PermaSql.VALUE_EOD))), todayValues) } fun getNoListFilter() = Filter( "No list", QueryTemplate() .join(Join.left(GoogleTask.TABLE, GoogleTask.TASK.eq(Task.ID))) .join(Join.left(CaldavTask.TABLE, CaldavTask.TASK.eq(Task.ID))) .where(and(GoogleTask.ID.eq(null), CaldavTask.ID.eq(null))) ).apply { icon = R.drawable.ic_outline_cloud_off_24px } fun getDeleted() = Filter("Deleted", QueryTemplate().where(Task.DELETION_DATE.gt(0))) .apply { icon = R.drawable.ic_outline_delete_24px } fun getMissingListFilter() = Filter( "Missing list", QueryTemplate() .join(Join.left(GoogleTask.TABLE, GoogleTask.TASK.eq(Task.ID))) .join(Join.left(CaldavTask.TABLE, CaldavTask.TASK.eq(Task.ID))) .join(Join.left(GoogleTaskList.TABLE, GoogleTaskList.REMOTE_ID.eq(GoogleTask.LIST))) .join(Join.left(CaldavCalendar.TABLE, CaldavCalendar.UUID.eq(CaldavTask.CALENDAR))) .where(or( and(GoogleTask.ID.gt(0), GoogleTaskList.REMOTE_ID.eq(null)), and(CaldavTask.ID.gt(0), CaldavCalendar.UUID.eq(null)))) ).apply { icon = R.drawable.ic_outline_cloud_off_24px } fun getMissingAccountFilter() = Filter( "Missing account", QueryTemplate() .join(Join.left(GoogleTask.TABLE, and(GoogleTask.TASK.eq(Task.ID)))) .join(Join.left(CaldavTask.TABLE, and(CaldavTask.TASK.eq(Task.ID)))) .join(Join.left(GoogleTaskList.TABLE, GoogleTaskList.REMOTE_ID.eq(GoogleTask.LIST))) .join(Join.left(CaldavCalendar.TABLE, CaldavCalendar.UUID.eq(CaldavTask.CALENDAR))) .join(Join.left(GoogleTaskAccount.TABLE, GoogleTaskAccount.ACCOUNT.eq(GoogleTaskList.ACCOUNT))) .join(Join.left(CaldavAccount.TABLE, CaldavAccount.UUID.eq(CaldavCalendar.ACCOUNT))) .where(or( and(GoogleTask.ID.gt(0), GoogleTaskAccount.ACCOUNT.eq(null)), and(CaldavTask.ID.gt(0), CaldavAccount.UUID.eq(null)))) ).apply { icon = R.drawable.ic_outline_cloud_off_24px } fun getNoTitleFilter() = Filter( "No title", QueryTemplate().where(or(Task.TITLE.eq(null), Task.TITLE.eq(""))) ).apply { icon = R.drawable.ic_outline_clear_24px } fun getNoCreateDateFilter() = Filter("No create time", QueryTemplate().where(Task.CREATION_DATE.eq(0))) .apply { icon = R.drawable.ic_outline_add_24px } fun getNoModificationDateFilter() = Filter("No modify time", QueryTemplate().where(Task.MODIFICATION_DATE.eq(0))) .apply { icon = R.drawable.ic_outline_edit_24px } fun getRecentlyModifiedFilter(r: Resources) = RecentlyModifiedFilter(r.getString(R.string.BFE_Recent)) fun getSnoozedFilter(r: Resources) = SnoozedFilter(r.getString(R.string.filter_snoozed)) fun getNotificationsFilter(context: Context) = NotificationsFilter(context) @JvmStatic fun isInbox(context: Context, filter: Filter?) = filter == getMyTasksFilter(context.resources) @JvmStatic fun isTodayFilter(context: Context, filter: Filter?) = filter == getTodayFilter(context.resources) fun isRecentlyModifiedFilter(context: Context, filter: Filter?) = filter == getRecentlyModifiedFilter(context.resources) fun isSnoozedFilter(context: Context, filter: Filter?) = filter == getSnoozedFilter(context.resources) fun isNotificationsFilter(context: Context, filter: Filter?) = filter == getNotificationsFilter(context) } }
gpl-3.0
74ecda206bc9274c3f98463293ae12b7
43.15508
127
0.575339
4.509011
false
false
false
false
didi/DoraemonKit
Android/app/src/debug/java/com/didichuxing/doraemondemo/App.kt
1
6905
package com.didichuxing.doraemondemo import android.app.Activity import android.app.Application import android.content.Context import android.view.View import androidx.multidex.MultiDex import com.baidu.mapapi.CoordType import com.baidu.mapapi.SDKInitializer import com.blankj.utilcode.util.PathUtils import com.blankj.utilcode.util.ToastUtils import com.didichuxing.doraemondemo.dokit.DemoKit import com.didichuxing.doraemondemo.dokit.TestSimpleDokitFloatViewKit import com.didichuxing.doraemondemo.dokit.TestSimpleDokitFragmentKit import com.didichuxing.doraemondemo.mc.SlideBar import com.didichuxing.doraemonkit.DoKit import com.didichuxing.doraemonkit.DoKitCallBack import com.didichuxing.doraemonkit.kit.AbstractKit import com.didichuxing.doraemonkit.kit.core.McClientProcessor import com.didichuxing.doraemonkit.kit.network.bean.NetworkRecord import com.didichuxing.doraemonkit.kit.network.okhttp.interceptor.DokitExtInterceptor import com.didichuxing.doraemonkit.util.LogUtils import com.facebook.drawee.backends.pipeline.Fresco import com.facebook.imagepipeline.core.ImagePipelineConfig import com.lzy.okgo.OkGo import okhttp3.Cache import okhttp3.Interceptor import okhttp3.OkHttpClient import okhttp3.Response import java.io.File /** * @author jint * @mail [email protected] */ class App : Application() { override fun onCreate() { super.onCreate() //百度地图初始化 SDKInitializer.initialize(this) SDKInitializer.setCoordType(CoordType.BD09LL) //测试环境:a49842eeebeb1989b3f9565eb12c276b //线上环境:749a0600b5e48dd77cf8ee680be7b1b7 //DoraemonKit.disableUpload() //是否显示入口icon // DoraemonKit.setAwaysShowMainIcon(false); val kits: MutableList<AbstractKit> = ArrayList() kits.add(DemoKit()) kits.add(TestSimpleDokitFloatViewKit()) kits.add(TestSimpleDokitFragmentKit()) val mapKits: LinkedHashMap<String, List<AbstractKit>> = linkedMapOf() mapKits["业务专区1"] = mutableListOf<AbstractKit>().apply { add(DemoKit()) add(TestSimpleDokitFloatViewKit()) add(TestSimpleDokitFragmentKit()) } mapKits["业务专区2"] = mutableListOf<AbstractKit>(DemoKit()) DoKit.Builder(this) .productId("749a0600b5e48dd77cf8ee680be7b1b7") //测试环境pid // .productId("277016abcc33bff1e6a4f1afdf14b8e1") .disableUpload() .customKits(mapKits) .fileManagerHttpPort(9001) .databasePass(mapOf("Person.db" to "a_password")) .mcWSPort(5555) .alwaysShowMainIcon(true) .callBack(object : DoKitCallBack { override fun onCpuCallBack(value: Float, filePath: String) { super.onCpuCallBack(value, filePath) } override fun onFpsCallBack(value: Float, filePath: String) { super.onFpsCallBack(value, filePath) } override fun onMemoryCallBack(value: Float, filePath: String) { super.onMemoryCallBack(value, filePath) } override fun onNetworkCallBack(record: NetworkRecord) { super.onNetworkCallBack(record) } }) .netExtInterceptor(object : DokitExtInterceptor.DokitExtInterceptorProxy { override fun intercept(chain: Interceptor.Chain): Response { return chain.proceed(chain.request()) } }) .mcClientProcess(object : McClientProcessor { override fun process( activity: Activity?, view: View?, eventType: String, params: Map<String, String> ) { when (eventType) { "un_lock" -> { ToastUtils.showShort(params["unlock"]) } "lock_process" -> { val leftMargin = params["progress"]?.toInt() leftMargin?.let { if (view is SlideBar) { view.setMarginLeftExtra(it) } } } else -> { } } } }) .build() val client: OkHttpClient = OkHttpClient.Builder() .addInterceptor(CustomInterceptor()) .cache(Cache(File("${PathUtils.getInternalAppCachePath()}/dokit"), 1024 * 1024 * 100)) .build() OkGo.getInstance().init(this).okHttpClient = client val config = ImagePipelineConfig.newBuilder(this) .setDiskCacheEnabled(false) .build() Fresco.initialize(this, config) // PaymentConfiguration.init( // this, // "pk_test_TYooMQauvdEDq54NiTphI7jx" // ) //严格检查模式 //StrictMode.enableDefaults(); com.didichuxing.doraemonkit.util.LogUtils.getConfig() .setLogSwitch(true) // 设置是否输出到控制台开关,默认开 .setConsoleSwitch(true) // 设置 log 全局标签,默认为空,当全局标签不为空时,我们输出的 log 全部为该 tag, 为空时,如果传入的 tag 为空那就显示类名,否则显示 tag .setGlobalTag("Dokit") // 设置 log 头信息开关,默认为开 .setLogHeadSwitch(true) // 打印 log 时是否存到文件的开关,默认关 .setLog2FileSwitch(false) // 当自定义路径为空时,写入应用的/cache/log/目录中 .setDir("") // 当文件前缀为空时,默认为"util",即写入文件为"util-MM-dd.txt" .setFilePrefix("djx-table-log") // 输出日志是否带边框开关,默认开 .setBorderSwitch(true) // 一条日志仅输出一条,默认开,为美化 AS 3.1 的 Logcat .setSingleTagSwitch(false) // log 的控制台过滤器,和 logcat 过滤器同理,默认 Verbose .setConsoleFilter(LogUtils.V) // log 文件过滤器,和 logcat 过滤器同理,默认 Verbose .setFileFilter(LogUtils.E) // log 栈深度,默认为 1 .setStackDeep(1) .stackOffset = 1 } override fun attachBaseContext(base: Context) { super.attachBaseContext(base) MultiDex.install(this) } companion object { private const val TAG = "App" var leakActivity: Activity? = null } }
apache-2.0
70d9ab8a25fe9a3642b8e18b95eb0089
33.664865
98
0.58896
4.17513
false
false
false
false
cout970/Magneticraft
src/main/kotlin/com/cout970/magneticraft/systems/tilemodules/ModuleStackInventory.kt
2
6736
package com.cout970.magneticraft.systems.tilemodules import com.cout970.magneticraft.misc.add import com.cout970.magneticraft.misc.inventory.withSize import com.cout970.magneticraft.misc.network.IntSyncVariable import com.cout970.magneticraft.misc.network.SyncVariable import com.cout970.magneticraft.misc.newNbt import com.cout970.magneticraft.misc.world.dropItem import com.cout970.magneticraft.registry.ITEM_HANDLER import com.cout970.magneticraft.systems.config.Config import com.cout970.magneticraft.systems.gui.DATA_ID_ITEM_AMOUNT import com.cout970.magneticraft.systems.tileentities.IModule import com.cout970.magneticraft.systems.tileentities.IModuleContainer import net.minecraft.item.ItemStack import net.minecraft.nbt.NBTTagCompound import net.minecraft.tileentity.TileEntity import net.minecraft.util.EnumFacing import net.minecraftforge.common.capabilities.Capability import net.minecraftforge.items.IItemHandler import net.minecraftforge.items.ItemHandlerHelper import kotlin.math.min class ModuleStackInventory( val maxItems: Int, override val name: String = "module_stack_inventory" ) : IModule { override lateinit var container: IModuleContainer var stackType: ItemStack = ItemStack.EMPTY var amount: Int = 0 override fun onBreak() { if (stackType.isEmpty) return var items = min(amount, Config.containerMaxItemDrops) while (items > 0) { val stackSize = min(items, stackType.maxStackSize) world.dropItem(stackType.withSize(stackSize), pos) items -= stackType.maxStackSize } stackType = ItemStack.EMPTY } @Suppress("UNCHECKED_CAST") override fun <T> getCapability(cap: Capability<T>, facing: EnumFacing?): T? { if (cap == ITEM_HANDLER) { return ContainerCapabilityFilter(this.container.tile) as T } return null } fun getGuiInventory() = object : IItemHandler { override fun insertItem(slot: Int, stack: ItemStack, simulate: Boolean): ItemStack { if (slot != 0 || stack.isEmpty) return stack if (stackType.isEmpty) { // This doesn't handle the case where maxItems is less than 64 items if (!simulate) { stackType = stack.withSize(1) amount = stack.count container.sendUpdateToNearPlayers() } return ItemStack.EMPTY } if (ItemHandlerHelper.canItemStacksStack(stackType, stack)) { val space = maxItems - amount val toAdd = min(space, stack.count) val itemsLeft = stack.count - toAdd if (!simulate) { amount += toAdd } return if (itemsLeft == 0) ItemStack.EMPTY else stack.withSize(itemsLeft) } return stack } override fun getStackInSlot(slot: Int): ItemStack = when (slot) { 0 -> ItemStack.EMPTY else -> stackType.withSize(min(amount, 64)) } override fun getSlotLimit(slot: Int): Int = 64 override fun getSlots(): Int = 2 override fun extractItem(slot: Int, count: Int, simulate: Boolean): ItemStack { if (slot != 1 || stackType.isEmpty || amount == 0) return ItemStack.EMPTY val toExtract = min(min(count, amount), 64) if (toExtract <= 0) return ItemStack.EMPTY val result = stackType.withSize(toExtract) if (!simulate) { amount -= toExtract if (amount <= 0) { stackType = ItemStack.EMPTY container.sendUpdateToNearPlayers() } } return result } } override fun getGuiSyncVariables(): List<SyncVariable> { return listOf(IntSyncVariable( id = DATA_ID_ITEM_AMOUNT, getter = { amount }, setter = { amount = it } )) } override fun deserializeNBT(nbt: NBTTagCompound) { if (nbt.hasKey("amount")) { amount = nbt.getInteger("amount") stackType = ItemStack(nbt.getCompoundTag("stackType")) } } override fun serializeNBT(): NBTTagCompound = newNbt { add("amount", amount) add("stackType", stackType.serializeNBT()) } inner class ContainerCapabilityFilter(val parent: TileEntity) : IItemHandler { override fun insertItem(slot: Int, stack: ItemStack, simulate: Boolean): ItemStack { if (stackType.isEmpty) { // This doesn't handle the case where maxItems is less than 64 items if (!simulate) { stackType = stack.withSize(1) amount = stack.count container.sendUpdateToNearPlayers() } return ItemStack.EMPTY } if (ItemHandlerHelper.canItemStacksStack(stackType, stack)) { val space = maxItems - amount val toAdd = min(space, stack.count) val itemsLeft = stack.count - toAdd if (!simulate) { amount += toAdd } return if (itemsLeft == 0) ItemStack.EMPTY else stack.withSize(itemsLeft) } return stack } override fun getStackInSlot(slot: Int): ItemStack { if (stackType.isEmpty) return ItemStack.EMPTY return stackType.withSize(amount) } override fun getSlotLimit(slot: Int): Int = maxItems override fun getSlots(): Int = 1 override fun extractItem(slot: Int, count: Int, simulate: Boolean): ItemStack { if (stackType.isEmpty || amount == 0) return ItemStack.EMPTY val toExtract = min(min(count, amount), 64) if (toExtract <= 0) return ItemStack.EMPTY val result = stackType.withSize(toExtract) if (!simulate) { amount -= toExtract if (amount <= 0) { stackType = ItemStack.EMPTY container.sendUpdateToNearPlayers() } } return result } override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as ContainerCapabilityFilter if (this.parent != other.parent) return false return true } override fun hashCode(): Int { return javaClass.hashCode() * 31 + this.parent.hashCode() } } }
gpl-2.0
fb0b95e0e8294369cab1ece8d915162c
33.372449
92
0.591449
4.853026
false
false
false
false
bailuk/AAT
aat-gtk/src/main/kotlin/ch/bailu/aat_gtk/view/VerticalScrollView.kt
1
1194
package ch.bailu.aat_gtk.view import ch.bailu.aat_gtk.lib.extensions.margin import ch.bailu.aat_gtk.lib.extensions.setMarkup import ch.bailu.aat_gtk.view.description.DescriptionLabelTextView import ch.bailu.aat_lib.description.ContentDescription import ch.bailu.aat_lib.dispatcher.DispatcherInterface import ch.bailu.gtk.gtk.* import ch.bailu.gtk.type.Str abstract class VerticalScrollView() { companion object { const val MARGIN = 10 } val scrolled = ScrolledWindow() private val container = Box(Orientation.VERTICAL,5) init { scrolled.child = container } fun add(child: Widget) { child.margin(MARGIN) container.append(child) } fun add(text: String) { val label = Label(Str.NULL) label.setMarkup("<b>${text}</b>") add(label) } fun add(di: DispatcherInterface, desc: ContentDescription, vararg iid: Int) { val view = DescriptionLabelTextView(desc) add(view.layout) iid.forEach { di.addTarget(view, it) } } fun addAllContent(di: DispatcherInterface, descs: Array<ContentDescription>, vararg iid: Int) { descs.forEach { add(di, it, *iid) } } }
gpl-3.0
d781ed4de281c83bd48dae23ad464983
26.767442
99
0.675879
3.708075
false
false
false
false
wiltonlazary/kotlin-native
samples/libcurl/src/libcurlMain/kotlin/CUrl.kt
3
2105
/* * Copyright 2010-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/LICENSE.txt file. */ package sample.libcurl import kotlinx.cinterop.* import platform.posix.size_t import libcurl.* class CUrl(url: String) { private val stableRef = StableRef.create(this) private val curl = curl_easy_init() init { curl_easy_setopt(curl, CURLOPT_URL, url) val header = staticCFunction(::header_callback) curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, header) curl_easy_setopt(curl, CURLOPT_HEADERDATA, stableRef.asCPointer()) val writeData = staticCFunction(::write_callback) curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, writeData) curl_easy_setopt(curl, CURLOPT_WRITEDATA, stableRef.asCPointer()) } val header = Event<String>() val body = Event<String>() fun nobody(){ curl_easy_setopt(curl, CURLOPT_NOBODY, 1L) } fun fetch() { val res = curl_easy_perform(curl) if (res != CURLE_OK) println("curl_easy_perform() failed: ${curl_easy_strerror(res)?.toKString()}") } fun close() { curl_easy_cleanup(curl) stableRef.dispose() } } fun CPointer<ByteVar>.toKString(length: Int): String { val bytes = this.readBytes(length) return bytes.decodeToString() } fun header_callback(buffer: CPointer<ByteVar>?, size: size_t, nitems: size_t, userdata: COpaquePointer?): size_t { if (buffer == null) return 0u if (userdata != null) { val header = buffer.toKString((size * nitems).toInt()).trim() val curl = userdata.asStableRef<CUrl>().get() curl.header(header) } return size * nitems } fun write_callback(buffer: CPointer<ByteVar>?, size: size_t, nitems: size_t, userdata: COpaquePointer?): size_t { if (buffer == null) return 0u if (userdata != null) { val data = buffer.toKString((size * nitems).toInt()).trim() val curl = userdata.asStableRef<CUrl>().get() curl.body(data) } return size * nitems }
apache-2.0
a34a520c4d9bc5b191fc41f0ada93c2d
28.647887
114
0.643705
3.555743
false
false
false
false
DemonWav/IntelliJBukkitSupport
src/main/kotlin/translations/lang/LangCommenter.kt
1
545
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2021 minecraft-dev * * MIT License */ package com.demonwav.mcdev.translations.lang import com.intellij.lang.Commenter class LangCommenter : Commenter { override fun getLineCommentPrefix(): String? = "#" override fun getBlockCommentPrefix(): String? = null override fun getBlockCommentSuffix(): String? = null override fun getCommentedBlockCommentPrefix(): String? = null override fun getCommentedBlockCommentSuffix(): String? = null }
mit
34c309a4589f6301166e20a2e793c5d0
24.952381
65
0.730275
4.579832
false
false
false
false
xsota/hardcore
src/main/java/com/xsota/hardcore/commands/Selfharm.kt
1
835
package com.xsota.hardcore.commands import org.bukkit.command.Command import org.bukkit.command.CommandExecutor import org.bukkit.command.CommandSender import org.bukkit.entity.Player import org.bukkit.potion.PotionEffect import org.bukkit.potion.PotionEffectType class Selfharm : CommandExecutor { override fun onCommand(sender: CommandSender, command: Command, arg2: String, arg3: Array<String>): Boolean { var player: Player? = null if (sender is Player) { player = sender } if (player == null) { return false } if (command.name.equals("selfharm", ignoreCase = true)) { sender.sendMessage(player.name + "はどこからか取り出した毒を飲んだ") player.addPotionEffect(PotionEffect(PotionEffectType.POISON, 360000, 1)) return true } return false } }
mit
4679355e24a1acc6c3932b4fa0a964a9
24.903226
111
0.721046
3.805687
false
false
false
false
mix-it/mixit
src/main/kotlin/mixit/repository/TicketRepository.kt
1
1776
package mixit.repository import com.fasterxml.jackson.databind.ObjectMapper import com.fasterxml.jackson.module.kotlin.readValue import mixit.model.Ticket import org.slf4j.LoggerFactory import org.springframework.core.io.ClassPathResource import org.springframework.data.mongodb.core.ReactiveMongoTemplate import org.springframework.data.mongodb.core.count import org.springframework.data.mongodb.core.findAll import org.springframework.data.mongodb.core.findOne import org.springframework.data.mongodb.core.query.Criteria import org.springframework.data.mongodb.core.query.Query import org.springframework.data.mongodb.core.query.isEqualTo import org.springframework.data.mongodb.core.remove import org.springframework.stereotype.Repository @Repository class TicketRepository( private val template: ReactiveMongoTemplate, private val objectMapper: ObjectMapper ) { private val logger = LoggerFactory.getLogger(this.javaClass) fun initData() { if (count().block() == 0L) { val usersResource = ClassPathResource("data/ticket.json") val tickets: List<Ticket> = objectMapper.readValue(usersResource.inputStream) tickets.forEach { save(it).block() } logger.info("Ticket data initialization complete") } } fun count() = template.count<Ticket>() fun save(ticket: Ticket) = template.insert(ticket).doOnSuccess { _ -> logger.info("Save new ticket $ticket") } fun findAll() = template.findAll<Ticket>() fun deleteAll() = template.remove<Ticket>(Query()) fun deleteOne(id: String) = template.remove<Ticket>(Query(Criteria.where("_id").isEqualTo(id))) fun findByEmail(email: String) = template.findOne<Ticket>(Query(Criteria.where("email").isEqualTo(email))) }
apache-2.0
7dc53d98755c6696f30d5e0f3575bb2a
36.787234
110
0.751689
4.269231
false
false
false
false
apixandru/intellij-community
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/patterns/groovyPatterns.kt
10
1571
/* * Copyright 2000-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.plugins.groovy.lang.psi.patterns import com.intellij.openapi.util.Key import com.intellij.patterns.PatternCondition import com.intellij.util.ProcessingContext import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.GrListOrMap import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrCall import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression val closureCallKey = Key.create<GrCall>("groovy.pattern.closure.call") inline fun <reified T : GrExpression> groovyExpression() = GroovyExpressionPattern.Capture(T::class.java) fun groovyList() = groovyExpression<GrListOrMap>().with(object : PatternCondition<GrListOrMap>("isList") { override fun accepts(t: GrListOrMap, context: ProcessingContext?) = !t.isMap }) fun psiMethod(containingClass: String, vararg name: String) = GroovyPatterns.psiMethod().withName(*name).definedInClass(containingClass) fun groovyClosure() = GroovyClosurePattern()
apache-2.0
86dc1b2aaa9d1eb0428a11dffebb89ff
43.885714
136
0.788033
4.156085
false
false
false
false
vanita5/twittnuker
twittnuker/src/main/kotlin/de/vanita5/twittnuker/fragment/CustomTabsFragment.kt
1
23082
/* * Twittnuker - Twitter client for Android * * Copyright (C) 2013-2017 vanita5 <[email protected]> * * This program incorporates a modified version of Twidere. * Copyright (C) 2012-2017 Mariotaku Lee <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package de.vanita5.twittnuker.fragment import android.accounts.AccountManager import android.app.Dialog import android.content.ContentValues import android.content.Context import android.content.DialogInterface import android.content.Intent import android.database.Cursor import android.graphics.Paint import android.graphics.PorterDuff.Mode import android.os.Bundle import android.support.v4.app.Fragment import android.support.v4.app.LoaderManager.LoaderCallbacks import android.support.v4.content.CursorLoader import android.support.v4.content.Loader import android.support.v7.app.AlertDialog import android.util.SparseArray import android.view.* import android.widget.* import android.widget.AbsListView.MultiChoiceModeListener import android.widget.AdapterView.OnItemClickListener import com.bumptech.glide.Glide import com.mobeta.android.dslv.SimpleDragSortCursorAdapter import kotlinx.android.synthetic.main.dialog_custom_tab_editor.* import kotlinx.android.synthetic.main.layout_draggable_list_with_empty_view.* import kotlinx.android.synthetic.main.list_item_section_header.view.* import org.mariotaku.chameleon.Chameleon import org.mariotaku.ktextension.Bundle import org.mariotaku.ktextension.contains import org.mariotaku.ktextension.set import org.mariotaku.ktextension.spannable import org.mariotaku.library.objectcursor.ObjectCursor import org.mariotaku.sqliteqb.library.Columns.Column import org.mariotaku.sqliteqb.library.Expression import org.mariotaku.sqliteqb.library.RawItemArray import de.vanita5.twittnuker.R import de.vanita5.twittnuker.TwittnukerConstants.* import de.vanita5.twittnuker.activity.SettingsActivity import de.vanita5.twittnuker.adapter.AccountsSpinnerAdapter import de.vanita5.twittnuker.adapter.ArrayAdapter import de.vanita5.twittnuker.annotation.CustomTabType import de.vanita5.twittnuker.annotation.TabAccountFlags import de.vanita5.twittnuker.extension.applyTheme import de.vanita5.twittnuker.extension.model.isOfficial import de.vanita5.twittnuker.model.AccountDetails import de.vanita5.twittnuker.model.Tab import de.vanita5.twittnuker.model.tab.DrawableHolder import de.vanita5.twittnuker.model.tab.TabConfiguration import de.vanita5.twittnuker.model.tab.iface.AccountCallback import de.vanita5.twittnuker.model.util.AccountUtils import de.vanita5.twittnuker.provider.TwidereDataStore.Tabs import de.vanita5.twittnuker.util.CustomTabUtils import de.vanita5.twittnuker.util.ThemeUtils import de.vanita5.twittnuker.view.holder.TwoLineWithIconViewHolder import java.lang.ref.WeakReference class CustomTabsFragment : BaseFragment(), LoaderCallbacks<Cursor?>, MultiChoiceModeListener { private lateinit var adapter: CustomTabsAdapter override fun onActionItemClicked(mode: ActionMode, item: MenuItem): Boolean { when (item.itemId) { R.id.delete -> { val itemIds = listView.checkedItemIds val where = Expression.`in`(Column(Tabs._ID), RawItemArray(itemIds)) context.contentResolver.delete(Tabs.CONTENT_URI, where.sql, null) SettingsActivity.setShouldRestart(activity) } } mode.finish() return true } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) setHasOptionsMenu(true) adapter = CustomTabsAdapter(context) listView.choiceMode = ListView.CHOICE_MODE_MULTIPLE_MODAL listView.setMultiChoiceModeListener(this) listView.onItemClickListener = OnItemClickListener { _, _, position, _ -> val tab = adapter.getTab(position) val df = TabEditorDialogFragment() df.arguments = Bundle { this[EXTRA_OBJECT] = tab } df.show(fragmentManager, TabEditorDialogFragment.TAG_EDIT_TAB) } listView.adapter = adapter listView.emptyView = emptyView listView.setDropListener { from, to -> adapter.drop(from, to) if (listView.choiceMode != AbsListView.CHOICE_MODE_NONE) { listView.moveCheckState(from, to) } saveTabPositions() } emptyText.setText(R.string.no_tab) emptyIcon.setImageResource(R.drawable.ic_info_tab) loaderManager.initLoader(0, null, this) setListShown(false) } private fun setListShown(shown: Boolean) { listContainer.visibility = if (shown) View.VISIBLE else View.GONE progressContainer.visibility = if (shown) View.GONE else View.VISIBLE } override fun onCreateActionMode(mode: ActionMode, menu: Menu): Boolean { mode.menuInflater.inflate(R.menu.action_multi_select_items, menu) return true } override fun onCreateLoader(id: Int, args: Bundle?): Loader<Cursor?> { return CursorLoader(activity, Tabs.CONTENT_URI, Tabs.COLUMNS, null, null, Tabs.DEFAULT_SORT_ORDER) } override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { inflater.inflate(R.menu.menu_custom_tabs, menu) val context = this.context val accounts = AccountUtils.getAllAccountDetails(AccountManager.get(context), false) val itemAdd = menu.findItem(R.id.add_submenu) val theme = Chameleon.getOverrideTheme(context, context) if (itemAdd != null && itemAdd.hasSubMenu()) { val subMenu = itemAdd.subMenu subMenu.clear() for ((type, conf) in TabConfiguration.all()) { val accountRequired = TabAccountFlags.FLAG_ACCOUNT_REQUIRED in conf.accountFlags val subItem = subMenu.add(0, 0, conf.sortPosition, conf.name.createString(context)) val disabledByNoAccount = accountRequired && accounts.none(conf::checkAccountAvailability) val disabledByDuplicateTab = conf.isSingleTab && CustomTabUtils.isTabAdded(context, type) val shouldDisable = disabledByDuplicateTab || disabledByNoAccount subItem.isVisible = !shouldDisable subItem.isEnabled = !shouldDisable val icon = conf.icon.createDrawable(context) icon.mutate().setColorFilter(theme.textColorPrimary, Mode.SRC_ATOP) subItem.icon = icon val weakFragment = WeakReference(this) subItem.setOnMenuItemClickListener { val fragment = weakFragment.get()?.takeUnless(Fragment::isDetached) ?: return@setOnMenuItemClickListener false val adapter = fragment.adapter val fm = fragment.childFragmentManager val df = TabEditorDialogFragment() df.arguments = Bundle { this[EXTRA_TAB_TYPE] = type if (!adapter.isEmpty) { this[EXTRA_TAB_POSITION] = adapter.getTab(adapter.count - 1).position + 1 } } df.show(fm, TabEditorDialogFragment.TAG_ADD_TAB) return@setOnMenuItemClickListener true } } } } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { return inflater.inflate(R.layout.layout_draggable_list_with_empty_view, container, false) } override fun onDestroyActionMode(mode: ActionMode) { } override fun onItemCheckedStateChanged(mode: ActionMode, position: Int, id: Long, checked: Boolean) { updateTitle(mode) } override fun onLoaderReset(loader: Loader<Cursor?>) { adapter.changeCursor(null) } override fun onLoadFinished(loader: Loader<Cursor?>, cursor: Cursor?) { adapter.changeCursor(cursor) setListShown(true) } override fun onPrepareActionMode(mode: ActionMode, menu: Menu): Boolean { updateTitle(mode) return true } override fun onStop() { super.onStop() } private fun saveTabPositions() { val positions = adapter.cursorPositions val c = adapter.cursor if (positions != null && c != null && !c.isClosed) { val idIdx = c.getColumnIndex(Tabs._ID) for (i in 0 until positions.size) { c.moveToPosition(positions[i]) val id = c.getLong(idIdx) val values = ContentValues() values.put(Tabs.POSITION, i) val where = Expression.equals(Tabs._ID, id).sql context.contentResolver.update(Tabs.CONTENT_URI, values, where, null) } } SettingsActivity.setShouldRestart(activity) } private fun updateTitle(mode: ActionMode?) { if (listView == null || mode == null || activity == null) return val count = listView.checkedItemCount mode.title = resources.getQuantityString(R.plurals.Nitems_selected, count, count) } class TabEditorDialogFragment : BaseDialogFragment(), DialogInterface.OnShowListener, AccountCallback { private val activityResultMap: SparseArray<TabConfiguration.ExtraConfiguration> = SparseArray() override fun onShow(dialogInterface: DialogInterface) { val dialog = dialogInterface as AlertDialog dialog.applyTheme() @CustomTabType val tabType: String val tab: Tab val conf: TabConfiguration when (tag) { TAG_ADD_TAB -> { tabType = arguments.getString(EXTRA_TAB_TYPE) tab = Tab() conf = TabConfiguration.ofType(tabType)!! tab.type = tabType tab.icon = conf.icon.persistentKey tab.position = arguments.getInt(EXTRA_TAB_POSITION) } TAG_EDIT_TAB -> { tab = arguments.getParcelable(EXTRA_OBJECT) tabType = tab.type conf = TabConfiguration.ofType(tabType) ?: run { dismiss() return } } else -> { throw AssertionError() } } val tabName = dialog.tabName val iconSpinner = dialog.tabIconSpinner val accountSpinner = dialog.accountSpinner val accountContainer = dialog.accountContainer val extraConfigContainer = dialog.extraConfigContainer val positiveButton = dialog.getButton(DialogInterface.BUTTON_POSITIVE) val iconsAdapter = TabIconsAdapter(context) val accountsAdapter = AccountsSpinnerAdapter(context, requestManager = requestManager) iconSpinner.adapter = iconsAdapter accountSpinner.adapter = accountsAdapter iconsAdapter.setData(DrawableHolder.builtins()) tabName.hint = conf.name.createString(context) tabName.setText(tab.name) iconSpinner.setSelection(iconsAdapter.findPositionByKey(tab.icon)) val editMode = tag == TAG_EDIT_TAB val hasAccount = TabAccountFlags.FLAG_HAS_ACCOUNT in conf.accountFlags val accountMutable = TabAccountFlags.FLAG_ACCOUNT_MUTABLE in conf.accountFlags if (hasAccount && (accountMutable || !editMode)) { accountContainer.visibility = View.VISIBLE val accountRequired = TabAccountFlags.FLAG_ACCOUNT_REQUIRED in conf.accountFlags accountsAdapter.clear() if (!accountRequired) { accountsAdapter.add(AccountDetails.dummy()) } val officialKeyOnly = arguments.getBoolean(EXTRA_OFFICIAL_KEY_ONLY, false) accountsAdapter.addAll(AccountUtils.getAllAccountDetails(AccountManager.get(context), true).filter { if (officialKeyOnly && !it.isOfficial(context)) { return@filter false } return@filter conf.checkAccountAvailability(it) }) accountsAdapter.setDummyItemText(R.string.activated_accounts) tab.arguments?.accountKeys?.firstOrNull()?.let { key -> accountSpinner.setSelection(accountsAdapter.findPositionByKey(key)) } } else { accountContainer.visibility = View.GONE } val extraConfigurations = conf.getExtraConfigurations(context).orEmpty() fun inflateHeader(title: String): View { val headerView = LayoutInflater.from(context).inflate(R.layout.list_item_section_header, extraConfigContainer, false) headerView.sectionHeader.text = title return headerView } extraConfigurations.forEachIndexed { idx, extraConf -> extraConf.onCreate(context) extraConf.position = idx + 1 // Hide immutable settings in edit mode if (editMode && !extraConf.isMutable) return@forEachIndexed extraConf.headerTitle?.let { // Inflate header with headerTitle extraConfigContainer.addView(inflateHeader(it.createString(context))) } val view = extraConf.onCreateView(context, extraConfigContainer) extraConf.onViewCreated(context, view, this) conf.readExtraConfigurationFrom(tab, extraConf) extraConfigContainer.addView(view) } accountSpinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener { private fun updateExtraTabs(account: AccountDetails?) { extraConfigurations.forEach { it.onAccountSelectionChanged(account) } } override fun onItemSelected(parent: AdapterView<*>, view: View, pos: Int, id: Long) { val account = parent.selectedItem as? AccountDetails updateExtraTabs(account) } override fun onNothingSelected(view: AdapterView<*>) { } } positiveButton.setOnClickListener { tab.name = tabName.text.toString() tab.icon = (iconSpinner.selectedItem as DrawableHolder).persistentKey if (tab.arguments == null) { tab.arguments = CustomTabUtils.newTabArguments(tabType) } if (tab.extras == null) { tab.extras = CustomTabUtils.newTabExtras(tabType) } if (hasAccount && (!editMode || TabAccountFlags.FLAG_ACCOUNT_MUTABLE in conf.accountFlags)) { val account = accountSpinner.selectedItem as? AccountDetails ?: return@setOnClickListener if (!account.dummy) { tab.arguments?.accountKeys = arrayOf(account.key) } else { tab.arguments?.accountKeys = null } } extraConfigurations.forEach { extraConf -> // Make sure immutable configuration skipped in edit mode if (editMode && !extraConf.isMutable) return@forEach if (!conf.applyExtraConfigurationTo(tab, extraConf)) { val titleString = extraConf.title.createString(context) Toast.makeText(context, getString(R.string.message_tab_field_is_required, titleString), Toast.LENGTH_SHORT).show() return@setOnClickListener } } val valuesCreator = ObjectCursor.valuesCreatorFrom(Tab::class.java) when (tag) { TAG_EDIT_TAB -> { val where = Expression.equals(Tabs._ID, tab.id).sql context.contentResolver.update(Tabs.CONTENT_URI, valuesCreator.create(tab), where, null) } TAG_ADD_TAB -> { context.contentResolver.insert(Tabs.CONTENT_URI, valuesCreator.create(tab)) } } SettingsActivity.setShouldRestart(activity) dismiss() } } override fun getAccount(): AccountDetails? { return dialog.findViewById<Spinner>(R.id.accountSpinner).selectedItem as? AccountDetails } override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { val builder = AlertDialog.Builder(context) builder.setView(R.layout.dialog_custom_tab_editor) builder.setPositiveButton(R.string.action_save, null) builder.setNegativeButton(android.R.string.cancel, null) val dialog = builder.create() dialog.setOnShowListener(this) return dialog } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { val extraConf = activityResultMap.get(requestCode) activityResultMap.remove(requestCode) extraConf?.onActivityResult(this, requestCode and 0xFF, resultCode, data) } fun startExtraConfigurationActivityForResult(extraConf: TabConfiguration.ExtraConfiguration, intent: Intent, requestCode: Int) { val requestCodeInternal = extraConf.position shl 8 and 0xFF00 or (requestCode and 0xFF) activityResultMap.put(requestCodeInternal, extraConf) startActivityForResult(intent, requestCodeInternal) } companion object { const val TAG_EDIT_TAB = "edit_tab" const val TAG_ADD_TAB = "add_tab" } } internal class TabIconsAdapter(context: Context) : ArrayAdapter<DrawableHolder>(context, R.layout.spinner_item_custom_tab_icon) { private val iconColor: Int = ThemeUtils.getThemeForegroundColor(context) init { setDropDownViewResource(R.layout.list_item_two_line_small) } override fun getDropDownView(position: Int, convertView: View?, parent: ViewGroup): View { val view = super.getDropDownView(position, convertView, parent) view.findViewById<View>(android.R.id.text2).visibility = View.GONE val text1 = view.findViewById<TextView>(android.R.id.text1) val item = getItem(position) text1.spannable = item.name bindIconView(item, view) return view } override fun getView(position: Int, convertView: View?, parent: ViewGroup): View { val view = super.getView(position, convertView, parent) bindIconView(getItem(position), view) return view } fun setData(list: List<DrawableHolder>?) { clear() if (list == null) return addAll(list) } private fun bindIconView(item: DrawableHolder, view: View) { val icon = view.findViewById<ImageView>(android.R.id.icon) icon.setColorFilter(iconColor, Mode.SRC_ATOP) icon.setImageDrawable(item.createDrawable(icon.context)) } fun findPositionByKey(key: String): Int { return (0 until count).indexOfFirst { getItem(it).persistentKey == key } } } class CustomTabsAdapter(context: Context) : SimpleDragSortCursorAdapter(context, R.layout.list_item_custom_tab, null, emptyArray(), intArrayOf(), 0) { private val iconColor: Int = ThemeUtils.getThemeForegroundColor(context) private val tempTab: Tab = Tab() private var indices: ObjectCursor.CursorIndices<Tab>? = null override fun bindView(view: View, context: Context?, cursor: Cursor) { super.bindView(view, context, cursor) val holder = view.tag as TwoLineWithIconViewHolder indices?.parseFields(tempTab, cursor) val type = tempTab.type val name = tempTab.name val iconKey = tempTab.icon if (type != null && CustomTabUtils.isTabTypeValid(type)) { val typeName = CustomTabUtils.getTabTypeName(context, type) holder.text1.spannable = name?.takeIf(String::isNotEmpty) ?: typeName holder.text1.paintFlags = holder.text1.paintFlags and Paint.STRIKE_THRU_TEXT_FLAG.inv() holder.text2.visibility = View.VISIBLE holder.text2.text = typeName } else { holder.text1.spannable = name holder.text1.paintFlags = holder.text1.paintFlags or Paint.STRIKE_THRU_TEXT_FLAG holder.text2.setText(R.string.invalid_tab) } val icon = CustomTabUtils.getTabIconDrawable(context, DrawableHolder.parse(iconKey)) holder.icon.visibility = View.VISIBLE if (icon != null) { holder.icon.setImageDrawable(icon) } else { holder.icon.setImageResource(R.drawable.ic_action_list) } holder.icon.setColorFilter(iconColor, Mode.SRC_ATOP) } override fun changeCursor(cursor: Cursor?) { indices = cursor?.let { ObjectCursor.indicesFrom(it, Tab::class.java) } super.changeCursor(cursor) } override fun newView(context: Context?, cursor: Cursor?, parent: ViewGroup): View { val view = super.newView(context, cursor, parent) val tag = view.tag if (tag !is TwoLineWithIconViewHolder) { val holder = TwoLineWithIconViewHolder(view) view.tag = holder } return view } fun getTab(position: Int): Tab { cursor.moveToPosition(position) return indices!!.newObject(cursor) } } }
gpl-3.0
9b41a78a08a3f4519c7a0f2f08aa5f9e
42.305816
136
0.625726
4.967076
false
false
false
false
Karma-Maker/gyg_test
app/src/main/java/space/serenity/berlinviewer/ui/providers/ReviewsProvider.kt
1
4681
package space.serenity.berlinviewer.ui.providers import retrofit2.Call import retrofit2.Callback import retrofit2.Response import space.serenity.berlinviewer.model.GYGReviewListResponse import space.serenity.berlinviewer.model.RestAPI import space.serenity.berlinviewer.model.Review import java.util.* /** * Created by karmamaker on 01/06/2017. */ class ReviewsProvider { private val source = ArrayList<Any>() // private val myReview : Review? = null private var dataPadding: Int = 0 // Number of items before first item in source private var lastLoadedPageSize = PAGE_SIZE internal var api = RestAPI() var dataSetChangeListener: () -> Unit = {} private var lastRequestFailed: Boolean = false private var currCall: Call<GYGReviewListResponse>? = null fun init() { clear() currCall = requestPage(0, PAGE_SIZE, callback) source.add(ITEM_LOADING_FULLSCREEN) } fun clear() { dataPadding = 0 lastLoadedPageSize = PAGE_SIZE val savedCall = currCall if (savedCall != null) { savedCall.cancel() currCall = null } } private val isFullyLoaded: Boolean get() = lastLoadedPageSize != PAGE_SIZE private fun requestPage(pageNumber: Int, pageSize: Int, callback: Callback<GYGReviewListResponse>): Call<GYGReviewListResponse> { val call = api.getReviews(pageNumber, pageSize) call.enqueue(callback) return call } private val callback: Callback<GYGReviewListResponse> get() = object : Callback<GYGReviewListResponse> { override fun onResponse(call: Call<GYGReviewListResponse>, response: Response<GYGReviewListResponse>) { beforeResponse() if (response.body() != null) { addPage(response.body().data) onFinish() } else { onFailure(call, Throwable("Bad response from server")) } lastRequestFailed = false } override fun onFailure(call: Call<GYGReviewListResponse>, t: Throwable) { beforeResponse() if (source.isEmpty()) { source.add(ITEM_NO_CONNECTION_FULLSCREEN) } else { source.add(ITEM_NO_CONNECTION_SMALL) } lastRequestFailed = true onFinish() } private fun onFinish() { currCall = null notifyDataSetChanged() } private fun beforeResponse() { source.remove(ITEM_NO_CONNECTION_FULLSCREEN) // Not reliable but let it be for the time beeng source.remove(ITEM_NO_CONNECTION_SMALL) source.remove(ITEM_LOADING) source.remove(ITEM_LOADING_FULLSCREEN) } } private fun notifyDataSetChanged() { dataSetChangeListener.invoke(); } operator fun get(position: Int): Any { val currentPage = (position + dataPadding) / PAGE_SIZE if (!lastRequestFailed && source.any { it is Review } && currCall == null && shouldRequestNextPage(position)) { source.remove(ITEM_NO_CONNECTION_FULLSCREEN) // Not reliable but let it be for the time beeng source.remove(ITEM_NO_CONNECTION_SMALL) source.remove(ITEM_LOADING_FULLSCREEN) source.add(ITEM_LOADING) currCall = requestPage(currentPage + 1, PAGE_SIZE, callback) } return source[position] } val count: Int get() = source.size private fun shouldRequestNextPage(position: Int): Boolean { return !isFullyLoaded && source.size - ITEMS_BEFORE_NEXT_REQUEST < position && currCall == null } private fun addPage(loadedPage: MutableList<Review>) { lastLoadedPageSize = loadedPage.size val dataSizeWithDuplicates = loadedPage.size loadedPage.removeAll(source) dataPadding += dataSizeWithDuplicates - loadedPage.size source.addAll(source.size, loadedPage) } companion object { val PAGE_SIZE = 32 // This value should be received from server val ITEMS_BEFORE_NEXT_REQUEST = 24 // This value should be received from server val ITEM_LOADING = "LOADING" val ITEM_LOADING_FULLSCREEN = "LOADING_FULLSCREEN" val ITEM_NO_REVIEWS = "NO_REVIEWS" val ITEM_NO_CONNECTION_SMALL = "NO_CONNECTION_SMALL " val ITEM_NO_CONNECTION_FULLSCREEN = "NO_CONNECTION_FULLSCREEN" } }
mit
86cbd37b9a401f8dc194af2e4cdae787
32.683453
133
0.60799
4.704523
false
false
false
false
stripe/stripe-android
identity/src/main/java/com/stripe/android/identity/analytics/ScreenTracker.kt
1
2804
package com.stripe.android.identity.analytics import android.util.Log import com.stripe.android.camera.framework.StatTracker import com.stripe.android.camera.framework.time.Clock import com.stripe.android.camera.framework.time.ClockMark import com.stripe.android.identity.injection.IdentityVerificationScope import com.stripe.android.identity.networking.IdentityRepository import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.launch import javax.inject.Inject /** * Tracker for screen transition. */ @IdentityVerificationScope internal class ScreenTracker @Inject constructor( private val identityAnalyticsRequestFactory: IdentityAnalyticsRequestFactory, private val identityRepository: IdentityRepository ) { private var screenStatTracker: ScreenTransitionStatTracker? = null /** * Start screen transition, if there is a pending start transition drop it. */ fun screenTransitionStart( fromScreenName: String? = null, startedAt: ClockMark = Clock.markNow() ) { // create a StatTracker with fromScreenName // if there is a screen already started, drop it screenStatTracker?.let { Log.e( TAG, "screenStateTracker is already set with ${it.fromScreenName}, when another " + "screenTransition starts from $fromScreenName, dropping the old screenStateTracker." ) } screenStatTracker = ScreenTransitionStatTracker(startedAt, fromScreenName) { toScreenName -> identityRepository.sendAnalyticsRequest( identityAnalyticsRequestFactory.timeToScreen( value = startedAt.elapsedSince().inMilliseconds.toLong(), fromScreenName = fromScreenName, toScreenName = requireNotNull(toScreenName) ) ) } } /** * Finish screen transition and send analytics event for the transition. */ suspend fun screenTransitionFinish(toScreenName: String) { screenStatTracker?.let { it.trackResult(toScreenName) screenStatTracker = null } ?: run { Log.e( TAG, "screenStateTracker is not set when screenTransition ends at $toScreenName" ) } } private companion object { val TAG: String = ScreenTracker::class.java.simpleName } } private class ScreenTransitionStatTracker( override val startedAt: ClockMark, val fromScreenName: String?, private val onComplete: suspend (String?) -> Unit ) : StatTracker { override suspend fun trackResult(result: String?) = coroutineScope { launch { onComplete(result) } }.let { } }
mit
2566fbe689bdc91f902b9c0f5c6ba3d1
34.05
104
0.663338
5.163904
false
false
false
false
stripe/stripe-android
stripe-core/src/main/java/com/stripe/android/core/model/StripeJsonUtils.kt
1
11189
package com.stripe.android.core.model import androidx.annotation.RestrictTo import androidx.annotation.Size import org.json.JSONArray import org.json.JSONException import org.json.JSONObject /** * A set of JSON parsing utility functions. */ @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) object StripeJsonUtils { private const val NULL = "null" /** * Calls through to [JSONObject.optBoolean] only in the case that the * key exists. This returns `null` if the key is not in the object. * * @param jsonObject the input object * @param fieldName the required field name * @return the value stored in the requested field, or `false` if the key is not present */ @JvmSynthetic fun optBoolean( jsonObject: JSONObject, @Size(min = 1) fieldName: String ): Boolean { return jsonObject.has(fieldName) && jsonObject.optBoolean(fieldName, false) } /** * Calls through to [JSONObject.optInt] only in the case that the * key exists. This returns `null` if the key is not in the object. * * @param jsonObject the input object * @param fieldName the required field name * @return the value stored in the requested field, or `null` if the key is not present */ @JvmSynthetic fun optInteger( jsonObject: JSONObject, @Size(min = 1) fieldName: String ): Int? { return if (!jsonObject.has(fieldName)) { null } else { jsonObject.optInt(fieldName) } } /** * Calls through to [JSONObject.optLong] only in the case that the * key exists. This returns `null` if the key is not in the object. * * @param jsonObject the input object * @param fieldName the required field name * @return the value stored in the requested field, or `null` if the key is not present */ @JvmSynthetic fun optLong( jsonObject: JSONObject, @Size(min = 1) fieldName: String ): Long? { return if (!jsonObject.has(fieldName)) { null } else { jsonObject.optLong(fieldName) } } /** * Calls through to [JSONObject.optString] while safely * converting the raw string "null" and the empty string to `null`. Will not throw * an exception if the field isn't found. * * @param jsonObject the input object * @param fieldName the optional field name * @return the value stored in the field, or `null` if the field isn't present */ @JvmStatic fun optString( jsonObject: JSONObject?, @Size(min = 1) fieldName: String ): String? { return nullIfNullOrEmpty(jsonObject?.optString(fieldName)) } /** * Calls through to [JSONObject.optString] while safely converting * the raw string "null" and the empty string to `null`, along with any value that isn't * a two-character string. * @param jsonObject the object from which to retrieve the country code * @param fieldName the name of the field in which the country code is stored * @return a two-letter country code if one is found, or `null` */ @JvmSynthetic @Size(2) fun optCountryCode( jsonObject: JSONObject, @Size(min = 1) fieldName: String ): String? { val value = nullIfNullOrEmpty(jsonObject.optString(fieldName)) return value?.takeIf { it.length == 2 } } /** * Calls through to [JSONObject.optString] while safely converting * the raw string "null" and the empty string to `null`, along with any value that isn't * a three-character string. * @param jsonObject the object from which to retrieve the currency code * @param fieldName the name of the field in which the currency code is stored * @return a three-letter currency code if one is found, or `null` */ @JvmStatic @Size(3) fun optCurrency( jsonObject: JSONObject, @Size(min = 1) fieldName: String ): String? { val value = nullIfNullOrEmpty(jsonObject.optString(fieldName)) return value?.takeIf { it.length == 3 } } /** * Calls through to [JSONObject.optJSONObject] and then uses [jsonObjectToMap] on the result. * * @param jsonObject the input object * @param fieldName the required field name * @return the value stored in the requested field, or `null` if the key is not present */ @JvmSynthetic fun optMap( jsonObject: JSONObject, @Size(min = 1) fieldName: String ): Map<String, Any?>? { return jsonObject.optJSONObject(fieldName)?.let { jsonObjectToMap(it) } } /** * Calls through to [JSONObject.optJSONObject] and then uses [jsonObjectToStringMap] on the result. * * @param jsonObject the input object * @param fieldName the required field name * @return the value stored in the requested field, or `null` if the key is not present */ @JvmSynthetic fun optHash( jsonObject: JSONObject, @Size(min = 1) fieldName: String ): Map<String, String>? { return jsonObject.optJSONObject(fieldName)?.let { jsonObjectToStringMap(it) } } /** * Convert a [JSONObject] to a [Map]. * * @param jsonObject a [JSONObject] to be converted * @return a [Map] representing the input, or `null` if the input is `null` */ @JvmSynthetic fun jsonObjectToMap(jsonObject: JSONObject?): Map<String, Any?>? { if (jsonObject == null) { return null } val keys = jsonObject.names() ?: JSONArray() return (0 until keys.length()) .map { idx -> keys.getString(idx) } .mapNotNull { key -> jsonObject.opt(key)?.let { value -> if (value != NULL) { mapOf( key to when (value) { is JSONObject -> jsonObjectToMap(value) is JSONArray -> jsonArrayToList(value) else -> value } ) } else { null } } } .fold(emptyMap()) { acc, map -> acc.plus(map) } } /** * Convert a [JSONObject] to a flat, string-keyed and string-valued map. All values * are recorded as strings. * * @param jsonObject the input [JSONObject] to be converted * @return a [Map] representing the input, or `null` if the input is `null` */ @JvmSynthetic fun jsonObjectToStringMap(jsonObject: JSONObject?): Map<String, String>? { if (jsonObject == null) { return null } val keys = jsonObject.names() ?: JSONArray() return (0 until keys.length()) .map { keys.getString(it) } .mapNotNull { key -> val value = jsonObject.opt(key) if (value != null && value != NULL) { mapOf(key to value.toString()) } else { null } } .fold(emptyMap()) { acc, map -> acc.plus(map) } } /** * Converts a [JSONArray] to a [List]. * * @param jsonArray a [JSONArray] to be converted * @return a [List] representing the input, or `null` if said input is `null` */ @JvmSynthetic fun jsonArrayToList(jsonArray: JSONArray?): List<Any>? { if (jsonArray == null) { return null } return (0 until jsonArray.length()) .map { idx -> jsonArray.get(idx) } .mapNotNull { ob -> if (ob is JSONArray) { jsonArrayToList(ob) } else if (ob is JSONObject) { jsonObjectToMap(ob) } else { if (ob == NULL) { null } else { ob } } } } /** * Converts a string-keyed [Map] into a [JSONObject]. This will cause a * [ClassCastException] if any sub-map has keys that are not [Strings][String]. * * @param mapObject the [Map] that you'd like in JSON form * @return a [JSONObject] representing the input map, or `null` if the input * object is `null` */ @Suppress("NestedBlockDepth") fun mapToJsonObject(mapObject: Map<String, *>?): JSONObject? { if (mapObject == null) { return null } val jsonObject = JSONObject() for (key in mapObject.keys) { val value = mapObject[key] ?: continue try { if (value is Map<*, *>) { try { val mapValue = value as Map<String, Any> jsonObject.put(key, mapToJsonObject(mapValue)) } catch (classCastException: ClassCastException) { // don't include the item in the JSONObject if the keys are not Strings } } else if (value is List<*>) { jsonObject.put(key, listToJsonArray(value as List<Any>)) } else if (value is Number || value is Boolean) { jsonObject.put(key, value) } else { jsonObject.put(key, value.toString()) } } catch (jsonException: JSONException) { // Simply skip this value } } return jsonObject } /** * Converts a [List] into a [JSONArray]. A [ClassCastException] will be * thrown if any object in the list (or any sub-list or sub-map) is a [Map] whose keys * are not [Strings][String]. * * @param values a [List] of values to be put in a [JSONArray] * @return a [JSONArray], or `null` if the input was `null` */ private fun listToJsonArray(values: List<*>?): JSONArray? { if (values == null) { return null } val jsonArray = JSONArray() values.forEach { objVal -> val jsonVal = if (objVal is Map<*, *>) { // We are ignoring type erasure here and crashing on bad input. // Now that this method is not public, we have more control on what is // passed to it. mapToJsonObject(objVal as Map<String, Any>) } else if (objVal is List<*>) { listToJsonArray(objVal) } else if (objVal is Number || objVal is Boolean) { objVal } else { objVal.toString() } jsonArray.put(jsonVal) } return jsonArray } @JvmSynthetic fun nullIfNullOrEmpty(possibleNull: String?): String? { return possibleNull?.let { s -> s.takeUnless { NULL == it || it.isEmpty() } } } }
mit
842c7b266aba64325036da7b5d44cf1f
33.112805
103
0.547949
4.68159
false
false
false
false
ryan652/EasyCrypt
easycrypt/src/main/java/com/pvryan/easycrypt/randomorg/RandomOrg.kt
1
772
package com.pvryan.easycrypt.randomorg import retrofit2.Callback import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory internal class RandomOrg { companion object { internal fun request(apiKey: String, passLength: Int, callback: Callback<RandomOrgResponse>) { val retrofit = Retrofit.Builder().baseUrl(RandomOrgApis.BASE_URL) .addConverterFactory(GsonConverterFactory.create()).build() val randomOrgApis: RandomOrgApis = retrofit.create(RandomOrgApis::class.java) val params = RandomOrgRequest.Params(apiKey = apiKey, n = passLength / 2) val post = RandomOrgRequest(params = params) randomOrgApis.request(post).enqueue(callback) } } }
apache-2.0
b57d84919ea73050004b2f441d1a5474
31.166667
102
0.696891
4.568047
false
false
false
false
androidx/androidx
compose/ui/ui/src/androidAndroidTest/kotlin/androidx/compose/ui/layout/LookaheadLayoutTest.kt
3
48590
/* * 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. */ @file:OptIn(ExperimentalComposeUiApi::class) package androidx.compose.ui.layout import androidx.activity.ComponentActivity import androidx.compose.animation.core.Animatable import androidx.compose.animation.core.AnimationVector2D import androidx.compose.animation.core.VectorConverter import androidx.compose.animation.core.tween import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Arrangement.Absolute.SpaceAround import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.IntrinsicSize import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.aspectRatio import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.offset import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.requiredHeight import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.sizeIn import androidx.compose.foundation.layout.width import androidx.compose.foundation.layout.widthIn import androidx.compose.foundation.layout.wrapContentHeight import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.collection.MutableVector import androidx.compose.runtime.collection.mutableVectorOf import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.ExperimentalComposeUiApi import androidx.compose.ui.Modifier import androidx.compose.ui.composed import androidx.compose.ui.geometry.Offset import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.Matrix import androidx.compose.ui.platform.AndroidOwnerExtraAssertionsRule import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.test.junit4.createAndroidComposeRule import androidx.compose.ui.unit.Constraints import androidx.compose.ui.unit.Density import androidx.compose.ui.unit.IntSize import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.filters.MediumTest import java.lang.Integer.max import junit.framework.TestCase.assertEquals import junit.framework.TestCase.assertTrue import kotlin.math.roundToInt import kotlinx.coroutines.launch import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith const val Debug = false @MediumTest @RunWith(AndroidJUnit4::class) class LookaheadLayoutTest { @get:Rule val rule = createAndroidComposeRule<ComponentActivity>() @get:Rule val excessiveAssertions = AndroidOwnerExtraAssertionsRule() @Test fun lookaheadLayoutAnimation() { var isLarge by mutableStateOf(true) var size1 = IntSize.Zero var size2 = IntSize.Zero rule.setContent { CompositionLocalProvider(LocalDensity provides Density(1f)) { LookaheadLayout( measurePolicy = { measurables, constraints -> val placeables = measurables.map { it.measure(constraints) } val maxWidth: Int = placeables.maxOf { it.width } val maxHeight = placeables.maxOf { it.height } // Position the children. layout(maxWidth, maxHeight) { placeables.forEach { it.place(0, 0) } } }, content = { Row(if (isLarge) Modifier.size(200.dp) else Modifier.size(50.dp, 100.dp)) { Box( Modifier .fillMaxHeight() .weight(2f) .onSizeChanged { size1 = it } .animateSize(this@LookaheadLayout)) Box( Modifier .fillMaxHeight() .weight(3f) .onSizeChanged { size2 = it } .animateSize(this@LookaheadLayout)) } } ) } } // Check that: // 1) size changes happen when parent constraints change, // 2) animations finish and actual measurements get updated by animation, // 3) during the animation the tree is consistent. rule.runOnIdle { assertEquals(IntSize(80, 200), size1) assertEquals(IntSize(120, 200), size2) isLarge = false } rule.runOnIdle { assertEquals(IntSize(20, 100), size1) assertEquals(IntSize(30, 100), size2) isLarge = true } rule.runOnIdle { assertEquals(IntSize(80, 200), size1) assertEquals(IntSize(120, 200), size2) } } private fun Modifier.animateSize(scope: LookaheadLayoutScope): Modifier = composed { val cScope = rememberCoroutineScope() var anim: Animatable<IntSize, AnimationVector2D>? by remember { mutableStateOf(null) } with(scope) { [email protected]( measure = { measurable, _, size -> anim = anim?.apply { cScope.launch { animateTo(size, tween(200)) } } ?: Animatable(size, IntSize.VectorConverter) val (width, height) = anim!!.value val placeable = measurable.measure(Constraints.fixed(width, height)) layout(placeable.width, placeable.height) { placeable.place(0, 0) } } ) } } @Test fun nestedLookaheadLayoutTest() { var parentLookaheadMeasure = 0 var childLookaheadMeasure = 0 var parentLookaheadPlace = 0 var childLookaheadPlace = 0 var parentMeasure = 0 var childMeasure = 0 var parentPlace = 0 var childPlace = 0 var rootPreMeasure = 0 var rootPrePlace = 0 var rootPostMeasure = 0 var rootPostPlace = 0 var counter = 0 rule.setContent { // The right sequence for this nested lookahead layout setup: // parentLookaheadMeasure -> childLookaheadMeasure -> parentMeasure -> childMeasure // -> parentLookaheadPlace -> childLookaheadPlace -> -> parentPlace -> childPlace // Each event should happen exactly once in the end. Box(Modifier.layout( measureWithLambdas( preMeasure = { rootPreMeasure = ++counter }, postMeasure = { rootPostMeasure = ++counter }, prePlacement = { rootPrePlace = ++counter }, postPlacement = { rootPostPlace = ++counter } ) )) { MyLookaheadLayout { Box( Modifier .padding(top = 100.dp) .fillMaxSize() .intermediateLayout( measure = { measurable, constraints, _ -> measureWithLambdas( preMeasure = { parentMeasure = ++counter }, prePlacement = { parentPlace = ++counter } ).invoke(this, measurable, constraints) } ) .layout( measureWithLambdas( preMeasure = { if (parentLookaheadMeasure == 0) { // Only the first invocation is for lookahead parentLookaheadMeasure = ++counter } }, prePlacement = { if (parentLookaheadPlace == 0) { // Only the first invocation is for lookahead parentLookaheadPlace = ++counter } } ) ) ) { MyLookaheadLayout { Column { Box( Modifier .size(100.dp) .background(Color.Red) .intermediateLayout { measurable, constraints, _ -> measureWithLambdas( preMeasure = { childMeasure = ++counter }, prePlacement = { childPlace = ++counter } ).invoke(this, measurable, constraints) } .layout( measure = measureWithLambdas( preMeasure = { if (childLookaheadMeasure == 0) { childLookaheadMeasure = ++counter } }, prePlacement = { if (childLookaheadPlace == 0) { childLookaheadPlace = ++counter } } ) ) ) Box( Modifier .size(100.dp) .background(Color.Green) ) } } } } } } rule.runOnIdle { assertEquals(1, rootPreMeasure) assertEquals(2, parentLookaheadMeasure) assertEquals(3, childLookaheadMeasure) assertEquals(4, parentMeasure) assertEquals(5, childMeasure) assertEquals(6, rootPostMeasure) // Measure finished. Then placement. assertEquals(7, rootPrePlace) assertEquals(8, parentLookaheadPlace) assertEquals(9, childLookaheadPlace) assertEquals(10, parentPlace) assertEquals(11, childPlace) assertEquals(12, rootPostPlace) } } @Test fun parentObserveActualMeasurementTest() { val width = 200 val height = 120 var scaleFactor by mutableStateOf(0.1f) var parentSize = IntSize.Zero var grandParentSize = IntSize.Zero var greatGrandParentSize = IntSize.Zero rule.setContent { CompositionLocalProvider(LocalDensity provides Density(1f)) { Column( Modifier.layout(measureWithLambdas(postMeasure = { greatGrandParentSize = it })) ) { Row( Modifier.layout(measureWithLambdas(postMeasure = { grandParentSize = it })) ) { Box( Modifier.layout(measureWithLambdas(postMeasure = { parentSize = it })) ) { MyLookaheadLayout { Box(modifier = Modifier .intermediateLayout { measurable, constraints, lookaheadSize -> assertEquals(width, lookaheadSize.width) assertEquals(height, lookaheadSize.height) val placeable = measurable.measure(constraints) layout( (scaleFactor * width).roundToInt(), (scaleFactor * height).roundToInt() ) { placeable.place(0, 0) } } .size(width.dp, height.dp)) } } Spacer(modifier = Modifier.size(20.dp)) } Spacer(modifier = Modifier.size(50.dp)) } } } val size = IntSize(width, height) repeat(20) { rule.runOnIdle { assertEquals(size * scaleFactor, parentSize) assertEquals((size * scaleFactor).width + 20, grandParentSize.width) assertEquals(max((size * scaleFactor).height, 20), grandParentSize.height) assertEquals(max(grandParentSize.width, 50), greatGrandParentSize.width) assertEquals(grandParentSize.height + 50, greatGrandParentSize.height) scaleFactor += 0.1f } } } private operator fun IntSize.times(multiplier: Float): IntSize = IntSize((width * multiplier).roundToInt(), (height * multiplier).roundToInt()) @Test fun noExtraLookaheadTest() { var parentMeasure = 0 var parentPlace = 0 var measurePlusLookahead = 0 var placePlusLookahead = 0 var measure = 0 var place = 0 var isSmall by mutableStateOf(true) var controlGroupEnabled by mutableStateOf(true) var controlGroupParentMeasure = 0 var controlGroupParentPlace = 0 var controlGroupMeasure = 0 var controlGroupPlace = 0 rule.setContent { if (controlGroupEnabled) { Box( Modifier.layout( measureWithLambdas( postMeasure = { controlGroupParentMeasure++ }, postPlacement = { controlGroupParentPlace++ } ) ) ) { Layout(measurePolicy = defaultMeasurePolicy, content = { Box( Modifier .size(if (isSmall) 100.dp else 200.dp) .layout( measureWithLambdas( postMeasure = { controlGroupMeasure++ }, postPlacement = { controlGroupPlace++ }, ) ) ) }) } } else { Box( Modifier.layout( measureWithLambdas( postMeasure = { parentMeasure++ }, postPlacement = { parentPlace++ } ) ) ) { MyLookaheadLayout { Box( Modifier .size(if (isSmall) 100.dp else 200.dp) .animateSize(this) .layout( measureWithLambdas( postMeasure = { measurePlusLookahead++ }, postPlacement = { placePlusLookahead++ }, ) ) .intermediateLayout { measurable, constraints, _ -> measureWithLambdas( postMeasure = { measure++ }, postPlacement = { place++ } ).invoke(this, measurable, constraints) } ) } } } } rule.runOnIdle { assertEquals(1, controlGroupParentMeasure) assertEquals(1, controlGroupParentPlace) assertEquals(1, controlGroupMeasure) assertEquals(1, controlGroupPlace) isSmall = !isSmall } rule.runOnIdle { // Check the starting condition before switching over from control group assertEquals(0, parentMeasure) assertEquals(0, parentPlace) assertEquals(0, measurePlusLookahead) assertEquals(0, placePlusLookahead) assertEquals(0, measure) assertEquals(0, place) // Switch to LookaheadLayout controlGroupEnabled = !controlGroupEnabled } rule.runOnIdle { // Expects 1 assertEquals(1, parentMeasure) assertEquals(1, parentPlace) val lookaheadMeasure = measurePlusLookahead - measure val lookaheadPlace = placePlusLookahead - place assertEquals(1, lookaheadMeasure) assertEquals(1, lookaheadPlace) } // Pump frames so that animation triggered measurements are not completely dependent on // system timing. rule.mainClock.autoAdvance = false rule.runOnIdle { isSmall = !isSmall } repeat(10) { rule.mainClock.advanceTimeByFrame() rule.waitForIdle() } rule.mainClock.autoAdvance = true rule.runOnIdle { // Compare number of lookahead measurements & placements with control group. assertEquals(controlGroupParentMeasure, parentMeasure) assertEquals(controlGroupParentPlace, parentPlace) val lookaheadMeasure = measurePlusLookahead - measure val lookaheadPlace = placePlusLookahead - place assertEquals(controlGroupMeasure, lookaheadMeasure) assertEquals(controlGroupPlace, lookaheadPlace) assertTrue(lookaheadMeasure < measure) assertTrue(lookaheadPlace < place) } } @Test fun lookaheadStaysTheSameDuringAnimationTest() { var isLarge by mutableStateOf(true) var parentLookaheadSize = IntSize.Zero var child1LookaheadSize = IntSize.Zero var child2LookaheadSize = IntSize.Zero rule.setContent { LookaheadLayout( measurePolicy = { measurables, constraints -> val placeables = measurables.map { it.measure(constraints) } val maxWidth: Int = placeables.maxOf { it.width } val maxHeight = placeables.maxOf { it.height } // Position the children. layout(maxWidth, maxHeight) { placeables.forEach { it.place(0, 0) } } }, content = { CompositionLocalProvider(LocalDensity provides Density(1f)) { Row( (if (isLarge) Modifier.size(200.dp) else Modifier.size(50.dp, 100.dp)) .intermediateLayout { measurable, constraints, lookaheadSize -> parentLookaheadSize = lookaheadSize measureWithLambdas().invoke(this, measurable, constraints) } ) { Box( Modifier .fillMaxHeight() .weight(2f) .intermediateLayout { measurable, constraints, lookaheadSize -> child1LookaheadSize = lookaheadSize measureWithLambdas().invoke(this, measurable, constraints) } .animateSize(this@LookaheadLayout) ) Box( Modifier .fillMaxHeight() .weight(3f) .intermediateLayout { measurable, constraints, lookaheadSize -> child2LookaheadSize = lookaheadSize measureWithLambdas().invoke(this, measurable, constraints) } .animateSize(this@LookaheadLayout) ) } } } ) } rule.waitForIdle() rule.runOnIdle { assertEquals(IntSize(200, 200), parentLookaheadSize) assertEquals(IntSize(80, 200), child1LookaheadSize) assertEquals(IntSize(120, 200), child2LookaheadSize) rule.mainClock.autoAdvance = false isLarge = false } rule.waitForIdle() rule.mainClock.advanceTimeByFrame() repeat(10) { rule.runOnIdle { assertEquals(IntSize(50, 100), parentLookaheadSize) assertEquals(IntSize(20, 100), child1LookaheadSize) assertEquals(IntSize(30, 100), child2LookaheadSize) } rule.mainClock.advanceTimeByFrame() } rule.runOnIdle { isLarge = true } rule.waitForIdle() rule.mainClock.advanceTimeByFrame() repeat(10) { rule.runOnIdle { assertEquals(IntSize(200, 200), parentLookaheadSize) assertEquals(IntSize(80, 200), child1LookaheadSize) assertEquals(IntSize(120, 200), child2LookaheadSize) } rule.mainClock.advanceTimeByFrame() } } @Test fun skipPlacementOnlyPostLookahead() { var child1TotalPlacement = 0 var child1Placement = 0 var child2TotalPlacement = 0 var child2Placement = 0 rule.setContent { MyLookaheadLayout { Row(Modifier.widthIn(100.dp, 200.dp)) { Box( modifier = Modifier .intermediateLayout { measurable, constraints, _ -> val placeable = measurable.measure(constraints) layout(placeable.width, placeable.height) { // skip placement in the post-lookahead placement pass } } .weight(1f) .layout { measurable, constraints -> measureWithLambdas( prePlacement = { child1TotalPlacement++ } ).invoke(this, measurable, constraints) } .intermediateLayout { measurable, constraints, _ -> measureWithLambdas(prePlacement = { child1Placement++ }) .invoke(this, measurable, constraints) } ) Box( modifier = Modifier .layout { measurable, constraints -> measureWithLambdas( prePlacement = { child2TotalPlacement++ } ).invoke(this, measurable, constraints) } .intermediateLayout { measurable, constraints, _ -> measureWithLambdas(prePlacement = { child2Placement++ }) .invoke(this, measurable, constraints) } .weight(3f) ) Box(modifier = Modifier.sizeIn(50.dp)) } } } rule.runOnIdle { // Child1 skips post-lookahead placement assertEquals(0, child1Placement) // Child2 is placed in post-lookahead placement assertEquals(1, child2Placement) val child1LookaheadPlacement = child1TotalPlacement - child1Placement val child2LookaheadPlacement = child2TotalPlacement - child2Placement // Both child1 & child2 should be placed in lookahead, since the skipping only // applies to regular placement pass, as per API contract in `intermediateLayout` assertEquals(1, child1LookaheadPlacement) assertEquals(1, child2LookaheadPlacement) } } @Composable private fun MyLookaheadLayout( postMeasure: () -> Unit = {}, postPlacement: () -> Unit = {}, content: @Composable LookaheadLayoutScope.() -> Unit ) { LookaheadLayout( measurePolicy = { measurables, constraints -> val placeables = measurables.map { it.measure(constraints) } val maxWidth: Int = placeables.maxOf { it.width } val maxHeight = placeables.maxOf { it.height } postMeasure() // Position the children. layout(maxWidth, maxHeight) { placeables.forEach { it.place(0, 0) } postPlacement() } }, content = { content() } ) } @Test fun alterPlacementTest() { var placementCount = 0 var totalPlacementCount = 0 var shouldPlace by mutableStateOf(false) rule.setContent { MyLookaheadLayout { Layout( content = { Box(Modifier .intermediateLayout { measurable, constraints, _ -> measureWithLambdas(prePlacement = { placementCount++ }).invoke(this, measurable, constraints) } .layout { measurable, constraints -> measureWithLambdas(prePlacement = { totalPlacementCount++ }).invoke(this, measurable, constraints) }) } ) { measurables, constraints -> val placeables = measurables.map { it.measure(constraints) } val maxWidth: Int = placeables.maxOf { it.width } val maxHeight = placeables.maxOf { it.height } // Position the children. layout(maxWidth, maxHeight) { if (shouldPlace) { placeables.forEach { it.place(0, 0) } } } } } } rule.runOnIdle { assertEquals(0, totalPlacementCount) assertEquals(0, placementCount) shouldPlace = true } rule.runOnIdle { val lookaheadPlacementCount = totalPlacementCount - placementCount assertEquals(1, lookaheadPlacementCount) assertEquals(1, placementCount) } } @Test fun localLookaheadPositionOfFromDisjointedLookaheadLayoutsTest() { var firstCoordinates: LookaheadLayoutCoordinates? = null var secondCoordinates: LookaheadLayoutCoordinates? = null rule.setContent { Row( Modifier.fillMaxSize(), horizontalArrangement = SpaceAround, verticalAlignment = Alignment.CenterVertically ) { MyLookaheadLayout { Box( Modifier .size(200.dp) .onPlaced { _, it -> firstCoordinates = it }) } Box( Modifier .padding(top = 30.dp, start = 70.dp) .offset(40.dp, 60.dp) ) { MyLookaheadLayout { Box( Modifier .size(100.dp, 50.dp) .onPlaced { _, it -> secondCoordinates = it }) } } } } rule.runOnIdle { val offset = secondCoordinates!!.localPositionOf(firstCoordinates!!, Offset.Zero) val lookaheadOffset = secondCoordinates!!.localLookaheadPositionOf(firstCoordinates!!) assertEquals(offset, lookaheadOffset) } } @Test fun localLookaheadPositionOfFromNestedLookaheadLayoutsTest() { var firstCoordinates: LookaheadLayoutCoordinates? = null var secondCoordinates: LookaheadLayoutCoordinates? = null rule.setContent { MyLookaheadLayout { Row( Modifier .fillMaxSize() .onPlaced { _, it -> firstCoordinates = it }, horizontalArrangement = SpaceAround, verticalAlignment = Alignment.CenterVertically ) { Box(Modifier.size(200.dp)) Box( Modifier .padding(top = 30.dp, start = 70.dp) .offset(40.dp, 60.dp) ) { MyLookaheadLayout { Box( Modifier .size(100.dp, 50.dp) .onPlaced { _, it -> secondCoordinates = it }) } } } } } rule.runOnIdle { val offset = secondCoordinates!!.localPositionOf(firstCoordinates!!, Offset.Zero) val lookaheadOffset = secondCoordinates!!.localLookaheadPositionOf(firstCoordinates!!) assertEquals(offset, lookaheadOffset) } } @Test fun lookaheadMaxHeightIntrinsicsTest() { assertSameLayoutWithAndWithoutLookahead { modifier -> Box(modifier) { Row(modifier.height(IntrinsicSize.Max)) { Box( modifier .fillMaxHeight() .weight(1f) .aspectRatio(2f) .background(Color.Gray) ) Box( modifier .fillMaxHeight() .weight(1f) .width(1.dp) .background(Color.Black) ) Box( modifier .fillMaxHeight() .weight(1f) .aspectRatio(1f) .background(Color.Blue) ) } } } } @Test fun lookaheadMinHeightIntrinsicsTest() { assertSameLayoutWithAndWithoutLookahead { modifier -> Box { Row(modifier.height(IntrinsicSize.Min)) { Text( text = "This is a really short text", modifier = modifier .weight(1f) .fillMaxHeight() ) Box( modifier .width(1.dp) .fillMaxHeight() .background(Color.Black) ) Text( text = "This is a much much much much much much much much much much" + " much much much much much much longer text", modifier = modifier .weight(1f) .fillMaxHeight() ) } } } } @Test fun lookaheadMinWidthIntrinsicsTest() { assertSameLayoutWithAndWithoutLookahead { modifier -> Column( modifier .width(IntrinsicSize.Min) .wrapContentHeight() ) { Box( modifier = modifier .fillMaxWidth() .size(20.dp, 10.dp) .background(Color.Gray) ) Box( modifier = modifier .fillMaxWidth() .size(30.dp, 10.dp) .background(Color.Blue) ) Box( modifier = modifier .fillMaxWidth() .size(10.dp, 10.dp) .background(Color.Magenta) ) } } } @Test fun lookaheadMaxWidthIntrinsicsTest() { assertSameLayoutWithAndWithoutLookahead { modifier -> Box { Column( modifier .width(IntrinsicSize.Max) .wrapContentHeight() ) { Box( modifier .fillMaxWidth() .background(Color.Gray) ) { Text("Short text") } Box( modifier .fillMaxWidth() .background(Color.Blue) ) { Text("Extremely long text giving the width of its siblings") } Box( modifier .fillMaxWidth() .background(Color.Magenta) ) { Text("Medium length text") } } } } } @Test fun firstBaselineAlignmentInLookaheadLayout() { assertSameLayoutWithAndWithoutLookahead { modifier -> Box(modifier.fillMaxWidth()) { Row { Text("Short", modifier.alignByBaseline()) Text("3\nline\n\text", modifier.alignByBaseline()) Text( "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do" + " eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim" + " ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut" + " aliquip ex ea commodo consequat. Duis aute irure dolor in" + " reprehenderit in voluptate velit esse cillum dolore eu fugiat" + " nulla pariatur. Excepteur sint occaecat cupidatat non proident," + " sunt in culpa qui officia deserunt mollit anim id est laborum.", modifier.alignByBaseline() ) } } } } @Test fun grandparentQueryBaseline() { assertSameLayoutWithAndWithoutLookahead { modifier -> Layout(modifier = modifier, content = { Row( modifier .fillMaxWidth() .wrapContentHeight() .background(Color(0xffb4c8ea)), horizontalArrangement = Arrangement.Center, verticalAlignment = Alignment.CenterVertically ) { Text( text = "First", fontSize = 80.sp, color = Color.White, modifier = modifier .alignByBaseline() .background(color = Color(0xfff3722c), RoundedCornerShape(10)) ) Spacer(modifier.size(10.dp)) Text( text = "Second", color = Color.White, fontSize = 30.sp, modifier = modifier .alignByBaseline() .background(color = Color(0xff90be6d), RoundedCornerShape(10)) ) Spacer(modifier.size(10.dp)) Text( text = "Text", fontSize = 50.sp, color = Color.White, modifier = modifier .alignByBaseline() .background(color = Color(0xffffb900), RoundedCornerShape(10)) ) } Spacer( modifier .fillMaxWidth() .requiredHeight(1.dp) .background(Color.Black) ) }) { measurables, constraints -> val placeables = measurables.map { it.measure(constraints) } val row = placeables.first() val position = row[FirstBaseline] layout(row.width, row.height) { row.place(0, 0) placeables[1].place(0, position) } } } } @Test fun lookaheadLayoutTransformFrom() { val matrix = Matrix() rule.setContent { CompositionLocalProvider(LocalDensity provides Density(1f)) { LookaheadLayout( measurePolicy = { measurables, constraints -> val placeable = measurables[0].measure(constraints) // Position the children. layout(placeable.width + 10, placeable.height + 10) { placeable.place(10, 10) } }, content = { Box( Modifier .onPlaced { lookaheadScopeCoordinates, layoutCoordinates -> layoutCoordinates.transformFrom( lookaheadScopeCoordinates, matrix ) } .size(10.dp)) } ) } } rule.waitForIdle() val posInChild = matrix.map(Offset(10f, 10f)) assertEquals(Offset.Zero, posInChild) } @Test fun multiMeasureLayoutInLookahead() { var horizontal by mutableStateOf(true) rule.setContent { MyLookaheadLayout { @Suppress("DEPRECATION") MultiMeasureLayout( content = { if (horizontal) { Row { repeat(3) { Box( Modifier .weight(1f) .background(Color.Red) ) } } } else { Column { repeat(3) { Box( Modifier .weight(1f) .background(Color.Red) ) } } } }, modifier = Modifier.fillMaxSize(0.6f), measurePolicy = MeasurePolicy { measurables, constraints -> // Intentionally measure twice here to ensure multi-measure is supported. measurables.map { it.measure(Constraints.fixed(200, 300)) } val placeables = measurables.map { it.measure(constraints) } val maxWidth: Int = placeables.maxOf { it.width } val maxHeight = placeables.maxOf { it.height } // Position the children. layout(maxWidth, maxHeight) { placeables.forEach { it.place(0, 0) } } }) } } rule.runOnIdle { horizontal = !horizontal } rule.runOnIdle { horizontal = !horizontal } rule.waitForIdle() } private fun assertSameLayoutWithAndWithoutLookahead( content: @Composable ( modifier: Modifier ) -> Unit ) { val controlGroupSizes = mutableVectorOf<IntSize>() val controlGroupPositions = mutableVectorOf<Offset>() val sizes = mutableVectorOf<IntSize>() val positions = mutableVectorOf<Offset>() var enableControlGroup by mutableStateOf(true) rule.setContent { if (enableControlGroup) { Layout(measurePolicy = defaultMeasurePolicy, content = { content( modifier = Modifier.trackSizeAndPosition( controlGroupSizes, controlGroupPositions, ) ) }) } else { MyLookaheadLayout { content( modifier = Modifier .trackSizeAndPosition(sizes, positions) .assertSameSizeAndPosition(this) ) } } } rule.runOnIdle { enableControlGroup = !enableControlGroup } rule.runOnIdle { if (Debug) { controlGroupPositions.debugPrint("Lookahead") controlGroupSizes.debugPrint("Lookahead") positions.debugPrint("Lookahead") sizes.debugPrint("Lookahead") } assertEquals(controlGroupPositions.size, positions.size) controlGroupPositions.forEachIndexed { i, position -> assertEquals(position, positions[i]) } assertEquals(controlGroupSizes.size, sizes.size) controlGroupSizes.forEachIndexed { i, size -> assertEquals(size, sizes[i]) } } } private fun Modifier.assertSameSizeAndPosition(scope: LookaheadLayoutScope) = composed { var lookaheadSize by remember { mutableStateOf(IntSize.Zero) } var lookaheadLayoutCoordinates: LookaheadLayoutCoordinates? by remember { mutableStateOf( null ) } var onPlacedCoordinates: LookaheadLayoutCoordinates? by remember { mutableStateOf(null) } with(scope) { this@composed .intermediateLayout { measurable, constraints, targetSize -> lookaheadSize = targetSize measureWithLambdas().invoke(this, measurable, constraints) } .onPlaced { scopeRoot, it -> lookaheadLayoutCoordinates = scopeRoot onPlacedCoordinates = it } .onGloballyPositioned { assertEquals(lookaheadSize, it.size) assertEquals( lookaheadLayoutCoordinates!!.localLookaheadPositionOf( onPlacedCoordinates!! ), lookaheadLayoutCoordinates!!.localPositionOf( onPlacedCoordinates!!, Offset.Zero ) ) } } } private fun Modifier.trackSizeAndPosition( sizes: MutableVector<IntSize>, positions: MutableVector<Offset> ) = this .onGloballyPositioned { positions.add(it.positionInRoot()) sizes.add(it.size) } private fun <T> MutableVector<T>.debugPrint(tag: String) { print("$tag: [") forEach { print("$it, ") } print("]") println() } private val defaultMeasurePolicy: MeasurePolicy = MeasurePolicy { measurables, constraints -> val placeables = measurables.map { it.measure(constraints) } val maxWidth: Int = placeables.maxOf { it.width } val maxHeight = placeables.maxOf { it.height } // Position the children. layout(maxWidth, maxHeight) { placeables.forEach { it.place(0, 0) } } } private fun measureWithLambdas( preMeasure: () -> Unit = {}, postMeasure: (IntSize) -> Unit = {}, prePlacement: () -> Unit = {}, postPlacement: () -> Unit = {} ): MeasureScope.(Measurable, Constraints) -> MeasureResult = { measurable, constraints -> preMeasure() val placeable = measurable.measure(constraints) postMeasure(IntSize(placeable.width, placeable.height)) layout(placeable.width, placeable.height) { prePlacement() placeable.place(0, 0) postPlacement() } } }
apache-2.0
c9347295297340c74ce4c26490c43aea
39.764262
100
0.457728
6.355788
false
false
false
false
bsmr-java/lwjgl3
modules/generator/src/main/kotlin/org/lwjgl/generator/FunctionTransforms.kt
1
19127
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license */ package org.lwjgl.generator import java.io.PrintWriter interface Transform interface FunctionTransform<in T : QualifiedType> : Transform { fun transformDeclaration(param: T, original: String): String? fun transformCall(param: T, original: String): String } /** A function transform that must generate additional code. */ interface CodeFunctionTransform<in T : QualifiedType> : Transform { fun generate(qtype: T, code: Code): Code } /** A function transform that makes use of the stack. */ interface StackFunctionTransform<in T : QualifiedType> : Transform { fun setupStack(func: Function, qtype: T, writer: PrintWriter) } /** Marker interface to indicate that pointer and buffer checks should be skipped. */ interface SkipCheckFunctionTransform internal open class AutoSizeTransform( val bufferParam: Parameter, val relaxedCast: Boolean, val applyTo: ApplyTo, val applyFactor: Boolean = true ) : FunctionTransform<Parameter> { override fun transformDeclaration(param: Parameter, original: String) = null // Remove the parameter override fun transformCall(param: Parameter, original: String): String { if ( applyTo === ApplyTo.NORMAL ) return param.name var expression = if (bufferParam.nativeType is ArrayType) { if (bufferParam has nullable) "lengthSafe(${bufferParam.name})" else "${bufferParam.name}.length" } else { if (bufferParam has nullable) "remainingSafe(${bufferParam.name})" else "${bufferParam.name}.remaining()" } val factor = param[AutoSize].factor if ( applyFactor && factor != null ) expression += " ${factor.expression()}" if ( (param.nativeType.mapping as PrimitiveMapping).bytes.let { if (relaxedCast) it < 4 else it != 4 } ) expression = "(${param.nativeType.javaMethodType})${if ( expression.contains(' ') ) "($expression)" else expression}" return expression } } internal fun AutoSizeTransform(bufferParam: Parameter, relaxedCast: Boolean, applyTo: ApplyTo, byteShift: String) = if ( byteShift == "0" ) AutoSizeTransform(bufferParam, relaxedCast, applyTo) else AutoSizeBytesTransform(bufferParam, relaxedCast, applyTo, byteShift) private class AutoSizeBytesTransform( bufferParam: Parameter, relaxedCast: Boolean, applyTo: ApplyTo, val byteShift: String ) : AutoSizeTransform(bufferParam, relaxedCast, applyTo) { override fun transformCall(param: Parameter, original: String): String { if ( applyTo === ApplyTo.NORMAL ) return param.name var expression = if (bufferParam has nullable) "remainingSafe(${bufferParam.name})" else "${bufferParam.name}.remaining()" val factor = param[AutoSize].factor if ( factor == null ) expression = "$expression << $byteShift" else { // TODO: may need to handle more cases in the future (e.g. integer factor + POINTER_SHIFT) try { val f = factor.expression.toInt() val b = byteShift.toInt() if ( factor.operator == "/" ) { expression = "$expression / ${f / (1 shl b)}" } else { val s = (if ( factor.operator == ">>" ) f else -f) - b if (s < 0) expression = "$expression << ${-s}" else expression = "$expression >> $s" } } catch(e: NumberFormatException) { if ( applyTo !== ApplyTo.ALTERNATIVE ) // Hack to skip the expression with MultiType expression = "($expression ${factor.expression()}) << $byteShift" } } if ( (param.nativeType.mapping as PrimitiveMapping).bytes.let { if (relaxedCast) it < 4 else it != 4 } ) expression = "(${param.nativeType.javaMethodType})($expression)" return expression } } internal open class AutoSizeCharSequenceTransform(val bufferParam: Parameter) : FunctionTransform<Parameter> { override fun transformDeclaration(param: Parameter, original: String) = null // Remove the parameter override fun transformCall(param: Parameter, original: String): String { var expression = if ( bufferParam has Nullable ) "${bufferParam.name} == null ? 0 : ${bufferParam.name}Encoded.remaining()" else "${bufferParam.name}EncodedLen" if ( param[AutoSize].factor != null ) expression = "$expression ${param[AutoSize].factor!!.expression()}" if ( (param.nativeType.mapping as PrimitiveMapping).bytes < 4 ) expression = "(${param.nativeType.javaMethodType})($expression)" return expression } } internal class AutoTypeParamTransform(val autoType: String) : FunctionTransform<Parameter> { override fun transformDeclaration(param: Parameter, original: String) = null // Remove the parameter override fun transformCall(param: Parameter, original: String) = autoType // Replace with hard-coded type } internal class AutoTypeTargetTransform(val autoType: PointerMapping) : FunctionTransform<Parameter> { override fun transformDeclaration(param: Parameter, original: String) = "${autoType.javaMethodType.simpleName} ${param.name}" override fun transformCall(param: Parameter, original: String) = original } internal open class ExpressionTransform( val expression: String, val keepParam: Boolean = false, val paramTransform: FunctionTransform<Parameter>? = null ) : FunctionTransform<Parameter>, SkipCheckFunctionTransform { override fun transformDeclaration(param: Parameter, original: String) = if ( keepParam ) paramTransform?.transformDeclaration(param, original) ?: original else null override fun transformCall(param: Parameter, original: String) = expression } internal class ExpressionLocalTransform( expression: String, keepParam: Boolean = false ) : ExpressionTransform(expression, keepParam), CodeFunctionTransform<Parameter>, SkipCheckFunctionTransform { override fun transformCall(param: Parameter, original: String) = original override fun generate(qtype: Parameter, code: Code) = code.append( javaInit = statement("\t\t${qtype.javaMethodType} ${qtype.name} = $expression;", ApplyTo.ALTERNATIVE) ) } internal class CharSequenceTransform( val nullTerminated: Boolean ) : FunctionTransform<Parameter>, StackFunctionTransform<Parameter> { override fun transformDeclaration(param: Parameter, original: String) = "CharSequence ${param.name}" override fun transformCall(param: Parameter, original: String) = if ( param has Nullable ) "memAddressSafe(${param.name}Encoded)" else "memAddress(${param.name}Encoded)" override fun setupStack(func: Function, qtype: Parameter, writer: PrintWriter) { writer.print("\t\t\tByteBuffer ${qtype.name}Encoded = ") writer.print("stack.${(qtype.nativeType as CharSequenceType).charMapping.charset}(${qtype.name}") if ( !nullTerminated ) writer.print(", false") writer.println(");") if ( !nullTerminated ) writer.println("\t\t\tint ${qtype.name}EncodedLen = ${qtype.name}Encoded.capacity();") } } internal object StringReturnTransform : FunctionTransform<ReturnValue> { override fun transformDeclaration(param: ReturnValue, original: String) = "String" override fun transformCall(param: ReturnValue, original: String): String { val expression = if ( original.startsWith("memByteBufferNT") ) original.substring(17, original.length - 1) else original return "mem${(param.nativeType as CharSequenceType).charMapping.charset}($expression)" } } internal class PrimitiveValueReturnTransform( val bufferType: PointerMapping, val paramName: String ) : FunctionTransform<ReturnValue>, StackFunctionTransform<ReturnValue> { override fun transformDeclaration(param: ReturnValue, original: String) = bufferType.primitive // Replace void with the buffer value type override fun transformCall(param: ReturnValue, original: String) = if ( bufferType === PointerMapping.DATA_BOOLEAN ) "\t\treturn $paramName.get(0) != 0;" else "\t\treturn $paramName.get(0);" // Replace with value from the stack override fun setupStack(func: Function, qtype: ReturnValue, writer: PrintWriter) = writer.println("\t\t\t${bufferType.box}Buffer $paramName = stack.calloc${bufferType.mallocType}(1);") } internal object PrimitiveValueTransform : FunctionTransform<Parameter>, SkipCheckFunctionTransform { override fun transformDeclaration(param: Parameter, original: String) = null // Remove the parameter override fun transformCall(param: Parameter, original: String) = "memAddress(${param.name})" // Replace with stack buffer } internal object Expression1Transform : FunctionTransform<Parameter> { override fun transformDeclaration(param: Parameter, original: String) = null // Remove the parameter override fun transformCall(param: Parameter, original: String) = "1" // Replace with 1 } internal class SingleValueTransform( val paramType: String, val elementType: String, val newName: String ) : FunctionTransform<Parameter>, StackFunctionTransform<Parameter>, SkipCheckFunctionTransform { override fun transformDeclaration(param: Parameter, original: String) = "$paramType $newName" // Replace with element type + new name override fun transformCall(param: Parameter, original: String) = "memAddress(${param.name})" // Replace with stack buffer override fun setupStack(func: Function, qtype: Parameter, writer: PrintWriter) = writer.println("\t\t\t${qtype.javaMethodType} ${qtype.name} = stack.${elementType}s($newName);") } internal class SingleValueStructTransform( val newName: String ) : FunctionTransform<Parameter> { override fun transformDeclaration(param: Parameter, original: String) = "${param.nativeType.javaMethodType} $newName" // Replace with element type + new name override fun transformCall(param: Parameter, original: String): String = "$newName.address()" } internal class VectorValueTransform( val paramType: PointerMapping, val elementType: String, val newName: String, val size: Int ) : FunctionTransform<Parameter>, StackFunctionTransform<Parameter>, SkipCheckFunctionTransform { override fun transformDeclaration(param: Parameter, original: String) = paramType.primitive.let { paramType -> (0..size - 1).map { "$paramType $newName$it" }.reduce { a, b -> "$a, $b" } } // Replace with vector elements override fun transformCall(param: Parameter, original: String) = "memAddress(${param.name})" // Replace with stack buffer override fun setupStack(func: Function, qtype: Parameter, writer: PrintWriter) { writer.print("\t\t\t${paramType.box}Buffer ${qtype.name} = stack.${elementType}s(${newName}0") for (i in 1..(size - 1)) writer.print(", $newName$i") writer.println(");") } } internal object MapPointerTransform : FunctionTransform<ReturnValue> { override fun transformDeclaration(param: ReturnValue, original: String) = "ByteBuffer" // Return a ByteBuffer override fun transformCall(param: ReturnValue, original: String) = """int $MAP_LENGTH = ${param[MapPointer].sizeExpression}; return $MAP_OLD == null ? memByteBuffer($RESULT, $MAP_LENGTH) : memSetupBuffer($MAP_OLD, $RESULT, $MAP_LENGTH);""" } internal class MapPointerExplicitTransform(val lengthParam: String, val addParam: Boolean = true) : FunctionTransform<ReturnValue> { override fun transformDeclaration(param: ReturnValue, original: String) = "ByteBuffer" // Return a ByteBuffer override fun transformCall(param: ReturnValue, original: String) = "$MAP_OLD == null ? memByteBuffer($RESULT, (int)$lengthParam) : memSetupBuffer($MAP_OLD, $RESULT, (int)$lengthParam)" } internal val BufferLengthTransform: FunctionTransform<Parameter> = object : FunctionTransform<Parameter>, StackFunctionTransform<Parameter>, SkipCheckFunctionTransform { override fun transformDeclaration(param: Parameter, original: String) = null // Remove the parameter override fun transformCall(param: Parameter, original: String) = "memAddress(${param.name})" // Replace with stack buffer override fun setupStack(func: Function, qtype: Parameter, writer: PrintWriter) = writer.println("\t\t\tIntBuffer ${qtype.name} = stack.ints(0);") } internal class StringAutoSizeTransform(val autoSizeParam: Parameter) : FunctionTransform<Parameter>, CodeFunctionTransform<Parameter>, SkipCheckFunctionTransform { override fun transformDeclaration(param: Parameter, original: String) = null // Remove the parameter override fun transformCall(param: Parameter, original: String) = "memAddress(${param.name})" // Replace with address of allocated buffer override fun generate(qtype: Parameter, code: Code): Code { val len = "${if ( 4 < (autoSizeParam.nativeType.mapping as PrimitiveMapping).bytes ) "(int)" else ""}${autoSizeParam.name}" return code.append( javaBeforeNative = statement("\t\tByteBuffer ${qtype.name} = memAlloc($len);", ApplyTo.ALTERNATIVE), javaFinally = statement("\t\t\tmemFree(${qtype.name});") ) } } internal class StringAutoSizeStackTransform(val autoSizeParam: Parameter) : FunctionTransform<Parameter>, StackFunctionTransform<Parameter>, SkipCheckFunctionTransform { override fun transformDeclaration(param: Parameter, original: String) = null // Remove the parameter override fun transformCall(param: Parameter, original: String) = "memAddress(${param.name})" // Replace with address of allocated buffer override fun setupStack(func: Function, qtype: Parameter, writer: PrintWriter) { val len = "${if ( 4 < (autoSizeParam.nativeType.mapping as PrimitiveMapping).bytes ) "(int)" else ""}${autoSizeParam.name}" writer.println("\t\t\tByteBuffer ${qtype.name} = stack.malloc($len);") } } internal val BufferReplaceReturnTransform: FunctionTransform<Parameter> = object : FunctionTransform<Parameter>, StackFunctionTransform<Parameter>, SkipCheckFunctionTransform { override fun transformDeclaration(param: Parameter, original: String) = null // Remove the parameter override fun transformCall(param: Parameter, original: String) = "memAddress(${param.name})" // Replace with stuck buffer override fun setupStack(func: Function, qtype: Parameter, writer: PrintWriter) { writer.println("\t\t\tPointerBuffer ${qtype.name} = stack.pointers(NULL);") } } internal class BufferAutoSizeReturnTransform( val outParam: Parameter, val lengthExpression: String, val encoding: String? = null ) : FunctionTransform<ReturnValue> { override fun transformDeclaration(param: ReturnValue, original: String) = (outParam.nativeType as PointerType).elementType!!.let { if ( it is StructType ) "${it.javaMethodType}.Buffer" else it.javaMethodType } override fun transformCall(param: ReturnValue, original: String) = (outParam.nativeType as PointerType).elementType!!.let { "\t\treturn ${if (it is StructType) "${it.javaMethodType}.create" else "mem${it.javaMethodType}" }(${outParam.name}.get(0), $lengthExpression);" } } internal class BufferReturnTransform( val outParam: Parameter, val lengthParam: String, val encoding: String? = null ) : FunctionTransform<ReturnValue> { override fun transformDeclaration(param: ReturnValue, original: String) = if ( encoding == null ) (outParam.nativeType.mapping as PointerMapping).javaMethodType.simpleName else "String" override fun transformCall(param: ReturnValue, original: String): String { return if ( encoding != null ) "\t\treturn mem$encoding(${outParam.name}, $lengthParam.get(0));" else if ( outParam.nativeType.mapping !== PointerMapping.DATA_BYTE ) "\t\t${outParam.name}.limit($lengthParam.get(0));\n" + "\t\treturn ${outParam.name}.slice();" else "\t\treturn memSlice(${outParam.name}, $lengthParam.get(0));" } } internal class BufferReturnNTTransform( val outParam: Parameter, val maxLengthParam: String, val encoding: String ) : FunctionTransform<ReturnValue> { override fun transformDeclaration(param: ReturnValue, original: String) = "String" override fun transformCall(param: ReturnValue, original: String): String = "\t\treturn mem$encoding(memByteBufferNT${(outParam.nativeType as CharSequenceType).charMapping.bytes}(memAddress(${outParam.name}), $maxLengthParam));" } internal open class PointerArrayTransform(val paramType: String) : FunctionTransform<Parameter>, StackFunctionTransform<Parameter>, CodeFunctionTransform<Parameter> { override fun transformDeclaration(param: Parameter, original: String): String? { val name = if ( paramType.isEmpty() ) param[PointerArray].singleName else param.name val paramClass = param[PointerArray].elementType.let { if ( it.mapping === PointerMapping.OPAQUE_POINTER ) "long" else if ( it is CharSequenceType ) "CharSequence" else "ByteBuffer" } return "$paramClass$paramType $name" } override fun transformCall(param: Parameter, original: String) = "${param.name}$POINTER_POSTFIX" // Replace with stuck buffer override fun setupStack(func: Function, qtype: Parameter, writer: PrintWriter) = writer.setupStackImpl(qtype) private fun PrintWriter.setupStackImpl(param: Parameter) { val pointerArray = param[PointerArray] if ( pointerArray.lengthsParam != null ) return println((if ( paramType.isNotEmpty() ) param.name else pointerArray.singleName).let { "\t\t\tlong ${param.name}$POINTER_POSTFIX = org.lwjgl.system.APIUtil.apiArray(stack,${if ( pointerArray.elementType is CharSequenceType ) " MemoryUtil::mem${pointerArray.elementType.charMapping.charset}," else ""} $it);" }) } override fun generate(qtype: Parameter, code: Code): Code { val pointerArray = qtype[PointerArray] val elementType = pointerArray.elementType if ( elementType is CharSequenceType ) { return code.append(javaAfterNative = statement( "\t\torg.lwjgl.system.APIUtil.apiArrayFree(${qtype.name}$POINTER_POSTFIX, ${if ( paramType.isEmpty() ) "1" else "${qtype.name}.length"});", ApplyTo.ALTERNATIVE )) } return code } } internal object PointerArrayTransformSingle : PointerArrayTransform(""), SkipCheckFunctionTransform internal val PointerArrayTransformArray = PointerArrayTransform("[]") internal val PointerArrayTransformVararg = PointerArrayTransform("...") internal class PointerArrayLengthsTransform( val arrayParam: Parameter, val multi: Boolean ) : FunctionTransform<Parameter>, StackFunctionTransform<Parameter>, SkipCheckFunctionTransform { override fun transformDeclaration(param: Parameter, original: String) = null // Remove the parameter override fun transformCall(param: Parameter, original: String) = // Replace with stack address - length(s) offset if ( multi ) "${arrayParam.name}$POINTER_POSTFIX - (${arrayParam.name}.length << ${if ( param.nativeType.mapping == PointerMapping.DATA_INT ) "2" else "POINTER_SHIFT"})" else "${arrayParam.name}$POINTER_POSTFIX - ${if ( param.nativeType.mapping == PointerMapping.DATA_INT ) "4" else "POINTER_SIZE"}" override fun setupStack(func: Function, qtype: Parameter, writer: PrintWriter) = writer.setupStackImpl(qtype) private fun PrintWriter.setupStackImpl(param: Parameter) { val pointerArray = arrayParam[PointerArray] val lengthType = (param.nativeType.mapping as PointerMapping).box[0].toLowerCase() println((if ( multi ) arrayParam.name else pointerArray.singleName).let { "\t\t\tlong ${arrayParam.name}$POINTER_POSTFIX = org.lwjgl.system.APIUtil.apiArray$lengthType(stack,${if ( pointerArray.elementType is CharSequenceType ) " MemoryUtil::mem${pointerArray.elementType.charMapping.charset}," else ""} $it);" }) } }
bsd-3-clause
d99ed9dd65ecc7067c5f1cdb4b743d05
45.767726
239
0.748732
4.056628
false
false
false
false
klazuka/intellij-elm
src/main/kotlin/org/elm/workspace/commandLineTools/make.kt
1
1650
package org.elm.workspace.commandLineTools import com.intellij.notification.NotificationType import com.intellij.openapi.project.Project import com.intellij.openapi.vfs.VirtualFile import org.elm.ide.notifications.showBalloon import org.elm.workspace.ElmProject import org.elm.workspace.LamderaApplicationProject import org.elm.workspace.elmToolchain import org.elm.workspace.elmWorkspace import java.nio.file.Path fun makeProject(elmProject: ElmProject, project: Project, entryPoints: List<Triple<Path, String?, Int>?>, currentFileInEditor: VirtualFile?): Boolean { return if (elmProject is LamderaApplicationProject) { val lamderaCLI = project.elmToolchain.lamderaCLI if (lamderaCLI == null) { showError(project, "Please set the path to the 'lamdera' binary", includeFixAction = true) return false } lamderaCLI.make(project, elmProject.projectDirPath, elmProject, entryPoints, jsonReport = true, currentFileInEditor) } else { val elmCLI = project.elmToolchain.elmCLI if (elmCLI == null) { showError(project, "Please set the path to the 'elm' binary", includeFixAction = true) return false } elmCLI.make(project, elmProject.projectDirPath, elmProject, entryPoints, jsonReport = true, currentFileInEditor) } } private fun showError(project: Project, message: String, includeFixAction: Boolean = false) { val actions = if (includeFixAction) arrayOf("Fix" to { project.elmWorkspace.showConfigureToolchainUI() }) else emptyArray() project.showBalloon(message, NotificationType.ERROR, *actions) }
mit
769a14fd64a81a25c27f1d2d1ef04c89
41.307692
151
0.733333
4.125
false
false
false
false
initrc/android-bootstrap
app/src/main/java/io/github/initrc/bootstrap/view/decoration/HorizontalEqualSpaceItemDecoration.kt
1
800
package io.github.initrc.bootstrap.view.decoration import android.graphics.Rect import android.support.v7.widget.RecyclerView import android.view.View /** * Equal space item decoration for grid view. */ class HorizontalEqualSpaceItemDecoration(space: Int) : RecyclerView.ItemDecoration() { private var halfSpace = space / 2 override fun getItemOffsets( outRect: Rect?, view: View?, parent: RecyclerView?, state: RecyclerView.State?) { if (parent?.paddingLeft != halfSpace) { parent?.setPadding(halfSpace, parent.paddingTop, halfSpace, parent.paddingBottom) parent?.clipToPadding = false } outRect?.left = halfSpace outRect?.right = halfSpace } fun setSpace(space: Int) { halfSpace = space / 2 } }
mit
51d8a4756f32f654d220711e3bd8e1cd
28.62963
93
0.67875
4.395604
false
false
false
false
Tvede-dk/CommonsenseAndroidKotlin
base/src/main/kotlin/com/commonsense/android/kotlin/base/scheduling/JobContainer.kt
1
4812
@file:Suppress("unused", "NOTHING_TO_INLINE", "MemberVisibilityCanBePrivate") package com.commonsense.android.kotlin.base.scheduling import com.commonsense.android.kotlin.base.* import com.commonsense.android.kotlin.base.debug.* import com.commonsense.android.kotlin.base.extensions.* import com.commonsense.android.kotlin.base.extensions.collections.* import kotlinx.coroutines.* import kotlinx.coroutines.sync.* import java.util.concurrent.* import kotlin.coroutines.* typealias QueuedJob = Pair<CoroutineContext, AsyncEmptyFunction> /** * Created by Kasper Tvede * It is meant for handling 3 types of scheduling * - localJobs * - queuedGroupedJobs * - groupedJobs */ open class JobContainer(val scope: CoroutineScope) { private val localJobs = ConcurrentLinkedQueue<Job>() private val queuedGroupedJobs = ConcurrentHashMap<String, MutableList<QueuedJob>>() private val groupedJobs = ConcurrentHashMap<String, Job>() //<editor-fold desc="Add job "> private fun addJobToLocal(job: Job) { localJobs.add(job) handleCompletedCompletion(job) } private fun addJobToGroup(job: Job, group: String) { groupedJobs[group]?.cancel() groupedJobs[group] = job handleCompletedCompletion(job) } //</editor-fold> private fun handleCompletedCompletion(job: Job) { job.invokeOnCompletion { removeDoneJobs() } } //<editor-fold desc="Description"> fun removeDoneJobs() { localJobs.removeAll { it.isCompleted } groupedJobs.removeAll { it.value.isCompleted } } fun cleanJobs() { localJobs.forEach { it.cancel() } localJobs.clear() groupedJobs.forEach { it.value.cancel() } groupedJobs.clear() queuedGroupedJobs.clear() } //</editor-fold> //<editor-fold desc="regular non grouped Actions"> fun addJob(job: Job) = addJobToLocal(job) fun performAction(context: CoroutineContext, action: AsyncEmptyFunction): Job { val scopedAction: AsyncCoroutineFunction = { action() } return performAction(context, scopedAction) } fun performAction(context: CoroutineContext, scopedAction: AsyncCoroutineFunction): Job { val job = GlobalScope.launch(context, block = scopedAction) addJobToLocal(job) return job } //</editor-fold> //<editor-fold desc="get jobs"> fun getRemainingJobs(): Int { removeDoneJobs() return localJobs.size } fun getRemainingGroupedJobs(): Int { removeDoneJobs() return groupedJobs.size } //</editor-fold> //<editor-fold desc="group action"> fun addJob(job: Job, group: String) = addJobToGroup(job, group) fun performAction(context: CoroutineContext, scopedAction: AsyncCoroutineFunction, forGroup: String): Job { val job = GlobalScope.launch(context, block = scopedAction) addJobToGroup(job, forGroup) return job } fun performAction(context: CoroutineContext, action: AsyncEmptyFunction, forGroup: String): Job { val scopedAction: AsyncCoroutineFunction = { action() } return performAction(context, scopedAction, forGroup) } //</editor-fold> /** * Executes all queued up actions in that group. * does not wait for the response of this. */ fun executeQueueBackground(group: String) = scope.launch { executeQueueAwaited(group) } /** * Executes all queued up actions in that group. * waits until all jobs are "done": */ suspend fun executeQueueAwaited(group: String) { //step 1 execute the group queuedGroupedJobs[group]?.map { performAction(it.first, it.second) }?.joinAll() //step 2 remove the group as it is not "queued" anymore queuedGroupedJobs.remove(group) } /** * Adds a given operation to a named queue. */ fun addToQueue(context: CoroutineContext, action: AsyncEmptyFunction, group: String) { queuedGroupedJobs.getOrPut(group) { mutableListOf() }.add(Pair(context, action)) } fun toPrettyString(): String { return "Job container state: " + localJobs.map { "$it" }.prettyStringContent( "\t\tlocal Jobs", "\t\tno local jobs") + queuedGroupedJobs.map { "$it" }.prettyStringContent( "\t\tQueue grouped jobs:", "\t\tno queue grouped jobs") + groupedJobs.map { "$it" }.prettyStringContent( "\t\tGrouped jobs", "\t\tno grouped jobs") } override fun toString() = toPrettyString() }
mit
e43e86e6f5baaf82586dd3beaad4fe91
29.462025
93
0.633416
4.501403
false
false
false
false
y2k/JoyReactor
ios/src/main/kotlin/y2k/joyreactor/BottomButton.kt
1
720
package y2k.joyreactor import org.robovm.apple.uikit.UIView /** * Created by y2k on 11/1/15. */ internal class BottomButton(private val view: UIView) { fun setHidden(hidden: Boolean) { if (hidden) { UIView.animate(0.3, { val f = view.frame f.setY(view.superview.frame.height) view.frame = f view.alpha = 0.0 }, { view.isHidden = true }) } else { view.isHidden = false UIView.animate(0.3) { val f = view.frame f.setY(view.superview.frame.height - f.height) view.frame = f view.alpha = 1.0 } } } }
gpl-2.0
eb9abd1165ad59668d0b02dd96094c08
24.75
62
0.483333
3.870968
false
false
false
false
saki4510t/libcommon
app/src/main/java/com/serenegiant/libcommon/ViewSliderFragment.kt
1
4545
package com.serenegiant.libcommon /* * libcommon * utility/helper classes for myself * * Copyright (c) 2014-2022 saki [email protected] * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import android.content.Context import android.os.Bundle import android.util.Log import android.view.LayoutInflater import android.view.MotionEvent import android.view.View import android.view.ViewGroup import com.serenegiant.view.ViewSlider import com.serenegiant.view.ViewUtils /** * ViewSliderテスト用フラグメント */ class ViewSliderFragment : BaseFragment() { private var mRootView: View? = null private var mViewSliderLeft: ViewSlider? = null private var mViewSliderTop: ViewSlider? = null private var mViewSliderRight: ViewSlider? = null private var mViewSliderBottom: ViewSlider? = null override fun onAttach(context: Context) { super.onAttach(context) requireActivity().title = getString(R.string.title_view_slider) } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { if (DEBUG) Log.v(TAG, "onCreateView:") val customInflater = ViewUtils.createCustomLayoutInflater(requireContext(), inflater, R.style.AppTheme_ViewSlider) return customInflater.inflate( if (USE_CONSTRAINT_LAYOUT) R.layout.fragment_viewslider_constraint else R.layout.fragment_viewslider, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) initView(view) } private fun initView(rootView: View) { mRootView = rootView rootView.setOnTouchListener(mOnTouchListener) mViewSliderLeft = ViewSlider(rootView, R.id.slide_view_left, ViewSlider.HORIZONTAL) mViewSliderLeft!!.hide(0) mViewSliderLeft!!.targetView.setOnTouchListener(mOnTouchListener) mViewSliderTop = ViewSlider(rootView, R.id.slide_view_top, ViewSlider.VERTICAL) mViewSliderTop!!.hide(0) mViewSliderTop!!.targetView.setOnTouchListener(mOnTouchListener) mViewSliderRight = ViewSlider(rootView, R.id.slide_view_right, ViewSlider.HORIZONTAL) mViewSliderRight!!.hide(0) mViewSliderRight!!.targetView.setOnTouchListener(mOnTouchListener) mViewSliderBottom = ViewSlider(rootView, R.id.slide_view_bottom) mViewSliderBottom!!.hide(0) } private val mOnTouchListener = View.OnTouchListener { view, event -> if (DEBUG) Log.v(TAG, "onTouch:${view.javaClass.simpleName}(${view.id}),${event}") if (event.actionMasked == MotionEvent.ACTION_UP) { if (view == mRootView) { view.performClick() val width = view.width val height = view.height val left = width / 4 val top = height / 4 val right = width * 3 / 4 val bottom = height * 3 / 4 if (event.y < top) { if (mViewSliderTop!!.isVisible) { mViewSliderTop!!.hide() } else { mViewSliderTop!!.show(0) } } else if (event.y > bottom) { if (mViewSliderBottom!!.isVisible) { mViewSliderBottom!!.hide() } else { mViewSliderBottom!!.show(0) } } else if (event.x < left) { if (mViewSliderLeft!!.isVisible) { mViewSliderLeft!!.hide() } else { mViewSliderLeft!!.show(0) } } else if (event.x > right) { if (mViewSliderRight!!.isVisible) { mViewSliderRight!!.hide() } else { mViewSliderRight!!.show(0) } } } else if (view == mViewSliderLeft!!.targetView) { view.performClick() mViewSliderLeft!!.hide() } else if (view == mViewSliderTop!!.targetView) { view.performClick() mViewSliderTop!!.hide() } else if (view == mViewSliderRight!!.targetView) { view.performClick() mViewSliderRight!!.hide() } else if (view == mViewSliderBottom!!.targetView) { view.performClick() mViewSliderBottom!!.hide() } } return@OnTouchListener true } companion object { private const val DEBUG = true // TODO set false on release private const val USE_CONSTRAINT_LAYOUT = false private val TAG = ViewSliderFragment::class.java.simpleName } }
apache-2.0
f39cbe1b48cee75879e4319150c68730
31.099291
98
0.715801
3.649194
false
false
false
false
laurentvdl/sqlbuilder
src/main/kotlin/sqlbuilder/RowMap.kt
1
1120
package sqlbuilder import java.io.Serializable import java.util.HashMap /** * Wrapper for JDBC rows mapped to both a named and an indexed map. * * @author Laurent Van der Linden */ class RowMap : Serializable { private val named = HashMap<String, Any?>() private val indexed = HashMap<Int, Any?>() fun get(key: String?): Any? { if (key == null) throw NullPointerException("key cannot be null") return named[key.toLowerCase()] } fun get(index: Int): Any? { return indexed[index] } fun put(index: Int, value: Any?): RowMap { indexed.put(index, value) return this } fun put(name: String?, value: Any?): RowMap { if (name == null) throw NullPointerException("name cannot be null") named.put(name.toLowerCase(), value) return this } fun getNamedMap(): Map<String, Any?> { return named } fun getIndexedMap(): Map<Int, Any?> { return indexed } fun size(): Int { return named.size } override fun toString(): String { return named.toString() } }
apache-2.0
e9a5278e3da5a2402c1ac8a7d5823f8e
20.960784
75
0.598214
4.087591
false
false
false
false
kryptnostic/rhizome
src/main/kotlin/com/openlattice/jdbc/DataSourceManager.kt
1
2194
package com.openlattice.jdbc import com.codahale.metrics.MetricRegistry import com.codahale.metrics.health.HealthCheckRegistry import com.geekbeast.configuration.postgres.PostgresConfiguration import com.openlattice.postgres.PostgresTableDefinition import com.openlattice.postgres.PostgresTableManager import com.zaxxer.hikari.HikariConfig import com.zaxxer.hikari.HikariDataSource import org.slf4j.LoggerFactory import org.springframework.stereotype.Component /** * * @author Matthew Tamayo-Rios &lt;[email protected]&gt; */ @Component //Open for mocking class DataSourceManager( dataSourceConfigurations: Map<String, PostgresConfiguration>, healthCheckRegistry: HealthCheckRegistry, metricRegistry: MetricRegistry ) { companion object { private val logger = LoggerFactory.getLogger(DataSourceManager::class.java) const val DEFAULT_DATASOURCE = "default" } private val dataSources = dataSourceConfigurations.mapValues { (dataSourceName, postgresConfiguration) -> val hc = HikariConfig(postgresConfiguration.hikariConfiguration) hc.healthCheckRegistry = healthCheckRegistry hc.metricRegistry = metricRegistry logger.info("JDBC URL = {}", hc.jdbcUrl) return@mapValues HikariDataSource(hc) } private val tableManagers = dataSources.mapValues { (dataSourceName, dataSource) -> val dataSourceConfiguration = dataSourceConfigurations.getValue(dataSourceName) PostgresTableManager( dataSource, dataSourceConfiguration.usingCitus, dataSourceConfiguration.initializeIndices, dataSourceConfiguration.initializeTables ) } fun getDefaultDataSource() = dataSources.getValue(DEFAULT_DATASOURCE) fun getDataSource(name: String) = dataSources.getValue(name) fun registerTables(name: String, vararg tableDefinitions: PostgresTableDefinition) { val tm = tableManagers.getValue(name) tm.registerTables(*tableDefinitions) } fun registerTablesWithAllDatasources(vararg tableDefinitions: PostgresTableDefinition) { tableManagers.values.forEach { it.registerTables(*tableDefinitions) } } }
apache-2.0
3265af04b67d7160bb0690bf7c6736ec
36.844828
109
0.761623
5.03211
false
true
false
false
Nilhcem/devfestnantes-2016
scraper/src/main/kotlin/com/nilhcem/devfestnantes/scraper/App.kt
1
1511
package com.nilhcem.devfestnantes.scraper import com.nilhcem.devfestnantes.scraper.api.DevFestApi import com.nilhcem.devfestnantes.scraper.model.output.Session import com.nilhcem.devfestnantes.scraper.model.output.Speaker import com.squareup.moshi.JsonAdapter import com.squareup.moshi.JsonWriter import com.squareup.moshi.Types import okio.Buffer import java.io.File fun main(args: Array<String>) { with(Scraper(DevFestApi.SERVICE)) { createJsons(speakers, sessions) } } fun createJsons(speakers: List<Speaker>, sessions: List<Session>) { val moshi = DevFestApi.MOSHI File("output").mkdir() File("output/speakers.json").printWriter().use { out -> val buffer = Buffer() val jsonWriter = JsonWriter.of(buffer) jsonWriter.use { jsonWriter.setIndent(" ") val adapter: JsonAdapter<List<Speaker>> = moshi.adapter(Types.newParameterizedType(List::class.java, Speaker::class.java)) adapter.toJson(jsonWriter, speakers) out.println(buffer.readUtf8()) } } File("output/sessions.json").printWriter().use { out -> val buffer = Buffer() val jsonWriter = JsonWriter.of(buffer) jsonWriter.use { jsonWriter.setIndent(" ") val adapter: JsonAdapter<List<Session>> = moshi.adapter(Types.newParameterizedType(List::class.java, Session::class.java)) adapter.toJson(jsonWriter, sessions) out.println(buffer.readUtf8()) } } }
apache-2.0
a4ac42a02d92cf82f3c43a19fe36c2d3
34.139535
134
0.678359
3.986807
false
false
false
false
robfletcher/orca
orca-core/src/main/java/com/netflix/spinnaker/orca/pipeline/model/support/TriggerDeserializer.kt
3
10219
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License") * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.spinnaker.orca.pipeline.model.support import com.fasterxml.jackson.core.JsonParser import com.fasterxml.jackson.databind.DeserializationContext import com.fasterxml.jackson.databind.JsonNode import com.fasterxml.jackson.databind.deser.std.StdDeserializer import com.netflix.spinnaker.orca.api.pipeline.models.PipelineExecution import com.netflix.spinnaker.orca.api.pipeline.models.Trigger import com.netflix.spinnaker.orca.pipeline.model.ArtifactoryTrigger import com.netflix.spinnaker.orca.pipeline.model.ConcourseTrigger import com.netflix.spinnaker.orca.pipeline.model.DefaultTrigger import com.netflix.spinnaker.orca.pipeline.model.DockerTrigger import com.netflix.spinnaker.orca.pipeline.model.GitTrigger import com.netflix.spinnaker.orca.pipeline.model.JenkinsTrigger import com.netflix.spinnaker.orca.pipeline.model.NexusTrigger import com.netflix.spinnaker.orca.pipeline.model.PipelineTrigger import com.netflix.spinnaker.orca.pipeline.model.PluginTrigger class TriggerDeserializer : StdDeserializer<Trigger>(Trigger::class.java) { companion object { val customTriggerSuppliers: MutableSet<CustomTriggerDeserializerSupplier> = mutableSetOf() } override fun deserialize(parser: JsonParser, context: DeserializationContext): Trigger = parser.codec.readTree<JsonNode>(parser).run { return when { looksLikeDocker() -> DockerTrigger( get("type").textValue(), get("correlationId")?.textValue(), get("user")?.textValue() ?: "[anonymous]", get("parameters")?.mapValue(parser) ?: mutableMapOf(), get("artifacts")?.listValue(parser) ?: mutableListOf(), get("notifications")?.listValue(parser) ?: mutableListOf(), get("rebake")?.booleanValue() == true, get("dryRun")?.booleanValue() == true, get("strategy")?.booleanValue() == true, get("account").textValue(), get("repository").textValue(), get("tag").textValue() ) looksLikeConcourse() -> ConcourseTrigger( get("type").textValue(), get("correlationId")?.textValue(), get("user")?.textValue() ?: "[anonymous]", get("parameters")?.mapValue(parser) ?: mutableMapOf(), get("artifacts")?.listValue(parser) ?: mutableListOf(), get("notifications")?.listValue(parser) ?: mutableListOf(), get("rebake")?.booleanValue() == true, get("dryRun")?.booleanValue() == true, get("strategy")?.booleanValue() == true ).apply { buildInfo = get("buildInfo")?.parseValue(parser) properties = get("properties")?.parseValue(parser) ?: mutableMapOf() } looksLikeJenkins() -> JenkinsTrigger( get("type").textValue(), get("correlationId")?.textValue(), get("user")?.textValue() ?: "[anonymous]", get("parameters")?.mapValue(parser) ?: mutableMapOf(), get("artifacts")?.listValue(parser) ?: mutableListOf(), get("notifications")?.listValue(parser) ?: mutableListOf(), get("rebake")?.booleanValue() == true, get("dryRun")?.booleanValue() == true, get("strategy")?.booleanValue() == true, get("master").textValue(), get("job").textValue(), get("buildNumber").intValue(), get("propertyFile")?.textValue() ).apply { buildInfo = get("buildInfo")?.parseValue(parser) properties = get("properties")?.mapValue(parser) ?: mutableMapOf() } looksLikePipeline() -> PipelineTrigger( get("type").textValue(), get("correlationId")?.textValue(), get("user")?.textValue() ?: "[anonymous]", get("parameters")?.mapValue(parser) ?: mutableMapOf(), get("artifacts")?.listValue(parser) ?: mutableListOf(), get("notifications")?.listValue(parser) ?: mutableListOf(), get("rebake")?.booleanValue() == true, get("dryRun")?.booleanValue() == true, get("strategy")?.booleanValue() == true, get("parentExecution").parseValue<PipelineExecution>(parser), get("parentPipelineStageId")?.textValue() ) looksLikeArtifactory() -> ArtifactoryTrigger( get("type").textValue(), get("correlationId")?.textValue(), get("user")?.textValue() ?: "[anonymous]", get("parameters")?.mapValue(parser) ?: mutableMapOf(), get("artifacts")?.listValue(parser) ?: mutableListOf(), get("notifications")?.listValue(parser) ?: mutableListOf(), get("rebake")?.booleanValue() == true, get("dryRun")?.booleanValue() == true, get("strategy")?.booleanValue() == true, get("artifactorySearchName").textValue() ) looksLikeNexus() -> NexusTrigger( get("type").textValue(), get("correlationId")?.textValue(), get("user")?.textValue() ?: "[anonymous]", get("parameters")?.mapValue(parser) ?: mutableMapOf(), get("artifacts")?.listValue(parser) ?: mutableListOf(), get("notifications")?.listValue(parser) ?: mutableListOf(), get("rebake")?.booleanValue() == true, get("dryRun")?.booleanValue() == true, get("strategy")?.booleanValue() == true, get("nexusSearchName").textValue() ) looksLikeGit() -> GitTrigger( get("type").textValue(), get("correlationId")?.textValue(), get("user")?.textValue() ?: "[anonymous]", get("parameters")?.mapValue(parser) ?: mutableMapOf(), get("artifacts")?.listValue(parser) ?: mutableListOf(), get("notifications")?.listValue(parser) ?: mutableListOf(), get("rebake")?.booleanValue() == true, get("dryRun")?.booleanValue() == true, get("strategy")?.booleanValue() == true, get("hash").textValue(), get("source").textValue(), get("project").textValue(), get("branch").textValue(), get("slug").textValue(), get("action")?.textValue() ?: "undefined" ) looksLikePlugin() -> PluginTrigger( get("type").textValue(), get("correlationId")?.textValue(), get("user")?.textValue() ?: "[anonymous]", get("parameters")?.mapValue(parser) ?: mutableMapOf(), get("artifacts")?.listValue(parser) ?: mutableListOf(), get("notifications")?.listValue(parser) ?: mutableListOf(), get("rebake")?.booleanValue() == true, get("dryRun")?.booleanValue() == true, get("strategy")?.booleanValue() == true, get("pluginId").textValue(), get("description")?.textValue() ?: "[no description]", get("provider")?.textValue() ?: "[no provider]", get("version").textValue(), get("releaseDate").textValue(), get("requires").listValue(parser), get("binaryUrl").textValue(), get("preferred").booleanValue() ) looksLikeCustom() -> { // chooses the first custom deserializer to keep behavior consistent // with the rest of this conditional customTriggerSuppliers.first { it.predicate.invoke(this) }.deserializer.invoke(this) } else -> DefaultTrigger( get("type")?.textValue() ?: "none", get("correlationId")?.textValue(), get("user")?.textValue() ?: "[anonymous]", get("parameters")?.mapValue(parser) ?: mutableMapOf(), get("artifacts")?.listValue(parser) ?: mutableListOf(), get("notifications")?.listValue(parser) ?: mutableListOf(), get("rebake")?.booleanValue() == true, get("dryRun")?.booleanValue() == true, get("strategy")?.booleanValue() == true ) }.apply { mapValue<Any>(parser).forEach { (k, v) -> other[k] = v } resolvedExpectedArtifacts = get("resolvedExpectedArtifacts")?.listValue(parser) ?: mutableListOf() } } private fun JsonNode.looksLikeDocker() = hasNonNull("account") && hasNonNull("repository") && hasNonNull("tag") private fun JsonNode.looksLikeGit() = hasNonNull("source") && hasNonNull("project") && hasNonNull("branch") && hasNonNull("slug") && hasNonNull("hash") private fun JsonNode.looksLikeJenkins() = hasNonNull("master") && hasNonNull("job") && hasNonNull("buildNumber") private fun JsonNode.looksLikeConcourse() = get("type")?.textValue() == "concourse" private fun JsonNode.looksLikePipeline() = hasNonNull("parentExecution") private fun JsonNode.looksLikeArtifactory() = hasNonNull("artifactorySearchName") private fun JsonNode.looksLikeNexus() = hasNonNull("nexusSearchName") private fun JsonNode.looksLikePlugin() = hasNonNull("pluginId") private fun JsonNode.looksLikeCustom() = customTriggerSuppliers.any { it.predicate.invoke(this) } private inline fun <reified E> JsonNode.listValue(parser: JsonParser): MutableList<E> = this.map { parser.codec.treeToValue(it, E::class.java) }.toMutableList() private inline fun <reified V> JsonNode.mapValue(parser: JsonParser): MutableMap<String, V> { val m = mutableMapOf<String, V>() this.fields().asSequence().forEach { entry -> m[entry.key] = parser.codec.treeToValue(entry.value, V::class.java) } return m } private inline fun <reified T> JsonNode.parseValue(parser: JsonParser): T = parser.codec.treeToValue(this, T::class.java) }
apache-2.0
d1c94230600e7290365ad2ffcd030cb3
44.017621
117
0.621392
4.766325
false
false
false
false
jiaminglu/kotlin-native
backend.native/tests/external/codegen/box/reflection/mapping/types/parameterizedTypes.kt
2
1331
// TODO: muted automatically, investigate should it be ran for JS or not // IGNORE_BACKEND: JS, NATIVE // WITH_REFLECT // FULL_JDK import java.lang.reflect.ParameterizedType import kotlin.reflect.* import kotlin.reflect.jvm.javaType import kotlin.test.assertEquals class A(private var foo: List<String>) object O { @JvmStatic private var bar: List<String> = listOf() } fun topLevel(): List<String> = listOf() fun Any.extension(): List<String> = listOf() fun assertGenericType(type: KType) { val javaType = type.javaType if (javaType !is ParameterizedType) { throw AssertionError("Type should be a parameterized type, but was $javaType (${javaType.javaClass})") } } fun box(): String { val foo = A::class.members.single { it.name == "foo" } as KMutableProperty<*> assertGenericType(foo.returnType) assertGenericType(foo.getter.returnType) assertGenericType(foo.setter.parameters.last().type) val bar = O::class.members.single { it.name == "bar" } as KMutableProperty<*> assertGenericType(bar.returnType) assertGenericType(bar.getter.returnType) assertGenericType(bar.setter.parameters.last().type) assertGenericType(::topLevel.returnType) assertGenericType(Any::extension.returnType) assertGenericType(::A.parameters.single().type) return "OK" }
apache-2.0
a39905035243f54f7d83da161343d656
28.577778
110
0.720511
3.996997
false
false
false
false
savvasdalkitsis/gameframe
workspace/src/main/java/com/savvasdalkitsis/gameframe/feature/workspace/view/WorkspaceFragment.kt
1
17717
/** * Copyright 2017 Savvas Dalkitsis * 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. * * 'Game Frame' is a registered trademark of LEDSEQ */ package com.savvasdalkitsis.gameframe.feature.workspace.view import android.annotation.SuppressLint import android.os.Bundle import android.support.annotation.ColorInt import android.support.design.internal.NavigationMenu import android.support.v4.widget.DrawerLayout import android.util.Log import android.view.* import com.afollestad.materialdialogs.MaterialDialog import com.afollestad.materialdialogs.color.ColorChooserDialog import com.savvasdalkitsis.gameframe.feature.analytics.injector.AnalyticsInjector import com.savvasdalkitsis.gameframe.feature.history.usecase.HistoryUseCase import com.savvasdalkitsis.gameframe.feature.message.Snackbars import com.savvasdalkitsis.gameframe.feature.workspace.R import com.savvasdalkitsis.gameframe.feature.workspace.element.grid.model.Grid import com.savvasdalkitsis.gameframe.feature.workspace.element.layer.model.Layer import com.savvasdalkitsis.gameframe.feature.workspace.element.palette.model.Palette import com.savvasdalkitsis.gameframe.feature.workspace.element.palette.view.AddNewPaletteSelectedListener import com.savvasdalkitsis.gameframe.feature.workspace.element.palette.view.AddPaletteView import com.savvasdalkitsis.gameframe.feature.workspace.element.palette.view.PaletteView import com.savvasdalkitsis.gameframe.feature.workspace.element.swatch.view.SwatchSelectedListener import com.savvasdalkitsis.gameframe.feature.workspace.element.swatch.view.SwatchView import com.savvasdalkitsis.gameframe.feature.workspace.element.tools.model.Tools import com.savvasdalkitsis.gameframe.feature.workspace.element.tools.view.ToolSelectedListener import com.savvasdalkitsis.gameframe.feature.workspace.injector.WorkspaceInjector.workspacePresenter import com.savvasdalkitsis.gameframe.feature.workspace.model.WorkspaceModel import com.savvasdalkitsis.gameframe.feature.workspace.presenter.WorkspacePresenter import com.savvasdalkitsis.gameframe.infra.android.BaseFragment import com.savvasdalkitsis.gameframe.infra.android.FragmentSelectedListener import com.savvasdalkitsis.gameframe.kotlin.Action import com.savvasdalkitsis.gameframe.kotlin.TypeAction import com.savvasdalkitsis.gameframe.kotlin.gone import com.savvasdalkitsis.gameframe.kotlin.visible import com.sothree.slidinguppanel.SlidingUpPanelLayout import io.github.yavski.fabspeeddial.CustomFabSpeedDial import io.github.yavski.fabspeeddial.SimpleMenuListenerAdapter import kotlinx.android.synthetic.main.fragment_workspace.* @SuppressLint("RtlHardcoded") private const val GRAVITY_PALETTES = Gravity.LEFT @SuppressLint("RtlHardcoded") private const val GRAVITY_LAYERS = Gravity.RIGHT class WorkspaceFragment : BaseFragment<WorkspaceView<Menu>, WorkspacePresenter<Menu, View>>(), FragmentSelectedListener, SwatchSelectedListener, WorkspaceView<Menu>, ColorChooserDialog.ColorCallback, ToolSelectedListener { private lateinit var fab: CustomFabSpeedDial private lateinit var drawer: DrawerLayout private val analytics = AnalyticsInjector.analytics() override val presenter = workspacePresenter() override val view = this private var swatchToModify: SwatchView? = null private var selected: Boolean = false private var activeSwatch: SwatchView? = null override val layoutId: Int get() = R.layout.fragment_workspace override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setHasOptionsMenu(true) } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) fab = activity!!.findViewById(R.id.view_fab_workspace) view_draw_tools.setOnToolSelectedListener(this) view_draw_tools_current.bind(Tools.defaultTool()) view_draw_sliding_up_panel.addPanelSlideListener(object : SlidingUpPanelLayout.SimplePanelSlideListener() { override fun onPanelStateChanged(panel: View?, previousState: SlidingUpPanelLayout.PanelState?, newState: SlidingUpPanelLayout.PanelState?) { val scale = if (newState == SlidingUpPanelLayout.PanelState.EXPANDED) 0f else 1f fab.visible() fab.animate().scaleY(scale).scaleX(scale) .withEndAction { if (scale == 0f) fab.gone() } .start() } }) drawer.addDrawerListener(object : DrawerLayout.SimpleDrawerListener() { override fun onDrawerOpened(drawerView: View) { setFabState() } override fun onDrawerClosed(drawerView: View) { setFabState() } }) drawer.addDrawerListener(object: DrawerLayout.SimpleDrawerListener() { override fun onDrawerOpened(drawerView: View) { if (drawer.isDrawerOpen(GRAVITY_LAYERS)) { analytics.logEvent("layers_open") } if (drawer.isDrawerOpen(GRAVITY_PALETTES)) { analytics.logEvent("palettes_open") } } }) view_draw_open_layers.setOnClickListener { drawer.openDrawer(GRAVITY_LAYERS) } view_draw_open_palette.setOnClickListener { drawer.openDrawer(GRAVITY_PALETTES) } listOf(view_draw_tools_change, view_draw_tools_current).forEach { it.setOnClickListener { view_draw_sliding_up_panel.panelState = SlidingUpPanelLayout.PanelState.EXPANDED } } listOf(view_draw_add_palette, view_draw_add_palette_title).forEach { it.setOnClickListener { addNewPalette() } } } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) drawer = view.findViewById(R.id.view_draw_drawer) view_draw_led_grid_view.setOnGridTouchedListener(presenter) } override fun wifiNotEnabledError(e: Throwable) { Snackbars.actionError(coordinator(), R.string.wifi_not_enabled, R.string.enable) { presenter.enableWifi() } } override fun onResume() { super.onResume() setFabState() presenter.bindGrid(view_draw_led_grid_view) } override fun onPause() { super.onPause() presenter.paused() } override fun bindPalette(selectedPalette: Palette) { val paletteView = drawer.findViewById<PaletteView>(R.id.view_draw_palette) paletteView.bind(selectedPalette) paletteView.setOnSwatchSelectedListener(this) } override fun onCreateOptionsMenu(menu: Menu?, inflater: MenuInflater) { if (selected) { inflater.inflate(R.menu.menu_workspace, menu) } } override fun onOptionsItemSelected(item: MenuItem) = when (item.itemId) { R.id.menu_borders -> { presenter.selectedOptionBorders() true } R.id.menu_undo -> { presenter.selectedOptionUndo() true } R.id.menu_redo -> { presenter.selectedOptionRedo() true } else -> false } override fun onPrepareOptionsMenu(menu: Menu) { presenter.prepareOptions(menu) } override fun displayLayoutBordersEnabled(options: Menu) { options.findItem(R.id.menu_borders)?.setIcon(R.drawable.ic_border_outer_white_48px) } override fun displayLayoutBordersDisabled(options: Menu) { options.findItem(R.id.menu_borders)?.setIcon(R.drawable.ic_border_clear_white_48px) } override fun enableUndo(options: Menu) { options[R.id.menu_undo]?.alpha(255) } override fun disableUndo(options: Menu) { options[R.id.menu_undo]?.alpha(125) } override fun enableRedo(options: Menu) { options[R.id.menu_redo]?.alpha(255) } override fun disableRedo(options: Menu) { options[R.id.menu_redo]?.alpha(125) } private operator fun Menu.get(id: Int): MenuItem? = findItem(id) private fun MenuItem.alpha(alpha: Int) { icon.alpha = alpha } override fun onFragmentSelected() { selected = true fab.visible() invalidateOptionsMenu() } override fun onFragmentUnselected() { selected = false fab.gone() invalidateOptionsMenu() } override fun observe(history: HistoryUseCase<WorkspaceModel>) { view_draw_layers.bind(history) { drawer.closeDrawer(GRAVITY_LAYERS) } view_draw_palettes.bind(history) { drawer.closeDrawer(GRAVITY_PALETTES) } } override fun onSwatchSelected(swatchView: SwatchView) { this.activeSwatch = swatchView } override fun onSwatchLongPressed(swatch: SwatchView) { swatchToModify = swatch ColorChooserDialog.Builder(context!!, R.string.change_color) .show(activity) } override fun onColorSelection(dialog: ColorChooserDialog, @ColorInt selectedColor: Int) { swatchToModify?.let { presenter.changeColor(it.color, selectedColor, it.index) } } override fun onColorChooserDismissed(dialog: ColorChooserDialog) {} override fun drawLayer(layer: Layer, startColumn: Int, startRow: Int, column: Int, row: Int) { activeSwatch?.let { view_draw_tools_current.drawingTool?.drawOn(layer, startColumn, startRow, column, row, it.color) } } override fun finishStroke(layer: Layer) { view_draw_tools_current.drawingTool?.finishStroke(layer) } @SuppressLint("SetTextI18n") override fun onToolSelected(tool: Tools) { view_draw_tools_current.bind(tool) view_draw_sliding_up_panel.panelState = SlidingUpPanelLayout.PanelState.HIDDEN view_draw_tools_change.text = "${tool.label}:" } override fun askForFileName(positiveText: Int, nameEntered: TypeAction<String>, cancelAction: Action) { MaterialDialog.Builder(activity!!) .input(R.string.name_of_drawing, 0, false) { _, input -> nameEntered(input.toString()) } .title(R.string.enter_name_for_drawing) .positiveText(positiveText) .negativeText(android.R.string.cancel) .onNegative { _, _ -> cancelAction() } .canceledOnTouchOutside(true) .cancelListener { cancelAction() } .build() .show() } override fun displayProgress() { fab.startProgress() } override fun stopProgress() { fab.stopProgress(R.drawable.ic_import_export_white_48px) } override fun drawingAlreadyExists(name: String, colorGrid: Grid, e: Throwable) { Log.e(WorkspacePresenter::class.java.name, "Drawing already exists", e) Snackbars.actionError(coordinator(), R.string.already_exists, R.string.replace, { presenter.replaceDrawing(name, colorGrid) }) stopProgress() } override fun displaySelectedPalette(paletteName: String) { view_draw_palette_name.text = paletteName } fun addNewPalette() { AddPaletteView.show(context!!, drawer, object : AddNewPaletteSelectedListener { override fun onAddNewPalletSelected(palette: Palette) { view_draw_palettes.addNewPalette(palette) } }) } private fun setFabState() = with(fab) { when { drawer.isDrawerOpen(GRAVITY_LAYERS) -> { setMenuListener(addNewLayerOperation()) setImageResource(R.drawable.ic_add_white_48px) } drawer.isDrawerOpen(GRAVITY_PALETTES) -> { setMenuListener(addNewPaletteOperation()) setImageResource(R.drawable.ic_add_white_48px) } else -> { setMenuListener(standardOperation()) setImageResource(R.drawable.ic_import_export_white_48px) } } } private fun addNewPaletteOperation() = object : SimpleMenuListenerAdapter() { override fun onPrepareMenu(navigationMenu: NavigationMenu?): Boolean { analytics.logEvent("add_new_palette") addNewPalette() return false } } private fun addNewLayerOperation() = object : SimpleMenuListenerAdapter() { override fun onPrepareMenu(navigationMenu: NavigationMenu?): Boolean { analytics.logEvent("add_new_layer") view_draw_layers.addNewLayer() return false } } private fun standardOperation() = object : SimpleMenuListenerAdapter() { override fun onPrepareMenu(navigationMenu: NavigationMenu?): Boolean { analytics.logEvent("workspace_fab_open") return true } override fun onMenuItemSelected(menuItem: MenuItem) = when (menuItem.itemId) { R.id.operation_upload -> { presenter.upload(view_draw_led_grid_view.colorGrid) true } R.id.operation_save -> { presenter.saveWorkspace() true } R.id.operation_open -> { presenter.loadProject() true } R.id.operation_delete -> { presenter.deleteProjects() true } R.id.operation_new -> { presenter.createNewProject() true } R.id.operation_export -> { presenter.exportImage(view_draw_led_grid_view) true } else -> false } } override fun askForApprovalToDismissChanges() { MaterialDialog.Builder(context!!) .title(R.string.dismiss_changes_question) .content(R.string.unsaved_changes) .positiveText(R.string.dismiss) .negativeText(R.string.do_not_dismiss) .onPositive { _, _ -> presenter.createNewProject(true) } .show() } override fun askForProjectToLoad(projectNames: List<String>) { MaterialDialog.Builder(context!!) .title(R.string.load_project) .items(projectNames) .itemsCallbackSingleChoice(-1) { _, _, which, _ -> presenter.loadProject(projectNames[which]) true } .show() } override fun displayUnsupportedVersion() { MaterialDialog.Builder(context!!) .title(R.string.unsupported_version) .content(R.string.unsupported_version_description) .positiveText(R.string.play_store) .negativeText(R.string.cancel) .onPositive { _, _ -> presenter.takeUserToPlayStore() } .show() } override fun askForProjectsToDelete(projectNames: List<String>) { MaterialDialog.Builder(context!!) .title(R.string.delete_projects) .items(projectNames) .itemsCallbackMultiChoice(null) { _, which, _ -> presenter.deleteProjects(which.map { projectNames[it] }) true } .positiveText(R.string.delete) .show() } override fun displayNoSavedProjectsExist() { Snackbars.error(coordinator(), R.string.no_saved_projects) stopProgress() } override fun displayProjectName(name: String) { view_draw_project_name.text = name } override fun displaySelectedLayerName(layerName: String) { view_draw_layer_name.text = layerName } private fun coordinator() = activity!!.findViewById<View>(R.id.view_coordinator) override fun displayBoundaries(col: Int, row: Int) { view_draw_led_grid_view.displayBoundaries(col, row) } override fun clearBoundaries() { view_draw_led_grid_view.clearBoundaries() } override fun rendered() { view_draw_led_grid_view.invalidate() invalidateOptionsMenu() } private fun invalidateOptionsMenu() { activity!!.invalidateOptionsMenu() } override fun showSuccess() { Snackbars.success(coordinator(), R.string.success) stopProgress() } override fun operationFailed(e: Throwable) { Log.e(WorkspacePresenter::class.java.name, "Workspace operation failed", e) Snackbars.error(coordinator(), R.string.operation_failed) stopProgress() } override fun upsellAccount(takeMeThere: Action, continueSaving: Action) { MaterialDialog.Builder(context!!) .title(R.string.save_drawings_on_cloud) .content(R.string.never_lose_your_drawings) .positiveText(R.string.yes_please) .negativeText(R.string.no_just_save) .onPositive { _,_ -> takeMeThere()} .onNegative { _,_ -> continueSaving()} .show() } }
apache-2.0
a30c7a2b79310942dddb4e078d922d16
35.987474
153
0.649771
4.600623
false
false
false
false
zlyne0/colonization
core/src/net/sf/freecol/common/model/ai/missions/pioneer/TakeRoleEquipmentMission.kt
1
4371
package net.sf.freecol.common.model.ai.missions.pioneer import net.sf.freecol.common.model.Colony import net.sf.freecol.common.model.ColonyId import net.sf.freecol.common.model.Game import net.sf.freecol.common.model.Specification import net.sf.freecol.common.model.Unit import net.sf.freecol.common.model.UnitRole import net.sf.freecol.common.model.ai.missions.AbstractMission import net.sf.freecol.common.model.ai.missions.PlayerMissionsContainer import net.sf.freecol.common.model.ai.missions.UnitMissionsMapping import net.sf.freecol.common.model.player.Player import promitech.colonization.ai.CommonMissionHandler import promitech.colonization.savegame.XmlNodeAttributes import promitech.colonization.savegame.XmlNodeAttributesWriter class TakeRoleEquipmentMission : AbstractMission { var unit: Unit private set val colonyId: ColonyId val role: UnitRole val roleCount: Int constructor(unit: Unit, colony: Colony, role: UnitRole, roleCount: Int = role.maximumCount) : super(Game.idGenerator.nextId(TakeRoleEquipmentMission::class.java)) { this.unit = unit this.colonyId = colony.id this.role = role this.roleCount = roleCount } private constructor(missionId: String, unit: Unit, colonyId: ColonyId, role: UnitRole, roleCount: Int) : super(missionId) { this.unit = unit this.colonyId = colonyId this.role = role this.roleCount = roleCount } internal fun isUnitExists(player: Player): Boolean { return CommonMissionHandler.isUnitExists(player, unit) } internal fun isColonyExist(player: Player): Boolean { return player.settlements.containsId(colonyId) } internal fun colony(): Colony = unit.owner.settlements.getById(colonyId).asColony() override fun blockUnits(unitMissionsMapping: UnitMissionsMapping) { unitMissionsMapping.blockUnit(unit, this) } override fun unblockUnits(unitMissionsMapping: UnitMissionsMapping) { unitMissionsMapping.unblockUnitFromMission(unit, this) } internal fun changeUnit(unitToReplace: Unit, replaceBy: Unit, playerMissionsContainer: PlayerMissionsContainer) { if (unit.equalsId(unitToReplace)) { playerMissionsContainer.unblockUnitFromMission(unit, this) unit = replaceBy playerMissionsContainer.blockUnitForMission(unit, this) } } fun makeReservation(game: Game, player: Player) { val requiredGoods = role.requiredGoodsForRoleCount(roleCount) val playerAiContainer = game.aiContainer.playerAiContainer(player) val colonySupplyGoods = playerAiContainer.findOrCreateColonySupplyGoods(colonyId) colonySupplyGoods.makeReservation(getId(), requiredGoods) } override fun toString(): String { return "TakeRoleEquipmentMission unitId: ${unit.id}, colonyId: ${colonyId}, role: ${role.id}, roleCount: ${roleCount}" } class Xml : AbstractMission.Xml<TakeRoleEquipmentMission>() { private val ATTR_UNIT = "unit" private val ATTR_COLONY = "colony" private val ATTR_ROLE_TYPE = "role" private val ATTR_ROLE_COUNT = "roleCount" override fun startElement(attr: XmlNodeAttributes) { nodeObject = TakeRoleEquipmentMission( missionId = attr.id, unit = PlayerMissionsContainer.Xml.getPlayerUnit(attr.getStrAttribute(ATTR_UNIT)), colonyId = attr.getStrAttribute(ATTR_COLONY), role = attr.getEntity(ATTR_ROLE_TYPE, Specification.instance.unitRoles), roleCount = attr.getIntAttribute(ATTR_ROLE_COUNT) ) super.startElement(attr) } override fun startWriteAttr(mission: TakeRoleEquipmentMission, attr: XmlNodeAttributesWriter) { super.startWriteAttr(mission, attr) attr.setId(mission) attr.set(ATTR_UNIT, mission.unit) attr.set(ATTR_COLONY, mission.colonyId) attr.set(ATTR_ROLE_TYPE, mission.role) attr.set(ATTR_ROLE_COUNT, mission.roleCount) } override fun getTagName(): String { return tagName() } companion object { @JvmStatic fun tagName(): String { return "takeRoleEquipmentMission" } } } }
gpl-2.0
d27104dea6be5e713d97c85851d0fb7e
37.017391
127
0.690689
4.327723
false
false
false
false
PolymerLabs/arcs
java/arcs/core/data/expression/InferredType.kt
1
5250
package arcs.core.data.expression import arcs.core.util.ArcsInstant import arcs.core.util.BigInt import kotlin.reflect.KClass /** * Matches [widenAndApply] in Expression.kt * * The types are listed in terms of decreasing width, so that a type at position n can always * be widened to a type at position n - 1. */ private val widenOrder = listOf<InferredType.Primitive>( InferredType.Primitive.NumberType, InferredType.Primitive.DoubleType, InferredType.Primitive.FloatType, InferredType.Primitive.BigIntType, InferredType.Primitive.LongType, InferredType.Primitive.IntType, InferredType.Primitive.ShortType, InferredType.Primitive.ByteType ) /** Convert a [KClass] into an appropriate [InferredType] */ fun KClass<*>.toType() = InferredType.Primitive.of(this) /** Widen a list of types to the largest type that encompasses all of them. */ fun widen(vararg types: InferredType): InferredType.Primitive { types.forEach { require(it is InferredType.Numeric) { "$it is not numeric" } } return widenOrder.firstOrNull { types.contains(it) } ?: throw IllegalArgumentException("$types contains incompatible types.") } /** * An [InferredType] is based on following a tree of DSL expressions from the leaves to the root, * flowing types upward so that each node can be assigned a conservative bound on the types it * may output. */ sealed class InferredType { /** True of this type can be assigned the [other] type. */ open fun isAssignableFrom(other: InferredType): Boolean = this == other /** Union two types together to create an [UnionType]. */ fun union(other: InferredType) = UnionType(this, other) /** Subtract the type from this type if possible. */ open fun nonNull(): InferredType = this /** Represents all primitive types such as numbers, text, booleans, etc. */ sealed class Primitive(val kClass: KClass<*>) : InferredType() { override fun isAssignableFrom(other: InferredType): Boolean = when { this is Numeric && other is Numeric -> widen(this, other) == this else -> this == other } override fun toString() = "${kClass.simpleName ?: super.toString()}" object DoubleType : Primitive(Double::class), Numeric object FloatType : Primitive(Float::class), Numeric object BigIntType : Primitive(BigInt::class), Numeric object LongType : Primitive(Long::class), Numeric object IntType : Primitive(Int::class), Numeric object ShortType : Primitive(Short::class), Numeric object ByteType : Primitive(Byte::class), Numeric object NumberType : Primitive(Number::class), Numeric object BooleanType : Primitive(Boolean::class) object TextType : Primitive(String::class) object CharType : Primitive(Char::class) object InstantType : Primitive(ArcsInstant::class), Numeric object NullType : Primitive(NullType::class) companion object { private val kclassToType by lazy { listOf( DoubleType, FloatType, BigIntType, LongType, IntType, ShortType, ByteType, NumberType, BooleanType, TextType, CharType, InstantType, NullType ).associateBy({ it.kClass }, { it }) } /** All primitive types. */ val allTypes by lazy { kclassToType.values.toSet() } /** Given a [KClass] return the corresponding [InferredType]. */ fun of(kClass: KClass<*>) = requireNotNull(kclassToType[kClass]) { "Unable to map $kClass to an InferredType." } } } /** Represents union of several possible types. */ data class UnionType(val types: Set<InferredType>) : InferredType() { constructor(vararg types: InferredType) : this(setOf(*types)) override fun nonNull(): InferredType = UnionType(types.map { it.nonNull() }.filterNot { it is Primitive.NullType }.toSet()) override fun toString() = "${types.joinToString(separator = "|")}" override fun isAssignableFrom(other: InferredType): Boolean = when (other) { is UnionType -> other.types.all { this.isAssignableFrom(it) } else -> types.any { it.isAssignableFrom(other) } } } /** Represents a sequence of values of the given type. */ data class SeqType(val type: InferredType) : InferredType() { override fun toString() = "Sequence<$type>" override fun isAssignableFrom(other: InferredType): Boolean = when (other) { is SeqType -> type.isAssignableFrom(other.type) else -> false } } /** Represents a type corresponding to a scope with variables of various types. */ data class ScopeType(val scope: Expression.Scope) : InferredType() { override fun toString() = "$scope" override fun isAssignableFrom(other: InferredType): Boolean { if (other !is ScopeType) { return false } val keys = scope.properties() val otherKeys = other.scope.properties() if (!keys.containsAll(otherKeys)) { return false } return otherKeys.all { scope.lookup<InferredType>(it) == other.scope.lookup<InferredType>(it) } } } /** Tagging interface for all [Primitive] types that are numeric. */ interface Numeric }
bsd-3-clause
ac466b32833bccf56e5762861909878c
32.870968
97
0.675429
4.371357
false
false
false
false
Maccimo/intellij-community
plugins/kotlin/jvm-debugger/core-fe10/src/org/jetbrains/kotlin/idea/debugger/ToggleKotlinVariablesView.kt
2
1893
// 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 import com.intellij.ide.util.PropertiesComponent import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.ToggleAction import com.intellij.openapi.components.service import com.intellij.xdebugger.XDebugSession import com.intellij.xdebugger.impl.XDebuggerUtilImpl import org.jetbrains.kotlin.idea.base.util.KOTLIN_FILE_EXTENSIONS class ToggleKotlinVariablesState { companion object { private const val KOTLIN_VARIABLE_VIEW = "debugger.kotlin.variable.view" fun getService(): ToggleKotlinVariablesState = service() } var kotlinVariableView = PropertiesComponent.getInstance().getBoolean(KOTLIN_VARIABLE_VIEW, true) set(newValue) { field = newValue PropertiesComponent.getInstance().setValue(KOTLIN_VARIABLE_VIEW, newValue) } } class ToggleKotlinVariablesView : ToggleAction() { private val kotlinVariableViewService = ToggleKotlinVariablesState.getService() override fun update(e: AnActionEvent) { super.update(e) val session = XDebugSession.DATA_KEY.getData(e.dataContext) e.presentation.isEnabledAndVisible = session != null && session.isInKotlinFile() } private fun XDebugSession.isInKotlinFile(): Boolean { val fileExtension = currentPosition?.file?.extension ?: return false return fileExtension in KOTLIN_FILE_EXTENSIONS } override fun isSelected(e: AnActionEvent) = kotlinVariableViewService.kotlinVariableView override fun setSelected(e: AnActionEvent, state: Boolean) { kotlinVariableViewService.kotlinVariableView = state XDebuggerUtilImpl.rebuildAllSessionsViews(e.project) } }
apache-2.0
f124f28e2408cf3523aa6e5203a33736
39.297872
158
0.758584
4.853846
false
false
false
false
Maccimo/intellij-community
plugins/devkit/devkit-core/src/inspections/ExtensionPointUsageAnalyzer.kt
1
28874
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.idea.devkit.inspections import com.intellij.codeInsight.hint.HintManager import com.intellij.codeInspection.dataFlow.JavaMethodContractUtil import com.intellij.lang.LanguageExtension import com.intellij.navigation.ItemPresentation import com.intellij.openapi.actionSystem.ActionUpdateThread import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.CommonDataKeys import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.runReadAction import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.markup.TextAttributes import com.intellij.openapi.extensions.ExtensionPointName import com.intellij.openapi.extensions.ProjectExtensionPointName import com.intellij.openapi.fileEditor.FileEditorLocation import com.intellij.openapi.module.ModuleUtil import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.progress.Task import com.intellij.openapi.project.Project import com.intellij.openapi.roots.ProjectRootManager import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.util.text.StringUtil import com.intellij.openapi.vfs.VirtualFile import com.intellij.openapi.wm.WindowManager import com.intellij.pom.Navigatable import com.intellij.psi.* import com.intellij.psi.impl.source.PsiClassReferenceType import com.intellij.psi.search.GlobalSearchScopesCore import com.intellij.psi.search.scope.ProjectProductionScope import com.intellij.psi.search.searches.MethodReferencesSearch import com.intellij.psi.search.searches.ReferencesSearch import com.intellij.psi.util.InheritanceUtil import com.intellij.psi.util.PsiTreeUtil import com.intellij.psi.xml.XmlTag import com.intellij.usages.* import com.intellij.usages.rules.PsiElementUsage import com.intellij.util.Processor import com.intellij.util.containers.ContainerUtil import com.intellij.util.xml.DomManager import org.jetbrains.annotations.Nls import org.jetbrains.annotations.NonNls import org.jetbrains.idea.devkit.DevKitBundle import org.jetbrains.idea.devkit.dom.Extension import org.jetbrains.idea.devkit.dom.ExtensionPoint import org.jetbrains.idea.devkit.dom.ExtensionPoints import org.jetbrains.idea.devkit.util.ExtensionPointLocator import org.jetbrains.idea.devkit.util.locateExtensionsByPsiClass import org.jetbrains.uast.* import java.awt.Font import javax.swing.Icon data class Leak(@Nls val reason: String, val targetElement: PsiElement?) private data class QualifiedCall(val callExpression: UCallExpression, val fullExpression: UExpression) private fun findQualifiedCall(element: UElement?): QualifiedCall? { val callExpression = element?.getParentOfType<UCallExpression>() if (callExpression != null && element == callExpression.receiver) { return QualifiedCall(callExpression, callExpression) } val qualifiedExpression = element?.getParentOfType<UQualifiedReferenceExpression>() if (qualifiedExpression != null && qualifiedExpression.receiver == element) { val selector = qualifiedExpression.selector if (selector is UCallExpression) { return QualifiedCall(selector, qualifiedExpression) } } return null } internal class LeakSearchContext(val project: Project, private val epName: String?, private val ignoreSafeClasses: Boolean) { @NonNls private val SAFE_CLASSES = setOf(CommonClassNames.JAVA_LANG_STRING, "javax.swing.Icon", "java.net.URL", "java.io.File", "java.net.URI", "com.intellij.openapi.vfs.pointers.VirtualFilePointer", "com.intellij.openapi.vfs.VirtualFile") @NonNls private val ANONYMOUS_PASS_THROUGH = mapOf("com.intellij.openapi.util.NotNullLazyValue" to "compute") private val searchScope = GlobalSearchScopesCore.filterScope(project, ProjectProductionScope.INSTANCE) private val classSafe = mutableMapOf<PsiClass, Boolean>() private val processedObjects = mutableSetOf<UExpression>() val unsafeUsages = mutableListOf<Pair<PsiReference, Leak>>() val safeUsages = mutableListOf<PsiReference>() fun processEPFieldUsages(sourcePsi: PsiElement) { ReferencesSearch.search(sourcePsi).forEach { ref -> val leaks = runReadAction { analyzeEPUsage(ref) } if (leaks.isEmpty()) { safeUsages.add(ref) } else { for (leak in leaks) { unsafeUsages.add(ref to leak) } } } WindowManager.getInstance().getStatusBar(project)?.info = "" } private fun analyzeEPUsage(reference: PsiReference): List<Leak> { val containingFile = reference.element.containingFile val containingFileName = FileUtil.getNameWithoutExtension(containingFile.name) if (containingFileName.endsWith("CoreEnvironment") || containingFileName.endsWith("CoreApplicationEnvironment")) { // dynamic extension registration in EP is safe return emptyList() } if (ProjectRootManager.getInstance(containingFile.project).fileIndex.isInTestSourceContent(containingFile.virtualFile)) { return emptyList() } if (PsiTreeUtil.getNonStrictParentOfType(reference.element, PsiComment::class.java) != null) { return emptyList() } val element = reference.element.toUElement() val qualifiedCall = findQualifiedCall(element) if (qualifiedCall != null) { val methodName = qualifiedCall.callExpression.methodName if (methodName == "getExtensions" || methodName == "getExtensionList" || methodName == "allForLanguage") { return analyzeGetExtensionsCall(qualifiedCall.fullExpression) } if (methodName == "findExtension" || methodName == "forLanguage") { return findObjectLeaks(qualifiedCall.callExpression, DevKitBundle.message("extension.point.analyzer.reason.extension.instance")) } if (methodName == "getName") { return emptyList() } } var parent = element?.uastParent while (parent is UQualifiedReferenceExpression && parent.selector == element) { parent = parent.uastParent } if (parent is UQualifiedReferenceExpression) { val name = (parent.referenceNameElement as? UIdentifier)?.name if (name == "extensions" || name == "extensionList") { // NON-NLS return analyzeGetExtensionsCall(parent) } } return listOf(Leak(DevKitBundle.message("extension.point.analyzer.reason.unknown.usage"), reference.element)) } private fun analyzeGetExtensionsCall(fullExpression: UExpression): List<Leak> { val loop = fullExpression.getParentOfType<UForEachExpression>() if (loop != null) { if (fullExpression != loop.iteratedValue) return listOf( Leak(DevKitBundle.message("extension.point.analyzer.reason.call.not.loop.value"), fullExpression.sourcePsi)) return findVariableUsageLeaks(loop.variable, DevKitBundle.message("extension.point.analyzer.reason.extension.instance")) } return findObjectLeaks(fullExpression, DevKitBundle.message("extension.point.analyzer.reason.extension.list")) } private fun findEnclosingCall(expr: UElement?): UCallExpression? { val call = expr?.getParentOfType<UCallExpression>() if (call != null && call.valueArguments.contains(expr)) return call val qualifiedExpression = expr?.getParentOfType<UQualifiedReferenceExpression>() if (qualifiedExpression != null && qualifiedExpression.receiver == expr) { return qualifiedExpression.selector as? UCallExpression } return null } private fun findLeaksThroughCall(call: UCallExpression, text: String): List<Leak> { val callee = call.resolve() ?: return listOf(Leak(DevKitBundle.message("extension.point.analyzer.reason.unresolved.method.call"), call.sourcePsi)) if (isSafeCall(callee)) { val type = call.returnType if (type == null || isSafeType(type)) return emptyList() return findObjectLeaks(call, DevKitBundle.message("extension.point.analyzer.reason.return.value", text, callee.name, type.presentableText)) } return listOf(Leak(DevKitBundle.message("extension.point.analyzer.reason.impure.method", text), call.sourcePsi)) } private fun isSafeCall(callee: PsiMethod): Boolean { if (JavaMethodContractUtil.isPure(callee)) return true // Not marked as pure because it's unclear whether side effects from 'compute' are acceptable if (callee.name == "getValue" && callee.containingClass?.qualifiedName == "com.intellij.openapi.util.NotNullLazyValue") return true // Not marked as pure because can reorder items for LinkedHashMap, but it's safe here if (callee.name == "get" && callee.containingClass?.qualifiedName == CommonClassNames.JAVA_UTIL_MAP) return true return false } private fun isSafeType(type: PsiType?): Boolean { if (!ignoreSafeClasses) return false return when (type) { null -> false is PsiPrimitiveType -> true is PsiArrayType -> isSafeType(type.deepComponentType) is PsiClassType -> { val resolveResult = type.resolveGenerics() val psiClass = resolveResult.element ?: return false var safe = classSafe.putIfAbsent(psiClass, true) if (safe == null) { safe = isSafeClass(resolveResult) classSafe[psiClass] = safe } safe } else -> false } } private fun isSafeClass(resolveResult: PsiClassType.ClassResolveResult): Boolean { val psiClass = resolveResult.element ?: return false val substitutor = resolveResult.substitutor return when { SAFE_CLASSES.contains(psiClass.qualifiedName) -> true psiClass.isEnum -> true InheritanceUtil.isInheritor(psiClass, "com.intellij.psi.PsiElement") -> true isConcreteExtension(psiClass) -> true psiClass.hasModifierProperty(PsiModifier.FINAL) -> { psiClass.allFields.any { f -> isSafeType(substitutor.substitute(f.type)) } } else -> false } } private fun isConcreteExtension(psiClass: PsiClass): Boolean { if (epName == null) return false val extension = ContainerUtil.getOnlyItem(locateExtensionsByPsiClass(psiClass))?.pointer?.element ?: return false val extensionTag = DomManager.getDomManager(project).getDomElement(extension) as? Extension val extensionPoint = extensionTag?.extensionPoint ?: return false if (extensionPoint.effectiveQualifiedName != epName) return false val effectiveClass = extensionPoint.effectiveClass return effectiveClass != null && psiClass.isInheritor(effectiveClass, true) } private fun findObjectLeaks(e: UElement, @Nls text: String): List<Leak> { val targetElement = e.sourcePsi if (e is UExpression && targetElement != null) { if (!processedObjects.add(e)) { return emptyList() } WindowManager.getInstance().getStatusBar(project)?.info = DevKitBundle.message("extension.point.analyzer.analyze.status.bar.info", StringUtil.shortenTextWithEllipsis(targetElement.text, 50, 5), processedObjects.size) if (tooManyObjects()) { return listOf(Leak(DevKitBundle.message("extension.point.analyzer.reason.too.many.visited.objects"), targetElement)) } val type = e.getExpressionType() if (isSafeType(type)) return emptyList() val parent = e.uastParent if (parent is UParenthesizedExpression || parent is UIfExpression || parent is UBinaryExpressionWithType || parent is UUnaryExpression || (e is UCallExpression && parent is UQualifiedReferenceExpression)) { return findObjectLeaks(parent, text) } if (parent is UPolyadicExpression && parent.operator != UastBinaryOperator.ASSIGN) { return emptyList() } if (parent is UForEachExpression && parent.iteratedValue == e) { return findVariableUsageLeaks(parent.variable, DevKitBundle.message("extension.point.analyzer.reason.element.of", text)) } if (parent is USwitchClauseExpression) { val switchExpr = parent.getParentOfType<USwitchExpression>() if (switchExpr != null) { return findObjectLeaks(switchExpr, text) } } val call = findEnclosingCall(e) if (call != null) { return findLeaksThroughCall(call, text) } if (parent is UBinaryExpression && parent.operator == UastBinaryOperator.ASSIGN) { val leftOperand = parent.leftOperand if (leftOperand is USimpleNameReferenceExpression) { val target = leftOperand.resolveToUElement() if (target is ULocalVariable) { return findVariableUsageLeaks(target, text) } } } if (parent is ULocalVariable) { return findVariableUsageLeaks(parent, text) } if (parent is UQualifiedReferenceExpression) { val target = parent.resolveToUElement() if (target is UField) { return findObjectLeaks(parent, text) } } if (parent is UReturnExpression) { val jumpTarget = parent.jumpTarget if (jumpTarget is UMethod) { val target = resolveAnonymousClass(jumpTarget) if (target != null) { return findObjectLeaks(target, text) } val psiMethod = jumpTarget.javaPsi if (psiMethod.name == "getInstance") { return listOf(Leak(DevKitBundle.message("extension.point.analyzer.reason.get.instance.method.skipped"), parent.sourcePsi)) } val methodsToFind = mutableSetOf<PsiMethod>() methodsToFind.add(psiMethod) ContainerUtil.addAll(methodsToFind, *psiMethod.findDeepestSuperMethods()) val result = mutableListOf<Leak>() for (methodToFind in methodsToFind) { MethodReferencesSearch.search(methodToFind, searchScope, true).forEach(Processor { ref: PsiReference -> val element = ref.element var uElement = element.toUElement() if (uElement is UReferenceExpression) { val uParent = element.parent?.toUElement() if (uParent is UCallExpression) { uElement = uParent } else { val maybeCall = (uParent as? UQualifiedReferenceExpression)?.selector as? UCallExpression if (maybeCall != null) { uElement = maybeCall } } } if (uElement != null) { result.addAll(findObjectLeaks(uElement, DevKitBundle.message("extension.point.analyzer.reason.returned.from.method", text, psiMethod.name))) } !tooManyObjects() }) } if (result.isNotEmpty()) { result.add(0, Leak(DevKitBundle.message("extension.point.analyzer.reason.leak.returned.from.method", text, psiMethod.name), parent.sourcePsi)) } return result } } } return listOf(Leak(DevKitBundle.message("extension.point.analyzer.reason.unknown.usage.text", text), targetElement?.parent)) } private fun resolveAnonymousClass(uMethod: UMethod): UObjectLiteralExpression? { val uClass = uMethod.getContainingUClass() ?: return null val anonymous = uClass.uastParent as? UObjectLiteralExpression ?: return null val onlySuperType = ContainerUtil.getOnlyItem(uClass.uastSuperTypes) ?: return null val methodName = ANONYMOUS_PASS_THROUGH[onlySuperType.getQualifiedName()] return if (uMethod.name == methodName) anonymous else null } private fun tooManyObjects() = processedObjects.size > 500 private fun findVariableUsageLeaks(variable: UVariable, @Nls text: String): List<Leak> { val sourcePsi = variable.sourcePsi if (sourcePsi == null) { return listOf(Leak(DevKitBundle.message("extension.point.analyzer.reason.uast.no.source.psi", text), null)) } val leaks = mutableListOf<Leak>() ReferencesSearch.search(sourcePsi, sourcePsi.useScope).forEach(Processor { psiReference -> val ref = psiReference.element.toUElement() if (ref != null) { leaks.addAll(findObjectLeaks(ref, text)) } !tooManyObjects() }) return leaks } } class AnalyzeEPUsageAction : AnAction() { override fun actionPerformed(e: AnActionEvent) { val editor = e.getData(CommonDataKeys.EDITOR) ?: return val file = e.getData(CommonDataKeys.PSI_FILE) ?: return val elementAtCaret = file.findElementAt(editor.caretModel.offset) ?: return analyze(elementAtCaret, file, editor, false) } override fun getActionUpdateThread(): ActionUpdateThread { return ActionUpdateThread.BGT } } class AnalyzeEPUsageIgnoreSafeClassesAction : AnAction() { override fun actionPerformed(e: AnActionEvent) { val editor = e.getData(CommonDataKeys.EDITOR) ?: return val file = e.getData(CommonDataKeys.PSI_FILE) ?: return val elementAtCaret = file.findElementAt(editor.caretModel.offset) ?: return analyze(elementAtCaret, file, editor, true) } override fun getActionUpdateThread(): ActionUpdateThread { return ActionUpdateThread.BGT } } private fun analyze(elementAtCaret: PsiElement, file: PsiFile, editor: Editor, ignoreSafeClasses: Boolean) { val target = elementAtCaret.getUastParentOfType<UField>() if (target != null) { val psiField = target.javaPsi as? PsiField val psiClass = psiField?.containingClass var epName: String? = null if (psiClass != null) { epName = ContainerUtil.getOnlyItem(ExtensionPointLocator(psiClass).findDirectCandidates())?.epName } if (!isEPField(psiField, null)) { HintManager.getInstance().showErrorHint(editor, DevKitBundle.message("extension.point.analyzer.not.extension.point.name")) return } analyzeEPFieldUsages(target, file, editor, epName, ignoreSafeClasses) } val xmlTag = PsiTreeUtil.getParentOfType(elementAtCaret, XmlTag::class.java) if (xmlTag != null) { if (xmlTag.name == "extensionPoint") { analyzeEPTagUsages(xmlTag, file, editor, ignoreSafeClasses) } else if (xmlTag.name == "extensionPoints") { batchAnalyzeEPTagUsages(xmlTag, file, editor, ignoreSafeClasses) } } } private fun isEPField(field: PsiField?, epClass: PsiClass?): Boolean { val referenceType = field?.type as? PsiClassReferenceType ?: return false val parameters = referenceType.parameters if (!referenceType.isRaw && parameters.size != 1) { return false } val fieldRawType = referenceType.rawType() if (fieldRawType.canonicalText == ExtensionPointName::class.java.name || fieldRawType.canonicalText == ProjectExtensionPointName::class.java.name || fieldRawType.canonicalText == LanguageExtension::class.java.name) { return parameters.size != 1 || epClass == null || epClass == (parameters[0] as? PsiClassReferenceType)?.resolve() } return false } private fun analyzeEPFieldUsages(target: UField, file: PsiFile, editor: Editor, epName: String?, ignoreSafeClasses: Boolean) { val sourcePsi = target.sourcePsi ?: return val context = LeakSearchContext(file.project, epName, ignoreSafeClasses) val task = object : Task.Backgroundable(file.project, DevKitBundle.message("extension.point.analyzer.analyze.title")) { override fun run(indicator: ProgressIndicator) { context.processEPFieldUsages(sourcePsi) ApplicationManager.getApplication().invokeLater(Runnable { if (context.unsafeUsages.isEmpty()) { if (context.safeUsages.isEmpty()) { HintManager.getInstance().showErrorHint(editor, DevKitBundle.message("extension.point.analyzer.analyze.no.usages")) } else { HintManager.getInstance().showInformationHint(editor, DevKitBundle.message("extension.point.analyzer.analyze.usage.all.safe")) } } else { val usages = context.unsafeUsages.map { EPElementUsage(it.second.targetElement ?: it.first.element, it.second.reason) } showEPElementUsages(file.project, EPUsageTarget(target.sourcePsi as PsiField), usages) } }) } } ProgressManager.getInstance().run(task) } private fun showEPElementUsages(project: Project, usageTarget: UsageTarget, usages: List<EPElementUsage>) { UsageViewManager.getInstance(project).showUsages(arrayOf(usageTarget), usages.toTypedArray(), UsageViewPresentation().apply { tabText = usageTarget.presentation!!.presentableText isOpenInNewTab = true }) } private fun analyzeEPTagUsages(xmlTag: XmlTag, file: PsiFile, editor: Editor, ignoreSafeClasses: Boolean) { val domElement = DomManager.getDomManager(file.project).getDomElement(xmlTag) as? ExtensionPoint if (domElement == null) { HintManager.getInstance().showErrorHint(editor, DevKitBundle.message("extension.point.analyzer.analyze.xml.not.extension.point")) return } var effectiveClass = domElement.effectiveClass ?: run { HintManager.getInstance().showErrorHint(editor, DevKitBundle.message("extension.point.analyzer.analyze.xml.cannot.resolve.ep.class")) return } if (effectiveClass.qualifiedName == "com.intellij.lang.LanguageExtensionPoint") { effectiveClass = ContainerUtil.getOnlyItem(domElement.withElements)?.implements?.value ?: run { HintManager.getInstance().showErrorHint(editor, DevKitBundle.message("extension.point.analyzer.analyze.xml.no.implementation.language.extension.point")) return } } val epField = findEPField(effectiveClass, effectiveClass) ?: run { HintManager.getInstance().showErrorHint(editor, DevKitBundle.message("extension.point.analyzer.analyze.xml.no.extension.point.name.field")) return } val epUField = epField.toUElementOfType<UField>() ?: return analyzeEPFieldUsages(epUField, file, editor, domElement.effectiveQualifiedName, ignoreSafeClasses) } private fun batchAnalyzeEPTagUsages(xmlTag: XmlTag, file: PsiFile, editor: Editor, ignoreSafeClasses: Boolean) { val domElement = DomManager.getDomManager(file.project).getDomElement(xmlTag) as? ExtensionPoints if (domElement == null) { HintManager.getInstance().showErrorHint(editor, DevKitBundle.message("extension.point.analyzer.analyze.xml.batch.not.extension.points")) return } val safeEPs = mutableListOf<ExtensionPoint>() val allUnsafeUsages = mutableListOf<EPElementUsage>() val task = object : Task.Backgroundable(file.project, DevKitBundle.message("extension.point.analyzer.analyze.xml.batch.title")) { override fun run(indicator: ProgressIndicator) { val extensionPoints = runReadAction { domElement.extensionPoints } for (extensionPoint in extensionPoints) { runReadAction { if (extensionPoint.dynamic.value != null) return@runReadAction indicator.text = extensionPoint.effectiveQualifiedName val epName = extensionPoint.name.xmlAttributeValue ?: return@runReadAction if (!ReferencesSearch.search(epName).anyMatch { isInPluginModule(it.element) }) { println("Skipping EP with no extensions in plugins: " + extensionPoint.effectiveQualifiedName) // NON-NLS return@runReadAction } val effectiveClass = extensionPoint.effectiveClass ?: return@runReadAction val epField = findEPField(effectiveClass, effectiveClass) if (epField == null) { allUnsafeUsages.add(EPElementUsage(effectiveClass, DevKitBundle.message("extension.point.analyzer.reason.no.ep.field"))) return@runReadAction } val context = LeakSearchContext(file.project, extensionPoint.effectiveQualifiedName, ignoreSafeClasses) context.processEPFieldUsages(epField) if (context.safeUsages.isNotEmpty() && context.unsafeUsages.isEmpty()) { safeEPs.add(extensionPoint) } else { context.unsafeUsages.mapTo(allUnsafeUsages) { EPElementUsage(it.second.targetElement ?: it.first.element, it.second.reason) } } } } ApplicationManager.getApplication().invokeLater(Runnable { showEPElementUsages(file.project, DummyUsageTarget(DevKitBundle.message("extension.point.analyzer.usage.safe.eps")), safeEPs.mapNotNull { it.xmlElement }.map { EPElementUsage(it) }) showEPElementUsages(file.project, DummyUsageTarget(DevKitBundle.message("extension.point.analyzer.usage.unsafe.eps")), allUnsafeUsages) }) } } ProgressManager.getInstance().run(task) } private fun findEPField(effectiveClass: PsiClass, epClass: PsiClass): PsiField? { val fields = effectiveClass.fields val epField = fields.find { isEPField(it, epClass) } if (epField != null) { return epField } effectiveClass.innerClasses.find { val nestedField = findEPField(it, epClass) if (nestedField != null) { return nestedField } return@find false } return null } private fun isInPluginModule(element: PsiElement): Boolean { val module = ModuleUtil.findModuleForPsiElement(element) ?: return false return !module.name.startsWith("intellij.platform") && !module.name.startsWith("intellij.clion") && !module.name.startsWith("intellij.appcode") } private class EPElementUsage(private val psiElement: PsiElement, @Nls private val reason: String = "") : PsiElementUsage { override fun getElement() = psiElement override fun getPresentation(): UsagePresentation { return object : UsagePresentation { override fun getTooltipText(): String = "" override fun getIcon(): Icon? = null override fun getPlainText(): String = psiElement.text override fun getText(): Array<TextChunk> = arrayOf(TextChunk(TextAttributes(), psiElement.text.replace(Regex("\\s+"), " ")), TextChunk(TextAttributes().apply { fontType = Font.ITALIC }, reason)) } } override fun getLocation(): FileEditorLocation? = null override fun canNavigate(): Boolean = psiElement is Navigatable && psiElement.canNavigate() override fun canNavigateToSource() = psiElement is Navigatable && psiElement.canNavigateToSource() override fun highlightInEditor() { } override fun selectInEditor() { } override fun isReadOnly() = false override fun navigate(requestFocus: Boolean) { (psiElement as? Navigatable)?.navigate(requestFocus) } override fun isNonCodeUsage(): Boolean = false override fun isValid(): Boolean = psiElement.isValid } private class EPUsageTarget(private val field: PsiField) : UsageTarget { override fun getFiles(): Array<VirtualFile>? { return field.containingFile?.virtualFile?.let { arrayOf(it) } } override fun getPresentation(): ItemPresentation { return object : ItemPresentation { override fun getIcon(unused: Boolean): Icon? = field.getIcon(0) override fun getPresentableText(): String { return "${field.containingClass?.qualifiedName}.${field.name}" } } } override fun canNavigate(): Boolean { return (field as? Navigatable)?.canNavigate() ?: false } override fun getName(): String { return "${field.containingClass?.qualifiedName}.${field.name}" } override fun findUsages() { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun canNavigateToSource(): Boolean { return (field as? Navigatable)?.canNavigateToSource() ?: false } override fun isReadOnly(): Boolean = false override fun navigate(requestFocus: Boolean) { (field as? Navigatable)?.navigate(true) } override fun isValid(): Boolean = field.isValid } private class DummyUsageTarget(@Nls val text: String) : UsageTarget { override fun getPresentation(): ItemPresentation { return object : ItemPresentation { override fun getIcon(unused: Boolean): Icon? = null override fun getPresentableText(): String = text } } override fun canNavigate(): Boolean = false override fun getName(): String = text override fun findUsages() { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun canNavigateToSource() = false override fun isReadOnly(): Boolean = false override fun navigate(requestFocus: Boolean) { } override fun isValid(): Boolean = true }
apache-2.0
91f5f7d4932c5795acf9209c4d341158
41.461765
189
0.705998
4.924783
false
false
false
false
nearbydelta/KoreanAnalyzer
utagger/src/main/kotlin/kr/bydelta/koala/utagger/data.kt
1
2118
@file:JvmName("Util") @file:JvmMultifileClass package kr.bydelta.koala.utagger import com.beust.klaxon.Json import kr.bydelta.koala.POS import kr.bydelta.koala.data.Morpheme import kr.bydelta.koala.data.Word /** * UTagger의 형태소 JSON 표현 규격 * * @param morphemeInfo 형태소 정보. `[표면형, 의미번호, 품사표기]` * @param meaning 형태소 대역어 정보. `[;로 분리된 대역어 목록, 의미]` */ data class UMorpheme(@Json(name = "BSP") private val morphemeInfo: List<String>, @Json(name = "ML") private val meaning: List<String>? = null) { /** 형태소 표면형 **/ val surface: String by lazy { morphemeInfo[0] } /** 형태소 의미번호. (앞 2자리는 동형이의어, 뒷 6자리는 다의어) **/ val wordSenseId: String? by lazy { morphemeInfo[1].takeIf { it.isNotBlank() } } /** 형태소 품사 표지 **/ val tag: String by lazy { morphemeInfo[2] } /** 대역어가 있는 경우, 대역어 목록 **/ val translatedWord: List<String>? by lazy { meaning?.get(0)?.split(';')?.map { it.trim() } } /** 대역어가 있는 경우, 대역어 언어권에서의 의미 **/ val translatedMeaning: String? by lazy { meaning?.get(1) } /** * KoalaNLP의 [Morpheme] 형태로 변환 * * @return 대응하는 [Morpheme] 인스턴스. 대역어 정보는 제외. */ fun toMorpheme(): Morpheme { val morpheme = Morpheme(surface, POS.valueOf(tag), originalTag = tag) wordSenseId?.let { morpheme.setWordSense(it) } return morpheme } } /** * UTagger의 어절 JSON 표현 규격 * * @param surface 어절의 표면형. * @param morphemes 형태소 목록. List<[UMorpheme]>. */ data class UWord(@Json(name = "SURF") val surface: String, @Json(name = "MA") val morphemes: List<UMorpheme>) { /** * KoalaNLP의 [Word] 형태로 변환 * * @return 대응하는 [Word] 인스턴스. 대역어 정보는 제외. */ fun toWord(): Word { return Word(surface, morphemes.map { it.toMorpheme() }) } }
gpl-3.0
cd64a400563bbaa3b962002e5856e468
26.261538
96
0.603273
2.676737
false
false
false
false
blindpirate/gradle
subprojects/kotlin-dsl-tooling-builders/src/main/kotlin/org/gradle/kotlin/dsl/tooling/builders/KotlinBuildScriptModelBuilder.kt
1
17525
/* * 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 org.gradle.kotlin.dsl.tooling.builders import org.gradle.api.Project import org.gradle.api.initialization.Settings import org.gradle.api.initialization.dsl.ScriptHandler import org.gradle.api.internal.GradleInternal import org.gradle.api.internal.SettingsInternal import org.gradle.api.internal.initialization.ClassLoaderScope import org.gradle.api.internal.initialization.ScriptHandlerFactory import org.gradle.api.internal.initialization.ScriptHandlerInternal import org.gradle.api.internal.project.ProjectInternal import org.gradle.api.invocation.Gradle import org.gradle.api.tasks.SourceSet import org.gradle.api.tasks.SourceSetContainer import org.gradle.groovy.scripts.TextResourceScriptSource import org.gradle.initialization.DependenciesAccessors import org.gradle.internal.classpath.ClassPath import org.gradle.internal.classpath.DefaultClassPath import org.gradle.internal.resource.TextFileResourceLoader import org.gradle.internal.time.Time.startTimer import org.gradle.kotlin.dsl.* import org.gradle.kotlin.dsl.accessors.AccessorsClassPath import org.gradle.kotlin.dsl.accessors.PluginAccessorClassPathGenerator import org.gradle.kotlin.dsl.accessors.ProjectAccessorsClassPathGenerator import org.gradle.kotlin.dsl.execution.EvalOption import org.gradle.kotlin.dsl.precompile.PrecompiledScriptDependenciesResolver import org.gradle.kotlin.dsl.provider.ClassPathModeExceptionCollector import org.gradle.kotlin.dsl.provider.KotlinScriptClassPathProvider import org.gradle.kotlin.dsl.provider.KotlinScriptEvaluator import org.gradle.kotlin.dsl.provider.ignoringErrors import org.gradle.kotlin.dsl.resolver.EditorReports import org.gradle.kotlin.dsl.resolver.SourceDistributionResolver import org.gradle.kotlin.dsl.resolver.SourcePathProvider import org.gradle.kotlin.dsl.support.ImplicitImports import org.gradle.kotlin.dsl.support.KotlinScriptType import org.gradle.kotlin.dsl.support.kotlinScriptTypeFor import org.gradle.kotlin.dsl.support.serviceOf import org.gradle.kotlin.dsl.tooling.models.EditorReport import org.gradle.kotlin.dsl.tooling.models.KotlinBuildScriptModel import org.gradle.tooling.model.kotlin.dsl.KotlinDslModelsParameters import org.gradle.tooling.provider.model.ToolingModelBuilder import java.io.File import java.io.PrintWriter import java.io.Serializable import java.io.StringWriter import java.util.EnumSet internal data class KotlinBuildScriptModelParameter( val scriptFile: File?, val correlationId: String? ) internal data class StandardKotlinBuildScriptModel( private val classPath: List<File>, private val sourcePath: List<File>, private val implicitImports: List<String>, private val editorReports: List<EditorReport>, private val exceptions: List<String>, private val enclosingScriptProjectDir: File? ) : KotlinBuildScriptModel, Serializable { override fun getClassPath() = classPath override fun getSourcePath() = sourcePath override fun getImplicitImports() = implicitImports override fun getEditorReports() = editorReports override fun getExceptions() = exceptions override fun getEnclosingScriptProjectDir() = enclosingScriptProjectDir } internal object KotlinBuildScriptModelBuilder : ToolingModelBuilder { override fun canBuild(modelName: String): Boolean = modelName == "org.gradle.kotlin.dsl.tooling.models.KotlinBuildScriptModel" override fun buildAll(modelName: String, modelRequestProject: Project): KotlinBuildScriptModel { val timer = startTimer() val parameter = requestParameterOf(modelRequestProject) try { return kotlinBuildScriptModelFor(modelRequestProject, parameter).also { log("$parameter => $it") } } catch (e: Exception) { log("$parameter => $e") throw e } finally { log("MODEL built in ${timer.elapsed}.") } } internal fun kotlinBuildScriptModelFor(modelRequestProject: Project, parameter: KotlinBuildScriptModelParameter) = scriptModelBuilderFor(modelRequestProject as ProjectInternal, parameter).buildModel() private fun scriptModelBuilderFor( modelRequestProject: ProjectInternal, parameter: KotlinBuildScriptModelParameter ): KotlinScriptTargetModelBuilder { val scriptFile = parameter.scriptFile ?: return projectScriptModelBuilder(null, modelRequestProject) modelRequestProject.findProjectWithBuildFile(scriptFile)?.let { buildFileProject -> return projectScriptModelBuilder(scriptFile, buildFileProject as ProjectInternal) } modelRequestProject.enclosingSourceSetOf(scriptFile)?.let { enclosingSourceSet -> return precompiledScriptPluginModelBuilder(scriptFile, enclosingSourceSet, modelRequestProject) } if (isSettingsFileOf(modelRequestProject, scriptFile)) { return settingsScriptModelBuilder(scriptFile, modelRequestProject) } return when (kotlinScriptTypeFor(scriptFile)) { KotlinScriptType.INIT -> initScriptModelBuilder(scriptFile, modelRequestProject) KotlinScriptType.SETTINGS -> settingsScriptPluginModelBuilder(scriptFile, modelRequestProject) else -> projectScriptPluginModelBuilder(scriptFile, modelRequestProject) } } private fun isSettingsFileOf(project: Project, scriptFile: File): Boolean = project.settings.settingsScript.resource.file?.canonicalFile == scriptFile private fun requestParameterOf(modelRequestProject: Project) = KotlinBuildScriptModelParameter( (modelRequestProject.findProperty(KotlinBuildScriptModel.SCRIPT_GRADLE_PROPERTY_NAME) as? String)?.let(::canonicalFile), modelRequestProject.findProperty(KotlinDslModelsParameters.CORRELATION_ID_GRADLE_PROPERTY_NAME) as? String ) } internal fun log(message: String) { if (System.getProperty("org.gradle.kotlin.dsl.logging.tapi") == "true") { println(message) } } private fun Project.findProjectWithBuildFile(file: File) = allprojects.find { it.buildFile == file } private fun Project.enclosingSourceSetOf(file: File): EnclosingSourceSet? = findSourceSetOf(file) ?: findSourceSetOfFileIn(subprojects, file) private data class EnclosingSourceSet(val project: Project, val sourceSet: SourceSet) private fun findSourceSetOfFileIn(projects: Iterable<Project>, file: File): EnclosingSourceSet? = projects .asSequence() .mapNotNull { it.findSourceSetOf(file) } .firstOrNull() private fun Project.findSourceSetOf(file: File): EnclosingSourceSet? = sourceSets?.find { file in it.allSource }?.let { EnclosingSourceSet(this, it) } private val Project.sourceSets get() = extensions.findByType(typeOf<SourceSetContainer>()) private fun precompiledScriptPluginModelBuilder( scriptFile: File, enclosingSourceSet: EnclosingSourceSet, modelRequestProject: Project ) = KotlinScriptTargetModelBuilder( scriptFile = scriptFile, project = modelRequestProject, scriptClassPath = DefaultClassPath.of(enclosingSourceSet.sourceSet.compileClasspath), enclosingScriptProjectDir = enclosingSourceSet.project.projectDir, additionalImports = { enclosingSourceSet.project.precompiledScriptPluginsMetadataDir.run { implicitImportsFrom( resolve("accessors").resolve(hashOf(scriptFile)) ) + implicitImportsFrom( resolve("plugin-spec-builders").resolve("implicit-imports") ) } } ) private val Project.precompiledScriptPluginsMetadataDir: File get() = buildDir.resolve("kotlin-dsl/precompiled-script-plugins-metadata") private fun implicitImportsFrom(file: File): List<String> = file.takeIf { it.isFile }?.readLines() ?: emptyList() private fun hashOf(scriptFile: File) = PrecompiledScriptDependenciesResolver.hashOf(scriptFile.readText()) private fun projectScriptModelBuilder( scriptFile: File?, project: ProjectInternal ) = KotlinScriptTargetModelBuilder( scriptFile = scriptFile, project = project, scriptClassPath = project.scriptCompilationClassPath, accessorsClassPath = { classPath -> val pluginAccessorClassPathGenerator = project.serviceOf<PluginAccessorClassPathGenerator>() val projectAccessorClassPathGenerator = project.serviceOf<ProjectAccessorsClassPathGenerator>() val dependenciesAccessors = project.serviceOf<DependenciesAccessors>() projectAccessorClassPathGenerator.projectAccessorsClassPath(project, classPath) + pluginAccessorClassPathGenerator.pluginSpecBuildersClassPath(project) + AccessorsClassPath(dependenciesAccessors.classes, dependenciesAccessors.sources) }, sourceLookupScriptHandlers = sourceLookupScriptHandlersFor(project), enclosingScriptProjectDir = project.projectDir ) private fun initScriptModelBuilder(scriptFile: File, project: ProjectInternal) = project.run { val (scriptHandler, scriptClassPath) = compilationClassPathForScriptPluginOf( target = gradle, scriptFile = scriptFile, baseScope = gradle.classLoaderScope, scriptHandlerFactory = scriptHandlerFactoryOf(gradle), project = project, resourceDescription = "initialization script" ) KotlinScriptTargetModelBuilder( scriptFile = scriptFile, project = project, scriptClassPath = scriptClassPath, sourceLookupScriptHandlers = listOf(scriptHandler) ) } private fun settingsScriptModelBuilder(scriptFile: File, project: Project) = project.run { KotlinScriptTargetModelBuilder( scriptFile = scriptFile, project = project, scriptClassPath = settings.scriptCompilationClassPath, sourceLookupScriptHandlers = listOf(settings.buildscript), enclosingScriptProjectDir = rootDir ) } private fun settingsScriptPluginModelBuilder(scriptFile: File, project: ProjectInternal) = project.run { val (scriptHandler, scriptClassPath) = compilationClassPathForScriptPluginOf( target = settings, scriptFile = scriptFile, baseScope = settings.baseClassLoaderScope, scriptHandlerFactory = scriptHandlerFactoryOf(gradle), project = project, resourceDescription = "settings file" ) KotlinScriptTargetModelBuilder( scriptFile = scriptFile, project = project, scriptClassPath = scriptClassPath, sourceLookupScriptHandlers = listOf(scriptHandler, settings.buildscript) ) } private fun projectScriptPluginModelBuilder(scriptFile: File, project: ProjectInternal) = project.run { val (scriptHandler, scriptClassPath) = compilationClassPathForScriptPluginOf( target = project, scriptFile = scriptFile, baseScope = rootProject.baseClassLoaderScope, scriptHandlerFactory = scriptHandlerFactoryOf(project), project = project, resourceDescription = "build file" ) KotlinScriptTargetModelBuilder( scriptFile = scriptFile, project = project, scriptClassPath = scriptClassPath, sourceLookupScriptHandlers = listOf(scriptHandler, buildscript) ) } private fun compilationClassPathForScriptPluginOf( target: Any, scriptFile: File, baseScope: ClassLoaderScope, scriptHandlerFactory: ScriptHandlerFactory, project: ProjectInternal, resourceDescription: String ): Pair<ScriptHandlerInternal, ClassPath> { val scriptSource = textResourceScriptSource(resourceDescription, scriptFile, project.serviceOf()) val scriptScope = baseScope.createChild("model-${scriptFile.toURI()}") val scriptHandler = scriptHandlerFactory.create(scriptSource, scriptScope) kotlinScriptFactoryOf(project).evaluate( target = target, scriptSource = scriptSource, scriptHandler = scriptHandler, targetScope = scriptScope, baseScope = baseScope, topLevelScript = false, options = EnumSet.of(EvalOption.IgnoreErrors, EvalOption.SkipBody) ) return scriptHandler to project.compilationClassPathOf(scriptScope) } private fun kotlinScriptFactoryOf(project: ProjectInternal) = project.serviceOf<KotlinScriptEvaluator>() private fun scriptHandlerFactoryOf(project: ProjectInternal) = project.serviceOf<ScriptHandlerFactory>() private fun scriptHandlerFactoryOf(gradle: Gradle) = gradle.serviceOf<ScriptHandlerFactory>() private fun textResourceScriptSource(description: String, scriptFile: File, resourceLoader: TextFileResourceLoader) = TextResourceScriptSource(resourceLoader.loadFile(description, scriptFile)) private fun sourceLookupScriptHandlersFor(project: Project) = project.hierarchy.map { it.buildscript }.toList() private data class KotlinScriptTargetModelBuilder( val scriptFile: File?, val project: Project, val scriptClassPath: ClassPath, val accessorsClassPath: (ClassPath) -> AccessorsClassPath = { AccessorsClassPath.empty }, val sourceLookupScriptHandlers: List<ScriptHandler> = emptyList(), val enclosingScriptProjectDir: File? = null, val additionalImports: () -> List<String> = { emptyList() } ) { fun buildModel(): KotlinBuildScriptModel { val classpathSources = sourcePathFor(sourceLookupScriptHandlers) val classPathModeExceptionCollector = project.serviceOf<ClassPathModeExceptionCollector>() val accessorsClassPath = classPathModeExceptionCollector.ignoringErrors { accessorsClassPath(scriptClassPath) } ?: AccessorsClassPath.empty val additionalImports = classPathModeExceptionCollector.ignoringErrors { additionalImports() } ?: emptyList() return StandardKotlinBuildScriptModel( (scriptClassPath + accessorsClassPath.bin).asFiles, (gradleSource() + classpathSources + accessorsClassPath.src).asFiles, implicitImports + additionalImports, buildEditorReportsFor(classPathModeExceptionCollector.exceptions), classPathModeExceptionCollector.exceptions.map(::exceptionToString), enclosingScriptProjectDir ) } private fun gradleSource() = SourcePathProvider.sourcePathFor( scriptClassPath, scriptFile, rootDir, gradleHomeDir, SourceDistributionResolver(project) ) val gradleHomeDir get() = project.gradle.gradleHomeDir val rootDir get() = project.rootDir val implicitImports get() = project.scriptImplicitImports private fun buildEditorReportsFor(exceptions: List<Exception>) = buildEditorReportsFor( scriptFile, exceptions, project.isLocationAwareEditorHintsEnabled ) private fun exceptionToString(exception: Exception) = StringWriter().also { exception.printStackTrace(PrintWriter(it)) }.toString() } private val Settings.scriptCompilationClassPath get() = serviceOf<KotlinScriptClassPathProvider>().safeCompilationClassPathOf(classLoaderScope, false) { (this as SettingsInternal).gradle } private val Settings.classLoaderScope get() = (this as SettingsInternal).classLoaderScope private val Project.settings get() = (gradle as GradleInternal).settings private val Project.scriptCompilationClassPath get() = compilationClassPathOf((this as ProjectInternal).classLoaderScope) private fun Project.compilationClassPathOf(classLoaderScope: ClassLoaderScope) = serviceOf<KotlinScriptClassPathProvider>().safeCompilationClassPathOf(classLoaderScope, true) { (this as ProjectInternal).gradle } private inline fun KotlinScriptClassPathProvider.safeCompilationClassPathOf( classLoaderScope: ClassLoaderScope, projectScript: Boolean, getGradle: () -> GradleInternal ): ClassPath = try { compilationClassPathOf(classLoaderScope) } catch (error: Exception) { getGradle().run { serviceOf<ClassPathModeExceptionCollector>().collect(error) compilationClassPathOf(if (projectScript) baseProjectClassLoaderScope() else this.classLoaderScope) } } private val Project.scriptImplicitImports get() = serviceOf<ImplicitImports>().list private val Project.hierarchy: Sequence<Project> get() = sequence { var project = this@hierarchy yield(project) while (project != project.rootProject) { project = project.parent!! yield(project) } } private val Project.isLocationAwareEditorHintsEnabled: Boolean get() = findProperty(EditorReports.locationAwareEditorHintsPropertyName) == "true" internal fun canonicalFile(path: String): File = File(path).canonicalFile
apache-2.0
c534882f4f52e45a4ba1daba1309a3af
32.380952
242
0.746077
5.078238
false
false
false
false
JetBrains/ideavim
vim-engine/src/main/kotlin/com/maddyhome/idea/vim/command/CommandBuilder.kt
1
7262
/* * Copyright 2003-2022 The IdeaVim authors * * Use of this source code is governed by an MIT-style * license that can be found in the LICENSE.txt file or at * https://opensource.org/licenses/MIT. */ package com.maddyhome.idea.vim.command import com.maddyhome.idea.vim.api.VimActionsInitiator import com.maddyhome.idea.vim.common.CurrentCommandState import com.maddyhome.idea.vim.diagnostic.debug import com.maddyhome.idea.vim.diagnostic.vimLogger import com.maddyhome.idea.vim.handler.EditorActionHandlerBase import com.maddyhome.idea.vim.key.CommandPartNode import com.maddyhome.idea.vim.key.Node import com.maddyhome.idea.vim.key.RootNode import org.jetbrains.annotations.TestOnly import java.util.* import javax.swing.KeyStroke class CommandBuilder(private var currentCommandPartNode: CommandPartNode<VimActionsInitiator>) { private val commandParts = ArrayDeque<Command>() private var keyList = mutableListOf<KeyStroke>() var commandState = CurrentCommandState.NEW_COMMAND var count = 0 private set val keys: Iterable<KeyStroke> get() = keyList // The argument type for the current command part's action. Kept separate to handle digraphs and characters. We first // try to accept a digraph. If we get it, set expected argument type to character and handle the converted key. If we // fail to convert to a digraph, set expected argument type to character and try to handle the key again. var expectedArgumentType: Argument.Type? = null private set private var prevExpectedArgumentType: Argument.Type? = null val isReady get() = commandState == CurrentCommandState.READY val isBad get() = commandState == CurrentCommandState.BAD_COMMAND val isEmpty get() = commandParts.isEmpty() val isAtDefaultState get() = isEmpty && count == 0 && expectedArgumentType == null val isExpectingCount: Boolean get() { return commandState == CurrentCommandState.NEW_COMMAND && expectedArgumentType != Argument.Type.CHARACTER && expectedArgumentType != Argument.Type.DIGRAPH } fun pushCommandPart(action: EditorActionHandlerBase) { commandParts.add(Command(count, action, action.type, action.flags)) prevExpectedArgumentType = expectedArgumentType expectedArgumentType = action.argumentType count = 0 } fun pushCommandPart(register: Char) { // We will never execute this command, but we need to push something to correctly handle counts on either side of a // select register command part. e.g. 2"a2d2w or even crazier 2"a2"a2"a2"a2"a2d2w commandParts.add(Command(count, register)) expectedArgumentType = null count = 0 } fun popCommandPart(): Command { val command = commandParts.removeLast() expectedArgumentType = if (commandParts.size > 0) commandParts.peekLast().action.argumentType else null return command } fun fallbackToCharacterArgument() { // Finished handling DIGRAPH. We either succeeded, in which case handle the converted character, or failed to parse, // in which case try to handle input as a character argument. assert(expectedArgumentType == Argument.Type.DIGRAPH) { "Cannot move state from $expectedArgumentType to CHARACTER" } expectedArgumentType = Argument.Type.CHARACTER } fun addKey(key: KeyStroke) { keyList.add(key) } fun addCountCharacter(key: KeyStroke) { count = (count * 10) + (key.keyChar - '0') // If count overflows and flips negative, reset to 999999999L. In Vim, count is a long, which is *usually* 32 bits, // so will flip at 2147483648. We store count as an Int, which is also 32 bit. // See https://github.com/vim/vim/blob/b376ace1aeaa7614debc725487d75c8f756dd773/src/normal.c#L631 if (count < 0) { count = 999999999 } addKey(key) } fun deleteCountCharacter() { count /= 10 keyList.removeAt(keyList.size - 1) } fun setCurrentCommandPartNode(newNode: CommandPartNode<VimActionsInitiator>) { currentCommandPartNode = newNode } fun getChildNode(key: KeyStroke): Node<VimActionsInitiator>? { return currentCommandPartNode[key] } fun isAwaitingCharOrDigraphArgument(): Boolean { if (commandParts.size == 0) return false val argumentType = commandParts.peekLast().action.argumentType val awaiting = argumentType == Argument.Type.CHARACTER || argumentType == Argument.Type.DIGRAPH LOG.debug { "Awaiting char of digraph: $awaiting" } return awaiting } fun isBuildingMultiKeyCommand(): Boolean { // Don't apply mapping if we're in the middle of building a multi-key command. // E.g. given nmap s v, don't try to map <C-W>s to <C-W>v // Similarly, nmap <C-W>a <C-W>s should not try to map the second <C-W> in <C-W><C-W> // Note that we might still be at RootNode if we're handling a prefix, because we might be buffering keys until we // get a match. This means we'll still process the rest of the keys of the prefix. val isMultikey = currentCommandPartNode !is RootNode LOG.debug { "Building multikey command: $isMultikey" } return isMultikey } fun isPuttingLiteral(): Boolean { return !commandParts.isEmpty() && commandParts.last.action.id == "VimInsertCompletedLiteralAction" } fun isDone(): Boolean { return commandParts.isEmpty() } fun completeCommandPart(argument: Argument) { commandParts.peekLast().argument = argument commandState = CurrentCommandState.READY } fun isDuplicateOperatorKeyStroke(key: KeyStroke): Boolean { val action = commandParts.peekLast().action as? DuplicableOperatorAction return action?.duplicateWith == key.keyChar } fun hasCurrentCommandPartArgument(): Boolean { return commandParts.peek()?.argument != null } fun buildCommand(): Command { if (commandParts.last.action.id == "VimInsertCompletedDigraphAction" || commandParts.last.action.id == "VimResetModeAction") { expectedArgumentType = prevExpectedArgumentType prevExpectedArgumentType = null return commandParts.removeLast() } var command: Command = commandParts.removeFirst() while (commandParts.size > 0) { val next = commandParts.removeFirst() next.count = if (command.rawCount == 0 && next.rawCount == 0) 0 else command.count * next.count command.count = 0 if (command.type == Command.Type.SELECT_REGISTER) { next.register = command.register command.register = null command = next } else { command.argument = Argument(next) assert(commandParts.size == 0) } } expectedArgumentType = null return command } fun resetAll(commandPartNode: CommandPartNode<VimActionsInitiator>) { resetInProgressCommandPart(commandPartNode) commandState = CurrentCommandState.NEW_COMMAND commandParts.clear() keyList.clear() expectedArgumentType = null prevExpectedArgumentType = null } fun resetCount() { count = 0 } fun resetInProgressCommandPart(commandPartNode: CommandPartNode<VimActionsInitiator>) { count = 0 setCurrentCommandPartNode(commandPartNode) } @TestOnly fun getCurrentTrie(): CommandPartNode<VimActionsInitiator> = currentCommandPartNode companion object { private val LOG = vimLogger<CommandBuilder>() } }
mit
fa1933dba106a7e0b51839b5d3fe15ef
35.676768
130
0.727899
4.168772
false
false
false
false
JetBrains/ideavim
src/main/java/com/maddyhome/idea/vim/helper/UpdatesChecker.kt
1
2721
/* * Copyright 2003-2022 The IdeaVim authors * * Use of this source code is governed by an MIT-style * license that can be found in the LICENSE.txt file or at * https://opensource.org/licenses/MIT. */ package com.maddyhome.idea.vim.helper import com.intellij.ide.util.PropertiesComponent import com.intellij.openapi.application.ApplicationInfo import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.PermanentInstallationID import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.util.JDOMUtil import com.intellij.openapi.util.SystemInfo import com.intellij.openapi.vfs.CharsetToolkit import com.intellij.util.io.HttpRequests import com.maddyhome.idea.vim.VimPlugin import org.jdom.JDOMException import java.io.IOException import java.net.URLEncoder import java.util.concurrent.TimeUnit object UpdatesChecker { private val logger = logger<UpdatesChecker>() private const val IDEAVIM_STATISTICS_TIMESTAMP_KEY = "ideavim.statistics.timestamp" private val DAY_IN_MILLIS = TimeUnit.DAYS.toMillis(1) /** * Check if we have plugin updates for IdeaVim. * * Also this code is necessary for JetStat, so do not remove this check. * See https://github.com/go-lang-plugin-org/go-lang-idea-plugin/commit/5182ab4a1d01ad37f6786268a2fe5e908575a217 */ fun check() { val lastUpdate = PropertiesComponent.getInstance().getLong(IDEAVIM_STATISTICS_TIMESTAMP_KEY, 0) val outOfDate = lastUpdate == 0L || System.currentTimeMillis() - lastUpdate > DAY_IN_MILLIS if (!outOfDate || !VimPlugin.isEnabled()) return ApplicationManager.getApplication().executeOnPooledThread { try { val buildNumber = ApplicationInfo.getInstance().build.asString() val version = URLEncoder.encode(VimPlugin.getVersion(), CharsetToolkit.UTF8) val os = URLEncoder.encode("${SystemInfo.OS_NAME} ${SystemInfo.OS_VERSION}", CharsetToolkit.UTF8) val uid = PermanentInstallationID.get() val url = "https://plugins.jetbrains.com/plugins/list?" + "pluginId=${VimPlugin.getPluginId().idString}" + "&build=$buildNumber" + "&pluginVersion=$version" + "&os=$os" + "&uuid=$uid" PropertiesComponent.getInstance() .setValue(IDEAVIM_STATISTICS_TIMESTAMP_KEY, System.currentTimeMillis().toString()) HttpRequests.request(url).connect { request: HttpRequests.Request -> logger.info("Check IdeaVim updates: $url") try { JDOMUtil.load(request.inputStream) } catch (e: JDOMException) { logger.warn(e) } } } catch (e: IOException) { logger.warn(e) } } } }
mit
ea766b0ff53892441eb2b3e5845c97cd
36.273973
114
0.710768
4.218605
false
false
false
false
google/identity-credential
appholder/src/main/java/com/android/mdl/app/fragment/RefreshAuthKeyFragment.kt
1
6389
package com.android.mdl.app.fragment import android.os.Bundle import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.navigation.fragment.findNavController import androidx.navigation.fragment.navArgs import co.nstant.`in`.cbor.CborBuilder import com.android.mdl.app.databinding.FragmentRefreshAuthKeyBinding import com.android.mdl.app.document.Document import com.android.mdl.app.document.DocumentManager import com.android.mdl.app.provisioning.RefreshAuthenticationKeyFlow import com.android.mdl.app.util.FormatUtil import java.util.* class RefreshAuthKeyFragment : Fragment() { companion object { private const val LOG_TAG = "RefreshAuthKeyFragment" } private val args: RefreshAuthKeyFragmentArgs by navArgs() private lateinit var serverUrl: String private lateinit var document: Document private var _binding: FragmentRefreshAuthKeyBinding? = null // This property is only valid between onCreateView and // onDestroyView. private val binding get() = _binding!! override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) serverUrl = args.serverUrl document = args.document } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { _binding = FragmentRefreshAuthKeyBinding.inflate(inflater) binding.fragment = this return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) startRefreshAuthKeyFlow() } fun onDone() { findNavController().navigate( RefreshAuthKeyFragmentDirections.actionRefreshAuthKeyFragmentToSelectDocumentFragment() ) } private fun startRefreshAuthKeyFlow() { val documentManager = DocumentManager.getInstance(requireContext()) val credential = documentManager.getCredential(document) if (credential == null) { binding.tvStatusRefreshing.append("\n- Error on retrieving a document for ${document.userVisibleName}\n") return } documentManager.setAvailableAuthKeys(credential) val dynAuthKeyCerts = credential.authKeysNeedingCertification val credentialCertificateChain = credential.credentialKeyCertificateChain // Start refresh auth key flow val refreshAuthKeyFlow = RefreshAuthenticationKeyFlow.getInstance(requireContext(), serverUrl) refreshAuthKeyFlow.setListener(object : RefreshAuthenticationKeyFlow.Listener { override fun onMessageSessionEnd(reason: String) { binding.tvStatusRefreshing.append("\n- onMessageSessionEnd: $reason\n") //Check if provisioning was successful if (reason == "Success") { binding.btDone.visibility = View.VISIBLE } binding.loadingProgress.visibility = View.GONE } override fun sendMessageRequestEnd(reason: String) { binding.tvStatusRefreshing.append("\n- sendMessageRequestEnd: $reason\n") binding.loadingProgress.visibility = View.GONE } override fun onError(error: String) { binding.tvStatusRefreshing.append("\n- onError: $error\n") binding.loadingProgress.visibility = View.GONE } override fun onMessageProveOwnership(challenge: ByteArray) { binding.tvStatusRefreshing.append( "\n- onMessageProveOwnership: ${FormatUtil.encodeToString(challenge)}\n" ) val proveOwnership = credential.proveOwnership(challenge) refreshAuthKeyFlow.sendMessageProveOwnership(proveOwnership) } override fun onMessageCertifyAuthKeysReady() { binding.tvStatusRefreshing.append("\n- onMessageCertifyAuthKeysReady") val builderArray = CborBuilder() .addArray() dynAuthKeyCerts.forEach { cert -> builderArray.add(cert.encoded) } val authKeyCerts = FormatUtil.cborEncode(builderArray.end().build()[0]) refreshAuthKeyFlow.sendMessageAuthKeyNeedingCertification(authKeyCerts) } override fun onMessageStaticAuthData(staticAuthDataList: MutableList<ByteArray>) { binding.tvStatusRefreshing.append("\n- onMessageStaticAuthData ${staticAuthDataList.size} ") dynAuthKeyCerts.forEachIndexed { i, cert -> Log.d( LOG_TAG, "Provisioned Issuer Auth ${FormatUtil.encodeToString(staticAuthDataList[i])} " + "for Device Key ${FormatUtil.encodeToString(cert.publicKey.encoded)}" ) credential.storeStaticAuthenticationData(cert, staticAuthDataList[i]) } refreshAuthKeyFlow.sendMessageRequestEndSession() } }) // Set timestamp for last refresh auth keys document.dateRefreshAuthKeys = Calendar.getInstance() documentManager.updateDocument(document) if (dynAuthKeyCerts.isNotEmpty()) { //credential.proveOwnership(challenge) Log.d(LOG_TAG, "Device Keys needing certification ${dynAuthKeyCerts.size}") binding.tvStatusRefreshing.append("\n- Device Keys needing certification ${dynAuthKeyCerts.size}") // returns the Cose_Sign1 Obj with the MSO in the payload credentialCertificateChain.first()?.publicKey?.let { publicKey -> val cborCoseKey = FormatUtil.cborBuildCoseKey(publicKey) refreshAuthKeyFlow.sendMessageCertifyAuthKeys(FormatUtil.cborEncode(cborCoseKey)) } } else { Log.d(LOG_TAG, "No Device Keys Needing Certification for now") binding.tvStatusRefreshing.append("\n- No Device Keys Needing Certification for now") binding.btDone.visibility = View.VISIBLE binding.loadingProgress.visibility = View.GONE } } }
apache-2.0
908f44abf225da0e04d31e825c49a018
39.188679
117
0.660354
5.022799
false
false
false
false
kpavlov/jreactive-8583
src/main/kotlin/com/github/kpavlov/jreactive8583/netty/pipeline/IsoMessageLoggingHandler.kt
1
4503
package com.github.kpavlov.jreactive8583.netty.pipeline import com.solab.iso8583.IsoMessage import com.solab.iso8583.IsoValue import io.netty.channel.ChannelHandler.Sharable import io.netty.channel.ChannelHandlerContext import io.netty.handler.logging.LogLevel import io.netty.handler.logging.LoggingHandler import java.io.IOException import java.io.InputStream import java.lang.Integer.parseInt /** * ChannelHandler responsible for logging messages. * * According to PCI DSS, sensitive cardholder data, like PAN and track data, * should not be exposed. When running in secure mode, * sensitive cardholder data will be printed masked. */ @Sharable internal class IsoMessageLoggingHandler( level: LogLevel, private val printSensitiveData: Boolean, private val printFieldDescriptions: Boolean, private val maskedFields: IntArray = DEFAULT_MASKED_FIELDS ) : LoggingHandler(level) { companion object { private const val MASK_CHAR = '*' private val MASKED_VALUE = "***".toCharArray() @JvmField val DEFAULT_MASKED_FIELDS = intArrayOf( 34, // PAN extended 35, // track 2 36, // track 3 45 // track 1 ) private val FIELD_NAMES = arrayOfNulls<String>(256) private const val FIELD_PROPERTIES = "iso8583fields.properties" private fun loadProperties() { try { propertiesStream.use { stream -> val properties = java.util.Properties() properties.load(stream) properties.forEach { key: Any, value: Any? -> val field = parseInt(key.toString()) FIELD_NAMES[field - 1] = value as String } } } catch (e: IOException) { throw IllegalStateException("Unable to load ISO8583 field descriptions", e) } catch (e: NumberFormatException) { throw IllegalStateException("Unable to load ISO8583 field descriptions", e) } } private val propertiesStream: InputStream get() { var stream = Thread.currentThread().contextClassLoader .getResourceAsStream("/$FIELD_PROPERTIES") if (stream == null) { stream = IsoMessageLoggingHandler::class.java.getResourceAsStream( "/com/github/kpavlov/jreactive8583/$FIELD_PROPERTIES" ) } return stream!! } init { loadProperties() } } public override fun format( ctx: ChannelHandlerContext, eventName: String, arg: Any ): String { return if (arg is IsoMessage) { super.format(ctx, eventName, formatIsoMessage(arg)) } else { super.format(ctx, eventName, arg) } } private fun formatIsoMessage(m: IsoMessage): String { val sb = StringBuilder() if (printSensitiveData) { sb.append("Message: ").append(m.debugString()).append("\n") } sb.append("MTI: 0x").append(String.format("%04x", m.type)) for (i in 2..127) { if (m.hasField(i)) { val field = m.getField<Any>(i) sb.append("\n ").append(i).append(": [") if (printFieldDescriptions) { sb.append(FIELD_NAMES[i - 1]).append(':') } val formattedValue: CharArray formattedValue = getFormattedValue(field, i) sb.append(field.type).append('(').append(field.length) .append(")] = '").append(formattedValue).append('\'') } } return sb.toString() } private fun getFormattedValue(field: IsoValue<Any>, i: Int): CharArray { return if (printSensitiveData) { field.toString().toCharArray() } else { when { i == 2 -> maskPAN(field.toString()) maskedFields.contains(i) -> MASKED_VALUE else -> field.toString().toCharArray() } } } private fun maskPAN(fullPan: String): CharArray { val maskedPan = fullPan.toCharArray() for (i in 6 until maskedPan.size - 4) { maskedPan[i] = MASK_CHAR } return maskedPan } }
apache-2.0
b8c2484f4ed66a9d415961918e611357
33.113636
91
0.55785
4.785335
false
false
false
false
SnakeEys/MessagePlus
app/src/main/java/info/fox/messup/data/ContactList.kt
1
3988
package info.fox.messup.data import android.net.Uri import android.os.Parcelable import android.text.TextUtils /** * Created by user on 2017/7/4. */ class ContactList : ArrayList<Contact>() { fun getPresenceResId(): Int { return if (size != 1) 0 else get(0).getPresenceResId() } fun formatNames(separator: String): String{ val names = arrayOfNulls<String>(size) var i = 0 for (c in this) { names[i++] = c.getName() } return TextUtils.join(separator, names) } fun formatNamesAndNumbers(separator: String): String { val nans = arrayOfNulls<String>(size) var i = 0 for (c in this) { nans[i++] = c.getNameAndNumber() } return TextUtils.join(separator, nans) } fun serialize() = TextUtils.join(";", getNumbers()) fun getNumbers() = getNumbers(false) fun getNumbers(scrubForMmsAddress: Boolean): Array<String?> { val numbers = mutableListOf<String?>() var number: String? this.forEach { number = it.getNumber() if (!TextUtils.isEmpty(number) && !numbers.contains(number)) { numbers.add(number) } } return numbers.toTypedArray() } override fun equals(other: Any?): Boolean { try { val other = other as ContactList // If they're different sizes, the contact // set is obviously different. if (size != other.size) { return false } // Make sure all the individual contacts are the same. return this.any { other.contains(it) } } catch (e: ClassCastException) { return false } } companion object { fun getByNumbers(numbers: Iterable<String>, canBlock: Boolean): ContactList { val list = ContactList() /*numbers.filter { !TextUtils.isEmpty(it) } .forEach { list.add(Contact.get(it, canBlock)) }*/ return list } fun getByNumbers(semiSepNumbers: String, canBlock: Boolean, replaceNumber: Boolean): ContactList { val list = ContactList() /*semiSepNumbers.split(";") .filter { !TextUtils.isEmpty(it) } .forEach { val contact = Contact.get(it, canBlock) if (replaceNumber) { contact.setNumber(number = it) } list.add(contact) }*/ return list } fun blockingGetByUris(uris: Array<Parcelable>?): ContactList { val list = ContactList() /*if (uris != null && uris.isNotEmpty()) { uris.forEach { if (it is Uri && TextUtils.equals("tel", it.scheme)) { val contact = Contact.get(it.schemeSpecificPart, true) list.add(contact) } } val contacts = Contact.getPhoneByUris(uris) contacts?.let { list.addAll(it) } }*/ return list } /** * Returns a ContactList for the corresponding recipient ids passed in. This method will * create the contact if it doesn't exist, and would inject the recipient id into the contact. */ fun getByIds(spaceSepIds: String, canBlock: Boolean): ContactList { val list = ContactList() /*for (entry in RecipientIdCache.getAddresses(spaceSepIds)) { if (!TextUtils.isEmpty(entry.number)) { val contact = Contact.get(entry.number, canBlock) contact.mRecipientId = entry.id list.add(contact) } }*/ return list } } }
mit
7acce4fa47ccb6a1a2ead0b54d50a7ef
31.169355
102
0.515296
4.776048
false
false
false
false
RadiationX/ForPDA
app/src/main/java/forpdateam/ru/forpda/entity/remote/devdb/Device.kt
1
1073
package forpdateam.ru.forpda.entity.remote.devdb import android.util.Pair /** * Created by radiationx on 06.08.17. */ class Device { val specs = mutableListOf<Pair<String, List<Pair<String, String>>>>() val images = mutableListOf<Pair<String, String>>() val comments = mutableListOf<Comment>() val discussions = mutableListOf<PostItem>() val firmwares = mutableListOf<PostItem>() val news = mutableListOf<PostItem>() var id: String? = null var title: String? = null var brandId: String? = null var brandTitle: String? = null var catId: String? = null var catTitle: String? = null var rating = 0 class Comment { var id = 0 var rating = 0 var userId = 0 var likes = 0 var dislikes = 0 var nick: String? = null var date: String? = null var text: String? = null } class PostItem { var id = 0 var image: String? = null var title: String? = null var date: String? = null var desc: String? = null } }
gpl-3.0
8bb744ae54ff14a1f6b260926b4a1d2d
24.547619
73
0.59739
4.003731
false
false
false
false
mdaniel/intellij-community
plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/extensibility/ModuleChangesSignalProviders.kt
2
2564
/******************************************************************************* * Copyright 2000-2022 JetBrains s.r.o. and contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.jetbrains.packagesearch.intellij.plugin.extensibility import com.intellij.openapi.project.Project import com.intellij.openapi.vfs.LocalFileSystem import com.jetbrains.packagesearch.intellij.plugin.util.filesChangedEventFlow import kotlinx.coroutines.channels.awaitClose import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.asFlow import kotlinx.coroutines.flow.channelFlow import kotlinx.coroutines.flow.filter import kotlinx.coroutines.flow.flatMapMerge import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.flow.onEach import java.nio.file.Path import kotlin.io.path.absolutePathString import kotlin.io.path.name open class FileWatcherSignalProvider(private val paths: List<Path>) : FlowModuleChangesSignalProvider { constructor(vararg paths: Path) : this(paths.toList()) private val absolutePathStrings = paths.map { it.absolutePathString() } override fun registerModuleChangesListener(project: Project): Flow<Unit> { val localFs: LocalFileSystem = LocalFileSystem.getInstance() val watchRequests = absolutePathStrings.asSequence() .onEach { localFs.findFileByPath(it) } .mapNotNull { localFs.addRootToWatch(it, false) } return channelFlow { project.filesChangedEventFlow.flatMapMerge { it.asFlow() } .filter { vFileEvent -> paths.any { it.name == vFileEvent.file?.name } } // check the file name before resolving the absolute path string .filter { vFileEvent -> absolutePathStrings.any { it == vFileEvent.file?.toNioPath()?.absolutePathString() } } .onEach { send(Unit) } .launchIn(this) awaitClose { watchRequests.forEach { request -> localFs.removeWatchedRoot(request) } } } } }
apache-2.0
f70635967c0df748704abddf2f1fa031
46.481481
153
0.695398
4.783582
false
false
false
false
mdaniel/intellij-community
platform/lang-impl/src/com/intellij/ide/navigationToolbar/experimental/NewToolbarRootPaneExtension.kt
2
9415
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.ide.navigationToolbar.experimental import com.intellij.ide.ui.ToolbarSettings import com.intellij.ide.ui.UISettings import com.intellij.ide.ui.customization.CustomActionsSchema import com.intellij.ide.ui.customization.CustomizationUtil import com.intellij.ide.ui.experimental.toolbar.RunWidgetAvailabilityManager import com.intellij.idea.ActionsBundle import com.intellij.openapi.Disposable import com.intellij.openapi.actionSystem.* import com.intellij.openapi.actionSystem.impl.ActionToolbarImpl import com.intellij.openapi.actionSystem.impl.segmentedActionBar.ToolbarActionsUpdatedListener import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.components.Service import com.intellij.openapi.components.service import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.project.Project import com.intellij.openapi.util.SimpleModificationTracker import com.intellij.openapi.wm.IdeRootPaneNorthExtension import com.intellij.util.application import com.intellij.util.concurrency.AppExecutorUtil import com.intellij.util.concurrency.annotations.RequiresBackgroundThread import com.intellij.util.concurrency.annotations.RequiresEdt import com.intellij.util.messages.Topic import com.intellij.util.ui.JBSwingUtilities import com.intellij.util.ui.JBUI import java.awt.BorderLayout import java.awt.Graphics import java.util.concurrent.CompletableFuture import javax.swing.BorderFactory import javax.swing.JComponent import javax.swing.JPanel @FunctionalInterface fun interface ExperimentalToolbarStateListener { companion object { @JvmField @Topic.ProjectLevel val TOPIC: Topic<ExperimentalToolbarStateListener> = Topic( ExperimentalToolbarStateListener::class.java, Topic.BroadcastDirection.NONE, true, ) } /** * This event gets emitted when the experimental toolbar wants things dependent on its state to refresh their visibility. */ fun refreshVisibility() } @Service internal class NewToolbarRootPaneManager(private val project: Project) : SimpleModificationTracker(), Disposable { companion object { private val LOG = logger<NewToolbarRootPaneManager>() fun getInstance(project: Project): NewToolbarRootPaneManager = project.service() } init { RunWidgetAvailabilityManager.getInstance(project).addListener(this) { LOG.info("New toolbar: run widget availability changed $it") IdeRootPaneNorthExtension.EP_NAME.findExtension(NewToolbarRootPaneExtension::class.java, project)?.let { extension -> startUpdateActionGroups(extension) } } ApplicationManager.getApplication().messageBus.connect(project).subscribe(ToolbarActionsUpdatedListener.TOPIC, ToolbarActionsUpdatedListener { IdeRootPaneNorthExtension.EP_NAME.findExtension(NewToolbarRootPaneExtension::class.java, project)?.let { extension -> application.invokeLater { extension.panel.revalidate() extension.panel.doLayout() } } }) } override fun dispose() { } internal fun startUpdateActionGroups(extension: NewToolbarRootPaneExtension) { incModificationCount() val panel = extension.panel if (panel.isEnabled && panel.isVisible && ToolbarSettings.getInstance().isEnabled) { CompletableFuture.supplyAsync(::correctedToolbarActions, AppExecutorUtil.getAppExecutorService()) .thenAcceptAsync({ placeToActionGroup -> applyTo(placeToActionGroup, panel, extension.layout) for ((place, actionGroup) in placeToActionGroup) { if (actionGroup == null) { val comp = extension.layout.getLayoutComponent(place) if (comp != null) { panel.remove(comp) } } } } ) { ApplicationManager.getApplication().invokeLater(it, project.disposed) } .exceptionally { LOG.error(it) null } getToolbarGroup()?.let { CustomizationUtil.installToolbarCustomizationHandler(it, mainGroupName(), panel, ActionPlaces.MAIN_TOOLBAR) } } } @RequiresBackgroundThread private fun correctedToolbarActions(): Map<String, ActionGroup?> { val toolbarGroup = getToolbarGroup() ?: return emptyMap() val children = toolbarGroup.getChildren(null) val leftGroup = children.firstOrNull { it.templateText.equals(ActionsBundle.message("group.LeftToolbarSideGroup.text")) || it.templateText.equals( ActionsBundle.message("group.LeftToolbarSideGroupXamarin.text")) } val rightGroup = children.firstOrNull { it.templateText.equals(ActionsBundle.message("group.RightToolbarSideGroup.text")) || it.templateText.equals( ActionsBundle.message("group.RightToolbarSideGroupXamarin.text")) } val restGroup = DefaultActionGroup(children.filter { it != leftGroup && it != rightGroup }) val map = mutableMapOf<String, ActionGroup?>() map[BorderLayout.WEST] = leftGroup as? ActionGroup map[BorderLayout.EAST] = rightGroup as? ActionGroup map[BorderLayout.CENTER] = restGroup return map } private fun getToolbarGroup(): ActionGroup? { val mainGroupName = mainGroupName() return CustomActionsSchema.getInstance().getCorrectedAction(mainGroupName) as? ActionGroup } private fun mainGroupName() = if (RunWidgetAvailabilityManager.getInstance(project).isAvailable()) { IdeActions.GROUP_EXPERIMENTAL_TOOLBAR } else { IdeActions.GROUP_EXPERIMENTAL_TOOLBAR_XAMARIN } private class MyActionToolbarImpl(place: String, actionGroup: ActionGroup, horizontal: Boolean, decorateButtons: Boolean, popupActionGroup: ActionGroup?, popupActionId: String?) : ActionToolbarImpl(place, actionGroup, horizontal, decorateButtons, popupActionGroup, popupActionId) { override fun addNotify() { super.addNotify() updateActionsImmediately() } } @RequiresEdt private fun applyTo( actions: Map<String, ActionGroup?>, component: JComponent, layout: BorderLayout ) { actions.mapValues { (_, actionGroup) -> if (actionGroup != null) { val toolbar = MyActionToolbarImpl(ActionPlaces.MAIN_TOOLBAR, actionGroup, true, false, getToolbarGroup(), mainGroupName()) ApplicationManager.getApplication().messageBus.syncPublisher(ActionManagerListener.TOPIC).toolbarCreated(ActionPlaces.MAIN_TOOLBAR, actionGroup, true, toolbar) toolbar } else { null } }.forEach { (layoutConstraints, toolbar) -> // We need to replace old component having the same constraints with the new one. if (toolbar != null) { layout.getLayoutComponent(component, layoutConstraints)?.let { component.remove(it) } toolbar.targetComponent = null toolbar.layoutPolicy = ActionToolbar.NOWRAP_LAYOUT_POLICY component.add(toolbar.component, layoutConstraints) } } component.revalidate() component.repaint() } } internal class NewToolbarRootPaneExtension(private val project: Project) : IdeRootPaneNorthExtension() { companion object { private const val NEW_TOOLBAR_KEY = "NEW_TOOLBAR_KEY" private val logger = logger<NewToolbarRootPaneExtension>() } internal val layout = NewToolbarBorderLayout() internal val panel: JPanel = object : JPanel(layout) { init { isOpaque = true border = BorderFactory.createEmptyBorder(0, JBUI.scale(4), 0, JBUI.scale(4)) //show ui customization option } override fun getComponentGraphics(graphics: Graphics?): Graphics { return JBSwingUtilities.runGlobalCGTransform(this, super.getComponentGraphics(graphics)) } } override fun getKey() = NEW_TOOLBAR_KEY override fun getComponent(): JPanel { NewToolbarRootPaneManager.getInstance(project).startUpdateActionGroups(this) return panel } override fun uiSettingsChanged(settings: UISettings) { logger.info("Show old main toolbar: ${settings.showMainToolbar}; show old navigation bar: ${settings.showNavigationBar}") logger.info("Show new main toolbar: ${ToolbarSettings.getInstance().isVisible}") val toolbarSettings = ToolbarSettings.getInstance() panel.isEnabled = toolbarSettings.isEnabled panel.isVisible = toolbarSettings.isVisible && !settings.presentationMode project.messageBus.syncPublisher(ExperimentalToolbarStateListener.TOPIC).refreshVisibility() panel.revalidate() panel.repaint() NewToolbarRootPaneManager.getInstance(project).startUpdateActionGroups(this) } override fun copy() = null//NewToolbarRootPaneExtension(project) override fun revalidate() { NewToolbarRootPaneManager.getInstance(project).startUpdateActionGroups(this) } }
apache-2.0
dd1322109b4c728d1efb34c919518577
37.909091
146
0.70069
5.153257
false
false
false
false
hsson/card-balance-app
app/src/main/java/se/creotec/chscardbalance2/controller/FoodDishFragment.kt
1
2888
// Copyright (c) 2017 Alexander Håkansson // // This software is released under the MIT License. // https://opensource.org/licenses/MIT package se.creotec.chscardbalance2.controller import android.content.Context import android.os.Bundle import android.support.v4.app.Fragment import android.support.v7.widget.DividerItemDecoration import android.support.v7.widget.LinearLayoutManager import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.google.gson.Gson import kotlinx.android.synthetic.main.fragment_dish_list.* import se.creotec.chscardbalance2.R import se.creotec.chscardbalance2.model.Dish import se.creotec.chscardbalance2.model.Restaurant class FoodDishFragment : Fragment() { private var restaurant: Restaurant = Restaurant("") private var dishListener: OnListFragmentInteractionListener? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) arguments?.let { restaurant = Gson().fromJson(it.getString(ARG_RESTAURANT), Restaurant::class.java) } } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { return inflater.inflate(R.layout.fragment_dish_list, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) // Set the adapter val layoutManager = LinearLayoutManager(context) dish_list.layoutManager = layoutManager val dividerLine = DividerItemDecoration(dish_list.context, layoutManager.orientation) dish_list.addItemDecoration(dividerLine) dish_list.adapter = FoodDishRecyclerViewAdapter(restaurant.dishes, dishListener) if (restaurant.isClosed()) { restaurant_closed_view.visibility = View.VISIBLE } } override fun onAttach(context: Context?) { super.onAttach(context) if (context is OnListFragmentInteractionListener) { dishListener = context } else { throw RuntimeException(context!!.toString() + " must implement OnListFragmentInteractionListener") } } override fun onDetach() { super.onDetach() dishListener = null } interface OnListFragmentInteractionListener { fun onListFragmentInteraction(item: Dish) } companion object { private const val ARG_RESTAURANT = "dish_restaurant" fun newInstance(restaurant: Restaurant): FoodDishFragment { val fragment = FoodDishFragment() val args = Bundle() val restaurantJSON = Gson().toJson(restaurant, Restaurant::class.java) args.putString(ARG_RESTAURANT, restaurantJSON) fragment.arguments = args return fragment } } }
mit
8074d9645c4adec46b5f52b4743afba3
33.783133
116
0.708001
4.709625
false
false
false
false
mdaniel/intellij-community
jvm/jvm-analysis-impl/src/com/intellij/codeInspection/test/junit/JUnitMalformedDeclarationInspection.kt
1
54541
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.codeInspection.test.junit import com.intellij.analysis.JvmAnalysisBundle import com.intellij.codeInsight.AnnotationUtil import com.intellij.codeInsight.MetaAnnotationUtil import com.intellij.codeInsight.daemon.impl.analysis.JavaGenericsUtil import com.intellij.codeInsight.intention.FileModifier.SafeFieldForPreview import com.intellij.codeInsight.intention.IntentionAction import com.intellij.codeInspection.* import com.intellij.codeInspection.test.junit.references.MethodSourceReference import com.intellij.codeInspection.util.InspectionMessage import com.intellij.codeInspection.util.SpecialAnnotationsUtil import com.intellij.lang.Language import com.intellij.lang.jvm.JvmMethod import com.intellij.lang.jvm.JvmModifier import com.intellij.lang.jvm.JvmModifiersOwner import com.intellij.lang.jvm.actions.* import com.intellij.lang.jvm.types.JvmPrimitiveTypeKind import com.intellij.lang.jvm.types.JvmType import com.intellij.openapi.project.Project import com.intellij.openapi.util.NlsSafe import com.intellij.openapi.util.text.StringUtil import com.intellij.psi.* import com.intellij.psi.impl.source.resolve.reference.impl.providers.FileReference import com.intellij.psi.impl.source.tree.java.PsiNameValuePairImpl import com.intellij.psi.search.searches.ClassInheritorsSearch import com.intellij.psi.util.InheritanceUtil import com.intellij.psi.util.PsiUtil import com.intellij.psi.util.TypeConversionUtil import com.intellij.psi.util.isAncestor import com.intellij.uast.UastHintedVisitorAdapter import com.intellij.util.castSafelyTo import com.siyeh.ig.junit.JUnitCommonClassNames.* import com.siyeh.ig.psiutils.TestUtils import org.jetbrains.uast.* import org.jetbrains.uast.visitor.AbstractUastNonRecursiveVisitor import javax.swing.JComponent import kotlin.streams.asSequence import kotlin.streams.toList class JUnitMalformedDeclarationInspection : AbstractBaseUastLocalInspectionTool() { @JvmField val ignorableAnnotations = mutableListOf("mockit.Mocked", "org.junit.jupiter.api.io.TempDir") override fun createOptionsPanel(): JComponent = SpecialAnnotationsUtil.createSpecialAnnotationsListControl( ignorableAnnotations, JvmAnalysisBundle.message("jvm.inspections.junit.malformed.option.ignore.test.parameter.if.annotated.by") ) override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean, session: LocalInspectionToolSession): PsiElementVisitor = UastHintedVisitorAdapter.create( holder.file.language, JUnitMalformedSignatureVisitor(holder, isOnTheFly, ignorableAnnotations), arrayOf(UClass::class.java, UField::class.java, UMethod::class.java), directOnly = true ) } private class JUnitMalformedSignatureVisitor( private val holder: ProblemsHolder, private val isOnTheFly: Boolean, private val ignorableAnnotations: List<String> ) : AbstractUastNonRecursiveVisitor() { override fun visitClass(node: UClass): Boolean { checkMalformedNestedClass(node) return true } override fun visitField(node: UField): Boolean { checkMalformedExtension(node) dataPoint.report(holder, node) ruleSignatureProblem.report(holder, node) classRuleSignatureProblem.report(holder, node) return true } override fun visitMethod(node: UMethod): Boolean { checkMalformedParameterized(node) checkRepeatedTestNonPositive(node) checkIllegalCombinedAnnotations(node) dataPoint.report(holder, node) checkSuite(node) checkedMalformedSetupTeardown(node) beforeAfterProblem.report(holder, node) beforeAfterEachProblem.report(holder, node) beforeAfterClassProblem.report(holder, node) beforeAfterAllProblem.report(holder, node) ruleSignatureProblem.report(holder, node) classRuleSignatureProblem.report(holder, node) checkJUnit3Test(node) junit4TestProblem.report(holder, node) junit5TestProblem.report(holder, node) return true } private fun checkMalformedNestedClass(aClass: UClass) { val javaClass = aClass.javaPsi val containingClass = javaClass.containingClass if (containingClass != null && aClass.isStatic && javaClass.hasAnnotation(ORG_JUNIT_JUPITER_API_NESTED)) { val message = JvmAnalysisBundle.message("jvm.inspections.junit.malformed.nested.class.descriptor") val fixes = createModifierQuickfixes(aClass, modifierRequest(JvmModifier.STATIC, shouldBePresent = false)) ?: return holder.registerUProblem(aClass, message, *fixes) } } private val dataPoint = AnnotatedSignatureProblem( annotations = listOf(ORG_JUNIT_EXPERIMENTAL_THEORIES_DATAPOINT, ORG_JUNIT_EXPERIMENTAL_THEORIES_DATAPOINTS), shouldBeStatic = true, validVisibility = { UastVisibility.PUBLIC }, ) private val ruleSignatureProblem = AnnotatedSignatureProblem( annotations = listOf(ORG_JUNIT_RULE), shouldBeStatic = false, shouldBeSubTypeOf = listOf(ORG_JUNIT_RULES_TEST_RULE, ORG_JUNIT_RULES_METHOD_RULE), validVisibility = { UastVisibility.PUBLIC } ) private val classRuleSignatureProblem = AnnotatedSignatureProblem( annotations = listOf(ORG_JUNIT_CLASS_RULE), shouldBeStatic = true, shouldBeSubTypeOf = listOf(ORG_JUNIT_RULES_TEST_RULE), validVisibility = { UastVisibility.PUBLIC } ) private val beforeAfterProblem = AnnotatedSignatureProblem( annotations = listOf(ORG_JUNIT_BEFORE, ORG_JUNIT_AFTER), shouldBeStatic = false, shouldBeVoidType = true, validVisibility = { UastVisibility.PUBLIC }, validParameters = { method -> method.uastParameters.filter { MetaAnnotationUtil.isMetaAnnotated(it, ignorableAnnotations) } } ) private val beforeAfterEachProblem = AnnotatedSignatureProblem( annotations = listOf(ORG_JUNIT_JUPITER_API_BEFORE_EACH, ORG_JUNIT_JUPITER_API_AFTER_EACH), shouldBeStatic = false, shouldBeVoidType = true, validVisibility = ::notPrivate, validParameters = { method -> if (method.uastParameters.isEmpty()) emptyList() else if (method.hasParameterResolver()) listOf(method.uastParameters.first()) else method.uastParameters.filter { it.type.canonicalText == ORG_JUNIT_JUPITER_API_TEST_INFO || it.type.canonicalText == ORG_JUNIT_JUPITER_API_REPETITION_INFO || it.type.canonicalText == ORG_JUNIT_JUPITER_API_TEST_REPORTER || MetaAnnotationUtil.isMetaAnnotated(it, ignorableAnnotations) } } ) private val beforeAfterClassProblem = AnnotatedSignatureProblem( annotations = listOf(ORG_JUNIT_BEFORE_CLASS, ORG_JUNIT_AFTER_CLASS), shouldBeStatic = true, shouldBeVoidType = true, validVisibility = { UastVisibility.PUBLIC }, validParameters = { method -> method.uastParameters.filter { MetaAnnotationUtil.isMetaAnnotated(it, ignorableAnnotations) } } ) private val beforeAfterAllProblem = AnnotatedSignatureProblem( annotations = listOf(ORG_JUNIT_JUPITER_API_BEFORE_ALL, ORG_JUNIT_JUPITER_API_AFTER_ALL), shouldBeInTestInstancePerClass = true, shouldBeStatic = true, shouldBeVoidType = true, validVisibility = ::notPrivate, validParameters = { method -> if (method.uastParameters.isEmpty()) emptyList() else if (method.hasParameterResolver()) listOf(method.uastParameters.first()) else method.uastParameters.filter { it.type.canonicalText == ORG_JUNIT_JUPITER_API_TEST_INFO || MetaAnnotationUtil.isMetaAnnotated(it, ignorableAnnotations) } } ) private val junit4TestProblem = AnnotatedSignatureProblem( annotations = listOf(ORG_JUNIT_TEST), shouldBeStatic = false, shouldBeVoidType = true, validVisibility = { UastVisibility.PUBLIC }, validParameters = { method -> method.uastParameters.filter { MetaAnnotationUtil.isMetaAnnotated(it, ignorableAnnotations) } } ) private val junit5TestProblem = AnnotatedSignatureProblem( annotations = listOf(ORG_JUNIT_JUPITER_API_TEST), shouldBeStatic = false, shouldBeVoidType = true, validVisibility = ::notPrivate, validParameters = { method -> if (method.uastParameters.isEmpty()) emptyList() else if (MetaAnnotationUtil.isMetaAnnotated(method.javaPsi, listOf( ORG_JUNIT_JUPITER_PARAMS_PROVIDER_ARGUMENTS_SOURCE))) null // handled in parameterized test check else if (method.hasParameterResolver()) listOf(method.uastParameters.first()) else method.uastParameters.filter { it.type.canonicalText == ORG_JUNIT_JUPITER_API_TEST_INFO || it.type.canonicalText == ORG_JUNIT_JUPITER_API_TEST_REPORTER || MetaAnnotationUtil.isMetaAnnotated(it, ignorableAnnotations) } } ) private fun notPrivate(method: UDeclaration): UastVisibility? = if (method.visibility == UastVisibility.PRIVATE) UastVisibility.PUBLIC else null private fun UMethod.hasParameterResolver(): Boolean { val sourcePsi = this.sourcePsi ?: return false val alternatives = UastFacade.convertToAlternatives(sourcePsi, arrayOf(UMethod::class.java)) val extension = alternatives.mapNotNull { it.javaPsi.containingClass }.flatMap { MetaAnnotationUtil.findMetaAnnotations(it, listOf(ORG_JUNIT_JUPITER_API_EXTENSION_EXTEND_WITH)).asSequence() }.firstOrNull()?.findAttributeValue("value")?.toUElement() ?: return false if (extension is UClassLiteralExpression) return InheritanceUtil.isInheritor(extension.type, ORG_JUNIT_JUPITER_API_EXTENSION_PARAMETER_RESOLVER) if (extension is UCallExpression && extension.kind == UastCallKind.NESTED_ARRAY_INITIALIZER) return extension.valueArguments.any { it is UClassLiteralExpression && InheritanceUtil.isInheritor(it.type, ORG_JUNIT_JUPITER_API_EXTENSION_PARAMETER_RESOLVER) } return false } private fun checkMalformedExtension(field: UField) { val javaField = field.javaPsi?.castSafelyTo<PsiField>() ?: return val type = javaField.type if (javaField.hasAnnotation(ORG_JUNIT_JUPITER_API_EXTENSION_REGISTER_EXTENSION)) { if (!type.isInheritorOf(ORG_JUNIT_JUPITER_API_EXTENSION)) { val message = JvmAnalysisBundle.message( "jvm.inspections.junit.malformed.extension.registration.descriptor", javaField.type.canonicalText, ORG_JUNIT_JUPITER_API_EXTENSION ) holder.registerUProblem(field, message) } else if (!field.isStatic && (type.isInheritorOf(ORG_JUNIT_JUPITER_API_EXTENSION_BEFORE_ALL_CALLBACK) || type.isInheritorOf(ORG_JUNIT_JUPITER_API_EXTENSION_AFTER_ALL_CALLBACK))) { val message = JvmAnalysisBundle.message( "jvm.inspections.junit.malformed.extension.class.level.descriptor", javaField.type.presentableText ) val fixes = createModifierQuickfixes(field, modifierRequest(JvmModifier.STATIC, shouldBePresent = true)) ?: return holder.registerUProblem(field, message, *fixes) } } } private fun UMethod.isNoArg(): Boolean = uastParameters.isEmpty() || uastParameters.all { param -> param.javaPsi?.castSafelyTo<PsiParameter>()?.let { AnnotationUtil.isAnnotated(it, ignorableAnnotations, 0) } == true } private fun checkSuspendFunction(method: UMethod): Boolean { return if (method.lang == Language.findLanguageByID("kotlin") && method.javaPsi.modifierList.text.contains("suspend")) { val message = JvmAnalysisBundle.message("jvm.inspections.junit.malformed.suspend.function.descriptor") holder.registerUProblem(method, message) true } else false } private fun checkJUnit3Test(method: UMethod) { val sourcePsi = method.sourcePsi ?: return val alternatives = UastFacade.convertToAlternatives(sourcePsi, arrayOf(UMethod::class.java)) val javaMethod = alternatives.firstOrNull { it.isStatic } ?: alternatives.firstOrNull() ?: return if (method.isConstructor) return if (!TestUtils.isJUnit3TestMethod(javaMethod.javaPsi)) return val containingClass = method.javaPsi.containingClass ?: return if (AnnotationUtil.isAnnotated(containingClass, TestUtils.RUN_WITH, AnnotationUtil.CHECK_HIERARCHY)) return if (checkSuspendFunction(method)) return if (PsiType.VOID != method.returnType || method.visibility != UastVisibility.PUBLIC || javaMethod.isStatic || !method.isNoArg()) { val message = JvmAnalysisBundle.message("jvm.inspections.junit.malformed.method.no.arg.void.descriptor", "public", "non-static") return holder.registerUProblem(method, message, MethodSignatureQuickfix(method.name, false, newVisibility = JvmModifier.PUBLIC)) } } private fun checkedMalformedSetupTeardown(method: UMethod) { if ("setUp" != method.name && "tearDown" != method.name) return if (!InheritanceUtil.isInheritor(method.javaPsi.containingClass, JUNIT_FRAMEWORK_TEST_CASE)) return val sourcePsi = method.sourcePsi ?: return if (checkSuspendFunction(method)) return val alternatives = UastFacade.convertToAlternatives(sourcePsi, arrayOf(UMethod::class.java)) val javaMethod = alternatives.firstOrNull { it.isStatic } ?: alternatives.firstOrNull() ?: return if (PsiType.VOID != method.returnType || method.visibility == UastVisibility.PRIVATE || javaMethod.isStatic || !method.isNoArg()) { val message = JvmAnalysisBundle.message("jvm.inspections.junit.malformed.method.no.arg.void.descriptor", "non-private", "non-static") val quickFix = MethodSignatureQuickfix( method.name, newVisibility = JvmModifier.PUBLIC, makeStatic = false, shouldBeVoidType = true, inCorrectParams = emptyMap() ) return holder.registerUProblem(method, message, quickFix) } } private fun checkSuite(method: UMethod) { if ("suite" != method.name) return if (!InheritanceUtil.isInheritor(method.javaPsi.containingClass, JUNIT_FRAMEWORK_TEST_CASE)) return val sourcePsi = method.sourcePsi ?: return if (checkSuspendFunction(method)) return val alternatives = UastFacade.convertToAlternatives(sourcePsi, arrayOf(UMethod::class.java)) val javaMethod = alternatives.firstOrNull { it.isStatic } ?: alternatives.firstOrNull() ?: return if (method.visibility == UastVisibility.PRIVATE || !javaMethod.isStatic || !method.isNoArg()) { val message = JvmAnalysisBundle.message("jvm.inspections.junit.malformed.method.no.arg.descriptor", "non-private", "static") val quickFix = MethodSignatureQuickfix( method.name, newVisibility = JvmModifier.PUBLIC, makeStatic = true, shouldBeVoidType = false, inCorrectParams = emptyMap() ) return holder.registerUProblem(method, message, quickFix) } } private fun checkIllegalCombinedAnnotations(decl: UDeclaration) { val javaPsi = decl.javaPsi.castSafelyTo<PsiModifierListOwner>() ?: return val annotatedTest = NON_COMBINED_TEST.filter { MetaAnnotationUtil.isMetaAnnotated(javaPsi, listOf(it)) } if (annotatedTest.size > 1) { val last = annotatedTest.last().substringAfterLast('.') val annText = annotatedTest.dropLast(1).joinToString { "'@${it.substringAfterLast('.')}'" } val message = JvmAnalysisBundle.message("jvm.inspections.junit.malformed.test.combination.descriptor", annText, last) return holder.registerUProblem(decl, message) } else if (annotatedTest.size == 1 && annotatedTest.first() != ORG_JUNIT_JUPITER_PARAMS_PARAMETERIZED_TEST) { val annotatedArgSource = PARAMETERIZED_SOURCES.filter { MetaAnnotationUtil.isMetaAnnotated(javaPsi, listOf(it)) } if (annotatedArgSource.isNotEmpty()) { val testAnnText = annotatedTest.first().substringAfterLast('.') val argAnnText = annotatedArgSource.joinToString { "'@${it.substringAfterLast('.')}'" } val message = JvmAnalysisBundle.message("jvm.inspections.junit.malformed.test.combination.descriptor", argAnnText, testAnnText) return holder.registerUProblem(decl, message) } } } private fun checkRepeatedTestNonPositive(method: UMethod) { val repeatedAnno = method.findAnnotation(ORG_JUNIT_JUPITER_API_REPEATED_TEST) ?: return val repeatedNumber = repeatedAnno.findDeclaredAttributeValue("value") ?: return val repeatedSrcPsi = repeatedNumber.sourcePsi ?: return val constant = repeatedNumber.evaluate() if (constant is Int && constant <= 0) { holder.registerProblem(repeatedSrcPsi, JvmAnalysisBundle.message("jvm.inspections.junit.malformed.repetition.number.descriptor")) } } private fun checkMalformedParameterized(method: UMethod) { if (!MetaAnnotationUtil.isMetaAnnotated(method.javaPsi, listOf(ORG_JUNIT_JUPITER_PARAMS_PARAMETERIZED_TEST))) return val usedSourceAnnotations = MetaAnnotationUtil.findMetaAnnotations(method.javaPsi, SOURCE_ANNOTATIONS).toList() checkConflictingSourceAnnotations(usedSourceAnnotations.associateWith { it.qualifiedName }, method) usedSourceAnnotations.forEach { when (it.qualifiedName) { ORG_JUNIT_JUPITER_PARAMS_PROVIDER_METHOD_SOURCE -> checkMethodSource(method, it) ORG_JUNIT_JUPITER_PARAMS_PROVIDER_VALUE_SOURCE -> checkValuesSource(method, it) ORG_JUNIT_JUPITER_PARAMS_PROVIDER_ENUM_SOURCE -> checkEnumSource(method, it) ORG_JUNIT_JUPITER_PARAMS_PROVIDER_CSV_FILE_SOURCE -> checkCsvSource(it) ORG_JUNIT_JUPITER_PARAMS_PROVIDER_NULL_SOURCE -> checkNullSource(method, it) ORG_JUNIT_JUPITER_PARAMS_PROVIDER_EMPTY_SOURCE -> checkEmptySource(method, it) ORG_JUNIT_JUPITER_PARAMS_PROVIDER_NULL_AND_EMPTY_SOURCE -> { checkNullSource(method, it) checkEmptySource(method, it) } } } } private fun checkConflictingSourceAnnotations(annMap: Map<PsiAnnotation, @NlsSafe String?>, method: UMethod) { val singleParameterProviders = annMap.containsValue(ORG_JUNIT_JUPITER_PARAMS_PROVIDER_ENUM_SOURCE) || annMap.containsValue(ORG_JUNIT_JUPITER_PARAMS_PROVIDER_VALUE_SOURCE) || annMap.containsValue(ORG_JUNIT_JUPITER_PARAMS_PROVIDER_NULL_SOURCE) || annMap.containsValue(ORG_JUNIT_JUPITER_PARAMS_PROVIDER_EMPTY_SOURCE) || annMap.containsValue(ORG_JUNIT_JUPITER_PARAMS_PROVIDER_NULL_AND_EMPTY_SOURCE) val multipleParametersProvider = annMap.containsValue(ORG_JUNIT_JUPITER_PARAMS_PROVIDER_METHOD_SOURCE) || annMap.containsValue(ORG_JUNIT_JUPITER_PARAMS_PROVIDER_CSV_FILE_SOURCE) || annMap.containsValue(ORG_JUNIT_JUPITER_PARAMS_PROVIDER_CSV_SOURCE) if (!multipleParametersProvider && !singleParameterProviders && hasCustomProvider(annMap)) return if (!multipleParametersProvider) { val message = if (!singleParameterProviders) { JvmAnalysisBundle.message("jvm.inspections.junit.malformed.param.no.sources.are.provided.descriptor") } else if (hasMultipleParameters(method.javaPsi)) { JvmAnalysisBundle.message( "jvm.inspections.junit.malformed.param.multiple.parameters.are.not.supported.by.this.source.descriptor") } else return holder.registerUProblem(method, message) } } private fun hasCustomProvider(annotations: Map<PsiAnnotation, String?>): Boolean { annotations.forEach { (anno, qName) -> when (qName) { ORG_JUNIT_JUPITER_PARAMS_PROVIDER_ARGUMENTS_SOURCE -> return@hasCustomProvider true ORG_JUNIT_JUPITER_PARAMS_PROVIDER_ARGUMENTS_SOURCES -> { val attributes = anno.findAttributeValue(PsiAnnotation.DEFAULT_REFERENCED_METHOD_NAME) if ((attributes as? PsiArrayInitializerMemberValue)?.initializers?.isNotEmpty() == true) return@hasCustomProvider true } } } return false } private fun checkMethodSource(method: UMethod, methodSource: PsiAnnotation) { val psiMethod = method.javaPsi val containingClass = psiMethod.containingClass ?: return val annotationMemberValue = methodSource.findDeclaredAttributeValue("value") if (annotationMemberValue == null) { if (methodSource.findAttributeValue(PsiAnnotation.DEFAULT_REFERENCED_METHOD_NAME) == null) return val foundMethod = containingClass.findMethodsByName(method.name, true).singleOrNull { it.parameters.isEmpty() } val uFoundMethod = foundMethod.toUElementOfType<UMethod>() if (uFoundMethod != null) { return checkSourceProvider(uFoundMethod, containingClass, methodSource, method) } else { return highlightAbsentSourceProvider(containingClass, methodSource, method.name, method) } } else { annotationMemberValue.nestedValues().forEach { attributeValue -> for (reference in attributeValue.references) { if (reference is MethodSourceReference) { val resolve = reference.resolve() if (resolve !is PsiMethod) { return highlightAbsentSourceProvider(containingClass, attributeValue, reference.value, method) } else { val sourceProvider: PsiMethod = resolve val uSourceProvider = sourceProvider.toUElementOfType<UMethod>() ?: return return checkSourceProvider(uSourceProvider, containingClass, attributeValue, method) } } } } } } private fun highlightAbsentSourceProvider( containingClass: PsiClass, attributeValue: PsiElement, sourceProviderName: String, method: UMethod ) { if (isOnTheFly) { val modifiers = mutableListOf(JvmModifier.PUBLIC) if (!TestUtils.testInstancePerClass(containingClass)) modifiers.add(JvmModifier.STATIC) val typeFromText = JavaPsiFacade.getElementFactory(containingClass.project).createTypeFromText( METHOD_SOURCE_RETURN_TYPE, containingClass ) val request = methodRequest(containingClass.project, sourceProviderName, modifiers, typeFromText) val actions = createMethodActions(containingClass, request) val quickFixes = IntentionWrapper.wrapToQuickFixes(actions, containingClass.containingFile).toTypedArray() val message = JvmAnalysisBundle.message("jvm.inspections.junit.malformed.param.method.source.unresolved.descriptor", sourceProviderName) val place = (if (method.javaPsi.isAncestor(attributeValue, true)) attributeValue else method.javaPsi.nameIdentifier ?: method.javaPsi).toUElement()?.sourcePsi ?: return return holder.registerProblem(place, message, *quickFixes) } } private fun checkSourceProvider(sourceProvider: UMethod, containingClass: PsiClass?, attributeValue: PsiElement, method: UMethod) { val place = (if (method.javaPsi.isAncestor(attributeValue, true)) attributeValue else method.javaPsi.nameIdentifier ?: method.javaPsi).toUElement()?.sourcePsi ?: return val providerName = sourceProvider.name if (!sourceProvider.isStatic && containingClass != null && !TestUtils.testInstancePerClass(containingClass) && !implementationsTestInstanceAnnotated(containingClass) ) { val annotation = JavaPsiFacade.getElementFactory(containingClass.project).createAnnotationFromText( TEST_INSTANCE_PER_CLASS, containingClass ) val actions = mutableListOf<IntentionAction>() val value = (annotation.attributes.first() as PsiNameValuePairImpl).value if (value != null) { actions.addAll(createAddAnnotationActions( containingClass, annotationRequest(ORG_JUNIT_JUPITER_API_TEST_INSTANCE, constantAttribute("value", value.text)) )) } actions.addAll(createModifierActions(sourceProvider, modifierRequest(JvmModifier.STATIC, true))) val quickFixes = IntentionWrapper.wrapToQuickFixes(actions, sourceProvider.javaPsi.containingFile).toTypedArray() val message = JvmAnalysisBundle.message("jvm.inspections.junit.malformed.param.method.source.static.descriptor", providerName) holder.registerProblem(place, message, *quickFixes) } else if (sourceProvider.uastParameters.isNotEmpty() && !classHasParameterResolverField(containingClass)) { val message = JvmAnalysisBundle.message( "jvm.inspections.junit.malformed.param.method.source.no.params.descriptor", providerName) holder.registerProblem(place, message) } else { val componentType = getComponentType(sourceProvider.returnType, method.javaPsi) if (componentType == null) { val message = JvmAnalysisBundle.message( "jvm.inspections.junit.malformed.param.method.source.return.type.descriptor", providerName) holder.registerProblem(place, message) } else if (hasMultipleParameters(method.javaPsi) && !InheritanceUtil.isInheritor(componentType, ORG_JUNIT_JUPITER_PARAMS_PROVIDER_ARGUMENTS) && !componentType.equalsToText(CommonClassNames.JAVA_LANG_OBJECT) && !componentType.deepComponentType.equalsToText(CommonClassNames.JAVA_LANG_OBJECT) ) { val message = JvmAnalysisBundle.message( "jvm.inspections.junit.malformed.param.wrapped.in.arguments.descriptor") holder.registerProblem(place, message) } } } private fun classHasParameterResolverField(aClass: PsiClass?): Boolean { if (aClass == null) return false if (aClass.isInterface) return false return aClass.fields.any { field -> AnnotationUtil.isAnnotated(field, ORG_JUNIT_JUPITER_API_EXTENSION_REGISTER_EXTENSION, 0) && field.type.isInheritorOf(ORG_JUNIT_JUPITER_API_EXTENSION_PARAMETER_RESOLVER) } } private fun implementationsTestInstanceAnnotated(containingClass: PsiClass): Boolean = ClassInheritorsSearch.search(containingClass, containingClass.resolveScope, true).any { TestUtils.testInstancePerClass(it) } private fun getComponentType(returnType: PsiType?, method: PsiMethod): PsiType? { val collectionItemType = JavaGenericsUtil.getCollectionItemType(returnType, method.resolveScope) if (collectionItemType != null) return collectionItemType if (InheritanceUtil.isInheritor(returnType, CommonClassNames.JAVA_UTIL_STREAM_INT_STREAM)) return PsiType.INT if (InheritanceUtil.isInheritor(returnType, CommonClassNames.JAVA_UTIL_STREAM_LONG_STREAM)) return PsiType.LONG if (InheritanceUtil.isInheritor(returnType, CommonClassNames.JAVA_UTIL_STREAM_DOUBLE_STREAM)) return PsiType.DOUBLE val streamItemType = PsiUtil.substituteTypeParameter(returnType, CommonClassNames.JAVA_UTIL_STREAM_STREAM, 0, true) if (streamItemType != null) return streamItemType return PsiUtil.substituteTypeParameter(returnType, CommonClassNames.JAVA_UTIL_ITERATOR, 0, true) } private fun hasMultipleParameters(method: PsiMethod): Boolean { val containingClass = method.containingClass return containingClass != null && method.parameterList.parameters.count { !InheritanceUtil.isInheritor(it.type, ORG_JUNIT_JUPITER_API_TEST_INFO) && !InheritanceUtil.isInheritor(it.type, ORG_JUNIT_JUPITER_API_TEST_REPORTER) } > 1 && !MetaAnnotationUtil.isMetaAnnotatedInHierarchy( containingClass, listOf(ORG_JUNIT_JUPITER_API_EXTENSION_EXTEND_WITH) ) } private fun checkNullSource( method: UMethod, psiAnnotation: PsiAnnotation ) { val size = method.uastParameters.size if (size != 1) { val sourcePsi = (if (method.javaPsi.isAncestor(psiAnnotation, true)) psiAnnotation else method.javaPsi.nameIdentifier ?: method.javaPsi).toUElement()?.sourcePsi ?: return return checkFormalParameters(size, sourcePsi, psiAnnotation.qualifiedName) } } private fun checkEmptySource( method: UMethod, psiAnnotation: PsiAnnotation ) { val sourcePsi = (if (method.javaPsi.isAncestor(psiAnnotation, true)) psiAnnotation else method.javaPsi.nameIdentifier ?: method.javaPsi).toUElement()?.sourcePsi ?: return val size = method.uastParameters.size val shortName = psiAnnotation.qualifiedName ?: return if (size == 1) { var type = method.uastParameters.first().type if (type is PsiClassType) type = type.rawType() if (type is PsiArrayType || type.equalsToText(CommonClassNames.JAVA_LANG_STRING) || type.equalsToText(CommonClassNames.JAVA_UTIL_LIST) || type.equalsToText(CommonClassNames.JAVA_UTIL_SET) || type.equalsToText(CommonClassNames.JAVA_UTIL_MAP) ) return val message = JvmAnalysisBundle.message( "jvm.inspections.junit.malformed.param.empty.source.cannot.provide.argument.descriptor", StringUtil.getShortName(shortName), type.presentableText) holder.registerProblem(sourcePsi, message) } else { checkFormalParameters(size, sourcePsi, shortName) } } private fun checkFormalParameters( size: Int, sourcePsi: PsiElement, sourceName: String? ) { if (sourceName == null) return val message = if (size == 0) { JvmAnalysisBundle.message( "jvm.inspections.junit.malformed.param.null.source.cannot.provide.argument.no.params.descriptor", StringUtil.getShortName(sourceName)) } else { JvmAnalysisBundle.message( "jvm.inspections.junit.malformed.param.null.source.cannot.provide.argument.too.many.params.descriptor", StringUtil.getShortName(sourceName)) } holder.registerProblem(sourcePsi, message) } private fun checkEnumSource(method: UMethod, enumSource: PsiAnnotation) { // @EnumSource#value type is Class<?>, not an array val value = enumSource.findAttributeValue(PsiAnnotation.DEFAULT_REFERENCED_METHOD_NAME) if (value is PsiClassObjectAccessExpression) { val enumType = value.operand.type checkSourceTypeAndParameterTypeAgree(method, value, enumType) checkEnumConstants(enumSource, enumType, method) } return } private fun checkSourceTypeAndParameterTypeAgree(method: UMethod, attributeValue: PsiAnnotationMemberValue, componentType: PsiType) { val parameters = method.uastParameters if (parameters.size == 1) { val paramType = parameters.first().type if (!paramType.isAssignableFrom(componentType) && !InheritanceUtil.isInheritor( componentType, ORG_JUNIT_JUPITER_PARAMS_PROVIDER_ARGUMENTS) ) { if (componentType.equalsToText(CommonClassNames.JAVA_LANG_STRING)) { //implicit conversion to primitive/wrapper if (TypeConversionUtil.isPrimitiveAndNotNullOrWrapper(paramType)) return val psiClass = PsiUtil.resolveClassInClassTypeOnly(paramType) //implicit conversion to enum if (psiClass != null) { if (psiClass.isEnum && psiClass.findFieldByName((attributeValue as PsiLiteral).value as String?, false) != null) return //implicit java time conversion val qualifiedName = psiClass.qualifiedName if (qualifiedName != null) { if (qualifiedName.startsWith("java.time.")) return if (qualifiedName == "java.nio.file.Path") return } val factoryMethod: (PsiMethod) -> Boolean = { !it.hasModifier(JvmModifier.PRIVATE) && it.parameterList.parametersCount == 1 && it.parameterList.parameters.first().type.equalsToText(CommonClassNames.JAVA_LANG_STRING) } if (!psiClass.hasModifier(JvmModifier.ABSTRACT) && psiClass.constructors.find(factoryMethod) != null) return if (psiClass.methods.find { it.hasModifier(JvmModifier.STATIC) && factoryMethod(it) } != null) return } } else if (componentType.equalsToText(ORG_JUNIT_JUPITER_PARAMS_PROVIDER_NULL_ENUM)) { val psiClass = PsiUtil.resolveClassInClassTypeOnly(paramType) if (psiClass != null && psiClass.isEnum) return } val param = parameters.first() val default = param.sourcePsi as PsiNameIdentifierOwner val place = (if (method.javaPsi.isAncestor(attributeValue, true)) attributeValue else default.nameIdentifier ?: default).toUElement()?.sourcePsi ?: return if (param.findAnnotation(ORG_JUNIT_JUPITER_PARAMS_CONVERTER_CONVERT_WITH) != null) return val message = JvmAnalysisBundle.message( "jvm.inspections.junit.malformed.param.method.source.assignable.descriptor", componentType.presentableText, paramType.presentableText ) holder.registerProblem(place, message) } } } private fun checkValuesSource(method: UMethod, valuesSource: PsiAnnotation) { val psiMethod = method.javaPsi val possibleValues = mapOf( "strings" to PsiType.getJavaLangString(psiMethod.manager, psiMethod.resolveScope), "ints" to PsiType.INT, "longs" to PsiType.LONG, "doubles" to PsiType.DOUBLE, "shorts" to PsiType.SHORT, "bytes" to PsiType.BYTE, "floats" to PsiType.FLOAT, "chars" to PsiType.CHAR, "booleans" to PsiType.BOOLEAN, "classes" to PsiType.getJavaLangClass(psiMethod.manager, psiMethod.resolveScope) ) possibleValues.keys.forEach { valueKey -> valuesSource.nestedAttributeValues(valueKey)?.forEach { value -> possibleValues[valueKey]?.let { checkSourceTypeAndParameterTypeAgree(method, value, it) } } } val attributesNumber = valuesSource.parameterList.attributes.size val annotation = (if (method.javaPsi.isAncestor(valuesSource, true)) valuesSource else method.javaPsi.nameIdentifier ?: method.javaPsi).toUElementOfType<UAnnotation>() ?: return val message = if (attributesNumber == 0) { JvmAnalysisBundle.message("jvm.inspections.junit.malformed.param.no.value.source.is.defined.descriptor") } else if (attributesNumber > 1) { JvmAnalysisBundle.message( "jvm.inspections.junit.malformed.param.exactly.one.type.of.input.must.be.provided.descriptor") } else return return holder.registerUProblem(annotation, message) } private fun checkEnumConstants( enumSource: PsiAnnotation, enumType: PsiType, method: UMethod ) { val mode = enumSource.findAttributeValue("mode") val uMode = mode.toUElement() if (uMode is UReferenceExpression && ("INCLUDE" == uMode.resolvedName || "EXCLUDE" == uMode.resolvedName)) { var validType = enumType if (enumType.canonicalText == ORG_JUNIT_JUPITER_PARAMS_PROVIDER_NULL_ENUM) { val parameters = method.uastParameters if (parameters.isNotEmpty()) validType = parameters.first().type } val allEnumConstants = (PsiUtil.resolveClassInClassTypeOnly(validType) ?: return).fields .filterIsInstance<PsiEnumConstant>() .map { it.name } .toSet() val definedConstants = mutableSetOf<String>() enumSource.nestedAttributeValues("names")?.forEach { name -> if (name is PsiLiteralExpression) { val value = name.value if (value is String) { val sourcePsi = (if (method.javaPsi.isAncestor(name, true)) name else method.javaPsi.nameIdentifier ?: method.javaPsi).toUElement()?.sourcePsi ?: return@forEach val message = if (!allEnumConstants.contains(value)) { JvmAnalysisBundle.message("jvm.inspections.junit.malformed.param.unresolved.enum.descriptor") } else if (!definedConstants.add(value)) { JvmAnalysisBundle.message("jvm.inspections.junit.malformed.param.duplicated.enum.descriptor") } else return@forEach holder.registerProblem(sourcePsi, message) } } } } } private fun checkCsvSource(methodSource: PsiAnnotation) { methodSource.nestedAttributeValues("resources")?.forEach { attributeValue -> for (ref in attributeValue.references) { if (ref.isSoft) continue if (ref is FileReference && ref.multiResolve(false).isEmpty()) { val message = JvmAnalysisBundle.message("jvm.inspections.junit.malformed.param.file.source.descriptor", attributeValue.text) holder.registerProblem(ref.element, message, *ref.quickFixes) } } } } private fun PsiAnnotation.nestedAttributeValues(value: String) = findAttributeValue(value)?.nestedValues() private fun PsiAnnotationMemberValue.nestedValues(): List<PsiAnnotationMemberValue> { return if (this is PsiArrayInitializerMemberValue) initializers.flatMap { it.nestedValues() } else listOf(this) } class AnnotatedSignatureProblem( private val annotations: List<String>, private val shouldBeStatic: Boolean, private val shouldBeInTestInstancePerClass: Boolean = false, private val shouldBeVoidType: Boolean? = null, private val shouldBeSubTypeOf: List<String>? = null, private val validVisibility: ((UDeclaration) -> UastVisibility?)? = null, private val validParameters: ((UMethod) -> List<UParameter>?)? = null, ) { private fun modifierProblems( validVisibility: UastVisibility?, decVisibility: UastVisibility, isStatic: Boolean, isInstancePerClass: Boolean ): List<@NlsSafe String> { val problems = mutableListOf<String>() if (shouldBeInTestInstancePerClass) { if (!isStatic && !isInstancePerClass) problems.add("static") } else if (shouldBeStatic && !isStatic) problems.add("static") else if (!shouldBeStatic && isStatic) problems.add("non-static") if (validVisibility != null && validVisibility != decVisibility) problems.add(validVisibility.text) return problems } fun report(holder: ProblemsHolder, element: UField) { val javaPsi = element.javaPsi.castSafelyTo<PsiField>() ?: return val annotation = annotations.firstOrNull { MetaAnnotationUtil.isMetaAnnotated(javaPsi, annotations) } ?: return val visibility = validVisibility?.invoke(element) val problems = modifierProblems(visibility, element.visibility, element.isStatic, false) if (shouldBeVoidType == true && element.type != PsiType.VOID) { return holder.fieldTypeProblem(element, visibility, annotation, problems, PsiType.VOID.name) } if (shouldBeSubTypeOf?.any { InheritanceUtil.isInheritor(element.type, it) } == false) { return holder.fieldTypeProblem(element, visibility, annotation, problems, shouldBeSubTypeOf.first()) } if (problems.isNotEmpty()) return holder.fieldModifierProblem(element, visibility, annotation, problems) } private fun ProblemsHolder.fieldModifierProblem( element: UField, visibility: UastVisibility?, annotation: String, problems: List<@NlsSafe String> ) { val message = if (problems.size == 1) { JvmAnalysisBundle.message("jvm.inspections.junit.malformed.annotated.field.single.descriptor", annotation.substringAfterLast('.'), problems.first() ) } else { JvmAnalysisBundle.message("jvm.inspections.junit.malformed.annotated.field.double.descriptor", annotation.substringAfterLast('.'), problems.first(), problems.last() ) } reportFieldProblem(message, element, visibility) } private fun ProblemsHolder.fieldTypeProblem( element: UField, visibility: UastVisibility?, annotation: String, problems: List<@NlsSafe String>, type: String ) { if (problems.isEmpty()) { val message = JvmAnalysisBundle.message( "jvm.inspections.junit.malformed.annotated.field.typed.descriptor", annotation.substringAfterLast('.'), type) registerUProblem(element, message) } else if (problems.size == 1) { val message = JvmAnalysisBundle.message("jvm.inspections.junit.malformed.annotated.field.single.typed.descriptor", annotation.substringAfterLast('.'), problems.first(), type ) reportFieldProblem(message, element, visibility) } else { val message = JvmAnalysisBundle.message("jvm.inspections.junit.malformed.annotated.field.double.typed.descriptor", annotation.substringAfterLast('.'), problems.first(), problems.last(), type ) reportFieldProblem(message, element, visibility) } } private fun ProblemsHolder.reportFieldProblem(message: @InspectionMessage String, element: UField, visibility: UastVisibility?) { val quickFix = FieldSignatureQuickfix(element.name, shouldBeStatic, visibilityToModifier[visibility]) return registerUProblem(element, message, quickFix) } fun report(holder: ProblemsHolder, element: UMethod) { val javaPsi = element.javaPsi.castSafelyTo<PsiMethod>() ?: return val sourcePsi = element.sourcePsi ?: return val annotation = annotations.firstOrNull { AnnotationUtil.isAnnotated(javaPsi, it, AnnotationUtil.CHECK_HIERARCHY) } ?: return val alternatives = UastFacade.convertToAlternatives(sourcePsi, arrayOf(UMethod::class.java)) val elementIsStatic = alternatives.any { it.isStatic } val visibility = validVisibility?.invoke(element) val params = validParameters?.invoke(element) val problems = modifierProblems( visibility, element.visibility, elementIsStatic, javaPsi.containingClass?.let { cls -> TestUtils.testInstancePerClass(cls) } == true ) if (element.lang == Language.findLanguageByID("kotlin") && element.javaPsi.modifierList.text.contains("suspend")) { val message = JvmAnalysisBundle.message( "jvm.inspections.junit.malformed.annotated.suspend.function.descriptor", annotation.substringAfterLast('.') ) return holder.registerUProblem(element, message) } if (params != null && params.size != element.uastParameters.size) { if (shouldBeVoidType == true && element.returnType != PsiType.VOID) { return holder.methodParameterTypeProblem(element, visibility, annotation, problems, PsiType.VOID.name, params) } if (shouldBeSubTypeOf?.any { InheritanceUtil.isInheritor(element.returnType, it) } == false) { return holder.methodParameterTypeProblem(element, visibility, annotation, problems, shouldBeSubTypeOf.first(), params) } if (params.isNotEmpty()) holder.methodParameterProblem(element, visibility, annotation, problems, params) return holder.methodParameterProblem(element, visibility, annotation, problems, params) } if (shouldBeVoidType == true && element.returnType != PsiType.VOID) { return holder.methodTypeProblem(element, visibility, annotation, problems, PsiType.VOID.name) } if (shouldBeSubTypeOf?.any { InheritanceUtil.isInheritor(element.returnType, it) } == false) { return holder.methodTypeProblem(element, visibility, annotation, problems, shouldBeSubTypeOf.first()) } if (problems.isNotEmpty()) return holder.methodModifierProblem(element, visibility, annotation, problems) } private fun ProblemsHolder.methodParameterProblem( element: UMethod, visibility: UastVisibility?, annotation: String, problems: List<@NlsSafe String>, parameters: List<UParameter> ) { val invalidParams = element.uastParameters.toMutableList().apply { removeAll(parameters) } val message = when { problems.isEmpty() && invalidParams.size == 1 -> JvmAnalysisBundle.message( "jvm.inspections.junit.malformed.annotated.method.param.single.descriptor", annotation.substringAfterLast('.'), invalidParams.first().name ) problems.isEmpty() && invalidParams.size > 1 -> JvmAnalysisBundle.message( "jvm.inspections.junit.malformed.annotated.method.param.double.descriptor", annotation.substringAfterLast('.'), invalidParams.joinToString { "'$it'" }, invalidParams.last().name ) problems.size == 1 && invalidParams.size == 1 -> JvmAnalysisBundle.message( "jvm.inspections.junit.malformed.annotated.method.single.param.single.descriptor", annotation.substringAfterLast('.'), problems.first(), invalidParams.first().name ) problems.size == 1 && invalidParams.size > 1 -> JvmAnalysisBundle.message( "jvm.inspections.junit.malformed.annotated.method.single.param.double.descriptor", annotation.substringAfterLast('.'), problems.first(), invalidParams.joinToString { "'$it'" }, invalidParams.last().name ) problems.size == 2 && invalidParams.size == 1 -> JvmAnalysisBundle.message( "jvm.inspections.junit.malformed.annotated.method.double.param.single.descriptor", annotation.substringAfterLast('.'), problems.first(), problems.last(), invalidParams.first().name ) problems.size == 2 && invalidParams.size > 1 -> JvmAnalysisBundle.message( "jvm.inspections.junit.malformed.annotated.method.double.param.double.descriptor", annotation.substringAfterLast('.'), problems.first(), problems.last(), invalidParams.joinToString { "'$it'" }, invalidParams.last().name ) else -> error("Non valid problem.") } reportMethodProblem(message, element, visibility) } private fun ProblemsHolder.methodParameterTypeProblem( element: UMethod, visibility: UastVisibility?, annotation: String, problems: List<@NlsSafe String>, type: String, parameters: List<UParameter> ) { val invalidParams = element.uastParameters.toMutableList().apply { removeAll(parameters) } val message = when { problems.isEmpty() && invalidParams.size == 1 -> JvmAnalysisBundle.message( "jvm.inspections.junit.malformed.annotated.method.typed.param.single.descriptor", annotation.substringAfterLast('.'), type, invalidParams.first().name ) problems.isEmpty() && invalidParams.size > 1 -> JvmAnalysisBundle.message( "jvm.inspections.junit.malformed.annotated.method.typed.param.double.descriptor", annotation.substringAfterLast('.'), type, invalidParams.joinToString { "'$it'" }, invalidParams.last().name ) problems.size == 1 && invalidParams.size == 1 -> JvmAnalysisBundle.message( "jvm.inspections.junit.malformed.annotated.method.single.typed.param.single.descriptor", annotation.substringAfterLast('.'), problems.first(), type, invalidParams.first().name ) problems.size == 1 && invalidParams.size > 1 -> JvmAnalysisBundle.message( "jvm.inspections.junit.malformed.annotated.method.single.typed.param.double.descriptor", annotation.substringAfterLast('.'), problems.first(), type, invalidParams.joinToString { "'$it'" }, invalidParams.last().name ) problems.size == 2 && invalidParams.size == 1 -> JvmAnalysisBundle.message( "jvm.inspections.junit.malformed.annotated.method.double.typed.param.single.descriptor", annotation.substringAfterLast('.'), problems.first(), problems.last(), type, invalidParams.first().name ) problems.size == 2 && invalidParams.size > 1 -> JvmAnalysisBundle.message( "jvm.inspections.junit.malformed.annotated.method.double.typed.param.double.descriptor", annotation.substringAfterLast('.'), problems.first(), problems.last(), type, invalidParams.joinToString { "'$it'" }, invalidParams.last().name ) else -> error("Non valid problem.") } reportMethodProblem(message, element, visibility) } private fun ProblemsHolder.methodTypeProblem( element: UMethod, visibility: UastVisibility?, annotation: String, problems: List<@NlsSafe String>, type: String ) { val message = if (problems.isEmpty()) { JvmAnalysisBundle.message( "jvm.inspections.junit.malformed.annotated.method.typed.descriptor", annotation.substringAfterLast('.'), type ) } else if (problems.size == 1) { JvmAnalysisBundle.message("jvm.inspections.junit.malformed.annotated.method.single.typed.descriptor", annotation.substringAfterLast('.'), problems.first(), type ) } else { JvmAnalysisBundle.message("jvm.inspections.junit.malformed.annotated.method.double.typed.descriptor", annotation.substringAfterLast('.'), problems.first(), problems.last(), type ) } reportMethodProblem(message, element, visibility) } private fun ProblemsHolder.methodModifierProblem( element: UMethod, visibility: UastVisibility?, annotation: String, problems: List<@NlsSafe String> ) { val message = if (problems.size == 1) { JvmAnalysisBundle.message("jvm.inspections.junit.malformed.annotated.method.single.descriptor", annotation.substringAfterLast('.'), problems.first() ) } else { JvmAnalysisBundle.message("jvm.inspections.junit.malformed.annotated.method.double.descriptor", annotation.substringAfterLast('.'), problems.first(), problems.last() ) } reportMethodProblem(message, element, visibility) } private fun ProblemsHolder.reportMethodProblem(message: @InspectionMessage String, element: UMethod, visibility: UastVisibility? = null, params: List<UParameter>? = null) { val quickFix = MethodSignatureQuickfix( element.name, shouldBeStatic, shouldBeVoidType, visibilityToModifier[visibility], params?.associate { it.name to it.type } ?: emptyMap() ) return registerUProblem(element, message, quickFix) } } class FieldSignatureQuickfix( private val name: @NlsSafe String, private val makeStatic: Boolean, private val newVisibility: JvmModifier? = null ) : LocalQuickFix { override fun getFamilyName(): String = JvmAnalysisBundle.message("jvm.inspections.junit.malformed.fix.field.signature") override fun getName(): String = JvmAnalysisBundle.message("jvm.inspections.junit.malformed.fix.field.signature.descriptor", name) override fun applyFix(project: Project, descriptor: ProblemDescriptor) { val containingFile = descriptor.psiElement.containingFile ?: return val javaDeclaration = getUParentForIdentifier(descriptor.psiElement)?.castSafelyTo<UField>()?.javaPsi ?: return val declPtr = SmartPointerManager.getInstance(project).createSmartPsiElementPointer(javaDeclaration) if (newVisibility != null) { declPtr.element?.castSafelyTo<JvmModifiersOwner>()?.let { jvmMethod -> createModifierActions(jvmMethod, modifierRequest(newVisibility, true)).forEach { it.invoke(project, null, containingFile) } } } declPtr.element?.castSafelyTo<JvmModifiersOwner>()?.let { jvmMethod -> createModifierActions(jvmMethod, modifierRequest(JvmModifier.STATIC, makeStatic)).forEach { it.invoke(project, null, containingFile) } } } } class MethodSignatureQuickfix( private val name: @NlsSafe String, private val makeStatic: Boolean, private val shouldBeVoidType: Boolean? = null, private val newVisibility: JvmModifier? = null, @SafeFieldForPreview private val inCorrectParams: Map<String, JvmType>? = null ) : LocalQuickFix { override fun getFamilyName(): String = JvmAnalysisBundle.message("jvm.inspections.junit.malformed.fix.method.signature") override fun getName(): String = JvmAnalysisBundle.message("jvm.inspections.junit.malformed.fix.method.signature.descriptor", name) override fun applyFix(project: Project, descriptor: ProblemDescriptor) { val containingFile = descriptor.psiElement.containingFile ?: return val javaDeclaration = getUParentForIdentifier(descriptor.psiElement)?.castSafelyTo<UMethod>()?.javaPsi ?: return val declPtr = SmartPointerManager.getInstance(project).createSmartPsiElementPointer(javaDeclaration) if (shouldBeVoidType == true) { declPtr.element?.castSafelyTo<JvmMethod>()?.let { jvmMethod -> createChangeTypeActions(jvmMethod, typeRequest(JvmPrimitiveTypeKind.VOID.name, emptyList())).forEach { it.invoke(project, null, containingFile) } } } if (newVisibility != null) { declPtr.element?.castSafelyTo<JvmModifiersOwner>()?.let { jvmMethod -> createModifierActions(jvmMethod, modifierRequest(newVisibility, true)).forEach { it.invoke(project, null, containingFile) } } } if (inCorrectParams != null) { declPtr.element?.castSafelyTo<JvmMethod>()?.let { jvmMethod -> createChangeParametersActions(jvmMethod, setMethodParametersRequest(inCorrectParams.entries)).forEach { it.invoke(project, null, containingFile) } } } declPtr.element?.castSafelyTo<JvmModifiersOwner>()?.let { jvmMethod -> createModifierActions(jvmMethod, modifierRequest(JvmModifier.STATIC, makeStatic)).forEach { it.invoke(project, null, containingFile) } } } } companion object { private const val TEST_INSTANCE_PER_CLASS = "@org.junit.jupiter.api.TestInstance(TestInstance.Lifecycle.PER_CLASS)" private const val METHOD_SOURCE_RETURN_TYPE = "java.util.stream.Stream<org.junit.jupiter.params.provider.Arguments>" private val visibilityToModifier = mapOf( UastVisibility.PUBLIC to JvmModifier.PUBLIC, UastVisibility.PROTECTED to JvmModifier.PROTECTED, UastVisibility.PRIVATE to JvmModifier.PRIVATE, UastVisibility.PACKAGE_LOCAL to JvmModifier.PACKAGE_LOCAL ) private val NON_COMBINED_TEST = listOf( ORG_JUNIT_JUPITER_API_TEST, ORG_JUNIT_JUPITER_API_TEST_FACTORY, ORG_JUNIT_JUPITER_API_REPEATED_TEST, ORG_JUNIT_JUPITER_PARAMS_PARAMETERIZED_TEST ) private val PARAMETERIZED_SOURCES = listOf( ORG_JUNIT_JUPITER_PARAMS_PROVIDER_METHOD_SOURCE, ORG_JUNIT_JUPITER_PARAMS_PROVIDER_VALUE_SOURCE, ORG_JUNIT_JUPITER_PARAMS_PROVIDER_ENUM_SOURCE, ORG_JUNIT_JUPITER_PARAMS_PROVIDER_CSV_FILE_SOURCE, ORG_JUNIT_JUPITER_PARAMS_PROVIDER_NULL_SOURCE, ORG_JUNIT_JUPITER_PARAMS_PROVIDER_EMPTY_SOURCE, ORG_JUNIT_JUPITER_PARAMS_PROVIDER_NULL_AND_EMPTY_SOURCE ) } }
apache-2.0
d570d3a143104dd4987ffaf925adb045
50.599811
140
0.712968
4.781782
false
true
false
false
benjamin-bader/thrifty
thrifty-schema/src/main/kotlin/com/microsoft/thrifty/schema/MapType.kt
1
2778
/* * Thrifty * * Copyright (c) Microsoft Corporation * * All rights reserved. * * 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 * * THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING * WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, * FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT. * * See the Apache Version 2.0 License for specific language governing permissions and limitations under the License. */ package com.microsoft.thrifty.schema /** * Represents a Thrift `map<K, V>`. * * @property keyType The type of keys contained in maps of this type. * @property valueType The type of values contained in maps of this type. */ class MapType internal constructor( val keyType: ThriftType, val valueType: ThriftType, override val annotations: Map<String, String> = emptyMap() ) : ThriftType("map<" + keyType.name + ", " + valueType.name + ">") { override val isMap: Boolean = true override fun <T> accept(visitor: ThriftType.Visitor<T>): T = visitor.visitMap(this) override fun withAnnotations(annotations: Map<String, String>): ThriftType { return MapType(keyType, valueType, mergeAnnotations(this.annotations, annotations)) } /** * Creates a [Builder] initialized with this map type. */ fun toBuilder(): Builder = Builder(this) /** * An object that can create [MapType] instances. */ class Builder( private var keyType: ThriftType, private var valueType: ThriftType, private var annotations: Map<String, String> ) { internal constructor(type: MapType) : this(type.keyType, type.valueType, type.annotations) /** * Use the given [keyType] for the [MapType] under construction. */ fun keyType(keyType: ThriftType): Builder = apply { this.keyType = keyType } /** * Use the given [valueType] for the [MapType] under construction. */ fun valueType(valueType: ThriftType): Builder = apply { this.valueType = valueType } /** * Use the given [annotations] for the [MapType] under construction. */ fun annotations(annotations: Map<String, String>): Builder = apply { this.annotations = annotations } /** * Creates a new [MapType] instance. */ fun build(): MapType { return MapType(keyType, valueType, annotations) } } }
apache-2.0
f6aea0c8aa5d3feecffb4b423b54a8df
31.302326
116
0.643269
4.517073
false
false
false
false
martinhellwig/DatapassWidget
app/src/main/java/de/schooltec/datapass/WidgetAutoUpdateProvider.kt
1
4626
package de.schooltec.datapass import android.appwidget.AppWidgetManager import android.appwidget.AppWidgetProvider import android.content.Context import android.os.AsyncTask import android.os.Build import android.telephony.TelephonyManager import de.schooltec.datapass.AppWidgetIdUtil.addEntry import de.schooltec.datapass.AppWidgetIdUtil.deleteEntryIfContained import de.schooltec.datapass.AppWidgetIdUtil.getCarrierForGivenAppWidgetId import de.schooltec.datapass.AppWidgetIdUtil.lastUpdateTimeoutOver /** * AppWidgetProvider which automatically gets called due to "ACTION_APPWIDGET_UPDATE" (see Manifest). * * Gets called when (1) a new instance of the widget is added to the home screen, (2) an update is requested every 6h * (see widget_provider.xml -> updatePeriodMillis) or (3) on device reboot. * * @author Martin Hellwig * @author Markus Hettig */ class WidgetAutoUpdateProvider : AppWidgetProvider() { override fun onUpdate(context: Context, appWidgetManager: AppWidgetManager, appWidgetIds: IntArray) { appWidgetIds.forEach { appWidgetId -> // Only go further, if the last update was long enough in the past if (!lastUpdateTimeoutOver(context, appWidgetId)) return@forEach val oldWidgetIds = AppWidgetIdUtil.getAllStoredAppWidgetIds(context) val alreadyContained = oldWidgetIds.any { it.contains(appWidgetId.toString()) } val carrierOfAlreadyContainedWidgetId = getCarrierForGivenAppWidgetId(context, appWidgetId) if (alreadyContained && carrierOfAlreadyContainedWidgetId != null) { updateExistingWidget(context, appWidgetId, carrierOfAlreadyContainedWidgetId) } else { addNewWidgetAndUpdate(context, appWidgetId) } } } private fun addNewWidgetAndUpdate(context: Context, appWidgetId: Int) { val telephonyManager = context.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager var toUseCarrier = // Only ask, if device is API 22 or otherwise (API 23 and up), if there are more than two sims // All devices with API lower than API 22 are not good supported for multi-sims if (Build.VERSION.SDK_INT == Build.VERSION_CODES.LOLLIPOP_MR1 || Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && telephonyManager.phoneCount > 1 ) { UpdateWidgetTask.CARRIER_NOT_SELECTED } else { // If the carrier of the phone has changed (or there is no carrier, because in // flight mode), use the new one, otherwise use the old one telephonyManager.networkOperatorName } if (toUseCarrier == null || toUseCarrier.isEmpty()) toUseCarrier = UpdateWidgetTask.CARRIER_NOT_SELECTED addEntry(context, appWidgetId, toUseCarrier) UpdateWidgetTask(appWidgetId, context, UpdateMode.REGULAR, toUseCarrier).executeOnExecutor( AsyncTask.THREAD_POOL_EXECUTOR ) } private fun updateExistingWidget(context: Context, appWidgetId: Int, carrier: String) { val telephonyManager = context.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager var toUseCarrier = // Only ask, if device is API 22 or otherwise (API 23 and up), if there are more than two sims // All devices with API lower than API 22 are not good supported for multi-sims if (carrier == UpdateWidgetTask.CARRIER_NOT_SELECTED && (Build.VERSION.SDK_INT == Build.VERSION_CODES.LOLLIPOP_MR1 || Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && telephonyManager.phoneCount > 1) ) { UpdateWidgetTask.CARRIER_NOT_SELECTED } else { // If the carrier of the phone has changed (or there is no carrier, because in // flight mode), use the new one, otherwise use the old one var possibleCarrier = telephonyManager.networkOperatorName if (possibleCarrier == null || possibleCarrier.isEmpty()) possibleCarrier = carrier possibleCarrier } if (toUseCarrier.isEmpty()) toUseCarrier = UpdateWidgetTask.CARRIER_NOT_SELECTED UpdateWidgetTask(appWidgetId, context, UpdateMode.SILENT, toUseCarrier).executeOnExecutor( AsyncTask.THREAD_POOL_EXECUTOR ) } override fun onDeleted(context: Context, appWidgetIds: IntArray) { super.onDeleted(context, appWidgetIds) appWidgetIds.forEach { deleteEntryIfContained(context, it) } } }
apache-2.0
8343ac1b275f15c4f69062ed8d1ca3bf
46.690722
160
0.689364
4.749487
false
false
false
false
micolous/metrodroid
src/commonMain/kotlin/au/id/micolous/metrodroid/transit/tfi_leap/LeapTransitData.kt
1
11072
/* * LeapTransitData.kt * * Copyright 2018-2019 Google * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package au.id.micolous.metrodroid.transit.tfi_leap import au.id.micolous.metrodroid.card.CardType import au.id.micolous.metrodroid.card.desfire.DesfireCard import au.id.micolous.metrodroid.card.desfire.DesfireCardTransitFactory import au.id.micolous.metrodroid.card.desfire.DesfireUnlocker import au.id.micolous.metrodroid.card.desfire.files.UnauthorizedDesfireFile import au.id.micolous.metrodroid.multi.* import au.id.micolous.metrodroid.time.* import au.id.micolous.metrodroid.transit.* import au.id.micolous.metrodroid.ui.HeaderListItem import au.id.micolous.metrodroid.ui.ListItem import au.id.micolous.metrodroid.util.ImmutableByteArray import au.id.micolous.metrodroid.util.NumberUtils import au.id.micolous.metrodroid.util.Preferences import au.id.micolous.metrodroid.util.StationTableReader private const val NAME = "Leap" internal expect fun createUnlockerDispatch(appId: Int, manufData: ImmutableByteArray): DesfireUnlocker? @Parcelize class LockedLeapTransitData : TransitData() { override val serialNumber: String? get() = null public override val balance: TransitBalance? get() = null override val info: List<ListItem>? get() = listOf(ListItem(R.string.leap_locked_warning, "")) override val cardName: String get() = NAME } @Parcelize private class AccumulatorBlock internal constructor(private val mAccumulators: List<Pair<Int, Int>>, // agency, value private val mAccumulatorRegion: Int?, private val mAccumulatorScheme: Int?, private val mAccumulatorStart: TimestampFull) : Parcelable { // Fare cap explanation: https://about.leapcard.ie/fare-capping // // There are two types of caps: // - Daily travel spend // - Weekly travel spend // // There are then two levels of caps: // - Single-operator spend (and each operator has different thresholds) // - All-operator spend (which applies to the sum of all fares) // // Certain services are excluded from the caps. internal val info: List<ListItem> get() = listOf(ListItem( R.string.leap_period_start, TimestampFormatter.dateTimeFormat(mAccumulatorStart)), ListItem(R.string.leap_accumulator_region, mAccumulatorRegion.toString()), ListItem(R.string.leap_accumulator_total, TransitCurrency.EUR(mAccumulatorScheme!!) .maybeObfuscateBalance().formatCurrencyString(true))) + mAccumulators.filter { (_, value) -> value != 0 }.map { (agency, value) -> ListItem( FormattedString(Localizer.localizeString(R.string.leap_accumulator_agency, StationTableReader.getOperatorName(LeapTransitData.LEAP_STR, agency, false))), TransitCurrency.EUR(value).maybeObfuscateBalance().formatCurrencyString(true) ) } internal constructor(file: ImmutableByteArray, offset: Int) : this( mAccumulatorStart = LeapTransitData.parseDate(file, offset), mAccumulatorRegion = file[offset + 4].toInt(), mAccumulatorScheme = file.byteArrayToInt(offset + 5, 3), mAccumulators = (0..3).map { i -> Pair(file.byteArrayToInt(offset + 8 + 2 * i, 2), LeapTransitData.parseBalance(file, offset + 0x10 + 3 * i)) } // 4 bytes hash ) } @Parcelize class LeapTransitData private constructor(private val mIssueDate: Timestamp, override val serialNumber: String, private val mBalance: Int, private val mIssuerId: Int, private val mInitDate: Timestamp, private val mExpiryDate: Timestamp, private val mDailyAccumulators: AccumulatorBlock, private val mWeeklyAccumulators: AccumulatorBlock, override val trips: List<LeapTrip>) : TransitData() { public override val balance: TransitBalance? get() = TransitBalanceStored(TransitCurrency.EUR(mBalance), null, mExpiryDate) override val info: List<ListItem>? get() = listOfNotNull( ListItem(R.string.initialisation_date, mInitDate.format()), ListItem(R.string.issue_date, mIssueDate.format()), if (Preferences.hideCardNumbers) { ListItem(R.string.card_issuer, mIssuerId.toString()) } else null, HeaderListItem(R.string.leap_daily_accumulators)) + mDailyAccumulators.info + HeaderListItem(R.string.leap_weekly_accumulators) + mWeeklyAccumulators.info override val cardName: String get() = NAME companion object { private const val APP_ID = 0xaf1122 internal const val LEAP_STR = "tfi_leap" private val CARD_INFO = CardInfo( name = NAME, locationId = R.string.location_ireland, cardType = CardType.MifareDesfire, imageId = R.drawable.leap_card, iOSSupported = false, imageAlphaId = R.drawable.iso7810_id1_alpha, resourceExtraNote = R.string.card_note_leap, region = TransitRegion.IRELAND, preview = true) private const val BLOCK_SIZE = 0x180 private val LEAP_EPOCH = Epoch.utc(1997, MetroTimeZone.DUBLIN) private fun parse(card: DesfireCard): TransitData { val app = card.getApplication(APP_ID) if (app!!.getFile(2) is UnauthorizedDesfireFile) { return LockedLeapTransitData() } val file2 = app.getFile(2)!!.data val file4 = app.getFile(4)!!.data val file6 = app.getFile(6)!!.data val balanceBlock = chooseBlock(file6, 6) // 1 byte unknown val mInitDate = parseDate(file6, balanceBlock + 1) val mExpiryDate = mInitDate.plus(Duration.yearsLocal(12)) // 1 byte unknown // offset: 0xc //offset 0x20 val trips = mutableListOf<LeapTrip?>() trips.add(LeapTrip.parseTopup(file6, 0x20)) trips.add(LeapTrip.parseTopup(file6, 0x35)) trips.add(LeapTrip.parseTopup(file6, 0x20 + BLOCK_SIZE)) trips.add(LeapTrip.parseTopup(file6, 0x35 + BLOCK_SIZE)) trips.add(LeapTrip.parsePurseTrip(file6, 0x80)) trips.add(LeapTrip.parsePurseTrip(file6, 0x90)) trips.add(LeapTrip.parsePurseTrip(file6, 0x80 + BLOCK_SIZE)) trips.add(LeapTrip.parsePurseTrip(file6, 0x90 + BLOCK_SIZE)) app.getFile(9)?.data?.also { file9 -> for (i in 0..6) trips.add(LeapTrip.parseTrip(file9, 0x80 * i)) } val capBlock = chooseBlock(file6, 0xa6) return LeapTransitData( serialNumber = getSerial(card), mBalance = parseBalance(file6, balanceBlock + 9), trips = LeapTrip.postprocess(trips), mExpiryDate = mExpiryDate, mInitDate = mInitDate, mIssueDate = parseDate(file4, 0x22), mIssuerId = file2.byteArrayToInt(0x22, 3), // offset 0x140 mDailyAccumulators = AccumulatorBlock(file6, capBlock + 0x140), mWeeklyAccumulators = AccumulatorBlock(file6, capBlock + 0x160) ) } private fun chooseBlock(file: ImmutableByteArray, txidoffset: Int): Int { val txIdA = file.byteArrayToInt(txidoffset, 2) val txIdB = file.byteArrayToInt(BLOCK_SIZE + txidoffset, 2) return if (txIdA > txIdB) { 0 } else BLOCK_SIZE } fun parseBalance(file: ImmutableByteArray, offset: Int): Int { return file.getBitsFromBufferSigned(offset * 8, 24) } fun parseDate(file: ImmutableByteArray, offset: Int): TimestampFull { val sec = file.byteArrayToInt(offset, 4) return LEAP_EPOCH.seconds(sec.toLong()) } private fun getSerial(card: DesfireCard): String { val app = card.getApplication(APP_ID) val serial = app!!.getFile(2)!!.data.byteArrayToInt(0x25, 4) val initDate = parseDate(app.getFile(6)!!.data, 1) // luhn checksum of number without date is always 6 val checkDigit = (NumberUtils.calculateLuhn(serial.toString()) + 6) % 10 return (NumberUtils.formatNumber(serial.toLong(), " ", 5, 4) + checkDigit + " " + NumberUtils.zeroPad(initDate.getMonth().oneBasedIndex, 2) + NumberUtils.zeroPad((initDate.getYear()) % 100, 2)) } val FACTORY: DesfireCardTransitFactory = object : DesfireCardTransitFactory { override val allCards: List<CardInfo> get() = listOf(CARD_INFO) override fun earlyCheck(appIds: IntArray) = APP_ID in appIds override fun parseTransitData(card: DesfireCard) = parse(card) override fun parseTransitIdentity(card: DesfireCard): TransitIdentity { try { return TransitIdentity(NAME, getSerial(card)) } catch (e: Exception) { return TransitIdentity( Localizer.localizeString(R.string.locked_leap), null) } } override fun createUnlocker(appIds: Int, manufData: ImmutableByteArray) = createUnlockerDispatch(appIds, manufData) override val notice: String? get() = StationTableReader.getNotice(LEAP_STR) } fun earlyCheck(appId: Int): Boolean { return appId == APP_ID } } }
gpl-3.0
f2dd113c111a02da78522580cb2623d0
41.098859
127
0.594924
4.598007
false
false
false
false
JetBrains/teamcity-nuget-support
nuget-feed/src/jetbrains/buildServer/nuget/feed/server/NuGetFeedUrlsProvider.kt
1
4292
package jetbrains.buildServer.nuget.feed.server import jetbrains.buildServer.nuget.feed.server.packages.NuGetRepository import jetbrains.buildServer.parameters.ReferencesResolverUtil import jetbrains.buildServer.serverSide.DataItem import jetbrains.buildServer.serverSide.ProjectDataFetcher import jetbrains.buildServer.serverSide.ProjectManager import jetbrains.buildServer.serverSide.SProject import jetbrains.buildServer.serverSide.auth.LoginConfiguration import jetbrains.buildServer.serverSide.packages.impl.RepositoryManager import jetbrains.buildServer.util.browser.Browser class NuGetFeedUrlsProvider(private val myProjectManager: ProjectManager, private val myRepositoryManager: RepositoryManager, private val myLoginConfiguration: LoginConfiguration) : ProjectDataFetcher { override fun getType() = "NuGetFeedUrls" override fun retrieveData(browser: Browser, queryString: String): MutableList<DataItem> { val feeds = mutableListOf<DataItem>() val parameters = getParameters(queryString) val apiVersions = getApiVersions(parameters) // Add global NuGet feeds feeds += apiVersions.mapNotNull { version -> when(version) { NuGetAPIVersion.V2 -> DataItem(NUGET_V2_URL, null) NuGetAPIVersion.V3 -> DataItem(NUGET_V3_URL, null) else -> null } } // Add TeamCity NuGet feeds val project = getProject(parameters) ?: return feeds val authTypes = getAuthTypes(parameters) feeds += myRepositoryManager.getRepositories(project, true) .filterIsInstance<NuGetRepository>() .flatMap { repository -> myProjectManager.findProjectById(repository.projectId)?.let { project -> apiVersions.flatMap { version -> authTypes.map { authType -> val feedReference = NuGetUtils.getProjectFeedReference( authType, project.externalId, repository.name, version ) DataItem(ReferencesResolverUtil.makeReference(feedReference), null) } } } ?: emptyList() } return feeds } private fun getApiVersions(parameters: Map<String, String>): Set<NuGetAPIVersion> { parameters["apiVersions"]?.let { apiVersions -> val versions = apiVersions.split(";").toSet() return NuGetAPIVersion.values().filter { versions.contains(it.name.toLowerCase()) }.toSet() } return NuGetAPIVersion.values().toSet() } private fun getAuthTypes(parameters: Map<String, String>): Set<String> { parameters["authTypes"]?.let { authTypes -> val types = authTypes.split(";").toMutableSet() if (types.contains(GUEST_AUTH) && !myLoginConfiguration.isGuestLoginAllowed) { types.remove(GUEST_AUTH) } return types } return setOf(HTTP_AUTH) } private fun getProject(parameters: Map<String, String>): SProject? { parameters["buildType"]?.let { buildType -> return myProjectManager.findBuildTypeByExternalId(buildType)?.project } parameters["template"]?.let { template -> return myProjectManager.findBuildTypeTemplateByExternalId(template)?.project } return null } private fun getParameters(queryString: String): Map<String, String> { val parameters = mutableMapOf<String, String>() queryString.split("&").forEach { pair -> val segments = pair.split("=") if (segments.size != 2 || segments.any { it.isEmpty() }) { return@forEach } parameters[segments[0]] = segments[1] } return parameters } companion object { const val GUEST_AUTH = "guestAuth" const val HTTP_AUTH = "httpAuth" const val NUGET_V2_URL = "https://www.nuget.org/api/v2" const val NUGET_V3_URL = "https://api.nuget.org/v3/index.json" } }
apache-2.0
a3acef3fa7bafe378dce17f876e192b6
40.269231
104
0.614865
5.097387
false
false
false
false
siarhei-luskanau/android-iot-doorbell
base_work_manager/src/main/kotlin/siarhei/luskanau/iot/doorbell/workmanager/DefaultWorkerFactory.kt
1
2225
package siarhei.luskanau.iot.doorbell.workmanager import android.content.Context import androidx.work.ListenableWorker import androidx.work.WorkerFactory import androidx.work.WorkerParameters import siarhei.luskanau.iot.doorbell.data.repository.CameraRepository import siarhei.luskanau.iot.doorbell.data.repository.DoorbellRepository import siarhei.luskanau.iot.doorbell.data.repository.ImageRepository import siarhei.luskanau.iot.doorbell.data.repository.ThisDeviceRepository import siarhei.luskanau.iot.doorbell.data.repository.UptimeRepository import timber.log.Timber class DefaultWorkerFactory( private val thisDeviceRepository: () -> ThisDeviceRepository, private val doorbellRepository: () -> DoorbellRepository, private val cameraRepository: () -> CameraRepository, private val uptimeRepository: () -> UptimeRepository, private val imageRepository: () -> ImageRepository ) : WorkerFactory() { override fun createWorker( appContext: Context, workerClassName: String, workerParameters: WorkerParameters ): ListenableWorker? = runCatching { Timber.e("DefaultWorkerFactory:createWorker:$workerClassName") when (workerClassName) { CameraWorker::class.java.name -> CameraWorker( context = appContext, workerParams = workerParameters, thisDeviceRepository = thisDeviceRepository.invoke(), doorbellRepository = doorbellRepository.invoke(), cameraRepository = cameraRepository.invoke(), imageRepository = imageRepository.invoke() ) UptimeWorker::class.java.name -> UptimeWorker( context = appContext, workerParams = workerParameters, uptimeRepository = uptimeRepository.invoke(), thisDeviceRepository = thisDeviceRepository.invoke(), doorbellRepository = doorbellRepository.invoke() ) else -> null } }.onFailure { Timber.e(it, "DefaultWorkerFactory:createWorker:$workerClassName") }.getOrNull() }
mit
8f78e0e9bcdd70895a4e4dc31ad99c28
41.788462
78
0.670112
5.618687
false
false
false
false
GunoH/intellij-community
platform/workspaceModel/storage/testEntities/gen/com/intellij/workspaceModel/storage/entities/test/api/CollectionFieldEntityImpl.kt
2
9317
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.workspaceModel.storage.entities.test.api import com.intellij.workspaceModel.storage.EntityInformation import com.intellij.workspaceModel.storage.EntitySource import com.intellij.workspaceModel.storage.EntityStorage import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion import com.intellij.workspaceModel.storage.MutableEntityStorage import com.intellij.workspaceModel.storage.WorkspaceEntity import com.intellij.workspaceModel.storage.impl.ConnectionId import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase import com.intellij.workspaceModel.storage.impl.UsedClassesCollector import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData import com.intellij.workspaceModel.storage.impl.containers.MutableWorkspaceList import com.intellij.workspaceModel.storage.impl.containers.MutableWorkspaceSet import com.intellij.workspaceModel.storage.impl.containers.toMutableWorkspaceList import com.intellij.workspaceModel.storage.impl.containers.toMutableWorkspaceSet import org.jetbrains.deft.ObjBuilder import org.jetbrains.deft.Type @GeneratedCodeApiVersion(1) @GeneratedCodeImplVersion(1) open class CollectionFieldEntityImpl(val dataSource: CollectionFieldEntityData) : CollectionFieldEntity, WorkspaceEntityBase() { companion object { val connections = listOf<ConnectionId>( ) } override val versions: Set<Int> get() = dataSource.versions override val names: List<String> get() = dataSource.names override val entitySource: EntitySource get() = dataSource.entitySource override fun connectionIdList(): List<ConnectionId> { return connections } class Builder(result: CollectionFieldEntityData?) : ModifiableWorkspaceEntityBase<CollectionFieldEntity, CollectionFieldEntityData>( result), CollectionFieldEntity.Builder { constructor() : this(CollectionFieldEntityData()) override fun applyToBuilder(builder: MutableEntityStorage) { if (this.diff != null) { if (existsInBuilder(builder)) { this.diff = builder return } else { error("Entity CollectionFieldEntity is already created in a different builder") } } this.diff = builder this.snapshot = builder addToBuilder() this.id = getEntityData().createEntityId() // After adding entity data to the builder, we need to unbind it and move the control over entity data to builder // Builder may switch to snapshot at any moment and lock entity data to modification this.currentEntityData = null // Process linked entities that are connected without a builder processLinkedEntities(builder) checkInitialization() // TODO uncomment and check failed tests } fun checkInitialization() { val _diff = diff if (!getEntityData().isEntitySourceInitialized()) { error("Field WorkspaceEntity#entitySource should be initialized") } if (!getEntityData().isVersionsInitialized()) { error("Field CollectionFieldEntity#versions should be initialized") } if (!getEntityData().isNamesInitialized()) { error("Field CollectionFieldEntity#names should be initialized") } } override fun connectionIdList(): List<ConnectionId> { return connections } override fun afterModification() { val collection_versions = getEntityData().versions if (collection_versions is MutableWorkspaceSet<*>) { collection_versions.cleanModificationUpdateAction() } val collection_names = getEntityData().names if (collection_names is MutableWorkspaceList<*>) { collection_names.cleanModificationUpdateAction() } } // Relabeling code, move information from dataSource to this builder override fun relabel(dataSource: WorkspaceEntity, parents: Set<WorkspaceEntity>?) { dataSource as CollectionFieldEntity if (this.entitySource != dataSource.entitySource) this.entitySource = dataSource.entitySource if (this.versions != dataSource.versions) this.versions = dataSource.versions.toMutableSet() if (this.names != dataSource.names) this.names = dataSource.names.toMutableList() if (parents != null) { } } override var entitySource: EntitySource get() = getEntityData().entitySource set(value) { checkModificationAllowed() getEntityData(true).entitySource = value changedProperty.add("entitySource") } private val versionsUpdater: (value: Set<Int>) -> Unit = { value -> changedProperty.add("versions") } override var versions: MutableSet<Int> get() { val collection_versions = getEntityData().versions if (collection_versions !is MutableWorkspaceSet) return collection_versions if (diff == null || modifiable.get()) { collection_versions.setModificationUpdateAction(versionsUpdater) } else { collection_versions.cleanModificationUpdateAction() } return collection_versions } set(value) { checkModificationAllowed() getEntityData(true).versions = value versionsUpdater.invoke(value) } private val namesUpdater: (value: List<String>) -> Unit = { value -> changedProperty.add("names") } override var names: MutableList<String> get() { val collection_names = getEntityData().names if (collection_names !is MutableWorkspaceList) return collection_names if (diff == null || modifiable.get()) { collection_names.setModificationUpdateAction(namesUpdater) } else { collection_names.cleanModificationUpdateAction() } return collection_names } set(value) { checkModificationAllowed() getEntityData(true).names = value namesUpdater.invoke(value) } override fun getEntityClass(): Class<CollectionFieldEntity> = CollectionFieldEntity::class.java } } class CollectionFieldEntityData : WorkspaceEntityData<CollectionFieldEntity>() { lateinit var versions: MutableSet<Int> lateinit var names: MutableList<String> fun isVersionsInitialized(): Boolean = ::versions.isInitialized fun isNamesInitialized(): Boolean = ::names.isInitialized override fun wrapAsModifiable(diff: MutableEntityStorage): WorkspaceEntity.Builder<CollectionFieldEntity> { val modifiable = CollectionFieldEntityImpl.Builder(null) modifiable.diff = diff modifiable.snapshot = diff modifiable.id = createEntityId() return modifiable } override fun createEntity(snapshot: EntityStorage): CollectionFieldEntity { return getCached(snapshot) { val entity = CollectionFieldEntityImpl(this) entity.snapshot = snapshot entity.id = createEntityId() entity } } override fun clone(): CollectionFieldEntityData { val clonedEntity = super.clone() clonedEntity as CollectionFieldEntityData clonedEntity.versions = clonedEntity.versions.toMutableWorkspaceSet() clonedEntity.names = clonedEntity.names.toMutableWorkspaceList() return clonedEntity } override fun getEntityInterface(): Class<out WorkspaceEntity> { return CollectionFieldEntity::class.java } override fun serialize(ser: EntityInformation.Serializer) { } override fun deserialize(de: EntityInformation.Deserializer) { } override fun createDetachedEntity(parents: List<WorkspaceEntity>): WorkspaceEntity { return CollectionFieldEntity(versions, names, entitySource) { } } override fun getRequiredParents(): List<Class<out WorkspaceEntity>> { val res = mutableListOf<Class<out WorkspaceEntity>>() return res } override fun equals(other: Any?): Boolean { if (other == null) return false if (this.javaClass != other.javaClass) return false other as CollectionFieldEntityData if (this.entitySource != other.entitySource) return false if (this.versions != other.versions) return false if (this.names != other.names) return false return true } override fun equalsIgnoringEntitySource(other: Any?): Boolean { if (other == null) return false if (this.javaClass != other.javaClass) return false other as CollectionFieldEntityData if (this.versions != other.versions) return false if (this.names != other.names) return false return true } override fun hashCode(): Int { var result = entitySource.hashCode() result = 31 * result + versions.hashCode() result = 31 * result + names.hashCode() return result } override fun hashCodeIgnoringEntitySource(): Int { var result = javaClass.hashCode() result = 31 * result + versions.hashCode() result = 31 * result + names.hashCode() return result } override fun collectClassUsagesData(collector: UsedClassesCollector) { this.versions?.let { collector.add(it::class.java) } this.names?.let { collector.add(it::class.java) } collector.sameForAllEntities = false } }
apache-2.0
e5645e72fdd21f9d14ca29a19919ecf6
34.026316
134
0.723087
5.351522
false
false
false
false
NiciDieNase/chaosflix
touch/src/main/java/de/nicidienase/chaosflix/touch/browse/adapters/EventRecyclerViewAdapter.kt
1
2045
package de.nicidienase.chaosflix.touch.browse.adapters import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.core.view.ViewCompat import androidx.recyclerview.widget.RecyclerView import de.nicidienase.chaosflix.common.mediadata.entities.recording.persistence.Event import de.nicidienase.chaosflix.touch.databinding.ItemEventCardviewBinding open class EventRecyclerViewAdapter(val listener: (Event) -> Unit) : ItemRecyclerViewAdapter<Event, EventRecyclerViewAdapter.ViewHolder>() { var showConferenceName: Boolean = false override fun getComparator(): Comparator<in Event>? { return Comparator { o1, o2 -> o1.title.compareTo(o2.title) } } override fun getItemId(position: Int): Long { return items[position].id } override fun getFilteredProperties(item: Event): List<String> { return listOfNotNull(item.title, item.subtitle, item.description, item.getSpeakerString() ) } override fun onCreateViewHolder(p0: ViewGroup, pItemConferenceCardviewBinding1: Int): ViewHolder { val binding = ItemEventCardviewBinding.inflate(LayoutInflater.from(p0.context), p0, false) return ViewHolder(binding) } override fun onBindViewHolder(holder: ViewHolder, position: Int) { val event = items[position] holder.binding.event = event holder.binding.root.setOnClickListener { listener(event) } if (showConferenceName) { holder.binding.conferenceNameText.visibility = View.VISIBLE } ViewCompat.setTransitionName(holder.binding.titleText, "title_${event.guid}") ViewCompat.setTransitionName(holder.binding.subtitleText, "subtitle_${event.guid}") ViewCompat.setTransitionName(holder.binding.imageView, "thumb_${event.guid}") } inner class ViewHolder(val binding: ItemEventCardviewBinding) : androidx.recyclerview.widget.RecyclerView.ViewHolder(binding.root) }
mit
557c7708a72e7ac9213e72ad3d53047c
37.584906
134
0.717848
4.711982
false
false
false
false
AsamK/TextSecure
app/src/main/java/org/thoughtcrime/securesms/registration/RegistrationData.kt
1
369
package org.thoughtcrime.securesms.registration import org.signal.libsignal.zkgroup.profiles.ProfileKey data class RegistrationData( val code: String, val e164: String, val password: String, val registrationId: Int, val profileKey: ProfileKey, val fcmToken: String? ) { val isFcm: Boolean = fcmToken != null val isNotFcm: Boolean = fcmToken == null }
gpl-3.0
fbbf620da62919bb0f17c2c71ee3750d
23.6
55
0.750678
3.804124
false
false
false
false
ktorio/ktor
ktor-utils/posix/src/io/ktor/util/PlatformUtilsNative.kt
1
577
// ktlint-disable filename /* * Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.util public actual object PlatformUtils { public actual val IS_BROWSER: Boolean = false public actual val IS_NODE: Boolean = false public actual val IS_JVM: Boolean = false public actual val IS_NATIVE: Boolean = true public actual val IS_DEVELOPMENT_MODE: Boolean = false @OptIn(ExperimentalStdlibApi::class) public actual val IS_NEW_MM_ENABLED: Boolean = isExperimentalMM() }
apache-2.0
be2bb33ff8b36c6a6e9d79970a3d46b9
31.055556
118
0.734835
4.121429
false
false
false
false
inorichi/mangafeed
app/src/main/java/eu/kanade/tachiyomi/ui/more/MoreController.kt
2
7158
package eu.kanade.tachiyomi.ui.more import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.preference.Preference import androidx.preference.PreferenceScreen import eu.kanade.tachiyomi.R import eu.kanade.tachiyomi.data.download.DownloadManager import eu.kanade.tachiyomi.data.download.DownloadService import eu.kanade.tachiyomi.ui.base.controller.NoAppBarElevationController import eu.kanade.tachiyomi.ui.base.controller.RootController import eu.kanade.tachiyomi.ui.base.controller.withFadeTransaction import eu.kanade.tachiyomi.ui.category.CategoryController import eu.kanade.tachiyomi.ui.download.DownloadController import eu.kanade.tachiyomi.ui.setting.SettingsBackupController import eu.kanade.tachiyomi.ui.setting.SettingsController import eu.kanade.tachiyomi.ui.setting.SettingsMainController import eu.kanade.tachiyomi.util.preference.add import eu.kanade.tachiyomi.util.preference.bindTo import eu.kanade.tachiyomi.util.preference.iconRes import eu.kanade.tachiyomi.util.preference.iconTint import eu.kanade.tachiyomi.util.preference.onClick import eu.kanade.tachiyomi.util.preference.preference import eu.kanade.tachiyomi.util.preference.preferenceCategory import eu.kanade.tachiyomi.util.preference.summaryRes import eu.kanade.tachiyomi.util.preference.switchPreference import eu.kanade.tachiyomi.util.preference.titleRes import eu.kanade.tachiyomi.util.system.getResourceColor import eu.kanade.tachiyomi.util.system.openInBrowser import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.flow.onEach import rx.Observable import rx.Subscription import rx.android.schedulers.AndroidSchedulers import rx.subscriptions.CompositeSubscription import uy.kohesive.injekt.injectLazy class MoreController : SettingsController(), RootController, NoAppBarElevationController { private val downloadManager: DownloadManager by injectLazy() private var isDownloading: Boolean = false private var downloadQueueSize: Int = 0 private var untilDestroySubscriptions = CompositeSubscription() private set override fun setupPreferenceScreen(screen: PreferenceScreen) = screen.apply { titleRes = R.string.label_more val tintColor = context.getResourceColor(R.attr.colorAccent) add(MoreHeaderPreference(context)) switchPreference { bindTo(preferences.downloadedOnly()) titleRes = R.string.label_downloaded_only summaryRes = R.string.downloaded_only_summary iconRes = R.drawable.ic_cloud_off_24dp iconTint = tintColor } switchPreference { bindTo(preferences.incognitoMode()) summaryRes = R.string.pref_incognito_mode_summary titleRes = R.string.pref_incognito_mode iconRes = R.drawable.ic_glasses_24dp iconTint = tintColor preferences.incognitoMode().asFlow() .onEach { isChecked = it } .launchIn(viewScope) } preferenceCategory { preference { titleRes = R.string.label_download_queue if (downloadManager.queue.isNotEmpty()) { initDownloadQueueSummary(this) } iconRes = R.drawable.ic_get_app_24dp iconTint = tintColor onClick { router.pushController(DownloadController().withFadeTransaction()) } } preference { titleRes = R.string.categories iconRes = R.drawable.ic_label_24dp iconTint = tintColor onClick { router.pushController(CategoryController().withFadeTransaction()) } } preference { titleRes = R.string.label_backup iconRes = R.drawable.ic_settings_backup_restore_24dp iconTint = tintColor onClick { router.pushController(SettingsBackupController().withFadeTransaction()) } } } preferenceCategory { preference { titleRes = R.string.label_settings iconRes = R.drawable.ic_settings_24dp iconTint = tintColor onClick { router.pushController(SettingsMainController().withFadeTransaction()) } } preference { iconRes = R.drawable.ic_info_24dp iconTint = tintColor titleRes = R.string.pref_category_about onClick { router.pushController(AboutController().withFadeTransaction()) } } preference { titleRes = R.string.label_help iconRes = R.drawable.ic_help_24dp iconTint = tintColor onClick { activity?.openInBrowser(URL_HELP) } } } } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup, savedInstanceState: Bundle?): View { if (untilDestroySubscriptions.isUnsubscribed) { untilDestroySubscriptions = CompositeSubscription() } return super.onCreateView(inflater, container, savedInstanceState) } override fun onDestroyView(view: View) { super.onDestroyView(view) untilDestroySubscriptions.unsubscribe() } private fun initDownloadQueueSummary(preference: Preference) { // Handle running/paused status change DownloadService.runningRelay .observeOn(AndroidSchedulers.mainThread()) .subscribeUntilDestroy { isRunning -> isDownloading = isRunning updateDownloadQueueSummary(preference) } // Handle queue progress updating downloadManager.queue.getUpdatedObservable() .observeOn(AndroidSchedulers.mainThread()) .subscribeUntilDestroy { downloadQueueSize = it.size updateDownloadQueueSummary(preference) } } private fun updateDownloadQueueSummary(preference: Preference) { var pendingDownloadExists = downloadQueueSize != 0 var pauseMessage = resources?.getString(R.string.paused) var numberOfPendingDownloads = resources?.getQuantityString(R.plurals.download_queue_summary, downloadQueueSize, downloadQueueSize) preference.summary = when { !pendingDownloadExists -> null !isDownloading && !pendingDownloadExists -> pauseMessage !isDownloading && pendingDownloadExists -> "$pauseMessage • $numberOfPendingDownloads" else -> numberOfPendingDownloads } } private fun <T> Observable<T>.subscribeUntilDestroy(onNext: (T) -> Unit): Subscription { return subscribe(onNext).also { untilDestroySubscriptions.add(it) } } companion object { const val URL_HELP = "https://tachiyomi.org/help/" } }
apache-2.0
5f3ca32f9f03527c94f571e619ccfc94
36.663158
139
0.65777
5.219548
false
false
false
false
DemonWav/MinecraftDev
src/main/kotlin/com/demonwav/mcdev/platform/mixin/inspection/implements/DuplicateInterfacePrefixInspection.kt
1
1489
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2018 minecraft-dev * * MIT License */ package com.demonwav.mcdev.platform.mixin.inspection.implements import com.demonwav.mcdev.platform.mixin.inspection.MixinAnnotationAttributeInspection import com.demonwav.mcdev.platform.mixin.util.MixinConstants.Annotations.IMPLEMENTS import com.demonwav.mcdev.util.constantStringValue import com.demonwav.mcdev.util.findAnnotations import com.demonwav.mcdev.util.ifEmpty import com.intellij.codeInspection.ProblemsHolder import com.intellij.psi.PsiAnnotation import com.intellij.psi.PsiAnnotationMemberValue class DuplicateInterfacePrefixInspection : MixinAnnotationAttributeInspection(IMPLEMENTS, null) { override fun getStaticDescription() = "Reports duplicate @Interface prefixes in an @Implements annotation." override fun visitAnnotationAttribute(annotation: PsiAnnotation, value: PsiAnnotationMemberValue, holder: ProblemsHolder) { val interfaces = value.findAnnotations().ifEmpty { return } val prefixes = ArrayList<String>() for (iface in interfaces) { val prefixValue = iface.findDeclaredAttributeValue("prefix") ?: continue val prefix = prefixValue.constantStringValue ?: continue if (prefix in prefixes) { holder.registerProblem(prefixValue, "Duplicate prefix '$prefix'") } else { prefixes.add(prefix) } } } }
mit
beee6a4c8efcd158fc6b7e73486b2c0a
36.225
127
0.739422
4.996644
false
false
false
false
jovr/imgui
openjfx/src/test/kotlin/imgui/jfx/test javafx.kt
2
5865
package imgui.jfx import glm_.f import glm_.i import glm_.vec4.Vec4 import imgui.* import imgui.classes.Context import imgui.impl.ImplJFX import imgui.impl.toJFXColor import javafx.application.Platform import javafx.scene.Scene import javafx.scene.SnapshotParameters import javafx.scene.canvas.Canvas import javafx.scene.image.WritableImage import javafx.scene.layout.Pane import javafx.stage.Stage import java.util.concurrent.atomic.AtomicBoolean fun main() { HelloWorld_jfx() } class HelloWorld_jfx { lateinit var stage: Stage lateinit var scene: Scene lateinit var canvas: Canvas private var ctx: Context var vsync = true var f = 0f val clearColor = Vec4(0.45f, 0.55f, 0.6f, 1f) var showAnotherWindow = false var showDemo = true var counter = 0 val startTime = System.nanoTime() var time = 0.0 init { val ready = AtomicBoolean(false) Platform.startup { canvas = Canvas(1280.0, 720.0) val vb = Pane(canvas) scene = Scene(vb) stage = Stage() stage.scene = scene stage.title = "OpenJFX Example" stage.show() ready.set(true) } Platform.requestNextPulse() ctx = Context() ImGui.styleColorsDark() while (!ready.get()) Thread.sleep(1) var internalCanvas = Canvas(canvas.width, canvas.height) val s = ImplJFX(stage, internalCanvas) while (stage.isShowing) { if (canvas.width != scene.width || canvas.height != scene.height) { canvas = Canvas(scene.width, scene.height) internalCanvas = Canvas(scene.width, scene.height) s.updateCanvas(internalCanvas) if (!Platform.isFxApplicationThread()) { Platform.runLater { val vb = Pane(canvas) scene = Scene(vb) stage.scene = scene } } else { val vb = Pane(canvas) scene = Scene(vb) stage.scene = scene } } internalCanvas.graphicsContext2D.clearRect(0.0, 0.0, internalCanvas.width, internalCanvas.height) vsyncCap() s.newFrame() ImGui.run { newFrame() // 1. Show the big demo window (Most of the sample code is in ImGui::ShowDemoWindow()! You can browse its code to learn more about Dear ImGui!). if (showDemo) showDemoWindow(::showDemo) // 2. Show a simple window that we create ourselves. We use a Begin/End pair to created a named window. run { begin("Hello, world!") // Create a window called "Hello, world!" and append into it. text("This is some useful text.") // Display some text (you can use a format strings too) checkbox("Demo Window", ::showDemo) // Edit bools storing our window open/close state checkbox("Another Window", ::showAnotherWindow) sliderFloat("float", ::f, 0f, 1f) // Edit 1 float using a slider from 0.0f to 1.0f colorEdit3("clear color", clearColor) // Edit 3 floats representing a color if (button("Button")) // Buttons return true when clicked (most widgets return true when edited/activated) counter++ /* Or you can take advantage of functional programming and pass directly a lambda as last parameter: button("Button") { counter++ } */ sameLine() text("counter = $counter") text("Application average %.3f ms/frame (%.1f FPS)", 1_000f / io.framerate, io.framerate) end() // 3. Show another simple window. if (showAnotherWindow) { // Pass a pointer to our bool variable (the window will have a closing button that will clear the bool when clicked) begin("Another Window", ::showAnotherWindow) text("Hello from another window!") if (button("Close Me")) showAnotherWindow = false end() } } } // Rendering ImGui.render() s.renderDrawData(ImGui.drawData!!) //copy to screen fun doCopy() { val wi = WritableImage(canvas.width.i, canvas.height.i) val r = SnapshotParameters() r.fill = clearColor.toJFXColor() internalCanvas.snapshot(r, wi) canvas.graphicsContext2D.drawImage(wi, 0.0, 0.0) } if (!Platform.isFxApplicationThread()) { val ss = AtomicBoolean(false) Platform.runLater { doCopy() ss.set(true) } while (!ss.get()) { } } else { doCopy() } } } private fun vsyncCap() { time = (System.nanoTime() - startTime).toDouble() / 1e9 if (!vsync) return var currentTime = time var deltaTime = if (time > 0) (currentTime - time).f else 1f / 60f while (deltaTime < 1.0 / 60.0) { currentTime = (System.nanoTime() - startTime).toDouble() / 1e9 deltaTime = if (time > 0) (currentTime - time).f else 1f / 60f } time = currentTime } }
mit
b6f53fc9663506d53cea786477574ab0
33.304094
160
0.515942
4.811321
false
false
false
false
JetBrains/spek
spek-ide-plugin-android-studio/src/main/kotlin/org/spekframework/intellij/SpekAndroidSettingsEditor.kt
1
3135
package org.spekframework.intellij import com.intellij.application.options.ModulesComboBox import com.intellij.execution.ui.CommonJavaParametersPanel import com.intellij.execution.ui.ConfigurationModuleSelector import com.intellij.execution.ui.DefaultJreSelector import com.intellij.execution.ui.JrePathEditor import com.intellij.openapi.module.Module import com.intellij.openapi.options.SettingsEditor import com.intellij.openapi.project.Project import com.intellij.openapi.ui.LabeledComponent import com.intellij.ui.TextFieldWithHistory import org.spekframework.spek2.runtime.scope.PathBuilder import javax.swing.JPanel import kotlin.properties.Delegates /** * @author Ranie Jade Ramiso */ class SpekAndroidSettingsEditor(project: Project): SettingsEditor<SpekAndroidRunConfiguration>() { private lateinit var panel: JPanel private lateinit var mainPanel: JPanel private lateinit var commonJavaParameters: CommonJavaParametersPanel private lateinit var module: LabeledComponent<ModulesComboBox> private lateinit var jrePathEditor: JrePathEditor private lateinit var path: LabeledComponent<TextFieldWithHistory> var moduleSelector: ConfigurationModuleSelector private var selectedModule: Module? get() { return module.component.selectedModule } set(value) { module.component.selectedModule = value } private var selectedPath by Delegates.observable(PathBuilder.ROOT) { _, _, value -> path.component.setTextAndAddToHistory(value.toString()) } init { module.component.fillModules(project) moduleSelector = ConfigurationModuleSelector(project, module.component) jrePathEditor.setDefaultJreSelector(DefaultJreSelector.fromModuleDependencies(module.component, false)) commonJavaParameters.setModuleContext(selectedModule) commonJavaParameters.setHasModuleMacro() module.component.addActionListener { commonJavaParameters.setModuleContext(selectedModule) } } override fun resetEditorFrom(configuration: SpekAndroidRunConfiguration) { selectedModule = configuration.configurationModule.module moduleSelector.reset(configuration) commonJavaParameters.reset(configuration) selectedPath = configuration.data.path jrePathEditor.setPathOrName(configuration.alternativeJrePath, configuration.isAlternativeJrePathEnabled) } override fun applyEditorTo(configuration: SpekAndroidRunConfiguration) { configuration.alternativeJrePath = jrePathEditor.jrePathOrName configuration.isAlternativeJrePathEnabled = jrePathEditor.isAlternativeJreSelected configuration.setModule(selectedModule) moduleSelector.applyTo(configuration) commonJavaParameters.applyTo(configuration) configuration.data.path = selectedPath } override fun createEditor() = panel private fun createUIComponents() { path = LabeledComponent.create( TextFieldWithHistory(), "Scope", "West" ) path.component.isEditable = false } }
bsd-3-clause
4f64d40db26a9a910b39c9a451c5d94b
37.231707
112
0.763317
5.358974
false
true
false
false
dhis2/dhis2-android-sdk
core/src/main/java/org/hisp/dhis/android/core/visualization/VisualizationTableInfo.kt
1
6072
/* * Copyright (c) 2004-2022, University of Oslo * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of the HISP project nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.hisp.dhis.android.core.visualization import org.hisp.dhis.android.core.arch.db.tableinfos.TableInfo import org.hisp.dhis.android.core.arch.helpers.CollectionsHelper import org.hisp.dhis.android.core.common.CoreColumns import org.hisp.dhis.android.core.common.IdentifiableColumns object VisualizationTableInfo { @JvmField val TABLE_INFO: TableInfo = object : TableInfo() { override fun name(): String { return "Visualization" } override fun columns(): CoreColumns { return Columns() } } class Columns : IdentifiableColumns() { override fun all(): Array<String> { return CollectionsHelper.appendInNewArray( super.all(), DESCRIPTION, DISPLAY_DESCRIPTION, DISPLAY_FORM_NAME, TITLE, DISPLAY_TITLE, SUBTITLE, DISPLAY_SUBTITLE, TYPE, HIDE_TITLE, HIDE_SUBTITLE, HIDE_EMPTY_COLUMNS, HIDE_EMPTY_ROWS, HIDE_EMPTY_ROW_ITEMS, HIDE_LEGEND, SHOW_HIERARCHY, ROW_TOTALS, ROW_SUB_TOTALS, COL_TOTALS, COL_SUB_TOTALS, SHOW_DIMENSION_LABELS, PERCENT_STACKED_VALUES, NO_SPACE_BETWEEN_COLUMNS, SKIP_ROUNDING, DISPLAY_DENSITY, DIGIT_GROUP_SEPARATOR, RELATIVE_PERIODS, FILTER_DIMENSIONS, ROW_DIMENSIONS, COLUMN_DIMENSIONS, ORGANISATION_UNIT_LEVELS, USER_ORGANISATION_UNIT, USER_ORGANISATION_UNIT_CHILDREN, USER_ORGANISATION_UNIT_GRAND_CHILDREN, ORGANISATION_UNITS, PERIODS, LEGEND_SHOW_KEY, LEGEND_STYLE, LEGEND_SET_ID, LEGEND_STRATEGY, AGGREGATION_TYPE ) } companion object { const val DESCRIPTION = "description" const val DISPLAY_DESCRIPTION = "displayDescription" const val DISPLAY_FORM_NAME = "displayFormName" const val TITLE = "title" const val DISPLAY_TITLE = "displayTitle" const val SUBTITLE = "subtitle" const val DISPLAY_SUBTITLE = "displaySubtitle" const val TYPE = "type" const val HIDE_TITLE = "hideTitle" const val HIDE_SUBTITLE = "hideSubtitle" const val HIDE_EMPTY_COLUMNS = "hideEmptyColumns" const val HIDE_EMPTY_ROWS = "hideEmptyRows" const val HIDE_EMPTY_ROW_ITEMS = "hideEmptyRowItems" const val HIDE_LEGEND = "hideLegend" const val SHOW_HIERARCHY = "showHierarchy" const val ROW_TOTALS = "rowTotals" const val ROW_SUB_TOTALS = "rowSubTotals" const val COL_TOTALS = "colTotals" const val COL_SUB_TOTALS = "colSubTotals" const val SHOW_DIMENSION_LABELS = "showDimensionLabels" const val PERCENT_STACKED_VALUES = "percentStackedValues" const val NO_SPACE_BETWEEN_COLUMNS = "noSpaceBetweenColumns" const val SKIP_ROUNDING = "skipRounding" const val DISPLAY_DENSITY = "displayDensity" const val DIGIT_GROUP_SEPARATOR = "digitGroupSeparator" const val RELATIVE_PERIODS = "relativePeriods" const val FILTER_DIMENSIONS = "filterDimensions" const val ROW_DIMENSIONS = "rowDimensions" const val COLUMN_DIMENSIONS = "columnDimensions" const val ORGANISATION_UNIT_LEVELS = "organisationUnitLevels" const val USER_ORGANISATION_UNIT = "userOrganisationUnit" const val USER_ORGANISATION_UNIT_CHILDREN = "userOrganisationUnitChildren" const val USER_ORGANISATION_UNIT_GRAND_CHILDREN = "userOrganisationUnitGrandChildren" const val ORGANISATION_UNITS = "organisationUnits" const val PERIODS = "periods" const val LEGEND_SHOW_KEY = "legendShowKey" const val LEGEND_STYLE = "legendStyle" const val LEGEND_SET_ID = "legendSetId" const val LEGEND_STRATEGY = "legendStrategy" const val AGGREGATION_TYPE = "aggregationType" } } }
bsd-3-clause
3db8e1a0a91878183ea5493f1b11e827
42.683453
97
0.622859
4.717949
false
false
false
false
mcdimus/mate-wp
src/main/kotlin/ee/mcdimus/matewp/service/ImageService.kt
1
1968
package ee.mcdimus.matewp.service import java.awt.Color import java.awt.Font import java.awt.image.BufferedImage import java.io.IOException import java.net.URL import javax.imageio.ImageIO /** * @author Dmitri Maksimov */ class ImageService { fun download(url: String) = this.download(URL(url)) fun download(url: URL): BufferedImage? { println("Downloading image: $url") return try { val contentLength = getImageSize(url) println("\t [-] size: $contentLength bytes") ImageIO.read(url) } catch (e: IOException) { System.err.println("\t [-] download failed: ${e.message}") null } } private fun getImageSize(url: URL) = url.openConnection().contentLengthLong @Suppress("MagicNumber") fun addText(image: BufferedImage, text: String): BufferedImage { val shapeX = 10 val shapeY = 40 val imageGraphics = image.graphics val mainTokens = text.substringBeforeLast('(').split(',').map(String::trim) // val copyrightToken = text.substringAfterLast('(').trimEnd { it == ')' } // val textTokens = mainTokens + copyrightToken val textTokens = mainTokens val font = Font(Font.SANS_SERIF, Font.BOLD, 24) val fontMetrics = imageGraphics.getFontMetrics(font) val lineHeight = fontMetrics.height val longestTextToken = textTokens.maxByOrNull { it.length }!! val shapeWidth = fontMetrics.getStringBounds(longestTextToken, imageGraphics).width + (2 * lineHeight) val shapeHeight = (textTokens.size + 2) * lineHeight imageGraphics.color = Color(255, 255, 255, 128) imageGraphics.fillRoundRect(shapeX, shapeY, shapeWidth.toInt(), shapeHeight, 15, 15) imageGraphics.font = font imageGraphics.color = Color(0, 0, 0, 128) val startX = shapeX + lineHeight var startY = shapeY + (fontMetrics.ascent) + lineHeight textTokens.forEach { imageGraphics.drawString(it, startX, startY) startY += lineHeight } return image } }
mit
7ec3f2ea8f27f12ae33e33f48cf60982
27.521739
106
0.691057
4.016327
false
false
false
false
cdietze/klay
tripleklay/src/main/kotlin/tripleklay/ui/util/Scale9.kt
1
5906
package tripleklay.ui.util /** * Facilitates the rendering of "scale-9" images, that is, images that are designed as a 3x3 grid * such that each of the 9 pieces is fixed or stretched in one or both directions to fit a * designated area. The corners are drawn without scaling, the top and bottom center pieces are * scaled horizontally, the left and right center pieces are scaled vertically, and the center * piece is scaled both horizontally and vertically. * * By default, the cells are assumed to be of equal size (hence scale-9 image dimensions are * normally a multiple of 3). By using [.xaxis] and [.yaxis], this partitioning can be * controlled directly. * * Here's a diagram showing the stretching and axes, H = horizontally stretched, V = vertically * stretched, U = unstretched. * <pre>`xaxis * 0 1 2 * --------------------------------- * | | | | * 0 | U | H | U | * | | | | * --------------------------------- * | | | | * yaxis 1 | V | H&V | V | * | | | | * --------------------------------- * | | | | * 2 | U | H | U | * | | | | * --------------------------------- `</pre> * * * *Example 1*: the horizontal middle of an image is a single pixel. This code will do * that and automatically grow the left and right columns:<pre> * Scale9 s9 = ...; * s9.xaxis.resize(1, 1);</pre> * * *Example 2*: there are no top and bottom rows. This code will stretch all of the image * vertically, but keep the left and right third of the image fixed horizontally:<pre> * Scale9 s9 = ...; * s9.yaxis.resize(0, 0).resize(2, 0);</pre> */ class Scale9 { /** A horizontal or vertical axis, broken up into 3 chunks. */ class Axis { /** Creates a new axis equally splitting the given length. */ constructor(length: Float) { val d = length / 3 _lengths = floatArrayOf(d, length - 2 * d, d) _offsets = floatArrayOf(0f, _lengths[0], _lengths[0] + _lengths[1]) } /** Creates a new axis with the given total length and 0th and 2nd lengths copied from a * source axis. */ constructor(length: Float, src: Axis) { _lengths = floatArrayOf(src.size(0), length - (src.size(0) + src.size(2)), src.size(2)) _offsets = floatArrayOf(0f, src.size(0), length - src.size(2)) } /** Returns the coordinate of the given chunk, 0 - 2. */ fun coord(idx: Int): Float { return _offsets[idx] } /** Returns the size of the given chunk, 0 - 2. */ fun size(idx: Int): Float { return _lengths[idx] } /** Sets the size and location of the given chunk, 0 - 2. */ fun set(idx: Int, coord: Float, size: Float): Axis { _offsets[idx] = coord _lengths[idx] = size return this } /** Sets the size of the given chunk, shifting neighbors. */ fun resize(idx: Int, size: Float): Axis { val excess = _lengths[idx] - size _lengths[idx] = size when (idx) { 0 -> { _offsets[1] -= excess _lengths[1] += excess } 1 -> { val half = excess * .5f _lengths[0] += half _lengths[2] += half _offsets[1] += half _offsets[2] -= half } 2 -> { _offsets[2] += excess _lengths[1] += excess } } return this } /** The positions of the 3 chunks. */ private val _offsets: FloatArray /** The lengths of the 3 chunks. */ private val _lengths: FloatArray } /** The axes of the 3x3 grid. */ val xaxis: Axis val yaxis: Axis /** Creates a new scale to match the given width and height. Each horizontal and vertical * sequence is divided equally between the given values. */ constructor(width: Float, height: Float) { xaxis = Axis(width) yaxis = Axis(height) } /** Creates a new scale to render the given scale onto a target of the given width and * height. */ constructor(width: Float, height: Float, source: Scale9) { xaxis = Axis(width, source.xaxis) clamp(xaxis, width) yaxis = Axis(height, source.yaxis) clamp(yaxis, height) } companion object { /** * Ensures that the `Axis` passed in does not exceed the length given. An equal chunk * will be removed from the outer chunks if it is too long. The given axis is modified and * returned. */ fun clamp(axis: Axis, length: Float): Axis { val left = axis.size(0) val middle = axis.size(1) val right = axis.size(2) if (left + middle + right > length && middle > 0 && left + right < length) { // the special case where for some reason the total is too wide, but the middle is non // zero, and it can absorb the extra all on its own. axis.set(1, left, length - left - right) axis.set(2, length - right, right) } else if (left + right > length) { // eat equal chunks out of each end so that we don't end up overlapping val remove = (left + right - length) / 2 axis.set(0, 0f, left - remove) axis.set(1, left - remove, 0f) axis.set(2, left - remove, right - remove) } return axis } } }
apache-2.0
16585038ed7af8a343a8eff63bf3d7ba
35.9125
102
0.507281
4.109951
false
false
false
false