repo_name
stringlengths
7
81
path
stringlengths
6
242
copies
stringclasses
53 values
size
stringlengths
2
6
content
stringlengths
73
737k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
5.44
99.8
line_max
int64
15
977
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.93
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
Adventech/sabbath-school-android-2
common/lessons-data/src/main/java/app/ss/lessons/data/repository/lessons/LessonsRepositoryImpl.kt
1
9889
/* * Copyright (c) 2021. Adventech <[email protected]> * * 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 app.ss.lessons.data.repository.lessons import app.ss.lessons.data.model.QuarterlyLessonInfo import app.ss.lessons.data.repository.quarterly.QuarterliesDataSource import app.ss.lessons.data.repository.quarterly.QuarterlyInfoDataSource import app.ss.models.PdfAnnotations import app.ss.models.PreferredBibleVersion import app.ss.models.SSDay import app.ss.models.SSLessonInfo import app.ss.models.SSQuarterlyInfo import app.ss.models.SSRead import app.ss.models.SSReadComments import app.ss.models.SSReadHighlights import app.ss.models.TodayData import app.ss.models.WeekData import app.ss.models.WeekDay import com.cryart.sabbathschool.core.extensions.coroutines.DispatcherProvider import com.cryart.sabbathschool.core.extensions.prefs.SSPrefs import com.cryart.sabbathschool.core.misc.DateHelper.formatDate import com.cryart.sabbathschool.core.misc.DateHelper.parseDate import com.cryart.sabbathschool.core.misc.SSConstants import com.cryart.sabbathschool.core.response.Resource import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.withContext import org.joda.time.DateTime import javax.inject.Inject import javax.inject.Singleton @Singleton internal class LessonsRepositoryImpl @Inject constructor( private val ssPrefs: SSPrefs, private val quarterliesDataSource: QuarterliesDataSource, private val quarterlyInfoDataSource: QuarterlyInfoDataSource, private val lessonInfoDataSource: LessonInfoDataSource, private val readsDataSource: ReadsDataSource, private val pdfAnnotationsDataSource: PdfAnnotationsDataSource, private val readCommentsDataSource: ReadCommentsDataSource, private val readHighlightsDataSource: ReadHighlightsDataSource, private val bibleVersionDataSource: BibleVersionDataSource, private val dispatcherProvider: DispatcherProvider, private val readerArtifactHelper: ReaderArtifactHelper ) : LessonsRepository { override suspend fun getLessonInfo(lessonIndex: String, cached: Boolean): Resource<SSLessonInfo> { return if (cached) { withContext(dispatcherProvider.io) { lessonInfoDataSource.cache.getItem(LessonInfoDataSource.Request(lessonIndex)) } } else { lessonInfoDataSource.getItem(LessonInfoDataSource.Request(lessonIndex)) } } override suspend fun getTodayRead(cached: Boolean): Resource<TodayData> { val dataResponse = getQuarterlyAndLessonInfo(cached) val lessonInfo = dataResponse.data?.lessonInfo ?: return Resource.error(dataResponse.error ?: Throwable("Invalid QuarterlyInfo")) val today = DateTime.now().withTimeAtStartOfDay() val todayModel = lessonInfo.days.find { day -> today.isEqual(parseDate(day.date)) }?.let { day -> TodayData( day.index, lessonInfo.lesson.index, day.title, formatDate(day.date), lessonInfo.lesson.cover ) } ?: return Resource.error(Throwable("Error Finding Today Read")) return Resource.success(todayModel) } private suspend fun getQuarterlyAndLessonInfo(cached: Boolean): Resource<QuarterlyLessonInfo> { val quarterlyResponse = getQuarterlyInfo() val quarterlyInfo = quarterlyResponse.data ?: return Resource.error(quarterlyResponse.error ?: Throwable("Invalid QuarterlyInfo")) val lessonInfo = getWeekLessonInfo(quarterlyInfo, cached) ?: return Resource.error(Throwable("Invalid LessonInfo")) return Resource.success(QuarterlyLessonInfo(quarterlyInfo, lessonInfo)) } private suspend fun getQuarterlyInfo(): Resource<SSQuarterlyInfo> { val index = getLastQuarterlyInfoIfCurrent()?.let { return Resource.success(it) } ?: getDefaultQuarterlyIndex() ?: return Resource.error(Throwable("Invalid Quarterly Index")) return withContext(dispatcherProvider.io) { quarterlyInfoDataSource.cache.getItem(QuarterlyInfoDataSource.Request(index)) } } private suspend fun getLastQuarterlyInfoIfCurrent(): SSQuarterlyInfo? { val index = ssPrefs.getLastQuarterlyIndex() ?: return null val info = withContext(dispatcherProvider.io) { quarterlyInfoDataSource.cache.getItem(QuarterlyInfoDataSource.Request(index)).data } ?: return null val today = DateTime.now().withTimeAtStartOfDay() return if (today.isBefore(parseDate(info.quarterly.end_date))) { info } else { null } } private suspend fun getDefaultQuarterlyIndex(): String? { val resource = withContext(dispatcherProvider.io) { quarterliesDataSource.cache.get(QuarterliesDataSource.Request(ssPrefs.getLanguageCode())) } val quarterly = resource.data?.firstOrNull() return quarterly?.index } private suspend fun getWeekLessonInfo(quarterlyInfo: SSQuarterlyInfo, cached: Boolean): SSLessonInfo? { val lesson = quarterlyInfo.lessons.find { lesson -> val startDate = parseDate(lesson.start_date) val endDate = parseDate(lesson.end_date) val today = DateTime.now().withTimeAtStartOfDay() startDate?.isBeforeNow == true && (endDate?.isAfterNow == true || today.isEqual(endDate)) } return lesson?.let { getLessonInfo(it.index, cached).data } } override suspend fun getDayRead(dayIndex: String): Resource<SSRead> = withContext(dispatcherProvider.io) { readsDataSource.cache.getItem( ReadsDataSource.Request(dayIndex = dayIndex, fullPath = "") ) } override suspend fun getDayRead(day: SSDay): Resource<SSRead> = readsDataSource.getItem( ReadsDataSource.Request( dayIndex = day.index, fullPath = day.full_read_path ) ) override suspend fun getWeekData(cached: Boolean): Resource<WeekData> { val dataResponse = getQuarterlyAndLessonInfo(cached) val (quarterlyInfo, lessonInfo) = dataResponse.data ?: return Resource.error(dataResponse.error ?: Throwable("Invalid QuarterlyInfo")) val today = DateTime.now().withTimeAtStartOfDay() val days = lessonInfo.days.map { ssDay -> WeekDay( ssDay.index, ssDay.title, formatDate(ssDay.date, SSConstants.SS_DATE_FORMAT_OUTPUT_DAY_SHORT), today.isEqual(parseDate(ssDay.date)) ) }.take(7) return Resource.success( WeekData( quarterlyInfo.quarterly.index, quarterlyInfo.quarterly.title, lessonInfo.lesson.index, lessonInfo.lesson.title, quarterlyInfo.quarterly.cover, days ) ) } override suspend fun saveAnnotations(lessonIndex: String, pdfId: String, annotations: List<PdfAnnotations>) { pdfAnnotationsDataSource.sync( PdfAnnotationsDataSource.Request(lessonIndex, pdfId), annotations ) } override fun getAnnotations( lessonIndex: String, pdfId: String ): Flow<Resource<List<PdfAnnotations>>> = pdfAnnotationsDataSource.getAsFlow( PdfAnnotationsDataSource.Request(lessonIndex, pdfId) ) override suspend fun getComments( readIndex: String ): Resource<SSReadComments> = readCommentsDataSource.getItem(ReadCommentsDataSource.Request(readIndex)) override suspend fun saveComments(comments: SSReadComments) { readCommentsDataSource.sync( ReadCommentsDataSource.Request(comments.readIndex), listOf(comments) ) } override suspend fun getReadHighlights( readIndex: String ): Resource<SSReadHighlights> = readHighlightsDataSource.getItem(ReadHighlightsDataSource.Request(readIndex)) override suspend fun saveHighlights(highlights: SSReadHighlights) { readHighlightsDataSource.sync( ReadHighlightsDataSource.Request(highlights.readIndex), listOf(highlights) ) } override fun checkReaderArtifact() { readerArtifactHelper.sync() } override suspend fun getPreferredBibleVersion(): String? = withContext(dispatcherProvider.io) { bibleVersionDataSource .cache .getItem(BibleVersionDataSource.Request(ssPrefs.getLanguageCode())) .data?.version } override suspend fun savePreferredBibleVersion(version: String) = withContext(dispatcherProvider.io) { bibleVersionDataSource .cache .updateItem(PreferredBibleVersion(version, ssPrefs.getLanguageCode())) } }
mit
3c56f22227eea20226a4cc034143ef4a
40.204167
142
0.703408
5.03001
false
false
false
false
hurricup/intellij-community
platform/analysis-impl/src/com/intellij/profile/codeInspection/BaseInspectionProfileManager.kt
1
3822
/* * Copyright 2000-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.profile.codeInspection import com.intellij.codeInsight.daemon.impl.SeverityRegistrar import com.intellij.codeInspection.InspectionProfile import com.intellij.codeInspection.ex.InspectionProfileImpl import com.intellij.configurationStore.LazySchemeProcessor import com.intellij.openapi.Disposable import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.options.SchemeManager import com.intellij.openapi.options.SchemeState import com.intellij.openapi.project.Project import com.intellij.profile.Profile import com.intellij.profile.ProfileChangeAdapter import com.intellij.util.containers.ContainerUtil import com.intellij.util.messages.MessageBus @JvmField internal val LOG = Logger.getInstance(BaseInspectionProfileManager::class.java) abstract class BaseInspectionProfileManager(messageBus: MessageBus) : InspectionProjectProfileManager() { protected abstract val schemeManager: SchemeManager<InspectionProfileImpl> protected val profileListeners: MutableList<ProfileChangeAdapter> = ContainerUtil.createLockFreeCopyOnWriteList<ProfileChangeAdapter>() private val severityRegistrar = SeverityRegistrar(messageBus) override final fun getSeverityRegistrar() = severityRegistrar override final fun getOwnSeverityRegistrar() = severityRegistrar override final fun addProfileChangeListener(listener: ProfileChangeAdapter, parentDisposable: Disposable) { ContainerUtil.add(listener, profileListeners, parentDisposable) } @Suppress("OverridingDeprecatedMember") override final fun addProfileChangeListener(listener: ProfileChangeAdapter) { profileListeners.add(listener) } @Suppress("OverridingDeprecatedMember") override final fun removeProfileChangeListener(listener: ProfileChangeAdapter) { profileListeners.remove(listener) } internal fun cleanupSchemes(project: Project) { for (profile in schemeManager.allSchemes) { profile.cleanup(project) } } override final fun fireProfileChanged(profile: Profile?) { if (profile is InspectionProfileImpl) { profile.profileChanged() } for (adapter in profileListeners) { adapter.profileChanged(profile) } } override final fun fireProfileChanged(oldProfile: Profile?, profile: Profile) { for (adapter in profileListeners) { adapter.profileActivated(oldProfile, profile) } } fun addProfile(profile: InspectionProfileImpl) { schemeManager.addScheme(profile) } override final fun deleteProfile(name: String) { schemeManager.removeScheme(name)?.let { schemeRemoved(it) } } fun deleteProfile(profile: InspectionProfileImpl) { schemeManager.removeScheme(profile) schemeRemoved(profile) } open protected fun schemeRemoved(scheme: InspectionProfile) { } override fun updateProfile(profile: Profile) { schemeManager.addScheme(profile as InspectionProfileImpl) fireProfileChanged(profile) } } abstract class InspectionProfileProcessor : LazySchemeProcessor<InspectionProfileImpl, InspectionProfileImpl>() { override fun getState(scheme: InspectionProfileImpl): SchemeState { return if (scheme.wasInitialized()) SchemeState.POSSIBLY_CHANGED else SchemeState.UNCHANGED } }
apache-2.0
0ccd6f5d5edb741d399c4e4e4d2a3aca
34.398148
137
0.790947
5.164865
false
false
false
false
Maccimo/intellij-community
plugins/kotlin/jvm/src/org/jetbrains/kotlin/idea/scratch/compile/KtScratchSourceFileProcessor.kt
3
5002
// 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.scratch.compile import org.jetbrains.kotlin.diagnostics.rendering.Renderers import org.jetbrains.kotlin.diagnostics.rendering.RenderingContext import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny import org.jetbrains.kotlin.idea.scratch.ScratchExpression import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.resolve.calls.util.isSingleUnderscore class KtScratchSourceFileProcessor { companion object { const val GENERATED_OUTPUT_PREFIX = "##scratch##generated##" const val LINES_INFO_MARKER = "end##" const val END_OUTPUT_MARKER = "end##!@#%^&*" const val OBJECT_NAME = "ScratchFileRunnerGenerated" const val INSTANCE_NAME = "instanceScratchFileRunner" const val PACKAGE_NAME = "org.jetbrains.kotlin.idea.scratch.generated" const val GET_RES_FUN_NAME_PREFIX = "generated_get_instance_res" } fun process(expressions: List<ScratchExpression>): Result { val sourceProcessor = KtSourceProcessor() expressions.forEach { sourceProcessor.process(it) } val codeResult = """ package $PACKAGE_NAME ${sourceProcessor.imports.joinToString("\n") { it.text }} object $OBJECT_NAME { class $OBJECT_NAME { ${sourceProcessor.classBuilder} } @JvmStatic fun main(args: Array<String>) { val $INSTANCE_NAME = $OBJECT_NAME() ${sourceProcessor.objectBuilder} println("$END_OUTPUT_MARKER") } } """ return Result.OK("$PACKAGE_NAME.$OBJECT_NAME", codeResult) } class KtSourceProcessor { val classBuilder = StringBuilder() val objectBuilder = StringBuilder() val imports = arrayListOf<KtImportDirective>() private var resCount = 0 fun process(expression: ScratchExpression) { when (val psiElement = expression.element) { is KtDestructuringDeclaration -> processDestructuringDeclaration(expression, psiElement) is KtVariableDeclaration -> processDeclaration(expression, psiElement) is KtFunction -> processDeclaration(expression, psiElement) is KtClassOrObject -> processDeclaration(expression, psiElement) is KtImportDirective -> imports.add(psiElement) is KtExpression -> processExpression(expression, psiElement) } } private fun processDeclaration(e: ScratchExpression, c: KtDeclaration) { classBuilder.append(c.text).newLine() val descriptor = c.resolveToDescriptorIfAny() ?: return val context = RenderingContext.of(descriptor) objectBuilder.println(Renderers.COMPACT.render(descriptor, context)) objectBuilder.appendLineInfo(e) } private fun processDestructuringDeclaration(e: ScratchExpression, c: KtDestructuringDeclaration) { val entries = c.entries.mapNotNull { if (it.isSingleUnderscore) null else it.resolveToDescriptorIfAny() } entries.forEach { val context = RenderingContext.of(it) val rendered = Renderers.COMPACT.render(it, context) classBuilder.append(rendered).newLine() objectBuilder.println(rendered) } objectBuilder.appendLineInfo(e) classBuilder.append("init {").newLine() classBuilder.append(c.text).newLine() entries.forEach { classBuilder.append("this.${it.name} = ${it.name}").newLine() } classBuilder.append("}").newLine() } private fun processExpression(e: ScratchExpression, expr: KtExpression) { val resName = "$GET_RES_FUN_NAME_PREFIX$resCount" classBuilder.append("fun $resName() = run { ${expr.text} }").newLine() objectBuilder.printlnObj("$INSTANCE_NAME.$resName()") objectBuilder.appendLineInfo(e) resCount += 1 } private fun StringBuilder.appendLineInfo(e: ScratchExpression) { println("$LINES_INFO_MARKER${e.lineStart}|${e.lineEnd}") } private fun StringBuilder.println(str: String) = append("println(\"$GENERATED_OUTPUT_PREFIX$str\")").newLine() private fun StringBuilder.printlnObj(str: String) = append("println(\"$GENERATED_OUTPUT_PREFIX\${$str}\")").newLine() private fun StringBuilder.newLine() = append("\n") } sealed class Result { class Error(val message: String) : Result() class OK(val mainClassName: String, val code: String) : Result() } }
apache-2.0
135ab4d50ae91f1258dc3701a815fcde
40.691667
158
0.626549
5.21585
false
false
false
false
wordpress-mobile/WordPress-Android
libs/editor/src/main/java/org/wordpress/android/editor/gutenberg/GutenbergDialogFragment.kt
1
5276
package org.wordpress.android.editor.gutenberg import android.app.Dialog import android.content.Context import android.content.DialogInterface import android.os.Bundle import androidx.appcompat.app.AppCompatDialogFragment import androidx.fragment.app.Fragment import com.google.android.material.dialog.MaterialAlertDialogBuilder class GutenbergDialogFragment : AppCompatDialogFragment() { private lateinit var mTag: String private lateinit var mMessage: CharSequence private var mPositiveButtonLabel: CharSequence? = null private var mTitle: CharSequence? = null private var mNegativeButtonLabel: CharSequence? = null private var mId: Int = 0 private var dismissedByPositiveButton = false private var dismissedByNegativeButton = false interface GutenbergDialogPositiveClickInterface { fun onGutenbergDialogPositiveClicked(instanceTag: String, id: Int) } interface GutenbergDialogNegativeClickInterface { fun onGutenbergDialogNegativeClicked(instanceTag: String) } interface GutenbergDialogOnDismissByOutsideTouchInterface { fun onDismissByOutsideTouch(instanceTag: String) } fun initialize( tag: String, title: CharSequence?, message: CharSequence, positiveButtonLabel: CharSequence, negativeButtonLabel: CharSequence? = null, id: Int ) { mTag = tag mTitle = title mMessage = message mPositiveButtonLabel = positiveButtonLabel mNegativeButtonLabel = negativeButtonLabel mId = id } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) this.isCancelable = true val theme = 0 setStyle(STYLE_NORMAL, theme) if (savedInstanceState != null) { mTag = requireNotNull(savedInstanceState.getString(STATE_KEY_TAG)) mTitle = savedInstanceState.getCharSequence(STATE_KEY_TITLE) mMessage = requireNotNull(savedInstanceState.getCharSequence(STATE_KEY_MESSAGE)) mPositiveButtonLabel = savedInstanceState.getCharSequence(STATE_KEY_POSITIVE_BUTTON_LABEL) mNegativeButtonLabel = savedInstanceState.getCharSequence(STATE_KEY_NEGATIVE_BUTTON_LABEL) mId = savedInstanceState.getInt(STATE_KEY_ID) } } override fun onSaveInstanceState(outState: Bundle) { outState.putString(STATE_KEY_TAG, mTag) outState.putCharSequence(STATE_KEY_TITLE, mTitle) outState.putCharSequence(STATE_KEY_MESSAGE, mMessage) outState.putCharSequence(STATE_KEY_POSITIVE_BUTTON_LABEL, mPositiveButtonLabel) outState.putCharSequence(STATE_KEY_NEGATIVE_BUTTON_LABEL, mNegativeButtonLabel) outState.putInt(STATE_KEY_ID, mId) super.onSaveInstanceState(outState) } override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { val builder = MaterialAlertDialogBuilder(requireActivity()) builder.setMessage(mMessage) mTitle?.let { builder.setTitle(mTitle) } mPositiveButtonLabel?.let { builder.setPositiveButton(mPositiveButtonLabel) { _, _ -> dismissedByPositiveButton = true (parentFragment as? GutenbergDialogPositiveClickInterface)?.let { it.onGutenbergDialogPositiveClicked(mTag, mId) } }.setCancelable(true) } mNegativeButtonLabel?.let { builder.setNegativeButton(mNegativeButtonLabel) { _, _ -> dismissedByNegativeButton = true (parentFragment as? GutenbergDialogNegativeClickInterface)?.let { it.onGutenbergDialogNegativeClicked(mTag) } } } return builder.create() } @Suppress("TooGenericExceptionThrown") override fun onAttach(context: Context) { super.onAttach(context) val parentFragment: Fragment? = parentFragment if (parentFragment !is GutenbergDialogPositiveClickInterface) { throw RuntimeException("Parent fragment must implement GutenbergDialogPositiveClickInterface") } if (mNegativeButtonLabel != null && parentFragment !is GutenbergDialogNegativeClickInterface) { throw RuntimeException("Parent fragment must implement GutenbergDialogNegativeClickInterface") } } override fun onDismiss(dialog: DialogInterface) { // Only handle the event if it wasn't triggered by a button if (!dismissedByPositiveButton && !dismissedByNegativeButton) { (parentFragment as? GutenbergDialogOnDismissByOutsideTouchInterface)?.let { it.onDismissByOutsideTouch(mTag) } } super.onDismiss(dialog) } companion object { private const val STATE_KEY_TAG = "state_key_tag" private const val STATE_KEY_TITLE = "state_key_title" private const val STATE_KEY_MESSAGE = "state_key_message" private const val STATE_KEY_POSITIVE_BUTTON_LABEL = "state_key_positive_button_label" private const val STATE_KEY_NEGATIVE_BUTTON_LABEL = "state_key_negative_button_label" private const val STATE_KEY_ID = "state_key_id" } }
gpl-2.0
bb318a2aacb855c0da1702ea63d0b357
38.373134
106
0.688969
5.411282
false
false
false
false
mdaniel/intellij-community
java/java-tests/testSrc/com/intellij/java/codeInsight/highlighting/AtomicReferenceImplicitUsageTest.kt
13
1435
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.java.codeInsight.highlighting import com.intellij.JavaTestUtil import com.intellij.codeInspection.deadCode.UnusedDeclarationInspection import com.intellij.testFramework.fixtures.LightJavaCodeInsightFixtureTestCase /** * @author Pavel.Dolgov */ class AtomicReferenceImplicitUsageTest : LightJavaCodeInsightFixtureTestCase() { override fun getProjectDescriptor() = JAVA_8 override fun getBasePath() = JavaTestUtil.getRelativeJavaTestDataPath() + "/codeInsight/atomicReferenceImplicitUsage/" override fun setUp() { super.setUp() myFixture.enableInspections(UnusedDeclarationInspection()) } fun testReferenceGet() = doTest() fun testIntegerGet() = doTest() fun testLongGet() = doTest() fun testReferenceCAS() = doTest() fun testIntegerCAS() = doTest() fun testLongCAS() = doTest() fun testReferenceGetAndSet() = doTest() fun testIntegerGetAndSet() = doTest() fun testLongGetAndSet() = doTest() fun testReferenceSet() = doTest() fun testIntegerSet() = doTest() fun testLongSet() = doTest() fun testIntegerIncrement() = doTest() fun testLongIncrement() = doTest() fun testNonVolatile() = doTest() private fun doTest() { myFixture.configureByFile(getTestName(false) + ".java") myFixture.checkHighlighting() } }
apache-2.0
18abe79c6d39d41c78490de484fc2081
30.911111
140
0.752613
4.767442
false
true
false
false
npryce/robots
webui/src/main/kotlin/vendor/react-aria-tabpanel-dsl.kt
1
520
package vendor import react.RBuilder import react.RHandler fun RBuilder.tab(id: TabId, contents: RHandler<TabProps>) = child(Tab::class) { attrs.id = id contents() } fun RBuilder.tabList(contents: RHandler<TabListProps>) = child(TabList::class, contents) fun RBuilder.tabPanel(tabId: TabId, contents: RHandler<TabPanelProps>) = child(TabPanel::class) { attrs.tabId = tabId contents() } fun RBuilder.tabPanelWrapper(contents: RHandler<TabPanelWrapperProps>) = child(TabPanelWrapper::class, contents)
gpl-3.0
cf408a4881780ce067d5273b7c9809d8
27.888889
112
0.751923
3.561644
false
false
false
false
benjamin-bader/thrifty
thrifty-schema/src/main/kotlin/com/microsoft/thrifty/schema/BuiltinType.kt
1
4596
/* * 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 types defined by the Thrift IDL, such as the numeric types, * strings, binaries, and void. */ class BuiltinType internal constructor( name: String, override val annotations: Map<String, String> = emptyMap() ) : ThriftType(name) { /** * True if this represents a numeric type, otherwise false. */ val isNumeric: Boolean get() = (this == I8 || this == I16 || this == I32 || this == I64 || this == DOUBLE) override val isBuiltin: Boolean = true override fun <T> accept(visitor: ThriftType.Visitor<T>): T { return when (this) { VOID -> visitor.visitVoid(this) BOOL -> visitor.visitBool(this) BYTE, I8 -> visitor.visitByte(this) I16 -> visitor.visitI16(this) I32 -> visitor.visitI32(this) I64 -> visitor.visitI64(this) DOUBLE -> visitor.visitDouble(this) STRING -> visitor.visitString(this) BINARY -> visitor.visitBinary(this) else -> throw AssertionError("Unexpected ThriftType: $name") } } override fun withAnnotations(annotations: Map<String, String>): ThriftType { return BuiltinType(name, mergeAnnotations(this.annotations, annotations)) } /** @inheritdoc */ override fun equals(other: Any?): Boolean { if (this === other) return true if (other == null) return false if (javaClass != other.javaClass) return false val that = other as BuiltinType if (this.name == that.name) { return true } // 'byte' and 'i8' are synonyms val synonyms = arrayOf(BYTE.name, I8.name) return this.name in synonyms && that.name in synonyms } /** @inheritdoc */ override fun hashCode(): Int { var name = name if (name == I8.name) { name = BYTE.name } return name.hashCode() } companion object { /** * The boolean type. */ val BOOL: ThriftType = BuiltinType("bool") /** * The (signed) byte type. */ val BYTE: ThriftType = BuiltinType("byte") /** * The (signed) byte type; identical to [BYTE], but with a regularized * name. */ val I8: ThriftType = BuiltinType("i8") /** * A 16-bit signed integer type (e.g. [Short]). */ val I16: ThriftType = BuiltinType("i16") /** * A 32-bit signed integer type (e.g. [Int]). */ val I32: ThriftType = BuiltinType("i32") /** * A 64-bit signed integer type (e.g. [Long]). */ val I64: ThriftType = BuiltinType("i64") /** * A double-precision floating-point type (e.g. [Double]). */ val DOUBLE: ThriftType = BuiltinType("double") /** * A type representing a series of bytes of unspecified encoding, * but we'll use UTF-8. */ val STRING: ThriftType = BuiltinType("string") /** * A type representing a series of bytes. */ val BINARY: ThriftType = BuiltinType("binary") /** * No type; used exclusively to indicate that a service method has no * return value. */ val VOID: ThriftType = BuiltinType("void") private val BUILTINS = listOf(BOOL, BYTE, I8, I16, I32, I64, DOUBLE, STRING, BINARY, VOID) .map { it.name to it } .toMap() /** * Returns the builtin type corresponding to the given [name], or null * if no such type exists. */ fun get(name: String): ThriftType? { return BUILTINS[name] } } }
apache-2.0
fe98c2c6872953aaf90185c7dd0194b5
28.651613
116
0.565492
4.393881
false
false
false
false
brianwernick/PlaylistCore
demo/src/main/java/com/devbrackets/android/playlistcoredemo/ui/activity/MediaSelectionActivity.kt
1
2837
package com.devbrackets.android.playlistcoredemo.ui.activity import android.app.Activity import android.content.Intent import android.os.Bundle import android.view.View import android.widget.AdapterView import android.widget.AdapterView.OnItemClickListener import android.widget.ListView import androidx.appcompat.app.AppCompatActivity import com.devbrackets.android.playlistcore.annotation.SupportedMediaType import com.devbrackets.android.playlistcore.manager.BasePlaylistManager import com.devbrackets.android.playlistcoredemo.R import com.devbrackets.android.playlistcoredemo.data.Samples import com.devbrackets.android.playlistcoredemo.ui.activity.AudioPlayerActivity import com.devbrackets.android.playlistcoredemo.ui.activity.MediaSelectionActivity import com.devbrackets.android.playlistcoredemo.ui.activity.VideoPlayerActivity import com.devbrackets.android.playlistcoredemo.ui.adapter.SampleListAdapter /** * A simple activity that allows the user to select a chapter form "The Count of Monte Cristo" * or a sample video to play. */ class MediaSelectionActivity : AppCompatActivity(), OnItemClickListener { private var isAudio = false override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.list_selection_activity) isAudio = intent.getLongExtra(EXTRA_MEDIA_TYPE, BasePlaylistManager.AUDIO.toLong()) == BasePlaylistManager.AUDIO.toLong() if (supportActionBar != null) { supportActionBar!!.title = resources.getString(if (isAudio) R.string.title_audio_selection_activity else R.string.title_video_selection_activity) } val exampleList = findViewById<ListView>(R.id.selection_activity_list) exampleList.adapter = SampleListAdapter(this, if (isAudio) Samples.audio else Samples.video) exampleList.onItemClickListener = this } override fun onItemClick(parent: AdapterView<*>?, view: View, position: Int, id: Long) { if (isAudio) { startAudioPlayerActivity(position) } else { startVideoPlayerActivity(position) } } private fun startAudioPlayerActivity(selectedIndex: Int) { val intent = Intent(this, AudioPlayerActivity::class.java) intent.putExtra(AudioPlayerActivity.Companion.EXTRA_INDEX, selectedIndex) startActivity(intent) } private fun startVideoPlayerActivity(selectedIndex: Int) { val intent = Intent(this, VideoPlayerActivity::class.java) intent.putExtra(VideoPlayerActivity.Companion.EXTRA_INDEX, selectedIndex) startActivity(intent) } companion object { const val EXTRA_MEDIA_TYPE = "EXTRA_MEDIA_TYPE" fun show(activity: Activity, @SupportedMediaType mediaType: Long) { val intent = Intent(activity, MediaSelectionActivity::class.java) intent.putExtra(EXTRA_MEDIA_TYPE, mediaType) activity.startActivity(intent) } } }
apache-2.0
b70964ae92e566c73221ada42230407a
42
151
0.790271
4.568438
false
false
false
false
yongce/AndroidLib
baseLib/src/main/java/me/ycdev/android/lib/common/utils/IntentUtils.kt
1
4187
@file:Suppress("unused") package me.ycdev.android.lib.common.utils import android.annotation.SuppressLint import android.content.Context import android.content.Intent import android.content.pm.ApplicationInfo import android.content.pm.PackageManager import android.os.Build.VERSION import android.os.Build.VERSION_CODES import android.os.PowerManager import androidx.annotation.IntDef import timber.log.Timber @Suppress("MemberVisibilityCanBePrivate") object IntentUtils { private const val TAG = "IntentUtils" const val INTENT_TYPE_ACTIVITY = 1 const val INTENT_TYPE_BROADCAST = 2 const val INTENT_TYPE_SERVICE = 3 @IntDef(INTENT_TYPE_ACTIVITY, INTENT_TYPE_BROADCAST, INTENT_TYPE_SERVICE) @Retention(AnnotationRetention.SOURCE) annotation class IntentType const val EXTRA_FOREGROUND_SERVICE = "extra.foreground_service" fun canStartActivity(cxt: Context, intent: Intent): Boolean { // Use PackageManager.MATCH_DEFAULT_ONLY to behavior same as Context#startAcitivty() val resolveInfo = cxt.packageManager.resolveActivity( intent, PackageManager.MATCH_DEFAULT_ONLY ) return resolveInfo != null } fun startActivity(context: Context, intent: Intent): Boolean { return if (canStartActivity(context, intent)) { context.startActivity(intent) true } else { Timber.tag(TAG).w("cannot start Activity: $intent") false } } fun needForegroundService( context: Context, ai: ApplicationInfo, listenSensor: Boolean ): Boolean { // no background limitation before Android O if (VERSION.SDK_INT < VERSION_CODES.O) { return false } // Need foreground service on Android P to listen sensors if (listenSensor && VERSION.SDK_INT >= VERSION_CODES.P) { return true } // The background limitation only works when the targetSdk is 26 or higher if (ai.targetSdkVersion < VERSION_CODES.O) { return false } // no background limitation if the app is in the battery optimization whitelist. val powerMgr = context.getSystemService(Context.POWER_SERVICE) as PowerManager if (powerMgr.isIgnoringBatteryOptimizations(ai.packageName)) { return false } // yes, we need foreground service return true } fun needForegroundService(context: Context, listenSensor: Boolean): Boolean { return needForegroundService(context, context.applicationInfo, listenSensor) } @SuppressLint("NewApi") fun startService(context: Context, intent: Intent): Boolean { val resolveInfo = context.packageManager.resolveService(intent, 0) ?: return false intent.setClassName( resolveInfo.serviceInfo.packageName, resolveInfo.serviceInfo.name ) // Here, we should set "listenSensor" to false. // The target service still can set "listenSensor" to true for its checking. if (needForegroundService(context, resolveInfo.serviceInfo.applicationInfo, false)) { intent.putExtra(EXTRA_FOREGROUND_SERVICE, true) context.startForegroundService(intent) } else { intent.putExtra(EXTRA_FOREGROUND_SERVICE, false) context.startService(intent) } return true } fun startForegroundService(context: Context, intent: Intent): Boolean { val resolveInfo = context.packageManager.resolveService(intent, 0) ?: return false intent.setClassName( resolveInfo.serviceInfo.packageName, resolveInfo.serviceInfo.name ) if (VERSION.SDK_INT < VERSION_CODES.O) { intent.putExtra(EXTRA_FOREGROUND_SERVICE, false) context.startService(intent) } else { // here, we add an extra so that the target service can know // it needs to call #startForeground() intent.putExtra(EXTRA_FOREGROUND_SERVICE, true) context.startForegroundService(intent) } return true } }
apache-2.0
bd62cbb3fbb9ca2eb63c65fbb346232e
34.184874
93
0.663005
4.914319
false
false
false
false
asedunov/intellij-community
platform/testGuiFramework/src/com/intellij/testGuiFramework/launcher/GuiTestLocalLauncher.kt
1
12033
/* * 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.launcher import com.intellij.openapi.application.PathManager import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.vfs.VfsUtilCore import com.intellij.testGuiFramework.impl.GuiTestStarter import com.intellij.testGuiFramework.launcher.classpath.ClassPathBuilder import com.intellij.testGuiFramework.launcher.classpath.ClassPathBuilder.Companion.isWin import com.intellij.testGuiFramework.launcher.classpath.PathUtils import com.intellij.testGuiFramework.launcher.ide.Ide import com.intellij.testGuiFramework.launcher.ide.IdeType import org.jetbrains.jps.model.JpsElementFactory import org.jetbrains.jps.model.JpsProject import org.jetbrains.jps.model.java.JpsJavaExtensionService import org.jetbrains.jps.model.module.JpsModule import org.jetbrains.jps.model.serialization.JpsModelSerializationDataService import org.jetbrains.jps.model.serialization.JpsProjectLoader import org.junit.Assert.fail import java.io.BufferedReader import java.io.File import java.io.InputStreamReader import java.net.URL import java.nio.file.Paths import java.util.* import java.util.concurrent.CountDownLatch import java.util.concurrent.TimeUnit import java.util.jar.JarInputStream import java.util.stream.Collectors import kotlin.concurrent.thread /** * @author Sergey Karashevich */ object GuiTestLocalLauncher { private val LOG = Logger.getInstance("#com.intellij.testGuiFramework.launcher.GuiTestLocalLauncher") var process: Process? = null val TEST_GUI_FRAMEWORK_MODULE_NAME = "testGuiFramework" val project: JpsProject by lazy { val home = PathManager.getHomePath() val model = JpsElementFactory.getInstance().createModel() val pathVariables = JpsModelSerializationDataService.computeAllPathVariables(model.global) val jpsProject = model.project JpsProjectLoader.loadProject(jpsProject, pathVariables, home) jpsProject.changeOutputIfNeeded() jpsProject } val modulesList: List<JpsModule> by lazy { project.modules } val testGuiFrameworkModule: JpsModule by lazy { modulesList.module(TEST_GUI_FRAMEWORK_MODULE_NAME) ?: throw Exception("Unable to find module '$TEST_GUI_FRAMEWORK_MODULE_NAME'") } fun killProcessIfPossible() { try { if (process?.isAlive ?: false) process!!.destroyForcibly() } catch (e: KotlinNullPointerException) { LOG.error("Seems that process has already destroyed, right after condition") } } fun runIdeLocally(ide: Ide = Ide(IdeType.IDEA_ULTIMATE, 0, 0), port: Int = 0) { //todo: check that we are going to run test locally val args = createArgs(ide = ide, port = port) return startIde(ide = ide, args = args) } fun runIdeByPath(path: String, ide: Ide = Ide(IdeType.IDEA_ULTIMATE, 0, 0), port: Int = 0) { //todo: check that we are going to run test locally val args = createArgsByPath(path, port) return startIde(ide = ide, args = args) } fun firstStartIdeLocally(ide: Ide = Ide(IdeType.IDEA_ULTIMATE, 0, 0)) { val args = createArgsForFirstStart(ide) return startIdeAndWait(ide = ide, args = args) } fun firstStartIdeByPath(path: String, ide: Ide = Ide(IdeType.IDEA_ULTIMATE, 0, 0)) { val args = createArgsForFirstStartByPath(ide, path) return startIdeAndWait(ide = ide, args = args) } private fun startIde(ide: Ide, needToWait: Boolean = false, timeOut: Long = 0, timeOutUnit: TimeUnit = TimeUnit.SECONDS, args: List<String>): Unit { LOG.info("Running $ide locally \n with args: $args") val startLatch = CountDownLatch(1) thread(start = true, name = "IdeaTestThread") { val ideaStartTest = ProcessBuilder().inheritIO().command(args) process = ideaStartTest.start() startLatch.countDown() } if (needToWait) { startLatch.await() if (timeOut != 0L) process!!.waitFor(timeOut, timeOutUnit) else process!!.waitFor() if (process!!.exitValue() != 1) { println("${ide.ideType} process completed successfully") LOG.info("${ide.ideType} process completed successfully") } else { System.err.println("${ide.ideType} process execution error:") val collectedError = BufferedReader(InputStreamReader(process!!.errorStream)).lines().collect(Collectors.joining("\n")) System.err.println(collectedError) LOG.error("${ide.ideType} process execution error:") LOG.error(collectedError) fail("Starting ${ide.ideType} failed.") } } } private fun startIdeAndWait(ide: Ide, args: List<String>): Unit = startIde(ide = ide, needToWait = true, args = args) private fun createArgs(ide: Ide, mainClass: String = "com.intellij.idea.Main", port: Int = 0): List<String> = createArgsBase(ide, mainClass, GuiTestStarter.COMMAND_NAME, port) private fun createArgsForFirstStart(ide: Ide, port: Int = 0): List<String> = createArgsBase(ide, "com.intellij.testGuiFramework.impl.FirstStarterKt", null, port) private fun createArgsBase(ide: Ide, mainClass: String, commandName: String?, port: Int): List<String> { var resultingArgs = listOf<String>() .plus(getCurrentJavaExec()) .plus(getDefaultVmOptions(ide)) .plus("-classpath") .plus(getOsSpecificClasspath(ide.ideType.mainModule)) .plus(mainClass) if (commandName != null) resultingArgs = resultingArgs.plus(commandName) if (port != 0) resultingArgs = resultingArgs.plus("port=$port") LOG.info("Running with args: ${resultingArgs.joinToString(" ")}") return resultingArgs } private fun createArgsForFirstStartByPath(ide: Ide, path: String): List<String> { val classpath = PathUtils(path).makeClassPathBuilder().build(emptyList()) val resultingArgs = listOf<String>() .plus(getCurrentJavaExec()) .plus(getDefaultVmOptions(ide)) .plus("-classpath") .plus(classpath) .plus(com.intellij.testGuiFramework.impl.FirstStarter::class.qualifiedName!! + "Kt") return resultingArgs } private fun createArgsByPath(path: String, port: Int = 0): List<String> { var resultingArgs = listOf<String>() .plus("open") .plus(path) //path to exec .plus("--args") .plus(GuiTestStarter.COMMAND_NAME) if (port != 0) resultingArgs = resultingArgs.plus("port=$port") LOG.info("Running with args: ${resultingArgs.joinToString(" ")}") return resultingArgs } /** * Default VM options to start IntelliJ IDEA (or IDEA-based IDE). To customize options use com.intellij.testGuiFramework.launcher.GuiTestOptions */ private fun getDefaultVmOptions(ide: Ide) : List<String> { return listOf<String>() .plus("-Xmx${GuiTestOptions.getXmxSize()}m") .plus("-XX:ReservedCodeCacheSize=150m") .plus("-XX:+UseConcMarkSweepGC") .plus("-XX:SoftRefLRUPolicyMSPerMB=50") .plus("-XX:MaxJavaStackTraceDepth=10000") .plus("-ea") .plus("-Xbootclasspath/p:${GuiTestOptions.getBootClasspath()}") .plus("-Dsun.awt.disablegrab=true") .plus("-Dsun.io.useCanonCaches=false") .plus("-Djava.net.preferIPv4Stack=true") .plus("-Dapple.laf.useScreenMenuBar=${GuiTestOptions.useAppleScreenMenuBar().toString()}") .plus("-Didea.is.internal=${GuiTestOptions.isInternal().toString()}") .plus("-Didea.config.path=${GuiTestOptions.getConfigPath()}") .plus("-Didea.system.path=${GuiTestOptions.getSystemPath()}") .plus("-Dfile.encoding=${GuiTestOptions.getEncoding()}") .plus("-Didea.platform.prefix=${ide.ideType.platformPrefix}") .plus("-Xdebug") .plus("-Xrunjdwp:transport=dt_socket,server=y,suspend=${GuiTestOptions.suspendDebug()},address=${GuiTestOptions.getDebugPort()}") } private fun getCurrentJavaExec(): String { return PathUtils.getJreBinPath() } private fun getOsSpecificClasspath(moduleName: String): String = ClassPathBuilder.buildOsSpecific( getFullClasspath(moduleName).map { it.path }) /** * return union of classpaths for current test (get from classloader) and classpaths of main and testGuiFramework modules* */ private fun getFullClasspath(moduleName: String): List<File> { val classpath = getExtendedClasspath(moduleName) classpath.addAll(getTestClasspath()) return classpath.toList() } private fun getTestClasspath(): List<File> { val classLoader = this.javaClass.classLoader val urlClassLoaderClass = classLoader.javaClass val getUrlsMethod = urlClassLoaderClass.methods.filter { it.name.toLowerCase() == "geturls" }.firstOrNull()!! @Suppress("UNCHECKED_CAST") val urlsListOrArray = getUrlsMethod.invoke(classLoader) var urls = (urlsListOrArray as? List<*> ?: (urlsListOrArray as Array<*>).toList()).filterIsInstance(URL::class.java) if (isWin()) { val classPathUrl = urls.find { it.toString().contains(Regex("classpath[\\d]*.jar")) } if (classPathUrl != null) { val jarStream = JarInputStream(File(classPathUrl.path).inputStream()) val mf = jarStream.manifest urls = mf.mainAttributes.getValue("Class-Path").split(" ").map { URL(it) } } } return urls.map { Paths.get(it.toURI()).toFile() } } /** * return union of classpaths for @moduleName and testGuiFramework modules */ private fun getExtendedClasspath(moduleName: String): MutableSet<File> { // here we trying to analyze output path for project from classloader path and from modules classpath. // If they didn't match than change it to output path from classpath val resultSet = LinkedHashSet<File>() val module = modulesList.module(moduleName) ?: throw Exception("Unable to find module with name: $moduleName") resultSet.addAll(module.getClasspath()) resultSet.addAll(testGuiFrameworkModule.getClasspath()) return resultSet } private fun List<JpsModule>.module(moduleName: String): JpsModule? = this.filter { it.name == moduleName }.firstOrNull() private fun JpsModule.getClasspath(): MutableCollection<File> = JpsJavaExtensionService.dependencies(this).productionOnly().runtimeOnly().recursively().classes().roots private fun getOutputRootFromClassloader(): File { val pathFromClassloader = PathManager.getJarPathForClass(GuiTestLocalLauncher::class.java) val productionDir = File(pathFromClassloader).parentFile assert(productionDir.isDirectory) val outputDir = productionDir.parentFile assert(outputDir.isDirectory) return outputDir } /** * @return true if classloader's output path is the same to module's output path (and also same to project) */ private fun needToChangeProjectOutput(project: JpsProject): Boolean = JpsJavaExtensionService.getInstance().getProjectExtension(project)?.outputUrl == getOutputRootFromClassloader().path private fun JpsProject.changeOutputIfNeeded() { if (!needToChangeProjectOutput(this)) { val projectExtension = JpsJavaExtensionService.getInstance().getOrCreateProjectExtension(this) projectExtension.outputUrl = VfsUtilCore.pathToUrl(FileUtil.toSystemIndependentName(getOutputRootFromClassloader().path)) } } } fun main(args: Array<String>) { GuiTestLocalLauncher.firstStartIdeLocally(Ide(ideType = IdeType.WEBSTORM, version = 0, build = 0)) }
apache-2.0
2a3783d2bcf4379ae2d2606d092f6324
39.518519
146
0.715283
4.584
false
true
false
false
robnixon/ComputingTutorAndroidApp
app/src/main/java/net/computingtutor/robert/computingtutor/BaseConverter.kt
1
1608
package net.computingtutor.robert.computingtutor import android.util.Log class BaseConverter(val inputVal: String, val plusve: Boolean, val fractional: Boolean, val inputBase: String){ var binaryResult: String = "" var hexResult: String = "" var decimalResult: String = "" val inputLength: Int = inputVal.length init { if (inputBase == "Base 2"){ binaryResult = inputVal //toHex() binToDecimal() } else if (inputBase == "Base 16") { //toBin() hexResult = inputVal //toDecimal() } else if (inputBase == "Base 10") { //toBin() //toHex() //toDecimal() } } private fun binToDecimal() { var tempDecimal: Double = 0.0 if (plusve and !fractional){ var count: Int = 0 var power: Int = inputLength - 1 while (count < inputLength){ if (inputVal.get(count) == '1'){ tempDecimal += Math.pow(2.0, power.toDouble()) } count += 1 power -= 1 } } else if (plusve and fractional) { } else if (!plusve and !fractional) { } else if (!plusve and fractional) { } decimalResult = tempDecimal.toInt().toString() } fun binToHex() { } fun hexToBin() { } fun hexToDec() { } fun decimalToHex() { } fun decimalToBin() { var tempBin: String = "" if (plusve and !fractional) { } } }
mit
2d849eaed7b947c8a073e143ef9d4802
20.72973
111
0.491915
4.322581
false
false
false
false
onnerby/musikcube
src/musikdroid/app/src/main/java/io/casey/musikcube/remote/ui/settings/activity/SettingsActivity.kt
1
20032
package io.casey.musikcube.remote.ui.settings.activity import android.app.Dialog import android.content.Context import android.content.Intent import android.net.Uri import android.os.Bundle import android.view.LayoutInflater import android.view.Menu import android.view.MenuItem import android.view.View import android.widget.* import androidx.appcompat.app.AlertDialog import androidx.fragment.app.DialogFragment import com.uacf.taskrunner.Task import com.uacf.taskrunner.Tasks import io.casey.musikcube.remote.R import io.casey.musikcube.remote.service.playback.PlayerWrapper import io.casey.musikcube.remote.service.playback.impl.streaming.StreamProxy import io.casey.musikcube.remote.ui.navigation.Transition import io.casey.musikcube.remote.ui.settings.constants.Prefs import io.casey.musikcube.remote.ui.settings.model.Connection import io.casey.musikcube.remote.ui.settings.model.ConnectionsDb import io.casey.musikcube.remote.ui.shared.activity.BaseActivity import io.casey.musikcube.remote.ui.shared.extension.* import io.casey.musikcube.remote.ui.shared.mixin.MetadataProxyMixin import io.casey.musikcube.remote.ui.shared.mixin.PlaybackMixin import java.util.* import javax.inject.Inject import io.casey.musikcube.remote.ui.settings.constants.Prefs.Default as Defaults import io.casey.musikcube.remote.ui.settings.constants.Prefs.Key as Keys class SettingsActivity : BaseActivity() { @Inject lateinit var connectionsDb: ConnectionsDb @Inject lateinit var streamProxy: StreamProxy private lateinit var addressText: EditText private lateinit var portText: EditText private lateinit var httpPortText: EditText private lateinit var passwordText: EditText private lateinit var albumArtCheckbox: CheckBox private lateinit var softwareVolume: CheckBox private lateinit var sslCheckbox: CheckBox private lateinit var certCheckbox: CheckBox private lateinit var transferCheckbox: CheckBox private lateinit var bitrateSpinner: Spinner private lateinit var formatSpinner: Spinner private lateinit var cacheSpinner: Spinner private lateinit var titleEllipsisSpinner: Spinner private lateinit var playback: PlaybackMixin private lateinit var data: MetadataProxyMixin override fun onCreate(savedInstanceState: Bundle?) { data = mixin(MetadataProxyMixin()) playback = mixin(PlaybackMixin()) component.inject(this) super.onCreate(savedInstanceState) prefs = this.getSharedPreferences(Prefs.NAME, Context.MODE_PRIVATE) setContentView(R.layout.settings_activity) setTitle(R.string.settings_title) cacheViews() bindListeners() rebindUi() } override fun onCreateOptionsMenu(menu: Menu): Boolean { menuInflater.inflate(R.menu.settings_menu, menu) return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { android.R.id.home -> { finish() return true } R.id.action_save -> { save() return true } } return super.onOptionsItemSelected(item) } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { if (requestCode == CONNECTIONS_REQUEST_CODE && resultCode == RESULT_OK) { if (data != null) { val connection = data.getParcelableExtra<Connection>( ConnectionsActivity.EXTRA_SELECTED_CONNECTION) if (connection != null) { addressText.setText(connection.hostname) passwordText.setText(connection.password) portText.setText(connection.wssPort.toString()) httpPortText.setText(connection.httpPort.toString()) sslCheckbox.setCheckWithoutEvent(connection.ssl, sslCheckChanged) certCheckbox.setCheckWithoutEvent(connection.noValidate, certValidationChanged) } } } super.onActivityResult(requestCode, resultCode, data) } override val transitionType: Transition get() = Transition.Vertical private fun rebindSpinner(spinner: Spinner, arrayResourceId: Int, key: String, defaultIndex: Int) { val items = ArrayAdapter.createFromResource(this, arrayResourceId, android.R.layout.simple_spinner_item) items.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item) spinner.adapter = items spinner.setSelection(prefs.getInt(key, defaultIndex)) } private fun rebindUi() { /* connection info */ addressText.setTextAndMoveCursorToEnd(prefs.getString(Keys.ADDRESS) ?: Defaults.ADDRESS) portText.setTextAndMoveCursorToEnd(String.format( Locale.ENGLISH, "%d", prefs.getInt(Keys.MAIN_PORT, Defaults.MAIN_PORT))) httpPortText.setTextAndMoveCursorToEnd(String.format( Locale.ENGLISH, "%d", prefs.getInt(Keys.AUDIO_PORT, Defaults.AUDIO_PORT))) passwordText.setTextAndMoveCursorToEnd(prefs.getString(Keys.PASSWORD) ?: Defaults.PASSWORD) /* bitrate */ rebindSpinner( bitrateSpinner, R.array.transcode_bitrate_array, Keys.TRANSCODER_BITRATE_INDEX, Defaults.TRANSCODER_BITRATE_INDEX) /* format */ rebindSpinner( formatSpinner, R.array.transcode_format_array, Keys.TRANSCODER_FORMAT_INDEX, Defaults.TRANSCODER_FORMAT_INDEX) /* disk cache */ rebindSpinner( cacheSpinner, R.array.disk_cache_array, Keys.DISK_CACHE_SIZE_INDEX, Defaults.DISK_CACHE_SIZE_INDEX) /* title ellipsis mode */ rebindSpinner( titleEllipsisSpinner, R.array.title_ellipsis_mode_array, Keys.TITLE_ELLIPSIS_MODE_INDEX, Defaults.TITLE_ELLIPSIS_SIZE_INDEX) /* advanced */ transferCheckbox.isChecked = prefs.getBoolean( Keys.TRANSFER_TO_SERVER_ON_HEADSET_DISCONNECT, Defaults.TRANSFER_TO_SERVER_ON_HEADSET_DISCONNECT) albumArtCheckbox.isChecked = prefs.getBoolean( Keys.LASTFM_ENABLED, Defaults.LASTFM_ENABLED) softwareVolume.isChecked = prefs.getBoolean( Keys.SOFTWARE_VOLUME, Defaults.SOFTWARE_VOLUME) sslCheckbox.setCheckWithoutEvent( this.prefs.getBoolean(Keys.SSL_ENABLED,Defaults.SSL_ENABLED), sslCheckChanged) certCheckbox.setCheckWithoutEvent( this.prefs.getBoolean( Keys.CERT_VALIDATION_DISABLED, Defaults.CERT_VALIDATION_DISABLED), certValidationChanged) enableUpNavigation() } private fun onDisableSslFromDialog() { sslCheckbox.setCheckWithoutEvent(false, sslCheckChanged) } private fun onDisableCertValidationFromDialog() { certCheckbox.setCheckWithoutEvent(false, certValidationChanged) } private val sslCheckChanged = { _: CompoundButton, value:Boolean -> if (value) { if (!dialogVisible(SslAlertDialog.TAG)) { showDialog(SslAlertDialog.newInstance(), SslAlertDialog.TAG) } } } private val certValidationChanged = { _: CompoundButton, value: Boolean -> if (value) { if (!dialogVisible(DisableCertValidationAlertDialog.TAG)) { showDialog( DisableCertValidationAlertDialog.newInstance(), DisableCertValidationAlertDialog.TAG) } } } private fun cacheViews() { this.addressText = findViewById(R.id.address) this.portText = findViewById(R.id.port) this.httpPortText = findViewById(R.id.http_port) this.passwordText = findViewById(R.id.password) this.albumArtCheckbox = findViewById(R.id.album_art_checkbox) this.softwareVolume = findViewById(R.id.software_volume) this.bitrateSpinner = findViewById(R.id.transcoder_bitrate_spinner) this.formatSpinner = findViewById(R.id.transcoder_format_spinner) this.cacheSpinner = findViewById(R.id.streaming_disk_cache_spinner) this.titleEllipsisSpinner = findViewById(R.id.title_ellipsis_mode_spinner) this.sslCheckbox = findViewById(R.id.ssl_checkbox) this.certCheckbox = findViewById(R.id.cert_validation) this.transferCheckbox = findViewById(R.id.transfer_on_disconnect_checkbox) } private fun bindListeners() { findViewById<View>(R.id.button_save_as).setOnClickListener{ showSaveAsDialog() } findViewById<View>(R.id.button_load).setOnClickListener{ startActivityForResult( ConnectionsActivity.getStartIntent(this), CONNECTIONS_REQUEST_CODE) } findViewById<View>(R.id.button_diagnostics).setOnClickListener { startActivity(Intent(this, DiagnosticsActivity::class.java)) } } private fun showSaveAsDialog() { if (!dialogVisible(SaveAsDialog.TAG)) { showDialog(SaveAsDialog.newInstance(), SaveAsDialog.TAG) } } private fun showInvalidConnectionDialog(messageId: Int = R.string.settings_invalid_connection_message) { if (!dialogVisible(InvalidConnectionDialog.TAG)) { showDialog(InvalidConnectionDialog.newInstance(messageId), InvalidConnectionDialog.TAG) } } private fun saveAs(name: String) { try { val connection = Connection() connection.name = name connection.hostname = addressText.text.toString() connection.wssPort = portText.text.toString().toInt() connection.httpPort = httpPortText.text.toString().toInt() connection.password = passwordText.text.toString() connection.ssl = sslCheckbox.isChecked connection.noValidate = certCheckbox.isChecked if (connection.valid) { runner.run(SaveAsTask.nameFor(connection), SaveAsTask(connectionsDb, connection)) } else { showInvalidConnectionDialog() } } catch (ex: NumberFormatException) { showInvalidConnectionDialog() } } private fun save() { val addr = addressText.text.toString() val port = portText.text.toString() val httpPort = httpPortText.text.toString() val password = passwordText.text.toString() try { prefs.edit() .putString(Keys.ADDRESS, addr) .putInt(Keys.MAIN_PORT, if (port.isNotEmpty()) port.toInt() else 0) .putInt(Keys.AUDIO_PORT, if (httpPort.isNotEmpty()) httpPort.toInt() else 0) .putString(Keys.PASSWORD, password) .putBoolean(Keys.LASTFM_ENABLED, albumArtCheckbox.isChecked) .putBoolean(Keys.SOFTWARE_VOLUME, softwareVolume.isChecked) .putBoolean(Keys.SSL_ENABLED, sslCheckbox.isChecked) .putBoolean(Keys.CERT_VALIDATION_DISABLED, certCheckbox.isChecked) .putBoolean(Keys.TRANSFER_TO_SERVER_ON_HEADSET_DISCONNECT, transferCheckbox.isChecked) .putInt(Keys.TRANSCODER_BITRATE_INDEX, bitrateSpinner.selectedItemPosition) .putInt(Keys.TRANSCODER_FORMAT_INDEX, formatSpinner.selectedItemPosition) .putInt(Keys.DISK_CACHE_SIZE_INDEX, cacheSpinner.selectedItemPosition) .putInt(Keys.TITLE_ELLIPSIS_MODE_INDEX, titleEllipsisSpinner.selectedItemPosition) .apply() if (!softwareVolume.isChecked) { PlayerWrapper.setVolume(1.0f) } streamProxy.reload() data.wss.disconnect() finish() } catch (ex: NumberFormatException) { showInvalidConnectionDialog(R.string.settings_invalid_connection_no_name_message) } } override fun onTaskCompleted(taskName: String, taskId: Long, task: Task<*, *>, result: Any) { if (SaveAsTask.match(taskName)) { if ((result as SaveAsTask.Result) == SaveAsTask.Result.Exists) { val connection = (task as SaveAsTask).connection if (!dialogVisible(ConfirmOverwriteDialog.TAG)) { showDialog( ConfirmOverwriteDialog.newInstance(connection), ConfirmOverwriteDialog.TAG) } } else { showSnackbar( findViewById<View>(android.R.id.content), R.string.snackbar_saved_connection_preset) } } } class SslAlertDialog : DialogFragment() { override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { val dlg = AlertDialog.Builder(activity!!) .setTitle(R.string.settings_ssl_dialog_title) .setMessage(R.string.settings_ssl_dialog_message) .setPositiveButton(R.string.button_enable, null) .setNegativeButton(R.string.button_disable) { _, _ -> (activity as SettingsActivity).onDisableSslFromDialog() } .setNeutralButton(R.string.button_learn_more) { _, _ -> try { val intent = Intent(Intent.ACTION_VIEW, Uri.parse(LEARN_MORE_URL)) startActivity(intent) } catch (ex: Exception) { } } .create() dlg.setCancelable(false) return dlg } companion object { private const val LEARN_MORE_URL = "https://github.com/clangen/musikcube/wiki/ssl-server-setup" const val TAG = "ssl_alert_dialog_tag" fun newInstance(): SslAlertDialog { return SslAlertDialog() } } } class DisableCertValidationAlertDialog : DialogFragment() { override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { val dlg = AlertDialog.Builder(activity!!) .setTitle(R.string.settings_disable_cert_validation_title) .setMessage(R.string.settings_disable_cert_validation_message) .setPositiveButton(R.string.button_enable, null) .setNegativeButton(R.string.button_disable) { _, _ -> (activity as SettingsActivity).onDisableCertValidationFromDialog() } .create() dlg.setCancelable(false) return dlg } companion object { const val TAG = "disable_cert_verify_dialog" fun newInstance(): DisableCertValidationAlertDialog { return DisableCertValidationAlertDialog() } } } class InvalidConnectionDialog: DialogFragment() { override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { val dlg = AlertDialog.Builder(activity!!) .setTitle(R.string.settings_invalid_connection_title) .setMessage(arguments!!.getInt(EXTRA_MESSAGE_ID)) .setNegativeButton(R.string.button_ok, null) .create() dlg.setCancelable(false) return dlg } companion object { const val TAG = "invalid_connection_dialog" private const val EXTRA_MESSAGE_ID = "extra_message_id" fun newInstance(messageId: Int = R.string.settings_invalid_connection_message): InvalidConnectionDialog { val args = Bundle() args.putInt(EXTRA_MESSAGE_ID, messageId) val result = InvalidConnectionDialog() result.arguments = args return result } } } class ConfirmOverwriteDialog : DialogFragment() { override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { val dlg = AlertDialog.Builder(activity!!) .setTitle(R.string.settings_confirm_overwrite_title) .setMessage(R.string.settings_confirm_overwrite_message) .setNegativeButton(R.string.button_no, null) .setPositiveButton(R.string.button_yes) { _, _ -> when (val connection = arguments?.getParcelable<Connection>(EXTRA_CONNECTION)) { null -> throw IllegalArgumentException("invalid connection") else -> { val db = (activity as SettingsActivity).connectionsDb val saveAs = SaveAsTask(db, connection, true) (activity as SettingsActivity).runner.run(SaveAsTask.nameFor(connection), saveAs) } } } .create() dlg.setCancelable(false) return dlg } companion object { const val TAG = "confirm_overwrite_dialog" private const val EXTRA_CONNECTION = "extra_connection" fun newInstance(connection: Connection): ConfirmOverwriteDialog { val args = Bundle() args.putParcelable(EXTRA_CONNECTION, connection) val result = ConfirmOverwriteDialog() result.arguments = args return result } } } class SaveAsDialog : DialogFragment() { override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { val inflater = LayoutInflater.from(context) val view = inflater.inflate(R.layout.dialog_edit, null) val edit = view.findViewById<EditText>(R.id.edit) edit.requestFocus() val dlg = AlertDialog.Builder(activity!!) .setTitle(R.string.settings_save_as_title) .setNegativeButton(R.string.button_cancel) { _, _ -> hideKeyboard() } .setOnCancelListener { hideKeyboard() } .setPositiveButton(R.string.button_save) { _, _ -> (activity as SettingsActivity).saveAs(edit.text.toString()) } .create() dlg.setView(view) dlg.setCancelable(false) return dlg } override fun onResume() { super.onResume() showKeyboard() } override fun onPause() { super.onPause() hideKeyboard() } companion object { const val TAG = "save_as_dialog" fun newInstance(): SaveAsDialog { return SaveAsDialog() } } } companion object { const val CONNECTIONS_REQUEST_CODE = 1000 fun getStartIntent(context: Context): Intent { return Intent(context, SettingsActivity::class.java) } } } private class SaveAsTask(val db: ConnectionsDb, val connection: Connection, val overwrite: Boolean = false) : Tasks.Blocking<SaveAsTask.Result, Exception>() { enum class Result { Exists, Added } override fun exec(context: Context?): Result { val dao = db.connectionsDao() if (!overwrite) { val existing: Connection? = dao.query(connection.name) if (existing != null) { return Result.Exists } } dao.insert(connection) return Result.Added } companion object { const val NAME = "SaveAsTask" fun nameFor(connection: Connection): String { return "$NAME.${connection.name}" } fun match(name: String?): Boolean { return name != null && name.startsWith("$NAME.") } } }
bsd-3-clause
89085d510cc0900521a23662f01598bc
37.011385
117
0.615665
5.094608
false
false
false
false
DemonWav/MinecraftDev
src/main/kotlin/com/demonwav/mcdev/platform/mixin/inspection/MixinSuperClassInspection.kt
1
2752
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2018 minecraft-dev * * MIT License */ package com.demonwav.mcdev.platform.mixin.inspection import com.demonwav.mcdev.platform.mixin.util.isMixin import com.demonwav.mcdev.platform.mixin.util.mixinTargets import com.demonwav.mcdev.util.equivalentTo import com.demonwav.mcdev.util.ifEmpty import com.demonwav.mcdev.util.shortName import com.intellij.codeInspection.ProblemsHolder import com.intellij.psi.CommonClassNames import com.intellij.psi.JavaElementVisitor import com.intellij.psi.PsiClass import com.intellij.psi.PsiElementVisitor class MixinSuperClassInspection : MixinInspection() { override fun getStaticDescription() = "Reports invalid @Mixin super classes." override fun buildVisitor(holder: ProblemsHolder): PsiElementVisitor = Visitor(holder) private class Visitor(private val holder: ProblemsHolder) : JavaElementVisitor() { override fun visitClass(psiClass: PsiClass) { if (!psiClass.isMixin) { return } val superClass = psiClass.superClass ?: return if (superClass.qualifiedName == CommonClassNames.JAVA_LANG_OBJECT) { return } val targetClasses = psiClass.mixinTargets.ifEmpty { return } val superTargets = superClass.mixinTargets if (superTargets.isEmpty()) { // Super class must be a regular class in the hierarchy of the target class(es) for (targetClass in targetClasses) { if (targetClass equivalentTo superClass) { reportSuperClass(psiClass, "Cannot extend target class") } else if (!targetClass.isInheritor(superClass, true)) { reportSuperClass(psiClass, "Cannot find '${superClass.shortName}' in the hierarchy of target class '${targetClass.shortName}'") } } } else { // At least one of the target classes of the super mixin must be in the hierarchy of the target class(es) for (targetClass in targetClasses) { if (!superTargets.any { superTarget -> targetClass.isInheritor(superTarget, true) }) { reportSuperClass(psiClass, "Cannot find '${targetClass.shortName}' in the hierarchy of the super mixin") } } } } private fun reportSuperClass(psiClass: PsiClass, description: String) { holder.registerProblem(psiClass.extendsList?.referenceElements?.firstOrNull() ?: psiClass, description) } } }
mit
1a7b784d277932b2a7ee116c9e45d454
38.314286
128
0.634448
5.343689
false
false
false
false
dhis2/dhis2-android-sdk
core/src/main/java/org/hisp/dhis/android/core/trackedentity/ownership/ProgramOwnerPostCall.kt
1
3312
/* * 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.trackedentity.ownership import dagger.Reusable import javax.inject.Inject import org.hisp.dhis.android.core.arch.api.executors.internal.APICallExecutor import org.hisp.dhis.android.core.arch.db.stores.internal.ObjectWithoutUidStore import org.hisp.dhis.android.core.common.State import org.hisp.dhis.android.core.common.internal.DataStatePropagator import org.hisp.dhis.android.core.maintenance.D2Error @Reusable internal class ProgramOwnerPostCall @Inject constructor( private val ownershipService: OwnershipService, private val apiCallExecutor: APICallExecutor, private val programOwnerStore: ObjectWithoutUidStore<ProgramOwner>, private val dataStatePropagator: DataStatePropagator ) { fun uploadProgramOwner(programOwner: ProgramOwner): Boolean { return try { val response = apiCallExecutor.executeObjectCall( ownershipService.transfer( programOwner.trackedEntityInstance(), programOwner.program(), programOwner.ownerOrgUnit() ) ) @Suppress("MagicNumber") val isSuccessful = response.httpStatusCode() == 200 if (isSuccessful) { val syncedProgramOwner = programOwner.toBuilder().syncState(State.SYNCED).build() programOwnerStore.updateOrInsertWhere(syncedProgramOwner) dataStatePropagator.refreshTrackedEntityInstanceAggregatedSyncState( programOwner.trackedEntityInstance() ) } isSuccessful } catch (e: D2Error) { // TODO Create a record in TEI false } } }
bsd-3-clause
58d2e0e8095e6d364bef723a95d2b34e
45
97
0.720411
4.987952
false
false
false
false
iSoron/uhabits
uhabits-core/src/jvmMain/java/org/isoron/uhabits/core/models/WeekdayList.kt
1
2355
/* * Copyright (C) 2016-2021 Álinson Santos Xavier <[email protected]> * * This file is part of Loop Habit Tracker. * * Loop Habit Tracker 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. * * Loop Habit Tracker 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 org.isoron.uhabits.core.models import org.apache.commons.lang3.builder.EqualsBuilder import org.apache.commons.lang3.builder.HashCodeBuilder import java.util.Arrays class WeekdayList { private val weekdays: BooleanArray constructor(packedList: Int) { weekdays = BooleanArray(7) var current = 1 for (i in 0..6) { if (packedList and current != 0) weekdays[i] = true current = current shl 1 } } constructor(weekdays: BooleanArray?) { this.weekdays = Arrays.copyOf(weekdays, 7) } val isEmpty: Boolean get() { for (d in weekdays) if (d) return false return true } fun toArray(): BooleanArray { return weekdays.copyOf(7) } fun toInteger(): Int { var packedList = 0 var current = 1 for (i in 0..6) { if (weekdays[i]) packedList = packedList or current current = current shl 1 } return packedList } override fun equals(other: Any?): Boolean { if (this === other) return true if (other == null || javaClass != other.javaClass) return false val that = other as WeekdayList return EqualsBuilder().append(weekdays, that.weekdays).isEquals } override fun hashCode(): Int { return HashCodeBuilder(17, 37).append(weekdays).toHashCode() } override fun toString() = "{weekdays: [${weekdays.joinToString(separator = ",")}]}" companion object { val EVERY_DAY = WeekdayList(127) } }
gpl-3.0
85d19b029f3e959fc1ceac7c4158e49f
29.571429
87
0.646134
4.287796
false
false
false
false
dbrant/apps-android-wikipedia
app/src/main/java/org/wikipedia/feed/image/FeaturedImageCardView.kt
1
3446
package org.wikipedia.feed.image import android.content.Context import android.view.LayoutInflater import android.view.View import org.wikipedia.databinding.ViewCardFeaturedImageBinding import org.wikipedia.feed.view.DefaultFeedCardView import org.wikipedia.feed.view.FeedAdapter import org.wikipedia.richtext.RichTextUtil import org.wikipedia.views.ImageZoomHelper import org.wikipedia.views.ViewUtil class FeaturedImageCardView(context: Context) : DefaultFeedCardView<FeaturedImageCard>(context) { interface Callback { fun onShareImage(card: FeaturedImageCard) fun onDownloadImage(image: FeaturedImage) fun onFeaturedImageSelected(card: FeaturedImageCard) } private val binding = ViewCardFeaturedImageBinding.inflate(LayoutInflater.from(context), this, true) override var card: FeaturedImageCard? = null set(value) { field = value value?.let { image(it.baseImage()) description(it.description().orEmpty()) header(it) setClickListeners() } } override var callback: FeedAdapter.Callback? = null set(value) { field = value binding.viewFeaturedImageCardHeader.setCallback(value) } private fun image(image: FeaturedImage) { binding.viewFeaturedImageCardContentContainer.post { if (!isAttachedToWindow) { return@post } loadImage(image) } } private fun loadImage(image: FeaturedImage) { ImageZoomHelper.setViewZoomable(binding.viewFeaturedImageCardImage) ViewUtil.loadImage(binding.viewFeaturedImageCardImage, image.thumbnailUrl) binding.viewFeaturedImageCardImagePlaceholder.layoutParams = LayoutParams( binding.viewFeaturedImageCardContentContainer.width, ViewUtil.adjustImagePlaceholderHeight( binding.viewFeaturedImageCardContentContainer.width.toFloat(), image.thumbnail.width.toFloat(), image.thumbnail.height.toFloat() ) ) } private fun description(text: String) { binding.viewFeaturedImageCardImageDescription.text = RichTextUtil.stripHtml(text) } private fun setClickListeners() { binding.viewFeaturedImageCardContentContainer.setOnClickListener(CardClickListener()) binding.viewFeaturedImageCardDownloadButton.setOnClickListener(CardDownloadListener()) binding.viewFeaturedImageCardShareButton.setOnClickListener(CardShareListener()) } private fun header(card: FeaturedImageCard) { binding.viewFeaturedImageCardHeader.setTitle(card.title()) .setLangCode(null) .setCard(card) .setCallback(callback) } private inner class CardClickListener : OnClickListener { override fun onClick(v: View) { card?.let { callback?.onFeaturedImageSelected(it) } } } private inner class CardDownloadListener : OnClickListener { override fun onClick(v: View) { card?.let { callback?.onDownloadImage(it.baseImage()) } } } private inner class CardShareListener : OnClickListener { override fun onClick(v: View) { card?.let { callback?.onShareImage(it) } } } }
apache-2.0
66979d3a52f6185bf1151d89497e656a
33.118812
104
0.661927
5.504792
false
false
false
false
cdietze/klay
klay-jvm/src/main/kotlin/klay/jvm/JvmGL20.kt
1
42010
package klay.jvm import klay.core.buffers.Buffer import klay.core.buffers.ByteBuffer import klay.core.buffers.FloatBuffer import klay.core.buffers.IntBuffer import org.lwjgl.BufferUtils import org.lwjgl.opengl.* import org.lwjgl.system.MemoryUtil import java.io.UnsupportedEncodingException import java.nio.ByteOrder /** * An implementation of the [GL20] interface based on LWJGL3 and OpenGL ~3.0. */ class JvmGL20 : klay.core.GL20(JvmBuffers(), java.lang.Boolean.getBoolean("klay.glerrors")) { override fun glActiveTexture(texture: Int) { GL13.glActiveTexture(texture) } override fun glAttachShader(program: Int, shader: Int) { GL20.glAttachShader(program, shader) } override fun glBindAttribLocation(program: Int, index: Int, name: String) { GL20.glBindAttribLocation(program, index, name) } override fun glBindBuffer(target: Int, buffer: Int) { GL15.glBindBuffer(target, buffer) } override fun glBindFramebuffer(target: Int, framebuffer: Int) { EXTFramebufferObject.glBindFramebufferEXT(target, framebuffer) } override fun glBindRenderbuffer(target: Int, renderbuffer: Int) { EXTFramebufferObject.glBindRenderbufferEXT(target, renderbuffer) } override fun glBindTexture(target: Int, texture: Int) { GL11.glBindTexture(target, texture) } override fun glBlendColor(red: Float, green: Float, blue: Float, alpha: Float) { GL14.glBlendColor(red, green, blue, alpha) } override fun glBlendEquation(mode: Int) { GL14.glBlendEquation(mode) } override fun glBlendEquationSeparate(modeRGB: Int, modeAlpha: Int) { GL20.glBlendEquationSeparate(modeRGB, modeAlpha) } override fun glBlendFunc(sfactor: Int, dfactor: Int) { GL11.glBlendFunc(sfactor, dfactor) } override fun glBlendFuncSeparate(srcRGB: Int, dstRGB: Int, srcAlpha: Int, dstAlpha: Int) { GL14.glBlendFuncSeparate(srcRGB, dstRGB, srcAlpha, dstAlpha) } override fun glBufferData(target: Int, size: Int, data: Buffer, usage: Int) { // Limit the buffer to the given size, restoring it afterwards val oldLimit = data.limit() if (data is JvmByteBuffer) { data.limit(data.position() + size) GL15.glBufferData(target, data.nioBuffer, usage) } else if (data is JvmIntBuffer) { data.limit(data.position() + size / 4) GL15.glBufferData(target, data.nioBuffer, usage) } else if (data is JvmFloatBuffer) { data.limit(data.position() + size / 4) GL15.glBufferData(target, data.nioBuffer, usage) } else if (data is JvmDoubleBuffer) { data.limit(data.position() + size / 8) GL15.glBufferData(target, data.nioBuffer, usage) } else if (data is JvmShortBuffer) { data.limit(data.position() + size / 2) GL15.glBufferData(target, data.nioBuffer, usage) } data.limit(oldLimit) } override fun glBufferSubData(target: Int, offset: Int, size: Int, data: Buffer) { // Limit the buffer to the given size, restoring it afterwards val oldLimit = data.limit() if (data is JvmByteBuffer) { data.limit(data.position() + size) GL15.glBufferSubData(target, offset.toLong(), data.nioBuffer) } else if (data is JvmIntBuffer) { data.limit(data.position() + size / 4) GL15.glBufferSubData(target, offset.toLong(), data.nioBuffer) } else if (data is JvmFloatBuffer) { data.limit(data.position() + size / 4) GL15.glBufferSubData(target, offset.toLong(), data.nioBuffer) } else if (data is JvmDoubleBuffer) { data.limit(data.position() + size / 8) GL15.glBufferSubData(target, offset.toLong(), data.nioBuffer) } else if (data is JvmShortBuffer) { data.limit(data.position() + size / 2) GL15.glBufferSubData(target, offset.toLong(), data.nioBuffer) } data.limit(oldLimit) } override fun glCheckFramebufferStatus(target: Int): Int { return EXTFramebufferObject.glCheckFramebufferStatusEXT(target) } override fun glClear(mask: Int) { GL11.glClear(mask) } override fun glClearColor(red: Float, green: Float, blue: Float, alpha: Float) { GL11.glClearColor(red, green, blue, alpha) } override fun glClearDepthf(depth: Float) { GL11.glClearDepth(depth.toDouble()) } override fun glClearStencil(s: Int) { GL11.glClearStencil(s) } override fun glColorMask(red: Boolean, green: Boolean, blue: Boolean, alpha: Boolean) { GL11.glColorMask(red, green, blue, alpha) } override fun glCompileShader(shader: Int) { GL20.glCompileShader(shader) } override fun glCompressedTexImage2D(target: Int, level: Int, internalformat: Int, width: Int, height: Int, border: Int, imageSize: Int, data: Buffer) { throw UnsupportedOperationException("not implemented") } override fun glCompressedTexSubImage2D(target: Int, level: Int, xoffset: Int, yoffset: Int, width: Int, height: Int, format: Int, imageSize: Int, data: Buffer) { throw UnsupportedOperationException("not implemented") } override fun glCopyTexImage2D(target: Int, level: Int, internalformat: Int, x: Int, y: Int, width: Int, height: Int, border: Int) { GL11.glCopyTexImage2D(target, level, internalformat, x, y, width, height, border) } override fun glCopyTexSubImage2D(target: Int, level: Int, xoffset: Int, yoffset: Int, x: Int, y: Int, width: Int, height: Int) { GL11.glCopyTexSubImage2D(target, level, xoffset, yoffset, x, y, width, height) } override fun glCreateProgram(): Int { return GL20.glCreateProgram() } override fun glCreateShader(type: Int): Int { return GL20.glCreateShader(type) } override fun glCullFace(mode: Int) { GL11.glCullFace(mode) } override fun glDeleteBuffers(n: Int, buffers: IntBuffer) { GL15.glDeleteBuffers((buffers as JvmIntBuffer).nioBuffer) } override fun glDeleteFramebuffers(n: Int, framebuffers: IntBuffer) { EXTFramebufferObject.glDeleteFramebuffersEXT((framebuffers as JvmIntBuffer).nioBuffer) } override fun glDeleteProgram(program: Int) { GL20.glDeleteProgram(program) } override fun glDeleteRenderbuffers(n: Int, renderbuffers: IntBuffer) { EXTFramebufferObject.glDeleteRenderbuffersEXT((renderbuffers as JvmIntBuffer).nioBuffer) } override fun glDeleteShader(shader: Int) { GL20.glDeleteShader(shader) } override fun glDeleteTextures(n: Int, textures: IntBuffer) { GL11.glDeleteTextures((textures as JvmIntBuffer).nioBuffer) } override fun glDepthFunc(func: Int) { GL11.glDepthFunc(func) } override fun glDepthMask(flag: Boolean) { GL11.glDepthMask(flag) } override fun glDepthRangef(zNear: Float, zFar: Float) { GL11.glDepthRange(zNear.toDouble(), zFar.toDouble()) } override fun glDetachShader(program: Int, shader: Int) { GL20.glDetachShader(program, shader) } override fun glDisable(cap: Int) { GL11.glDisable(cap) } override fun glDisableVertexAttribArray(index: Int) { GL20.glDisableVertexAttribArray(index) } override fun glDrawArrays(mode: Int, first: Int, count: Int) { GL11.glDrawArrays(mode, first, count) } override fun glDrawElements(mode: Int, count: Int, type: Int, indices: Buffer) { if (indices is JvmShortBuffer && type == GL_UNSIGNED_SHORT) GL11.glDrawElements(mode, indices.nioBuffer) else if (indices is JvmByteBuffer && type == GL_UNSIGNED_SHORT) GL11.glDrawElements(mode, indices.nioBuffer.asShortBuffer()) // FIXME // yay... else if (indices is JvmByteBuffer && type == GL_UNSIGNED_BYTE) GL11.glDrawElements(mode, indices.nioBuffer) else throw RuntimeException( "Can't use " + indices.javaClass.name + " with this method. Use ShortBuffer or ByteBuffer instead. Blame LWJGL") } override fun glEnable(cap: Int) { GL11.glEnable(cap) } override fun glEnableVertexAttribArray(index: Int) { GL20.glEnableVertexAttribArray(index) } override fun glFinish() { GL11.glFinish() } override fun glFlush() { GL11.glFlush() } override fun glFramebufferRenderbuffer(target: Int, attachment: Int, renderbuffertarget: Int, renderbuffer: Int) { EXTFramebufferObject.glFramebufferRenderbufferEXT( target, attachment, renderbuffertarget, renderbuffer) } override fun glFramebufferTexture2D(target: Int, attachment: Int, textarget: Int, texture: Int, level: Int) { EXTFramebufferObject.glFramebufferTexture2DEXT(target, attachment, textarget, texture, level) } override fun glFrontFace(mode: Int) { GL11.glFrontFace(mode) } override fun glGenBuffers(n: Int, buffers: IntBuffer) { GL15.glGenBuffers((buffers as JvmIntBuffer).nioBuffer) } override fun glGenFramebuffers(n: Int, framebuffers: IntBuffer) { EXTFramebufferObject.glGenFramebuffersEXT((framebuffers as JvmIntBuffer).nioBuffer) } override fun glGenRenderbuffers(n: Int, renderbuffers: IntBuffer) { EXTFramebufferObject.glGenRenderbuffersEXT((renderbuffers as JvmIntBuffer).nioBuffer) } override fun glGenTextures(n: Int, textures: IntBuffer) { GL11.glGenTextures((textures as JvmIntBuffer).nioBuffer) } override fun glGenerateMipmap(target: Int) { EXTFramebufferObject.glGenerateMipmapEXT(target) } override fun glGetAttribLocation(program: Int, name: String): Int { return GL20.glGetAttribLocation(program, name) } override fun glGetBufferParameteriv(target: Int, pname: Int, params: IntBuffer) { GL15.glGetBufferParameteriv(target, pname, (params as JvmIntBuffer).nioBuffer) } override fun glGetError(): Int { return GL11.glGetError() } override fun glGetFloatv(pname: Int, params: FloatBuffer) { GL11.glGetFloatv(pname, (params as JvmFloatBuffer).nioBuffer) } override fun glGetFramebufferAttachmentParameteriv(target: Int, attachment: Int, pname: Int, params: IntBuffer) { EXTFramebufferObject.glGetFramebufferAttachmentParameterivEXT(target, attachment, pname, (params as JvmIntBuffer).nioBuffer) } override fun glGetIntegerv(pname: Int, params: IntBuffer) { GL11.glGetIntegerv(pname, (params as JvmIntBuffer).nioBuffer) } override fun glGetProgramInfoLog(program: Int): String { val buffer = java.nio.ByteBuffer.allocateDirect(1024 * 10) buffer.order(ByteOrder.nativeOrder()) val tmp = java.nio.ByteBuffer.allocateDirect(4) tmp.order(ByteOrder.nativeOrder()) val intBuffer = tmp.asIntBuffer() GL20.glGetProgramInfoLog(program, intBuffer, buffer) val numBytes = intBuffer.get(0) val bytes = ByteArray(numBytes) buffer.get(bytes) return String(bytes) } override fun glGetProgramiv(program: Int, pname: Int, params: IntBuffer) { GL20.glGetProgramiv(program, pname, (params as JvmIntBuffer).nioBuffer) } override fun glGetRenderbufferParameteriv(target: Int, pname: Int, params: IntBuffer) { EXTFramebufferObject.glGetRenderbufferParameterivEXT(target, pname, (params as JvmIntBuffer).nioBuffer) } override fun glGetShaderInfoLog(shader: Int): String { val buffer = java.nio.ByteBuffer.allocateDirect(1024 * 10) buffer.order(ByteOrder.nativeOrder()) val tmp = java.nio.ByteBuffer.allocateDirect(4) tmp.order(ByteOrder.nativeOrder()) val intBuffer = tmp.asIntBuffer() GL20.glGetShaderInfoLog(shader, intBuffer, buffer) val numBytes = intBuffer.get(0) val bytes = ByteArray(numBytes) buffer.get(bytes) return String(bytes) } override fun glGetShaderPrecisionFormat(shadertype: Int, precisiontype: Int, range: IntBuffer, precision: IntBuffer) { glGetShaderPrecisionFormat(shadertype, precisiontype, range, precision) } override fun glGetShaderiv(shader: Int, pname: Int, params: IntBuffer) { GL20.glGetShaderiv(shader, pname, (params as JvmIntBuffer).nioBuffer) } override fun glGetString(name: Int): String { return GL11.glGetString(name) } override fun glGetTexParameterfv(target: Int, pname: Int, params: FloatBuffer) { GL11.glGetTexParameterfv(target, pname, (params as JvmFloatBuffer).nioBuffer) } override fun glGetTexParameteriv(target: Int, pname: Int, params: IntBuffer) { GL11.glGetTexParameteriv(target, pname, (params as JvmIntBuffer).nioBuffer) } override fun glGetUniformLocation(program: Int, name: String): Int { return GL20.glGetUniformLocation(program, name) } override fun glGetUniformfv(program: Int, location: Int, params: FloatBuffer) { GL20.glGetUniformfv(program, location, (params as JvmFloatBuffer).nioBuffer) } override fun glGetUniformiv(program: Int, location: Int, params: IntBuffer) { GL20.glGetUniformiv(program, location, (params as JvmIntBuffer).nioBuffer) } override fun glGetVertexAttribfv(index: Int, pname: Int, params: FloatBuffer) { GL20.glGetVertexAttribfv(index, pname, (params as JvmFloatBuffer).nioBuffer) } override fun glGetVertexAttribiv(index: Int, pname: Int, params: IntBuffer) { GL20.glGetVertexAttribiv(index, pname, (params as JvmIntBuffer).nioBuffer) } override fun glHint(target: Int, mode: Int) { GL11.glHint(target, mode) } override fun glIsBuffer(buffer: Int): Boolean { return GL15.glIsBuffer(buffer) } override fun glIsEnabled(cap: Int): Boolean { return GL11.glIsEnabled(cap) } override fun glIsFramebuffer(framebuffer: Int): Boolean { return EXTFramebufferObject.glIsFramebufferEXT(framebuffer) } override fun glIsProgram(program: Int): Boolean { return GL20.glIsProgram(program) } override fun glIsRenderbuffer(renderbuffer: Int): Boolean { return EXTFramebufferObject.glIsRenderbufferEXT(renderbuffer) } override fun glIsShader(shader: Int): Boolean { return GL20.glIsShader(shader) } override fun glIsTexture(texture: Int): Boolean { return GL11.glIsTexture(texture) } override fun glLineWidth(width: Float) { GL11.glLineWidth(width) } override fun glLinkProgram(program: Int) { GL20.glLinkProgram(program) } override fun glPixelStorei(pname: Int, param: Int) { GL11.glPixelStorei(pname, param) } override fun glPolygonOffset(factor: Float, units: Float) { GL11.glPolygonOffset(factor, units) } override fun glReadPixels(x: Int, y: Int, width: Int, height: Int, format: Int, type: Int, pixels: Buffer) { if (pixels is JvmByteBuffer) GL11.glReadPixels(x, y, width, height, format, type, pixels.nioBuffer) else if (pixels is JvmShortBuffer) GL11.glReadPixels(x, y, width, height, format, type, pixels.nioBuffer) else if (pixels is JvmIntBuffer) GL11.glReadPixels(x, y, width, height, format, type, pixels.nioBuffer) else if (pixels is JvmFloatBuffer) GL11.glReadPixels(x, y, width, height, format, type, pixels.nioBuffer) else throw RuntimeException( "Can't use " + pixels.javaClass.name + " with this method. Use ByteBuffer, " + "ShortBuffer, IntBuffer or FloatBuffer instead. Blame LWJGL") } override fun glReleaseShaderCompiler() { // nothing to do here } override fun glRenderbufferStorage(target: Int, internalformat: Int, width: Int, height: Int) { EXTFramebufferObject.glRenderbufferStorageEXT(target, internalformat, width, height) } override fun glSampleCoverage(value: Float, invert: Boolean) { GL13.glSampleCoverage(value, invert) } override fun glScissor(x: Int, y: Int, width: Int, height: Int) { GL11.glScissor(x, y, width, height) } override fun glShaderBinary(n: Int, shaders: IntBuffer, binaryformat: Int, binary: Buffer, length: Int) { throw UnsupportedOperationException("unsupported, won't implement") } override fun glShaderSource(shader: Int, string: String) { GL20.glShaderSource(shader, string) } override fun glStencilFunc(func: Int, ref: Int, mask: Int) { GL11.glStencilFunc(func, ref, mask) } override fun glStencilFuncSeparate(face: Int, func: Int, ref: Int, mask: Int) { GL20.glStencilFuncSeparate(face, func, ref, mask) } override fun glStencilMask(mask: Int) { GL11.glStencilMask(mask) } override fun glStencilMaskSeparate(face: Int, mask: Int) { GL20.glStencilMaskSeparate(face, mask) } override fun glStencilOp(fail: Int, zfail: Int, zpass: Int) { GL11.glStencilOp(fail, zfail, zpass) } override fun glStencilOpSeparate(face: Int, fail: Int, zfail: Int, zpass: Int) { GL20.glStencilOpSeparate(face, fail, zfail, zpass) } override fun glTexImage2D(target: Int, level: Int, internalformat: Int, width: Int, height: Int, border: Int, format: Int, type: Int, pixels: Buffer?) { if (pixels == null) GL11.glTexImage2D(target, level, internalformat, width, height, border, format, type, null as java.nio.ByteBuffer?) else if (pixels is JvmByteBuffer) GL11.glTexImage2D(target, level, internalformat, width, height, border, format, type, pixels.nioBuffer) else if (pixels is JvmShortBuffer) GL11.glTexImage2D(target, level, internalformat, width, height, border, format, type, pixels.nioBuffer) else if (pixels is JvmIntBuffer) GL11.glTexImage2D(target, level, internalformat, width, height, border, format, type, pixels.nioBuffer) else if (pixels is JvmFloatBuffer) GL11.glTexImage2D(target, level, internalformat, width, height, border, format, type, pixels.nioBuffer) else if (pixels is JvmDoubleBuffer) GL11.glTexImage2D(target, level, internalformat, width, height, border, format, type, pixels.nioBuffer) else throw RuntimeException( "Can't use " + pixels.javaClass.name + " with this method. Use ByteBuffer, " + "ShortBuffer, IntBuffer, FloatBuffer or DoubleBuffer instead. Blame LWJGL") } override fun glTexParameterf(target: Int, pname: Int, param: Float) { GL11.glTexParameterf(target, pname, param) } override fun glTexParameterfv(target: Int, pname: Int, params: FloatBuffer) { GL11.glTexParameterfv(target, pname, (params as JvmFloatBuffer).nioBuffer) } override fun glTexParameteri(target: Int, pname: Int, param: Int) { GL11.glTexParameteri(target, pname, param) } override fun glTexParameteriv(target: Int, pname: Int, params: IntBuffer) { GL11.glTexParameteriv(target, pname, (params as JvmIntBuffer).nioBuffer) } override fun glTexSubImage2D(target: Int, level: Int, xoffset: Int, yoffset: Int, width: Int, height: Int, format: Int, type: Int, pixels: Buffer) { if (pixels is JvmByteBuffer) GL11.glTexSubImage2D(target, level, xoffset, yoffset, width, height, format, type, pixels.nioBuffer) else if (pixels is JvmShortBuffer) GL11.glTexSubImage2D(target, level, xoffset, yoffset, width, height, format, type, pixels.nioBuffer) else if (pixels is JvmIntBuffer) GL11.glTexSubImage2D(target, level, xoffset, yoffset, width, height, format, type, pixels.nioBuffer) else if (pixels is JvmFloatBuffer) GL11.glTexSubImage2D(target, level, xoffset, yoffset, width, height, format, type, pixels.nioBuffer) else if (pixels is JvmDoubleBuffer) GL11.glTexSubImage2D(target, level, xoffset, yoffset, width, height, format, type, pixels.nioBuffer) else throw RuntimeException( "Can't use " + pixels.javaClass.name + " with this method. Use ByteBuffer, " + "ShortBuffer, IntBuffer, FloatBuffer or DoubleBuffer instead. Blame LWJGL") } override fun glUniform1f(location: Int, x: Float) { GL20.glUniform1f(location, x) } override fun glUniform1fv(location: Int, count: Int, buffer: FloatBuffer) { val oldLimit = buffer.limit() buffer.limit(buffer.position() + count) GL20.glUniform1fv(location, (buffer as JvmFloatBuffer).nioBuffer) buffer.limit(oldLimit) } override fun glUniform1i(location: Int, x: Int) { GL20.glUniform1i(location, x) } override fun glUniform1iv(location: Int, count: Int, value: IntBuffer) { val oldLimit = value.limit() value.limit(value.position() + count) GL20.glUniform1iv(location, (value as JvmIntBuffer).nioBuffer) value.limit(oldLimit) } override fun glUniform2f(location: Int, x: Float, y: Float) { GL20.glUniform2f(location, x, y) } override fun glUniform2fv(location: Int, count: Int, value: FloatBuffer) { val oldLimit = value.limit() value.limit(value.position() + 2 * count) GL20.glUniform2fv(location, (value as JvmFloatBuffer).nioBuffer) value.limit(oldLimit) } override fun glUniform2i(location: Int, x: Int, y: Int) { GL20.glUniform2i(location, x, y) } override fun glUniform2iv(location: Int, count: Int, value: IntBuffer) { val oldLimit = value.limit() value.limit(value.position() + 2 * count) GL20.glUniform2iv(location, (value as JvmIntBuffer).nioBuffer) value.limit(oldLimit) } override fun glUniform3f(location: Int, x: Float, y: Float, z: Float) { GL20.glUniform3f(location, x, y, z) } override fun glUniform3fv(location: Int, count: Int, value: FloatBuffer) { val oldLimit = value.limit() value.limit(value.position() + 3 * count) GL20.glUniform3fv(location, (value as JvmFloatBuffer).nioBuffer) value.limit(oldLimit) } override fun glUniform3i(location: Int, x: Int, y: Int, z: Int) { GL20.glUniform3i(location, x, y, z) } override fun glUniform3iv(location: Int, count: Int, value: IntBuffer) { val oldLimit = value.limit() value.limit(value.position() + 3 * count) GL20.glUniform3iv(location, (value as JvmIntBuffer).nioBuffer) value.limit(oldLimit) } override fun glUniform4f(location: Int, x: Float, y: Float, z: Float, w: Float) { GL20.glUniform4f(location, x, y, z, w) } override fun glUniform4fv(location: Int, count: Int, value: FloatBuffer) { val oldLimit = value.limit() value.limit(value.position() + 4 * count) GL20.glUniform4fv(location, (value as JvmFloatBuffer).nioBuffer) value.limit(oldLimit) } override fun glUniform4i(location: Int, x: Int, y: Int, z: Int, w: Int) { GL20.glUniform4i(location, x, y, z, w) } override fun glUniform4iv(location: Int, count: Int, value: IntBuffer) { val oldLimit = value.limit() value.limit(value.position() + 4 * count) GL20.glUniform4iv(location, (value as JvmIntBuffer).nioBuffer) value.limit(oldLimit) } override fun glUniformMatrix2fv(location: Int, count: Int, transpose: Boolean, value: FloatBuffer) { val oldLimit = value.limit() value.limit(value.position() + 2 * 2 * count) GL20.glUniformMatrix2fv(location, transpose, (value as JvmFloatBuffer).nioBuffer) value.limit(oldLimit) } override fun glUniformMatrix3fv(location: Int, count: Int, transpose: Boolean, value: FloatBuffer) { val oldLimit = value.limit() value.limit(value.position() + 3 * 3 * count) GL20.glUniformMatrix3fv(location, transpose, (value as JvmFloatBuffer).nioBuffer) value.limit(oldLimit) } override fun glUniformMatrix4fv(location: Int, count: Int, transpose: Boolean, value: FloatBuffer) { val oldLimit = value.limit() value.limit(value.position() + 4 * 4 * count) GL20.glUniformMatrix4fv(location, transpose, (value as JvmFloatBuffer).nioBuffer) value.limit(oldLimit) } override fun glUseProgram(program: Int) { GL20.glUseProgram(program) } override fun glValidateProgram(program: Int) { GL20.glValidateProgram(program) } override fun glVertexAttrib1f(index: Int, x: Float) { GL20.glVertexAttrib1f(index, x) } override fun glVertexAttrib1fv(index: Int, values: FloatBuffer) { GL20.glVertexAttrib1f(index, (values as JvmFloatBuffer).nioBuffer.get()) } override fun glVertexAttrib2f(index: Int, x: Float, y: Float) { GL20.glVertexAttrib2f(index, x, y) } override fun glVertexAttrib2fv(index: Int, values: FloatBuffer) { val nioBuffer = (values as JvmFloatBuffer).nioBuffer GL20.glVertexAttrib2f(index, nioBuffer.get(), nioBuffer.get()) } override fun glVertexAttrib3f(index: Int, x: Float, y: Float, z: Float) { GL20.glVertexAttrib3f(index, x, y, z) } override fun glVertexAttrib3fv(index: Int, values: FloatBuffer) { val nioBuffer = (values as JvmFloatBuffer).nioBuffer GL20.glVertexAttrib3f(index, nioBuffer.get(), nioBuffer.get(), nioBuffer.get()) } override fun glVertexAttrib4f(index: Int, x: Float, y: Float, z: Float, w: Float) { GL20.glVertexAttrib4f(index, x, y, z, w) } override fun glVertexAttrib4fv(index: Int, values: FloatBuffer) { val nioBuffer = (values as JvmFloatBuffer).nioBuffer GL20.glVertexAttrib4f(index, nioBuffer.get(), nioBuffer.get(), nioBuffer.get(), nioBuffer.get()) } override fun glVertexAttribPointer(index: Int, size: Int, type: Int, normalized: Boolean, stride: Int, ptr: Buffer) { if (ptr is JvmFloatBuffer) { GL20.glVertexAttribPointer(index, size, type, normalized, stride, ptr.nioBuffer) } else if (ptr is JvmByteBuffer) { GL20.glVertexAttribPointer(index, size, type, normalized, stride, ptr.nioBuffer) } else if (ptr is JvmShortBuffer) { GL20.glVertexAttribPointer(index, size, type, normalized, stride, ptr.nioBuffer) } else if (ptr is JvmIntBuffer) { GL20.glVertexAttribPointer(index, size, type, normalized, stride, ptr.nioBuffer) } else { throw RuntimeException("NYI for " + ptr.javaClass) } } override fun glViewport(x: Int, y: Int, width: Int, height: Int) { GL11.glViewport(x, y, width, height) } override fun glDrawElements(mode: Int, count: Int, type: Int, indices: Int) { GL11.glDrawElements(mode, count, type, indices.toLong()) } override fun glVertexAttribPointer(index: Int, size: Int, type: Int, normalized: Boolean, stride: Int, ptr: Int) { GL20.glVertexAttribPointer(index, size, type, normalized, stride, ptr.toLong()) } override val platformGLExtensions: String get() = throw UnsupportedOperationException("NYI - not in LWJGL.") override val swapInterval: Int get() = throw UnsupportedOperationException("NYI - not in LWJGL.") override fun glClearDepth(depth: Double) { GL11.glClearDepth(depth) } override fun glCompressedTexImage2D(target: Int, level: Int, internalformat: Int, width: Int, height: Int, border: Int, imageSize: Int, data: Int) { GL13.glCompressedTexImage2D(target, level, internalformat, width, height, border, imageSize, data.toLong()) } override fun glCompressedTexImage3D(target: Int, level: Int, internalformat: Int, width: Int, height: Int, depth: Int, border: Int, imageSize: Int, data: ByteBuffer) { GL13.glCompressedTexImage3D(target, level, internalformat, width, height, depth, border, imageSize, MemoryUtil.memAddress((data as JvmByteBuffer).nioBuffer)) } override fun glCompressedTexImage3D(target: Int, level: Int, internalFormat: Int, width: Int, height: Int, depth: Int, border: Int, imageSize: Int, data: Int) { GL13.glCompressedTexImage3D( target, level, internalFormat, width, height, depth, border, imageSize, data.toLong()) } override fun glCompressedTexSubImage2D(target: Int, level: Int, xoffset: Int, yoffset: Int, width: Int, height: Int, format: Int, imageSize: Int, data: Int) { GL13.glCompressedTexSubImage2D( target, level, xoffset, yoffset, width, height, format, imageSize, data.toLong()) } override fun glCompressedTexSubImage3D(target: Int, level: Int, xoffset: Int, yoffset: Int, zoffset: Int, width: Int, height: Int, depth: Int, format: Int, imageSize: Int, data: ByteBuffer) { // imageSize is calculated in glCompressedTexSubImage3D. GL13.glCompressedTexSubImage3D(target, level, xoffset, yoffset, zoffset, width, height, depth, format, (data as JvmByteBuffer).nioBuffer) } override fun glCompressedTexSubImage3D(target: Int, level: Int, xoffset: Int, yoffset: Int, zoffset: Int, width: Int, height: Int, depth: Int, format: Int, imageSize: Int, data: Int) { val dataBuffer = BufferUtils.createByteBuffer(4) dataBuffer.putInt(data) dataBuffer.rewind() // imageSize is calculated in glCompressedTexSubImage3D. GL13.glCompressedTexSubImage3D( target, level, xoffset, yoffset, zoffset, width, height, depth, format, dataBuffer) } override fun glCopyTexSubImage3D(target: Int, level: Int, xoffset: Int, yoffset: Int, zoffset: Int, x: Int, y: Int, width: Int, height: Int) { GL12.glCopyTexSubImage3D(target, level, xoffset, yoffset, zoffset, x, y, width, height) } override fun glDepthRange(zNear: Double, zFar: Double) { GL11.glDepthRange(zNear, zFar) } override fun glFramebufferTexture3D(target: Int, attachment: Int, textarget: Int, texture: Int, level: Int, zoffset: Int) { EXTFramebufferObject.glFramebufferTexture3DEXT( target, attachment, textarget, texture, level, zoffset) } override fun glGetActiveAttrib(program: Int, index: Int, bufsize: Int, length: IntArray, lengthOffset: Int, size: IntArray, sizeOffset: Int, type: IntArray, typeOffset: Int, name: ByteArray, nameOffset: Int) { // http://www.khronos.org/opengles/sdk/docs/man/xhtml/glGetActiveAttrib.xml // Returns length, size, type, name bufs.resizeIntBuffer(2) // Return name, length val nameString = GL20.glGetActiveAttrib(program, index, BufferUtils.createIntBuffer(bufsize), (bufs.intBuffer as JvmIntBuffer).nioBuffer) try { val nameBytes = nameString.toByteArray(charset("UTF-8")) val nameLength = nameBytes.size - nameOffset bufs.setByteBuffer(nameBytes, nameOffset, nameLength) bufs.byteBuffer.get(name, nameOffset, nameLength) length[lengthOffset] = nameLength } catch (e: UnsupportedEncodingException) { e.printStackTrace() } // Return size, type bufs.intBuffer.get(size, 0, 1) bufs.intBuffer.get(type, 0, 1) } override fun glGetActiveAttrib(program: Int, index: Int, bufsize: Int, length: IntBuffer, size: IntBuffer, type: IntBuffer, name: ByteBuffer) { val typeTmp = BufferUtils.createIntBuffer(2) GL20.glGetActiveAttrib(program, index, BufferUtils.createIntBuffer(256), typeTmp) type.put(typeTmp.get(0)) type.rewind() } override fun glGetActiveUniform(program: Int, index: Int, bufsize: Int, length: IntArray, lengthOffset: Int, size: IntArray, sizeOffset: Int, type: IntArray, typeOffset: Int, name: ByteArray, nameOffset: Int) { bufs.resizeIntBuffer(2) // Return name, length val nameString = GL20.glGetActiveUniform(program, index, BufferUtils.createIntBuffer(256), (bufs.intBuffer as JvmIntBuffer).nioBuffer) try { val nameBytes = nameString.toByteArray(charset("UTF-8")) val nameLength = nameBytes.size - nameOffset bufs.setByteBuffer(nameBytes, nameOffset, nameLength) bufs.byteBuffer.get(name, nameOffset, nameLength) length[lengthOffset] = nameLength } catch (e: UnsupportedEncodingException) { e.printStackTrace() } // Return size, type bufs.intBuffer.get(size, 0, 1) bufs.intBuffer.get(type, 0, 1) } override fun glGetActiveUniform(program: Int, index: Int, bufsize: Int, length: IntBuffer, size: IntBuffer, type: IntBuffer, name: ByteBuffer) { val typeTmp = BufferUtils.createIntBuffer(2) GL20.glGetActiveAttrib(program, index, BufferUtils.createIntBuffer(256), typeTmp) type.put(typeTmp.get(0)) type.rewind() } override fun glGetAttachedShaders(program: Int, maxcount: Int, count: IntBuffer, shaders: IntBuffer) { GL20.glGetAttachedShaders(program, (count as JvmIntBuffer).nioBuffer, (shaders as JvmIntBuffer).nioBuffer) } override fun glGetBoolean(pname: Int): Boolean { return GL11.glGetBoolean(pname) } override fun glGetBooleanv(pname: Int, params: ByteBuffer) { GL11.glGetBooleanv(pname, (params as JvmByteBuffer).nioBuffer) } override fun glGetBoundBuffer(target: Int): Int { throw UnsupportedOperationException("glGetBoundBuffer not supported in GLES 2.0 or LWJGL.") } override fun glGetFloat(pname: Int): Float { return GL11.glGetFloat(pname) } override fun glGetInteger(pname: Int): Int { return GL11.glGetInteger(pname) } override fun glGetProgramBinary(program: Int, bufSize: Int, length: IntBuffer, binaryFormat: IntBuffer, binary: ByteBuffer) { GL41.glGetProgramBinary(program, (length as JvmIntBuffer).nioBuffer, (binaryFormat as JvmIntBuffer).nioBuffer, (binary as JvmByteBuffer).nioBuffer) } override fun glGetProgramInfoLog(program: Int, bufsize: Int, length: IntBuffer, infolog: ByteBuffer) { val buffer = java.nio.ByteBuffer.allocateDirect(1024 * 10) buffer.order(ByteOrder.nativeOrder()) val tmp = java.nio.ByteBuffer.allocateDirect(4) tmp.order(ByteOrder.nativeOrder()) val intBuffer = tmp.asIntBuffer() GL20.glGetProgramInfoLog(program, intBuffer, buffer) } override fun glGetShaderInfoLog(shader: Int, bufsize: Int, length: IntBuffer, infolog: ByteBuffer) { GL20.glGetShaderInfoLog(shader, (length as JvmIntBuffer).nioBuffer, (infolog as JvmByteBuffer).nioBuffer) } override fun glGetShaderPrecisionFormat(shadertype: Int, precisiontype: Int, range: IntArray, rangeOffset: Int, precision: IntArray, precisionOffset: Int) { throw UnsupportedOperationException("NYI") } override fun glGetShaderSource(shader: Int, bufsize: Int, length: IntArray, lengthOffset: Int, source: ByteArray, sourceOffset: Int) { throw UnsupportedOperationException("NYI") } override fun glGetShaderSource(shader: Int, bufsize: Int, length: IntBuffer, source: ByteBuffer) { throw UnsupportedOperationException("NYI") } override fun glIsVBOArrayEnabled(): Boolean { throw UnsupportedOperationException("NYI - not in LWJGL.") } override fun glIsVBOElementEnabled(): Boolean { throw UnsupportedOperationException("NYI - not in LWJGL.") } override fun glMapBuffer(target: Int, access: Int): ByteBuffer { return JvmByteBuffer(GL15.glMapBuffer(target, access, null)) } override fun glProgramBinary(program: Int, binaryFormat: Int, binary: ByteBuffer, length: Int) { // Length is calculated in glProgramBinary. GL41.glProgramBinary(program, binaryFormat, (binary as JvmByteBuffer).nioBuffer) } override fun glReadPixels(x: Int, y: Int, width: Int, height: Int, format: Int, type: Int, pixelsBufferOffset: Int) { GL11.glReadPixels(x, y, width, height, format, type, pixelsBufferOffset.toLong()) } override fun glShaderBinary(n: Int, shaders: IntArray, offset: Int, binaryformat: Int, binary: Buffer, length: Int) { throw UnsupportedOperationException("NYI") } override fun glShaderSource(shader: Int, count: Int, strings: Array<String>, length: IntArray, lengthOffset: Int) { for (str in strings) GL20.glShaderSource(shader, str) } override fun glShaderSource(shader: Int, count: Int, strings: Array<String>, length: IntBuffer) { for (str in strings) GL20.glShaderSource(shader, str) } override fun glTexImage2D(target: Int, level: Int, internalFormat: Int, width: Int, height: Int, border: Int, format: Int, type: Int, pixels: Int) { GL11.glTexImage2D(target, level, internalFormat, width, height, border, format, type, pixels.toLong()) } override fun glTexImage3D(target: Int, level: Int, internalFormat: Int, width: Int, height: Int, depth: Int, border: Int, format: Int, type: Int, pixels: Buffer) { if (pixels !is JvmByteBuffer) throw UnsupportedOperationException("Buffer must be a ByteBuffer.") GL12.glTexImage3D(target, level, internalFormat, width, height, depth, border, format, type, pixels.nioBuffer) } override fun glTexImage3D(target: Int, level: Int, internalFormat: Int, width: Int, height: Int, depth: Int, border: Int, format: Int, type: Int, pixels: Int) { GL12.glTexImage3D(target, level, internalFormat, width, height, depth, border, format, type, pixels.toLong()) } override fun glTexSubImage2D(target: Int, level: Int, xoffset: Int, yoffset: Int, width: Int, height: Int, format: Int, type: Int, pixels: Int) { GL11.glTexSubImage2D(target, level, xoffset, yoffset, width, height, format, type, pixels.toLong()) } override fun glTexSubImage3D(target: Int, level: Int, xoffset: Int, yoffset: Int, zoffset: Int, width: Int, height: Int, depth: Int, format: Int, type: Int, pixels: ByteBuffer) { GL12.glTexSubImage3D(target, level, xoffset, yoffset, zoffset, width, height, depth, format, type, (pixels as JvmByteBuffer).nioBuffer) } override fun glTexSubImage3D(target: Int, level: Int, xoffset: Int, yoffset: Int, zoffset: Int, width: Int, height: Int, depth: Int, format: Int, type: Int, pixels: Int) { val byteBuffer = BufferUtils.createByteBuffer(1) byteBuffer.putInt(pixels) byteBuffer.rewind() GL12.glTexSubImage3D(target, level, xoffset, yoffset, zoffset, width, height, depth, format, type, byteBuffer) } override fun glUnmapBuffer(target: Int): Boolean { return GL15.glUnmapBuffer(target) } override fun hasGLSL(): Boolean { throw UnsupportedOperationException("NYI - not in LWJGL.") } override fun isExtensionAvailable(extension: String): Boolean { throw UnsupportedOperationException("NYI - not in LWJGL.") } override fun isFunctionAvailable(function: String): Boolean { throw UnsupportedOperationException("NYI - not in LWJGL.") } }
apache-2.0
4bdb85e88f7a157ba3539d86f46f0e7f
39.550193
155
0.636444
4.439396
false
false
false
false
dahlstrom-g/intellij-community
platform/build-scripts/icons/src/org/jetbrains/intellij/build/images/util.kt
5
3949
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.intellij.build.images import com.intellij.openapi.application.PathManager import com.intellij.openapi.util.io.FileUtilRt import com.intellij.ui.svg.SvgTranscoder import com.intellij.ui.svg.createSvgDocument import com.intellij.util.io.DigestUtil import java.awt.Dimension import java.awt.image.BufferedImage import java.io.File import java.io.IOException import java.math.BigInteger import java.nio.file.Files import java.nio.file.Path import java.nio.file.Paths import javax.imageio.ImageIO internal val File.children: List<File> get() = if (isDirectory) listFiles()?.toList() ?: emptyList() else emptyList() internal fun isImage(file: Path, iconsOnly: Boolean): Boolean { return if (iconsOnly) isIcon(file) else isImage(file) } // allow other project path setups to generate Android Icons var androidIcons: Path = Paths.get(PathManager.getCommunityHomePath(), "android/artwork/resources") internal fun isIcon(file: Path): Boolean { if (!isImage(file)) { return false } val size = imageSize(file) ?: return false if (file.startsWith(androidIcons)) { return true } return size.height == size.width || size.height <= 100 && size.width <= 100 } internal fun isImage(file: Path) = ImageExtension.fromName(file.fileName.toString()) != null internal fun isImage(file: File) = ImageExtension.fromName(file.name) != null internal fun imageSize(file: Path, failOnMalformedImage: Boolean = false): Dimension? { val image = try { loadImage(file, failOnMalformedImage) } catch (e: Exception) { if (failOnMalformedImage) throw e null } if (image == null) { if (failOnMalformedImage) error("Can't load $file") println("WARNING: can't load $file") return null } val width = image.width val height = image.height return Dimension(width, height) } private fun loadImage(file: Path, failOnMalformedImage: Boolean): BufferedImage? { if (file.toString().endsWith(".svg")) { // don't mask any exception for svg file Files.newInputStream(file).use { try { return SvgTranscoder.createImage(1f, createSvgDocument(null, it), null) } catch (e: Exception) { throw IOException("Cannot decode $file", e) } } } try { return Files.newInputStream(file).buffered().use { ImageIO.read(it) } } catch (e: Exception) { if (failOnMalformedImage) throw e return null } } internal fun md5(file: Path): String { val hash = DigestUtil.md5().digest(Files.readAllBytes(file)) return BigInteger(hash).abs().toString(16) } internal enum class ImageType(private val suffix: String) { BASIC(""), RETINA("@2x"), DARCULA("_dark"), RETINA_DARCULA("@2x_dark"); companion object { fun getBasicName(suffix: String, prefix: String): String { return "$prefix/${stripSuffix(FileUtilRt.getNameWithoutExtension(suffix))}" } fun fromFile(file: Path): ImageType { return fromName(FileUtilRt.getNameWithoutExtension(file.fileName.toString())) } private fun fromName(name: String): ImageType { return when { name.endsWith(RETINA_DARCULA.suffix) -> RETINA_DARCULA name.endsWith(RETINA.suffix) -> RETINA name.endsWith(DARCULA.suffix) -> DARCULA else -> BASIC } } fun stripSuffix(name: String): String { return name.removeSuffix(fromName(name).suffix) } } } internal enum class ImageExtension(private val suffix: String) { PNG(".png"), SVG(".svg"), GIF(".gif"); companion object { fun fromFile(file: Path) = fromName(file.fileName.toString()) fun fromName(name: String): ImageExtension? { if (name.endsWith(PNG.suffix)) return PNG if (name.endsWith(SVG.suffix)) return SVG if (name.endsWith(GIF.suffix)) return GIF return null } } }
apache-2.0
a5bb87b7265bf6f6d2173e897a6af61c
28.924242
140
0.697898
3.902174
false
false
false
false
dahlstrom-g/intellij-community
plugins/settings-sync/src/com/intellij/settingsSync/SettingsSyncTroubleshootingAction.kt
1
15267
package com.intellij.settingsSync import com.intellij.CommonBundle import com.intellij.icons.AllIcons import com.intellij.ide.IdeBundle import com.intellij.ide.actions.RevealFileAction import com.intellij.ide.actions.ShowLogAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.project.DumbAwareAction import com.intellij.openapi.project.Project import com.intellij.openapi.ui.DialogBuilder import com.intellij.openapi.ui.DialogWrapper import com.intellij.openapi.ui.Messages import com.intellij.openapi.util.NlsSafe import com.intellij.openapi.util.ThrowableComputable import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.util.text.StringUtil import com.intellij.settingsSync.auth.SettingsSyncAuthService import com.intellij.ui.JBAccountInfoService import com.intellij.ui.components.JBLabel import com.intellij.ui.components.JBScrollPane import com.intellij.ui.dsl.builder.Panel import com.intellij.ui.dsl.builder.Row import com.intellij.ui.dsl.builder.RowLayout import com.intellij.ui.dsl.builder.panel import com.intellij.util.io.Compressor import com.intellij.util.ui.JBUI import com.intellij.util.ui.UIUtil import com.jetbrains.cloudconfig.FileVersionInfo import org.jetbrains.annotations.Nls import java.awt.BorderLayout import java.io.File import java.text.SimpleDateFormat import java.util.* import javax.swing.Action import javax.swing.JButton import javax.swing.JComponent import javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED import javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED internal class SettingsSyncTroubleshootingAction : DumbAwareAction() { override fun update(e: AnActionEvent) { e.presentation.isEnabledAndVisible = isSettingsSyncEnabledByKey() } override fun actionPerformed(e: AnActionEvent) { val remoteCommunicator = SettingsSyncMain.getInstance().getRemoteCommunicator() if (remoteCommunicator !is CloudConfigServerCommunicator) { Messages.showErrorDialog(e.project, SettingsSyncBundle.message("troubleshooting.dialog.error.wrong.configuration", remoteCommunicator::class), SettingsSyncBundle.message("troubleshooting.dialog.title")) return } try { val version = ProgressManager.getInstance().runProcessWithProgressSynchronously(ThrowableComputable { val fileVersion = remoteCommunicator.getLatestVersion() if (fileVersion == null) { null } else { val zip = downloadToZip(fileVersion, remoteCommunicator) Version(fileVersion, SettingsSnapshotZipSerializer.extractFromZip(zip!!.toPath())) } }, SettingsSyncBundle.message("troubleshooting.loading.info.progress.dialog.title"), false, e.project) TroubleshootingDialog(e.project, remoteCommunicator, version).show() } catch (ex: Exception) { LOG.error(ex) if (Messages.OK == Messages.showOkCancelDialog(e.project, SettingsSyncBundle.message("troubleshooting.dialog.error.check.log.file.for.errors"), SettingsSyncBundle.message("troubleshooting.dialog.error.loading.info.failed"), ShowLogAction.getActionName(), CommonBundle.getCancelButtonText(), null)) { ShowLogAction.showLog() } } } private data class Version(val fileVersion: FileVersionInfo, val snapshot: SettingsSnapshot?) private class TroubleshootingDialog(val project: Project?, val remoteCommunicator: CloudConfigServerCommunicator, val latestVersion: Version?) : DialogWrapper(project, true) { val userData = SettingsSyncAuthService.getInstance().getUserData() init { title = SettingsSyncBundle.message("troubleshooting.dialog.title") init() } override fun createActions(): Array<Action> { setCancelButtonText(CommonBundle.getCloseButtonText()) cancelAction.putValue(DEFAULT_ACTION, true) return arrayOf(cancelAction) } override fun createCenterPanel(): JComponent { return panel { statusRow() serverUrlRow() loginNameRow(userData) emailRow(userData) appInfoRow() if (latestVersion == null) { row { label(SettingsSyncBundle.message("troubleshooting.dialog.no.file.on.server", SETTINGS_SYNC_SNAPSHOT_ZIP)) } } else { row { label(SettingsSyncBundle.message("troubleshooting.dialog.latest.version.label", SETTINGS_SYNC_SNAPSHOT_ZIP)).bold() } versionRow(latestVersion) row { button(SettingsSyncBundle.message("troubleshooting.dialog.show.history.button")) { showHistoryDialog(project, remoteCommunicator, userData?.loginName!!) } button(SettingsSyncBundle.message("troubleshooting.dialog.delete.button")) { deleteFile(project, remoteCommunicator) } } } } } private fun Panel.statusRow() = row { label(SettingsSyncBundle.message("troubleshooting.dialog.local.status.label")) label(if (SettingsSyncSettings.getInstance().syncEnabled) IdeBundle.message("plugins.configurable.enabled") else IdeBundle.message("plugins.configurable.disabled")) }.layout(RowLayout.PARENT_GRID) private fun Panel.serverUrlRow() = row { label(SettingsSyncBundle.message("troubleshooting.dialog.server.url.label")) copyableLabel(CloudConfigServerCommunicator.url) }.layout(RowLayout.PARENT_GRID) private fun Panel.loginNameRow(userData: JBAccountInfoService.JBAData?) = row { label(SettingsSyncBundle.message("troubleshooting.dialog.login.label")) copyableLabel(userData?.loginName) }.layout(RowLayout.PARENT_GRID) private fun Panel.emailRow(userData: JBAccountInfoService.JBAData?) = row { label(SettingsSyncBundle.message("troubleshooting.dialog.email.label")) copyableLabel(userData?.email) }.layout(RowLayout.PARENT_GRID) private fun Panel.appInfoRow() { val appInfo = getLocalApplicationInfo() row { label(SettingsSyncBundle.message("troubleshooting.dialog.applicationId.label")) copyableLabel(appInfo.applicationId) }.layout(RowLayout.PARENT_GRID) row { label(SettingsSyncBundle.message("troubleshooting.dialog.username.label")) copyableLabel(appInfo.userName) }.layout(RowLayout.PARENT_GRID) row { label(SettingsSyncBundle.message("troubleshooting.dialog.hostname.label")) copyableLabel(appInfo.hostName) }.layout(RowLayout.PARENT_GRID) row { label(SettingsSyncBundle.message("troubleshooting.dialog.configFolder.label")) copyableLabel(appInfo.configFolder) }.layout(RowLayout.PARENT_GRID) } private fun String.shorten() = StringUtil.shortenTextWithEllipsis(this, 12, 0, true) private fun Panel.versionRow(version: Version) = row { label(SettingsSyncBundle.message("troubleshooting.dialog.version.date.label")) copyableLabel(formatDate(version.fileVersion.modifiedDate)) label(SettingsSyncBundle.message("troubleshooting.dialog.version.id.label")) copyableLabel(version.fileVersion.versionId.shorten()) val snapshot = version.snapshot if (snapshot != null) { label(SettingsSyncBundle.message("troubleshooting.dialog.machineInfo.label")) val appInfo = snapshot.metaInfo.appInfo val text = if (appInfo != null) { val appId = appInfo.applicationId val thisOrThat = if (appId == SettingsSyncLocalSettings.getInstance().applicationId) "[this] " else "[other]" "$thisOrThat ${appId.toString().shorten()} - ${appInfo.userName} - ${appInfo.hostName} - ${appInfo.configFolder}" } else { "Unknown" } copyableLabel(text) } actionButton(object : DumbAwareAction(AllIcons.Actions.Download) { override fun actionPerformed(e: AnActionEvent) { downloadVersion(version.fileVersion, e.project) } }) } private fun downloadVersion(version: FileVersionInfo, project: Project?) { val zipFile = ProgressManager.getInstance().runProcessWithProgressSynchronously(ThrowableComputable<File?, Exception> { downloadToZip(version, remoteCommunicator) }, SettingsSyncBundle.message("troubleshooting.dialog.downloading.settings.from.server.progress.title"), false, project) if (zipFile != null) { showFileDownloadedMessage(zipFile, SettingsSyncBundle.message("troubleshooting.dialog.successfully.downloaded.message")) } else { if (Messages.OK == Messages.showOkCancelDialog(contentPane, SettingsSyncBundle.message("troubleshooting.dialog.error.check.log.file.for.errors"), SettingsSyncBundle.message("troubleshooting.dialog.error.download.zip.file.failed"), ShowLogAction.getActionName(), CommonBundle.getCancelButtonText(), null)) { ShowLogAction.showLog() } } } private fun showFileDownloadedMessage(zipFile: File, @Nls message: String) { if (Messages.OK == Messages.showOkCancelDialog(contentPane, message, "", RevealFileAction.getActionName(), CommonBundle.getCancelButtonText(), null)) { RevealFileAction.openFile(zipFile) } } private fun showHistoryDialog(project: Project?, remoteCommunicator: CloudConfigServerCommunicator, loginName: String) { val history = ProgressManager.getInstance().runProcessWithProgressSynchronously(ThrowableComputable { remoteCommunicator.fetchHistory().mapIndexed { index, fileVersion -> val snapshot = if (index < 10) { val zip = downloadToZip(fileVersion, remoteCommunicator) SettingsSnapshotZipSerializer.extractFromZip(zip!!.toPath()) } else null Version(fileVersion, snapshot) } }, SettingsSyncBundle.message("troubleshooting.fetching.history.progress.title"), false, project) val dialogBuilder = DialogBuilder(contentPane).title(SettingsSyncBundle.message("troubleshooting.settings.history.dialog.title")) val historyPanel = panel { for (version in history) { versionRow(version).layout(RowLayout.PARENT_GRID) } }.withBorder(JBUI.Borders.empty(UIUtil.DEFAULT_VGAP, UIUtil.DEFAULT_HGAP, UIUtil.DEFAULT_VGAP, UIUtil.DEFAULT_HGAP)) val button = JButton(SettingsSyncBundle.message("troubleshooting.dialog.download.full.history.button")) button.addActionListener { downloadFullHistory(project, remoteCommunicator, history, loginName) } val scrollPanel = JBScrollPane(historyPanel, VERTICAL_SCROLLBAR_AS_NEEDED, HORIZONTAL_SCROLLBAR_AS_NEEDED) val mainPanel = JBUI.Panels.simplePanel() mainPanel.add(scrollPanel, BorderLayout.CENTER) mainPanel.add(button, BorderLayout.SOUTH) dialogBuilder.centerPanel(mainPanel) dialogBuilder.addCloseButton() dialogBuilder.show() } private fun downloadFullHistory(project: Project?, remoteCommunicator: CloudConfigServerCommunicator, history: List<Version>, loginName: String) { val compoundZip = ProgressManager.getInstance().runProcessWithProgressSynchronously(ThrowableComputable { val fileName = "settings-server-history-${FileUtil.sanitizeFileName(loginName)}-${formatDate(Date())}.zip" val zipFile = FileUtil.createTempFile(fileName, null) val indicator = ProgressManager.getInstance().progressIndicator indicator.isIndeterminate = false Compressor.Zip(zipFile).use { zip -> for ((step, version) in history.withIndex()) { indicator.checkCanceled() indicator.fraction = (step.toDouble() / history.size) val fileVersion = version.fileVersion val stream = remoteCommunicator.downloadSnapshot(fileVersion) if (stream != null) { zip.addFile(getSnapshotFileName(fileVersion), stream) } else { LOG.warn("Couldn't download snapshot for version made on ${fileVersion.modifiedDate}") } } } zipFile }, SettingsSyncBundle.message("troubleshooting.fetching.history.progress.title"), true, project) showFileDownloadedMessage(compoundZip, SettingsSyncBundle.message("troubleshooting.dialog.download.full.history.success.message")) } private fun deleteFile(project: Project?, remoteCommunicator: CloudConfigServerCommunicator) { val choice = Messages.showOkCancelDialog(contentPane, SettingsSyncBundle.message("troubleshooting.dialog.delete.confirmation.message"), SettingsSyncBundle.message("troubleshooting.dialog.delete.confirmation.title"), IdeBundle.message("button.delete"), CommonBundle.getCancelButtonText(), null) if (choice == Messages.OK) { try { ProgressManager.getInstance().runProcessWithProgressSynchronously(ThrowableComputable { SettingsSyncSettings.getInstance().syncEnabled = false remoteCommunicator.delete() }, SettingsSyncBundle.message("troubleshooting.delete.file.from.server.progress.title"), false, project) } catch (e: Exception) { LOG.warn("Couldn't delete $SETTINGS_SYNC_SNAPSHOT_ZIP from server", e) Messages.showErrorDialog(contentPane, e.message, SettingsSyncBundle.message("troubleshooting.dialog.delete.confirmation.title")) } } } private fun Row.copyableLabel(@NlsSafe text: Any?) = cell(JBLabel(text.toString()).apply { setCopyable(true) }) } companion object { val LOG = logger<SettingsSyncTroubleshootingAction>() } } private fun downloadToZip(version: FileVersionInfo, remoteCommunicator: CloudConfigServerCommunicator): File? { val stream = remoteCommunicator.downloadSnapshot(version) ?: return null try { val tempFile = FileUtil.createTempFile(getSnapshotFileName(version), null) FileUtil.writeToFile(tempFile, stream.readAllBytes()) return tempFile } catch (e: Throwable) { SettingsSyncTroubleshootingAction.LOG.error(e) return null } } private fun getSnapshotFileName(version: FileVersionInfo) = "settings-sync-snapshot-${formatDate(version.modifiedDate)}.zip" private fun formatDate(date: Date) = SimpleDateFormat("yyyy-MM-dd HH-mm-ss", Locale.US).format(date)
apache-2.0
cac005b2a4a3ef4500f2959228973b40
43.902941
140
0.684286
5.280872
false
false
false
false
securityfirst/Umbrella_android
app/src/main/java/org/secfirst/umbrella/data/database/content/entity.kt
1
2350
package org.secfirst.umbrella.data.database.content import android.content.Context import android.content.Intent import android.net.Uri import org.apache.commons.text.WordUtils import org.secfirst.advancedsearch.models.SearchResult import org.secfirst.umbrella.data.database.checklist.Content import org.secfirst.umbrella.data.database.form.Form import org.secfirst.umbrella.data.database.lesson.Module import org.secfirst.umbrella.data.database.reader.FeedSource import org.secfirst.umbrella.data.database.reader.RSS class ContentData(val modules: MutableList<Module> = arrayListOf(), val forms: MutableList<Form> = arrayListOf()) fun Content.toSearchResult(): SearchResult { val segments = this.checklist?.id.orEmpty().split("/") return SearchResult("${WordUtils.capitalizeFully(segments[1])} - ${WordUtils.capitalizeFully(segments[2])}", "" ) { c: Context -> val withoutLanguage = this.checklist?.id?.split("/")?.drop(1)?.joinToString("/") c.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse("umbrella://$withoutLanguage"))) } } fun createFeedSources(): List<FeedSource> { val feedSources = mutableListOf<FeedSource>() val feedSource1 = FeedSource("ReliefWeb / United Nations (UN)", false, 0) val feedSource3 = FeedSource("Foreign and Commonwealth Office", false, 2) val feedSource4 = FeedSource("Centres for Disease Control", false, 3) val feedSource5 = FeedSource("Global Disaster Alert Coordination System", false, 4) val feedSource6 = FeedSource("US State Department Country Warnings", false, 5) feedSources.add(feedSource1) feedSources.add(feedSource3) feedSources.add(feedSource4) feedSources.add(feedSource5) feedSources.add(feedSource6) return feedSources } fun createDefaultRSS(): List<RSS> { val rssList = mutableListOf<RSS>() val rss1 = RSS("https://threatpost.com/feed/") val rss2 = RSS("https://krebsonsecurity.com/feed/") val rss3 = RSS("http://feeds.bbci.co.uk/news/world/rss.xml?edition=uk") val rss4 = RSS("http://rss.cnn.com/rss/edition.rss") val rss5 = RSS("https://www.aljazeera.com/xml/rss/all.xml") val rss6 = RSS("https://www.theguardian.com/world/rss") rssList.add(rss1) rssList.add(rss2) rssList.add(rss3) rssList.add(rss4) rssList.add(rss5) rssList.add(rss6) return rssList }
gpl-3.0
34cfc56c11efe94776e2ef955fd1ab4f
39.517241
115
0.731064
3.766026
false
false
false
false
paplorinc/intellij-community
platform/platform-impl/src/com/intellij/internal/statistic/DeviceIdManager.kt
2
2386
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.internal.statistic import com.intellij.openapi.application.PermanentInstallationID import com.intellij.openapi.application.ex.ApplicationInfoEx import com.intellij.openapi.application.impl.ApplicationInfoImpl import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.util.SystemInfo import com.intellij.openapi.util.text.StringUtil import java.text.SimpleDateFormat import java.util.* import java.util.prefs.Preferences object DeviceIdManager { private val LOG = Logger.getInstance(DeviceIdManager::class.java) private const val DEVICE_ID_SHARED_FILE = "PermanentDeviceId" private const val DEVICE_ID_PREFERENCE_KEY = "device_id" fun getOrGenerateId(): String { val appInfo = ApplicationInfoImpl.getShadowInstance() val prefs = getPreferences(appInfo) var deviceId = prefs.get(DEVICE_ID_PREFERENCE_KEY, null) if (StringUtil.isEmptyOrSpaces(deviceId)) { deviceId = generateId(Calendar.getInstance(), getOSChar()) prefs.put(DEVICE_ID_PREFERENCE_KEY, deviceId) LOG.info("Generating new Device ID") } if (appInfo.isVendorJetBrains && SystemInfo.isWindows) { deviceId = PermanentInstallationID.syncWithSharedFile(DEVICE_ID_SHARED_FILE, deviceId, prefs, DEVICE_ID_PREFERENCE_KEY) } return deviceId } private fun getPreferences(appInfo: ApplicationInfoEx): Preferences { val companyName = appInfo.shortCompanyName val name = if (StringUtil.isEmptyOrSpaces(companyName)) "jetbrains" else companyName.toLowerCase(Locale.US) return Preferences.userRoot().node(name) } /** * Device id is generating by concatenating following values: * Current date, written in format ddMMyy, where year coerced between 2000 and 2099 * Character, representing user's OS (see [getOSChar]) * [toString] call on representation of [UUID.randomUUID] */ fun generateId(calendar: Calendar, OSChar: Char): String { calendar.set(Calendar.YEAR, calendar.get(Calendar.YEAR).coerceIn(2000, 2099)) return SimpleDateFormat("ddMMyy").format(calendar.time) + OSChar + UUID.randomUUID().toString() } private fun getOSChar() = if (SystemInfo.isWindows) '1' else if (SystemInfo.isMac) '2' else if (SystemInfo.isLinux) '3' else '0' }
apache-2.0
778830018662c10fe240e8ef685c9932
41.625
140
0.760687
4.215548
false
false
false
false
outbrain/ob1k
ob1k-crud/src/main/java/com/outbrain/ob1k/crud/model/EntityField.kt
1
4134
package com.outbrain.ob1k.crud.model import com.fasterxml.jackson.annotation.JsonIgnore import com.google.gson.JsonObject data class EntityField(@JsonIgnore var dbName: String, var name: String, var label: String, var type: EFieldType, var required: Boolean = true, var readOnly: Boolean = false, @JsonIgnore var autoGenerate: Boolean = false, var reference: String? = null, var target: String? = null, var display: EntityFieldDisplay? = null, var hidden: Boolean = false, var options: EntityFieldOptions? = null, var choices: List<String>? = null, var rangeStyles: MutableList<RangeStyle>? = null, var fields: MutableList<EntityField>? = null) { var className: String? = null fun withRangeStyle(values: List<String>, style: Map<String, String>) = withRangeStyle(RangeStyle(style = style, values = values)) fun withRangeStyle(value: String, style: Map<String, String>) = withRangeStyle(RangeStyle(style = style, value = value)) fun withRangeStyle(start: Number?, end: Number?, style: Map<String, String>) = withRangeStyle(RangeStyle(style = style, range = listOf(start, end))) private fun withRangeStyle(rangeStyle: RangeStyle): EntityField { if (rangeStyles == null) { rangeStyles = mutableListOf() } rangeStyles?.let { it += rangeStyle } return this } fun nonNullOptions(): EntityFieldOptions { if (options == null) { options = EntityFieldOptions() } return options!! } fun setChoices(cls: Class<*>) { choices = cls.enumChoices() } internal fun toMysqlMatchValue(value: String): String { return when (type) { EFieldType.BOOLEAN -> if (value == "true") "=1" else "=0" EFieldType.STRING, EFieldType.URL, EFieldType.TEXT, EFieldType.SELECT_BY_STRING, EFieldType.IMAGE -> " LIKE \"%$value%\"" EFieldType.NUMBER, EFieldType.REFERENCE -> { val cleaned = value.removePrefix("[").removeSuffix("]").replace("\"", "") val split = cleaned.split(",") return if (split.size == 1) "=$cleaned" else " IN ($cleaned)" } EFieldType.DATE -> "=\"$value\"" EFieldType.SELECT_BY_IDX -> "=${choices!!.indexOf(value)}" else -> "=$value" } } internal fun toMysqlValue(value: String): String { return when (type) { EFieldType.BOOLEAN -> if (value == "true") "1" else "0" EFieldType.STRING, EFieldType.DATE, EFieldType.URL, EFieldType.TEXT, EFieldType.SELECT_BY_STRING, EFieldType.IMAGE -> "\"$value\"" EFieldType.SELECT_BY_IDX -> "${choices!!.indexOf(value)}" else -> value } } internal fun fillJsonObject(obj: JsonObject, property: String, value: String?) { when (type) { EFieldType.BOOLEAN -> obj.addProperty(property, value == "1") EFieldType.NUMBER, EFieldType.REFERENCE -> { value?.let { try { obj.addProperty(property, it.toInt()) } catch (e: NumberFormatException) { try { obj.addProperty(property, it.toDouble()) } catch (e: NumberFormatException) { throw RuntimeException(e.message, e) } } } } EFieldType.REFERENCEMANY -> throw UnsupportedOperationException() EFieldType.SELECT_BY_IDX -> value?.let { obj.addProperty(property, choices!![it.toInt()]) } else -> obj.addProperty(property, value) } } private fun Class<*>.enumChoices() = enumConstants?.map { it.toString() } }
apache-2.0
80bf6c71c083f408becbe915d219366b
38.75
142
0.538703
5.010909
false
false
false
false
paplorinc/intellij-community
plugins/git4idea/src/git4idea/rebase/GitInteractiveRebaseAction.kt
2
1542
/* * 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 git4idea.rebase import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.progress.Task import git4idea.branch.GitRebaseParams class GitInteractiveRebaseAction : GitCommitEditingAction() { override fun update(e: AnActionEvent) { super.update(e) prohibitRebaseDuringRebase(e, "rebase") } override fun actionPerformedAfterChecks(e: AnActionEvent) { val commit = getSelectedCommit(e) val project = e.project!! val repository = getRepository(e) object : Task.Backgroundable(project, "Rebasing") { override fun run(indicator: ProgressIndicator) { val params = GitRebaseParams.editCommits(commit.parents.first().asString(), null, false) GitRebaseUtils.rebase(project, listOf(repository), params, indicator); } }.queue() } override fun getFailureTitle(): String = "Couldn't Start Rebase" }
apache-2.0
a4ff68621fa956d5985a7ec59531f70a
34.883721
96
0.745136
4.283333
false
false
false
false
paplorinc/intellij-community
plugins/git4idea/src/git4idea/commands/GitAuthenticationGates.kt
3
1837
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package git4idea.commands import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.progress.ProcessCanceledException import com.intellij.util.containers.ContainerUtil.newConcurrentMap import java.util.concurrent.Semaphore import java.util.function.Supplier private val LOG = logger<GitRestrictingAuthenticationGate>() class GitRestrictingAuthenticationGate : GitAuthenticationGate { private val semaphore = Semaphore(1) @Volatile private var cancelled = false private val inputData = newConcurrentMap<String, String>() override fun <T> waitAndCompute(operation: Supplier<T>): T { try { LOG.debug("Entered waitAndCompute") semaphore.acquire() LOG.debug("Acquired permission") if (cancelled) { LOG.debug("Authentication Gate has already been cancelled") throw ProcessCanceledException() } return operation.get() } catch (e: InterruptedException) { LOG.warn(e) throw ProcessCanceledException(e) } finally { semaphore.release() } } override fun cancel() { cancelled = true } override fun getSavedInput(key: String): String? { return inputData[key] } override fun saveInput(key: String, value: String) { inputData[key] = value } } class GitPassthroughAuthenticationGate : GitAuthenticationGate { override fun <T> waitAndCompute(operation: Supplier<T>): T { return operation.get() } override fun cancel() { } override fun getSavedInput(key: String): String? { return null } override fun saveInput(key: String, value: String) { } companion object { @JvmStatic val instance = GitPassthroughAuthenticationGate() } }
apache-2.0
ee4eadd027889ad255190cd24599ae3a
26.014706
140
0.717474
4.394737
false
false
false
false
paplorinc/intellij-community
platform/diff-impl/tests/com/intellij/diff/tools/fragmented/UnifiedFragmentBuilderTest.kt
1
10066
/* * Copyright 2000-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.diff.tools.fragmented import com.intellij.diff.DiffTestCase import com.intellij.diff.comparison.ComparisonPolicy import com.intellij.diff.comparison.iterables.DiffIterable import com.intellij.diff.comparison.iterables.DiffIterableUtil import com.intellij.diff.fragments.LineFragment import com.intellij.diff.fragments.LineFragmentImpl import com.intellij.diff.util.LineRange import com.intellij.diff.util.Range import com.intellij.diff.util.Side import com.intellij.openapi.editor.impl.DocumentImpl import junit.framework.TestCase import java.util.* class UnifiedFragmentBuilderTest : DiffTestCase() { fun testSimple() { Test("", "", ".", " ") .run() Test("A_B_C", "A_B_C", "A_B_C", " _ _ ") .run() // empty document has one line, so it's "modified" case (and not "deleted") Test("A", "", "A_.", "L_R") .run() Test("", "A", "._A", "L_R") .run() Test("A_", "", "A_.", "L_ ") .run() Test("A_", "B", "A_._B", "L_L_R") .run() Test("B_", "B", "B_.", " _L") .run() Test("_B", "B", "._B", "L_ ") .run() Test("A_A", "B", "A_A_B", "L_L_R") .run() Test("A_B_C_D", "A_D", "A_B_C_D", " _L_L_ ") .run() Test("X_B_C", "A_B_C", "X_A_B_C", "L_R_ _ ") .run() Test("A_B_C", "A_B_Y", "A_B_C_Y", " _ _L_R") .run() Test("A_B_C_D_E_F", "A_X_C_D_Y_F", "A_B_X_C_D_E_Y_F", " _L_R_ _ _L_R_ ") .run() Test("A_B_C_D_E_F", "A_B_X_C_D_F", "A_B_X_C_D_E_F", " _ _R_ _ _L_ ") .run() Test("A_B_C_D_E_F", "A_B_X_Y_E_F", "A_B_C_D_X_Y_E_F", " _ _L_L_R_R_ _ ") .run() Test("", "", ".", " ") .changes() .run() Test("A", "B", "A_B", "L_R") .changes(mod(0, 0, 1, 1)) .runLeft() Test("A", "B", "A", " ") .changes() .runLeft() Test("A", "B", "B", " ") .changes() .runRight() } fun testNonFair() { Test("A_B", "", "A_B", " _ ") .changes() .runLeft() Test("A_B", "", ".", " ") .changes() .runRight() Test("A_B", "A_._B", "A_B", " _ ") .changes() .runLeft() Test("A_B", "A_._B", "A_._B", " _ _ ") .changes() .runRight() Test("_._A_._", "X", "._._A_X_._.", " _ _L_R_ _ ") .changes(mod(2, 0, 1, 1)) .runLeft() Test("_._A_._", "X", "A_X", "L_R") .changes(mod(2, 0, 1, 1)) .runRight() Test("A_B_C_D", "X_BC_Y", "A_X_BC_D_Y", "L_R_ _L_R") .changes(mod(0, 0, 1, 1), mod(3, 2, 1, 1)) .runRight() Test("A_B_C_D", "A_BC_Y", "A_BC_D_Y", " _ _L_R") .changes(mod(3, 2, 1, 1)) .runRight() Test("AB_C_DE", "A_B_D_E", "AB_C_DE", " _L_ ") .changes(del(1, 2, 1)) .runLeft() Test("AB_C_DE", "A_B_D_E", "A_B_C_D_E", " _ _L_ _ ") .changes(del(1, 2, 1)) .runRight() Test("AB_DE", "A_B_C_D_E", "AB_C_DE", " _R_ ") .changes(ins(1, 2, 1)) .runLeft() Test("AB_DE", "A_B_C_D_E", "A_B_C_D_E", " _ _R_ _ ") .changes(ins(1, 2, 1)) .runRight() } private inner class Test(val input1: String, val input2: String, val result: String, val lineMapping: String) { private var customFragments: List<LineFragment>? = null fun runLeft() { doRun(Side.LEFT) } fun runRight() { doRun(Side.RIGHT) } fun run() { doRun(Side.LEFT, Side.RIGHT) } private fun doRun(vararg sides: Side) { sides.forEach { side -> assert(result.length == lineMapping.length) val text1 = processText(input1) val text2 = processText(input2) val fragments = if (customFragments != null) customFragments!! else MANAGER.compareLines(text1, text2, ComparisonPolicy.DEFAULT, INDICATOR) val builder = UnifiedFragmentBuilder(fragments, DocumentImpl(text1), DocumentImpl(text2), side) builder.exec() val lineCount1 = input1.count { it == '_' } + 1 val lineCount2 = input2.count { it == '_' } + 1 val resultLineCount = result.count { it == '_' } + 1 val lineIterable = DiffIterableUtil.create(fragments.map { Range(it.startLine1, it.endLine1, it.startLine2, it.endLine2) }, lineCount1, lineCount2) val expectedText = processText(result) val actualText = processActualText(builder) val expectedMapping = processExpectedLineMapping(lineMapping) val actualMapping = processActualLineMapping(builder.blocks, resultLineCount) val expectedChangedLines = processExpectedChangedLines(lineMapping) val actualChangedLines = processActualChangedLines(builder.changedLines) val expectedMappedLines1 = processExpectedMappedLines(lineIterable, Side.LEFT) val expectedMappedLines2 = processExpectedMappedLines(lineIterable, Side.RIGHT) val actualMappedLines1 = processActualMappedLines(builder.convertor1, resultLineCount) val actualMappedLines2 = processActualMappedLines(builder.convertor2, resultLineCount) assertEquals(expectedText, actualText) assertEquals(expectedMapping, actualMapping) assertEquals(expectedChangedLines, actualChangedLines) if (customFragments == null) { assertEquals(expectedMappedLines1, actualMappedLines1) assertEquals(expectedMappedLines2, actualMappedLines2) } } } fun changes(vararg ranges: Range): Test { customFragments = ranges.map { LineFragmentImpl(it.start1, it.end1, it.start2, it.end2, -1, -1, -1, -1) } return this } private fun processText(text: String): String { return text.filterNot { it == '.' }.replace('_', '\n') } private fun processActualText(builder: UnifiedFragmentBuilder): String { return builder.text.toString().removeSuffix("\n") } private fun processExpectedLineMapping(lineMapping: String): LineMapping { val leftSet = BitSet() val rightSet = BitSet() val unchangedSet = BitSet() lineMapping.split('_').forEachIndexed { index, line -> if (!line.isEmpty()) { val left = line.all { it == 'L' } val right = line.all { it == 'R' } val unchanged = line.all { it == ' ' } if (left) leftSet.set(index) else if (right) rightSet.set(index) else if (unchanged) unchangedSet.set(index) else TestCase.fail() } } return LineMapping(leftSet, rightSet, unchangedSet) } private fun processActualLineMapping(blocks: List<ChangedBlock>, lineCount: Int): LineMapping { val leftSet = BitSet() val rightSet = BitSet() val unchangedSet = BitSet() blocks.forEach { leftSet.set(it.range1.start, it.range1.end) rightSet.set(it.range2.start, it.range2.end) } unchangedSet.set(0, lineCount) unchangedSet.andNot(leftSet) unchangedSet.andNot(rightSet) return LineMapping(leftSet, rightSet, unchangedSet) } private fun processExpectedChangedLines(lineMapping: String): BitSet { val expectedMapping = processExpectedLineMapping(lineMapping) val result = BitSet() result.or(expectedMapping.left) result.or(expectedMapping.right) return result } private fun processActualChangedLines(changedRanges: List<LineRange>): BitSet { val result = BitSet() changedRanges.forEach { result.set(it.start, it.end) } return result } private fun processExpectedMappedLines(iterable: DiffIterable, side: Side): BitSet { val result = BitSet() DiffIterableUtil.iterateAll(iterable).forEach { pair -> val range = pair.first val start = side.select(range.start1, range.start2) val end = side.select(range.end1, range.end2) result.set(start, end) } return result } private fun processActualMappedLines(convertor: LineNumberConvertor, lineCount: Int): BitSet { val result = BitSet() for (i in -5..lineCount + 5) { val line = convertor.convert(i) if (line != -1) { if (result[line]) TestCase.fail() result.set(line) } } return result } } private fun mod(line1: Int, line2: Int, count1: Int, count2: Int): Range { assert(count1 != 0) assert(count2 != 0) return Range(line1, line1 + count1, line2, line2 + count2) } private fun del(line1: Int, line2: Int, count1: Int): Range { assert(count1 != 0) return Range(line1, line1 + count1, line2, line2) } private fun ins(line1: Int, line2: Int, count2: Int): Range { assert(count2 != 0) return Range(line1, line1, line2, line2 + count2) } private data class LineMapping(val left: BitSet, val right: BitSet, val unchanged: BitSet) }
apache-2.0
01c304a3a02c68251f64e0ed65add682
25.419948
131
0.550964
3.572037
false
true
false
false
google/intellij-community
plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/data/PackageSearchProjectService.kt
1
16753
/******************************************************************************* * 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.data import com.intellij.codeInsight.daemon.DaemonCodeAnalyzer import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.readAction import com.intellij.openapi.components.Service import com.intellij.openapi.fileEditor.FileEditorManager import com.intellij.openapi.project.Project import com.intellij.psi.PsiManager import com.jetbrains.packagesearch.intellij.plugin.PackageSearchBundle import com.jetbrains.packagesearch.intellij.plugin.PluginEnvironment import com.jetbrains.packagesearch.intellij.plugin.extensibility.ProjectModule import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.PackageSearchToolWindowFactory import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.KnownRepositories import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.ModuleModel import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.ProjectDataProvider import com.jetbrains.packagesearch.intellij.plugin.util.BackgroundLoadingBarController import com.jetbrains.packagesearch.intellij.plugin.util.PowerSaveModeState import com.jetbrains.packagesearch.intellij.plugin.util.TraceInfo import com.jetbrains.packagesearch.intellij.plugin.util.batchAtIntervals import com.jetbrains.packagesearch.intellij.plugin.util.catchAndLog import com.jetbrains.packagesearch.intellij.plugin.util.combineLatest import com.jetbrains.packagesearch.intellij.plugin.util.filesChangedEventFlow import com.jetbrains.packagesearch.intellij.plugin.util.lifecycleScope import com.jetbrains.packagesearch.intellij.plugin.util.logTrace import com.jetbrains.packagesearch.intellij.plugin.util.mapLatestTimedWithLoading import com.jetbrains.packagesearch.intellij.plugin.util.modifiedBy import com.jetbrains.packagesearch.intellij.plugin.util.moduleChangesSignalFlow import com.jetbrains.packagesearch.intellij.plugin.util.moduleTransformers import com.jetbrains.packagesearch.intellij.plugin.util.nativeModulesFlow import com.jetbrains.packagesearch.intellij.plugin.util.packageSearchProjectCachesService import com.jetbrains.packagesearch.intellij.plugin.util.packageVersionNormalizer import com.jetbrains.packagesearch.intellij.plugin.util.parallelMap import com.jetbrains.packagesearch.intellij.plugin.util.parallelUpdatedKeys import com.jetbrains.packagesearch.intellij.plugin.util.powerSaveModeFlow import com.jetbrains.packagesearch.intellij.plugin.util.replayOnSignals import com.jetbrains.packagesearch.intellij.plugin.util.send import com.jetbrains.packagesearch.intellij.plugin.util.showBackgroundLoadingBar import com.jetbrains.packagesearch.intellij.plugin.util.throttle import com.jetbrains.packagesearch.intellij.plugin.util.timer import com.jetbrains.packagesearch.intellij.plugin.util.toolWindowManagerFlow import com.jetbrains.packagesearch.intellij.plugin.util.trustedProjectFlow import com.jetbrains.packagesearch.intellij.plugin.util.trySend import com.jetbrains.packagesearch.intellij.plugin.util.whileLoading import kotlinx.coroutines.async import kotlinx.coroutines.awaitAll import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.asFlow import kotlinx.coroutines.flow.channelFlow import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.combineTransform import kotlinx.coroutines.flow.consumeAsFlow import kotlinx.coroutines.flow.filter import kotlinx.coroutines.flow.flatMapLatest import kotlinx.coroutines.flow.flow import kotlinx.coroutines.flow.flowOf import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.mapLatest import kotlinx.coroutines.flow.mapNotNull import kotlinx.coroutines.flow.merge import kotlinx.coroutines.flow.onEach import kotlinx.coroutines.flow.receiveAsFlow import kotlinx.coroutines.flow.shareIn import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.flow.take import kotlinx.serialization.json.Json import org.jetbrains.idea.packagesearch.api.PackageSearchApiClient import kotlin.time.Duration.Companion.hours import kotlin.time.Duration.Companion.seconds @Service(Service.Level.PROJECT) internal class PackageSearchProjectService(private val project: Project) { private val retryFromErrorChannel = Channel<Unit>() val dataProvider = ProjectDataProvider( PackageSearchApiClient(), project.packageSearchProjectCachesService.installedDependencyCache ) private val projectModulesLoadingFlow = MutableStateFlow(false) private val knownRepositoriesLoadingFlow = MutableStateFlow(false) private val moduleModelsLoadingFlow = MutableStateFlow(false) private val allInstalledKnownRepositoriesLoadingFlow = MutableStateFlow(false) private val installedPackagesStep1LoadingFlow = MutableStateFlow(false) private val installedPackagesStep2LoadingFlow = MutableStateFlow(false) private val installedPackagesDifferenceLoadingFlow = MutableStateFlow(false) private val packageUpgradesLoadingFlow = MutableStateFlow(false) private val availableUpgradesLoadingFlow = MutableStateFlow(false) private val computationInterruptedChannel = Channel<Unit>() private val computationStartedChannel = Channel<Unit>() private val computationAllowedState = channelFlow { computationInterruptedChannel.consumeAsFlow() .onEach { send(false) } .launchIn(this) computationStartedChannel.consumeAsFlow() .onEach { send(true) } .launchIn(this) }.stateIn(project.lifecycleScope, SharingStarted.Eagerly, true) val isComputationAllowed get() = computationAllowedState.value private val canShowLoadingBar = MutableStateFlow(false) private val operationExecutedChannel = Channel<List<ProjectModule>>() private val json = Json { prettyPrint = true } private val cacheDirectory = project.packageSearchProjectCachesService.projectCacheDirectory.resolve("installedDependencies") val isLoadingFlow = combineTransform( projectModulesLoadingFlow, knownRepositoriesLoadingFlow, moduleModelsLoadingFlow, allInstalledKnownRepositoriesLoadingFlow, installedPackagesStep1LoadingFlow, installedPackagesStep2LoadingFlow, installedPackagesDifferenceLoadingFlow, packageUpgradesLoadingFlow ) { booleans -> emit(booleans.any { it }) } .stateIn(project.lifecycleScope, SharingStarted.Eagerly, false) private val projectModulesSharedFlow = combine( project.trustedProjectFlow, ApplicationManager.getApplication().powerSaveModeFlow.map { it == PowerSaveModeState.ENABLED }, computationAllowedState ) { isProjectTrusted, powerSaveModeEnabled, computationEnabled -> isProjectTrusted && !powerSaveModeEnabled && computationEnabled } .flatMapLatest { isPkgsEnabled -> if (isPkgsEnabled) project.nativeModulesFlow else flowOf(emptyList()) } .replayOnSignals( retryFromErrorChannel.receiveAsFlow().throttle(10.seconds), project.moduleChangesSignalFlow, ) .mapLatestTimedWithLoading("projectModulesSharedFlow", projectModulesLoadingFlow) { modules -> project.moduleTransformers .map { async { it.transformModules(project, modules) } } .awaitAll() .flatten() } .catchAndLog( context = "${this::class.qualifiedName}#projectModulesSharedFlow", message = "Error while elaborating latest project modules" ) .shareIn(project.lifecycleScope, SharingStarted.Eagerly) val projectModulesStateFlow = projectModulesSharedFlow.stateIn(project.lifecycleScope, SharingStarted.Eagerly, emptyList()) val isAvailable get() = projectModulesStateFlow.value.isNotEmpty() || !isComputationAllowed private val knownRepositoriesFlow = timer(1.hours) .mapLatestTimedWithLoading("knownRepositoriesFlow", knownRepositoriesLoadingFlow) { dataProvider.fetchKnownRepositories() } .catchAndLog( context = "${this::class.qualifiedName}#knownRepositoriesFlow", message = "Error while refreshing known repositories" ) .stateIn(project.lifecycleScope, SharingStarted.Eagerly, emptyList()) private val buildFileChangesFlow = combine( projectModulesSharedFlow, project.filesChangedEventFlow.map { it.mapNotNull { it.file } } ) { modules, changedBuildFiles -> modules.filter { it.buildFile in changedBuildFiles } } .shareIn(project.lifecycleScope, SharingStarted.Eagerly) private val projectModulesChangesFlow = merge( buildFileChangesFlow.filter { it.isNotEmpty() }, operationExecutedChannel.consumeAsFlow() ) .batchAtIntervals(1.seconds) .map { it.flatMap { it }.distinct() } .catchAndLog( context = "${this::class.qualifiedName}#projectModulesChangesFlow", message = "Error while checking Modules changes" ) .shareIn(project.lifecycleScope, SharingStarted.Eagerly) val moduleModelsStateFlow = projectModulesSharedFlow .mapLatestTimedWithLoading( loggingContext = "moduleModelsStateFlow", loadingFlow = moduleModelsLoadingFlow ) { projectModules -> projectModules.parallelMap { it to ModuleModel(it) }.toMap() } .modifiedBy(projectModulesChangesFlow) { repositories, changedModules -> repositories.parallelUpdatedKeys(changedModules) { ModuleModel(it) } } .map { it.values.toList() } .catchAndLog( context = "${this::class.qualifiedName}#moduleModelsStateFlow", message = "Error while evaluating modules models" ) .stateIn(project.lifecycleScope, SharingStarted.Eagerly, emptyList()) val allInstalledKnownRepositoriesStateFlow = combine(moduleModelsStateFlow, knownRepositoriesFlow) { moduleModels, repos -> moduleModels to repos } .mapLatestTimedWithLoading( loggingContext = "allInstalledKnownRepositoriesFlow", loadingFlow = allInstalledKnownRepositoriesLoadingFlow ) { (moduleModels, repos) -> allKnownRepositoryModels(moduleModels, repos) } .catchAndLog( context = "${this::class.qualifiedName}#allInstalledKnownRepositoriesFlow", message = "Error while evaluating installed repositories" ) .stateIn(project.lifecycleScope, SharingStarted.Eagerly, KnownRepositories.All.EMPTY) val dependenciesByModuleStateFlow = projectModulesSharedFlow .mapLatestTimedWithLoading("installedPackagesStep1LoadingFlow", installedPackagesStep1LoadingFlow) { fetchProjectDependencies(it, cacheDirectory, json) } .modifiedBy(projectModulesChangesFlow) { installed, changedModules -> val (result, time) = installedPackagesDifferenceLoadingFlow.whileLoading { installed.parallelUpdatedKeys(changedModules) { it.installedDependencies(cacheDirectory, json) } } logTrace("installedPackagesStep1LoadingFlow") { "Took ${time} to process diffs for ${changedModules.size} module" + if (changedModules.size > 1) "s" else "" } result } .catchAndLog( context = "${this::class.qualifiedName}#dependenciesByModuleStateFlow", message = "Error while evaluating installed dependencies" ) .stateIn(project.lifecycleScope, SharingStarted.Eagerly, emptyMap()) val installedPackagesStateFlow = dependenciesByModuleStateFlow .mapLatestTimedWithLoading("installedPackagesStep2LoadingFlow", installedPackagesStep2LoadingFlow) { installedPackages( it, project, dataProvider, TraceInfo(TraceInfo.TraceSource.INIT) ) } .catchAndLog( context = "${this::class.qualifiedName}#installedPackagesStateFlow", message = "Error while evaluating installed packages" ) .stateIn(project.lifecycleScope, SharingStarted.Eagerly, emptyList()) val packageUpgradesStateFlow = combineLatest( installedPackagesStateFlow, moduleModelsStateFlow, knownRepositoriesFlow ) { (installedPackages, moduleModels, repos) -> availableUpgradesLoadingFlow.emit(true) val result = PackageUpgradeCandidates( computePackageUpgrades( installedPackages = installedPackages, onlyStable = false, normalizer = packageVersionNormalizer, repos = allKnownRepositoryModels(moduleModels, repos), nativeModulesMap = moduleModels.associateBy { it.projectModule } ) ) availableUpgradesLoadingFlow.emit(false) result } .catchAndLog( context = "${this::class.qualifiedName}#packageUpgradesStateFlow", message = "Error while evaluating packages upgrade candidates" ) .stateIn(project.lifecycleScope, SharingStarted.Lazily, PackageUpgradeCandidates.EMPTY) init { // allows rerunning PKGS inspections on already opened files // when the data is finally available or changes for PackageUpdateInspection // or when a build file changes packageUpgradesStateFlow.throttle(5.seconds) .map { projectModulesStateFlow.value.mapNotNull { it.buildFile?.path }.toSet() } .filter { it.isNotEmpty() } .flatMapLatest { knownBuildFiles -> FileEditorManager.getInstance(project).openFiles .filter { it.path in knownBuildFiles }.asFlow() } .mapNotNull { readAction { PsiManager.getInstance(project).findFile(it) } } .onEach { readAction { DaemonCodeAnalyzer.getInstance(project).restart(it) } } .catchAndLog("${this::class.qualifiedName}#inspectionsRestart") .launchIn(project.lifecycleScope) var controller: BackgroundLoadingBarController? = null project.toolWindowManagerFlow .filter { it.id == PackageSearchToolWindowFactory.ToolWindowId } .take(1) .onEach { canShowLoadingBar.emit(true) } .launchIn(project.lifecycleScope) if (PluginEnvironment.isNonModalLoadingEnabled) { canShowLoadingBar.filter { it } .flatMapLatest { isLoadingFlow } .throttle(1.seconds) .onEach { controller?.clear() } .filter { it } .onEach { controller = showBackgroundLoadingBar( project = project, title = PackageSearchBundle.message("toolwindow.stripe.Dependencies"), upperMessage = PackageSearchBundle.message("packagesearch.ui.loading"), cancellable = true ).also { it.addOnComputationInterruptedCallback { computationInterruptedChannel.trySend() } } }.launchIn(project.lifecycleScope) } } fun notifyOperationExecuted(successes: List<ProjectModule>) { operationExecutedChannel.trySend(successes) } suspend fun restart() { computationStartedChannel.send() retryFromErrorChannel.send() } fun resumeComputation() { computationStartedChannel.trySend() } }
apache-2.0
6d6285496d5841e0150a1d00e1ee2f2f
47.279539
131
0.71426
5.798892
false
false
false
false
Virtlink/aesi
paplj/src/main/kotlin/com/virtlink/terms/DefaultTermFactory.kt
1
2032
package com.virtlink.terms /** * Default implementation of a term factory. */ open class DefaultTermFactory : TermFactory() { /** The registered term builders. */ private val termBuilders: HashMap<ITermConstructor, (ITermConstructor, List<ITerm>) -> ITerm> = hashMapOf() override fun createString(value: String): StringTerm = getTerm(StringTerm(value)) override fun createInt(value: Int): IntTerm = getTerm(IntTerm(value)) override fun <T: ITerm> createList(elements: List<T>): ListTerm<T> = getTerm(ListTerm(elements)) override fun <T : ITerm> createOption(value: T?): OptionTerm<T> = getTerm(if (value != null) SomeTerm(value) else NoneTerm()) override fun createTerm(constructor: ITermConstructor, children: List<ITerm>): ITerm { if (children.size != constructor.arity) { throw IllegalArgumentException("Expected ${constructor.arity} child terms, got ${children.size}.") } val builder = getBuilder(constructor) ?: { c, cl -> c.create(cl) } return getTerm(builder(constructor, children)) } override fun registerBuilder(constructor: ITermConstructor, builder: (ITermConstructor, List<ITerm>) -> ITerm) { this.termBuilders.put(constructor, builder) } override fun unregisterBuilder(constructor: ITermConstructor) { this.termBuilders.remove(constructor) } /** * Gets the term builder with the specified term constructor. * * @param constructor The term constructor. * @return The term builder; or null when not found. */ protected fun getBuilder(constructor: ITermConstructor): ((ITermConstructor, List<ITerm>) -> ITerm)? { return this.termBuilders[constructor] } /** * Gets the actual term given a term. * * @param term The input term. * @return The resulting term. */ protected open fun <T: ITerm> getTerm(term: T): T { // Default implementation. return term } }
apache-2.0
3abeb2123d34e754ff2d3a5f915acb56
32.327869
116
0.654528
4.545861
false
false
false
false
google/intellij-community
plugins/git4idea/src/git4idea/conflicts/GitConflictsUtil.kt
5
5409
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package git4idea.conflicts import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.progress.Task import com.intellij.openapi.project.Project import com.intellij.openapi.vcs.VcsNotifier import com.intellij.openapi.vcs.impl.BackgroundableActionLock import com.intellij.openapi.vfs.LocalFileSystem import com.intellij.openapi.vfs.VirtualFile import git4idea.GitNotificationIdsHolder import git4idea.i18n.GitBundle import git4idea.merge.GitMergeUtil import git4idea.repo.GitConflict import git4idea.repo.GitRepositoryManager import org.jetbrains.annotations.Nls object GitConflictsUtil { internal fun getConflictOperationLock(project: Project, conflict: GitConflict): BackgroundableActionLock { return BackgroundableActionLock.getLock(project, conflict.filePath) } internal fun acceptConflictSide(project: Project, handler: GitMergeHandler, selectedConflicts: List<GitConflict>, takeTheirs: Boolean) { acceptConflictSide(project, handler, selectedConflicts, takeTheirs) { root -> isReversedRoot(project, root) } } internal fun acceptConflictSide(project: Project, handler: GitMergeHandler, selectedConflicts: List<GitConflict>, takeTheirs: Boolean, isReversed: (root: VirtualFile) -> Boolean) { val conflicts = selectedConflicts.filterNot { getConflictOperationLock(project, it).isLocked }.toList() if (conflicts.isEmpty()) return val locks = conflicts.map { getConflictOperationLock(project, it) } locks.forEach { it.lock() } object : Task.Backgroundable(project, GitBundle.message("conflicts.accept.progress", conflicts.size), true) { override fun run(indicator: ProgressIndicator) { val reversedRoots = conflicts.mapTo(mutableSetOf()) { it.root }.filter(isReversed) handler.acceptOneVersion(conflicts, reversedRoots, takeTheirs) } override fun onFinished() { locks.forEach { it.unlock() } } }.queue() } private fun hasActiveMergeWindow(conflict: GitConflict) : Boolean { val file = LocalFileSystem.getInstance().findFileByPath(conflict.filePath.path) ?: return false return MergeConflictResolveUtil.hasActiveMergeWindow(file) } internal fun canShowMergeWindow(project: Project, handler: GitMergeHandler, conflict: GitConflict): Boolean { return handler.canResolveConflict(conflict) && (!getConflictOperationLock(project, conflict).isLocked || hasActiveMergeWindow(conflict)) } internal fun showMergeWindow(project: Project, handler: GitMergeHandler, selectedConflicts: List<GitConflict>) { showMergeWindow(project, handler, selectedConflicts, { root -> isReversedRoot(project, root) }) } internal fun showMergeWindow(project: Project, handler: GitMergeHandler, selectedConflicts: List<GitConflict>, isReversed: (root: VirtualFile) -> Boolean) { val conflicts = selectedConflicts.filter { canShowMergeWindow(project, handler, it) }.toList() if (conflicts.isEmpty()) return for (conflict in conflicts) { val file = LocalFileSystem.getInstance().refreshAndFindFileByPath(conflict.filePath.path) if (file == null) { VcsNotifier.getInstance(project).notifyError(GitNotificationIdsHolder.CANNOT_RESOLVE_CONFLICT, GitBundle.message("conflicts.merge.window.error.title"), GitBundle.message("conflicts.merge.window.error.message", conflict.filePath)) continue } val lock = getConflictOperationLock(project, conflict) MergeConflictResolveUtil.showMergeWindow(project, file, lock) { handler.resolveConflict(conflict, file, isReversed(conflict.root)) } } } @Nls internal fun getConflictType(conflict: GitConflict): String { val oursStatus = conflict.getStatus(GitConflict.ConflictSide.OURS, true) val theirsStatus = conflict.getStatus(GitConflict.ConflictSide.THEIRS, true) return when { oursStatus == GitConflict.Status.DELETED && theirsStatus == GitConflict.Status.DELETED -> GitBundle.message("conflicts.type.both.deleted") oursStatus == GitConflict.Status.ADDED && theirsStatus == GitConflict.Status.ADDED -> GitBundle.message("conflicts.type.both.added") oursStatus == GitConflict.Status.MODIFIED && theirsStatus == GitConflict.Status.MODIFIED -> GitBundle.message("conflicts.type.both.modified") oursStatus == GitConflict.Status.DELETED -> GitBundle.message("conflicts.type.deleted.by.you") theirsStatus == GitConflict.Status.DELETED -> GitBundle.message("conflicts.type.deleted.by.them") oursStatus == GitConflict.Status.ADDED -> GitBundle.message("conflicts.type.added.by.you") theirsStatus == GitConflict.Status.ADDED -> GitBundle.message("conflicts.type.added.by.them") else -> throw IllegalStateException("ours: $oursStatus; theirs: $theirsStatus") } } internal fun isReversedRoot(project: Project, root: VirtualFile): Boolean { val repository = GitRepositoryManager.getInstance(project).getRepositoryForRootQuick(root) ?: return false return GitMergeUtil.isReverseRoot(repository) } }
apache-2.0
77d1959466d05033681a20b122128ac7
49.560748
140
0.728785
4.985253
false
false
false
false
google/intellij-community
platform/external-system-impl/src/com/intellij/openapi/externalSystem/autoimport/AutoImportProjectTracker.kt
6
14567
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.externalSystem.autoimport import com.intellij.ide.file.BatchFileChangeListener import com.intellij.openapi.Disposable import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.components.PersistentStateComponent import com.intellij.openapi.components.State import com.intellij.openapi.components.Storage import com.intellij.openapi.components.StoragePathMacros.CACHE_FILE import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.externalSystem.autoimport.ExternalSystemModificationType.* import com.intellij.openapi.externalSystem.autoimport.ExternalSystemProjectTrackerSettings.AutoReloadType import com.intellij.openapi.externalSystem.autoimport.ExternalSystemRefreshStatus.SUCCESS import com.intellij.openapi.externalSystem.autoimport.update.PriorityEatUpdate import com.intellij.openapi.externalSystem.model.ProjectSystemId import com.intellij.openapi.observable.operations.AnonymousParallelOperationTrace import com.intellij.openapi.observable.operations.CompoundParallelOperationTrace import com.intellij.openapi.observable.properties.AtomicBooleanProperty import com.intellij.openapi.observable.properties.BooleanProperty import com.intellij.openapi.progress.impl.CoreProgressManager import com.intellij.openapi.project.Project import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.registry.Registry import com.intellij.util.LocalTimeCounter.currentTime import com.intellij.util.concurrency.AppExecutorUtil import com.intellij.util.ui.update.MergingUpdateQueue import org.jetbrains.annotations.TestOnly import java.util.concurrent.ConcurrentHashMap import kotlin.streams.asStream @State(name = "ExternalSystemProjectTracker", storages = [Storage(CACHE_FILE)]) class AutoImportProjectTracker(private val project: Project) : ExternalSystemProjectTracker, PersistentStateComponent<AutoImportProjectTracker.State> { private val settings get() = AutoImportProjectTrackerSettings.getInstance(project) private val projectStates = ConcurrentHashMap<State.Id, State.Project>() private val projectDataMap = ConcurrentHashMap<ExternalSystemProjectId, ProjectData>() private val isDisabled = AtomicBooleanProperty(isDisabledAutoReload.get()) private val asyncChangesProcessingProperty = AtomicBooleanProperty( !ApplicationManager.getApplication().isHeadlessEnvironment || CoreProgressManager.shouldKeepTasksAsynchronousInHeadlessMode() ) private val projectChangeOperation = AnonymousParallelOperationTrace(debugName = "Project change operation") private val projectReloadOperation = CompoundParallelOperationTrace<String>(debugName = "Project reload operation") private val dispatcher = MergingUpdateQueue("AutoImportProjectTracker.dispatcher", 300, false, null, project) private val backgroundExecutor = AppExecutorUtil.createBoundedApplicationPoolExecutor("AutoImportProjectTracker.backgroundExecutor", 1) var isAsyncChangesProcessing by asyncChangesProcessingProperty private fun createProjectChangesListener() = object : ProjectBatchFileChangeListener(project) { override fun batchChangeStarted(activityName: String?) = projectChangeOperation.startTask() override fun batchChangeCompleted() = projectChangeOperation.finishTask() } private fun createProjectReloadListener(projectData: ProjectData) = object : ExternalSystemProjectListener { val id = "ProjectTracker: ${projectData.projectAware.projectId.debugName}" override fun onProjectReloadStart() { projectReloadOperation.startTask(id) projectData.status.markSynchronized(currentTime()) projectData.isActivated = true } override fun onProjectReloadFinish(status: ExternalSystemRefreshStatus) { if (status != SUCCESS) projectData.status.markBroken(currentTime()) projectReloadOperation.finishTask(id) } } override fun scheduleProjectRefresh() { LOG.debug("Schedule project reload", Throwable()) schedule(priority = 0, dispatchIterations = 1) { reloadProject(smart = false) } } override fun scheduleChangeProcessing() { LOG.debug("Schedule change processing") schedule(priority = 1, dispatchIterations = 1) { processChanges() } } /** * ``` * dispatcher.mergingTimeSpan = 300 ms * dispatchIterations = 9 * We already dispatched processChanges * So delay is equal to (1 + 9) * 300 ms = 3000 ms = 3 s * ``` */ private fun scheduleDelayedSmartProjectReload() { LOG.debug("Schedule delayed project reload") schedule(priority = 2, dispatchIterations = 9) { reloadProject(smart = true) } } private fun schedule(priority: Int, dispatchIterations: Int, action: () -> Unit) { dispatcher.queue(PriorityEatUpdate(priority) { if (dispatchIterations - 1 > 0) { schedule(priority, dispatchIterations - 1, action) } else { action() } }) } private fun processChanges() { when (settings.autoReloadType) { AutoReloadType.ALL -> when (getModificationType()) { INTERNAL -> scheduleDelayedSmartProjectReload() EXTERNAL -> scheduleDelayedSmartProjectReload() UNKNOWN -> updateProjectNotification() } AutoReloadType.SELECTIVE -> when (getModificationType()) { INTERNAL -> updateProjectNotification() EXTERNAL -> scheduleDelayedSmartProjectReload() UNKNOWN -> updateProjectNotification() } AutoReloadType.NONE -> updateProjectNotification() } } private fun reloadProject(smart: Boolean) { LOG.debug("Incremental project reload") val projectsToReload = projectDataMap.values .filter { (!smart || it.isActivated) && !it.isUpToDate() } if (isDisabledAutoReload() || projectsToReload.isEmpty()) { LOG.debug("Skipped all projects reload") updateProjectNotification() return } for (projectData in projectsToReload) { LOG.debug("${projectData.projectAware.projectId.debugName}: Project reload") val hasUndefinedModifications = !projectData.status.isUpToDate() val settingsContext = projectData.settingsTracker.getSettingsContext() val context = ProjectReloadContext(!smart, hasUndefinedModifications, settingsContext) projectData.projectAware.reloadProject(context) } } private fun updateProjectNotification() { LOG.debug("Notification status update") val isDisabledAutoReload = isDisabledAutoReload() val notificationAware = ExternalSystemProjectNotificationAware.getInstance(project) for ((projectId, data) in projectDataMap) { when (isDisabledAutoReload || data.isUpToDate()) { true -> notificationAware.notificationExpire(projectId) else -> notificationAware.notificationNotify(data.projectAware) } } } private fun isDisabledAutoReload(): Boolean { return isDisabled.get() || Registry.`is`("external.system.auto.import.disabled") || !projectChangeOperation.isOperationCompleted() || !projectReloadOperation.isOperationCompleted() } private fun getModificationType(): ExternalSystemModificationType { return projectDataMap.values .asSequence() .map { it.getModificationType() } .asStream() .reduce(ProjectStatus::merge) .orElse(UNKNOWN) } override fun register(projectAware: ExternalSystemProjectAware) { val projectId = projectAware.projectId val projectIdName = projectId.debugName val activationProperty = AtomicBooleanProperty(false) val projectStatus = ProjectStatus(debugName = projectIdName) val parentDisposable = Disposer.newDisposable(projectIdName) val settingsTracker = ProjectSettingsTracker(project, this, backgroundExecutor, projectAware, parentDisposable) val projectData = ProjectData(projectStatus, activationProperty, projectAware, settingsTracker, parentDisposable) val notificationAware = ExternalSystemProjectNotificationAware.getInstance(project) projectDataMap[projectId] = projectData val id = "ProjectSettingsTracker: $projectIdName" settingsTracker.beforeApplyChanges { projectReloadOperation.startTask(id) } settingsTracker.afterApplyChanges { projectReloadOperation.finishTask(id) } activationProperty.afterSet({ LOG.debug("$projectIdName is activated") }, parentDisposable) activationProperty.afterSet({ scheduleChangeProcessing() }, parentDisposable) Disposer.register(project, parentDisposable) projectAware.subscribe(createProjectReloadListener(projectData), parentDisposable) Disposer.register(parentDisposable, Disposable { notificationAware.notificationExpire(projectId) }) loadState(projectId, projectData) } override fun activate(id: ExternalSystemProjectId) { val projectData = projectDataMap(id) { get(it) } ?: return projectData.isActivated = true } override fun remove(id: ExternalSystemProjectId) { val projectData = projectDataMap.remove(id) ?: return Disposer.dispose(projectData.parentDisposable) } override fun markDirty(id: ExternalSystemProjectId) { val projectData = projectDataMap(id) { get(it) } ?: return projectData.status.markDirty(currentTime()) } override fun markDirtyAllProjects() { val modificationTimeStamp = currentTime() projectDataMap.forEach { it.value.status.markDirty(modificationTimeStamp) } } private fun projectDataMap( id: ExternalSystemProjectId, action: MutableMap<ExternalSystemProjectId, ProjectData>.(ExternalSystemProjectId) -> ProjectData? ): ProjectData? { val projectData = projectDataMap.action(id) if (projectData == null) { LOG.warn(String.format("Project isn't registered by id=%s", id), Throwable()) } return projectData } override fun getState(): State { val projectSettingsTrackerStates = projectDataMap.asSequence() .map { (id, data) -> id.getState() to data.getState() } .toMap() return State(projectSettingsTrackerStates) } override fun loadState(state: State) { projectStates.putAll(state.projectSettingsTrackerStates) projectDataMap.forEach { (id, data) -> loadState(id, data) } } private fun loadState(projectId: ExternalSystemProjectId, projectData: ProjectData) { val projectState = projectStates.remove(projectId.getState()) val settingsTrackerState = projectState?.settingsTracker if (settingsTrackerState == null || projectState.isDirty) { projectData.status.markDirty(currentTime(), EXTERNAL) scheduleChangeProcessing() return } projectData.settingsTracker.loadState(settingsTrackerState) projectData.settingsTracker.refreshChanges() } override fun initializeComponent() { LOG.debug("Project tracker initialization") ApplicationManager.getApplication().messageBus.connect(project).subscribe(BatchFileChangeListener.TOPIC, createProjectChangesListener()) dispatcher.setRestartTimerOnAdd(true) dispatcher.isPassThrough = !isAsyncChangesProcessing dispatcher.activate() } @TestOnly fun getActivatedProjects() = projectDataMap.values .filter { it.isActivated } .map { it.projectAware.projectId } .toSet() /** * Enables auto-import in tests * Note: project tracker automatically enabled out of tests */ @TestOnly fun enableAutoImportInTests() { isDisabled.set(false) } @TestOnly fun setDispatcherMergingSpan(delay: Int) { dispatcher.setMergingTimeSpan(delay) } init { val notificationAware = ExternalSystemProjectNotificationAware.getInstance(project) projectReloadOperation.beforeOperation { LOG.debug("Project reload started") } projectReloadOperation.beforeOperation { notificationAware.notificationExpire() } projectReloadOperation.afterOperation { scheduleChangeProcessing() } projectReloadOperation.afterOperation { LOG.debug("Project reload finished") } projectChangeOperation.beforeOperation { LOG.debug("Project change started") } projectChangeOperation.beforeOperation { notificationAware.notificationExpire() } projectChangeOperation.afterOperation { scheduleChangeProcessing() } projectChangeOperation.afterOperation { LOG.debug("Project change finished") } settings.autoReloadTypeProperty.afterChange { scheduleChangeProcessing() } asyncChangesProcessingProperty.afterChange { dispatcher.isPassThrough = !it } } private fun ProjectData.getState() = State.Project(status.isDirty(), settingsTracker.getState()) private fun ProjectSystemId.getState() = id private fun ExternalSystemProjectId.getState() = State.Id(systemId.getState(), externalProjectPath) private data class ProjectData( val status: ProjectStatus, val activationProperty: BooleanProperty, val projectAware: ExternalSystemProjectAware, val settingsTracker: ProjectSettingsTracker, val parentDisposable: Disposable ) { var isActivated by activationProperty fun isUpToDate() = status.isUpToDate() && settingsTracker.isUpToDate() fun getModificationType(): ExternalSystemModificationType { return ProjectStatus.merge(status.getModificationType(), settingsTracker.getModificationType()) } } data class State(var projectSettingsTrackerStates: Map<Id, Project> = emptyMap()) { data class Id(var systemId: String? = null, var externalProjectPath: String? = null) data class Project( var isDirty: Boolean = false, var settingsTracker: ProjectSettingsTracker.State? = null ) } private data class ProjectReloadContext( override val isExplicitReload: Boolean, override val hasUndefinedModifications: Boolean, override val settingsFilesContext: ExternalSystemSettingsFilesReloadContext ) : ExternalSystemProjectReloadContext companion object { val LOG = Logger.getInstance("#com.intellij.openapi.externalSystem.autoimport") @TestOnly @JvmStatic fun getInstance(project: Project): AutoImportProjectTracker { return ExternalSystemProjectTracker.getInstance(project) as AutoImportProjectTracker } private val isDisabledAutoReload = AtomicBooleanProperty( ApplicationManager.getApplication().isUnitTestMode ) @TestOnly fun enableAutoReloadInTests(parentDisposable: Disposable) { Disposer.register(parentDisposable) { isDisabledAutoReload.reset() } isDisabledAutoReload.set(false) } } }
apache-2.0
78e8dfb5c5a4f7f30a3c3ff29e0be99e
40.386364
158
0.764124
5.532472
false
false
false
false
google/intellij-community
platform/workspaceModel/storage/testEntities/gen/com/intellij/workspaceModel/storage/entities/test/api/XChildEntityImpl.kt
1
12967
package com.intellij.workspaceModel.storage.entities.test.api import com.intellij.workspaceModel.storage.* 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.ModifiableWorkspaceEntity 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.EntityLink 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.extractOneToManyChildren import com.intellij.workspaceModel.storage.impl.extractOneToManyParent import com.intellij.workspaceModel.storage.impl.updateOneToManyChildrenOfParent import com.intellij.workspaceModel.storage.impl.updateOneToManyParentOfChild import org.jetbrains.deft.ObjBuilder import org.jetbrains.deft.Type import org.jetbrains.deft.annotations.Child @GeneratedCodeApiVersion(1) @GeneratedCodeImplVersion(1) open class XChildEntityImpl(val dataSource: XChildEntityData) : XChildEntity, WorkspaceEntityBase() { companion object { internal val PARENTENTITY_CONNECTION_ID: ConnectionId = ConnectionId.create(XParentEntity::class.java, XChildEntity::class.java, ConnectionId.ConnectionType.ONE_TO_MANY, false) internal val CHILDCHILD_CONNECTION_ID: ConnectionId = ConnectionId.create(XChildEntity::class.java, XChildChildEntity::class.java, ConnectionId.ConnectionType.ONE_TO_MANY, false) val connections = listOf<ConnectionId>( PARENTENTITY_CONNECTION_ID, CHILDCHILD_CONNECTION_ID, ) } override val childProperty: String get() = dataSource.childProperty override val dataClass: DataClassX? get() = dataSource.dataClass override val parentEntity: XParentEntity get() = snapshot.extractOneToManyParent(PARENTENTITY_CONNECTION_ID, this)!! override val childChild: List<XChildChildEntity> get() = snapshot.extractOneToManyChildren<XChildChildEntity>(CHILDCHILD_CONNECTION_ID, this)!!.toList() override fun connectionIdList(): List<ConnectionId> { return connections } class Builder(val result: XChildEntityData?) : ModifiableWorkspaceEntityBase<XChildEntity>(), XChildEntity.Builder { constructor() : this(XChildEntityData()) override fun applyToBuilder(builder: MutableEntityStorage) { if (this.diff != null) { if (existsInBuilder(builder)) { this.diff = builder return } else { error("Entity XChildEntity is already created in a different builder") } } this.diff = builder this.snapshot = builder addToBuilder() this.id = getEntityData().createEntityId() // 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().isChildPropertyInitialized()) { error("Field XChildEntity#childProperty should be initialized") } if (_diff != null) { if (_diff.extractOneToManyParent<WorkspaceEntityBase>(PARENTENTITY_CONNECTION_ID, this) == null) { error("Field XChildEntity#parentEntity should be initialized") } } else { if (this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)] == null) { error("Field XChildEntity#parentEntity should be initialized") } } // Check initialization for list with ref type if (_diff != null) { if (_diff.extractOneToManyChildren<WorkspaceEntityBase>(CHILDCHILD_CONNECTION_ID, this) == null) { error("Field XChildEntity#childChild should be initialized") } } else { if (this.entityLinks[EntityLink(true, CHILDCHILD_CONNECTION_ID)] == null) { error("Field XChildEntity#childChild should be initialized") } } } override fun connectionIdList(): List<ConnectionId> { return connections } // Relabeling code, move information from dataSource to this builder override fun relabel(dataSource: WorkspaceEntity, parents: Set<WorkspaceEntity>?) { dataSource as XChildEntity this.entitySource = dataSource.entitySource this.childProperty = dataSource.childProperty this.dataClass = dataSource.dataClass if (parents != null) { this.parentEntity = parents.filterIsInstance<XParentEntity>().single() } } override var entitySource: EntitySource get() = getEntityData().entitySource set(value) { checkModificationAllowed() getEntityData().entitySource = value changedProperty.add("entitySource") } override var childProperty: String get() = getEntityData().childProperty set(value) { checkModificationAllowed() getEntityData().childProperty = value changedProperty.add("childProperty") } override var dataClass: DataClassX? get() = getEntityData().dataClass set(value) { checkModificationAllowed() getEntityData().dataClass = value changedProperty.add("dataClass") } override var parentEntity: XParentEntity get() { val _diff = diff return if (_diff != null) { _diff.extractOneToManyParent(PARENTENTITY_CONNECTION_ID, this) ?: this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)]!! as XParentEntity } else { this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)]!! as XParentEntity } } set(value) { checkModificationAllowed() val _diff = diff if (_diff != null && value is ModifiableWorkspaceEntityBase<*> && value.diff == null) { // Setting backref of the list if (value is ModifiableWorkspaceEntityBase<*>) { val data = (value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] as? List<Any> ?: emptyList()) + this value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] = data } // else you're attaching a new entity to an existing entity that is not modifiable _diff.addEntity(value) } if (_diff != null && (value !is ModifiableWorkspaceEntityBase<*> || value.diff != null)) { _diff.updateOneToManyParentOfChild(PARENTENTITY_CONNECTION_ID, this, value) } else { // Setting backref of the list if (value is ModifiableWorkspaceEntityBase<*>) { val data = (value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] as? List<Any> ?: emptyList()) + this value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] = data } // else you're attaching a new entity to an existing entity that is not modifiable this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)] = value } changedProperty.add("parentEntity") } // List of non-abstract referenced types var _childChild: List<XChildChildEntity>? = emptyList() override var childChild: List<XChildChildEntity> get() { // Getter of the list of non-abstract referenced types val _diff = diff return if (_diff != null) { _diff.extractOneToManyChildren<XChildChildEntity>(CHILDCHILD_CONNECTION_ID, this)!!.toList() + (this.entityLinks[EntityLink(true, CHILDCHILD_CONNECTION_ID)] as? List<XChildChildEntity> ?: emptyList()) } else { this.entityLinks[EntityLink(true, CHILDCHILD_CONNECTION_ID)] as? List<XChildChildEntity> ?: emptyList() } } set(value) { // Setter of the list of non-abstract referenced types checkModificationAllowed() val _diff = diff if (_diff != null) { for (item_value in value) { if (item_value is ModifiableWorkspaceEntityBase<*> && (item_value as? ModifiableWorkspaceEntityBase<*>)?.diff == null) { _diff.addEntity(item_value) } } _diff.updateOneToManyChildrenOfParent(CHILDCHILD_CONNECTION_ID, this, value) } else { for (item_value in value) { if (item_value is ModifiableWorkspaceEntityBase<*>) { item_value.entityLinks[EntityLink(false, CHILDCHILD_CONNECTION_ID)] = this } // else you're attaching a new entity to an existing entity that is not modifiable } this.entityLinks[EntityLink(true, CHILDCHILD_CONNECTION_ID)] = value } changedProperty.add("childChild") } override fun getEntityData(): XChildEntityData = result ?: super.getEntityData() as XChildEntityData override fun getEntityClass(): Class<XChildEntity> = XChildEntity::class.java } } class XChildEntityData : WorkspaceEntityData<XChildEntity>() { lateinit var childProperty: String var dataClass: DataClassX? = null fun isChildPropertyInitialized(): Boolean = ::childProperty.isInitialized override fun wrapAsModifiable(diff: MutableEntityStorage): ModifiableWorkspaceEntity<XChildEntity> { val modifiable = XChildEntityImpl.Builder(null) modifiable.allowModifications { modifiable.diff = diff modifiable.snapshot = diff modifiable.id = createEntityId() modifiable.entitySource = this.entitySource } modifiable.changedProperty.clear() return modifiable } override fun createEntity(snapshot: EntityStorage): XChildEntity { return getCached(snapshot) { val entity = XChildEntityImpl(this) entity.entitySource = entitySource entity.snapshot = snapshot entity.id = createEntityId() entity } } override fun getEntityInterface(): Class<out WorkspaceEntity> { return XChildEntity::class.java } override fun serialize(ser: EntityInformation.Serializer) { } override fun deserialize(de: EntityInformation.Deserializer) { } override fun createDetachedEntity(parents: List<WorkspaceEntity>): WorkspaceEntity { return XChildEntity(childProperty, entitySource) { this.dataClass = [email protected] this.parentEntity = parents.filterIsInstance<XParentEntity>().single() } } override fun getRequiredParents(): List<Class<out WorkspaceEntity>> { val res = mutableListOf<Class<out WorkspaceEntity>>() res.add(XParentEntity::class.java) return res } override fun equals(other: Any?): Boolean { if (other == null) return false if (this::class != other::class) return false other as XChildEntityData if (this.entitySource != other.entitySource) return false if (this.childProperty != other.childProperty) return false if (this.dataClass != other.dataClass) return false return true } override fun equalsIgnoringEntitySource(other: Any?): Boolean { if (other == null) return false if (this::class != other::class) return false other as XChildEntityData if (this.childProperty != other.childProperty) return false if (this.dataClass != other.dataClass) return false return true } override fun hashCode(): Int { var result = entitySource.hashCode() result = 31 * result + childProperty.hashCode() result = 31 * result + dataClass.hashCode() return result } override fun hashCodeIgnoringEntitySource(): Int { var result = javaClass.hashCode() result = 31 * result + childProperty.hashCode() result = 31 * result + dataClass.hashCode() return result } override fun collectClassUsagesData(collector: UsedClassesCollector) { collector.add(DataClassX::class.java) this.dataClass?.let { collector.addDataToInspect(it) } collector.sameForAllEntities = true } }
apache-2.0
ea2904f4b08a57f7ab39e141ae18e11f
37.93994
188
0.671936
5.439178
false
false
false
false
RuneSuite/client
updater-mapper/src/main/java/org/runestar/client/updater/mapper/std/classes/Model.kt
1
13509
package org.runestar.client.updater.mapper.std.classes import org.runestar.client.common.startsWith import org.objectweb.asm.Opcodes.* import org.objectweb.asm.Type.* import org.runestar.client.updater.mapper.IdentityMapper import org.runestar.client.updater.mapper.OrderMapper import org.runestar.client.updater.mapper.UniqueMapper import org.runestar.client.updater.mapper.DependsOn import org.runestar.client.updater.mapper.MethodParameters import org.runestar.client.updater.mapper.and import org.runestar.client.updater.mapper.predicateOf import org.runestar.client.updater.mapper.type import org.runestar.client.updater.mapper.withDimensions import org.runestar.client.updater.mapper.Class2 import org.runestar.client.updater.mapper.Instruction2 import org.runestar.client.updater.mapper.Method2 @DependsOn(Entity.getModel::class) class Model : IdentityMapper.Class() { override val predicate = predicateOf<Class2> { it.type == method<Entity.getModel>().returnType } class verticesX : OrderMapper.InConstructor.Field(Model::class, 0) { override val constructorPredicate = predicateOf<Method2> { it.arguments.isNotEmpty() } override val predicate = predicateOf<Instruction2> { it.opcode == PUTFIELD && it.fieldType == IntArray::class.type } } class verticesY : OrderMapper.InConstructor.Field(Model::class, 1) { override val constructorPredicate = predicateOf<Method2> { it.arguments.isNotEmpty() } override val predicate = predicateOf<Instruction2> { it.opcode == PUTFIELD && it.fieldType == IntArray::class.type } } class verticesZ : OrderMapper.InConstructor.Field(Model::class, 2) { override val constructorPredicate = predicateOf<Method2> { it.arguments.isNotEmpty() } override val predicate = predicateOf<Instruction2> { it.opcode == PUTFIELD && it.fieldType == IntArray::class.type } } class indices1 : OrderMapper.InConstructor.Field(Model::class, 3) { override val constructorPredicate = predicateOf<Method2> { it.arguments.isNotEmpty() } override val predicate = predicateOf<Instruction2> { it.opcode == PUTFIELD && it.fieldType == IntArray::class.type } } class indices2 : OrderMapper.InConstructor.Field(Model::class, 4) { override val constructorPredicate = predicateOf<Method2> { it.arguments.isNotEmpty() } override val predicate = predicateOf<Instruction2> { it.opcode == PUTFIELD && it.fieldType == IntArray::class.type } } class indices3 : OrderMapper.InConstructor.Field(Model::class, 5) { override val constructorPredicate = predicateOf<Method2> { it.arguments.isNotEmpty() } override val predicate = predicateOf<Instruction2> { it.opcode == PUTFIELD && it.fieldType == IntArray::class.type } } @MethodParameters("yaw", "cameraPitchSine", "cameraPitchCosine", "cameraYawSine", "cameraYawCosine", "x", "y", "z", "tag") @DependsOn(Entity.draw::class) class draw : IdentityMapper.InstanceMethod() { override val predicate = predicateOf<Method2> { it.mark == method<Entity.draw>().mark } } @MethodParameters("pitch") @DependsOn(Projectile.getModel::class) class rotateZ : OrderMapper.InMethod.Method(Projectile.getModel::class, 0) { override val predicate = predicateOf<Instruction2> { it.isMethod && it.methodOwner == type<Model>() } } class draw0 : IdentityMapper.InstanceMethod() { override val predicate = predicateOf<Method2> { it.returnType == VOID_TYPE } .and { it.arguments.startsWith(BOOLEAN_TYPE, BOOLEAN_TYPE, BOOLEAN_TYPE) } } class verticesCount : OrderMapper.InConstructor.Field(Model::class, 0) { override val predicate = predicateOf<Instruction2> { it.opcode == PUTFIELD && it.fieldType == INT_TYPE } override val constructorPredicate = predicateOf<Method2> { it.arguments.isEmpty() } } class indicesCount : OrderMapper.InConstructor.Field(Model::class, 1) { override val predicate = predicateOf<Instruction2> { it.opcode == PUTFIELD && it.fieldType == INT_TYPE } override val constructorPredicate = predicateOf<Method2> { it.arguments.isEmpty() } } // either xz or xyz @DependsOn(Model.draw::class) class xzRadius : OrderMapper.InMethod.Field(Model.draw::class, 1) { override val predicate = predicateOf<Instruction2> { it.opcode == GETFIELD && it.fieldType == INT_TYPE } } @MethodParameters("x", "y", "z") @DependsOn(Npc.getModel::class) class offset : OrderMapper.InMethod.Method(Npc.getModel::class, 1) { override val predicate = predicateOf<Instruction2> { it.opcode == INVOKEVIRTUAL && it.methodOwner == type<Model>() } } // yaw @MethodParameters() @DependsOn(Player.getModel::class) class rotateY90Ccw : OrderMapper.InMethod.Method(Player.getModel::class, -1) { override val predicate = predicateOf<Instruction2> { it.opcode == INVOKEVIRTUAL && it.methodOwner == type<Model>() && it.methodType.argumentTypes.size in 0..1 } } @MethodParameters() @DependsOn(rotateZ::class) class resetBounds : UniqueMapper.InMethod.Method(rotateZ::class) { override val predicate = predicateOf<Instruction2> { it.isMethod } } // new = old * scale / 128 @MethodParameters("x", "y", "z") class resize : IdentityMapper.InstanceMethod() { override val predicate = predicateOf<Method2> { it.returnType == VOID_TYPE } .and { it.arguments.size in 3..4 } .and { it.arguments.startsWith(INT_TYPE, INT_TYPE, INT_TYPE) } .and { it.instructions.count { it.opcode == SIPUSH && it.intOperand == 128 } == 3 } } @MethodParameters() @DependsOn(draw::class) class calculateBoundsCylinder : OrderMapper.InMethod.Method(draw::class, 0) { override val predicate = predicateOf<Instruction2> { it.isMethod } } @MethodParameters("yaw") @DependsOn(draw::class) class calculateBoundingBox : OrderMapper.InMethod.Method(draw::class, 1) { override val predicate = predicateOf<Instruction2> { it.isMethod } } @DependsOn(draw::class) class boundsType : OrderMapper.InMethod.Field(draw::class, 0) { override val predicate = predicateOf<Instruction2> { it.opcode == GETFIELD && it.fieldType == INT_TYPE } } @DependsOn(calculateBoundsCylinder::class) class bottomY : OrderMapper.InMethod.Field(calculateBoundsCylinder::class, 2) { override val predicate = predicateOf<Instruction2> { it.opcode == PUTFIELD && it.fieldType == INT_TYPE } } @DependsOn(calculateBoundsCylinder::class) class radius : OrderMapper.InMethod.Field(calculateBoundsCylinder::class, -2) { override val predicate = predicateOf<Instruction2> { it.opcode == PUTFIELD && it.fieldType == INT_TYPE } } @DependsOn(calculateBoundsCylinder::class) class diameter : OrderMapper.InMethod.Field(calculateBoundsCylinder::class, -1) { override val predicate = predicateOf<Instruction2> { it.opcode == PUTFIELD && it.fieldType == INT_TYPE } } @DependsOn(calculateBoundingBox::class) class xMid : OrderMapper.InMethod.Field(calculateBoundingBox::class, 0) { override val predicate = predicateOf<Instruction2> { it.opcode == PUTFIELD && it.fieldType == INT_TYPE } } @DependsOn(calculateBoundingBox::class) class yMid : OrderMapper.InMethod.Field(calculateBoundingBox::class, 1) { override val predicate = predicateOf<Instruction2> { it.opcode == PUTFIELD && it.fieldType == INT_TYPE } } @DependsOn(calculateBoundingBox::class) class zMid : OrderMapper.InMethod.Field(calculateBoundingBox::class, 2) { override val predicate = predicateOf<Instruction2> { it.opcode == PUTFIELD && it.fieldType == INT_TYPE } } @DependsOn(calculateBoundingBox::class) class xMidOffset : OrderMapper.InMethod.Field(calculateBoundingBox::class, 3) { override val predicate = predicateOf<Instruction2> { it.opcode == PUTFIELD && it.fieldType == INT_TYPE } } @DependsOn(calculateBoundingBox::class) class yMidOffset : OrderMapper.InMethod.Field(calculateBoundingBox::class, 4) { override val predicate = predicateOf<Instruction2> { it.opcode == PUTFIELD && it.fieldType == INT_TYPE } } @DependsOn(calculateBoundingBox::class) class zMidOffset : OrderMapper.InMethod.Field(calculateBoundingBox::class, 5) { override val predicate = predicateOf<Instruction2> { it.opcode == PUTFIELD && it.fieldType == INT_TYPE } } @DependsOn(Model::class, Player.getModel::class) class isSingleTile : UniqueMapper.InMethod.Field(Player.getModel::class) { override val predicate = predicateOf<Instruction2> { it.isField && it.fieldOwner == type<Model>() && it.fieldType == BOOLEAN_TYPE } } @DependsOn(Model::class) class copy0 : IdentityMapper.InstanceMethod() { override val predicate = predicateOf<Method2> { it.returnType == type<Model>() } .and { it.arguments.startsWith(BOOLEAN_TYPE, type<Model>(), ByteArray::class.type) } } @MethodParameters("type", "labels", "tx", "ty", "tz") class transform : IdentityMapper.InstanceMethod() { override val predicate = predicateOf<Method2> { it.returnType == VOID_TYPE } .and { it.arguments.size in 5..6 } .and { it.arguments.startsWith(INT_TYPE, IntArray::class.type, INT_TYPE, INT_TYPE, INT_TYPE) } } @DependsOn(transform::class) class vertexLabels : OrderMapper.InMethod.Field(transform::class, 0) { override val predicate = predicateOf<Instruction2> { it.opcode == GETFIELD && it.fieldType == INT_TYPE.withDimensions(2) } } @DependsOn(transform::class) class faceLabelsAlpha : OrderMapper.InMethod.Field(transform::class, -1) { override val predicate = predicateOf<Instruction2> { it.opcode == GETFIELD && it.fieldType == INT_TYPE.withDimensions(2) } } @MethodParameters("frames", "frame") @DependsOn(AnimFrameset::class) class animate : IdentityMapper.InstanceMethod() { override val predicate = predicateOf<Method2> { it.returnType == VOID_TYPE } .and { it.arguments.size in 2..3 } .and { it.arguments.startsWith(type<AnimFrameset>(), INT_TYPE) } } @DependsOn(AnimFrameset::class) class animate2 : IdentityMapper.InstanceMethod() { override val predicate = predicateOf<Method2> { it.returnType == VOID_TYPE } .and { it.arguments.size in 5..6 } .and { it.arguments.startsWith(type<AnimFrameset>(), INT_TYPE, type<AnimFrameset>(), INT_TYPE, IntArray::class.type) } } @MethodParameters("b") @DependsOn(SpotType.getModel::class) class toSharedSpotAnimationModel : UniqueMapper.InMethod.Method(SpotType.getModel::class) { override val predicate = predicateOf<Instruction2> { it.isMethod && it.methodOwner == type<Model>() && it.methodType.returnType == type<Model>() } } @MethodParameters("b") @DependsOn(NPCType.getModel::class) class toSharedSequenceModel : UniqueMapper.InMethod.Method(NPCType.getModel::class) { override val predicate = predicateOf<Instruction2> { it.isMethod && it.methodOwner == type<Model>() && it.methodType.returnType == type<Model>() } } @DependsOn(transform::class) class faceAlphas : UniqueMapper.InMethod.Field(transform::class) { override val predicate = predicateOf<Instruction2> { it.opcode == GETFIELD && it.fieldType == ByteArray::class.type } } @MethodParameters() class rotateY180 : IdentityMapper.InstanceMethod() { override val predicate = predicateOf<Method2> { it.returnType == VOID_TYPE } .and { it.arguments.size in 0..1 } .and { it.instructions.count { it.opcode == INEG } == 2 } .and { it.instructions.count { it.opcode == IASTORE } == 2 } } @MethodParameters() @DependsOn(rotateY90Ccw::class) class rotateY270Ccw : IdentityMapper.InstanceMethod() { override val predicate = predicateOf<Method2> { it.returnType == VOID_TYPE } .and { it.arguments.size in 0..1 } .and { it.instructions.count { it.opcode == INEG } == 1 } .and { it != method<rotateY90Ccw>() } } @DependsOn(UnlitModel.light::class) class faceColors1 : OrderMapper.InMethod.Field(UnlitModel.light::class, 0) { override val predicate = predicateOf<Instruction2> { it.opcode == PUTFIELD && it.fieldOwner == type<Model>() && it.fieldType == IntArray::class.type } } @DependsOn(UnlitModel.light::class) class faceColors2 : OrderMapper.InMethod.Field(UnlitModel.light::class, 1) { override val predicate = predicateOf<Instruction2> { it.opcode == PUTFIELD && it.fieldOwner == type<Model>() && it.fieldType == IntArray::class.type } } @DependsOn(UnlitModel.light::class) class faceColors3 : OrderMapper.InMethod.Field(UnlitModel.light::class, 2) { override val predicate = predicateOf<Instruction2> { it.opcode == PUTFIELD && it.fieldOwner == type<Model>() && it.fieldType == IntArray::class.type } } @DependsOn(UnlitModel.light::class) class faceTextures : OrderMapper.InMethod.Field(UnlitModel.light::class, -1) { override val predicate = predicateOf<Instruction2> { it.opcode == PUTFIELD && it.fieldOwner == type<Model>() && it.fieldType == ShortArray::class.type } } }
mit
35bf84ca50bedeb296a13849c882960e
48.669118
168
0.686431
4.298123
false
false
false
false
JetBrains/intellij-community
platform/lang-impl/src/com/intellij/codeInsight/hints/declarative/impl/InlayPresentationList.kt
1
7805
// 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.codeInsight.hints.declarative.impl import com.intellij.codeInsight.hints.InlayHintsUtils import com.intellij.codeInsight.hints.declarative.impl.util.TinyTree import com.intellij.codeInsight.hints.presentation.InlayTextMetricsStorage import com.intellij.codeInsight.hints.presentation.withTranslated import com.intellij.openapi.editor.DefaultLanguageHighlighterColors import com.intellij.openapi.editor.Inlay import com.intellij.openapi.editor.colors.EditorColors import com.intellij.openapi.editor.event.EditorMouseEvent import com.intellij.openapi.editor.impl.EditorImpl import com.intellij.openapi.editor.markup.TextAttributes import com.intellij.util.concurrency.annotations.RequiresEdt import com.intellij.util.ui.GraphicsUtil import org.jetbrains.annotations.TestOnly import java.awt.Graphics2D import java.awt.Point import java.awt.geom.Rectangle2D /** * @see PresentationTreeBuilderImpl */ class InlayPresentationList(private var state: TinyTree<Any?>, @TestOnly var hasBackground: Boolean, @TestOnly var isDisabled: Boolean) { companion object { private const val NOT_COMPUTED = -1 private const val LEFT_MARGIN = 7 private const val RIGHT_MARGIN = 7 private const val BOTTOM_MARGIN = 1 private const val TOP_MARGIN = 1 private const val ARC_WIDTH = 8 private const val ARC_HEIGHT = 8 private const val BACKGROUND_ALPHA : Float = 0.55f } private var entries: Array<InlayPresentationEntry> = PresentationEntryBuilder(state).buildPresentationEntries() private var _partialWidthSums: IntArray? = null private var computedWidth: Int = NOT_COMPUTED private fun computePartialSums(fontMetricsStorage: InlayTextMetricsStorage): IntArray { var width = 0 return IntArray(entries.size) { val entry = entries[it] val oldWidth = width width += entry.computeWidth(fontMetricsStorage) oldWidth } } private fun getPartialWidthSums(storage: InlayTextMetricsStorage): IntArray { val sums = _partialWidthSums if (sums != null) { return sums } val computed = computePartialSums(storage) _partialWidthSums = computed return computed } fun handleClick(e: EditorMouseEvent, pointInsideInlay: Point, fontMetricsStorage: InlayTextMetricsStorage) { val entry = findEntryByPoint(fontMetricsStorage, pointInsideInlay) ?: return entry.handleClick(e.editor, this) } private fun findEntryByPoint(fontMetricsStorage: InlayTextMetricsStorage, pointInsideInlay: Point): InlayPresentationEntry? { val x = pointInsideInlay.x val partialWidthSums = getPartialWidthSums(fontMetricsStorage) for ((index, entry) in entries.withIndex()) { val leftBound = partialWidthSums[index] + LEFT_MARGIN val rightBound = partialWidthSums.getOrElse(index + 1) { Int.MAX_VALUE - LEFT_MARGIN } + LEFT_MARGIN if (x in leftBound..rightBound) { return entry } } return null } @RequiresEdt fun updateState(state: TinyTree<Any?>, disabled: Boolean, hasBackground: Boolean) { updateStateTree(state, this.state, 0, 0) this.state = state this.entries = PresentationEntryBuilder(state).buildPresentationEntries() this.computedWidth = NOT_COMPUTED this._partialWidthSums = null this.isDisabled = disabled this.hasBackground = hasBackground } private fun updateStateTree(treeToUpdate: TinyTree<Any?>, treeToUpdateFrom: TinyTree<Any?>, treeToUpdateIndex: Byte, treeToUpdateFromIndex: Byte) { // we want to preserve the structure val treeToUpdateTag = treeToUpdate.getBytePayload(treeToUpdateIndex) val treeToUpdateFromTag = treeToUpdateFrom.getBytePayload(treeToUpdateFromIndex) if (treeToUpdateFromTag == InlayTags.COLLAPSIBLE_LIST_EXPLICITLY_EXPANDED_TAG || treeToUpdateFromTag == InlayTags.COLLAPSIBLE_LIST_EXPLICITLY_COLLAPSED_TAG) { if (treeToUpdateTag == InlayTags.COLLAPSIBLE_LIST_EXPLICITLY_EXPANDED_TAG || treeToUpdateTag == InlayTags.COLLAPSIBLE_LIST_EXPLICITLY_COLLAPSED_TAG || treeToUpdateTag == InlayTags.COLLAPSIBLE_LIST_IMPLICITLY_EXPANDED_TAG || treeToUpdateTag == InlayTags.COLLAPSIBLE_LIST_IMPLICITLY_COLLAPSED_TAG) { treeToUpdate.setBytePayload(nodePayload = treeToUpdateFromTag, index = treeToUpdateIndex) } } treeToUpdateFrom.syncProcessChildren(treeToUpdateFromIndex, treeToUpdateIndex, treeToUpdate) { treeToUpdateFromChildIndex, treeToUpdateChildIndex -> updateStateTree(treeToUpdate, treeToUpdateFrom, treeToUpdateChildIndex, treeToUpdateFromChildIndex) true } } fun toggleTreeState(parentIndexToSwitch: Byte) { when (val payload = state.getBytePayload(parentIndexToSwitch)) { InlayTags.COLLAPSIBLE_LIST_EXPLICITLY_COLLAPSED_TAG, InlayTags.COLLAPSIBLE_LIST_IMPLICITLY_COLLAPSED_TAG -> { state.setBytePayload(InlayTags.COLLAPSIBLE_LIST_EXPLICITLY_EXPANDED_TAG, parentIndexToSwitch) } InlayTags.COLLAPSIBLE_LIST_EXPLICITLY_EXPANDED_TAG, InlayTags.COLLAPSIBLE_LIST_IMPLICITLY_EXPANDED_TAG -> { state.setBytePayload(InlayTags.COLLAPSIBLE_LIST_EXPLICITLY_COLLAPSED_TAG, parentIndexToSwitch) } else -> { error("Unexpected payload: $payload") } } updateState(state, isDisabled, hasBackground) } fun getWidthInPixels(textMetricsStorage: InlayTextMetricsStorage) : Int { if (computedWidth == NOT_COMPUTED) { val width = entries.sumOf { it.computeWidth(textMetricsStorage) } + LEFT_MARGIN + RIGHT_MARGIN computedWidth = width return width } return computedWidth } fun paint(inlay: Inlay<*>, g: Graphics2D, targetRegion: Rectangle2D, textAttributes: TextAttributes) { val editor = inlay.editor as EditorImpl val storage = InlayHintsUtils.getTextMetricStorage(editor) val height = if (entries.isEmpty()) 0 else entries.maxOf { it.computeHeight(storage) } var xOffset = 0 val gap = (targetRegion.height.toInt() - height) / 2 val attrKey = if (hasBackground) DefaultLanguageHighlighterColors.INLAY_DEFAULT else DefaultLanguageHighlighterColors.INLAY_TEXT_WITHOUT_BACKGROUND val attrs = editor.colorsScheme.getAttributes(attrKey) g.withTranslated(targetRegion.x, targetRegion.y) { if (hasBackground) { val rectHeight = height + TOP_MARGIN + BOTTOM_MARGIN val rectWidth = getWidthInPixels(storage) val config = GraphicsUtil.setupAAPainting(g) GraphicsUtil.paintWithAlpha(g, BACKGROUND_ALPHA) g.color = attrs.backgroundColor ?: textAttributes.backgroundColor g.fillRoundRect(0, gap, rectWidth, rectHeight, ARC_WIDTH, ARC_HEIGHT) config.restore() } } g.withTranslated(LEFT_MARGIN + targetRegion.x, targetRegion.y) { for (entry in entries) { val hovered = entry.isHovered val finalAttrs = if (hovered) { val refAttrs = inlay.editor.colorsScheme.getAttributes(EditorColors.REFERENCE_HYPERLINK_COLOR) val inlayAttrsWithRefForeground = attrs.clone() inlayAttrsWithRefForeground.foregroundColor = refAttrs.foregroundColor inlayAttrsWithRefForeground } else { attrs } g.withTranslated(xOffset, 0) { entry.render(g, storage, finalAttrs, isDisabled, gap) } xOffset += entry.computeWidth(storage) } } } @TestOnly fun getEntries(): Array<InlayPresentationEntry> { return entries } fun getMouseArea(pointInsideInlay: Point, fontMetricsStorage: InlayTextMetricsStorage): InlayMouseArea? { val entry = findEntryByPoint(fontMetricsStorage, pointInsideInlay) ?: return null return entry.clickArea } }
apache-2.0
7135c34e4631b6171cbfae36af469a23
41.423913
152
0.741192
4.665272
false
false
false
false
JetBrains/intellij-community
platform/lang-impl/src/com/intellij/codeInsight/hints/declarative/impl/DeclarativeInlayRenderer.kt
1
3799
// 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.codeInsight.hints.declarative.impl import com.intellij.codeInsight.CodeInsightBundle import com.intellij.codeInsight.hints.declarative.DeclarativeInlayHintsSettings import com.intellij.codeInsight.hints.declarative.InlayHintsProviderFactory import com.intellij.codeInsight.hints.declarative.impl.util.TinyTree import com.intellij.codeInsight.hints.presentation.InlayTextMetricsStorage import com.intellij.openapi.actionSystem.ActionUpdateThread import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.DefaultActionGroup import com.intellij.openapi.editor.EditorCustomElementRenderer import com.intellij.openapi.editor.Inlay import com.intellij.openapi.editor.event.EditorMouseEvent import com.intellij.openapi.editor.markup.TextAttributes import com.intellij.openapi.ui.JBPopupMenu import com.intellij.psi.PsiDocumentManager import com.intellij.util.concurrency.annotations.RequiresEdt import org.jetbrains.annotations.Nls import org.jetbrains.annotations.TestOnly import java.awt.Graphics2D import java.awt.Point import java.awt.geom.Rectangle2D class DeclarativeInlayRenderer( @TestOnly val presentationList: InlayPresentationList, private val fontMetricsStorage: InlayTextMetricsStorage, val providerId: String, ) : EditorCustomElementRenderer { private var inlay: Inlay<DeclarativeInlayRenderer>? = null override fun calcWidthInPixels(inlay: Inlay<*>): Int { return presentationList.getWidthInPixels(fontMetricsStorage) } @RequiresEdt fun updateState(newState: TinyTree<Any?>, disabled: Boolean, hasBackground: Boolean) { presentationList.updateState(newState, disabled, hasBackground) } override fun paint(inlay: Inlay<*>, g: Graphics2D, targetRegion: Rectangle2D, textAttributes: TextAttributes) { presentationList.paint(inlay, g, targetRegion, textAttributes) } fun handleLeftClick(e: EditorMouseEvent, pointInsideInlay: Point) { presentationList.handleClick(e, pointInsideInlay, fontMetricsStorage) } fun handleRightClick(e: EditorMouseEvent) { val project = e.editor.project ?: return val document = e.editor.document val psiFile = PsiDocumentManager.getInstance(project).getPsiFile(document) ?: return val providerInfo = InlayHintsProviderFactory.getProviderInfo(psiFile.language, providerId) ?: return val providerName = providerInfo.providerName JBPopupMenu.showByEvent(e.mouseEvent, "InlayMenu", DefaultActionGroup(DisableDeclarativeInlayAction(providerName, providerId))) } fun setInlay(inlay: Inlay<DeclarativeInlayRenderer>) { this.inlay = inlay } fun getMouseArea(pointInsideInlay: Point): InlayMouseArea? { return presentationList.getMouseArea(pointInsideInlay, fontMetricsStorage) } // this should not be shown anywhere, but it is required to show custom menu in com.intellij.openapi.editor.impl.EditorImpl.DefaultPopupHandler.getActionGroup override fun getContextMenuGroupId(inlay: Inlay<*>): String { return "DummyActionGroup" } } private class DisableDeclarativeInlayAction(private val providerName: @Nls String, private val providerId: String) : AnAction() { override fun getActionUpdateThread(): ActionUpdateThread { return ActionUpdateThread.BGT } override fun update(e: AnActionEvent) { e.presentation.text = CodeInsightBundle.message("inlay.hints.declarative.disable.action.text", providerName) } override fun actionPerformed(e: AnActionEvent) { val project = e.project ?: return val settings = DeclarativeInlayHintsSettings.getInstance(project) settings.setProviderEnabled(providerId, false) } }
apache-2.0
8aafce4dc1928ccb3ad64429c190399d
42.181818
160
0.809687
4.808861
false
false
false
false
StepicOrg/stepik-android
app/src/main/java/org/stepik/android/view/catalog/ui/adapter/delegate/OfflineAdapterDelegate.kt
1
2081
package org.stepik.android.view.catalog.ui.adapter.delegate import android.view.View import android.view.ViewGroup import androidx.core.view.doOnLayout import androidx.core.view.isVisible import androidx.core.view.updateLayoutParams import kotlinx.android.extensions.LayoutContainer import kotlinx.android.synthetic.main.error_no_connection_with_button_small.* import org.stepic.droid.R import org.stepik.android.view.catalog.model.CatalogItem import ru.nobird.app.core.model.safeCast import ru.nobird.android.ui.adapterdelegates.AdapterDelegate import ru.nobird.android.ui.adapterdelegates.DelegateViewHolder class OfflineAdapterDelegate( private val onRetry: () -> Unit ) : AdapterDelegate<CatalogItem, DelegateViewHolder<CatalogItem>>() { override fun isForViewType(position: Int, data: CatalogItem): Boolean = data is CatalogItem.Offline override fun onCreateViewHolder(parent: ViewGroup): DelegateViewHolder<CatalogItem> { val view = createView(parent, R.layout.error_no_connection_with_button_small) view.updateLayoutParams<ViewGroup.MarginLayoutParams> { width = ViewGroup.LayoutParams.MATCH_PARENT } return OfflineViewHolder(view, onRetry = onRetry) } private class OfflineViewHolder( override val containerView: View, private val onRetry: () -> Unit ) : DelegateViewHolder<CatalogItem>(containerView), LayoutContainer { init { tryAgain.setOnClickListener { onRetry() } containerView.isVisible = true } override fun onBind(data: CatalogItem) { data as CatalogItem.Offline itemView.doOnLayout { val parent = it.parent.safeCast<View>() ?: return@doOnLayout val remainingHeight = parent.height - containerView.bottom - containerView.top if (remainingHeight > 0) { itemView.updateLayoutParams { height = containerView.height + remainingHeight } } } } } }
apache-2.0
67982b1b9e5ea78a877c20c46b1f0e38
37.555556
94
0.691014
5.002404
false
false
false
false
allotria/intellij-community
platform/external-system-impl/testSrc/com/intellij/openapi/externalSystem/autoimport/MockProjectAware.kt
3
4196
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.externalSystem.autoimport import com.intellij.openapi.Disposable import com.intellij.openapi.externalSystem.autoimport.ExternalSystemRefreshStatus.SUCCESS import com.intellij.openapi.externalSystem.autoimport.MockProjectAware.RefreshCollisionPassType.* import com.intellij.openapi.observable.operations.AnonymousParallelOperationTrace import com.intellij.openapi.observable.operations.AnonymousParallelOperationTrace.Companion.task import com.intellij.openapi.util.Disposer import com.intellij.util.ConcurrencyUtil.once import com.intellij.util.EventDispatcher import java.util.* import java.util.concurrent.atomic.AtomicInteger import java.util.concurrent.atomic.AtomicReference class MockProjectAware(override val projectId: ExternalSystemProjectId) : ExternalSystemProjectAware { val subscribeCounter = AtomicInteger(0) val unsubscribeCounter = AtomicInteger(0) val settingsAccessCounter = AtomicInteger(0) val refreshCounter = AtomicInteger(0) val refreshCollisionPassType = AtomicReference(DUPLICATE) val refreshStatus = AtomicReference(SUCCESS) private val eventDispatcher = EventDispatcher.create(Listener::class.java) private val refresh = AnonymousParallelOperationTrace(debugName = "$projectId MockProjectAware.refreshProject") private val _settingsFiles = LinkedHashSet<String>() override val settingsFiles: Set<String> get() = _settingsFiles.toSet().also { settingsAccessCounter.incrementAndGet() } fun resetAssertionCounters() { settingsAccessCounter.set(0) refreshCounter.set(0) subscribeCounter.set(0) unsubscribeCounter.set(0) } fun registerSettingsFile(path: String) { _settingsFiles.add(path) } override fun subscribe(listener: ExternalSystemProjectRefreshListener, parentDisposable: Disposable) { eventDispatcher.addListener(listener.asListener(), parentDisposable) subscribeCounter.incrementAndGet() Disposer.register(parentDisposable, Disposable { unsubscribeCounter.incrementAndGet() }) } override fun reloadProject(context: ExternalSystemProjectReloadContext) { when (refreshCollisionPassType.get()!!) { DUPLICATE -> { doRefreshProject(context) } CANCEL -> { val task = once { doRefreshProject(context) } refresh.afterOperation { task.run() } if (refresh.isOperationCompleted()) task.run() } IGNORE -> { if (refresh.isOperationCompleted()) { doRefreshProject(context) } } } } private fun doRefreshProject(context: ExternalSystemProjectReloadContext) { val refreshStatus = refreshStatus.get() eventDispatcher.multicaster.beforeProjectRefresh() refresh.task { refreshCounter.incrementAndGet() eventDispatcher.multicaster.insideProjectRefresh(context) } eventDispatcher.multicaster.afterProjectRefresh(refreshStatus) } fun onceDuringRefresh(action: (ExternalSystemProjectReloadContext) -> Unit) { val disposable = Disposer.newDisposable() duringRefresh(disposable) { Disposer.dispose(disposable) action(it) } } fun duringRefresh(parentDisposable: Disposable, action: (ExternalSystemProjectReloadContext) -> Unit) { eventDispatcher.addListener(object : Listener { override fun insideProjectRefresh(context: ExternalSystemProjectReloadContext) = action(context) }, parentDisposable) } private fun ExternalSystemProjectRefreshListener.asListener(): Listener { return object : Listener, ExternalSystemProjectRefreshListener { override fun beforeProjectRefresh() { [email protected]() } override fun afterProjectRefresh(status: ExternalSystemRefreshStatus) { [email protected](status) } } } interface Listener : ExternalSystemProjectRefreshListener, EventListener { @JvmDefault fun insideProjectRefresh(context: ExternalSystemProjectReloadContext) { } } enum class RefreshCollisionPassType { DUPLICATE, CANCEL, IGNORE } }
apache-2.0
26977685c4e32133de0220b111adef0f
36.141593
140
0.766444
5.271357
false
false
false
false
android/wear-os-samples
WearTilesKotlin/app/src/debug/java/com/example/wear/tiles/golden/Workout.kt
1
4741
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.wear.tiles.golden import android.content.Context import androidx.wear.tiles.ColorBuilders import androidx.wear.tiles.DeviceParametersBuilders.DeviceParameters import androidx.wear.tiles.DimensionBuilders.ExpandedDimensionProp import androidx.wear.tiles.ModifiersBuilders.Clickable import androidx.wear.tiles.material.Button import androidx.wear.tiles.material.ChipColors import androidx.wear.tiles.material.CompactChip import androidx.wear.tiles.material.Text import androidx.wear.tiles.material.TitleChip import androidx.wear.tiles.material.Typography import androidx.wear.tiles.material.layouts.MultiButtonLayout import androidx.wear.tiles.material.layouts.PrimaryLayout object Workout { const val BUTTON_1_ICON_ID = "workout 1" const val BUTTON_2_ICON_ID = "workout 2" const val BUTTON_3_ICON_ID = "workout 3" fun buttonsLayout( context: Context, deviceParameters: DeviceParameters, weekSummary: String, button1Clickable: Clickable, button2Clickable: Clickable, button3Clickable: Clickable, chipClickable: Clickable ) = PrimaryLayout.Builder(deviceParameters) .setPrimaryLabelTextContent( Text.Builder(context, weekSummary) .setTypography(Typography.TYPOGRAPHY_CAPTION1) .setColor(ColorBuilders.argb(GoldenTilesColors.Blue)) .build() ) .setContent( MultiButtonLayout.Builder() .addButtonContent( Button.Builder(context, button1Clickable).setIconContent(BUTTON_1_ICON_ID) .build() ) .addButtonContent( Button.Builder(context, button2Clickable).setIconContent(BUTTON_2_ICON_ID) .build() ) .addButtonContent( Button.Builder(context, button3Clickable).setIconContent(BUTTON_3_ICON_ID) .build() ) .build() ) .setPrimaryChipContent( CompactChip.Builder(context, "More", chipClickable, deviceParameters) .setChipColors( ChipColors( /*backgroundColor=*/ ColorBuilders.argb(GoldenTilesColors.BlueGray), /*contentColor=*/ ColorBuilders.argb(GoldenTilesColors.White) ) ) .build() ) .build() fun largeChipLayout( context: Context, deviceParameters: DeviceParameters, clickable: Clickable, lastWorkoutSummary: String ) = PrimaryLayout.Builder(deviceParameters) .setPrimaryLabelTextContent( Text.Builder(context, "Power Yoga") .setTypography(Typography.TYPOGRAPHY_CAPTION1) .setColor(ColorBuilders.argb(GoldenTilesColors.Yellow)) .build() ) .setContent( TitleChip.Builder(context, "Start", clickable, deviceParameters) // TitleChip/Chip's default width == device width minus some padding // Since PrimaryLayout's content slot already has margin, this leads to clipping // unless we override the width to use the available space .setWidth(ExpandedDimensionProp.Builder().build()) .setChipColors( ChipColors( /*backgroundColor=*/ ColorBuilders.argb(GoldenTilesColors.Yellow), /*contentColor=*/ ColorBuilders.argb(GoldenTilesColors.Black) ) ) .build() ) .setSecondaryLabelTextContent( Text.Builder(context, lastWorkoutSummary) .setTypography(Typography.TYPOGRAPHY_CAPTION1) .setColor(ColorBuilders.argb(GoldenTilesColors.White)) .build() ) .build() }
apache-2.0
ec020ecf01e32fa425ef5c2eb10fc384
40.587719
98
0.609576
5.357062
false
false
false
false
leafclick/intellij-community
uast/uast-common/src/org/jetbrains/uast/expressions/UStringConcatenationsFacade.kt
1
4454
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.uast.expressions import com.intellij.openapi.util.TextRange import com.intellij.psi.ElementManipulators import com.intellij.psi.PsiElement import com.intellij.psi.PsiLanguageInjectionHost import com.intellij.psi.util.PartiallyKnownString import com.intellij.psi.util.StringEntry import org.jetbrains.annotations.ApiStatus import org.jetbrains.uast.* class UStringConcatenationsFacade @ApiStatus.Experimental constructor(uContext: UExpression) { val uastOperands: Sequence<UExpression> = run { when { uContext is UPolyadicExpression -> uContext.operands.asSequence() uContext is ULiteralExpression && uContext.uastParent !is UPolyadicExpression -> { val host = uContext.sourceInjectionHost if (host == null || !host.isValidHost) emptySequence() else sequenceOf(uContext) } else -> emptySequence() } } val psiLanguageInjectionHosts: Sequence<PsiLanguageInjectionHost> = uastOperands.mapNotNull { (it as? ULiteralExpression)?.psiLanguageInjectionHost }.distinct() /** * external (non string-literal) expressions in string interpolations and/or concatenations */ val placeholders: List<Pair<TextRange, String>> get() = segments.mapNotNull { segment -> when (segment) { is Segment.Placeholder -> segment.range to (segment.value ?: "missingValue") else -> null } } private sealed class Segment { abstract val value: String? abstract val range: TextRange abstract val uExpression: UExpression class StringLiteral(override val value: String, override val range: TextRange, override val uExpression: ULiteralExpression) : Segment() class Placeholder(override val value: String?, override val range: TextRange, override val uExpression: UExpression) : Segment() } private val segments: List<Segment> by lazy(LazyThreadSafetyMode.NONE) { val bounds = uContext.sourcePsi?.textRange ?: return@lazy emptyList<Segment>() val operandsList = uastOperands.toList() ArrayList<Segment>(operandsList.size).apply { for (i in operandsList.indices) { val operand = operandsList[i] val sourcePsi = operand.sourcePsi ?: continue val selfRange = sourcePsi.textRange if (operand is ULiteralExpression) add(Segment.StringLiteral(operand.evaluateString() ?: "", selfRange, operand)) else { val prev = operandsList.getOrNull(i - 1) val next = operandsList.getOrNull(i + 1) val start = when (prev) { null -> bounds.startOffset is ULiteralExpression -> prev.sourcePsi?.textRange?.endOffset ?: selfRange.startOffset else -> selfRange.startOffset } val end = when (next) { null -> bounds.endOffset is ULiteralExpression -> next.sourcePsi?.textRange?.startOffset ?: selfRange.endOffset else -> selfRange.endOffset } val range = TextRange.create(start, end) val evaluate = operand.evaluateString() add(Segment.Placeholder(evaluate, range, operand)) } } } } @ApiStatus.Experimental fun asPartiallyKnownString() : PartiallyKnownString = PartiallyKnownString(segments.map { segment -> segment.value?.let { value -> StringEntry.Known(value, segment.uExpression.sourcePsi, getSegmentInnerTextRange(segment)) } ?: StringEntry.Unknown(segment.uExpression.sourcePsi, getSegmentInnerTextRange(segment)) }) private fun getSegmentInnerTextRange(segment: Segment): TextRange { val sourcePsi = segment.uExpression.sourcePsi ?: throw IllegalStateException("no sourcePsi for $segment") val sourcePsiTextRange = sourcePsi.textRange val range = segment.range if (range.startOffset > sourcePsiTextRange.startOffset) return range.shiftLeft(sourcePsiTextRange.startOffset) return ElementManipulators.getValueTextRange(sourcePsi) } companion object { @JvmStatic fun create(context: PsiElement): UStringConcatenationsFacade? { if (context !is PsiLanguageInjectionHost && context.firstChild !is PsiLanguageInjectionHost) { return null } val uElement = context.toUElement(UExpression::class.java) ?: return null return UStringConcatenationsFacade(uElement) } } }
apache-2.0
271e64e9a1c9f8b19fd1e5e4096b1b2b
40.635514
140
0.712618
5.010124
false
false
false
false
smmribeiro/intellij-community
plugins/markdown/core/src/org/intellij/plugins/markdown/lang/formatter/blocks/MarkdownFormattingBlock.kt
1
3953
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.intellij.plugins.markdown.lang.formatter.blocks import com.intellij.formatting.* import com.intellij.lang.ASTNode import com.intellij.psi.codeStyle.CodeStyleSettings import com.intellij.psi.formatter.common.AbstractBlock import com.intellij.psi.formatter.common.SettingsAwareBlock import com.intellij.psi.tree.TokenSet import org.intellij.plugins.markdown.injection.MarkdownCodeFenceUtils import org.intellij.plugins.markdown.lang.MarkdownElementTypes import org.intellij.plugins.markdown.lang.MarkdownTokenTypeSets import org.intellij.plugins.markdown.lang.formatter.settings.MarkdownCustomCodeStyleSettings import org.intellij.plugins.markdown.lang.psi.MarkdownAstUtils.children import org.intellij.plugins.markdown.lang.psi.MarkdownAstUtils.parents import org.intellij.plugins.markdown.util.MarkdownPsiUtil /** * Formatting block used by markdown plugin * * It defines alignment equal for all block on the same line, and new for inner lists */ internal open class MarkdownFormattingBlock( node: ASTNode, private val settings: CodeStyleSettings, protected val spacing: SpacingBuilder, alignment: Alignment? = null, wrap: Wrap? = null ) : AbstractBlock(node, wrap, alignment), SettingsAwareBlock { companion object { private val NON_ALIGNABLE_LIST_ELEMENTS = TokenSet.orSet(MarkdownTokenTypeSets.LIST_MARKERS, MarkdownTokenTypeSets.LISTS) } override fun getSettings(): CodeStyleSettings = settings protected fun obtainCustomSettings(): MarkdownCustomCodeStyleSettings { return settings.getCustomSettings(MarkdownCustomCodeStyleSettings::class.java) } override fun isLeaf(): Boolean = subBlocks.isEmpty() override fun getSpacing(child1: Block?, child2: Block): Spacing? = spacing.getSpacing(this, child1, child2) override fun getIndent(): Indent? { if (node.elementType in MarkdownTokenTypeSets.LISTS && node.parents(withSelf = false).any { it.elementType == MarkdownElementTypes.LIST_ITEM }) { return Indent.getNormalIndent() } return Indent.getNoneIndent() } /** * Get indent for new formatting block, that will be created when user will start typing after enter * In general `getChildAttributes` defines where to move caret after enter. * Other changes (for example, adding of `>` for blockquote) are handled by MarkdownEnterHandler */ override fun getChildAttributes(newChildIndex: Int): ChildAttributes { return MarkdownEditingAligner.calculateChildAttributes(subBlocks.getOrNull(newChildIndex - 1)) } override fun getSubBlocks(): List<Block?> { //Non top-level codefences cannot be formatted correctly even with correct inject, so -- just ignore it if (MarkdownCodeFenceUtils.isCodeFence(node) && !MarkdownPsiUtil.isTopLevel(node)) return EMPTY return super.getSubBlocks() } override fun buildChildren(): List<Block> { val newAlignment = Alignment.createAlignment() return when (node.elementType) { //Code fence alignment is not supported for now because of manipulator problems // and the fact that when end of code fence is in blockquote -- parser // would treat blockquote as a part of code fence end token MarkdownElementTypes.CODE_FENCE -> emptyList() MarkdownElementTypes.LIST_ITEM -> { MarkdownBlocks.create(node.children(), settings, spacing) { if (it.elementType in NON_ALIGNABLE_LIST_ELEMENTS) alignment else newAlignment }.toList() } MarkdownElementTypes.PARAGRAPH, MarkdownElementTypes.CODE_BLOCK, MarkdownElementTypes.BLOCK_QUOTE -> { MarkdownBlocks.create(node.children(), settings, spacing) { alignment ?: newAlignment }.toList() } else -> { MarkdownBlocks.create(node.children(), settings, spacing) { alignment }.toList() } } } }
apache-2.0
465b967143190ea4d90aeab05b2cce58
43.41573
158
0.7617
4.617991
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/uast/uast-kotlin/tests/testData/LambdaReturn.kt
3
762
package org.jetbrains.uast.kotlin fun foo() { val lam1 = { a: Int -> val b = 1 a + b } val lam2 = { a: Int -> val c = 1 if (a > 0) a + c else a - c } val lam3 = lbd@{ a: Int -> val d = 1 return@lbd a + d } val lam4 = fun(a: Int): String { if (a < 5) return "5" if (a > 0) return "1" else return "2" } val lam5 = fun(a: Int) = "a" + a bar { if (it > 5) return val b = 1 it + b } val x: () -> Unit = { val (a, b) = listOf(1, 2) } val y: () -> Unit = { listOf(1) } } private inline fun bar(lmbd: (Int) -> Int) { lmbd(1) }
apache-2.0
1cb5b2c11d7d84a350874bc0250cb0ad
13.673077
44
0.356955
3.035857
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/tests/testData/intentions/branched/unfolding/assignmentToIf/innerIfTransformed.kt
9
462
// AFTER-WARNING: Parameter 'a' is never used fun <T> doSomething(a: T) {} fun test(n: Int): String { var res: String if (n == 1) { <caret>res = if (3 > 2) { doSomething("***") "one" } else { doSomething("***") "???" } } else if (n == 2) { doSomething("***") res = "two" } else { doSomething("***") res = "too many" } return res }
apache-2.0
b98ce7cd0e0a88b8ce408604e613ca05
18.25
45
0.396104
3.85
false
false
false
false
kickstarter/android-oss
app/src/main/java/com/kickstarter/libs/utils/AnalyticEventsUtils.kt
1
15200
package com.kickstarter.libs.utils import com.kickstarter.libs.RefTag import com.kickstarter.libs.utils.EventContextValues.VideoContextName.LENGTH import com.kickstarter.libs.utils.EventContextValues.VideoContextName.POSITION import com.kickstarter.libs.utils.RewardUtils.isItemized import com.kickstarter.libs.utils.RewardUtils.isReward import com.kickstarter.libs.utils.RewardUtils.isShippable import com.kickstarter.libs.utils.RewardUtils.isTimeLimitedEnd import com.kickstarter.libs.utils.extensions.addOnsCost import com.kickstarter.libs.utils.extensions.bonus import com.kickstarter.libs.utils.extensions.intValueOrZero import com.kickstarter.libs.utils.extensions.isNonZero import com.kickstarter.libs.utils.extensions.isTrue import com.kickstarter.libs.utils.extensions.refTag import com.kickstarter.libs.utils.extensions.rewardCost import com.kickstarter.libs.utils.extensions.round import com.kickstarter.libs.utils.extensions.shippingAmount import com.kickstarter.libs.utils.extensions.timeInDaysOfDuration import com.kickstarter.libs.utils.extensions.timeInSecondsUntilDeadline import com.kickstarter.libs.utils.extensions.totalAmount import com.kickstarter.libs.utils.extensions.totalCountUnique import com.kickstarter.libs.utils.extensions.totalQuantity import com.kickstarter.libs.utils.extensions.userIsCreator import com.kickstarter.models.Activity import com.kickstarter.models.Category import com.kickstarter.models.Location import com.kickstarter.models.Project import com.kickstarter.models.Reward import com.kickstarter.models.Update import com.kickstarter.models.User import com.kickstarter.models.extensions.getCreatedAndDraftProjectsCount import com.kickstarter.services.DiscoveryParams import com.kickstarter.ui.data.CheckoutData import com.kickstarter.ui.data.PledgeData import java.util.Locale import kotlin.math.ceil import kotlin.math.roundToInt object AnalyticEventsUtils { @JvmOverloads fun checkoutProperties(checkoutData: CheckoutData, pledgeData: PledgeData, prefix: String = "checkout_"): Map<String, Any> { val project = pledgeData.projectData().project() val properties = HashMap<String, Any>().apply { put("amount", checkoutData.amount().round()) checkoutData.id()?.let { put("id", it.toString()) } put( "payment_type", checkoutData.paymentType().rawValue().lowercase(Locale.getDefault()) ) put("amount_total_usd", checkoutData.totalAmount(project.staticUsdRate()).round()) put("shipping_amount", checkoutData.shippingAmount()) put("shipping_amount_usd", checkoutData.shippingAmount(project.staticUsdRate()).round()) put("bonus_amount", checkoutData.bonus()) put("bonus_amount_usd", checkoutData.bonus(project.staticUsdRate()).round()) put("add_ons_count_total", pledgeData.totalQuantity()) put("add_ons_count_unique", pledgeData.totalCountUnique()) put("add_ons_minimum_usd", pledgeData.addOnsCost(project.staticUsdRate()).round()) } return MapUtils.prefixKeys(properties, prefix) } @JvmOverloads fun checkoutProperties(checkoutData: CheckoutData, project: Project, addOns: List<Reward>?, prefix: String = "checkout_"): Map<String, Any> { val properties = HashMap<String, Any>().apply { put("amount", checkoutData.amount().round()) checkoutData.id()?.let { put("id", it.toString()) } put( "payment_type", checkoutData.paymentType().rawValue().lowercase(Locale.getDefault()) ) put("amount_total_usd", checkoutData.totalAmount(project.staticUsdRate()).round()) put("shipping_amount", checkoutData.shippingAmount()) put("shipping_amount_usd", checkoutData.shippingAmount(project.staticUsdRate()).round()) put("bonus_amount", checkoutData.bonus()) put("bonus_amount_usd", checkoutData.bonus(project.staticUsdRate()).round()) put("add_ons_count_total", totalQuantity(addOns)) put("add_ons_count_unique", totalCountUnique(addOns)) put("add_ons_minimum_usd", addOnsCost(project.staticUsdRate(), addOns).round()) } return MapUtils.prefixKeys(properties, prefix) } fun checkoutDataProperties(checkoutData: CheckoutData, pledgeData: PledgeData, loggedInUser: User?): Map<String, Any> { val props = pledgeDataProperties(pledgeData, loggedInUser) props.putAll(checkoutProperties(checkoutData, pledgeData)) return props } @JvmOverloads fun discoveryParamsProperties(params: DiscoveryParams, discoverSort: DiscoveryParams.Sort? = params.sort(), prefix: String = "discover_"): Map<String, Any> { val properties = HashMap<String, Any>().apply { put("everything", params.isAllProjects.isTrue()) put("pwl", params.staffPicks().isTrue()) put("recommended", params.recommended()?.isTrue() ?: false) params.refTag()?.tag()?.let { put("ref_tag", it) } params.term()?.let { put("search_term", it) } put("social", params.social().isNonZero()) put( "sort", discoverSort?.let { when (it) { DiscoveryParams.Sort.POPULAR -> "popular" DiscoveryParams.Sort.ENDING_SOON -> "ending_soon" else -> it.toString() } } ?: "" ) params.tagId()?.let { put("tag", it) } put("watched", params.starred().isNonZero()) val paramsCategory = params.category() paramsCategory?.let { category -> if (category.isRoot) { putAll(categoryProperties(category)) } else { category.root()?.let { putAll(categoryProperties(it)) } putAll(subcategoryProperties(category)) } } } return MapUtils.prefixKeys(properties, prefix) } fun subcategoryProperties(category: Category): Map<String, Any> { return categoryProperties(category, "subcategory_") } @JvmOverloads fun categoryProperties(category: Category, prefix: String = "category_"): Map<String, Any> { val properties = HashMap<String, Any>().apply { put("id", category.id().toString()) put("name", category.analyticsName().toString()) } return MapUtils.prefixKeys(properties, prefix) } @JvmOverloads fun locationProperties(location: Location, prefix: String = "location_"): Map<String, Any> { val properties = HashMap<String, Any>().apply { put("id", location.id().toString()) put("name", location.name()) put("displayable_name", location.displayableName()) location.city()?.let { put("city", it) } location.state()?.let { put("state", it) } put("country", location.country()) location.projectsCount()?.let { put("projects_count", it) } } return MapUtils.prefixKeys(properties, prefix) } @JvmOverloads fun userProperties(user: User, prefix: String = "user_"): Map<String, Any> { val properties = HashMap<String, Any>() properties["backed_projects_count"] = user.backedProjectsCount() ?: 0 properties["launched_projects_count"] = user.createdProjectsCount() ?: 0 properties["created_projects_count"] = user.getCreatedAndDraftProjectsCount() properties["facebook_connected"] = user.facebookConnected() ?: false properties["watched_projects_count"] = user.starredProjectsCount() ?: 0 properties["uid"] = user.id().toString() properties["is_admin"] = user.isAdmin() ?: false return MapUtils.prefixKeys(properties, prefix) } fun pledgeDataProperties(pledgeData: PledgeData, loggedInUser: User?): MutableMap<String, Any> { val projectData = pledgeData.projectData() val props = projectProperties(projectData.project(), loggedInUser) props.putAll(pledgeProperties(pledgeData)) props.putAll(refTagProperties(projectData.refTagFromIntent(), projectData.refTagFromCookie())) props["context_pledge_flow"] = pledgeData.pledgeFlowContext().trackingString return props } @JvmOverloads fun videoProperties(videoLength: Long, videoPosition: Long, prefix: String = "video_"): Map<String, Any> { val properties = HashMap<String, Any>().apply { put(LENGTH.contextName, videoLength) put(POSITION.contextName, videoPosition) } return MapUtils.prefixKeys(properties, prefix) } @JvmOverloads fun pledgeProperties(pledgeData: PledgeData, prefix: String = "checkout_"): Map<String, Any> { val reward = pledgeData.reward() val project = pledgeData.projectData().project() val properties = HashMap<String, Any>().apply { reward.estimatedDeliveryOn()?.let { deliveryDate -> put("estimated_delivery_on", deliveryDate) } put("has_items", isItemized(reward)) put("id", reward.id().toString()) put("is_limited_time", isTimeLimitedEnd(reward)) put("is_limited_quantity", reward.limit() != null) put("minimum", reward.minimum()) put("shipping_enabled", isShippable(reward)) put("minimum_usd", pledgeData.rewardCost(project.staticUsdRate()).round()) reward.shippingPreference()?.let { put("shipping_preference", it) } reward.title()?.let { put("title", it) } } val props = MapUtils.prefixKeys(properties, "reward_") props.apply { put("add_ons_count_total", pledgeData.totalQuantity()) put("add_ons_count_unique", pledgeData.totalCountUnique()) put("add_ons_minimum_usd", addOnsCost(project.staticUsdRate(), pledgeData.addOns()?.let { it as? List<Reward> } ?: emptyList()).round()) } return MapUtils.prefixKeys(props, prefix) } @JvmOverloads fun projectProperties(project: Project, loggedInUser: User?, prefix: String = "project_"): MutableMap<String, Any> { val properties = HashMap<String, Any>().apply { put("backers_count", project.backersCount()) project.category()?.let { category -> if (category.isRoot) { put("category", category.analyticsName()) } else { category.parent()?.let { parent -> put("category", parent.analyticsName()) } ?: category.parentName()?.let { if (!this.containsKey("category")) this["category"] = it } put("subcategory", category.analyticsName()) } } project.commentsCount()?.let { put("comments_count", it) } project.prelaunchActivated()?.let { put("project_prelaunch_activated", it) } put("country", project.country()) put("creator_uid", project.creator().id().toString()) put("currency", project.currency()) put("current_pledge_amount", project.pledged()) put("current_amount_pledged_usd", (project.pledged() * project.usdExchangeRate()).round()) project.deadline()?.let { deadline -> put("deadline", deadline) } put("duration", project.timeInDaysOfDuration().toFloat().roundToInt()) put("goal", project.goal()) put("goal_usd", (project.goal() * project.usdExchangeRate()).round()) put("has_video", project.video() != null) put("hours_remaining", ceil((project.timeInSecondsUntilDeadline() / 60.0f / 60.0f).toDouble()).toInt()) put("is_repeat_creator", project.creator().createdProjectsCount().intValueOrZero() >= 2) project.launchedAt()?.let { launchedAt -> put("launched_at", launchedAt) } project.location()?.let { location -> put("location", location.name()) } put("name", project.name()) put("percent_raised", (project.percentageFunded()).toInt()) put("pid", project.id().toString()) put("prelaunch_activated", project.prelaunchActivated().isTrue()) project.rewards()?.let { a -> val rewards = a.filter { isReward(it) } put("rewards_count", rewards.size) } put("state", project.state()) put("static_usd_rate", project.staticUsdRate()) project.updatesCount()?.let { put("updates_count", it) } put("user_is_project_creator", project.userIsCreator(loggedInUser)) put("user_is_backer", project.isBacking()) put("user_has_watched", project.isStarred()) val hasAddOns = project.rewards()?.find { it.hasAddons() } put("has_add_ons", hasAddOns?.hasAddons() ?: false) put("tags", project.tags()?.let { it.joinToString(", ") } ?: "") put("url", project.urls().web().project()) project.photo()?.full()?.let { put("image_url", it) } } return MapUtils.prefixKeys(properties, prefix) } fun refTagProperties(intentRefTag: RefTag?, cookieRefTag: RefTag?) = HashMap<String, Any>().apply { intentRefTag?.tag()?.let { put("session_ref_tag", it) } cookieRefTag?.tag()?.let { put("session_referrer_credit", it) } } @JvmOverloads fun activityProperties(activity: Activity, loggedInUser: User?, prefix: String = "activity_"): Map<String, Any> { val props = HashMap<String, Any>().apply { activity.category()?.let { put("category", it) } } val properties = MapUtils.prefixKeys(props, prefix) activity.project()?.let { project -> properties.putAll(projectProperties(project, loggedInUser)) activity.update()?.let { update -> properties.putAll(updateProperties(project, update, loggedInUser)) } } return properties } @JvmOverloads fun updateProperties(project: Project, update: Update, loggedInUser: User?, prefix: String = "update_"): Map<String, Any> { val props = HashMap<String, Any>().apply { update.commentsCount()?.let { put("comments_count", it) } update.hasLiked()?.let { put("has_liked", it) } put("id", update.id()) update.likesCount()?.let { put("likes_count", it) } put("title", update.title()) put("sequence", update.sequence()) update.visible()?.let { put("visible", it) } update.publishedAt()?.let { put("published_at", it) } } val properties = MapUtils.prefixKeys(props, prefix) properties.putAll(projectProperties(project, loggedInUser)) return properties } }
apache-2.0
9294fabd3c802be105d33d34c10db241
46.204969
161
0.622566
4.701516
false
false
false
false
anitawoodruff/habitica-android
Habitica/src/main/java/com/habitrpg/android/habitica/ui/menu/HabiticaDrawerItem.kt
1
652
package com.habitrpg.android.habitica.ui.menu import android.graphics.drawable.Drawable import android.os.Bundle data class HabiticaDrawerItem(var transitionId: Int, val identifier: String, val text: String, val isHeader: Boolean = false) { constructor(transitionId: Int, identifier: String) : this(transitionId, identifier, "") var bundle: Bundle? = null var itemViewType: Int? = null var subtitle: String? = null var subtitleTextColor: Int? = null var pillText: String? = null var pillBackground: Drawable? = null var showBubble: Boolean = false var isVisible: Boolean = true var isEnabled: Boolean = true }
gpl-3.0
e92de8b50615d26b9c2e49e63d578527
35.277778
127
0.728528
4.179487
false
false
false
false
jotomo/AndroidAPS
app/src/main/java/info/nightscout/androidaps/utils/androidNotification/NotificationHolder.kt
1
1928
package info.nightscout.androidaps.utils.androidNotification import android.app.Notification import android.app.NotificationManager import android.app.PendingIntent import android.content.Context import android.content.Intent import androidx.core.app.NotificationCompat import androidx.core.app.TaskStackBuilder import info.nightscout.androidaps.MainActivity import info.nightscout.androidaps.MainApp import info.nightscout.androidaps.R import info.nightscout.androidaps.interfaces.NotificationHolderInterface import info.nightscout.androidaps.utils.resources.IconsProvider import info.nightscout.androidaps.utils.resources.ResourceHelper import javax.inject.Inject import javax.inject.Singleton @Singleton class NotificationHolder @Inject constructor( private val resourceHelper: ResourceHelper, private val context: Context, private val iconsProvider: IconsProvider ) : NotificationHolderInterface { override val channelID = "AndroidAPS-Ongoing" override val notificationID = 4711 override lateinit var notification: Notification init { val stackBuilder = TaskStackBuilder.create(context) .addParentStack(MainActivity::class.java) .addNextIntent(Intent(context, MainApp::class.java)) val builder = NotificationCompat.Builder(context, channelID) .setOngoing(true) .setOnlyAlertOnce(true) .setCategory(NotificationCompat.CATEGORY_STATUS) .setSmallIcon(iconsProvider.getNotificationIcon()) .setLargeIcon(resourceHelper.decodeResource(iconsProvider.getIcon())) .setContentTitle(resourceHelper.gs(R.string.loading)) .setContentIntent(stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT)) notification = builder.build() (context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager).notify(notificationID, notification) } }
agpl-3.0
5469145197eb20807c5cd2afecf0b2a5
41.844444
124
0.779564
5.224932
false
false
false
false
siosio/intellij-community
plugins/markdown/src/org/intellij/plugins/markdown/editor/lists/ListUtils.kt
1
3460
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.intellij.plugins.markdown.editor.lists import com.intellij.application.options.CodeStyle import com.intellij.openapi.editor.Document import com.intellij.openapi.fileEditor.FileDocumentManager import com.intellij.openapi.project.guessProjectForFile import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiDocumentManager import com.intellij.psi.PsiFile import com.intellij.psi.util.PsiUtilCore import com.intellij.psi.util.parentOfType import com.intellij.util.text.CharArrayUtil import org.intellij.plugins.markdown.lang.psi.impl.MarkdownFile import org.intellij.plugins.markdown.lang.psi.impl.MarkdownListImpl import org.intellij.plugins.markdown.lang.psi.impl.MarkdownListItemImpl internal object ListUtils { /** [offset] may be located inside the indent of the returned item, but not on a blank line */ fun MarkdownFile.getListItemAt(offset: Int, document: Document) = getListItemAtLine(document.getLineNumber(offset), document) /** [lineNumber] should belong to a list item and not represent a blank line, otherwise returns `null` */ fun MarkdownFile.getListItemAtLine(lineNumber: Int, document: Document): MarkdownListItemImpl? { val lineStart = document.getLineStartOffset(lineNumber) val lineEnd = document.getLineEndOffset(lineNumber) val searchingOffset = CharArrayUtil.shiftBackward(document.charsSequence, lineStart, lineEnd - 1, " \t\n") if (searchingOffset < lineStart) { return null } val elementAtOffset = PsiUtilCore.getElementAtOffset(this, searchingOffset) return elementAtOffset.parentOfType(true) } /** If 0 <= [lineNumber] < [Document.getLineCount], equivalent to [getListItemAtLine]. * Otherwise, returns null. */ fun MarkdownFile.getListItemAtLineSafely(lineNumber: Int, document: Document) = if (lineNumber in 0 until document.lineCount) getListItemAtLine(lineNumber, document) else null fun Document.getLineIndentRange(lineNumber: Int): TextRange { val lineStart = getLineStartOffset(lineNumber) val nonWsStart = CharArrayUtil.shiftForward(charsSequence, lineStart, " \t") return TextRange.create(lineStart, nonWsStart) } /** * Returns the indent at line [lineNumber], with all tabs replaced with spaces. * Returns `null` if [file] is null and failed to guess it. */ fun Document.getLineIndentSpaces(lineNumber: Int, file: PsiFile? = null): String? { val psiFile = file ?: run { val virtualFile = FileDocumentManager.getInstance().getFile(this) val project = guessProjectForFile(virtualFile) ?: return null PsiDocumentManager.getInstance(project).getPsiFile(this) ?: return null } val tabSize = CodeStyle.getFacade(psiFile).tabSize val indentStr = getText(getLineIndentRange(lineNumber)) return indentStr.replace("\t", " ".repeat(tabSize)) } val MarkdownListImpl.items get() = children.filterIsInstance<MarkdownListItemImpl>() val MarkdownListItemImpl.sublists get() = children.filterIsInstance<MarkdownListImpl>() val MarkdownListItemImpl.list get() = parent as MarkdownListImpl /** * Returns a marker of the item with leading whitespaces trimmed, and with a single space in the end. */ val MarkdownListItemImpl.normalizedMarker: String get() = this.markerElement!!.text.trim().let { "$it " } }
apache-2.0
cf617ac9458820d5b4a476a348cd0b08
43.358974
140
0.764451
4.570674
false
false
false
false
vovagrechka/fucking-everything
shared-kjs/src/fuck.kt
1
2830
package vgrechka import kotlin.properties.Delegates import kotlin.properties.ReadOnlyProperty import kotlin.properties.ReadWriteProperty import kotlin.reflect.KProperty annotation class Ser annotation class AllOpen var exhaustive: Any? = null class BreakOnMeException(msg: String) : RuntimeException(msg) fun <T: Any> notNull(): ReadWriteProperty<Any?, T> = Delegates.notNull() class notNullOnce<T: Any> : ReadWriteProperty<Any?, T> { var _value: T? = null override fun getValue(thisRef: Any?, property: KProperty<*>): T { return _value ?: throw IllegalStateException("Property `${property.name}` should be initialized before get.") } override fun setValue(thisRef: Any?, property: KProperty<*>, value: T) { check(this._value == null) {"Property `${property.name}` should be assigned only once"} this._value = value } } class maybeNullOnce<T: Any> : ReadWriteProperty<Any?, T?> { // TODO:vgrechka Unify with notNullOnce var assigned = false var _value: T? = null override fun getValue(thisRef: Any?, property: KProperty<*>): T? { if (!assigned) throw IllegalStateException("Property `${property.name}` should be initialized before get.") return _value } override fun setValue(thisRef: Any?, property: KProperty<*>, value: T?) { check(!assigned) {"Property `${property.name}` should be assigned only once"} this.assigned = true this._value = value } } fun <T> named(make: (ident: String) -> T) = object : ReadOnlyProperty<Any?, T> { private var value: T? = null override fun getValue(thisRef: Any?, property: KProperty<*>): T { if (value == null) value = make(property.name) return bang(value) } } fun myName() = named {it} fun slashMyName() = named {"/" + it} fun <T> bang(x: T?): T { if (x == null) bitch("Banging on freaking null") return x } fun StringBuilder.ln(x: Any? = "") { append(x) append("\n") } fun String.indexOfOrNull(needle: String, startIndex: Int = 0, ignoreCase: Boolean = false): Int? { val index = indexOf(needle, startIndex, ignoreCase) return if (index >= 0) index else null } inline fun <T> List<T>.indexOfFirstOrNull(predicate: (T) -> Boolean): Int? { val index = this.indexOfFirst(predicate) return when (index) { -1 -> null else -> index } } fun <T> List<T>.indexOfOrNull(element: T): Int? { val index = this.indexOf(element) return when (index) { -1 -> null else -> index } } // "Create parameter" refactoring aids fun <R> call(f: () -> R): R = f() fun <R, P0> call(f: (P0) -> R, p0: P0): R = f(p0) fun <R, P0, P1> call(f: (P0, P1) -> R, p0: P0, p1: P1): R = f(p0, p1) operator fun StringBuilder.plusAssign(x: Any?) { this.append(x) }
apache-2.0
9c893cd4f876b6eb8dada8cc11b417bb
24.963303
117
0.632509
3.614304
false
false
false
false
nrizzio/Signal-Android
app/src/main/java/org/thoughtcrime/securesms/safety/SafetyNumberRecipientRowItem.kt
1
3119
package org.thoughtcrime.securesms.safety import android.view.View import android.view.ViewGroup import android.widget.TextView import org.signal.core.util.DimensionUnit import org.signal.core.util.or import org.thoughtcrime.securesms.R import org.thoughtcrime.securesms.components.AvatarImageView import org.thoughtcrime.securesms.components.menu.ActionItem import org.thoughtcrime.securesms.components.menu.SignalContextMenu import org.thoughtcrime.securesms.recipients.Recipient import org.thoughtcrime.securesms.util.adapter.mapping.LayoutFactory import org.thoughtcrime.securesms.util.adapter.mapping.MappingAdapter import org.thoughtcrime.securesms.util.adapter.mapping.MappingModel import org.thoughtcrime.securesms.util.adapter.mapping.MappingViewHolder import org.thoughtcrime.securesms.util.visible /** * An untrusted recipient who can be verified or removed. */ object SafetyNumberRecipientRowItem { fun register(mappingAdapter: MappingAdapter) { mappingAdapter.registerFactory(Model::class.java, LayoutFactory(::ViewHolder, R.layout.safety_number_recipient_row_item)) } class Model( val recipient: Recipient, val isVerified: Boolean, val distributionListMembershipCount: Int, val groupMembershipCount: Int, val getContextMenuActions: (Model) -> List<ActionItem> ) : MappingModel<Model> { override fun areItemsTheSame(newItem: Model): Boolean { return recipient.id == newItem.recipient.id } override fun areContentsTheSame(newItem: Model): Boolean { return recipient.hasSameContent(newItem.recipient) && isVerified == newItem.isVerified && distributionListMembershipCount == newItem.distributionListMembershipCount && groupMembershipCount == newItem.groupMembershipCount } } class ViewHolder(itemView: View) : MappingViewHolder<Model>(itemView) { private val avatar: AvatarImageView = itemView.findViewById(R.id.safety_number_recipient_avatar) private val name: TextView = itemView.findViewById(R.id.safety_number_recipient_name) private val identifier: TextView = itemView.findViewById(R.id.safety_number_recipient_identifier) override fun bind(model: Model) { avatar.setRecipient(model.recipient) name.text = model.recipient.getDisplayName(context) val identifierText = model.recipient.e164.or(model.recipient.username).orElse(null) val subLineText = when { model.isVerified && identifierText.isNullOrBlank() -> context.getString(R.string.SafetyNumberRecipientRowItem__verified) model.isVerified -> context.getString(R.string.SafetyNumberRecipientRowItem__s_dot_verified, identifierText) else -> identifierText } identifier.text = subLineText identifier.visible = !subLineText.isNullOrBlank() itemView.setOnClickListener { itemView.isSelected = true SignalContextMenu.Builder(itemView, itemView.rootView as ViewGroup) .offsetY(DimensionUnit.DP.toPixels(12f).toInt()) .onDismiss { itemView.isSelected = false } .show(model.getContextMenuActions(model)) } } } }
gpl-3.0
75e7c8e113935b94eb37409c9d151a90
40.586667
128
0.764989
4.59352
false
false
false
false
androidx/androidx
wear/watchface/watchface-data/src/main/java/android/support/wearable/watchface/ParcelableWrapper.kt
3
1888
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package android.support.wearable.watchface import android.annotation.SuppressLint import android.os.Parcel import android.os.Parcelable import androidx.annotation.RestrictTo /** * Wraps a Parcelable. * * @hide */ @SuppressLint("BanParcelableUsage") @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) class ParcelableWrapper(val parcelable: Parcelable) : Parcelable { constructor(parcel: Parcel) : this(unparcel(parcel)) override fun writeToParcel(dest: Parcel, flags: Int) { parcelable.writeToParcel(dest, flags) } override fun describeContents(): Int = parcelable.describeContents() public companion object { @JvmField @Suppress("DEPRECATION") public val CREATOR: Parcelable.Creator<ParcelableWrapper> = object : Parcelable.Creator<ParcelableWrapper> { override fun createFromParcel(parcel: Parcel) = ParcelableWrapper(parcel) override fun newArray(size: Int) = arrayOfNulls<ParcelableWrapper?>(size) } internal var unparcel: (Parcel) -> Parcelable = { throw RuntimeException("setUnparceler not called") } public fun setUnparceler(unparceler: (Parcel) -> Parcelable) { unparcel = unparceler } } }
apache-2.0
8c24ebfe0353a0e59da9890a3f35d885
31.016949
89
0.701801
4.616137
false
false
false
false
djkovrik/YapTalker
app/src/main/java/com/sedsoftware/yaptalker/di/module/network/HttpClientsModule.kt
1
2988
package com.sedsoftware.yaptalker.di.module.network import android.content.Context import com.franmontiel.persistentcookiejar.PersistentCookieJar import com.franmontiel.persistentcookiejar.cache.SetCookieCache import com.franmontiel.persistentcookiejar.persistence.SharedPrefsCookiePersistor import com.sedsoftware.yaptalker.BuildConfig import com.sedsoftware.yaptalker.di.module.network.interceptors.HeaderAndParamManipulationInterceptor import com.sedsoftware.yaptalker.di.module.network.interceptors.HtmlFixerInterceptor import com.sedsoftware.yaptalker.di.module.network.interceptors.SaveReceivedCookiesInterceptor import com.sedsoftware.yaptalker.di.module.network.interceptors.SendSavedCookiesInterceptor import com.sedsoftware.yaptalker.domain.device.CookieStorage import dagger.Module import dagger.Provides import okhttp3.OkHttpClient import okhttp3.logging.HttpLoggingInterceptor import okhttp3.logging.HttpLoggingInterceptor.Level import javax.inject.Named import javax.inject.Singleton @Module class HttpClientsModule { private val loggingLevel: Level by lazy { if (BuildConfig.DEBUG) Level.HEADERS else Level.NONE } private val loggingInterceptor: HttpLoggingInterceptor by lazy { HttpLoggingInterceptor().setLevel(loggingLevel) } @Provides @Singleton fun provideSetCookieCache(): SetCookieCache = SetCookieCache() @Provides @Singleton fun provideSharedPrefsCookiePersistor(context: Context): SharedPrefsCookiePersistor = SharedPrefsCookiePersistor(context) @Provides @Singleton fun providePersistentCookieJar( cache: SetCookieCache, persistor: SharedPrefsCookiePersistor ): PersistentCookieJar = PersistentCookieJar(cache, persistor) @Singleton @Provides @Named("siteClient") fun provideSiteClient(cookieStorage: CookieStorage): OkHttpClient = OkHttpClient.Builder() .addInterceptor(HtmlFixerInterceptor()) .addInterceptor(HeaderAndParamManipulationInterceptor()) .addInterceptor(SaveReceivedCookiesInterceptor(cookieStorage)) .addInterceptor(SendSavedCookiesInterceptor(cookieStorage)) .addInterceptor(loggingInterceptor) .build() @Singleton @Provides @Named("apiClient") fun provideApiClient(jar: PersistentCookieJar): OkHttpClient { val builder = OkHttpClient.Builder() builder.addInterceptor(HeaderAndParamManipulationInterceptor()) builder.addInterceptor(loggingInterceptor) builder.cookieJar(jar) builder.cache(null) return builder.build() } @Singleton @Provides @Named("fileClient") fun provideFileClient(): OkHttpClient = OkHttpClient.Builder().build() @Singleton @Provides @Named("outerClient") fun provideOuterClient(): OkHttpClient = OkHttpClient.Builder() .addInterceptor(loggingInterceptor) .build() }
apache-2.0
80bf2c2ace09f3715f52ef5b7e50ec00
33.344828
101
0.756359
5.482569
false
false
false
false
GunoH/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/dfa/KotlinConstantConditionsInspection.kt
1
30953
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.inspections.dfa import com.intellij.codeInsight.PsiEquivalenceUtil import com.intellij.codeInspection.ProblemHighlightType import com.intellij.codeInspection.ProblemsHolder import com.intellij.codeInspection.dataFlow.interpreter.RunnerResult import com.intellij.codeInspection.dataFlow.interpreter.StandardDataFlowInterpreter import com.intellij.codeInspection.dataFlow.jvm.JvmDfaMemoryStateImpl import com.intellij.codeInspection.dataFlow.lang.DfaAnchor import com.intellij.codeInspection.dataFlow.lang.DfaListener import com.intellij.codeInspection.dataFlow.lang.UnsatisfiedConditionProblem import com.intellij.codeInspection.dataFlow.lang.ir.DataFlowIRProvider import com.intellij.codeInspection.dataFlow.lang.ir.DfaInstructionState import com.intellij.codeInspection.dataFlow.memory.DfaMemoryState import com.intellij.codeInspection.dataFlow.types.DfType import com.intellij.codeInspection.dataFlow.types.DfTypes import com.intellij.codeInspection.dataFlow.value.DfaValue import com.intellij.codeInspection.dataFlow.value.DfaValueFactory import com.intellij.psi.PsiElement import com.intellij.psi.PsiElementVisitor import com.intellij.psi.util.PsiTreeUtil import com.intellij.psi.util.siblings import com.intellij.util.ThreeState import org.jetbrains.kotlin.caches.resolve.KotlinCacheService import org.jetbrains.kotlin.descriptors.PackageFragmentDescriptor import org.jetbrains.kotlin.diagnostics.Errors import org.jetbrains.kotlin.diagnostics.Severity import org.jetbrains.kotlin.idea.base.facet.platform.platform import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.base.util.module import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall import org.jetbrains.kotlin.idea.codeinsight.api.classic.inspections.AbstractKotlinInspection import org.jetbrains.kotlin.idea.inspections.dfa.KotlinAnchor.* import org.jetbrains.kotlin.idea.inspections.dfa.KotlinProblem.* import org.jetbrains.kotlin.idea.intentions.loopToCallChain.isConstant import org.jetbrains.kotlin.idea.intentions.negate import org.jetbrains.kotlin.idea.references.mainReference import org.jetbrains.kotlin.idea.references.readWriteAccess import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.platform.jvm.isJvm import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.isNull import org.jetbrains.kotlin.resolve.bindingContextUtil.isUsedAsStatement import org.jetbrains.kotlin.resolve.constants.evaluate.ConstantExpressionEvaluator import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.types.typeUtil.isNullableNothing class KotlinConstantConditionsInspection : AbstractKotlinInspection() { private enum class ConstantValue { TRUE, FALSE, NULL, ZERO, UNKNOWN } private class KotlinDfaListener : DfaListener { val constantConditions = hashMapOf<KotlinAnchor, ConstantValue>() val problems = hashMapOf<KotlinProblem, ThreeState>() override fun beforePush(args: Array<out DfaValue>, value: DfaValue, anchor: DfaAnchor, state: DfaMemoryState) { if (anchor is KotlinAnchor) { recordExpressionValue(anchor, state, value) } } override fun onCondition(problem: UnsatisfiedConditionProblem, value: DfaValue, failed: ThreeState, state: DfaMemoryState) { if (problem is KotlinProblem) { problems.merge(problem, failed, ThreeState::merge) } } private fun recordExpressionValue(anchor: KotlinAnchor, state: DfaMemoryState, value: DfaValue) { val oldVal = constantConditions[anchor] if (oldVal == ConstantValue.UNKNOWN) return var newVal = when (val dfType = state.getDfType(value)) { DfTypes.TRUE -> ConstantValue.TRUE DfTypes.FALSE -> ConstantValue.FALSE DfTypes.NULL -> ConstantValue.NULL else -> { val constVal: Number? = dfType.getConstantOfType(Number::class.java) if (constVal != null && (constVal == 0 || constVal == 0L)) ConstantValue.ZERO else ConstantValue.UNKNOWN } } if (oldVal != null && oldVal != newVal) { newVal = ConstantValue.UNKNOWN } constantConditions[anchor] = newVal } } override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor { // Non-JVM is not supported now if (holder.file.module?.platform?.isJvm() != true) return PsiElementVisitor.EMPTY_VISITOR return object : KtVisitorVoid() { override fun visitProperty(property: KtProperty) { if (shouldAnalyzeProperty(property)) { val initializer = property.delegateExpressionOrInitializer ?: return analyze(initializer) } } override fun visitPropertyAccessor(accessor: KtPropertyAccessor) { if (shouldAnalyzeProperty(accessor.property)) { val bodyExpression = accessor.bodyExpression ?: accessor.bodyBlockExpression ?: return analyze(bodyExpression) } } override fun visitParameter(parameter: KtParameter) { analyze(parameter.defaultValue ?: return) } private fun shouldAnalyzeProperty(property: KtProperty) = property.isTopLevel || property.parent is KtClassBody override fun visitClassInitializer(initializer: KtClassInitializer) { analyze(initializer.body ?: return) } override fun visitNamedFunction(function: KtNamedFunction) { val body = function.bodyExpression ?: function.bodyBlockExpression ?: return analyze(body) } private fun analyze(body: KtExpression) { val factory = DfaValueFactory(holder.project) processDataflowAnalysis(factory, body, holder, listOf(JvmDfaMemoryStateImpl(factory))) } } } private fun processDataflowAnalysis( factory: DfaValueFactory, body: KtExpression, holder: ProblemsHolder, states: Collection<DfaMemoryState> ) { val flow = DataFlowIRProvider.forElement(body, factory) ?: return val listener = KotlinDfaListener() val interpreter = StandardDataFlowInterpreter(flow, listener) if (interpreter.interpret(states.map { s -> DfaInstructionState(flow.getInstruction(0), s) }) != RunnerResult.OK) return reportProblems(listener, holder) for ((closure, closureStates) in interpreter.closures.entrySet()) { if (closure is KtExpression) { processDataflowAnalysis(factory, closure, holder, closureStates) } } } private fun reportProblems( listener: KotlinDfaListener, holder: ProblemsHolder ) { listener.constantConditions.forEach { (anchor, cv) -> if (cv != ConstantValue.UNKNOWN) { when (anchor) { is KotlinExpressionAnchor -> { val expr = anchor.expression if (!shouldSuppress(cv, expr)) { val key = when (cv) { ConstantValue.TRUE -> if (shouldReportAsValue(expr)) "inspection.message.value.always.true" else if (logicalChain(expr)) "inspection.message.condition.always.true.when.reached" else "inspection.message.condition.always.true" ConstantValue.FALSE -> if (shouldReportAsValue(expr)) "inspection.message.value.always.false" else if (logicalChain(expr)) "inspection.message.condition.always.false.when.reached" else "inspection.message.condition.always.false" ConstantValue.NULL -> "inspection.message.value.always.null" ConstantValue.ZERO -> "inspection.message.value.always.zero" else -> throw IllegalStateException("Unexpected constant: $cv") } val highlightType = if (shouldReportAsValue(expr)) ProblemHighlightType.WEAK_WARNING else ProblemHighlightType.GENERIC_ERROR_OR_WARNING holder.registerProblem(expr, KotlinBundle.message(key, expr.text), highlightType) } } is KotlinWhenConditionAnchor -> { val condition = anchor.condition if (!shouldSuppressWhenCondition(cv, condition)) { val message = KotlinBundle.message("inspection.message.when.condition.always.false") if (cv == ConstantValue.FALSE) { holder.registerProblem(condition, message) } else if (cv == ConstantValue.TRUE) { condition.siblings(forward = true, withSelf = false) .filterIsInstance<KtWhenCondition>() .forEach { cond -> holder.registerProblem(cond, message) } val nextEntry = condition.parent as? KtWhenEntry ?: return@forEach nextEntry.siblings(forward = true, withSelf = false) .filterIsInstance<KtWhenEntry>() .filterNot { entry -> entry.isElse } .flatMap { entry -> entry.conditions.asSequence() } .forEach { cond -> holder.registerProblem(cond, message) } } } } is KotlinForVisitedAnchor -> { val loopRange = anchor.forExpression.loopRange!! if (cv == ConstantValue.FALSE && !shouldSuppressForCondition(loopRange)) { val message = KotlinBundle.message("inspection.message.for.never.visited") holder.registerProblem(loopRange, message) } } } } } listener.problems.forEach { (problem, state) -> if (state == ThreeState.YES) { when (problem) { is KotlinArrayIndexProblem -> holder.registerProblem(problem.index, KotlinBundle.message("inspection.message.index.out.of.bounds")) is KotlinNullCheckProblem -> { val expr = problem.expr if (expr.baseExpression?.isNull() != true) { holder.registerProblem(expr.operationReference, KotlinBundle.message("inspection.message.nonnull.cast.will.always.fail")) } } is KotlinCastProblem -> { val anchor = (problem.cast as? KtBinaryExpressionWithTypeRHS)?.operationReference ?: problem.cast if (!isCompilationWarning(anchor)) { holder.registerProblem(anchor, KotlinBundle.message("inspection.message.cast.will.always.fail")) } } } } } } private fun shouldSuppressForCondition(loopRange: KtExpression): Boolean { if (loopRange is KtBinaryExpression) { val left = loopRange.left val right = loopRange.right // Reported separately by EmptyRangeInspection return left != null && right != null && left.isConstant() && right.isConstant() } return false } private fun shouldReportAsValue(expr: KtExpression) = expr is KtSimpleNameExpression || expr is KtQualifiedExpression && expr.selectorExpression is KtSimpleNameExpression private fun logicalChain(expr: KtExpression): Boolean { var context = expr var parent = context.parent while (parent is KtParenthesizedExpression) { context = parent parent = context.parent } if (parent is KtBinaryExpression && parent.right == context) { val token = parent.operationToken return token == KtTokens.ANDAND || token == KtTokens.OROR } return false } private fun shouldSuppressWhenCondition( cv: ConstantValue, condition: KtWhenCondition ): Boolean { if (cv != ConstantValue.FALSE && cv != ConstantValue.TRUE) return true if (cv == ConstantValue.TRUE && isLastCondition(condition)) return true if (condition.textLength == 0) return true return isCompilationWarning(condition) } private fun isLastCondition(condition: KtWhenCondition): Boolean { val entry = condition.parent as? KtWhenEntry ?: return false val whenExpr = entry.parent as? KtWhenExpression ?: return false if (entry.conditions.last() == condition) { val entries = whenExpr.entries val lastEntry = entries.last() if (lastEntry == entry) return true val size = entries.size // Also, do not report the always reachable entry right before 'else', // usually it's necessary for the smart-cast, or for definite assignment, and the report is just noise if (lastEntry.isElse && size > 1 && entries[size - 2] == entry) return true } return false } companion object { private fun areEquivalent(e1: KtElement, e2: KtElement): Boolean { return PsiEquivalenceUtil.areElementsEquivalent(e1, e2, {ref1, ref2 -> ref1.element.text.compareTo(ref2.element.text)}, null, null, false) } private tailrec fun isOppositeCondition(candidate: KtExpression?, template: KtBinaryExpression, expression: KtExpression): Boolean { if (candidate !is KtBinaryExpression || candidate.operationToken !== KtTokens.ANDAND) return false val left = candidate.left val right = candidate.right if (left == null || right == null) return false val templateLeft = template.left val templateRight = template.right if (templateLeft == null || templateRight == null) return false if (templateRight === expression) { return areEquivalent(left, templateLeft) && areEquivalent(right.negate(false), templateRight) } if (!areEquivalent(right, templateRight)) return false if (templateLeft === expression) { return areEquivalent(left.negate(false), templateLeft) } if (templateLeft !is KtBinaryExpression || templateLeft.operationToken !== KtTokens.ANDAND) return false return isOppositeCondition(left, templateLeft, expression) } private fun hasOppositeCondition(whenExpression: KtWhenExpression, topCondition: KtExpression, expression: KtExpression): Boolean { for (entry in whenExpression.entries) { for (condition in entry.conditions) { if (condition is KtWhenConditionWithExpression) { val candidate = condition.expression if (candidate === topCondition) return false if (topCondition is KtBinaryExpression && isOppositeCondition(candidate, topCondition, expression)) return true if (candidate != null && areEquivalent(expression.negate(false), candidate)) return true } } } return false } /** * Returns true if expression is part of when condition expression that looks like * ``` * when { * a && b -> ... * a && !b -> ... * } * ``` * In this case, !b could be reported as 'always true' but such warnings are annoying */ private fun isPairingConditionInWhen(expression: KtExpression): Boolean { val parent = expression.parent if (parent is KtBinaryExpression && parent.operationToken == KtTokens.ANDAND) { var topAnd: KtBinaryExpression = parent while (true) { val nextParent = topAnd.parent if (nextParent is KtBinaryExpression && nextParent.operationToken == KtTokens.ANDAND) { topAnd = nextParent } else break } val topAndParent = topAnd.parent if (topAndParent is KtWhenConditionWithExpression) { val whenExpression = (topAndParent.parent as? KtWhenEntry)?.parent as? KtWhenExpression if (whenExpression != null && hasOppositeCondition(whenExpression, topAnd, expression)) { return true } } } if (parent is KtWhenConditionWithExpression) { val whenExpression = (parent.parent as? KtWhenEntry)?.parent as? KtWhenExpression if (whenExpression != null && hasOppositeCondition(whenExpression, expression, expression)) { return true } } return false } private fun isCompilationWarning(anchor: KtElement): Boolean { val context = anchor.analyze(BodyResolveMode.FULL) if (context.diagnostics.forElement(anchor).any { it.factory == Errors.CAST_NEVER_SUCCEEDS || it.factory == Errors.SENSELESS_COMPARISON || it.factory == Errors.SENSELESS_NULL_IN_WHEN || it.factory == Errors.USELESS_IS_CHECK || it.factory == Errors.DUPLICATE_LABEL_IN_WHEN } ) { return true } val rootElement = anchor.containingFile val suppressionCache = KotlinCacheService.getInstance(anchor.project).getSuppressionCache() return suppressionCache.isSuppressed(anchor, rootElement, "CAST_NEVER_SUCCEEDS", Severity.WARNING) || suppressionCache.isSuppressed(anchor, rootElement, "SENSELESS_COMPARISON", Severity.WARNING) || suppressionCache.isSuppressed(anchor, rootElement, "SENSELESS_NULL_IN_WHEN", Severity.WARNING) || suppressionCache.isSuppressed(anchor, rootElement, "USELESS_IS_CHECK", Severity.WARNING) || suppressionCache.isSuppressed(anchor, rootElement, "DUPLICATE_LABEL_IN_WHEN", Severity.WARNING) } private fun isCallToMethod(call: KtCallExpression, packageName: String, methodName: String): Boolean { val descriptor = call.resolveToCall()?.resultingDescriptor ?: return false if (descriptor.name.asString() != methodName) return false val packageFragment = descriptor.containingDeclaration as? PackageFragmentDescriptor ?: return false return packageFragment.fqName.asString() == packageName } // Do not report x.let { true } or x.let { false } as it's pretty evident private fun isLetConstant(expr: KtExpression): Boolean { val call = (expr as? KtQualifiedExpression)?.selectorExpression as? KtCallExpression ?: return false if (!isCallToMethod(call, "kotlin", "let")) return false val lambda = call.lambdaArguments.singleOrNull()?.getLambdaExpression() ?: return false return lambda.bodyExpression?.statements?.singleOrNull() is KtConstantExpression } // Do not report on also, as it always returns the qualifier. If necessary, qualifier itself will be reported private fun isAlsoChain(expr: KtExpression): Boolean { val call = (expr as? KtQualifiedExpression)?.selectorExpression as? KtCallExpression ?: return false return isCallToMethod(call, "kotlin", "also") } private fun isAssertion(parent: PsiElement?, value: Boolean): Boolean { return when (parent) { is KtBinaryExpression -> (parent.operationToken == KtTokens.ANDAND || parent.operationToken == KtTokens.OROR) && isAssertion(parent.parent, value) is KtParenthesizedExpression -> isAssertion(parent.parent, value) is KtPrefixExpression -> parent.operationToken == KtTokens.EXCL && isAssertion(parent.parent, !value) is KtValueArgument -> { if (!value) return false val valueArgList = parent.parent as? KtValueArgumentList ?: return false val call = valueArgList.parent as? KtCallExpression ?: return false val descriptor = call.resolveToCall()?.resultingDescriptor ?: return false val name = descriptor.name.asString() if (name != "assert" && name != "require" && name != "check") return false val pkg = descriptor.containingDeclaration as? PackageFragmentDescriptor ?: return false return pkg.fqName.asString() == "kotlin" } else -> false } } private fun hasWritesTo(block: PsiElement?, variable: KtProperty): Boolean { return !PsiTreeUtil.processElements(block, KtSimpleNameExpression::class.java) { ref -> val write = ref.mainReference.isReferenceTo(variable) && ref.readWriteAccess(false).isWrite !write } } private fun isUpdateChain(expression: KtExpression): Boolean { // x = x or ..., etc. if (expression !is KtSimpleNameExpression) return false val binOp = expression.parent as? KtBinaryExpression ?: return false val op = binOp.operationReference.text if (op != "or" && op != "and" && op != "xor" && op != "||" && op != "&&") return false val assignment = binOp.parent as? KtBinaryExpression ?: return false if (assignment.operationToken != KtTokens.EQ) return false val left = assignment.left if (left !is KtSimpleNameExpression || !left.textMatches(expression.text)) return false val variable = expression.mainReference.resolve() as? KtProperty ?: return false val varParent = variable.parent as? KtBlockExpression ?: return false var context: PsiElement = assignment var block = context.parent while (block is KtContainerNode || block is KtBlockExpression && block.statements.first() == context || block is KtIfExpression && block.then?.parent == context && block.`else` == null && !hasWritesTo(block.condition, variable) ) { context = block block = context.parent } if (block !== varParent) return false var curExpression = variable.nextSibling while (curExpression != context) { if (hasWritesTo(curExpression, variable)) return false curExpression = curExpression.nextSibling } return true } fun shouldSuppress(value: DfType, expression: KtExpression): Boolean { val constant = when(value) { DfTypes.NULL -> ConstantValue.NULL DfTypes.TRUE -> ConstantValue.TRUE DfTypes.FALSE -> ConstantValue.FALSE DfTypes.intValue(0), DfTypes.longValue(0) -> ConstantValue.ZERO else -> ConstantValue.UNKNOWN } return shouldSuppress(constant, expression) } private fun shouldSuppress(value: ConstantValue, expression: KtExpression): Boolean { // TODO: do something with always false branches in exhaustive when statements // TODO: return x && y.let {return...} var parent = expression.parent if (parent is KtDotQualifiedExpression && parent.selectorExpression == expression) { // Will be reported for parent qualified expression return true } while (parent is KtParenthesizedExpression) { parent = parent.parent } if (expression is KtConstantExpression || // If result of initialization is constant, then the initializer will be reported expression is KtProperty || // If result of assignment is constant, then the right-hand part will be reported expression is KtBinaryExpression && expression.operationToken == KtTokens.EQ || // Negation operand: negation itself will be reported (parent as? KtPrefixExpression)?.operationToken == KtTokens.EXCL ) { return true } if (expression is KtBinaryExpression && expression.operationToken == KtTokens.ELVIS) { // Left part of Elvis is Nothing?, so the right part is always executed // Could be caused by code like return x?.let { return ... } ?: true // While inner "return" is redundant, the "always true" warning is confusing // probably separate inspection could report extra "return" if (expression.left?.getKotlinType()?.isNullableNothing() == true) { return true } } if (isAlsoChain(expression) || isLetConstant(expression) || isUpdateChain(expression)) return true when (value) { ConstantValue.TRUE -> { if (isSmartCastNecessary(expression, true)) return true if (isPairingConditionInWhen(expression)) return true if (isAssertion(parent, true)) return true } ConstantValue.FALSE -> { if (isSmartCastNecessary(expression, false)) return true if (isAssertion(parent, false)) return true } ConstantValue.ZERO -> { if (expression.readWriteAccess(false).isWrite) { // like if (x == 0) x++, warning would be somewhat annoying return true } if (expression is KtDotQualifiedExpression && expression.selectorExpression?.textMatches("ordinal") == true) { var receiver: KtExpression? = expression.receiverExpression if (receiver is KtQualifiedExpression) { receiver = receiver.selectorExpression } if (receiver is KtSimpleNameExpression && receiver.mainReference.resolve() is KtEnumEntry) { // ordinal() call on explicit enum constant return true } } val bindingContext = expression.analyze() if (ConstantExpressionEvaluator.getConstant(expression, bindingContext) != null) return true if (expression is KtSimpleNameExpression && (parent is KtValueArgument || parent is KtContainerNode && parent.parent is KtArrayAccessExpression) ) { // zero value is passed as argument to another method or used for array access. Often, such a warning is annoying return true } } ConstantValue.NULL -> { if (parent is KtProperty && parent.typeReference == null && expression is KtSimpleNameExpression) { // initialize other variable with null to copy type, like // var x1 : X = null // var x2 = x1 -- let's suppress this return true } if (expression is KtBinaryExpressionWithTypeRHS && expression.left.isNull()) { // like (null as? X) return true } if (parent is KtBinaryExpression) { val token = parent.operationToken if ((token === KtTokens.EQEQ || token === KtTokens.EXCLEQ || token === KtTokens.EQEQEQ || token === KtTokens.EXCLEQEQEQ) && (parent.left?.isNull() == true || parent.right?.isNull() == true) ) { // like if (x == null) when 'x' is known to be null: report 'always true' instead return true } } val kotlinType = expression.getKotlinType() if (kotlinType.toDfType() == DfTypes.NULL) { // According to type system, nothing but null could be stored in such an expression (likely "Void?" type) return true } } else -> {} } if (expression is KtSimpleNameExpression) { val target = expression.mainReference.resolve() if (target is KtProperty && !target.isVar && target.initializer is KtConstantExpression) { // suppress warnings uses of boolean constant like 'val b = true' return true } } if (isCompilationWarning(expression)) { return true } return expression.isUsedAsStatement(expression.analyze(BodyResolveMode.FULL)) } } }
apache-2.0
a7a2193377300d7e4c04136a1264e574
52.003425
158
0.582948
5.943356
false
false
false
false
TonnyL/Mango
app/src/main/java/io/github/tonnyl/mango/ui/main/shots/ShotsAdapter.kt
1
3273
/* * Copyright (c) 2017 Lizhaotailang * * 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.tonnyl.mango.ui.main.shots import android.content.Context import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import io.github.tonnyl.mango.R import io.github.tonnyl.mango.data.Shot import io.github.tonnyl.mango.glide.GlideLoader import kotlinx.android.synthetic.main.item_shot.view.* /** * Created by lizhaotailang on 2017/6/29. */ class ShotsAdapter(context: Context, list: List<Shot>) : RecyclerView.Adapter<RecyclerView.ViewHolder>() { private var mContext = context private var mList = list private var mListener: OnRecyclerViewItemClickListener? = null override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): RecyclerView.ViewHolder { return ShotViewHolder(LayoutInflater.from(mContext).inflate(R.layout.item_shot, parent, false), mListener) } override fun onBindViewHolder(holderFollower: RecyclerView.ViewHolder?, position: Int) { if (position <= mList.size) { val shot = mList[position] with(holderFollower as ShotViewHolder) { GlideLoader.loadAvatar(itemView.avatar, shot.user?.avatarUrl) GlideLoader.loadNormal(itemView.shot_image_view, shot.images.best()) itemView.tag_gif.visibility = if (shot.animated) View.VISIBLE else View.GONE itemView.shot_title.text = mContext.getString(R.string.shot_title).format(shot.user?.name, shot.title) } } } override fun getItemCount() = mList.size fun setItemClickListener(listener: OnRecyclerViewItemClickListener) { mListener = listener } inner class ShotViewHolder(itemView: View, listener: OnRecyclerViewItemClickListener?) : RecyclerView.ViewHolder(itemView) { private val mListener = listener init { itemView.avatar.setOnClickListener({ view -> mListener?.onAvatarClick(view, layoutPosition) }) itemView.setOnClickListener({ view -> mListener?.onItemClick(view, layoutPosition) }) } } }
mit
380d7dd8629baebff7edd28e17343b1c
37.97619
128
0.716774
4.603376
false
false
false
false
GunoH/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/SimplifyBooleanWithConstantsIntention.kt
4
9169
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.intentions import com.intellij.openapi.editor.Editor import com.intellij.psi.tree.IElementType import org.jetbrains.kotlin.builtins.KotlinBuiltIns import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.base.psi.copied import org.jetbrains.kotlin.idea.base.psi.replaced import org.jetbrains.kotlin.idea.caches.resolve.safeAnalyzeNonSourceRootCode import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingOffsetIndependentIntention import org.jetbrains.kotlin.idea.codeinsight.api.classic.inspections.IntentionBasedInspection import org.jetbrains.kotlin.idea.intentions.loopToCallChain.isTrueConstant import org.jetbrains.kotlin.lexer.KtTokens.* import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.getNonStrictParentOfType import org.jetbrains.kotlin.psi.psiUtil.parentsWithSelf import org.jetbrains.kotlin.psi2ir.deparenthesize import org.jetbrains.kotlin.resolve.CompileTimeConstantUtils import org.jetbrains.kotlin.resolve.calls.util.getType import org.jetbrains.kotlin.resolve.constants.evaluate.ConstantExpressionEvaluator import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameOrNull import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode.PARTIAL import org.jetbrains.kotlin.types.TypeUtils import org.jetbrains.kotlin.types.isFlexible @Suppress("DEPRECATION") class SimplifyBooleanWithConstantsInspection : IntentionBasedInspection<KtBinaryExpression>(SimplifyBooleanWithConstantsIntention::class) { override fun inspectionProblemText(element: KtBinaryExpression): String { return KotlinBundle.message("inspection.simplify.boolean.with.constants.display.name") } } class SimplifyBooleanWithConstantsIntention : SelfTargetingOffsetIndependentIntention<KtBinaryExpression>( KtBinaryExpression::class.java, KotlinBundle.lazyMessage("simplify.boolean.expression") ) { override fun isApplicableTo(element: KtBinaryExpression): Boolean = areThereExpressionsToBeSimplified(element.topBinary()) private fun KtBinaryExpression.topBinary(): KtBinaryExpression = this.parentsWithSelf.takeWhile { it is KtBinaryExpression }.lastOrNull() as? KtBinaryExpression ?: this private fun areThereExpressionsToBeSimplified(element: KtExpression?): Boolean { if (element == null) return false when (element) { is KtParenthesizedExpression -> return areThereExpressionsToBeSimplified(element.expression) is KtBinaryExpression -> { val op = element.operationToken if (op == ANDAND || op == OROR || op == EQEQ || op == EXCLEQ) { if (areThereExpressionsToBeSimplified(element.left) && element.right.hasBooleanType()) return true if (areThereExpressionsToBeSimplified(element.right) && element.left.hasBooleanType()) return true } if (isPositiveNegativeZeroComparison(element)) return false } } return element.canBeReducedToBooleanConstant() } private fun isPositiveNegativeZeroComparison(element: KtBinaryExpression): Boolean { val op = element.operationToken if (op != EQEQ && op != EQEQEQ) { return false } val left = element.left?.deparenthesize() as? KtExpression ?: return false val right = element.right?.deparenthesize() as? KtExpression ?: return false val context = element.safeAnalyzeNonSourceRootCode(PARTIAL) fun KtExpression.getConstantValue() = ConstantExpressionEvaluator.getConstant(this, context)?.toConstantValue(TypeUtils.NO_EXPECTED_TYPE)?.value val leftValue = left.getConstantValue() val rightValue = right.getConstantValue() fun isPositiveZero(value: Any?) = value == +0.0 || value == +0.0f fun isNegativeZero(value: Any?) = value == -0.0 || value == -0.0f val hasPositiveZero = isPositiveZero(leftValue) || isPositiveZero(rightValue) val hasNegativeZero = isNegativeZero(leftValue) || isNegativeZero(rightValue) return hasPositiveZero && hasNegativeZero } override fun applyTo(element: KtBinaryExpression, editor: Editor?) { val topBinary = element.topBinary() val simplified = toSimplifiedExpression(topBinary) val result = topBinary.replaced(KtPsiUtil.safeDeparenthesize(simplified, true)) removeRedundantAssertion(result) } internal fun removeRedundantAssertion(expression: KtExpression) { val callExpression = expression.getNonStrictParentOfType<KtCallExpression>() ?: return val fqName = callExpression.getCallableDescriptor()?.fqNameOrNull() val valueArguments = callExpression.valueArguments val isRedundant = fqName?.asString() == "kotlin.assert" && valueArguments.singleOrNull()?.getArgumentExpression().isTrueConstant() if (isRedundant) callExpression.delete() } private fun toSimplifiedExpression(expression: KtExpression): KtExpression { val psiFactory = KtPsiFactory(expression) when { expression.canBeReducedToTrue() -> { return psiFactory.createExpression("true") } expression.canBeReducedToFalse() -> { return psiFactory.createExpression("false") } expression is KtParenthesizedExpression -> { val expr = expression.expression if (expr != null) { val simplified = toSimplifiedExpression(expr) return if (simplified is KtBinaryExpression) { // wrap in new parentheses to keep the user's original format psiFactory.createExpressionByPattern("($0)", simplified) } else { // if we now have a simpleName, constant, or parenthesized we don't need parentheses simplified } } } expression is KtBinaryExpression -> { if (!areThereExpressionsToBeSimplified(expression)) return expression.copied() val left = expression.left val right = expression.right val op = expression.operationToken if (left != null && right != null && (op == ANDAND || op == OROR || op == EQEQ || op == EXCLEQ)) { val simpleLeft = simplifyExpression(left) val simpleRight = simplifyExpression(right) return when { simpleLeft.canBeReducedToTrue() -> toSimplifiedBooleanBinaryExpressionWithConstantOperand(true, simpleRight, op) simpleLeft.canBeReducedToFalse() -> toSimplifiedBooleanBinaryExpressionWithConstantOperand(false, simpleRight, op) simpleRight.canBeReducedToTrue() -> toSimplifiedBooleanBinaryExpressionWithConstantOperand(true, simpleLeft, op) simpleRight.canBeReducedToFalse() -> toSimplifiedBooleanBinaryExpressionWithConstantOperand(false, simpleLeft, op) else -> { val opText = expression.operationReference.text psiFactory.createExpressionByPattern("$0 $opText $1", simpleLeft, simpleRight) } } } } } return expression.copied() } private fun toSimplifiedBooleanBinaryExpressionWithConstantOperand( constantOperand: Boolean, otherOperand: KtExpression, operation: IElementType ): KtExpression { val factory = KtPsiFactory(otherOperand) when (operation) { OROR -> { if (constantOperand) return factory.createExpression("true") } ANDAND -> { if (!constantOperand) return factory.createExpression("false") } EQEQ, EXCLEQ -> toSimplifiedExpression(otherOperand).let { return if (constantOperand == (operation == EQEQ)) it else factory.createExpressionByPattern("!$0", it) } } return toSimplifiedExpression(otherOperand) } private fun simplifyExpression(expression: KtExpression) = expression.replaced(toSimplifiedExpression(expression)) private fun KtExpression?.hasBooleanType(): Boolean { val type = this?.getType(safeAnalyzeNonSourceRootCode(PARTIAL)) ?: return false return KotlinBuiltIns.isBoolean(type) && !type.isFlexible() } private fun KtExpression.canBeReducedToBooleanConstant(constant: Boolean? = null): Boolean = CompileTimeConstantUtils.canBeReducedToBooleanConstant(this, safeAnalyzeNonSourceRootCode(PARTIAL), constant) private fun KtExpression.canBeReducedToTrue() = canBeReducedToBooleanConstant(true) private fun KtExpression.canBeReducedToFalse() = canBeReducedToBooleanConstant(false) }
apache-2.0
fd3f2a6cac37a303cc43049f54355d70
46.020513
139
0.683172
5.799494
false
false
false
false
GunoH/intellij-community
platform/lang-impl/src/com/intellij/util/indexing/diagnostic/dto/JsonProjectIndexingHistory.kt
7
2601
// 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.util.indexing.diagnostic.dto import com.fasterxml.jackson.annotation.JsonIgnoreProperties import com.fasterxml.jackson.annotation.JsonInclude @JsonInclude(JsonInclude.Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) data class JsonProjectIndexingHistory( val projectName: String = "", val times: JsonProjectIndexingHistoryTimes = JsonProjectIndexingHistoryTimes(), val fileCount: JsonProjectIndexingFileCount = JsonProjectIndexingFileCount(), val totalStatsPerFileType: List<JsonStatsPerFileType> = emptyList(), val totalStatsPerIndexer: List<JsonStatsPerIndexer> = emptyList(), val scanningStatistics: List<JsonScanningStatistics> = emptyList(), val fileProviderStatistics: List<JsonFileProviderIndexStatistics> = emptyList(), val visibleTimeToAllThreadTimeRatio: Double = 0.0 ) { @JsonIgnoreProperties(ignoreUnknown = true) data class JsonStatsPerFileType( val fileType: String = "", val partOfTotalProcessingTime: JsonPercentages = JsonPercentages(), val partOfTotalContentLoadingTime: JsonPercentages = JsonPercentages(), val totalNumberOfFiles: Int = 0, val totalFilesSize: JsonFileSize = JsonFileSize(), /** * bytes to total (not visible) processing (not just indexing) time */ val totalProcessingSpeed: JsonProcessingSpeed = JsonProcessingSpeed(), val biggestContributors: List<JsonBiggestFileTypeContributor> = emptyList() ) { @JsonIgnoreProperties(ignoreUnknown = true) data class JsonBiggestFileTypeContributor( val providerName: String = "", val numberOfFiles: Int = 0, val totalFilesSize: JsonFileSize = JsonFileSize(), val partOfTotalProcessingTimeOfThisFileType: JsonPercentages = JsonPercentages() ) } @JsonIgnoreProperties(ignoreUnknown = true) data class JsonStatsPerIndexer( val indexId: String = "", val partOfTotalIndexingTime: JsonPercentages = JsonPercentages(), val totalNumberOfFiles: Int = 0, val totalNumberOfFilesIndexedByExtensions: Int = 0, val totalFilesSize: JsonFileSize = JsonFileSize(), val indexValueChangerEvaluationSpeed: JsonProcessingSpeed = JsonProcessingSpeed(), val snapshotInputMappingStats: JsonSnapshotInputMappingStats = JsonSnapshotInputMappingStats() ) { @JsonIgnoreProperties(ignoreUnknown = true) data class JsonSnapshotInputMappingStats( val totalRequests: Long = 0, val totalMisses: Long = 0, val totalHits: Long = 0 ) } }
apache-2.0
4ff1c3b7cfb500ccb53d2284990b886a
43.101695
120
0.767397
5.265182
false
false
false
false
GunoH/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/ConvertLateinitPropertyToNullableIntention.kt
3
1809
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.intentions import com.intellij.openapi.editor.Editor import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingIntention import org.jetbrains.kotlin.idea.core.setType import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.KtNullableType import org.jetbrains.kotlin.psi.KtProperty import org.jetbrains.kotlin.psi.KtPsiFactory import org.jetbrains.kotlin.psi.KtTypeReference import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.types.typeUtil.makeNullable class ConvertLateinitPropertyToNullableIntention : SelfTargetingIntention<KtProperty>( KtProperty::class.java, KotlinBundle.lazyMessage("convert.to.nullable.var") ) { override fun isApplicableTo(element: KtProperty, caretOffset: Int): Boolean = element.hasModifier(KtTokens.LATEINIT_KEYWORD) && element.isVar && element.typeReference?.typeElement !is KtNullableType && element.initializer == null override fun applyTo(element: KtProperty, editor: Editor?) { val typeReference: KtTypeReference = element.typeReference ?: return val nullableType = element.analyze(BodyResolveMode.PARTIAL)[BindingContext.TYPE, typeReference]?.makeNullable() ?: return element.removeModifier(KtTokens.LATEINIT_KEYWORD) element.setType(nullableType) element.initializer = KtPsiFactory(element).createExpression(KtTokens.NULL_KEYWORD.value) } }
apache-2.0
43bb66339115fb0cefa89534c060392a
52.205882
158
0.793809
4.650386
false
false
false
false
JetBrains/kotlin-native
Interop/Runtime/src/native/kotlin/kotlinx/cinterop/Pinning.kt
2
5741
/* * Copyright 2010-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 kotlinx.cinterop import kotlin.native.* data class Pinned<out T : Any> internal constructor(private val stablePtr: COpaquePointer) { /** * Disposes the handle. It must not be [used][get] after that. */ fun unpin() { disposeStablePointer(this.stablePtr) } /** * Returns the underlying pinned object. */ fun get(): T = @Suppress("UNCHECKED_CAST") (derefStablePointer(stablePtr) as T) } fun <T : Any> T.pin() = Pinned<T>(createStablePointer(this)) inline fun <T : Any, R> T.usePinned(block: (Pinned<T>) -> R): R { val pinned = this.pin() return try { block(pinned) } finally { pinned.unpin() } } fun Pinned<ByteArray>.addressOf(index: Int): CPointer<ByteVar> = this.get().addressOfElement(index) fun ByteArray.refTo(index: Int): CValuesRef<ByteVar> = this.usingPinned { addressOf(index) } fun Pinned<String>.addressOf(index: Int): CPointer<COpaque> = this.get().addressOfElement(index) fun String.refTo(index: Int): CValuesRef<COpaque> = this.usingPinned { addressOf(index) } fun Pinned<CharArray>.addressOf(index: Int): CPointer<COpaque> = this.get().addressOfElement(index) fun CharArray.refTo(index: Int): CValuesRef<COpaque> = this.usingPinned { addressOf(index) } fun Pinned<ShortArray>.addressOf(index: Int): CPointer<ShortVar> = this.get().addressOfElement(index) fun ShortArray.refTo(index: Int): CValuesRef<ShortVar> = this.usingPinned { addressOf(index) } fun Pinned<IntArray>.addressOf(index: Int): CPointer<IntVar> = this.get().addressOfElement(index) fun IntArray.refTo(index: Int): CValuesRef<IntVar> = this.usingPinned { addressOf(index) } fun Pinned<LongArray>.addressOf(index: Int): CPointer<LongVar> = this.get().addressOfElement(index) fun LongArray.refTo(index: Int): CValuesRef<LongVar> = this.usingPinned { addressOf(index) } // TODO: pinning of unsigned arrays involves boxing as they are inline classes wrapping signed arrays. fun Pinned<UByteArray>.addressOf(index: Int): CPointer<UByteVar> = this.get().addressOfElement(index) fun UByteArray.refTo(index: Int): CValuesRef<UByteVar> = this.usingPinned { addressOf(index) } fun Pinned<UShortArray>.addressOf(index: Int): CPointer<UShortVar> = this.get().addressOfElement(index) fun UShortArray.refTo(index: Int): CValuesRef<UShortVar> = this.usingPinned { addressOf(index) } fun Pinned<UIntArray>.addressOf(index: Int): CPointer<UIntVar> = this.get().addressOfElement(index) fun UIntArray.refTo(index: Int): CValuesRef<UIntVar> = this.usingPinned { addressOf(index) } fun Pinned<ULongArray>.addressOf(index: Int): CPointer<ULongVar> = this.get().addressOfElement(index) fun ULongArray.refTo(index: Int): CValuesRef<ULongVar> = this.usingPinned { addressOf(index) } fun Pinned<FloatArray>.addressOf(index: Int): CPointer<FloatVar> = this.get().addressOfElement(index) fun FloatArray.refTo(index: Int): CValuesRef<FloatVar> = this.usingPinned { addressOf(index) } fun Pinned<DoubleArray>.addressOf(index: Int): CPointer<DoubleVar> = this.get().addressOfElement(index) fun DoubleArray.refTo(index: Int): CValuesRef<DoubleVar> = this.usingPinned { addressOf(index) } private inline fun <T : Any, P : CPointed> T.usingPinned( crossinline block: Pinned<T>.() -> CPointer<P> ) = object : CValuesRef<P>() { override fun getPointer(scope: AutofreeScope): CPointer<P> { val pinned = [email protected]() scope.defer { pinned.unpin() } return pinned.block() } } @SymbolName("Kotlin_Arrays_getByteArrayAddressOfElement") private external fun ByteArray.addressOfElement(index: Int): CPointer<ByteVar> @SymbolName("Kotlin_Arrays_getStringAddressOfElement") private external fun String.addressOfElement(index: Int): CPointer<COpaque> @SymbolName("Kotlin_Arrays_getCharArrayAddressOfElement") private external fun CharArray.addressOfElement(index: Int): CPointer<COpaque> @SymbolName("Kotlin_Arrays_getShortArrayAddressOfElement") private external fun ShortArray.addressOfElement(index: Int): CPointer<ShortVar> @SymbolName("Kotlin_Arrays_getIntArrayAddressOfElement") private external fun IntArray.addressOfElement(index: Int): CPointer<IntVar> @SymbolName("Kotlin_Arrays_getLongArrayAddressOfElement") private external fun LongArray.addressOfElement(index: Int): CPointer<LongVar> @SymbolName("Kotlin_Arrays_getByteArrayAddressOfElement") private external fun UByteArray.addressOfElement(index: Int): CPointer<UByteVar> @SymbolName("Kotlin_Arrays_getShortArrayAddressOfElement") private external fun UShortArray.addressOfElement(index: Int): CPointer<UShortVar> @SymbolName("Kotlin_Arrays_getIntArrayAddressOfElement") private external fun UIntArray.addressOfElement(index: Int): CPointer<UIntVar> @SymbolName("Kotlin_Arrays_getLongArrayAddressOfElement") private external fun ULongArray.addressOfElement(index: Int): CPointer<ULongVar> @SymbolName("Kotlin_Arrays_getFloatArrayAddressOfElement") private external fun FloatArray.addressOfElement(index: Int): CPointer<FloatVar> @SymbolName("Kotlin_Arrays_getDoubleArrayAddressOfElement") private external fun DoubleArray.addressOfElement(index: Int): CPointer<DoubleVar>
apache-2.0
ef66261ae26e90f768297bfaeb85a52d
43.503876
103
0.760495
4.10952
false
false
false
false
loxal/FreeEthereum
free-ethereum-core/src/main/java/org/ethereum/net/dht/Peer.kt
1
2684
/* * The MIT License (MIT) * * Copyright 2017 Alexander Orlov <[email protected]>. All rights reserved. * Copyright (c) [2016] [ <ether.camp> ] * * 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 org.ethereum.net.dht import org.ethereum.crypto.HashUtil import org.spongycastle.util.BigIntegers import org.spongycastle.util.encoders.Hex import java.math.BigInteger internal class Peer { private var id: ByteArray? = null private var host = "127.0.0.1" private var port = 0 constructor(id: ByteArray, host: String, port: Int) { this.id = id this.host = host this.port = port } constructor(ip: ByteArray) { this.id = ip } constructor() { HashUtil.randomPeerId() } fun nextBit(startPattern: String): Byte { if (this.toBinaryString().startsWith(startPattern + "1")) return 1 else return 0 } fun calcDistance(toPeer: Peer): ByteArray { val aPeer = BigInteger(getId()) val bPeer = BigInteger(toPeer.getId()) val distance = aPeer.xor(bPeer) return BigIntegers.asUnsignedByteArray(distance) } private fun getId(): ByteArray { return id!! } fun setId(ip: ByteArray) { this.id = id } override fun toString(): String { return String.format("Peer {\n id=%s, \n host=%s, \n port=%d\n}", Hex.toHexString(id!!), host, port) } fun toBinaryString(): String { val bi = BigInteger(1, id!!) var out = String.format("%512s", bi.toString(2)) out = out.replace(' ', '0') return out } }
mit
c6e0bc7d7c2863307371c13a260287ae
27.860215
108
0.663934
4.103976
false
false
false
false
SDS-Studios/ScoreKeeper
app/src/main/java/io/github/sdsstudios/ScoreKeeper/Fragment/ChangeScoreFragment.kt
1
3204
package io.github.sdsstudios.ScoreKeeper.Fragment import android.arch.lifecycle.ViewModelProviders import android.os.Bundle import android.support.v4.app.FragmentManager import android.support.v7.app.AlertDialog import android.text.Editable import android.text.InputType import android.text.TextWatcher import android.view.View import io.github.sdsstudios.ScoreKeeper.R import io.github.sdsstudios.ScoreKeeper.ViewModels.GameWithRoundsViewModel /** * Created by sethsch1 on 04/11/17. */ class ChangeScoreFragment : EditTextFragment() { companion object { private const val KEY_SCORE_INDEX = "score_index" private const val KEY_PLAYER_ID = "player_id" fun showDialog(fragmentManager: FragmentManager, playerId: Long, scoreIndex: Int) { ChangeScoreFragment().apply { arguments = Bundle().apply { putLong(KEY_PLAYER_ID, playerId) putInt(KEY_SCORE_INDEX, scoreIndex) } }.show(fragmentManager, TAG) } } private val mPlayerId by lazy { arguments!!.getLong(KEY_PLAYER_ID) } private val mScoreIndex by lazy { arguments!!.getInt(KEY_SCORE_INDEX) } private val mPlayerScores by lazy { mGameViewModel.game.rounds.single { it.playerId == mPlayerId } } private lateinit var mGameViewModel: GameWithRoundsViewModel override val title by lazy { getString(R.string.title_change_score) } override val inputType = InputType.TYPE_CLASS_NUMBER or InputType.TYPE_NUMBER_FLAG_SIGNED override fun onCreateDialog(savedInstanceState: Bundle?): AlertDialog { mGameViewModel = ViewModelProviders.of(activity!!).get(GameWithRoundsViewModel::class.java) return super.onCreateDialog(savedInstanceState) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) editText.apply { addTextChangedListener(object : TextWatcher { override fun afterTextChanged(s: Editable?) { if (s.isNullOrEmpty()) { error = getString(R.string.error_can_not_be_empty) return } else { try { text.toString().toLong() } catch (e: NumberFormatException) { editText.error = getString(R.string.error_number_too_big) return } } if (error != null) error = null } override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {} override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {} }) setText(mPlayerScores.scores[mScoreIndex].toString()) } } override fun onPosClick() { if (editText.error == null) { mPlayerScores.score = editText.text.toString().toLong() mGameViewModel.updateScoresInDb(mPlayerScores) super.onPosClick() } } }
gpl-3.0
cf128b2d10d0e7d957f3eca03fff8e77
33.836957
99
0.607054
4.847201
false
false
false
false
vector-im/vector-android
vector/src/main/java/im/vector/notifications/NotificationDrawerManager.kt
2
20378
/* * Copyright 2019 New Vector Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package im.vector.notifications import android.app.Notification import android.content.Context import android.graphics.Bitmap import android.graphics.BitmapFactory import android.os.PowerManager import android.text.TextUtils import android.view.WindowManager import android.widget.ImageView import androidx.core.app.NotificationCompat import androidx.core.app.Person import im.vector.BuildConfig import im.vector.Matrix import im.vector.R import im.vector.VectorApp import im.vector.util.SecretStoringUtils import org.matrix.androidsdk.MXSession import org.matrix.androidsdk.core.Log import java.io.File import java.io.FileInputStream import java.io.FileOutputStream /** * The NotificationDrawerManager receives notification events as they arrived (from event stream or fcm) and * organise them in order to display them in the notification drawer. * Events can be grouped into the same notification, old (already read) events can be removed to do some cleaning. */ class NotificationDrawerManager(val context: Context) { //The first time the notification drawer is refreshed, we force re-render of all notifications private var firstTime = true private var eventList = loadEventInfo() private var myUserDisplayName: String = "" private var myUserAvatarUrl: String = "" private val avatarSize = context.resources.getDimensionPixelSize(R.dimen.profile_avatar_size) private var currentRoomId: String? = null private var iconLoader = IconLoader(context, object : IconLoader.IconLoaderListener { override fun onIconsLoaded() { // Force refresh refreshNotificationDrawer(null) } }) /** * No multi session support for now */ private fun initWithSession(session: MXSession?) { session?.let { myUserDisplayName = it.myUser?.displayname ?: it.myUserId // User Avatar it.myUser?.avatarUrl?.let { avatarUrl -> val userAvatarUrlPath = it.mediaCache?.thumbnailCacheFile(avatarUrl, avatarSize) if (userAvatarUrlPath != null) { myUserAvatarUrl = userAvatarUrlPath.path } else { // prepare for the next time session.mediaCache?.loadAvatarThumbnail(session.homeServerConfig, ImageView(context), avatarUrl, avatarSize) } } } } /** Should be called as soon as a new event is ready to be displayed. The notification corresponding to this event will not be displayed until #refreshNotificationDrawer() is called. Events might be grouped and there might not be one notification per event! */ fun onNotifiableEventReceived(notifiableEvent: NotifiableEvent) { //If we support multi session, event list should be per userId //Currently only manage single session if (BuildConfig.LOW_PRIVACY_LOG_ENABLE) { Log.d(LOG_TAG, "%%%%%%%% onNotifiableEventReceived $notifiableEvent") } synchronized(eventList) { val existing = eventList.firstOrNull { it.eventId == notifiableEvent.eventId } if (existing != null) { if (existing.isPushGatewayEvent) { //Use the event coming from the event stream as it may contains more info than //the fcm one (like type/content/clear text) // In this case the message has already been notified, and might have done some noise // So we want the notification to be updated even if it has already been displayed // But it should make no noise (e.g when an encrypted message from FCM should be // update with clear text after a sync) notifiableEvent.hasBeenDisplayed = false notifiableEvent.noisy = false eventList.remove(existing) eventList.add(notifiableEvent) } else { //keep the existing one, do not replace } } else { eventList.add(notifiableEvent) } } } /** Clear all known events and refresh the notification drawer */ fun clearAllEvents() { synchronized(eventList) { eventList.clear() } refreshNotificationDrawer(null) } /** Clear all known message events for this room and refresh the notification drawer */ fun clearMessageEventOfRoom(roomId: String?) { Log.d(LOG_TAG, "clearMessageEventOfRoom $roomId") if (roomId != null) { eventList.removeAll { e -> if (e is NotifiableMessageEvent) { return@removeAll e.roomId == roomId } return@removeAll false } NotificationUtils.cancelNotificationMessage(context, roomId, ROOM_MESSAGES_NOTIFICATION_ID) } refreshNotificationDrawer(null) } /** Should be called when the application is currently opened and showing timeline for the given roomId. Used to ignore events related to that room (no need to display notification) and clean any existing notification on this room. */ fun setCurrentRoom(roomId: String?) { var hasChanged: Boolean synchronized(eventList) { hasChanged = roomId != currentRoomId currentRoomId = roomId } if (hasChanged) { clearMessageEventOfRoom(roomId) } } fun homeActivityDidResume(matrixID: String?) { synchronized(eventList) { eventList.removeAll { e -> return@removeAll e !is NotifiableMessageEvent //messages are cleared when entering room } } } fun clearMemberShipNotificationForRoom(roomId: String) { synchronized(eventList) { eventList.removeAll { e -> if (e is InviteNotifiableEvent) { return@removeAll e.roomId == roomId } return@removeAll false } } } fun refreshNotificationDrawer(outdatedDetector: OutdatedEventDetector?) { try { _refreshNotificationDrawer(outdatedDetector) } catch (e: Exception) { //defensive coding Log.e(LOG_TAG, "## Failed to refresh drawer", e) } } private fun _refreshNotificationDrawer(outdatedDetector: OutdatedEventDetector?) { if (myUserDisplayName.isBlank()) { initWithSession(Matrix.getInstance(context).defaultSession) } if (myUserDisplayName.isBlank()) { // Should not happen, but myUserDisplayName cannot be blank if used to create a Person return } synchronized(eventList) { Log.d(LOG_TAG, "%%%%%%%% REFRESH NOTIFICATION DRAWER ") //TMP code var hasNewEvent = false var summaryIsNoisy = false val summaryInboxStyle = NotificationCompat.InboxStyle() //group events by room to create a single MessagingStyle notif val roomIdToEventMap: MutableMap<String, ArrayList<NotifiableMessageEvent>> = HashMap() val simpleEvents: ArrayList<NotifiableEvent> = ArrayList() val notifications: ArrayList<Notification> = ArrayList() val eventIterator = eventList.listIterator() while (eventIterator.hasNext()) { val event = eventIterator.next() if (event is NotifiableMessageEvent) { val roomId = event.roomId var roomEvents = roomIdToEventMap[roomId] if (roomEvents == null) { roomEvents = ArrayList() roomIdToEventMap[roomId] = roomEvents } if (shouldIgnoreMessageEventInRoom(roomId) || outdatedDetector?.isMessageOutdated(event) == true) { //forget this event eventIterator.remove() } else { roomEvents.add(event) } } else { simpleEvents.add(event) } } Log.d(LOG_TAG, "%%%%%%%% REFRESH NOTIFICATION DRAWER ${roomIdToEventMap.size} room groups") var globalLastMessageTimestamp = 0L //events have been grouped for ((roomId, events) in roomIdToEventMap) { if (events.isEmpty()) { //Just clear this notification Log.d(LOG_TAG, "%%%%%%%% REFRESH NOTIFICATION DRAWER $roomId has no more events") NotificationUtils.cancelNotificationMessage(context, roomId, ROOM_MESSAGES_NOTIFICATION_ID) continue } val roomGroup = RoomEventGroupInfo(roomId) roomGroup.hasNewEvent = false roomGroup.shouldBing = false roomGroup.isDirect = events[0].roomIsDirect val roomName = events[0].roomName ?: events[0].senderName ?: "" val style = NotificationCompat.MessagingStyle(Person.Builder() .setName(myUserDisplayName) .setIcon(iconLoader.getUserIcon(myUserAvatarUrl)) .setKey(events[0].matrixID) .build()) roomGroup.roomDisplayName = roomName style.isGroupConversation = !roomGroup.isDirect if (!roomGroup.isDirect) { style.conversationTitle = roomName } val largeBitmap = getRoomBitmap(events) for (event in events) { //if all events in this room have already been displayed there is no need to update it if (!event.hasBeenDisplayed) { roomGroup.shouldBing = roomGroup.shouldBing || event.noisy roomGroup.customSound = event.soundName } roomGroup.hasNewEvent = roomGroup.hasNewEvent || !event.hasBeenDisplayed val senderPerson = Person.Builder() .setName(event.senderName) .setIcon(iconLoader.getUserIcon(event.senderAvatarPath)) .setKey(event.senderId) .build() if (event.outGoingMessage && event.outGoingMessageFailed) { style.addMessage(context.getString(R.string.notification_inline_reply_failed), event.timestamp, senderPerson) roomGroup.hasSmartReplyError = true } else { style.addMessage(event.body, event.timestamp, senderPerson) } event.hasBeenDisplayed = true //we can consider it as displayed //It is possible that this event was previously shown as an 'anonymous' simple notif. //And now it will be merged in a single MessageStyle notif, so we can clean to be sure NotificationUtils.cancelNotificationMessage(context, event.eventId, ROOM_EVENT_NOTIFICATION_ID) } try { val summaryLine = context.resources.getQuantityString( R.plurals.notification_compat_summary_line_for_room, events.size, roomName, events.size) summaryInboxStyle.addLine(summaryLine) } catch (e: Throwable) { //String not found or bad format Log.d(LOG_TAG, "%%%%%%%% REFRESH NOTIFICATION DRAWER failed to resolve string") summaryInboxStyle.addLine(roomName) } if (firstTime || roomGroup.hasNewEvent) { //Should update displayed notification Log.d(LOG_TAG, "%%%%%%%% REFRESH NOTIFICATION DRAWER $roomId need refresh") val lastMessageTimestamp = events.last().timestamp if (globalLastMessageTimestamp < lastMessageTimestamp) { globalLastMessageTimestamp = lastMessageTimestamp } NotificationUtils.buildMessagesListNotification(context, style, roomGroup, largeBitmap, lastMessageTimestamp, myUserDisplayName) ?.let { //is there an id for this room? notifications.add(it) NotificationUtils.showNotificationMessage(context, roomId, ROOM_MESSAGES_NOTIFICATION_ID, it) } hasNewEvent = true summaryIsNoisy = summaryIsNoisy || roomGroup.shouldBing } else { Log.d(LOG_TAG, "%%%%%%%% REFRESH NOTIFICATION DRAWER $roomId is up to date") } } //Handle simple events for (event in simpleEvents) { //We build a simple event if (firstTime || !event.hasBeenDisplayed) { NotificationUtils.buildSimpleEventNotification(context, event, null, myUserDisplayName)?.let { notifications.add(it) NotificationUtils.showNotificationMessage(context, event.eventId, ROOM_EVENT_NOTIFICATION_ID, it) event.hasBeenDisplayed = true //we can consider it as displayed hasNewEvent = true summaryIsNoisy = summaryIsNoisy || event.noisy summaryInboxStyle.addLine(event.description) } } } //======== Build summary notification ========= //On Android 7.0 (API level 24) and higher, the system automatically builds a summary for // your group using snippets of text from each notification. The user can expand this // notification to see each separate notification. // To support older versions, which cannot show a nested group of notifications, // you must create an extra notification that acts as the summary. // This appears as the only notification and the system hides all the others. // So this summary should include a snippet from all the other notifications, // which the user can tap to open your app. // The behavior of the group summary may vary on some device types such as wearables. // To ensure the best experience on all devices and versions, always include a group summary when you create a group // https://developer.android.com/training/notify-user/group if (eventList.isEmpty()) { NotificationUtils.cancelNotificationMessage(context, null, SUMMARY_NOTIFICATION_ID) } else { val nbEvents = roomIdToEventMap.size + simpleEvents.size val sumTitle = context.resources.getQuantityString( R.plurals.notification_compat_summary_title, nbEvents, nbEvents) summaryInboxStyle.setBigContentTitle(sumTitle) NotificationUtils.buildSummaryListNotification( context, summaryInboxStyle, sumTitle, noisy = hasNewEvent && summaryIsNoisy, lastMessageTimestamp = globalLastMessageTimestamp )?.let { NotificationUtils.showNotificationMessage(context, null, SUMMARY_NOTIFICATION_ID, it) } if (hasNewEvent && summaryIsNoisy) { try { // turn the screen on for 3 seconds if (Matrix.getInstance(VectorApp.getInstance())!!.pushManager.isScreenTurnedOn) { val pm = VectorApp.getInstance().getSystemService(Context.POWER_SERVICE) as PowerManager val wl = pm.newWakeLock(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON or PowerManager.ACQUIRE_CAUSES_WAKEUP, NotificationDrawerManager::class.java.name) wl.acquire(3000) wl.release() } } catch (e: Throwable) { Log.e(LOG_TAG, "## Failed to turn screen on", e) } } } //notice that we can get bit out of sync with actual display but not a big issue firstTime = false } } private fun getRoomBitmap(events: ArrayList<NotifiableMessageEvent>): Bitmap? { if (events.isEmpty()) return null //Use the last event (most recent?) val roomAvatarPath = events[events.size - 1].roomAvatarPath ?: events[events.size - 1].senderAvatarPath if (!TextUtils.isEmpty(roomAvatarPath)) { val options = BitmapFactory.Options() options.inPreferredConfig = Bitmap.Config.ARGB_8888 try { return BitmapFactory.decodeFile(roomAvatarPath, options) } catch (oom: OutOfMemoryError) { Log.e(LOG_TAG, "## decodeFile failed with an oom", oom) } catch (e: Exception) { Log.e(LOG_TAG, "## decodeFile failed", e) } } return null } private fun shouldIgnoreMessageEventInRoom(roomId: String?): Boolean { return currentRoomId != null && roomId == currentRoomId } fun persistInfo() { if (eventList.isEmpty()) { deleteCachedRoomNotifications(context) return } try { val file = File(context.applicationContext.cacheDir, ROOMS_NOTIFICATIONS_FILE_NAME) if (!file.exists()) file.createNewFile() FileOutputStream(file).use { SecretStoringUtils.securelyStoreObject(eventList, "notificationMgr", it, this.context) } } catch (e: Throwable) { Log.e(LOG_TAG, "## Failed to save cached notification info", e) } } private fun loadEventInfo(): ArrayList<NotifiableEvent> { try { val file = File(context.applicationContext.cacheDir, ROOMS_NOTIFICATIONS_FILE_NAME) if (file.exists()) { FileInputStream(file).use { val events: ArrayList<NotifiableEvent>? = SecretStoringUtils.loadSecureSecret(it, "notificationMgr", this.context) if (events != null) { return ArrayList(events.mapNotNull { it as? NotifiableEvent }) } } } } catch (e: Throwable) { Log.e(LOG_TAG, "## Failed to load cached notification info", e) } return ArrayList() } private fun deleteCachedRoomNotifications(context: Context) { val file = File(context.applicationContext.cacheDir, ROOMS_NOTIFICATIONS_FILE_NAME) if (file.exists()) { file.delete() } } companion object { private const val SUMMARY_NOTIFICATION_ID = 0 private const val ROOM_MESSAGES_NOTIFICATION_ID = 1 private const val ROOM_EVENT_NOTIFICATION_ID = 2 private const val ROOMS_NOTIFICATIONS_FILE_NAME = "im.vector.notifications.cache" private val LOG_TAG = NotificationDrawerManager::class.java.simpleName } }
apache-2.0
96bbcab07c1bed8b63d9f5f2b2528c1b
42.082452
148
0.58308
5.532989
false
false
false
false
sg26565/hott-transmitter-config
HoTT-TTS/src/main/kotlin/de/treichels/hott/tts/voicerss/VoiceRSSTTSProvider.kt
1
2277
package de.treichels.hott.tts.voicerss import de.treichels.hott.tts.* import java.net.URL import java.net.URLEncoder import java.util.* import java.util.prefs.Preferences import javax.sound.sampled.AudioInputStream import javax.sound.sampled.AudioSystem class VoiceRSSTTSProvider : Text2SpeechProvider() { companion object { private val PREFS = Preferences.userNodeForPackage(VoiceRSSTTSProvider::class.java) private const val VOICE_RSS_DEFAULT_API_KEY = "46209359f9804adb8616c76d18de928a" private const val API_KEY = "apiKey" internal var apiKey: String? get() = PREFS.get(API_KEY, null) set(key) { PREFS.put(API_KEY, key) } } override val enabled = true override val name = "VoiceRSS" override val qualities: List<Quality> = SampleRate.values().flatMap { listOf(Quality(it.rate.toInt(), 1), Quality(it.rate.toInt(), 2)) } override val ssmlSupported: Boolean = false override fun installedVoices() = VoiceRssLanguage.values().map { lang -> Voice().apply { enabled = true age = Age.Adult // VoiceRSS has only adult voices locale = Locale.forLanguageTag(lang.name.replace("_", "-")) description = lang.toString() gender = Gender.Female // VoiceRSS has only female voices id = lang.key name = locale.getDisplayLanguage(locale) // VoiceRSS does not provide a name for its voices - use the language instead } } override fun speak(text: String, voice: Voice, speed: Int, volume: Int, quality: Quality, ssml: Boolean): AudioInputStream { if (ssml) throw UnsupportedOperationException("SSML markup is not supported") // test format - throws exception if not valid val format = Format.valueOf("pcm_${quality.sampleRate / 1000}khz_${quality.sampleSize}bit_${if (quality.channels == 1) "mono" else "stereo"}") val key = if (apiKey.isNullOrBlank()) VOICE_RSS_DEFAULT_API_KEY else apiKey!! val url = URL("http://api.voicerss.org/?key=$key&hl=${voice.id}&r=$speed&c=WAV&f=${format.key}&ssml=false&b64=false&src=${URLEncoder.encode(text, "UTF-8")}") return AudioSystem.getAudioInputStream(url) } }
lgpl-3.0
907d5b20959b964a60c268bf6f7adb98
41.166667
165
0.661397
3.966899
false
false
false
false
aosp-mirror/platform_frameworks_support
core/ktx/src/androidTest/java/androidx/core/graphics/BitmapTest.kt
1
2135
/* * Copyright (C) 2017 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.core.graphics import android.graphics.Bitmap import android.graphics.ColorSpace import android.support.test.filters.SdkSuppress import org.junit.Assert.assertEquals import org.junit.Test class BitmapTest { @Test fun create() { val bitmap = createBitmap(7, 9) assertEquals(7, bitmap.width) assertEquals(9, bitmap.height) assertEquals(Bitmap.Config.ARGB_8888, bitmap.config) } @Test fun createWithConfig() { val bitmap = createBitmap(7, 9, config = Bitmap.Config.RGB_565) assertEquals(Bitmap.Config.RGB_565, bitmap.config) } @SdkSuppress(minSdkVersion = 26) @Test fun createWithColorSpace() { val colorSpace = ColorSpace.get(ColorSpace.Named.ADOBE_RGB) val bitmap = createBitmap(7, 9, colorSpace = colorSpace) assertEquals(colorSpace, bitmap.colorSpace) } @Test fun scale() { val b = createBitmap(7, 9).scale(3, 5) assertEquals(3, b.width) assertEquals(5, b.height) } @Test fun applyCanvas() { val p = createBitmap(2, 2).applyCanvas { drawColor(0x40302010) }.getPixel(1, 1) assertEquals(0x40302010, p) } @Test fun getPixel() { val b = createBitmap(2, 2).applyCanvas { drawColor(0x40302010) } assertEquals(0x40302010, b[1, 1]) } @Test fun setPixel() { val b = createBitmap(2, 2) b[1, 1] = 0x40302010 assertEquals(0x40302010, b[1, 1]) } }
apache-2.0
07f0a05c2095b8840361c26331da0bd0
29.070423
75
0.659016
3.975791
false
true
false
false
chiken88/passnotes
app/src/main/kotlin/com/ivanovsky/passnotes/extensions/FileDescriptorExt.kt
1
1061
package com.ivanovsky.passnotes.extensions import com.ivanovsky.passnotes.R import com.ivanovsky.passnotes.data.entity.FSType import com.ivanovsky.passnotes.data.entity.FileDescriptor import com.ivanovsky.passnotes.data.entity.UsedFile import com.ivanovsky.passnotes.domain.ResourceProvider fun FileDescriptor.toUsedFile( addedTime: Long, lastAccessTime: Long? = null ): UsedFile = UsedFile( fsAuthority = fsAuthority, filePath = path, fileUid = uid, fileName = name, addedTime = addedTime, lastAccessTime = lastAccessTime ) fun FileDescriptor.formatReadablePath(resourceProvider: ResourceProvider): String { return when (fsAuthority.type) { FSType.REGULAR_FS -> { path } FSType.DROPBOX -> { resourceProvider.getString(R.string.dropbox) + ":/" + path } FSType.WEBDAV -> { val url = fsAuthority.credentials?.serverUrl ?: "" url + path } FSType.SAF -> { path } } }
gpl-2.0
065a0ca3450b7f8d78292c7f7806c66f
26.947368
83
0.637135
4.514894
false
false
false
false
aosp-mirror/platform_frameworks_support
core/ktx/src/androidTest/java/androidx/core/text/SpannableStringBuilderTest.kt
1
8902
/* * Copyright (C) 2017 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.core.text import android.graphics.Color.RED import android.graphics.Color.YELLOW import android.graphics.Typeface.BOLD import android.graphics.Typeface.ITALIC import android.text.SpannedString import android.text.style.BackgroundColorSpan import android.text.style.BulletSpan import android.text.style.ForegroundColorSpan import android.text.style.RelativeSizeSpan import android.text.style.StrikethroughSpan import android.text.style.StyleSpan import android.text.style.SubscriptSpan import android.text.style.SuperscriptSpan import android.text.style.UnderlineSpan import org.junit.Assert.assertEquals import org.junit.Assert.assertSame import org.junit.Test class SpannableStringBuilderTest { @Test fun builder() { val result: SpannedString = buildSpannedString { append("Hello,") append(" World") } assertEquals("Hello, World", result.toString()) } @Test fun builderInSpan() { val bold = StyleSpan(BOLD) val result: SpannedString = buildSpannedString { append("Hello, ") inSpans(bold) { append("World") } } assertEquals("Hello, World", result.toString()) val spans = result.getSpans<Any>() assertEquals(1, spans.size) val boldSpan = spans.filterIsInstance<StyleSpan>().single() assertSame(bold, boldSpan) assertEquals(7, result.getSpanStart(bold)) assertEquals(12, result.getSpanEnd(bold)) } @Test fun builderBold() { val result: SpannedString = buildSpannedString { append("Hello, ") bold { append("World") } } assertEquals("Hello, World", result.toString()) val spans = result.getSpans<Any>() assertEquals(1, spans.size) val bold = spans.filterIsInstance<StyleSpan>().single() assertEquals(BOLD, bold.style) assertEquals(7, result.getSpanStart(bold)) assertEquals(12, result.getSpanEnd(bold)) } @Test fun builderItalic() { val result: SpannedString = buildSpannedString { append("Hello, ") italic { append("World") } } assertEquals("Hello, World", result.toString()) val spans = result.getSpans<Any>() assertEquals(1, spans.size) val italic = spans.filterIsInstance<StyleSpan>().single() assertEquals(ITALIC, italic.style) assertEquals(7, result.getSpanStart(italic)) assertEquals(12, result.getSpanEnd(italic)) } @Test fun builderUnderline() { val result: SpannedString = buildSpannedString { append("Hello, ") underline { append("World") } } assertEquals("Hello, World", result.toString()) val spans = result.getSpans<Any>() assertEquals(1, spans.size) val underline = spans.filterIsInstance<UnderlineSpan>().single() assertEquals(7, result.getSpanStart(underline)) assertEquals(12, result.getSpanEnd(underline)) } @Test fun builderColor() { val result: SpannedString = buildSpannedString { append("Hello, ") color(RED) { append("World") } } assertEquals("Hello, World", result.toString()) val spans = result.getSpans<Any>() assertEquals(1, spans.size) val color = spans.filterIsInstance<ForegroundColorSpan>().single() assertEquals(RED, color.foregroundColor) assertEquals(7, result.getSpanStart(color)) assertEquals(12, result.getSpanEnd(color)) } @Test fun builderBackgroundColor() { val result: SpannedString = buildSpannedString { append("Hello, ") backgroundColor(RED) { append("World") } } assertEquals("Hello, World", result.toString()) val spans = result.getSpans<Any>() assertEquals(1, spans.size) val color = spans.filterIsInstance<BackgroundColorSpan>().single() assertEquals(RED, color.backgroundColor) assertEquals(7, result.getSpanStart(color)) assertEquals(12, result.getSpanEnd(color)) } @Test fun builderStrikeThrough() { val result: SpannedString = buildSpannedString { append("Hello, ") strikeThrough { append("World") } } assertEquals("Hello, World", result.toString()) val spans = result.getSpans<Any>() assertEquals(1, spans.size) val strikeThrough = spans.filterIsInstance<StrikethroughSpan>().single() assertEquals(7, result.getSpanStart(strikeThrough)) assertEquals(12, result.getSpanEnd(strikeThrough)) } @Test fun builderScale() { val result: SpannedString = buildSpannedString { append("Hello, ") scale(2f) { append("World") } } assertEquals("Hello, World", result.toString()) val spans = result.getSpans<Any>() assertEquals(1, spans.size) val scale = spans.filterIsInstance<RelativeSizeSpan>().single() assertEquals(2f, scale.sizeChange) assertEquals(7, result.getSpanStart(scale)) assertEquals(12, result.getSpanEnd(scale)) } @Test fun nested() { val result: SpannedString = buildSpannedString { color(RED) { append('H') inSpans(SubscriptSpan()) { append('e') } append('l') inSpans(SuperscriptSpan()) { append('l') } append('o') } append(", ") backgroundColor(YELLOW) { append('W') underline { append('o') bold { append('r') } append('l') } append('d') } } assertEquals("Hello, World", result.toString()) val spans = result.getSpans<Any>() assertEquals(6, spans.size) val color = spans.filterIsInstance<ForegroundColorSpan>().single() assertEquals(RED, color.foregroundColor) assertEquals(0, result.getSpanStart(color)) assertEquals(5, result.getSpanEnd(color)) val subscript = spans.filterIsInstance<SubscriptSpan>().single() assertEquals(1, result.getSpanStart(subscript)) assertEquals(2, result.getSpanEnd(subscript)) val superscript = spans.filterIsInstance<SuperscriptSpan>().single() assertEquals(3, result.getSpanStart(superscript)) assertEquals(4, result.getSpanEnd(superscript)) val backgroundColor = spans.filterIsInstance<BackgroundColorSpan>().single() assertEquals(YELLOW, backgroundColor.backgroundColor) assertEquals(7, result.getSpanStart(backgroundColor)) assertEquals(12, result.getSpanEnd(backgroundColor)) val underline = spans.filterIsInstance<UnderlineSpan>().single() assertEquals(8, result.getSpanStart(underline)) assertEquals(11, result.getSpanEnd(underline)) val bold = spans.filterIsInstance<StyleSpan>().single() assertEquals(BOLD, bold.style) assertEquals(9, result.getSpanStart(bold)) assertEquals(10, result.getSpanEnd(bold)) } @Test fun multipleSpans() { val result: SpannedString = buildSpannedString { append("Hello, ") inSpans(BulletSpan(), UnderlineSpan()) { append("World") } } assertEquals("Hello, World", result.toString()) val spans = result.getSpans<Any>() assertEquals(2, spans.size) val bullet = spans.filterIsInstance<BulletSpan>().single() assertEquals(7, result.getSpanStart(bullet)) assertEquals(12, result.getSpanEnd(bullet)) val underline = spans.filterIsInstance<UnderlineSpan>().single() assertEquals(7, result.getSpanStart(underline)) assertEquals(12, result.getSpanEnd(underline)) } }
apache-2.0
f986ba777c1ee8ca698d833c4769496a
32.340824
84
0.6102
5.086857
false
false
false
false
developer--/before_after_slider
beforeafterslider/src/main/java/com/github/developer__/asycn/ClipDrawableProcessorTask.kt
1
3550
package com.github.developer__.asycn import android.content.Context import android.graphics.Bitmap import android.graphics.drawable.BitmapDrawable import android.graphics.drawable.ClipDrawable import android.os.AsyncTask import android.os.Looper import android.view.Gravity import android.widget.ImageView import android.widget.SeekBar import com.bumptech.glide.Glide import java.lang.ref.WeakReference /** * Created by Jemo on 12/5/16. */ class ClipDrawableProcessorTask<T>(imageView: ImageView, seekBar: SeekBar, private val context: Context, private val loadedFinishedListener: OnAfterImageLoaded? = null) : AsyncTask<T, Void, ClipDrawable>() { private val imageRef: WeakReference<ImageView> private val seekBarRef: WeakReference<SeekBar> init { this.imageRef = WeakReference(imageView) this.seekBarRef = WeakReference(seekBar) } override fun doInBackground(vararg args: T): ClipDrawable? { Looper.myLooper()?.let { Looper.prepare() } try { var theBitmap: Bitmap if (args[0] is String) { theBitmap = Glide.with(context) .load(args[0]) .asBitmap() .into(-1, -1) .get() } else { theBitmap = (args[0] as BitmapDrawable).bitmap } val tmpBitmap = getScaledBitmap(theBitmap) if (tmpBitmap != null) theBitmap = tmpBitmap val bitmapDrawable = BitmapDrawable(context.resources, theBitmap) return ClipDrawable(bitmapDrawable, Gravity.LEFT, ClipDrawable.HORIZONTAL) } catch (e: Exception) { e.printStackTrace() } return null } private fun getScaledBitmap(bitmap: Bitmap): Bitmap? { try { if (imageRef.get() == null) return bitmap val imageWidth = imageRef.get().width val imageHeight = imageRef.get().height if (imageWidth > 0 && imageHeight > 0) return Bitmap.createScaledBitmap(bitmap, imageWidth, imageHeight, false) } catch (e: Exception) { e.printStackTrace() } return null } override fun onPostExecute(clipDrawable: ClipDrawable?) { if (imageRef.get() != null) { if (clipDrawable != null) { initSeekBar(clipDrawable) imageRef.get().setImageDrawable(clipDrawable) if (clipDrawable.level != 0) { val progressNum = 5000 clipDrawable.level = progressNum } else clipDrawable.level = seekBarRef.get().progress loadedFinishedListener?.onLoadedFinished(true) } else { loadedFinishedListener?.onLoadedFinished(false) } } else { loadedFinishedListener?.onLoadedFinished(false) } } private fun initSeekBar(clipDrawable: ClipDrawable) { seekBarRef.get().setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener { override fun onProgressChanged(seekBar: SeekBar, i: Int, b: Boolean) { clipDrawable.level = i } override fun onStartTrackingTouch(seekBar: SeekBar) { } override fun onStopTrackingTouch(seekBar: SeekBar) { } }) } interface OnAfterImageLoaded { fun onLoadedFinished(loadedSuccess: Boolean) } }
apache-2.0
59b2c158eabe0fb302376a03da700d8e
31.281818
207
0.597746
5.122655
false
false
false
false
YouriAckx/AdventOfCode
2017/src/day16/part01.kt
1
1029
package day16 import java.io.File import java.util.* fun main(args: Array<String>) { val re = Regex("([sxp])(\\d+|\\w)/?(\\d+|\\w)?") var programs = ('a'..'p').map { it.toString() }.toMutableList() File("src/day16/input.txt").bufferedReader().readLine()!!.split(",").forEach { action -> val (move, param1, param2) = re.matchEntire(action)!!.destructured when (move) { "s" -> { val spins = param1.toInt() % programs.size val left = programs.subList(programs.size - spins, programs.size) val right = programs.subList(0, programs.size - spins) programs = left programs.addAll(right) } "x" -> Collections.swap(programs, param1.toInt(), param2.toInt()) "p" -> Collections.swap(programs, programs.indexOf(param1), programs.indexOf(param2)) else -> throw IllegalArgumentException("Unknown dance move: $move") } } println(programs.joinToString("")) }
gpl-3.0
7a3cc8d7cd11e33234f0291ccad2148f
40.2
97
0.568513
3.988372
false
false
false
false
BlueBoxWare/LibGDXPlugin
src/main/kotlin/com/gmail/blueboxware/libgdxplugin/filetypes/skin/highlighting/LibGDXSkinColorsPage.kt
1
7064
package com.gmail.blueboxware.libgdxplugin.filetypes.skin.highlighting import com.gmail.blueboxware.libgdxplugin.filetypes.skin.LibGDXSkinLanguage import com.gmail.blueboxware.libgdxplugin.filetypes.skin.highlighting.SkinSyntaxHighlighterFactory.Companion.SKIN_BLOCK_COMMENT import com.gmail.blueboxware.libgdxplugin.filetypes.skin.highlighting.SkinSyntaxHighlighterFactory.Companion.SKIN_BRACES import com.gmail.blueboxware.libgdxplugin.filetypes.skin.highlighting.SkinSyntaxHighlighterFactory.Companion.SKIN_BRACKETS import com.gmail.blueboxware.libgdxplugin.filetypes.skin.highlighting.SkinSyntaxHighlighterFactory.Companion.SKIN_CLASS_NAME import com.gmail.blueboxware.libgdxplugin.filetypes.skin.highlighting.SkinSyntaxHighlighterFactory.Companion.SKIN_COLON import com.gmail.blueboxware.libgdxplugin.filetypes.skin.highlighting.SkinSyntaxHighlighterFactory.Companion.SKIN_COMMA import com.gmail.blueboxware.libgdxplugin.filetypes.skin.highlighting.SkinSyntaxHighlighterFactory.Companion.SKIN_INVALID_ESCAPE import com.gmail.blueboxware.libgdxplugin.filetypes.skin.highlighting.SkinSyntaxHighlighterFactory.Companion.SKIN_KEYWORD import com.gmail.blueboxware.libgdxplugin.filetypes.skin.highlighting.SkinSyntaxHighlighterFactory.Companion.SKIN_LINE_COMMENT import com.gmail.blueboxware.libgdxplugin.filetypes.skin.highlighting.SkinSyntaxHighlighterFactory.Companion.SKIN_NUMBER import com.gmail.blueboxware.libgdxplugin.filetypes.skin.highlighting.SkinSyntaxHighlighterFactory.Companion.SKIN_PARENT_PROPERTY import com.gmail.blueboxware.libgdxplugin.filetypes.skin.highlighting.SkinSyntaxHighlighterFactory.Companion.SKIN_PROPERTY_NAME import com.gmail.blueboxware.libgdxplugin.filetypes.skin.highlighting.SkinSyntaxHighlighterFactory.Companion.SKIN_RESOURCE_NAME import com.gmail.blueboxware.libgdxplugin.filetypes.skin.highlighting.SkinSyntaxHighlighterFactory.Companion.SKIN_STRING import com.gmail.blueboxware.libgdxplugin.filetypes.skin.highlighting.SkinSyntaxHighlighterFactory.Companion.SKIN_VALID_ESCAPE import com.intellij.application.options.colors.InspectionColorSettingsPage import com.intellij.openapi.fileTypes.SyntaxHighlighter import com.intellij.openapi.fileTypes.SyntaxHighlighterFactory import com.intellij.openapi.options.colors.AttributesDescriptor import com.intellij.openapi.options.colors.ColorDescriptor import com.intellij.openapi.options.colors.ColorSettingsPage import com.intellij.psi.codeStyle.DisplayPriority import com.intellij.psi.codeStyle.DisplayPrioritySortable import icons.Icons import javax.swing.Icon /* * Copyright 2016 Blue Box Ware * * 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. */ class LibGDXSkinColorsPage : ColorSettingsPage, InspectionColorSettingsPage, DisplayPrioritySortable { companion object { private val additionalHighlighting = mapOf( "resourceName" to SKIN_RESOURCE_NAME, "propertyName" to SKIN_PROPERTY_NAME, "className" to SKIN_CLASS_NAME, "number" to SKIN_NUMBER, "keyword" to SKIN_KEYWORD, "parent" to SKIN_PARENT_PROPERTY ) private val myAttributeDescriptors = arrayOf( AttributesDescriptor("Property name", SKIN_PROPERTY_NAME), AttributesDescriptor("Parent property", SKIN_PARENT_PROPERTY), AttributesDescriptor("Braces", SKIN_BRACES), AttributesDescriptor("Brackets", SKIN_BRACKETS), AttributesDescriptor("Comma", SKIN_COMMA), AttributesDescriptor("Colon", SKIN_COLON), AttributesDescriptor("Number", SKIN_NUMBER), AttributesDescriptor("Keyword", SKIN_KEYWORD), AttributesDescriptor("Line comment", SKIN_LINE_COMMENT), AttributesDescriptor("Block comment", SKIN_BLOCK_COMMENT), AttributesDescriptor("Valid escape sequence", SKIN_VALID_ESCAPE), AttributesDescriptor("Invalid escape sequence", SKIN_INVALID_ESCAPE), AttributesDescriptor("String", SKIN_STRING), AttributesDescriptor("Class name", SKIN_CLASS_NAME), AttributesDescriptor("Resource name", SKIN_RESOURCE_NAME) ) } override fun getIcon(): Icon = Icons.SKIN_FILETYPE override fun getHighlighter(): SyntaxHighlighter = SyntaxHighlighterFactory.getSyntaxHighlighter( LibGDXSkinLanguage.INSTANCE, null, null ) override fun getDemoText() = """ { // Line comment /* Block comment */ <className>com.badlogic.gdx.graphics.Color</className>: { <resourceName>red</resourceName>: { <propertyName>r</propertyName>: <number>1</number>, <propertyName>g</propertyName>: <number>0</number>, <propertyName>b</propertyName>: <number>0</number>, <propertyName>a</propertyName>: <number>1</number> }, <resourceName>yellow</resourceName>: { <propertyName>r</propertyName>: <number>0.5</number>, <propertyName>g</propertyName>: <number>0.5</number>, <propertyName>b</propertyName>: <number>0</number>, <propertyName>a</propertyName>: <number>1</number> } }, <className>com.badlogic.gdx.graphics.g2d.BitmapFont</className>: { <resourceName>medium</resourceName>: { <propertyName>file</propertyName>: medium.fnt, <propertyName>keyword</propertyName>: <keyword>true</keyword> } }, <className>com.badlogic.gdx.scenes.scene2d.ui.TextButton${'$'}TextButtonStyle</className>: { <resourceName>default</resourceName>: { <propertyName>down</propertyName>: "round-down", <propertyName>up</propertyName>: round, <propertyName>font</propertyName>: 'medium', <propertyName>fontColor</propertyName>: white }, <resourceName>toggle</resourceName>: { <parent>parent</parent>: default, <propertyName>down</propertyName>: round-down, <propertyName>up</propertyName>: round, <propertyName>checked</propertyName>: round-down, <propertyName>font</propertyName>: medium, <propertyName>fontColor</propertyName>: white, <propertyName>checkedFontColor</propertyName>: red }, } } """ override fun getAdditionalHighlightingTagToDescriptorMap() = additionalHighlighting override fun getAttributeDescriptors(): Array<out AttributesDescriptor> = myAttributeDescriptors override fun getColorDescriptors(): Array<out ColorDescriptor> = ColorDescriptor.EMPTY_ARRAY @Suppress("DialogTitleCapitalization") override fun getDisplayName() = "libGDX skin" override fun getPriority(): DisplayPriority = DisplayPriority.LANGUAGE_SETTINGS }
apache-2.0
74d473c15620589d0f0a549b0a42cbc9
53.338462
259
0.761608
4.978154
false
false
false
false
grote/Liberario
app/src/main/java/de/grobox/transportr/about/ContributorFragment.kt
1
4071
/* * Transportr * * Copyright (c) 2013 - 2018 Torsten Grote * * 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.grobox.transportr.about import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import de.grobox.transportr.R import de.grobox.transportr.TransportrFragment import de.grobox.transportr.about.ContributorAdapter.ContributorViewHolder import de.grobox.transportr.about.ContributorGroupAdapter.ContributorGroupViewHolder class ContributorFragment : TransportrFragment() { override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { val v = inflater.inflate(R.layout.fragment_contributors, container, false) val list = v.findViewById<RecyclerView>(R.id.list) list.layoutManager = LinearLayoutManager(context) list.adapter = ContributorGroupAdapter(CONTRIBUTORS) return v } } class TranslatorsFragment : TransportrFragment() { override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { val v = inflater.inflate(R.layout.fragment_translators, container, false) val list = v.findViewById<RecyclerView>(R.id.list) list.layoutManager = LinearLayoutManager(context) list.adapter = ContributorGroupAdapter(LANGUAGES) return v } } private class ContributorGroupAdapter(val groups: List<ContributorGroup>) : RecyclerView.Adapter<ContributorGroupViewHolder>() { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ContributorGroupViewHolder { val v = LayoutInflater.from(parent.context).inflate(R.layout.list_item_contributor_group, parent, false) return ContributorGroupViewHolder(v) } override fun onBindViewHolder(ui: ContributorGroupViewHolder, position: Int) { ui.bind(groups[position]) } override fun getItemCount(): Int = groups.size private class ContributorGroupViewHolder(v: View) : RecyclerView.ViewHolder(v) { val languageName: TextView = v.findViewById(R.id.languageName) val list: RecyclerView = v.findViewById(R.id.list) internal fun bind(contributorGroup: ContributorGroup) { languageName.setText(contributorGroup.name) list.layoutManager = LinearLayoutManager(list.context) list.adapter = ContributorAdapter(contributorGroup.contributors) } } } private class ContributorAdapter(val contributors: List<Contributor>) : RecyclerView.Adapter<ContributorViewHolder>() { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ContributorViewHolder { val v = LayoutInflater.from(parent.context).inflate(R.layout.list_item_contributor, parent, false) return ContributorViewHolder(v) } override fun onBindViewHolder(ui: ContributorViewHolder, position: Int) { ui.bind(contributors[position]) } override fun getItemCount(): Int = contributors.size private class ContributorViewHolder(v: View) : RecyclerView.ViewHolder(v) { val name: TextView = v.findViewById(R.id.name) internal fun bind(contributor: Contributor) { name.text = contributor.name } } }
gpl-3.0
0dd246da6903f2e7fecd8495018006b4
34.710526
128
0.733235
4.652571
false
false
false
false
soeminnminn/EngMyanDictionary
app/src/main/java/com/s16/utils/Extension.context.kt
1
5180
package com.s16.utils import android.app.Activity import android.app.Service import android.content.ActivityNotFoundException import android.content.Context import android.content.Intent import android.content.pm.ActivityInfo import android.content.res.Configuration import android.graphics.drawable.Drawable import android.net.Uri import android.os.Bundle import android.util.DisplayMetrics import android.view.Surface import android.view.WindowManager import androidx.annotation.ColorRes import androidx.annotation.DrawableRes import androidx.core.content.ContextCompat import androidx.core.os.bundleOf import androidx.fragment.app.Fragment /* * Context */ val Context.screenOrientation: Int get() { val manager = getSystemService(Context.WINDOW_SERVICE) as WindowManager val rotation = manager.defaultDisplay.rotation val orientation = resources.configuration.orientation if (orientation == Configuration.ORIENTATION_PORTRAIT) { return if (rotation == Surface.ROTATION_0 || rotation == Surface.ROTATION_270) { ActivityInfo.SCREEN_ORIENTATION_PORTRAIT } else { ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT } } return if (orientation == Configuration.ORIENTATION_LANDSCAPE) { if (rotation == Surface.ROTATION_0 || rotation == Surface.ROTATION_90) { ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE } else { ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE } } else ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED } val Context.isTablet: Boolean get() { val xlarge = resources.configuration.screenLayout and Configuration.SCREENLAYOUT_SIZE_MASK == 4 val large = resources.configuration.screenLayout and Configuration.SCREENLAYOUT_SIZE_MASK == Configuration.SCREENLAYOUT_SIZE_LARGE return xlarge || large } val Context.isPortrait: Boolean get() { return screenOrientation == ActivityInfo.SCREEN_ORIENTATION_PORTRAIT || screenOrientation == ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT } inline fun <reified T: Any> Context.intentFor(vararg params: Pair<String, Any?>): Intent = Intent(this, T::class.java).also { if (params.isNotEmpty()) { it.putExtras(bundleOf(*params)) } } inline fun <reified T: Any> Fragment.intentFor(vararg params: Pair<String, Any?>): Intent = Intent(this.activity, T::class.java).also { if (params.isNotEmpty()) { it.putExtras(bundleOf(*params)) } } inline fun <reified T: Activity> Context.startActivity(extras: Bundle? = null) { val intent = Intent(this, T::class.java) if (extras != null) { intent.putExtras(extras) } startActivity(intent) } inline fun <reified T: Activity> Context.startActivity(vararg params: Pair<String, Any?>) { val intent = Intent(this, T::class.java) if (params.isNotEmpty()) { intent.putExtras(bundleOf(*params)) } startActivity(intent) } inline fun <reified T: Service> Context.startService(vararg params: Pair<String, Any?>) { val intent = Intent(this, T::class.java) if (params.isNotEmpty()) { intent.putExtras(bundleOf(*params)) } startService(intent) } inline fun <reified T : Service> Context.stopService(vararg params: Pair<String, Any?>) { val intent = Intent(this, T::class.java) if (params.isNotEmpty()) { intent.putExtras(bundleOf(*params)) } stopService(intent) } fun Context.share(text: String, subject: String = "", title: String? = null): Boolean { return try { val intent = Intent(Intent.ACTION_SEND) intent.type = "text/plain" intent.putExtra(Intent.EXTRA_SUBJECT, subject) intent.putExtra(Intent.EXTRA_TEXT, text) startActivity(Intent.createChooser(intent, title)) true } catch (e: ActivityNotFoundException) { e.printStackTrace() false } } fun Context.browse(url: String, newTask: Boolean = false): Boolean { return try { val intent = Intent(Intent.ACTION_VIEW) intent.data = Uri.parse(url) if (newTask) { intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) } startActivity(intent) true } catch (e: ActivityNotFoundException) { e.printStackTrace() false } } fun Context.getColorCompat(@ColorRes resId: Int): Int { return ContextCompat.getColor(this, resId) } fun Context.getDrawableCompat(@DrawableRes resId: Int): Drawable? { return ContextCompat.getDrawable(this, resId) } fun Context.dpToPixel(dp: Int): Int { val metrics = resources.displayMetrics val px = dp * (metrics.densityDpi.toFloat() / DisplayMetrics.DENSITY_DEFAULT) return px.toInt() } fun Context.dpToPixel(dp: Float): Float { val metrics = resources.displayMetrics return dp * (metrics.densityDpi.toFloat() / DisplayMetrics.DENSITY_DEFAULT) } fun Context.pixelToDp(px: Int): Float { val metrics = resources.displayMetrics return px / (metrics.densityDpi.toFloat() / DisplayMetrics.DENSITY_DEFAULT) }
gpl-2.0
3d657b231db599f18ac4774e11251748
31.791139
130
0.683398
4.345638
false
true
false
false
cesarferreira/kotlin-pluralizer
library/src/main/kotlin/com/cesarferreira/pluralize/Pluralize.kt
1
7948
package com.cesarferreira.pluralize import com.cesarferreira.pluralize.utils.Plurality import java.util.regex.Pattern fun String.pluralize(plurality: Plurality = Plurality.Singular): String { if (plurality == Plurality.Plural) return this if (plurality == Plurality.Singular) return this.pluralizer() if (this.singularizer() != this && this.singularizer() + "s" != this && this.singularizer().pluralizer() == this && this.pluralizer() != this) return this return this.pluralizer() } fun String.singularize(plurality: Plurality = Plurality.Plural): String { if (plurality == Plurality.Singular) return this if (plurality == Plurality.Plural) return this.singularizer() if (this.pluralizer() != this && this + "s" != this.pluralizer() && this.pluralizer().singularize() == this && this.singularizer() != this) return this return this.singularize() } fun String.pluralize(count: Int): String { if (count > 1) return this.pluralize(Plurality.Plural) else return this.pluralize(Plurality.Singular) } fun String.singularize(count: Int): String { if (count > 1) return this.singularize(Plurality.Plural) else return this.singularize(Plurality.Singular) } private fun String.pluralizer(): String { if (unCountable().contains(this.toLowerCase())) return this val rule = pluralizeRules().last { Pattern.compile(it.component1(), Pattern.CASE_INSENSITIVE).matcher(this).find() } var found = Pattern.compile(rule.component1(), Pattern.CASE_INSENSITIVE).matcher(this).replaceAll(rule.component2()) val endsWith = exceptions().firstOrNull { this.endsWith(it.component1()) } if (endsWith != null) found = this.replace(endsWith.component1(), endsWith.component2()) val exception = exceptions().firstOrNull() { this.equals(it.component1(), true) } if (exception != null) found = exception.component2() return found } private fun String.singularizer(): String { if (unCountable().contains(this.toLowerCase())) { return this } val exceptions = exceptions().firstOrNull() { this.equals(it.component2(), true) } if (exceptions != null) { return exceptions.component1() } val endsWith = exceptions().firstOrNull { this.endsWith(it.component2()) } if (endsWith != null) return this.replace(endsWith.component2(), endsWith.component1()) try { if (singularizeRules().count { Pattern.compile(it.component1(), Pattern.CASE_INSENSITIVE).matcher(this).find() } == 0) return this val rule = singularizeRules().last { Pattern.compile(it.component1(), Pattern.CASE_INSENSITIVE).matcher(this).find() } return Pattern.compile(rule.component1(), Pattern.CASE_INSENSITIVE).matcher(this).replaceAll(rule.component2()) } catch(ex: IllegalArgumentException) { Exception("Can't singularize this word, could not find a rule to match.") } return this } fun unCountable(): List<String> { return listOf("equipment", "information", "rice", "money", "species", "series", "fish", "sheep", "aircraft", "bison", "flounder", "pliers", "bream", "gallows", "proceedings", "breeches", "graffiti", "rabies", "britches", "headquarters", "salmon", "carp", "herpes", "scissors", "chassis", "high-jinks", "sea-bass", "clippers", "homework", "cod", "innings", "shears", "contretemps", "jackanapes", "corps", "mackerel", "swine", "debris", "measles", "trout", "diabetes", "mews", "tuna", "djinn", "mumps", "whiting", "eland", "news", "wildebeest", "elk", "pincers", "sugar") } fun exceptions(): List<Pair<String, String>> { return listOf("person" to "people", "man" to "men", "goose" to "geese", "child" to "children", "sex" to "sexes", "move" to "moves", "stadium" to "stadiums", "deer" to "deer", "codex" to "codices", "murex" to "murices", "silex" to "silices", "radix" to "radices", "helix" to "helices", "alumna" to "alumnae", "alga" to "algae", "vertebra" to "vertebrae", "persona" to "personae", "stamen" to "stamina", "foramen" to "foramina", "lumen" to "lumina", "afreet" to "afreeti", "afrit" to "afriti", "efreet" to "efreeti", "cherub" to "cherubim", "goy" to "goyim", "human" to "humans", "lumen" to "lumina", "seraph" to "seraphim", "Alabaman" to "Alabamans", "Bahaman" to "Bahamans", "Burman" to "Burmans", "German" to "Germans", "Hiroshiman" to "Hiroshimans", "Liman" to "Limans", "Nakayaman" to "Nakayamans", "Oklahoman" to "Oklahomans", "Panaman" to "Panamans", "Selman" to "Selmans", "Sonaman" to "Sonamans", "Tacoman" to "Tacomans", "Yakiman" to "Yakimans", "Yokohaman" to "Yokohamans", "Yuman" to "Yumans", "criterion" to "criteria", "perihelion" to "perihelia", "aphelion" to "aphelia", "phenomenon" to "phenomena", "prolegomenon" to "prolegomena", "noumenon" to "noumena", "organon" to "organa", "asyndeton" to "asyndeta", "hyperbaton" to "hyperbata", "foot" to "feet") } fun pluralizeRules(): List<Pair<String, String>> { return listOf( "$" to "s", "s$" to "s", "(ax|test)is$" to "$1es", "us$" to "i", "(octop|vir)us$" to "$1i", "(octop|vir)i$" to "$1i", "(alias|status)$" to "$1es", "(bu)s$" to "$1ses", "(buffal|tomat)o$" to "$1oes", "([ti])um$" to "$1a", "([ti])a$" to "$1a", "sis$" to "ses", "(,:([^f])fe|([lr])f)$" to "$1$2ves", "(hive)$" to "$1s", "([^aeiouy]|qu)y$" to "$1ies", "(x|ch|ss|sh)$" to "$1es", "(matr|vert|ind)ix|ex$" to "$1ices", "([m|l])ouse$" to "$1ice", "([m|l])ice$" to "$1ice", "^(ox)$" to "$1en", "(quiz)$" to "$1zes", "f$" to "ves", "fe$" to "ves", "um$" to "a", "on$" to "a", "tion" to "tions", "sion" to "sions") } fun singularizeRules(): List<Pair<String, String>> { return listOf( "s$" to "", "(s|si|u)s$" to "$1s", "(n)ews$" to "$1ews", "([ti])a$" to "$1um", "((a)naly|(b)a|(d)iagno|(p)arenthe|(p)rogno|(s)ynop|(t)he)ses$" to "$1$2sis", "(^analy)ses$" to "$1sis", "(^analy)sis$" to "$1sis", "([^f])ves$" to "$1fe", "(hive)s$" to "$1", "(tive)s$" to "$1", "([lr])ves$" to "$1f", "([^aeiouy]|qu)ies$" to "$1y", "(s)eries$" to "$1eries", "(m)ovies$" to "$1ovie", "(x|ch|ss|sh)es$" to "$1", "([m|l])ice$" to "$1ouse", "(bus)es$" to "$1", "(o)es$" to "$1", "(shoe)s$" to "$1", "(cris|ax|test)is$" to "$1is", "(cris|ax|test)es$" to "$1is", "(octop|vir)i$" to "$1us", "(octop|vir)us$" to "$1us", "(alias|status)es$" to "$1", "(alias|status)$" to "$1", "^(ox)en" to "$1", "(vert|ind)ices$" to "$1ex", "(matr)ices$" to "$1ix", "(quiz)zes$" to "$1", "a$" to "um", "i$" to "us", "ae$" to "a") }
mit
6235d925084cdb77c0e58a72a7b8e857
35.292237
120
0.509311
3.484437
false
false
false
false
JakeWharton/AssistedInject
inflation-inject-processor/src/main/java/app/cash/inject/inflation/processor/internal/javaPoet.kt
1
1561
package app.cash.inject.inflation.processor.internal import com.squareup.javapoet.AnnotationSpec import com.squareup.javapoet.ClassName import com.squareup.javapoet.CodeBlock import com.squareup.javapoet.ParameterizedTypeName import com.squareup.javapoet.TypeName import javax.lang.model.element.AnnotationMirror import javax.lang.model.element.TypeElement import javax.lang.model.type.TypeMirror import kotlin.reflect.KClass fun TypeElement.toClassName(): ClassName = ClassName.get(this) fun TypeMirror.toTypeName(): TypeName = TypeName.get(this) fun KClass<*>.toClassName(): ClassName = ClassName.get(java) fun AnnotationMirror.toAnnotationSpec(): AnnotationSpec = AnnotationSpec.get(this) fun Iterable<CodeBlock>.joinToCode(separator: String = ", ") = CodeBlock.join(this, separator) /** * Like [ClassName.peerClass] except instead of honoring the enclosing class names they are * concatenated with `$` similar to the reflection name. `foo.Bar.Baz` invoking this function with * `Fuzz` will produce `foo.Baz$Fuzz`. */ fun ClassName.peerClassWithReflectionNesting(name: String): ClassName { var prefix = "" var peek = this while (true) { peek = peek.enclosingClassName() ?: break prefix = peek.simpleName() + "$" + prefix } return ClassName.get(packageName(), prefix + name) } // TODO https://github.com/square/javapoet/issues/671 fun TypeName.rawClassName(): ClassName = when (this) { is ClassName -> this is ParameterizedTypeName -> rawType else -> throw IllegalStateException("Cannot extract raw class name from $this") }
apache-2.0
d82237a279738369eab96fba68e723d2
37.073171
98
0.77066
4.207547
false
false
false
false
proxer/ProxerAndroid
src/main/kotlin/me/proxer/app/profile/history/HistoryAdapter.kt
1
3904
package me.proxer.app.profile.history import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.TextView import androidx.core.view.ViewCompat import androidx.recyclerview.widget.RecyclerView import com.jakewharton.rxbinding3.view.clicks import com.jakewharton.rxbinding3.view.longClicks import com.uber.autodispose.autoDisposable import io.reactivex.subjects.PublishSubject import kotterknife.bindView import me.proxer.app.GlideRequests import me.proxer.app.R import me.proxer.app.base.AutoDisposeViewHolder import me.proxer.app.base.BaseAdapter import me.proxer.app.profile.history.HistoryAdapter.ViewHolder import me.proxer.app.util.extension.defaultLoad import me.proxer.app.util.extension.distanceInWordsToNow import me.proxer.app.util.extension.mapBindingAdapterPosition import me.proxer.app.util.extension.toAppString import me.proxer.library.enums.Category import me.proxer.library.util.ProxerUrls /** * @author Ruben Gees */ class HistoryAdapter : BaseAdapter<LocalUserHistoryEntry, ViewHolder>() { var glide: GlideRequests? = null val clickSubject: PublishSubject<Pair<ImageView, LocalUserHistoryEntry>> = PublishSubject.create() val longClickSubject: PublishSubject<Pair<ImageView, LocalUserHistoryEntry>> = PublishSubject.create() init { setHasStableIds(false) } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { return ViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.item_history_entry, parent, false)) } override fun onBindViewHolder(holder: ViewHolder, position: Int) = holder.bind(data[position]) override fun onViewRecycled(holder: ViewHolder) { glide?.clear(holder.image) } override fun onDetachedFromRecyclerView(recyclerView: RecyclerView) { glide = null } inner class ViewHolder(itemView: View) : AutoDisposeViewHolder(itemView) { internal val container: ViewGroup by bindView(R.id.container) internal val title: TextView by bindView(R.id.title) internal val medium: TextView by bindView(R.id.medium) internal val image: ImageView by bindView(R.id.image) internal val status: TextView by bindView(R.id.status) fun bind(item: LocalUserHistoryEntry) { container.clicks() .mapBindingAdapterPosition({ bindingAdapterPosition }) { image to data[it] } .autoDisposable(this) .subscribe(clickSubject) container.longClicks() .mapBindingAdapterPosition({ bindingAdapterPosition }) { image to data[it] } .autoDisposable(this) .subscribe(longClickSubject) ViewCompat.setTransitionName(image, "history_${item.id}") title.text = item.name medium.text = item.medium.toAppString(medium.context) status.text = when (item is LocalUserHistoryEntry.Ucp) { true -> status.context.getString( when (item.category) { Category.ANIME -> R.string.fragment_history_entry_ucp_status_anime Category.MANGA, Category.NOVEL -> R.string.fragment_history_entry_ucp_status_manga }, item.episode, item.date.distanceInWordsToNow(status.context) ) false -> status.context.getString( when (item.category) { Category.ANIME -> R.string.fragment_history_entry_status_anime Category.MANGA, Category.NOVEL -> R.string.fragment_history_entry_status_manga }, item.episode ) } glide?.defaultLoad(image, ProxerUrls.entryImage(item.entryId)) } } }
gpl-3.0
e3318b521523aa8b44fe167dd624ff1e
38.434343
114
0.680072
4.778458
false
false
false
false
proxer/ProxerAndroid
src/main/kotlin/me/proxer/app/settings/SettingsFragment.kt
1
6980
package me.proxer.app.settings import android.content.SharedPreferences import android.content.SharedPreferences.OnSharedPreferenceChangeListener import android.content.pm.PackageManager import android.os.Bundle import android.os.Environment import android.view.View import androidx.appcompat.app.AppCompatActivity import androidx.core.os.bundleOf import com.uber.autodispose.android.lifecycle.scope import com.uber.autodispose.autoDisposable import me.proxer.app.BuildConfig import me.proxer.app.MainActivity import me.proxer.app.R import me.proxer.app.base.BaseActivity import me.proxer.app.chat.prv.sync.MessengerWorker import me.proxer.app.notification.NotificationWorker import me.proxer.app.profile.settings.ProfileSettingsActivity import me.proxer.app.settings.theme.ThemeDialog import me.proxer.app.util.KotterKnifePreference import me.proxer.app.util.bindPreference import me.proxer.app.util.data.PreferenceHelper import me.proxer.app.util.data.PreferenceHelper.Companion.AGE_CONFIRMATION import me.proxer.app.util.data.PreferenceHelper.Companion.EXTERNAL_CACHE import me.proxer.app.util.data.PreferenceHelper.Companion.HTTP_LOG_LEVEL import me.proxer.app.util.data.PreferenceHelper.Companion.HTTP_REDACT_TOKEN import me.proxer.app.util.data.PreferenceHelper.Companion.HTTP_VERBOSE import me.proxer.app.util.data.PreferenceHelper.Companion.NOTIFICATIONS_ACCOUNT import me.proxer.app.util.data.PreferenceHelper.Companion.NOTIFICATIONS_CHAT import me.proxer.app.util.data.PreferenceHelper.Companion.NOTIFICATIONS_INTERVAL import me.proxer.app.util.data.PreferenceHelper.Companion.NOTIFICATIONS_NEWS import me.proxer.app.util.data.PreferenceHelper.Companion.THEME import me.proxer.app.util.data.StorageHelper import me.proxer.app.util.extension.clearTop import me.proxer.app.util.extension.clicks import me.proxer.app.util.extension.safeInject import me.proxer.app.util.extension.snackbar import net.xpece.android.support.preference.ListPreference import net.xpece.android.support.preference.Preference import net.xpece.android.support.preference.PreferenceCategory import net.xpece.android.support.preference.TwoStatePreference import net.xpece.android.support.preference.XpPreferenceFragment import kotlin.system.exitProcess /** * @author Ruben Gees */ class SettingsFragment : XpPreferenceFragment(), OnSharedPreferenceChangeListener { companion object { fun newInstance() = SettingsFragment().apply { arguments = bundleOf() } } private val hostingActivity: BaseActivity get() = activity as MainActivity private val packageManager by safeInject<PackageManager>() private val preferenceHelper by safeInject<PreferenceHelper>() private val storageHelper by safeInject<StorageHelper>() private val profile by bindPreference<Preference>("profile") private val ageConfirmation by bindPreference<TwoStatePreference>(AGE_CONFIRMATION) private val theme by bindPreference<Preference>(THEME) private val externalCache by bindPreference<TwoStatePreference>(EXTERNAL_CACHE) private val notificationsInterval by bindPreference<ListPreference>(NOTIFICATIONS_INTERVAL) private val developerOptions by bindPreference<PreferenceCategory>("developer_options") override fun onCreatePreferences2(savedInstanceState: Bundle?, rootKey: String?) { addPreferencesFromResource(R.xml.preferences) if ( Environment.isExternalStorageEmulated() || Environment.getExternalStorageState() != Environment.MEDIA_MOUNTED ) { externalCache.isVisible = false } if (!BuildConfig.DEBUG && !BuildConfig.LOG) { developerOptions.isVisible = false } } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) storageHelper.isLoggedInObservable .autoDisposable(viewLifecycleOwner.scope()) .subscribe { profile.isEnabled = it } profile.clicks() .autoDisposable(viewLifecycleOwner.scope()) .subscribe { ProfileSettingsActivity.navigateTo(requireActivity()) } ageConfirmation.clicks() .autoDisposable(viewLifecycleOwner.scope()) .subscribe { if (ageConfirmation.isChecked) { ageConfirmation.isChecked = false AgeConfirmationDialog.show(requireActivity() as AppCompatActivity) } } theme.clicks() .autoDisposable(viewLifecycleOwner.scope()) .subscribe { ThemeDialog.show(requireActivity() as AppCompatActivity) } profile.isEnabled = storageHelper.isLoggedIn theme.summary = preferenceHelper.themeContainer.let { (theme, variant) -> "${getString(theme.themeName)} ${if (variant.variantName != null) getString(variant.variantName) else ""}" } updateIntervalNotificationPreference() listView.isFocusable = false } override fun onResume() { super.onResume() preferenceManager.sharedPreferences.registerOnSharedPreferenceChangeListener(this) } override fun onPause() { preferenceManager.sharedPreferences.unregisterOnSharedPreferenceChangeListener(this) super.onPause() } override fun onDestroyView() { KotterKnifePreference.reset(this) super.onDestroyView() } override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences, key: String) { when (key) { AGE_CONFIRMATION -> if (preferenceHelper.isAgeRestrictedMediaAllowed) { ageConfirmation.isChecked = true } NOTIFICATIONS_NEWS, NOTIFICATIONS_ACCOUNT -> { updateIntervalNotificationPreference() NotificationWorker.enqueueIfPossible() } NOTIFICATIONS_CHAT -> MessengerWorker.enqueueSynchronizationIfPossible() NOTIFICATIONS_INTERVAL -> { NotificationWorker.enqueueIfPossible() MessengerWorker.enqueueSynchronizationIfPossible() } EXTERNAL_CACHE, HTTP_LOG_LEVEL, HTTP_VERBOSE, HTTP_REDACT_TOKEN -> showRestartMessage() } } private fun updateIntervalNotificationPreference() { notificationsInterval.isEnabled = preferenceHelper.areNewsNotificationsEnabled || preferenceHelper.areAccountNotificationsEnabled } private fun showRestartMessage() { hostingActivity.snackbar( R.string.fragment_settings_restart_message, actionMessage = R.string.fragment_settings_restart_action, actionCallback = View.OnClickListener { val intent = packageManager.getLaunchIntentForPackage(BuildConfig.APPLICATION_ID)?.clearTop() startActivity(intent) exitProcess(0) } ) } }
gpl-3.0
6791417db6600bd537c23ebf5b11a686
37.351648
118
0.726934
5.24812
false
false
false
false
LorittaBot/Loritta
discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/cinnamon/discord/utils/DiscordResourceLimits.kt
1
824
package net.perfectdreams.loritta.cinnamon.discord.utils object DiscordResourceLimits { object Command { object Description { const val Length = 100 } object Options { object Description { const val Length = 100 } } } object Message { const val Length = 2000 const val EmbedsPerMessage = 10 } object Embed { const val Title = 256 const val Description = 4096 const val FieldsPerEmbed = 25 const val TotalCharacters = 6000 object Field { const val Name = 256 const val Value = 1024 } object Footer { const val Text = 2048 } object Author { const val Name = 256 } } }
agpl-3.0
5a39bd1cb8cc9869dca1bd550456be66
19.625
56
0.518204
5.421053
false
false
false
false
ericberman/MyFlightbookAndroid
app/src/main/java/com/myflightbook/android/ActLocalVideo.kt
1
1823
/* MyFlightbook for Android - provides native access to MyFlightbook pilot's logbook Copyright (C) 2017-2022 MyFlightbook, LLC This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.myflightbook.android import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import model.MFBConstants import android.widget.VideoView import android.net.Uri import android.util.Log import java.io.File class ActLocalVideo : AppCompatActivity() { private var szTempFile: String? = "" public override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.localvideo) val szURL = this.intent.getStringExtra(MFBConstants.intentViewURL) szTempFile = this.intent.getStringExtra(MFBConstants.intentViewTempFile) val video = findViewById<VideoView>(R.id.video) // Load and start the movie video.setVideoURI(Uri.parse(szURL)) video.start() } public override fun onPause() { super.onPause() if (szTempFile != null && szTempFile!!.isNotEmpty()) { if (!File(szTempFile!!).delete()) Log.v(MFBConstants.LOG_TAG, "Local video delete failed") } } }
gpl-3.0
6cbf537490567d1b8b129d140993c54b
37
102
0.72079
4.546135
false
false
false
false
elmozgo/PortalMirror
portalmirror-twitterfeed-core/src/main/kotlin/org/portalmirror/twitterfeed/core/domain/TwitterFeedEntry.kt
1
2506
package org.portalmirror.twitterfeed.core.domain import org.joda.time.DateTime import org.portalmirror.twitterfeed.core.logic.TwitterRepository import twitter4j.Status class TwitterFeedEntry { val screenName : String val status : Status var replies : List<TwitterFeedEntry> private val repository: TwitterRepository val depth : Int val createdAt : DateTime private val repliesMaxDepth: Int /*** * Constructor to create root entries */ constructor(screenName : String, status : Status, repository: TwitterRepository, repliesMaxDepth: Int) { this.screenName = screenName this.status = status this.repository = repository this.depth = 0 this.repliesMaxDepth = repliesMaxDepth if(this.repliesMaxDepth > 0 ) { this.replies = getReplies(repository, status) } else { this.replies = emptyList() } this.createdAt = DateTime.now() } constructor(status : Status, repository: TwitterRepository, parent : TwitterFeedEntry) { this.screenName = status.user.screenName this.status = status this.repository = repository this.depth = parent.depth + 1 this.repliesMaxDepth = parent.repliesMaxDepth if(this.repliesMaxDepth > this.depth) { this.replies = getReplies(repository, status) } else { this.replies = emptyList() } this.createdAt = DateTime.now() } private fun getReplies(repository: TwitterRepository, status: Status) = repository.getAllRepliesToStatus(this.status).map { s -> TwitterFeedEntry(s, repository, this) } fun isEagerLoaded() : Boolean { return this.depth <= this.repliesMaxDepth } fun refreshReplies() : Unit { this.replies = getReplies(this.repository, this.status) } fun isReplyTo() : Boolean { return status.inReplyToStatusId > 0 } fun isRetweeted() : Boolean { return status.retweetedStatus != null } fun hasQuotedStatus() : Boolean { return status.quotedStatus != null } fun hasVideo() : Boolean { return hasMediaEntityOfType("video") } fun hasGif() : Boolean { return hasMediaEntityOfType("animated_gif") } fun hasPhoto() : Boolean { return hasMediaEntityOfType("photo") } private fun hasMediaEntityOfType(type : String) = status.mediaEntities.find { me -> me.type.equals(type) } != null }
gpl-3.0
d1074a435c62f19d2d55eb1c15a9c5eb
26.538462
172
0.649242
4.675373
false
false
false
false
vanniktech/Emoji
emoji/src/androidMain/kotlin/com/vanniktech/emoji/traits/SearchInPlaceTrait.kt
1
2724
/* * Copyright (C) 2016 - Niklas Baudy, Ruben Gees, Mario Đanić 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 * * 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.vanniktech.emoji.traits import android.os.Handler import android.os.Looper import android.text.Editable import android.text.TextWatcher import android.widget.EditText import com.vanniktech.emoji.EmojiPopup import com.vanniktech.emoji.internal.EmojiSearchPopup import com.vanniktech.emoji.search.NoSearchEmoji /** * Popup similar to how Telegram and Slack does it to search for an Emoji */ class SearchInPlaceTrait( private val emojiPopup: EmojiPopup, ) : EmojiTraitable { override fun install(editText: EditText): EmojiTrait { if (emojiPopup.searchEmoji is NoSearchEmoji) { return EmptyEmojiTrait } val popup = EmojiSearchPopup(emojiPopup.rootView, editText, emojiPopup.theming) val handler = Handler(Looper.getMainLooper()) val watcher = object : TextWatcher { override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) = Unit override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) = Unit override fun afterTextChanged(s: Editable) { handler.removeCallbacksAndMessages(null) // Cheap debounce without RxJava. handler.postDelayed({ val lastColon = s.indexOfLast { it == ':' } if (lastColon >= 0) { val query = s.drop(lastColon + 1).toString() val isProperQuery = query.all { it.isLetterOrDigit() || it == '_' } if (isProperQuery) { popup.show( emojis = emojiPopup.searchEmoji.search(query), delegate = { val new = "${it.unicode} " editText.text.replace(lastColon, s.length, new, 0, new.length) }, ) } else { popup.dismiss() } } else { popup.dismiss() } }, 300L,) } } editText.addTextChangedListener(watcher) return object : EmojiTrait { override fun uninstall() { popup.dismiss() editText.removeTextChangedListener(watcher) } } } }
apache-2.0
8f396f90bc09c302f8b1a7733880c9f1
32.195122
97
0.652094
4.462295
false
false
false
false
jean79/yested_fw
src/jsMain/kotlin/net/yested/ext/jquery/YestedJQuery.kt
1
1429
package net.yested.ext.jquery import globals.JQuery import globals.JQueryStatic import globals.jQuery import org.w3c.dom.HTMLElement import org.w3c.dom.Window /** * JQuery functions that are are available via Yested to applications. * If you need additional functions, create similar code with a different Kotlin name. * Your new code can extend YestedJQuery, which will enable chaining into these functions. */ @Deprecated("use globals.jQuery", replaceWith = ReplaceWith("jQuery", "globals.jQuery")) val yestedJQuery: JQuery = jQuery.unsafeCast<JQuery>() @Deprecated("use jQuery(element)", replaceWith = ReplaceWith("jQuery(element)", "globals.jQuery")) fun yestedJQuery(element: HTMLElement): JQuery = jQuery(element) @Deprecated("use jQuery(window)", replaceWith = ReplaceWith("jQuery(window)", "globals.jQuery")) fun yestedJQuery(window: Window): JQuery = jQuery(window) @Deprecated("use JQuery") typealias YestedJQuery = JQuery fun JQuery.datetimepicker(param: Any?) { this.asDynamic().datetimepicker(param) } fun JQuery.modal(command: String) { this.asDynamic().modal(command) } fun <T> JQueryStatic.get(url:String, loaded:(response: T) -> Unit) { this.asDynamic().get(url, loaded) } fun <RESULT> JQueryStatic.ajax(request: AjaxRequest<RESULT>) { this.asDynamic().ajax(request) } @Deprecated("use JQuery", replaceWith = ReplaceWith("JQuery", "globals.JQuery")) typealias JQueryWindow = JQuery
mit
379e7ce6a2356f4798b3b56336978477
32.232558
98
0.755773
3.904372
false
false
false
false
Magneticraft-Team/Magneticraft
src/main/kotlin/com/cout970/magneticraft/systems/tilemodules/ModuleHeatProcessing.kt
2
2776
package com.cout970.magneticraft.systems.tilemodules import com.cout970.magneticraft.api.heat.IHeatNode import com.cout970.magneticraft.misc.add import com.cout970.magneticraft.misc.crafting.IHeatCraftingProcess import com.cout970.magneticraft.misc.crafting.TimedCraftingProcess import com.cout970.magneticraft.misc.gui.ValueAverage import com.cout970.magneticraft.misc.network.FloatSyncVariable import com.cout970.magneticraft.misc.network.SyncVariable import com.cout970.magneticraft.misc.newNbt import com.cout970.magneticraft.misc.world.isClient import com.cout970.magneticraft.systems.gui.DATA_ID_BURNING_TIME import com.cout970.magneticraft.systems.gui.DATA_ID_MACHINE_CONSUMPTION import com.cout970.magneticraft.systems.tileentities.IModule import com.cout970.magneticraft.systems.tileentities.IModuleContainer import net.minecraft.nbt.NBTTagCompound /** * Created by cout970 on 2017/07/01. */ class ModuleHeatProcessing( val craftingProcess: IHeatCraftingProcess, val node: IHeatNode, val workingRate: Float, val costPerTick: Float, override val name: String = "module_electric_processing" ) : IModule { override lateinit var container: IModuleContainer val timedProcess = TimedCraftingProcess(craftingProcess, this::onWorkingTick) val consumption = ValueAverage() var working = false override fun update() { if (world.isClient) return val rate = (workingRate * getSpeed()).toDouble() //making sure that (speed * costPerTick) is an integer val speed = Math.floor((rate * costPerTick)).toFloat() / costPerTick if (speed > 0) { timedProcess.tick(world, speed) } val isWorking = timedProcess.isWorking(world) if (isWorking != working) { working = isWorking container.sendUpdateToNearPlayers() } consumption.tick() } fun getSpeed(): Float { val headDiff = node.temperature - craftingProcess.minTemperature() return headDiff.toFloat().coerceIn(0.0f, 1.0f) } fun onWorkingTick(speed: Float) { consumption += speed * costPerTick node.applyHeat(-speed * costPerTick.toDouble()) } override fun deserializeNBT(nbt: NBTTagCompound) { timedProcess.deserializeNBT(nbt.getCompoundTag("timedProcess")) working = nbt.getBoolean("working") } override fun serializeNBT(): NBTTagCompound = newNbt { add("timedProcess", timedProcess.serializeNBT()) add("working", working) } override fun getGuiSyncVariables(): List<SyncVariable> = listOf( FloatSyncVariable(DATA_ID_BURNING_TIME, { timedProcess.timer }, { timedProcess.timer = it }), consumption.toSyncVariable(DATA_ID_MACHINE_CONSUMPTION) ) }
gpl-2.0
d9ed43dd406cdef13267e069e39dad8c
34.602564
101
0.722262
4.371654
false
false
false
false
Magneticraft-Team/Magneticraft
src/main/kotlin/com/cout970/magneticraft/features/items/ToolItems.kt
2
8686
package com.cout970.magneticraft.features.items import com.cout970.magneticraft.api.energy.IElectricNode import com.cout970.magneticraft.api.energy.IManualConnectionHandler.Result.* import com.cout970.magneticraft.api.heat.IHeatNode import com.cout970.magneticraft.misc.* import com.cout970.magneticraft.misc.gui.formatHeat import com.cout970.magneticraft.misc.inventory.isNotEmpty import com.cout970.magneticraft.misc.player.sendMessage import com.cout970.magneticraft.misc.player.sendUnlocalizedMessage import com.cout970.magneticraft.misc.world.isClient import com.cout970.magneticraft.misc.world.isServer import com.cout970.magneticraft.registry.* import com.cout970.magneticraft.systems.blocks.IRotable import com.cout970.magneticraft.systems.items.* import net.minecraft.block.properties.IProperty import net.minecraft.entity.player.EntityPlayer import net.minecraft.item.Item import net.minecraft.item.ItemStack import net.minecraft.util.* import net.minecraft.util.math.BlockPos import net.minecraft.util.text.TextFormatting import net.minecraft.world.World /** * Created by cout970 on 2017/06/12. */ object ToolItems : IItemMaker { lateinit var stoneHammer: ItemBase private set lateinit var ironHammer: ItemBase private set lateinit var steelHammer: ItemBase private set lateinit var copperCoil: ItemBase private set lateinit var voltmeter: ItemBase private set lateinit var thermometer: ItemBase private set lateinit var wrench: ItemBase private set override fun initItems(): List<Item> { val builder = ItemBuilder().apply { creativeTab = CreativeTabMg isFull3d = true maxStackSize = 1 } stoneHammer = builder.withName("stone_hammer").copy { onHitEntity = createHitEntity(2.0f) maxDamage = 130 }.build() ironHammer = builder.withName("iron_hammer").copy { onHitEntity = createHitEntity(3.5f) maxDamage = 250 }.build() steelHammer = builder.withName("steel_hammer").copy { onHitEntity = createHitEntity(5.0f) maxDamage = 750 }.build() copperCoil = builder.withName("copper_coil").copy { constructor = ToolItems::CopperCoil isFull3d = false maxStackSize = 16 }.build() voltmeter = builder.withName("voltmeter").copy { onItemUse = ToolItems::onUseVoltmeter }.build() thermometer = builder.withName("thermometer").copy { onItemUse = ToolItems::onUseThermometer }.build() wrench = builder.withName("wrench").copy { onItemUse = ToolItems::onUseWrench }.build() return listOf(stoneHammer, ironHammer, steelHammer, copperCoil, voltmeter, thermometer, wrench) } fun onUseVoltmeter(args: OnItemUseArgs): EnumActionResult { if (args.worldIn.isServer) { val tile = args.worldIn.getTileEntity(args.pos) ?: return EnumActionResult.PASS val handler = tile.getOrNull(ELECTRIC_NODE_HANDLER, args.facing) ?: return EnumActionResult.PASS val msg = handler.nodes .filterIsInstance<IElectricNode>() .joinToString("\n") { "%.2fV %.2fA %.2fW".format(it.voltage, it.amperage, it.voltage * it.amperage) } args.player.sendUnlocalizedMessage(msg) } return EnumActionResult.PASS } fun onUseThermometer(args: OnItemUseArgs): EnumActionResult { if (args.worldIn.isServer) { val tile = args.worldIn.getTileEntity(args.pos) ?: return EnumActionResult.PASS val handler = tile.getOrNull(HEAT_NODE_HANDLER, args.facing) ?: return EnumActionResult.PASS val msg = handler.nodes .filterIsInstance<IHeatNode>() .joinToString("\n") { formatHeat(it.temperature) } args.player.sendUnlocalizedMessage(msg) } return EnumActionResult.PASS } fun onUseWrench(args: OnItemUseArgs): EnumActionResult { if (args.worldIn.isClient) return EnumActionResult.PASS val state = args.worldIn.getBlockState(args.pos) val entry = state.properties.entries.find { it.value is IRotable } ?: return EnumActionResult.PASS @Suppress("UNCHECKED_CAST") val prop = entry.key as IProperty<IRotable<Any>> val facing = state.getValue(prop) val newState = state.withProperty(prop, facing.next()) if (state != newState) { args.worldIn.setBlockState(args.pos, newState) } return EnumActionResult.PASS } private fun createHitEntity(damage: Float): (HitEntityArgs) -> Boolean { return { it.stack.damageItem(2, it.attacker) it.target.attackEntityFrom(DamageSource.GENERIC, damage) } } class CopperCoil : ItemBase() { companion object { const val POSITION_KEY = "Position" } override fun getItemStackDisplayName(stack: ItemStack): String { val name = super.getItemStackDisplayName(stack) if (stack.hasKey(POSITION_KEY)) { val basePos = stack.getBlockPos(POSITION_KEY) return name + " [${TextFormatting.AQUA}${basePos.x}, ${basePos.y}, ${basePos.z}${TextFormatting.WHITE}]" } return name } override fun onItemRightClick(worldIn: World, playerIn: EntityPlayer, handIn: EnumHand): ActionResult<ItemStack> { if (playerIn.isSneaking && playerIn.getHeldItem(handIn).isNotEmpty) { val item = playerIn.getHeldItem(handIn) item.checkNBT() item.tagCompound?.removeTag(POSITION_KEY) return ActionResult(EnumActionResult.SUCCESS, item) } return super.onItemRightClick(worldIn, playerIn, handIn) } override fun onItemUse(player: EntityPlayer, worldIn: World, pos: BlockPos, hand: EnumHand, facing: EnumFacing, hitX: Float, hitY: Float, hitZ: Float): EnumActionResult { val stack = player.getHeldItem(hand) if (stack.isEmpty) return EnumActionResult.PASS val block = worldIn.getBlockState(pos) val handler = MANUAL_CONNECTION_HANDLER!!.fromBlock(block.block) if (handler != null) { if (player.isSneaking) { val basePos = handler.getBasePos(pos, worldIn, player, facing, stack) if (basePos != null) { stack.setBlockPos(POSITION_KEY, basePos) player.sendMessage("text.magneticraft.wire_connect.updated_position", "[${TextFormatting.AQUA}" + "${basePos.x}, ${basePos.y}, ${basePos.z}${TextFormatting.WHITE}]") return EnumActionResult.SUCCESS } } else { if (stack.hasKey(POSITION_KEY)) { val basePos = stack.getBlockPos(POSITION_KEY) val result = handler.connectWire(basePos, pos, worldIn, player, facing, stack) if (worldIn.isServer) { when (result) { SUCCESS -> player.sendMessage("text.magneticraft.wire_connect.success") TOO_FAR -> player.sendMessage("text.magneticraft.wire_connect.too_far") NOT_A_CONNECTOR -> player.sendMessage("text.magneticraft.wire_connect.not_a_connector") INVALID_CONNECTOR -> player.sendMessage("text.magneticraft.wire_connect.invalid_connector") SAME_CONNECTOR -> player.sendMessage("text.magneticraft.wire_connect.same_connector") ALREADY_CONNECTED -> player.sendMessage("text.magneticraft.wire_connect.already_connected") ERROR, null -> player.sendMessage("text.magneticraft.wire_connect.fail") } } return EnumActionResult.SUCCESS } else { if (worldIn.isServer) { player.sendMessage("text.magneticraft.wire_connect.no_other_connector") } } } } return EnumActionResult.PASS } } }
gpl-2.0
8a4c2728fba4524bf00c74cfc30cccf8
40.366667
123
0.602809
4.868834
false
false
false
false
Shynixn/PetBlocks
petblocks-core/src/main/kotlin/com/github/shynixn/petblocks/core/logic/persistence/entity/AIFollowOwnerEntity.kt
1
2092
package com.github.shynixn.petblocks.core.logic.persistence.entity import com.github.shynixn.petblocks.api.business.annotation.YamlSerialize import com.github.shynixn.petblocks.api.persistence.entity.AIFollowOwner /** * Created by Shynixn 2018. * <p> * Version 1.2 * <p> * MIT License * <p> * Copyright (c) 2018 by Shynixn * <p> * 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: * <p> * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * <p> * 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. */ class AIFollowOwnerEntity : AIBaseEntity(), AIFollowOwner { /** * Name of the type. */ override var type: String = "follow-owner" /** * Distance to the owner which the pet tries to stay away. */ @YamlSerialize(value = "min-distance", orderNumber = 1) override var distanceToOwner: Double = 3.0 /** * The max range a pet can be away from a player until it teleports back. */ @YamlSerialize(value = "max-distance", orderNumber = 2) override var maxRange: Double = 50.0 /** * Speed of the pathfinder. */ @YamlSerialize(value = "speed", orderNumber = 3) override var speed: Double = 3.0 }
apache-2.0
532797d9be92ef88745eddefc16aa42b
37.759259
81
0.715583
4.159046
false
false
false
false
AlmasB/FXGLGames
GeoJumper/src/main/kotlin/com/almasb/fxglgames/geojumper/GeoJumperApp.kt
1
7131
package com.almasb.fxglgames.geojumper import com.almasb.fxgl.app.GameApplication import com.almasb.fxgl.app.GameSettings import com.almasb.fxgl.core.math.FXGLMath import com.almasb.fxgl.dsl.* import com.almasb.fxgl.entity.Entity import com.almasb.fxgl.entity.EntityFactory import com.almasb.fxgl.entity.SpawnData import com.almasb.fxgl.entity.Spawns import com.almasb.fxgl.entity.component.Component import com.almasb.fxgl.entity.components.CollidableComponent import com.almasb.fxgl.input.UserAction import com.almasb.fxgl.physics.BoundingShape import com.almasb.fxgl.physics.CollisionHandler import com.almasb.fxgl.physics.HitBox import com.almasb.fxgl.physics.PhysicsComponent import com.almasb.fxgl.physics.box2d.dynamics.BodyType import javafx.geometry.Point2D import javafx.scene.input.KeyCode import javafx.scene.input.MouseButton import javafx.scene.paint.Color import javafx.scene.shape.Rectangle import java.util.* /** * * * @author Almas Baimagambetov ([email protected]) */ class GeoJumperApp : GameApplication() { private val LEVEL_HEIGHT = 2600.0 private lateinit var playerComponent: PlayerComponent override fun initSettings(settings: GameSettings) { with(settings) { width = 600 height = 800 title = "Geo Jumper" version = "0.1" } } override fun initInput() { onBtnDown(MouseButton.PRIMARY, "Jump") { playerComponent.jump() } getInput().addAction(object : UserAction("Rewind") { override fun onAction() { playerComponent.rewind() } override fun onActionEnd() { playerComponent.endRewind() } }, KeyCode.R) } override fun initGame() { getGameWorld().addEntityFactory(Factory()) //gameWorld.addEntity(Entities.makeScreenBounds(40.0)) // ground entityBuilder() .at(0.0, LEVEL_HEIGHT) .bbox(HitBox(BoundingShape.box(getAppWidth()*1.0, 40.0))) .with(PhysicsComponent()) .buildAndAttach() initPlayer() initPlatforms() } override fun initPhysics() { getPhysicsWorld().setGravity(0.0, 1200.0) getPhysicsWorld().addCollisionHandler(object : CollisionHandler(EntityType.PLAYER, EntityType.PLATFORM) { override fun onCollisionBegin(player: Entity, platform: Entity) { // only if player actually lands on the platform if (player.bottomY <= platform.y) { platform.getComponent(PlatformComponent::class.java).stop() playerComponent.startNewCapture() } } override fun onCollisionEnd(player: Entity, platform: Entity) { // only if player is jumping off that platform if (player.bottomY <= platform.y) { playerComponent.removedPlatformAt(platform.position) platform.removeFromWorld() } } }) } private fun initPlayer() { val physics = PhysicsComponent() physics.setBodyType(BodyType.DYNAMIC) physics.addGroundSensor(HitBox(Point2D(10.0, 60.0), BoundingShape.box(10.0, 5.0))) playerComponent = PlayerComponent() val player = entityBuilder() .type(EntityType.PLAYER) .at(getAppWidth() / 2.0, LEVEL_HEIGHT - 60.0) .viewWithBBox(Rectangle(30.0, 60.0, Color.BLUE)) .with(physics, CollidableComponent(true)) .with(playerComponent) .buildAndAttach() getGameScene().viewport.setBounds(0, 0, getAppWidth(), LEVEL_HEIGHT.toInt()) getGameScene().viewport.bindToEntity(player, 0.0, getAppHeight() / 2.0) } private fun initPlatforms() { for (y in 0..LEVEL_HEIGHT.toInt() step 200) { entityBuilder() .at(0.0, y * 1.0) .view(getUIFactoryService().newText("$y", Color.BLACK, 16.0)) .buildAndAttach() spawn("platform", 20.0, y * 1.0) } } } class PlayerComponent : Component() { private lateinit var physics: PhysicsComponent private val playerPoints = ArrayDeque<Point2D>() private val platformPoints = arrayListOf<Point2D>() private var isRewinding = false private var t = 0.0 override fun onUpdate(tpf: Double) { physics.velocityX = 0.0 t += tpf if (t >= 0.05 && !isRewinding) { playerPoints.addLast(entity.position) t = 0.0 } } fun startNewCapture() { //if (isOnPlatform()) { playerPoints.clear() platformPoints.clear() //} } fun removedPlatformAt(point: Point2D) { platformPoints.add(point) } fun rewind() { if (playerPoints.isEmpty()) { isRewinding = false entity.getComponent(CollidableComponent::class.java).value = true t = 0.0 return } isRewinding = true entity.getComponent(CollidableComponent::class.java).value = false val point = playerPoints.removeLast() entity.getComponent(PhysicsComponent::class.java).overwritePosition(point) if (platformPoints.isNotEmpty()) { platformPoints.forEach { spawn("platform", it).getComponent(PlatformComponent::class.java).stop() } platformPoints.clear() } } fun endRewind() { isRewinding = false entity.getComponent(CollidableComponent::class.java).value = true t = 0.0 } fun isOnPlatform(): Boolean = physics.isOnGround || FXGLMath.abs(physics.velocityY) < 2 fun jump() { if (isOnPlatform()) { physics.velocityY = -800.0 } } } class PlatformComponent : Component() { private val speed = FXGLMath.random(100.0, 400.0) private lateinit var physics: PhysicsComponent override fun onAdded() { physics.setOnPhysicsInitialized { physics.velocityX = speed } } override fun onUpdate(tpf: Double) { if (entity.rightX >= FXGL.getAppWidth()) { physics.velocityX = -speed } if (entity.x <= 0) { physics.velocityX = speed } } fun stop() { pause() physics.velocityX = 0.0 } } class Factory : EntityFactory { @Spawns("platform") fun newPlatform(data: SpawnData): Entity { val physics = PhysicsComponent() physics.setBodyType(BodyType.KINEMATIC) return entityBuilder(data) .type(EntityType.PLATFORM) .viewWithBBox(Rectangle(100.0, 40.0)) .with(physics, CollidableComponent(true)) .with(PlatformComponent()) .build() } } enum class EntityType { PLAYER, PLATFORM } fun main(args: Array<String>) { GameApplication.launch(GeoJumperApp::class.java, args) }
mit
c9fb0b8713faa0750d438d6c741c22e9
26.750973
113
0.601038
4.459662
false
false
false
false
chat-sdk/chat-sdk-android
chat-sdk-core-ui/src/main/java/sdk/chat/ui/recycler/ViewHolders.kt
1
5286
package sdk.chat.ui.recycler import android.app.Activity import android.view.View import android.view.ViewGroup import android.widget.CompoundButton import kotlinx.android.synthetic.main.recycler_view_holder_navigation.view.* import kotlinx.android.synthetic.main.recycler_view_holder_radio.view.* import kotlinx.android.synthetic.main.recycler_view_holder_section.view.* import kotlinx.android.synthetic.main.recycler_view_holder_section.view.textView import kotlinx.android.synthetic.main.recycler_view_holder_toggle.view.* import sdk.chat.ui.R import sdk.chat.ui.icons.Icons import smartadapter.viewholder.SmartViewHolder import java.util.* open class SmartViewModel() { } open class SectionViewModel(val title: String, val paddingTop: Int? = null): SmartViewModel() { var hideTopBorder = false var hideBottomBorder = false open fun hideBorders(top: Boolean? = false, bottom: Boolean? = false): SectionViewModel { if (top != null) { hideTopBorder = top } if (bottom != null) { hideBottomBorder = bottom } return this } } interface RadioRunnable { fun run(value: String) } class RadioViewModel(val group: String, val title: String, val value: String, var starting: StartingValue, val onClick: RadioRunnable): SmartViewModel() { var checked: Boolean = starting.get() fun click() { onClick.run(value) } } class NavigationViewModel(val title: String, val onClick: Runnable): SmartViewModel() { var clicked = false fun click() { if (!clicked) { clicked = true onClick.run() } } } class DividerViewModel(): SmartViewModel() interface ButtonRunnable { fun run(value: Activity) } class ButtonViewModel(val title: String, val color: Int, val onClick: ButtonRunnable): SmartViewModel() { fun click(activity: Activity) { onClick.run(activity) } } interface ToggleRunnable { fun run(value: Boolean) } interface StartingValue { fun get(): Boolean } class ToggleViewModel(val title: String, var enabled: StartingValue, val onChange: ToggleRunnable): SmartViewModel() { fun change(value: Boolean) { onChange.run(value) } } open class RadioViewHolder(parentView: ViewGroup) : SmartViewHolder<RadioViewModel>(parentView, R.layout.recycler_view_holder_radio) { override fun bind(item: RadioViewModel) { with(itemView) { textView.text = item.title radioButton.isChecked = item.starting.get() } } } open class SectionViewHolder(parentView: ViewGroup) : SmartViewHolder<SectionViewModel>(parentView, R.layout.recycler_view_holder_section) { override fun bind(item: SectionViewModel) { with(itemView) { if (item.paddingTop != null) { itemView.setPadding(itemView.paddingLeft, item.paddingTop, itemView.paddingRight, itemView.paddingBottom) itemView.requestLayout(); } textView.text = item.title.toUpperCase(Locale.ROOT) if (item.hideTopBorder) { topBorder.visibility = View.INVISIBLE } else { topBorder.visibility = View.VISIBLE } if (item.hideBottomBorder) { bottomBorder.visibility = View.INVISIBLE } else { bottomBorder.visibility = View.VISIBLE } } } } open class NavigationViewHolder(parentView: ViewGroup) : SmartViewHolder<NavigationViewModel>(parentView, R.layout.recycler_view_holder_navigation) { init { with(itemView) { imageView.setImageDrawable(Icons.get(Icons.choose().arrowRight, R.color.gray_very_light)) } } // init(par) { // imageView // } override fun bind(item: NavigationViewModel) { with(itemView) { textView.text = item.title } } } open class ButtonViewHolder(parentView: ViewGroup) : SmartViewHolder<ButtonViewModel>(parentView, R.layout.recycler_view_holder_button) { override fun bind(item: ButtonViewModel) { with(itemView) { textView.text = item.title textView.setTextColor(item.color) } } } open class DividerViewHolder(parentView: ViewGroup) : SmartViewHolder<DividerViewModel>(parentView, R.layout.recycler_view_holder_divider) { override fun bind(item: DividerViewModel) {} } open class ToggleViewHolder(parentView: ViewGroup) : SmartViewHolder<ToggleViewModel>(parentView, R.layout.recycler_view_holder_toggle) { protected var model: ToggleViewModel? = null // protected var checked = false init { with(itemView) { itemView.isEnabled = false switchMaterial.setOnCheckedChangeListener(CompoundButton.OnCheckedChangeListener { _, isChecked -> // Run after animation model?.change(isChecked) // if (isChecked != checked) { // } }) } } override fun bind(item: ToggleViewModel) { with(itemView) { model = item textView.text = item.title switchMaterial.isChecked = item.enabled.get() } } }
apache-2.0
6419193b80f7bdf101900b9f2e490773
26.973545
154
0.649451
4.408674
false
false
false
false
epabst/kotlin-showcase
src/commonMain/kotlin/util/undo/UndoProvider.kt
1
1128
package util.undo import util.Entity interface UndoProvider { suspend fun <T : Entity<T>, F> undoableSave(original: T?, replacementWithID: T, function: suspend () -> F): F { val isUpdate = original?.id != null val pastTenseDescription = if (isUpdate) "Updated $original" else "Added $replacementWithID" val undoPastTenseDescription = if (isUpdate) "Reverted $original" else "Deleted $replacementWithID" return undoable(pastTenseDescription, undoPastTenseDescription, function) } suspend fun <T> undoable(pastTenseDescription: String, undoPastTenseDescription: String, function: suspend () -> T): T suspend fun <T> notUndoable(function: suspend () -> T): T companion object { val empty: UndoProvider = object : UndoProvider { override suspend fun <T> undoable(pastTenseDescription: String, undoPastTenseDescription: String, function: suspend () -> T): T { return function() } override suspend fun <T> notUndoable(function: suspend () -> T): T { return function() } } } }
apache-2.0
6cb3b3396a8481a748633edd5d98b0b3
37.931034
141
0.648936
4.604082
false
false
false
false
appfoundry/fastlane-android-example
sample/app/src/main/kotlin/be/vergauwen/simon/androidretaindata/core/rx/RxTransformers.kt
1
1353
package be.vergauwen.simon.androidretaindata.core.rx import rx.* import rx.android.schedulers.AndroidSchedulers import rx.schedulers.Schedulers class RxTransformers : Transformers { override fun <T> applyComputationSchedulers(): Observable.Transformer<T, T> = Observable.Transformer<T, T> { it.subscribeOn(Schedulers.computation()).observeOn(AndroidSchedulers.mainThread()) } override fun <T> applyIOSchedulers(): Observable.Transformer<T, T> = Observable.Transformer<T, T> { it.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()) } override fun <T> applyIOSingleSchedulers(): Single.Transformer<T, T> = Single.Transformer<T, T> { it.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()) } override fun <T> applyComputationSingleSchedulers(): Single.Transformer<T, T> = Single.Transformer<T, T> { it.subscribeOn(Schedulers.computation()).observeOn(AndroidSchedulers.mainThread()) } override fun applyIOCompletableSchedulers(): Completable.CompletableTransformer = Completable.CompletableTransformer { it.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()) } override fun applyComputationCompletableSchedulers(): Completable.CompletableTransformer = Completable.CompletableTransformer { it.subscribeOn(Schedulers.computation()).observeOn(AndroidSchedulers.mainThread()) } }
mit
4fbf9e13a22778f981c75ad23aad9934
95.714286
216
0.798965
4.730769
false
false
false
false
Kiskae/Twitch-Archiver
hls-parser/src/main/kotlin/net/serverpeon/twitcharchiver/hls/OfficialTags.kt
1
24881
package net.serverpeon.twitcharchiver.hls import com.google.common.collect.ImmutableList import java.math.BigInteger import java.net.URI import java.time.Duration import java.time.ZonedDateTime import java.util.concurrent.TimeUnit /** * [http://tools.ietf.org/html/draft-pantos-http-live-streaming-08] */ object OfficialTags { /** * An Extended M3U file is distinguished from a basic M3U file by its * first line, which MUST be the tag #EXTM3U. */ val EXTM3U: HlsTag<Nothing> = HlsTag( "EXTM3U", appliesTo = HlsTag.AppliesTo.ENTIRE_PLAYLIST, hasAttributes = false, required = true, unique = true ) /** * The EXTINF tag specifies the duration of a media segment. It applies * only to the media URI that follows it. Each media segment URI MUST * be preceded by an EXTINF tag. Its format is: * * #EXTINF:<duration>,<title> * * "duration" is an integer or floating-point number in decimal * positional notation that specifies the duration of the media segment * in seconds. Durations that are reported as integers SHOULD be * rounded to the nearest integer. Durations MUST be integers if the * protocol version of the Playlist file is less than 3. The remainder * of the line following the comma is an optional human-readable * informative title of the media segment. */ val EXTINF: HlsTag<SegmentInformation> = HlsTag( "EXTINF", appliesTo = HlsTag.AppliesTo.NEXT_SEGMENT, required = true, unique = true ) { rawData -> val data = rawData.split(',', limit = 2) SegmentInformation(data[0].toDuration(), if (data.size == 2) data[1] else "") } /** * The EXT-X-BYTERANGE tag indicates that a media segment is a sub-range * of the resource identified by its media URI. It applies only to the * next media URI that follows it in the Playlist. Its format is: * * #EXT-X-BYTERANGE:<n>[@o] * * where n is a decimal-integer indicating the length of the sub-range * in bytes. If present, o is a decimal-integer indicating the start of * the sub-range, as a byte offset from the beginning of the resource. * If o is not present, the sub-range begins at the next byte following * the sub-range of the previous media segment. * * If o is not present, a previous media segment MUST appear in the * Playlist file and MUST be a sub-range of the same media resource. * * A media URI with no EXT-X-BYTERANGE tag applied to it specifies a * media segment that consists of the entire resource. * * The EXT-X-BYTERANGE tag appeared in version 4 of the protocol. */ val EXT_X_BYTERANGE: HlsTag<SourceSubrange> = HlsTag( "EXT-X-BYTERANGE", appliesTo = HlsTag.AppliesTo.NEXT_SEGMENT, unique = true ) { rawData -> val data = rawData.split('@', limit = 2) SourceSubrange(data[0].toLong(), if (data.size == 2) data[1].toLong() else 0) } /** * The EXT-X-TARGETDURATION tag specifies the maximum media segment * duration. The EXTINF duration of each media segment in the Playlist * file MUST be less than or equal to the target duration. This tag * MUST appear once in the Playlist file. It applies to the entire * Playlist file. Its format is: * * #EXT-X-TARGETDURATION:<s> * * where s is an integer indicating the target duration in seconds. */ val EXT_X_TARGETDURATION: HlsTag<Duration> = HlsTag( "EXT-X-TARGETDURATION", appliesTo = HlsTag.AppliesTo.ENTIRE_PLAYLIST, required = true, unique = true ) { rawData -> Duration.ofSeconds(rawData.toLong()) } /** * Each media URI in a Playlist has a unique integer sequence number. * The sequence number of a URI is equal to the sequence number of the * URI that preceded it plus one. The EXT-X-MEDIA-SEQUENCE tag * indicates the sequence number of the first URI that appears in a * Playlist file. Its format is: * * #EXT-X-MEDIA-SEQUENCE:<number> * * A Playlist file MUST NOT contain more than one EXT-X-MEDIA-SEQUENCE * tag. If the Playlist file does not contain an EXT-X-MEDIA-SEQUENCE * tag then the sequence number of the first URI in the playlist SHALL * be considered to be 0. * * A media URI is not required to contain its sequence number. * * See Section 6.3.2 and Section 6.3.5 for information on handling the * EXT-X-MEDIA-SEQUENCE tag. */ val EXT_X_MEDIA_SEQUENCE: HlsTag<Int> = HlsTag( "EXT-X-MEDIA-SEQUENCE", appliesTo = HlsTag.AppliesTo.ENTIRE_PLAYLIST, unique = true ) { rawData -> rawData.toInt() } /** * Media segments MAY be encrypted. The EXT-X-KEY tag specifies how to * decrypt them. It applies to every media URI that appears between it * and the next EXT-X-KEY tag in the Playlist file (if any). Its format * is: * * #EXT-X-KEY:<attribute-list> * * The following attributes are defined: * * The METHOD attribute specifies the encryption method. It is of type * enumerated-string. Each EXT-X-KEY tag MUST contain a METHOD * attribute. * * Two methods are defined: NONE and AES-128. * * An encryption method of NONE means that media segments are not * encrypted. If the encryption method is NONE, the URI and the IV * attributes MUST NOT be present. * * An encryption method of AES-128 means that media segments are * encrypted using the Advanced Encryption Standard [AES_128] with a * 128-bit key and PKCS7 padding [RFC5652]. If the encryption method is * AES-128, the URI attribute MUST be present. The IV attribute MAY be * present; see Section 5.2. * * The URI attribute specifies how to obtain the key. Its value is a * quoted-string that contains a URI [RFC3986] for the key. * * The IV attribute, if present, specifies the Initialization Vector to * be used with the key. Its value is a hexadecimal-integer. The IV * attribute appeared in protocol version 2. * * If the Playlist file does not contain an EXT-X-KEY tag then media * segments are not encrypted. * * See Section 5 for the format of the key file, and Section 5.2, * Section 6.2.3 and Section 6.3.6 for additional information on media * segment encryption. */ val EXT_X_KEY: HlsTag<EncryptionKey?> = HlsTag( "EXT-X-KEY", appliesTo = HlsTag.AppliesTo.FOLLOWING_SEGMENTS ) { rawData -> val parser = AttributeListParser(rawData) var uri: URI? = null var iv: BigInteger? = null var method: String = "NONE" while (parser.hasMoreAttributes()) { when (parser.readAttributeName()) { "URI" -> uri = URI.create(parser.readQuotedString()) "IV" -> iv = parser.readHexadecimalInt() "METHOD" -> method = parser.readEnumeratedString() } } if (!"NONE".equals(method)) EncryptionKey(method, uri!!, iv) else null } /** * The EXT-X-PROGRAM-DATE-TIME tag associates the first sample of a * media segment with an absolute date and/or time. It applies only to * the next media URI. * * The date/time representation is ISO/IEC 8601:2004 [ISO_8601] and * SHOULD indicate a time zone: * * #EXT-X-PROGRAM-DATE-TIME:<YYYY-MM-DDThh:mm:ssZ> * * For example: * * #EXT-X-PROGRAM-DATE-TIME:2010-02-19T14:54:23.031+08:00 * * See Section 6.2.1 and Section 6.3.3 for more information on the EXT- * X-PROGRAM-DATE-TIME tag. */ val EXT_X_PROGRAM_DATE_TIME: HlsTag<ZonedDateTime> = HlsTag( "EXT-X-PROGRAM-DATE-TIME", appliesTo = HlsTag.AppliesTo.NEXT_SEGMENT, unique = true ) { rawData -> ZonedDateTime.parse(rawData) } /** * The EXT-X-ALLOW-CACHE tag indicates whether the client MAY or MUST * NOT cache downloaded media segments for later replay. It MAY occur * anywhere in the Playlist file; it MUST NOT occur more than once. The * EXT-X-ALLOW-CACHE tag applies to all segments in the playlist. Its * format is: * * #EXT-X-ALLOW-CACHE:<YES|NO> * * See Section 6.3.3 for more information on the EXT-X-ALLOW-CACHE tag. */ val EXT_X_ALLOW_CACHE: HlsTag<Boolean> = HlsTag( "EXT-X-ALLOW-CACHE", appliesTo = HlsTag.AppliesTo.ENTIRE_PLAYLIST, unique = true ) { rawData -> readYesNo(rawData) } /** * The EXT-X-PLAYLIST-TYPE tag provides mutability information about the * Playlist file. It applies to the entire Playlist file. It is * optional. Its format is: * * #EXT-X-PLAYLIST-TYPE:<EVENT|VOD> * * Section 6.2.1 defines the implications of the EXT-X-PLAYLIST-TYPE * tag. */ val EXT_X_PLAYLIST_TYPE: HlsTag<PlaylistType> = HlsTag( "EXT-X-PLAYLIST-TYPE", appliesTo = HlsTag.AppliesTo.ENTIRE_PLAYLIST, unique = true ) { rawData -> when (rawData) { "EVENT" -> PlaylistType.EVENT "VOD" -> PlaylistType.VOD else -> throw IllegalArgumentException("Invalid value for EXT-X-PLAYLIST-TYPE: $rawData") } } /** * The EXT-X-ENDLIST tag indicates that no more media segments will be * added to the Playlist file. It MAY occur anywhere in the Playlist * file; it MUST NOT occur more than once. Its format is: * * #EXT-X-ENDLIST */ val EXT_X_ENDLIST: HlsTag<Nothing> = HlsTag( "EXT-X-ENDLIST", appliesTo = HlsTag.AppliesTo.ENTIRE_PLAYLIST, hasAttributes = false, unique = true ) /** * The EXT-X-MEDIA tag is used to relate Playlists that contain * alternative renditions of the same content. For example, three EXT- * X-MEDIA tags can be used to identify audio-only Playlists that * contain English, French and Spanish renditions of the same * presentation. Or two EXT-X-MEDIA tags can be used to identify video- * only Playlists that show two different camera angles. * * The EXT-X-MEDIA tag stands alone, in that it does not apply to a * particular URI in the Playlist. Its format is: * * #EXT-X-MEDIA:<attribute-list> * * The following attributes are defined: * * URI * * The value is a quoted-string containing a URI that identifies the * Playlist file. This attribute is optional; see Section 3.4.10.1. * * TYPE * * The value is enumerated-string; valid strings are AUDIO and VIDEO. * If the value is AUDIO, the Playlist described by the tag MUST contain * audio media. If the value is VIDEO, the Playlist MUST contain video * media. * * GROUP-ID * * The value is a quoted-string identifying a mutually-exclusive group * of renditions. The presence of this attribute signals membership in * the group. See Section 3.4.9.1. * * LANGUAGE * * The value is a quoted-string containing an RFC 5646 [RFC5646] * language tag that identifies the primary language used in the * rendition. This attribute is optional. * * NAME * * The value is a quoted-string containing a human-readable description * of the rendition. If the LANGUAGE attribute is present then this * description SHOULD be in that language. * * DEFAULT * * The value is enumerated-string; valid strings are YES and NO. If the * value is YES, then the client SHOULD play this rendition of the * content in the absence of information from the user indicating a * different choice. This attribute is optional. Its absence indicates * an implicit value of NO. * * AUTOSELECT * * The value is enumerated-string; valid strings are YES and NO. This * attribute is optional. Its absence indicates an implicit value of * NO. If the value is YES, then the client MAY choose to play this * rendition in the absence of explicit user preference because it * matches the current playback environment, such as chosen system * language. * * The EXT-X-MEDIA tag appeared in version 4 of the protocol. */ val EXT_X_MEDIA: HlsTag<MediaRendition> = HlsTag( "EXT-X-MEDIA", appliesTo = HlsTag.AppliesTo.ADDITIONAL_DATA ) { rawData -> val parser = AttributeListParser(rawData) var type: String? = null var uri: URI? = null var group: String? = null var language: String? = null var name: String? = null var default: Boolean = false var autoSelect: Boolean = false while (parser.hasMoreAttributes()) { when (parser.readAttributeName()) { "URI" -> uri = URI.create(parser.readQuotedString()) "TYPE" -> type = parser.readEnumeratedString() "GROUP-ID" -> group = parser.readQuotedString() "LANGUAGE" -> language = parser.readQuotedString() "NAME" -> name = parser.readQuotedString() "DEFAULT" -> default = readYesNo(parser.readEnumeratedString()) "AUTOSELECT" -> autoSelect = readYesNo(parser.readEnumeratedString()) } } MediaRendition(when (type) { "VIDEO" -> MediaType.VIDEO "AUDIO" -> MediaType.AUDIO else -> throw IllegalStateException("invalid MediaType: $type") }, uri, group, language, name, default, autoSelect) } /** * The EXT-X-STREAM-INF tag identifies a media URI as a Playlist file * containing a multimedia presentation and provides information about * that presentation. It applies only to the URI that follows it. Its * format is: * * #EXT-X-STREAM-INF:<attribute-list> * <URI> * * The following attributes are defined: * * BANDWIDTH * * The value is a decimal-integer of bits per second. It MUST be an * upper bound of the overall bitrate of each media segment (calculated * to include container overhead) that appears or will appear in the * Playlist. * * Every EXT-X-STREAM-INF tag MUST include the BANDWIDTH attribute. * * PROGRAM-ID * * The value is a decimal-integer that uniquely identifies a particular * presentation within the scope of the Playlist file. * A Playlist file MAY contain multiple EXT-X-STREAM-INF tags with the * same PROGRAM-ID to identify different encodings of the same * presentation. These variant playlists MAY contain additional EXT-X- * STREAM-INF tags. * * CODECS * * The value is a quoted-string containing a comma-separated list of * formats, where each format specifies a media sample type that is * present in a media segment in the Playlist file. Valid format * identifiers are those in the ISO File Format Name Space defined by * RFC 6381 [RFC6381]. * * Every EXT-X-STREAM-INF tag SHOULD include a CODECS attribute. * * RESOLUTION * * The value is a decimal-resolution describing the approximate encoded * horizontal and vertical resolution of video within the presentation. * * AUDIO * * The value is a quoted-string. It MUST match the value of the * GROUP-ID attribute of an EXT-X-MEDIA tag elsewhere in the Playlist * whose TYPE attribute is AUDIO. It indicates the set of audio * renditions that MAY be used when playing the presentation. See * Section 3.4.10.1. * * VIDEO * * The value is a quoted-string. It MUST match the value of the * GROUP-ID attribute of an EXT-X-MEDIA tag elsewhere in the Playlist * whose TYPE attribute is VIDEO. It indicates the set of video * renditions that MAY be used when playing the presentation. See * Section 3.4.10.1. */ val EXT_X_STREAM_INF: HlsTag<StreamInformation> = HlsTag( "EXT-X-STREAM-INF", appliesTo = HlsTag.AppliesTo.NEXT_SEGMENT, unique = true ) { rawData -> val parser = AttributeListParser(rawData) var bandwidth: Long? = null var programId: Long? = null var codecs: String? = null var resolution: AttributeListParser.Resolution? = null var audio: String? = null var video: String? = null while (parser.hasMoreAttributes()) { when (parser.readAttributeName()) { "BANDWIDTH" -> bandwidth = parser.readDecimalInt() "PROGRAM-ID" -> programId = parser.readDecimalInt() "CODECS" -> codecs = parser.readQuotedString() "RESOLUTION" -> resolution = parser.readResolution() "AUDIO" -> audio = parser.readQuotedString() "VIDEO" -> video = parser.readQuotedString() } } StreamInformation( bandwidth!!, programId, codecs?.let { ImmutableList.copyOf(it.split(',')) } ?: ImmutableList.of(), resolution, audio, video ) } /** * The EXT-X-DISCONTINUITY tag indicates an encoding discontinuity * between the media segment that follows it and the one that preceded * it. The set of characteristics that MAY change is: * * o file format * * o number and type of tracks * * o encoding parameters * * o encoding sequence * * o timestamp sequence * * Its format is: * * #EXT-X-DISCONTINUITY * * See Section 4, Section 6.2.1, and Section 6.3.3 for more information * about the EXT-X-DISCONTINUITY tag. */ val EXT_X_DISCONTINUITY: HlsTag<Nothing> = HlsTag( "EXT-X-DISCONTINUITY", appliesTo = HlsTag.AppliesTo.NEXT_SEGMENT, hasAttributes = false ) /** * The EXT-X-I-FRAMES-ONLY tag indicates that each media segment in the * Playlist describes a single I-frame. I-frames (or Intra frames) are * encoded video frames whose encoding does not depend on any other * frame. * * The EXT-X-I-FRAMES-ONLY tag applies to the entire Playlist. Its * format is: * * #EXT-X-I-FRAMES-ONLY * * In a Playlist with the EXT-X-I-FRAMES-ONLY tag, the media segment * duration (EXTINF tag value) is the time between the presentation time * of the I-frame in the media segment and the presentation time of the * next I-frame in the Playlist, or the end of the presentation if it is * the last I-frame in the Playlist. * * Media resources containing I-frame segments MUST begin with a * Transport Stream PAT/PMT. The byte range of an I-frame segment with * an EXT-X-BYTERANGE tag applied to it (Section 3.4.1) MUST NOT include * a PAT/PMT. * * The EXT-X-I-FRAMES-ONLY tag appeared in version 4 of the protocol. */ val EXT_X_I_FRAMES_ONLY: HlsTag<Nothing> = HlsTag( "EXT-X-I-FRAMES-ONLY", appliesTo = HlsTag.AppliesTo.ENTIRE_PLAYLIST, hasAttributes = false ) /** * The EXT-X-I-FRAME-STREAM-INF tag identifies a Playlist file * containing the I-frames of a multimedia presentation. It stands * alone, in that it does not apply to a particular URI in the Playlist. * Its format is: * * #EXT-X-I-FRAME-STREAM-INF:<attribute-list> * * All attributes defined for the EXT-X-STREAM-INF tag (Section 3.4.10) * are also defined for the EXT-X-I-FRAME-STREAM-INF tag, except for the * AUDIO attribute. In addition, the following attribute is defined: * * URI * * The value is a quoted-string containing a URI that identifies the * I-frame Playlist file. * * Every EXT-X-I-FRAME-STREAM-INF tag MUST include a BANDWIDTH attribute * and a URI attribute. * * The provisions in Section 3.4.10.1 also apply to EXT-X-I-FRAME- * STREAM-INF tags with a VIDEO attribute. * * A Playlist that specifies alternative VIDEO renditions and I-frame * Playlists SHOULD include an alternative I-frame VIDEO rendition for * each regular VIDEO rendition, with the same NAME and LANGUAGE * attributes. * * The EXT-X-I-FRAME-STREAM-INF tag appeared in version 4 of the * protocol. Clients that do not implement protocol version 4 or higher * MUST ignore it. */ val EXT_X_I_FRAME_STREAM_INF: HlsTag<Any> = HlsTag( "EXT-X-I-FRAME-STREAM-INF", appliesTo = HlsTag.AppliesTo.ADDITIONAL_DATA ) { rawData -> val parser = AttributeListParser(rawData) var bandwidth: Long? = null var programId: Long? = null var codecs: String? = null var resolution: AttributeListParser.Resolution? = null var video: String? = null var uri: URI? = null while (parser.hasMoreAttributes()) { when (parser.readAttributeName()) { "BANDWIDTH" -> bandwidth = parser.readDecimalInt() "PROGRAM-ID" -> programId = parser.readDecimalInt() "CODECS" -> codecs = parser.readQuotedString() "RESOLUTION" -> resolution = parser.readResolution() "VIDEO" -> video = parser.readQuotedString() "URI" -> uri = URI.create(parser.readQuotedString()) } } IFrameStreamInformation( bandwidth!!, programId, codecs?.let { ImmutableList.copyOf(it.split(',')) } ?: ImmutableList.of(), resolution, video, uri!! ) } /** * The EXT-X-VERSION tag indicates the compatibility version of the * Playlist file. The Playlist file, its associated media, and its * server MUST comply with all provisions of the most-recent version of * this document describing the protocol version indicated by the tag * value. * * The EXT-X-VERSION tag applies to the entire Playlist file. Its * format is: * * #EXT-X-VERSION:<n> * * where n is an integer indicating the protocol version. * * A Playlist file MUST NOT contain more than one EXT-X-VERSION tag. A * Playlist file that does not contain an EXT-X-VERSION tag MUST comply * with version 1 of this protocol. */ val EXT_X_VERSION: HlsTag<Int> = HlsTag( "EXT-X-VERSION", appliesTo = HlsTag.AppliesTo.ENTIRE_PLAYLIST, required = true, unique = false ) { rawData -> rawData.toInt() } data class SegmentInformation(val duration: Duration, val title: String) data class SourceSubrange(val length: Long, val offset: Long) data class EncryptionKey(val method: String, val uri: URI, val iv: BigInteger?) data class MediaRendition( val type: MediaType, val uri: URI?, val group: String?, val language: String?, val name: String?, val default: Boolean, val autoSelect: Boolean ) data class StreamInformation( val bandwidth: Long, val programId: Long?, val codecs: List<String>, val resolution: AttributeListParser.Resolution?, val audio: String?, val video: String? ) data class IFrameStreamInformation( val bandwidth: Long, val programId: Long?, val codecs: List<String>, val resolution: AttributeListParser.Resolution?, val video: String?, val uri: URI ) enum class PlaylistType { EVENT, VOD } enum class MediaType { VIDEO, AUDIO, } private fun readYesNo(input: String): Boolean { return when (input) { "YES" -> true "NO" -> false else -> throw IllegalArgumentException("Invalid value for YES/NO: $input") } } fun CharSequence.toDuration(): Duration { val parts = this.split('.', limit = 2) return Duration.ofSeconds(parts[0].toLong(), if (parts.size == 2) TimeUnit.MILLISECONDS.toNanos(parts[1].toLong()) else 0) } }
mit
f9de70c282c27b7fac959859368cde4c
36.247006
130
0.617298
4.286871
false
false
false
false
wordpress-mobile/WordPress-FluxC-Android
fluxc/src/main/java/org/wordpress/android/fluxc/model/BloggingRemindersMapper.kt
2
2381
package org.wordpress.android.fluxc.model import org.wordpress.android.fluxc.model.BloggingRemindersModel.Day import org.wordpress.android.fluxc.model.BloggingRemindersModel.Day.FRIDAY import org.wordpress.android.fluxc.model.BloggingRemindersModel.Day.MONDAY import org.wordpress.android.fluxc.model.BloggingRemindersModel.Day.SATURDAY import org.wordpress.android.fluxc.model.BloggingRemindersModel.Day.SUNDAY import org.wordpress.android.fluxc.model.BloggingRemindersModel.Day.THURSDAY import org.wordpress.android.fluxc.model.BloggingRemindersModel.Day.TUESDAY import org.wordpress.android.fluxc.model.BloggingRemindersModel.Day.WEDNESDAY import org.wordpress.android.fluxc.persistence.BloggingRemindersDao.BloggingReminders import javax.inject.Inject class BloggingRemindersMapper @Inject constructor() { fun toDatabaseModel(domainModel: BloggingRemindersModel): BloggingReminders = with(domainModel) { return BloggingReminders( localSiteId = this.siteId, monday = enabledDays.contains(MONDAY), tuesday = enabledDays.contains(TUESDAY), wednesday = enabledDays.contains(WEDNESDAY), thursday = enabledDays.contains(THURSDAY), friday = enabledDays.contains(FRIDAY), saturday = enabledDays.contains(SATURDAY), sunday = enabledDays.contains(SUNDAY), hour = this.hour, minute = this.minute, isPromptRemindersOptedIn = domainModel.isPromptIncluded ) } fun toDomainModel(databaseModel: BloggingReminders): BloggingRemindersModel = with(databaseModel) { return BloggingRemindersModel( siteId = localSiteId, enabledDays = mutableSetOf<Day>().let { list -> if (monday) list.add(MONDAY) if (tuesday) list.add(TUESDAY) if (wednesday) list.add(WEDNESDAY) if (thursday) list.add(THURSDAY) if (friday) list.add(FRIDAY) if (saturday) list.add(SATURDAY) if (sunday) list.add(SUNDAY) list }, hour = hour, minute = minute, isPromptIncluded = isPromptRemindersOptedIn ) } }
gpl-2.0
6d2b599c513965f2ad7f0c5f28042dbb
44.788462
85
0.647207
5.267699
false
false
false
false
vase4kin/TeamCityApp
app/src/androidTest/java/com/github/vase4kin/teamcityapp/artifact/view/ArtifactListFragmentTest.kt
1
30394
/* * Copyright 2020 Andrey Tolpeev * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.vase4kin.teamcityapp.artifact.view import android.content.Intent import android.net.Uri import android.os.Bundle import androidx.test.espresso.Espresso.onView import androidx.test.espresso.action.ViewActions.click import androidx.test.espresso.action.ViewActions.longClick import androidx.test.espresso.action.ViewActions.scrollTo import androidx.test.espresso.assertion.ViewAssertions.matches import androidx.test.espresso.intent.Intents.intended import androidx.test.espresso.intent.matcher.IntentMatchers.hasAction import androidx.test.espresso.intent.matcher.IntentMatchers.hasData import androidx.test.espresso.intent.matcher.IntentMatchers.hasType import androidx.test.espresso.matcher.ViewMatchers.isDisplayed import androidx.test.espresso.matcher.ViewMatchers.withId import androidx.test.espresso.matcher.ViewMatchers.withParent import androidx.test.espresso.matcher.ViewMatchers.withText import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.filters.SdkSuppress import androidx.test.platform.app.InstrumentationRegistry import androidx.test.rule.GrantPermissionRule import com.azimolabs.conditionwatcher.ConditionWatcher import com.azimolabs.conditionwatcher.Instruction import com.github.vase4kin.teamcityapp.R import com.github.vase4kin.teamcityapp.TeamCityApplication import com.github.vase4kin.teamcityapp.api.TeamCityService import com.github.vase4kin.teamcityapp.artifact.api.File import com.github.vase4kin.teamcityapp.artifact.api.Files import com.github.vase4kin.teamcityapp.base.extractor.BundleExtractorValues import com.github.vase4kin.teamcityapp.build_details.view.BuildDetailsActivity import com.github.vase4kin.teamcityapp.buildlist.api.Build import com.github.vase4kin.teamcityapp.dagger.components.AppComponent import com.github.vase4kin.teamcityapp.dagger.components.RestApiComponent import com.github.vase4kin.teamcityapp.dagger.modules.AppModule import com.github.vase4kin.teamcityapp.dagger.modules.FakeTeamCityServiceImpl import com.github.vase4kin.teamcityapp.dagger.modules.Mocks import com.github.vase4kin.teamcityapp.dagger.modules.RestApiModule import com.github.vase4kin.teamcityapp.helper.CustomIntentsTestRule import com.github.vase4kin.teamcityapp.helper.RecyclerViewMatcher.Companion.withRecyclerView import com.github.vase4kin.teamcityapp.helper.TestUtils import com.github.vase4kin.teamcityapp.helper.TestUtils.Companion.hasItemsCount import io.reactivex.Single import it.cosenonjaviste.daggermock.DaggerMockRule import okhttp3.ResponseBody import org.hamcrest.core.AllOf.allOf import org.junit.Before import org.junit.BeforeClass import org.junit.Ignore import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith import org.mockito.Matchers.anyString import org.mockito.Mockito.`when` import org.mockito.Spy import java.util.ArrayList private const val BUILD_TYPE_NAME = "name" private const val TIMEOUT = 5000 /** * Tests for [ArtifactListFragment] */ @RunWith(AndroidJUnit4::class) class ArtifactListFragmentTest { @JvmField @Rule val restComponentDaggerRule: DaggerMockRule<RestApiComponent> = DaggerMockRule(RestApiComponent::class.java, RestApiModule(Mocks.URL)) .addComponentDependency( AppComponent::class.java, AppModule(InstrumentationRegistry.getInstrumentation().targetContext.applicationContext as TeamCityApplication) ) .set { restApiComponent -> val app = InstrumentationRegistry.getInstrumentation().targetContext.applicationContext as TeamCityApplication app.setRestApiInjector(restApiComponent) } @JvmField @Rule val activityRule: CustomIntentsTestRule<BuildDetailsActivity> = CustomIntentsTestRule(BuildDetailsActivity::class.java) @JvmField @Rule val grantPermissionRule: GrantPermissionRule = GrantPermissionRule.grant("android.permission.WRITE_EXTERNAL_STORAGE") @Spy private val teamCityService: TeamCityService = FakeTeamCityServiceImpl() @Spy private val build: Build = Mocks.successBuild() companion object { @JvmStatic @BeforeClass fun disableOnboarding() { TestUtils.disableOnboarding() } } @Before fun setUp() { val app = InstrumentationRegistry.getInstrumentation().targetContext.applicationContext as TeamCityApplication app.restApiInjector.sharedUserStorage().clearAll() app.restApiInjector.sharedUserStorage() .saveGuestUserAccountAndSetItAsActive(Mocks.URL, false) ConditionWatcher.setTimeoutLimit(TIMEOUT) } @Test fun testUserCanSeeArtifacts() { // Prepare mocks `when`(teamCityService.build(anyString())).thenReturn(Single.just(build)) // Prepare intent // <! ---------------------------------------------------------------------- !> // Passing build object to activity, had to create it for real, Can't pass mock object as serializable in bundle :( // <! ---------------------------------------------------------------------- !> val intent = Intent() val b = Bundle() b.putSerializable(BundleExtractorValues.BUILD, Mocks.successBuild()) b.putString(BundleExtractorValues.NAME, BUILD_TYPE_NAME) intent.putExtras(b) // Start activity activityRule.launchActivity(intent) // Checking artifact tab title onView(withText("Artifacts")) .perform(scrollTo()) .check(matches(isDisplayed())) .perform(click()) // Checking artifacts onView(withId(R.id.artifact_recycler_view)).check(hasItemsCount(3)) onView( withRecyclerView(R.id.artifact_recycler_view).atPositionOnView( 0, R.id.title ) ).check(matches(withText("res"))) onView( withRecyclerView(R.id.artifact_recycler_view).atPositionOnView( 1, R.id.title ) ).check(matches(withText("AndroidManifest.xml"))) val sizeText = if (android.os.Build.VERSION.SDK_INT > android.os.Build.VERSION_CODES.N) { "7.77 kB" } else { "7.59 KB" } onView( withRecyclerView(R.id.artifact_recycler_view).atPositionOnView( 1, R.id.subTitle ) ).check(matches(withText(sizeText))) onView( withRecyclerView(R.id.artifact_recycler_view).atPositionOnView( 2, R.id.title ) ).check(matches(withText("index.html"))) val sizeText2 = if (android.os.Build.VERSION.SDK_INT > android.os.Build.VERSION_CODES.N) { "698 kB" } else { "681 KB" } onView( withRecyclerView(R.id.artifact_recycler_view).atPositionOnView( 2, R.id.subTitle ) ).check(matches(withText(sizeText2))) } @Test fun testUserCanSeeArtifactsEmptyMessageIfArtifactsAreEmpty() { // Prepare mocks `when`(teamCityService.build(anyString())).thenReturn(Single.just(build)) `when`( teamCityService.listArtifacts( anyString(), anyString() ) ).thenReturn(Single.just(Files(emptyList()))) // Prepare intent // <! ---------------------------------------------------------------------- !> // Passing build object to activity, had to create it for real, Can't pass mock object as serializable in bundle :( // <! ---------------------------------------------------------------------- !> val intent = Intent() val b = Bundle() b.putSerializable(BundleExtractorValues.BUILD, Mocks.successBuild()) b.putString(BundleExtractorValues.NAME, BUILD_TYPE_NAME) intent.putExtras(b) // Start activity activityRule.launchActivity(intent) // Checking artifact tab title onView(withText("Artifacts")) .perform(scrollTo()) .check(matches(isDisplayed())) .perform(click()) // Checking message onView(withText(R.string.empty_list_message_artifacts)).check(matches(isDisplayed())) } @Test fun testUserCanSeeArtifactsErrorMessageIfSmthBadHappens() { // Prepare mocks `when`(teamCityService.build(anyString())).thenReturn(Single.just(build)) `when`(teamCityService.listArtifacts(anyString(), anyString())).thenReturn( Single.error( RuntimeException("Fake error happened!") ) ) // Prepare intent // <! ---------------------------------------------------------------------- !> // Passing build object to activity, had to create it for real, Can't pass mock object as serializable in bundle :( // <! ---------------------------------------------------------------------- !> val intent = Intent() val b = Bundle() b.putSerializable(BundleExtractorValues.BUILD, Mocks.successBuild()) b.putString(BundleExtractorValues.NAME, BUILD_TYPE_NAME) intent.putExtras(b) // Start activity activityRule.launchActivity(intent) // Checking artifact tab title onView(withText("Artifacts")) .perform(scrollTo()) .check(matches(isDisplayed())) .perform(click()) // Checking error onView( allOf( withText(R.string.error_view_error_text), withParent(isDisplayed()) ) ).check( matches(isDisplayed()) ) } @Test @Throws(Exception::class) fun testUserCanOpenArtifactWithChildren() { // Prepare mocks `when`(teamCityService.build(anyString())).thenReturn(Single.just(build)) val folderOne = File( "res", File.Children("/guestAuth/app/rest/builds/id:92912/artifacts/children/TCity.apk!/res"), "/guestAuth/app/rest/builds/id:92912/artifacts/metadata/TCity.apk!/res" ) val folderTwo = File( "res_level_deeper1", File.Children("/guestAuth/app/rest/builds/id:92912/artifacts/children/TCity.apk!/res"), "/guestAuth/app/rest/builds/id:92912/artifacts/metadata/TCity.apk!/res" ) val folderThree = File( "res_level_deeper2", File.Children("/guestAuth/app/rest/builds/id:92912/artifacts/children/TCity.apk!/res"), "/guestAuth/app/rest/builds/id:92912/artifacts/metadata/TCity.apk!/res" ) val deeperArtifacts = ArrayList<File>() deeperArtifacts.add(folderTwo) deeperArtifacts.add(folderThree) `when`(teamCityService.listArtifacts(anyString(), anyString())) .thenReturn(Single.just(Files(listOf(folderOne)))) .thenReturn(Single.just(Files(deeperArtifacts))) // Prepare intent // <! ---------------------------------------------------------------------- !> // Passing build object to activity, had to create it for real, Can't pass mock object as serializable in bundle :( // <! ---------------------------------------------------------------------- !> val intent = Intent() val b = Bundle() b.putSerializable(BundleExtractorValues.BUILD, Mocks.successBuild()) b.putString(BundleExtractorValues.NAME, BUILD_TYPE_NAME) intent.putExtras(b) // Start activity activityRule.launchActivity(intent) // Checking artifact tab title onView(withText("Artifacts")) .perform(scrollTo()) .check(matches(isDisplayed())) .perform(click()) // Checking first level artifacts onView(withId(R.id.artifact_recycler_view)).check(hasItemsCount(1)) ConditionWatcher.waitForCondition(object : Instruction() { override fun getDescription(): String { return "Can't find artifact with name res" } override fun checkCondition(): Boolean { return try { onView( withRecyclerView(R.id.artifact_recycler_view).atPositionOnView( 0, R.id.title ) ) .check(matches(withText("res"))) true } catch (ignored: Exception) { false } } }) // Clicking first level artifacts ConditionWatcher.waitForCondition(object : Instruction() { override fun getDescription(): String { return "Can't click on artifact at position 0" } override fun checkCondition(): Boolean { return try { onView( withRecyclerView(R.id.artifact_recycler_view).atPositionOnView( 0, R.id.title ) ) .perform(click()) true } catch (ignored: Exception) { false } } }) ConditionWatcher.waitForCondition(object : Instruction() { override fun getDescription(): String { return "The artifact page is not loaded" } override fun checkCondition(): Boolean { var isResFolderClicked = false try { onView(withText("res_level_deeper1")).check(matches(isDisplayed())) isResFolderClicked = true } catch (ignored: Exception) { onView(withRecyclerView(R.id.artifact_recycler_view).atPosition(0)) .perform(click()) } return isResFolderClicked } }) // In case of the same recycler view ids onView(withText("res_level_deeper1")).check(matches(isDisplayed())) onView(withText("res_level_deeper2")).check(matches(isDisplayed())) } @Test @Throws(Exception::class) fun testUserCanOpenArtifactWithChildrenByLongTap() { // Prepare mocks `when`(teamCityService.build(anyString())).thenReturn(Single.just(build)) val folderOne = File( "res", File.Children("/guestAuth/app/rest/builds/id:92912/artifacts/children/TCity.apk!/res"), "/guestAuth/app/rest/builds/id:92912/artifacts/metadata/TCity.apk!/res" ) val folderTwo = File( "res_level_deeper1", File.Children("/guestAuth/app/rest/builds/id:92912/artifacts/children/TCity.apk!/res"), "/guestAuth/app/rest/builds/id:92912/artifacts/metadata/TCity.apk!/res" ) val folderThree = File( "res_level_deeper2", File.Children("/guestAuth/app/rest/builds/id:92912/artifacts/children/TCity.apk!/res"), "/guestAuth/app/rest/builds/id:92912/artifacts/metadata/TCity.apk!/res" ) val deeperArtifacts = ArrayList<File>() deeperArtifacts.add(folderTwo) deeperArtifacts.add(folderThree) `when`(teamCityService.listArtifacts(anyString(), anyString())) .thenReturn(Single.just(Files(listOf(folderOne)))) .thenReturn(Single.just(Files(deeperArtifacts))) // Prepare intent // <! ---------------------------------------------------------------------- !> // Passing build object to activity, had to create it for real, Can't pass mock object as serializable in bundle :( // <! ---------------------------------------------------------------------- !> val intent = Intent() val b = Bundle() b.putSerializable(BundleExtractorValues.BUILD, Mocks.successBuild()) b.putString(BundleExtractorValues.NAME, BUILD_TYPE_NAME) intent.putExtras(b) // Start activity activityRule.launchActivity(intent) // Checking artifact tab title onView(withText("Artifacts")) .perform(scrollTo()) .check(matches(isDisplayed())) .perform(click()) // Checking first level artifacts onView(withId(R.id.artifact_recycler_view)).check(hasItemsCount(1)) ConditionWatcher.waitForCondition(object : Instruction() { override fun getDescription(): String { return "Can't find artifact with name res" } override fun checkCondition(): Boolean { return try { onView( withRecyclerView(R.id.artifact_recycler_view).atPositionOnView( 0, R.id.title ) ) .check(matches(withText("res"))) true } catch (ignored: Exception) { false } } }) // Long click on first level artifacts ConditionWatcher.waitForCondition(object : Instruction() { override fun getDescription(): String { return "Can't do long click on artifact at 0 position" } override fun checkCondition(): Boolean { return try { onView( withRecyclerView(R.id.artifact_recycler_view).atPositionOnView( 0, R.id.title ) ) .perform(longClick()) true } catch (ignored: Exception) { false } } }) ConditionWatcher.waitForCondition(object : Instruction() { override fun getDescription(): String { return "The artifact menu is not opened" } override fun checkCondition(): Boolean { var isMenuOpened = false try { onView(withText(R.string.artifact_open)) .check(matches(isDisplayed())) isMenuOpened = true } catch (ignored: Exception) { // Clicking first level artifacts onView( withRecyclerView(R.id.artifact_recycler_view).atPositionOnView( 0, R.id.title ) ) .perform(longClick()) } return isMenuOpened } }) // Click on open option onView(withText(R.string.artifact_open)) .perform(click()) // In case of the same recycler view ids onView(withText("res_level_deeper1")).check(matches(isDisplayed())) onView(withText("res_level_deeper2")).check(matches(isDisplayed())) } @Ignore @Test fun testUserCanDownloadArtifact() { // Prepare mocks `when`(teamCityService.build(anyString())).thenReturn(Single.just(build)) `when`(teamCityService.downloadFile(anyString())).thenReturn( Single.just( ResponseBody.create( null, "text" ) ) ) // Prepare intent // <! ---------------------------------------------------------------------- !> // Passing build object to activity, had to create it for real, Can't pass mock object as serializable in bundle :( // <! ---------------------------------------------------------------------- !> val intent = Intent() val b = Bundle() b.putSerializable(BundleExtractorValues.BUILD, Mocks.successBuild()) b.putString(BundleExtractorValues.NAME, BUILD_TYPE_NAME) intent.putExtras(b) // Start activity activityRule.launchActivity(intent) // Checking artifact tab title onView(withText("Artifacts")) .perform(scrollTo()) .check(matches(isDisplayed())) .perform(click()) // Clicking on artifact to download onView( withRecyclerView(R.id.artifact_recycler_view) .atPositionOnView(1, R.id.title) ) .check(matches(withText("AndroidManifest.xml"))) .perform(click()) // Click on download option onView(withText(R.string.artifact_download)) .perform(click()) // Check filter builds activity is opened intended( allOf( hasAction(Intent.ACTION_VIEW), hasType("*/*") ) ) } @Ignore("Test opens chrome and gets stuck") @Test fun testUserCanOpenHtmlFileInBrowser() { // Prepare mocks `when`(teamCityService.build(anyString())).thenReturn(Single.just(build)) // Prepare intent // <! ---------------------------------------------------------------------- !> // Passing build object to activity, had to create it for real, Can't pass mock object as serializable in bundle :( // <! ---------------------------------------------------------------------- !> val intent = Intent() val b = Bundle() b.putSerializable(BundleExtractorValues.BUILD, Mocks.successBuild()) b.putString(BundleExtractorValues.NAME, BUILD_TYPE_NAME) intent.putExtras(b) // Start activity activityRule.launchActivity(intent) // Checking artifact tab title onView(withText("Artifacts")) .perform(scrollTo()) .check(matches(isDisplayed())) .perform(click()) // Clicking on artifact onView( withRecyclerView(R.id.artifact_recycler_view) .atPositionOnView(2, R.id.title) ) .check(matches(withText("index.html"))) .perform(click()) // Click on download option onView(withText(R.string.artifact_open_in_browser)) .perform(click()) // Check filter builds activity is opened intended( allOf( hasData(Uri.parse("https://teamcity.server.com/repository/download/Checkstyle_IdeaInspectionsPullRequest/null:id/TCity.apk!/index.html?guest=1")), hasAction(Intent.ACTION_VIEW) ) ) } @Test @Throws(Exception::class) fun testUserSeeSnackBarWithErrorMessageIfArtifactWasNotDownloaded() { // Prepare mocks `when`(teamCityService.build(anyString())).thenReturn(Single.just(build)) `when`(teamCityService.downloadFile(anyString())).thenReturn(Single.error(RuntimeException("ERROR!"))) // Prepare intent // <! ---------------------------------------------------------------------- !> // Passing build object to activity, had to create it for real, Can't pass mock object as serializable in bundle :( // <! ---------------------------------------------------------------------- !> val intent = Intent() val b = Bundle() b.putSerializable(BundleExtractorValues.BUILD, Mocks.successBuild()) b.putString(BundleExtractorValues.NAME, BUILD_TYPE_NAME) intent.putExtras(b) // Start activity activityRule.launchActivity(intent) // Checking artifact tab title onView(withText("Artifacts")) .perform(scrollTo()) .check(matches(isDisplayed())) .perform(click()) // Checking artifact title and clicking on it val artifactName = "AndroidManifest.xml" ConditionWatcher.waitForCondition(object : Instruction() { override fun getDescription(): String { return "Can't click on artifact with name $artifactName" } override fun checkCondition(): Boolean { return try { onView( withRecyclerView(R.id.artifact_recycler_view) .atPositionOnView(1, R.id.title) ) .check(matches(withText(artifactName))) .perform(click()) true } catch (ignored: Exception) { false } } }) ConditionWatcher.waitForCondition(object : Instruction() { override fun getDescription(): String { return "The artifact menu is not opened" } override fun checkCondition(): Boolean { var isMenuOpened = false try { onView(withText(R.string.artifact_download)) .check(matches(isDisplayed())) isMenuOpened = true } catch (ignored: Exception) { onView( withRecyclerView(R.id.artifact_recycler_view) .atPositionOnView(1, R.id.title) ) .perform(click()) } return isMenuOpened } }) // Click on download option onView(withText(R.string.artifact_download)) .perform(click()) // Checking error snack bar message onView(withText(R.string.download_artifact_retry_snack_bar_text)) .check(matches(isDisplayed())) } @SdkSuppress(minSdkVersion = android.os.Build.VERSION_CODES.O) @Test fun testUserBeingAskedToGrantAllowInstallPackagesPermissions() { // Prepare mocks `when`(teamCityService.build(anyString())).thenReturn(Single.just(build)) val files = ArrayList<File>() files.add( File( "my-fancy-app.apk", 697840, File.Content("/guestAuth/app/rest/builds/id:92912/artifacts/content/TCity.apk!/my-fancy-app.apk"), "/guestAuth/app/rest/builds/id:92912/artifacts/metadata/TCity.apk!/my-fancy-app.apk" ) ) val filesMock = Files(files) `when`(teamCityService.listArtifacts(anyString(), anyString())).thenReturn( Single.just( filesMock ) ) // Prepare intent // <! ---------------------------------------------------------------------- !> // Passing build object to activity, had to create it for real, Can't pass mock object as serializable in bundle :( // <! ---------------------------------------------------------------------- !> val intent = Intent() val b = Bundle() b.putSerializable(BundleExtractorValues.BUILD, Mocks.successBuild()) b.putString(BundleExtractorValues.NAME, BUILD_TYPE_NAME) intent.putExtras(b) // Start activity activityRule.launchActivity(intent) // Checking artifact tab title onView(withText("Artifacts")) .perform(scrollTo()) .check(matches(isDisplayed())) .perform(click()) // Clicking on apk to download val artifactName = "my-fancy-app.apk" ConditionWatcher.waitForCondition(object : Instruction() { override fun getDescription(): String { return "Can't click on artifact with name $artifactName" } override fun checkCondition(): Boolean { return try { onView( withRecyclerView(R.id.artifact_recycler_view) .atPositionOnView(0, R.id.title) ) .check(matches(withText(artifactName))) .perform(click()) true } catch (ignored: Exception) { false } } }) ConditionWatcher.waitForCondition(object : Instruction() { override fun getDescription(): String { return "The artifact menu is not opened" } override fun checkCondition(): Boolean { var isMenuOpened = false try { onView(withText(R.string.artifact_download)) .check(matches(isDisplayed())) isMenuOpened = true } catch (ignored: Exception) { onView( withRecyclerView(R.id.artifact_recycler_view) .atPositionOnView(0, R.id.title) ) .perform(click()) } return isMenuOpened } }) // Click on download option onView(withText(R.string.artifact_download)) .perform(click()) // Check dialog text onView(withText(R.string.permissions_install_packages_dialog_content)).check( matches( isDisplayed() ) ) /*// Confirm dialog onView(withText(R.string.dialog_ok_title)).perform(click()); // Check filter builds activity is opened intended(allOf( hasAction(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES), hasData("package:com.github.vase4kin.teamcityapp.mock.debug")));*/ } }
apache-2.0
57d9719c45bc972066268d09525daf2e
37.087719
162
0.558564
5.361439
false
true
false
false
google/ksp
test-utils/src/main/kotlin/com/google/devtools/ksp/processor/GetSymbolsFromAnnotationProcessor.kt
1
1797
package com.google.devtools.ksp.processor import com.google.devtools.ksp.processing.Resolver import com.google.devtools.ksp.symbol.KSAnnotated class GetSymbolsFromAnnotationProcessor : AbstractTestProcessor() { val result = mutableListOf<String>() override fun toResult(): List<String> = result override fun process(resolver: Resolver): List<KSAnnotated> { result.add("==== Anno superficial====") resolver.getSymbolsWithAnnotation("Anno").forEach { result.add(toString(it)) } result.add("==== Anno in depth ====") resolver.getSymbolsWithAnnotation("Anno", true).forEach { result.add(toString(it)) } result.add("==== Bnno superficial====") resolver.getSymbolsWithAnnotation("Bnno").forEach { result.add(toString(it)) } result.add("==== Bnno in depth ====") resolver.getSymbolsWithAnnotation("Bnno", true).forEach { result.add(toString(it)) } result.add("==== A1 superficial====") resolver.getSymbolsWithAnnotation("A1").forEach { result.add(toString(it)) } result.add("==== A1 in depth ====") resolver.getSymbolsWithAnnotation("A1", true).forEach { result.add(toString(it)) } result.add("==== A2 superficial====") resolver.getSymbolsWithAnnotation("A2").forEach { result.add(toString(it)) } result.add("==== A2 in depth ====") resolver.getSymbolsWithAnnotation("A2", true).forEach { result.add(toString(it)) } result.add("==== Cnno in depth ====") resolver.getSymbolsWithAnnotation("Cnno", true).forEach { result.add(toString(it)) } return emptyList() } fun toString(annotated: KSAnnotated): String { return "$annotated:${annotated::class.supertypes.first().classifier.toString().substringAfterLast('.')}" } }
apache-2.0
e5283c8215418da104d13f8aa7380bab
50.342857
112
0.658876
4.526448
false
false
false
false
komu/siilinkari
src/main/kotlin/siilinkari/lexer/Token.kt
1
2780
package siilinkari.lexer import siilinkari.objects.Value /** * Tokens are the indivisible building blocks of source code. * * [Lexer] analyzes the source string to return tokens to be consumed by the parser. * * Some tokens are singleton values: e.g. when encountering `if` in the source code, * the lexer will return simply [Token.Keyword.If]. Other tokens contain information about * the value read: e.g. for source code `123`, the lexer will return [Token.Literal], * with its `value` set to integer `123`. * * @see TokenInfo */ sealed class Token { /** * Identifier such as variable, method or class name. */ class Identifier(val name: String): Token() { override fun toString() = "[Identifier $name]" override fun equals(other: Any?) = other is Identifier && name == other.name override fun hashCode(): Int = name.hashCode() } /** * Literal value, e.g. `42`, `"foo"`, or `true`. */ class Literal(val value: Value) : Token() { override fun toString() = "[Literal ${value.repr()}]" override fun equals(other: Any?) = other is Literal && value == other.value override fun hashCode(): Int = value.hashCode() } /** * Reserved word in the language. */ sealed class Keyword(private val name: String) : Token() { override fun toString() = name object Else : Keyword("else") object Fun : Keyword("fun") object If : Keyword("if") object Var : Keyword("var") object Val : Keyword("val") object While : Keyword("while") } /** * Operators. */ sealed class Operator(private val name: String) : Token() { override fun toString() = name object Plus : Operator("+") object Minus : Operator("-") object Multiply : Operator("*") object Divide : Operator("/") object EqualEqual : Operator("==") object NotEqual : Operator("!=") object Not : Operator("!") object LessThan : Operator("<") object GreaterThan : Operator(">") object LessThanOrEqual : Operator("<=") object GreaterThanOrEqual : Operator(">=") object And : Operator("&&") object Or : Operator("&&") } /** * General punctuation. */ sealed class Punctuation(private val name: String) : Token() { override fun toString() = "'$name'" object LeftParen : Punctuation("(") object RightParen : Punctuation(")") object LeftBrace : Punctuation("{") object RightBrace : Punctuation("}") object Equal : Punctuation("=") object Colon : Punctuation(":") object Semicolon : Punctuation(";") object Comma : Punctuation(",") } }
mit
3226cb70b41179a29b840d122fb53c1c
29.888889
90
0.591007
4.688027
false
false
false
false
polson/MetroTripper
app/src/main/java/com/philsoft/metrotripper/app/nextrip/TripViewHolder.kt
1
1754
package com.philsoft.metrotripper.app.nextrip import android.support.v7.widget.RecyclerView import android.view.View import com.philsoft.metrotripper.R import com.philsoft.metrotripper.app.nextrip.constants.Direction import com.philsoft.metrotripper.model.Trip import kotlinx.android.extensions.LayoutContainer import kotlinx.android.synthetic.main.trip_item.* class TripViewHolder(override val containerView: View) : RecyclerView.ViewHolder(containerView), LayoutContainer { fun render(trip: Trip) { timeUnit.visibility = View.VISIBLE route.text = trip.route + trip.terminal description.text = trip.description routeDirection.setImageResource(getTripDirectionResource(trip)) val timeAndText = trip.departureText.split("\\s+".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray() timeNumber.text = timeAndText[0] if (timeAndText.size > 1) { timeUnit.setText(R.string.minutes) } else { timeUnit.visibility = View.GONE } } private fun getTripDirectionResource(trip: Trip): Int { val direction = Direction.valueOf(trip.routeDirection) return when (direction) { Direction.NORTHBOUND -> R.drawable.ic_up_arrow Direction.SOUTHBOUND -> R.drawable.ic_down_arrow Direction.EASTBOUND -> R.drawable.ic_right_arrow Direction.WESTBOUND -> R.drawable.ic_left_arrow else -> 0 } } private fun setColors(mainColorResId: Int, topLineColorResId: Int, bottomLineColorResId: Int) { mainLayout.setBackgroundResource(mainColorResId) lineTop.setBackgroundResource(topLineColorResId) lineBottom.setBackgroundResource(bottomLineColorResId) } }
apache-2.0
5a4d03fd3e21a738889e4fc80231fcd2
39.790698
114
0.708096
4.463104
false
false
false
false
alygin/intellij-rust
src/main/kotlin/org/rust/ide/annotator/RsRecursiveCallLineMarkerProvider.kt
2
2154
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.ide.annotator import com.intellij.codeHighlighting.Pass import com.intellij.codeInsight.daemon.LineMarkerInfo import com.intellij.codeInsight.daemon.LineMarkerProvider import com.intellij.openapi.editor.markup.GutterIconRenderer import com.intellij.psi.PsiDocumentManager import com.intellij.psi.PsiElement import com.intellij.util.FunctionUtil import org.rust.ide.icons.RsIcons import org.rust.lang.core.psi.* import org.rust.lang.core.psi.ext.parentOfType import java.util.* /** * Line marker provider that annotates recursive funciton and method calls with * an icon on the gutter. */ class RsRecursiveCallLineMarkerProvider : LineMarkerProvider { override fun getLineMarkerInfo(element: PsiElement) = null override fun collectSlowLineMarkers(elements: List<PsiElement>, result: MutableCollection<LineMarkerInfo<PsiElement>>) { val lines = HashSet<Int>() // To prevent several markers on one line for (el in elements.filter { it.isRecursive }) { val doc = PsiDocumentManager.getInstance(el.project).getDocument(el.containingFile) ?: continue val lineNumber = doc.getLineNumber(el.textOffset) if (lineNumber !in lines) { lines.add(lineNumber) result.add(LineMarkerInfo( el, el.textRange, RsIcons.RECURSIVE_CALL, Pass.LINE_MARKERS, FunctionUtil.constant("Recursive call"), null, GutterIconRenderer.Alignment.RIGHT)) } } } private val RsCallExpr.pathExpr: RsPathExpr? get() = expr as? RsPathExpr private val PsiElement.isRecursive: Boolean get() { val def = when (this) { is RsCallExpr -> pathExpr?.path?.reference?.resolve() is RsMethodCall -> reference.resolve() else -> null } ?: return false return parentOfType<RsFunction>() == def } }
mit
13af1138e78d3c17ef8003d9e644b758
34.311475
107
0.649954
4.917808
false
false
false
false
alygin/intellij-rust
src/main/kotlin/org/rust/ide/formatter/impl/spacing.kt
2
12715
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.ide.formatter.impl import com.intellij.formatting.ASTBlock import com.intellij.formatting.Block import com.intellij.formatting.Spacing import com.intellij.formatting.Spacing.createSpacing import com.intellij.formatting.SpacingBuilder import com.intellij.lang.ASTNode import com.intellij.psi.PsiComment import com.intellij.psi.PsiElement import com.intellij.psi.TokenType.WHITE_SPACE import com.intellij.psi.codeStyle.CommonCodeStyleSettings import com.intellij.psi.impl.source.tree.TreeUtil import com.intellij.psi.tree.IElementType import com.intellij.psi.tree.TokenSet import org.rust.ide.formatter.RsFmtContext import org.rust.ide.formatter.settings.RsCodeStyleSettings import org.rust.lang.core.psi.* import org.rust.lang.core.psi.RsElementTypes.* import org.rust.lang.core.psi.ext.RsItemElement import org.rust.lang.core.psi.ext.RsNamedElement import org.rust.lang.core.psi.ext.getNextNonCommentSibling import org.rust.lang.core.psi.ext.getPrevNonCommentSibling import com.intellij.psi.tree.TokenSet.create as ts fun createSpacingBuilder(commonSettings: CommonCodeStyleSettings, rustSettings: RsCodeStyleSettings): SpacingBuilder { // Use `sbX` temporaries to work around // https://youtrack.jetbrains.com/issue/KT-12239 val sb1 = SpacingBuilder(commonSettings) // Rules defined earlier have higher priority. // Beware of comments between blocks! //== some special operators // FIXME(mkaput): Doesn't work well with comments .afterInside(COMMA, ts(BLOCK_FIELDS, ENUM_BODY)).parentDependentLFSpacing(1, 1, true, 1) .afterInside(COMMA, ts(BLOCK_FIELDS, STRUCT_LITERAL_BODY)).parentDependentLFSpacing(1, 1, true, 1) .after(COMMA).spacing(1, 1, 0, true, 0) .before(COMMA).spaceIf(false) .after(COLON).spaceIf(true) .before(COLON).spaceIf(false) .after(SEMICOLON).spaceIf(true) .before(SEMICOLON).spaceIf(false) .afterInside(AND, ts(REF_LIKE_TYPE, SELF_PARAMETER, PAT_REF, VALUE_PARAMETER)).spaces(0) .beforeInside(Q, TRY_EXPR).spaces(0) .afterInside(UNARY_OPS, UNARY_EXPR).spaces(0) // `use ::{bar}` .between(USE, COLONCOLON).spaces(1) //== attributes .aroundInside(ts(SHA, EXCL, LBRACK, RBRACK), ATTRS).spaces(0) .aroundInside(ts(LPAREN, RPAREN), META_ITEM_ARGS).spaces(0) .around(META_ITEM_ARGS).spaces(0) //== empty parens .between(LPAREN, RPAREN).spacing(0, 0, 0, false, 0) .between(LBRACK, RBRACK).spacing(0, 0, 0, false, 0) .between(LBRACE, RBRACE).spacing(0, 0, 0, false, 0) .betweenInside(OR, OR, LAMBDA_EXPR).spacing(0, 0, 0, false, 0) //== paren delimited lists // withinPairInside does not accept TokenSet as parent node set :( // and we cannot create our own, because RuleCondition stuff is private .afterInside(LPAREN, PAREN_LISTS).spacing(0, 0, 0, true, 0) .beforeInside(RPAREN, PAREN_LISTS).spacing(0, 0, 0, true, 0) .afterInside(LBRACK, BRACK_LISTS).spacing(0, 0, 0, true, 0) .beforeInside(RBRACK, BRACK_LISTS).spacing(0, 0, 0, true, 0) .afterInside(LBRACE, BRACE_LISTS).spacing(0, 0, 0, true, 0) .beforeInside(RBRACE, BRACE_LISTS).spacing(0, 0, 0, true, 0) .afterInside(LT, ANGLE_LISTS).spacing(0, 0, 0, true, 0) .beforeInside(GT, ANGLE_LISTS).spacing(0, 0, 0, true, 0) .aroundInside(OR, VALUE_PARAMETER_LIST).spacing(0, 0, 0, false, 0) val sb2 = sb1 //== items .between(VALUE_PARAMETER_LIST, RET_TYPE).spacing(1, 1, 0, true, 0) .before(WHERE_CLAUSE).spacing(1, 1, 0, true, 0) .beforeInside(LBRACE, FLAT_BRACE_BLOCKS).spaces(1) .between(ts(IDENTIFIER, FN), VALUE_PARAMETER_LIST).spaceIf(false) .between(IDENTIFIER, TUPLE_FIELDS).spaces(0) .between(IDENTIFIER, TYPE_PARAMETER_LIST).spaceIf(false) .between(IDENTIFIER, TYPE_ARGUMENT_LIST).spaceIf(false) .between(IDENTIFIER, VALUE_ARGUMENT_LIST).spaceIf(false) .between(TYPE_PARAMETER_LIST, VALUE_PARAMETER_LIST).spaceIf(false) .before(VALUE_ARGUMENT_LIST).spaceIf(false) .between(BINDING_MODE, IDENTIFIER).spaces(1) .between(IMPL, TYPE_PARAMETER_LIST).spaces(0) .afterInside(TYPE_PARAMETER_LIST, IMPL_ITEM).spaces(1) .betweenInside(ts(TYPE_PARAMETER_LIST), TYPES, IMPL_ITEM).spaces(1) // Handling blocks is pretty complicated. Do not tamper with // them too much and let rustfmt do all the pesky work. // Some basic transformation from in-line block to multi-line block // is also performed; see doc of #blockMustBeMultiLine() for details. .afterInside(LBRACE, BLOCK_LIKE).parentDependentLFSpacing(1, 1, true, 0) .beforeInside(RBRACE, BLOCK_LIKE).parentDependentLFSpacing(1, 1, true, 0) .afterInside(LBRACE, FLAT_BRACE_BLOCKS).parentDependentLFSpacing(1, 1, true, 0) .beforeInside(RBRACE, FLAT_BRACE_BLOCKS).parentDependentLFSpacing(1, 1, true, 0) .withinPairInside(LBRACE, RBRACE, PAT_STRUCT).spacing(1, 1, 0, true, 0) .betweenInside(IDENTIFIER, ALIAS, EXTERN_CRATE_ITEM).spaces(1) .betweenInside(IDENTIFIER, TUPLE_FIELDS, ENUM_VARIANT).spaces(0) .betweenInside(IDENTIFIER, VARIANT_DISCRIMINANT, ENUM_VARIANT).spaces(1) return sb2 //== types .afterInside(LIFETIME, REF_LIKE_TYPE).spaceIf(true) .betweenInside(ts(MUL), ts(CONST, MUT), REF_LIKE_TYPE).spaces(0) .before(TYPE_PARAM_BOUNDS).spaces(0) .beforeInside(LPAREN, PATH).spaces(0) .after(TYPE_QUAL).spaces(0) .betweenInside(FOR, LT, FOR_LIFETIMES).spacing(0, 0, 0, true, 0) .around(FOR_LIFETIMES).spacing(1, 1, 0, true, 0) .aroundInside(EQ, ASSOC_TYPE_BINDING).spaces(0) //== expressions .beforeInside(LPAREN, PAT_ENUM).spaces(0) .beforeInside(LBRACK, INDEX_EXPR).spaces(0) .afterInside(VALUE_PARAMETER_LIST, LAMBDA_EXPR).spacing(1, 1, 0, true, 1) .between(MATCH_ARM, MATCH_ARM).spacing(1, 1, if (rustSettings.ALLOW_ONE_LINE_MATCH) 0 else 1, true, 1) .before(ELSE_BRANCH).spacing(1, 1, 0, false, 0) .betweenInside(ELSE, BLOCK, ELSE_BRANCH).spacing(1, 1, 0, false, 0) //== macros .beforeInside(EXCL, MACRO_CALL).spaces(0) .beforeInside(EXCL, MACRO_DEFINITION).spaces(0) .afterInside(EXCL, MACRO_DEFINITION).spaces(1) .betweenInside(IDENTIFIER, MACRO_DEFINITION_BODY, MACRO_DEFINITION).spaces(1) //== rules with very large area of application .around(NO_SPACE_AROUND_OPS).spaces(0) .around(SPACE_AROUND_OPS).spaces(1) .around(RS_KEYWORDS).spaces(1) .applyForEach(BLOCK_LIKE) { before(it).spaces(1) } } fun Block.computeSpacing(child1: Block?, child2: Block, ctx: RsFmtContext): Spacing? { if (child1 is ASTBlock && child2 is ASTBlock) SpacingContext.create(child1, child2, ctx).apply { when { // #[attr]\n<comment>\n => #[attr] <comment>\n etc. psi1 is RsOuterAttr && psi2 is PsiComment -> return createSpacing(1, 1, 0, true, 0) // Determine spacing between macro invocation and it's arguments parentPsi is RsMacroCall && elementType1 == EXCL -> return if (node2.chars.first() == '{' || elementType2 == IDENTIFIER) { createSpacing(1, 1, 0, false, 0) } else { createSpacing(0, 0, 0, false, 0) } // Ensure that each attribute is in separate line; comment aware psi1 is RsOuterAttr && (psi2 is RsOuterAttr || psi1.parent is RsItemElement) || psi1 is PsiComment && (psi2 is RsOuterAttr || psi1.getPrevNonCommentSibling() is RsOuterAttr) -> return lineBreak(keepBlankLines = 0) // Format blank lines between statements (or return expression) ncPsi1 is RsStmt && ncPsi2.isStmtOrExpr -> return lineBreak( keepLineBreaks = ctx.commonSettings.KEEP_LINE_BREAKS, keepBlankLines = ctx.commonSettings.KEEP_BLANK_LINES_IN_CODE) // Format blank lines between impl & trait members parentPsi is RsMembers && ncPsi1 is RsNamedElement && ncPsi2 is RsNamedElement -> return lineBreak( keepLineBreaks = ctx.commonSettings.KEEP_LINE_BREAKS, keepBlankLines = ctx.commonSettings.KEEP_BLANK_LINES_IN_DECLARATIONS) // Format blank lines between top level items ncPsi1.isTopLevelItem && ncPsi2.isTopLevelItem -> return lineBreak( minLineFeeds = 1 + if (!needsBlankLineBetweenItems()) 0 else ctx.rustSettings.MIN_NUMBER_OF_BLANKS_BETWEEN_ITEMS, keepLineBreaks = ctx.commonSettings.KEEP_LINE_BREAKS, keepBlankLines = ctx.commonSettings.KEEP_BLANK_LINES_IN_DECLARATIONS) } } return ctx.spacingBuilder.getSpacing(this, child1, child2) } private data class SpacingContext(val node1: ASTNode, val node2: ASTNode, val psi1: PsiElement, val psi2: PsiElement, val elementType1: IElementType, val elementType2: IElementType, val parentType: IElementType?, val parentPsi: PsiElement?, val ncPsi1: PsiElement, val ncPsi2: PsiElement, val ctx: RsFmtContext) { companion object { fun create(child1: ASTBlock, child2: ASTBlock, ctx: RsFmtContext): SpacingContext { val node1 = child1.node val node2 = child2.node val psi1 = node1.psi val psi2 = node2.psi val elementType1 = psi1.node.elementType val elementType2 = psi2.node.elementType val parentType = node1.treeParent.elementType val parentPsi = psi1.parent val (ncPsi1, ncPsi2) = omitCommentBlocks(node1, psi1, node2, psi2) return SpacingContext(node1, node2, psi1, psi2, elementType1, elementType2, parentType, parentPsi, ncPsi1, ncPsi2, ctx) } /** * Handle blocks of comments to get proper spacing between items and statements */ private fun omitCommentBlocks(node1: ASTNode, psi1: PsiElement, node2: ASTNode, psi2: PsiElement): Pair<PsiElement, PsiElement> = Pair( if (psi1 is PsiComment && node1.hasLineBreakAfterInSameParent()) { psi1.getPrevNonCommentSibling() ?: psi1 } else { psi1 }, if (psi2 is PsiComment && node2.hasLineBreakBeforeInSameParent()) { psi2.getNextNonCommentSibling() ?: psi2 } else { psi2 } ) } } private inline fun SpacingBuilder.applyForEach( tokenSet: TokenSet, block: SpacingBuilder.(IElementType) -> SpacingBuilder): SpacingBuilder { var self = this for (tt in tokenSet.types) { self = block(this, tt) } return self } private fun lineBreak(minLineFeeds: Int = 1, keepLineBreaks: Boolean = true, keepBlankLines: Int = 1): Spacing = createSpacing(0, Int.MAX_VALUE, minLineFeeds, keepLineBreaks, keepBlankLines) private fun ASTNode.hasLineBreakAfterInSameParent(): Boolean = treeNext != null && TreeUtil.findFirstLeaf(treeNext).isWhiteSpaceWithLineBreak() private fun ASTNode.hasLineBreakBeforeInSameParent(): Boolean = treePrev != null && TreeUtil.findLastLeaf(treePrev).isWhiteSpaceWithLineBreak() private fun ASTNode?.isWhiteSpaceWithLineBreak(): Boolean = this != null && elementType == WHITE_SPACE && textContains('\n') private fun SpacingContext.needsBlankLineBetweenItems(): Boolean { if (elementType1 in RS_COMMENTS || elementType2 in RS_COMMENTS) return false // Allow to keep consecutive runs of `use`, `const` or other "one line" items without blank lines if (elementType1 == elementType2 && elementType1 in ONE_LINE_ITEMS) return false // #![deny(missing_docs) // extern crate regex; if (elementType1 == INNER_ATTR && elementType2 == EXTERN_CRATE_ITEM) return false return true }
mit
a8159d4327398e44ed088212b37111dd
45.236364
118
0.638065
4.192219
false
false
false
false
JimSeker/ui
RecyclerViews/CallBacksItemViewDemo_kt/app/src/main/java/edu/cs4730/callbacksitemviewdemo_kt/MainFragment.kt
1
3749
package edu.cs4730.callbacksitemviewdemo_kt import android.content.Context import androidx.recyclerview.widget.RecyclerView import android.view.LayoutInflater import android.view.ViewGroup import android.os.Bundle import android.util.Log import android.view.View import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.DefaultItemAnimator import android.widget.Toast import androidx.fragment.app.Fragment import java.lang.ClassCastException import java.util.* /** * A simple fragment that displays a recyclerview and has a callback * plus creates the listener needed in the adapter. */ class MainFragment : Fragment() { private var mCallback: OntransInteractionCallback? = null private lateinit var mRecyclerView: RecyclerView private lateinit var mAdapter: myAdapter private val TAG = "MainFragment" private val mList: List<String> override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { val myView = inflater.inflate(R.layout.fragment_main, container, false) mRecyclerView = myView.findViewById(R.id.listtrans) mRecyclerView.layoutManager = LinearLayoutManager(requireActivity()) mRecyclerView.itemAnimator = DefaultItemAnimator() mAdapter = myAdapter(mList, R.layout.row_layout, requireActivity()) // mAdapter.setOnItemClickListener { view, id -> // String name = users.get(position).name; // Log.v(TAG, "Listener at $TAG") // Toast.makeText(context, "MainFragment: $id was clicked!", Toast.LENGTH_SHORT).show() // //we could just send the id or in this case get the name as something more useful here. // val name = mAdapter.myList[id.toInt()] // mCallback!!.ontransInteraction(name) // } mAdapter.setOnItemClickListener(object : myAdapter.OnItemClickListener { override fun onItemClick(itemView: View, id: String) { // String name = users.get(position).name; Log.v(TAG, "Listener at $TAG") Toast.makeText(context, "MainFragment: $id was clicked!", Toast.LENGTH_SHORT).show() //we could just send the id or in this case get the name as something more useful here. val name = mAdapter.myList?.get(id.toInt()) if (name != null) { mCallback!!.ontransInteraction(name) } else { //this else should never happen, but kotlin got weird about a null check you don't do in java. mCallback!!.ontransInteraction(id) } } }) //add the adapter to the recyclerview mRecyclerView.adapter = mAdapter return myView } //use this one instead of the one above. Note it's the parameter, context instead of activity. override fun onAttach(context: Context) { super.onAttach(context) mCallback = try { requireActivity() as OntransInteractionCallback } catch (e: ClassCastException) { throw ClassCastException( requireActivity() .toString() + " must implement OnFragmentInteractionListener" ) } } override fun onDetach() { super.onDetach() mCallback = null } //The interface for the call back code that needs to be implemented. interface OntransInteractionCallback { fun ontransInteraction(item: String) } init { mList = Arrays.asList( "Android", "iPhone", "WindowsMobile", "Blackberry", "WebOS", "Ubuntu", "Windows7", "Max OS X", "Linux", "OS/2" ) } }
apache-2.0
f776762eb2386ee4347465d8a46e4fa7
37.265306
114
0.65004
4.837419
false
false
false
false
dataloom/conductor-client
src/main/kotlin/com/openlattice/users/export/UserExportEntity.kt
1
3242
/* * Copyright (C) 2020. OpenLattice, Inc. * * 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/>. * * You can contact the owner of the copyright at [email protected] * * */ package com.openlattice.users.export import com.auth0.json.mgmt.jobs.Job import com.dataloom.mappers.ObjectMappers import okhttp3.* import org.slf4j.LoggerFactory private const val JOBS_PATH = "api/v2/jobs" private const val CONTENT_TYPE_APPLICATION_JSON = "application/json" class UserExportEntity(private val client: OkHttpClient, private val baseUrl: HttpUrl, private val apiToken: String) { private val mapper = ObjectMappers.getJsonMapper() companion object { private val logger = LoggerFactory.getLogger(UserExportJobRequest::class.java) } /** * Submits a user export job to auth0. */ fun submitExportJob(exportJob: UserExportJobRequest): Job { val url = baseUrl .newBuilder() .addPathSegments("$JOBS_PATH/users-exports") .build() .toString() val body = RequestBody.create( MediaType.parse(CONTENT_TYPE_APPLICATION_JSON), mapper.writeValueAsBytes(exportJob) ) val request = Request.Builder() .url(url) .addHeader("Authorization", "Bearer $apiToken") .addHeader("Content-Type", CONTENT_TYPE_APPLICATION_JSON) .post(body) .build() try { val response = client.newCall(request).execute() return mapper.readValue(response.body()?.bytes(), Job::class.java) } catch (ex: Exception) { logger.info("Encountered exception $ex when submitting export job $exportJob.") throw ex } } /** * Retrieves a job result from auth0 by [jobId]. */ fun getJob(jobId: String): UserExportJobResult { val url = baseUrl .newBuilder() .addPathSegments("$JOBS_PATH/$jobId") .build() .toString() val request = Request.Builder() .url(url) .addHeader("Authorization", "Bearer $apiToken") .addHeader("Content-Type", CONTENT_TYPE_APPLICATION_JSON) .get() .build() try { val response = client.newCall(request).execute() return mapper.readValue(response.body()?.bytes(), UserExportJobResult::class.java) } catch (ex: Exception) { logger.info("Encountered exception $ex when trying to get export job $jobId.") throw ex } } }
gpl-3.0
bfe114aed25e41a80ece154781b8f87f
33.870968
118
0.621838
4.566197
false
false
false
false
weibaohui/korm
src/main/kotlin/com/sdibt/korm/core/callbacks/CallBackBatchInsert.kt
1
5439
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.sdibt.korm.core.callbacks import com.sdibt.korm.core.db.DataSourceType import com.sdibt.korm.core.db.KormSqlSession import com.sdibt.korm.core.entity.EntityFieldsCache import java.time.LocalDateTime class CallBackBatchInsert(db: KormSqlSession) { val defaultCallBack = DefaultCallBack.instance.getCallBack(db) fun init() { defaultCallBack.batchInsert().reg("batchSetSqlParam") { batchSetSqlParamCallback(it) } defaultCallBack.batchInsert().reg("beforeBatchInsert") { beforeBatchInsertCallback(it) } defaultCallBack.batchInsert().reg("batchInsertDateTime") { batchInsertDateTimeCallback(it) } defaultCallBack.batchInsert().reg("batchInsertOperator") { batchInsertOperatorCallback(it) } defaultCallBack.batchInsert().reg("batchInsert") { batchInsertCallback(it) } defaultCallBack.batchInsert().reg("sqlProcess") { CallBackCommon().sqlProcess(it) } defaultCallBack.batchInsert().reg("setDataSource") { CallBackCommon().setDataSoure(it) } defaultCallBack.batchInsert().reg("exec") { execCallback(it) } defaultCallBack.batchInsert().reg("afterBatchInsert") { afterBatchInsertCallback(it) } } fun beforeBatchInsertCallback(scope: Scope): Scope { var execScope = scope if (!execScope.hasError) { execScope = scope.callMethod("beforeSave") } if (!execScope.hasError) { execScope = scope.callMethod("beforeInsert") } return execScope } fun afterBatchInsertCallback(scope: Scope): Scope { var execScope = scope if (!execScope.hasError) { execScope = scope.callMethod("afterInsert") } if (!execScope.hasError) { execScope = scope.callMethod("afterSave") } return execScope } fun batchSetSqlParamCallback(scope: Scope): Scope { if (scope.hasError) return scope if (scope.batchEntitys == null || scope.batchEntitys!!.isEmpty()) return scope //单独拿出来作为一个操作 scope.batchEntitys?.forEach { entity -> scope.batchSqlParam.put(entity, entity.sqlParams().toMutableMap()) } return scope } fun batchInsertOperatorCallback(scope: Scope): Scope { if (scope.hasError) return scope if (scope.batchEntitys == null || scope.batchEntitys!!.isEmpty()) return scope val item = EntityFieldsCache.item(scope.entity!!) item.createdBy?.apply { scope.batchSqlParam.forEach { entity, sqlParam -> sqlParam.put("${item.createdBy}", scope.callMethodGetOperator("getOperator")) } } item.createdBy?.apply { scope.batchSqlParam.forEach { entity, sqlParam -> sqlParam.put("${item.updatedBy}", scope.callMethodGetOperator("getOperator")) } } return scope } fun batchInsertDateTimeCallback(scope: Scope): Scope { if (scope.hasError) return scope if (scope.batchEntitys == null || scope.batchEntitys!!.isEmpty()) return scope val item = EntityFieldsCache.item(scope.entity!!) val time = LocalDateTime.now() item.createdBy?.apply { scope.batchSqlParam.forEach { entity, sqlParam -> sqlParam.put("${item.createdAt}", time) } } item.createdBy?.apply { scope.batchSqlParam.forEach { entity, sqlParam -> sqlParam.put("${item.updatedAt}", time) } } return scope } fun batchInsertCallback(scope: Scope): Scope { if (scope.hasError) return scope if (scope.batchEntitys == null || scope.batchEntitys!!.isEmpty()) return scope when (scope.actionType) { ActionType.Entity -> return scope.batchInsertEntity() } return scope } fun execCallback(scope: Scope): Scope { if (scope.hasError) return scope if (scope.batchEntitys == null || scope.batchEntitys!!.isEmpty()) return scope if (scope.db.Error == null) { val (rowsAffected, generatedKeys) = scope.db.executeBatchUpdate( scope.sqlString, scope.batchSqlParam, dsName = scope.dsName, dsType = DataSourceType.WRITE ) scope.rowsAffected = rowsAffected scope.generatedKeys = generatedKeys scope.result = rowsAffected } return scope } }
apache-2.0
41adb6e3b0b8f992bde5314f71666a7b
36.10274
100
0.633192
4.871403
false
false
false
false
http4k/http4k
http4k-core/src/main/kotlin/org/http4k/lens/extractInject.kt
1
1823
package org.http4k.lens interface LensInjector<in IN, in OUT> { /** * Lens operation to set the value into the target */ operator fun <R : OUT> invoke(value: IN, target: R): R /** * Lens operation to set the value into the target. Synomym for invoke(IN, OUT) */ fun <R : OUT> inject(value: IN, target: R): R = invoke(value, target) /** * Lens operation to set the value into the target. Synomym for invoke(IN, OUT) */ operator fun <R : OUT> set(target: R, value: IN) = inject(value, target) /** * Bind this Lens to a value, so we can set it into a target */ infix fun <R : OUT> of(value: IN): (R) -> R = { invoke(value, it) } /** * Restrict the type that this Lens can inject into */ fun <NEXT : OUT> restrictInto(): LensInjector<IN, NEXT> = this } interface LensExtractor<in IN, out OUT> : (IN) -> OUT { /** * Lens operation to get the value from the target * @throws LensFailure if the value could not be retrieved from the target (missing/invalid etc) */ @Throws(LensFailure::class) override operator fun invoke(target: IN): OUT /** * Lens operation to get the value from the target. Synonym for invoke(IN) * @throws LensFailure if the value could not be retrieved from the target (missing/invalid etc) */ @Throws(LensFailure::class) fun extract(target: IN): OUT = invoke(target) /** * Lens operation to get the value from the target. Synonym for invoke(IN) */ operator fun <R : IN> get(target: R) = extract(target) /** * Restrict the type that this Lens can extract from */ fun <NEXT : IN> restrictFrom(): LensExtractor<NEXT, OUT> = this } interface LensInjectorExtractor<IN, OUT> : LensExtractor<IN, OUT>, LensInjector<OUT, IN>
apache-2.0
b71977c8299dddbad632298b82d293af
31.553571
100
0.630828
3.758763
false
false
false
false
geckour/Egret
app/src/main/java/com/geckour/egret/view/fragment/AccountBlockFragment.kt
1
5766
package com.geckour.egret.view.fragment import android.databinding.DataBindingUtil import android.os.Bundle import android.support.design.widget.FloatingActionButton import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.MotionEvent import android.view.View import android.view.ViewGroup import com.geckour.egret.R import com.geckour.egret.api.MastodonClient import com.geckour.egret.api.model.Account import com.geckour.egret.databinding.FragmentBlockAccountBinding import com.geckour.egret.util.Common import com.geckour.egret.view.activity.MainActivity import com.geckour.egret.view.adapter.BlockAccountAdapter import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.schedulers.Schedulers import timber.log.Timber class AccountBlockFragment: BaseFragment() { lateinit private var binding: FragmentBlockAccountBinding private val adapter: BlockAccountAdapter by lazy { BlockAccountAdapter() } private val preItems: ArrayList<Account> = ArrayList() private var onTop = true private var inTouch = false private var maxId: Long = -1 private var sinceId: Long = -1 companion object { val TAG: String = this::class.java.simpleName fun newInstance(): AccountBlockFragment = AccountBlockFragment().apply { } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) } override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? { binding = DataBindingUtil.inflate(inflater, R.layout.fragment_block_account, container, false) return binding.root } override fun onViewCreated(view: View?, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val helper = Common.getSwipeToDismissTouchHelperForBlockAccount(adapter) helper.attachToRecyclerView(binding.recyclerView) binding.recyclerView.addItemDecoration(helper) binding.recyclerView.adapter = adapter binding.recyclerView.setOnTouchListener { _, event -> when (event.action) { MotionEvent.ACTION_DOWN, MotionEvent.ACTION_POINTER_DOWN -> { inTouch = true } MotionEvent.ACTION_UP, MotionEvent.ACTION_POINTER_UP -> { inTouch = false } } false } binding.recyclerView.addOnScrollListener(object: RecyclerView.OnScrollListener() { override fun onScrolled(recyclerView: RecyclerView?, dx: Int, dy: Int) { super.onScrolled(recyclerView, dx, dy) val scrollY: Int = recyclerView?.computeVerticalScrollOffset() ?: -1 onTop = scrollY == 0 || onTop && !(inTouch && scrollY > 0) if (!onTop) { val y = scrollY + (recyclerView?.height ?: -1) val h = recyclerView?.computeVerticalScrollRange() ?: -1 if (y == h) { bindAccounts(true) } } } }) binding.swipeRefreshLayout.apply { setColorSchemeResources(R.color.colorAccent) setOnRefreshListener { bindAccounts() } } } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) bindAccounts() } override fun onResume() { super.onResume() if (activity is MainActivity) ((activity as MainActivity).findViewById(R.id.fab) as FloatingActionButton?)?.hide() } override fun onPause() { super.onPause() removeAccounts(adapter.getItems()) } fun bindAccounts(loadNext: Boolean = false) { if (loadNext && maxId == -1L) return Common.resetAuthInfo()?.let { domain -> MastodonClient(domain).getBlockedUsersWithHeaders(maxId = if (loadNext) maxId else null, sinceId = if (!loadNext && sinceId != -1L) sinceId else null) .subscribeOn(Schedulers.newThread()) .observeOn(AndroidSchedulers.mainThread()) .compose(bindToLifecycle()) .subscribe({ it.response()?.let { adapter.addAllItems(it.body()) preItems.addAll(it.body()) it.headers().get("Link")?.let { maxId = Common.getMaxIdFromLinkString(it) sinceId = Common.getSinceIdFromLinkString(it) } toggleRefreshIndicatorState(false) } }, { throwable -> throwable.printStackTrace() toggleRefreshIndicatorState(false) }) } } fun removeAccounts(items: List<Account>) { val shouldRemoveItems = preItems.filter { items.none { item -> it.id == item.id } } Common.resetAuthInfo()?.let { domain -> shouldRemoveItems.forEach { MastodonClient(domain).unBlockAccount(it.id) .subscribeOn(Schedulers.newThread()) .observeOn(AndroidSchedulers.mainThread()) .subscribe({ Timber.d("unblocked account: ${it.accountId}") }, Throwable::printStackTrace) } // Snackbar.make(binding.root, "hoge", Snackbar.LENGTH_SHORT).show() } } fun toggleRefreshIndicatorState(show: Boolean) = Common.toggleRefreshIndicatorState(binding.swipeRefreshLayout, show) }
gpl-3.0
54dba4c577b15010b5ed07bf8f6f95f8
36.940789
162
0.61221
5.232305
false
false
false
false
czyzby/gdx-setup
src/main/kotlin/com/github/czyzby/setup/data/platforms/iOS.kt
1
5396
package com.github.czyzby.setup.data.platforms import com.github.czyzby.setup.data.files.CopiedFile import com.github.czyzby.setup.data.files.SourceFile import com.github.czyzby.setup.data.files.path import com.github.czyzby.setup.data.gradle.GradleFile import com.github.czyzby.setup.data.project.Project import com.github.czyzby.setup.views.GdxPlatform /** * Represents iOS backend. * @author MJ */ @GdxPlatform class iOS : Platform { companion object { const val ID = "ios" } override val id = ID override fun createGradleFile(project: Project): GradleFile = iOSGradleFile(project) override fun initiate(project: Project) { project.rootGradle.buildDependencies.add("\"com.mobidevelop.robovm:robovm-gradle-plugin:\$robovmVersion\"") project.properties["robovmVersion"] = project.advanced.robovmVersion // Including RoboVM config files: project.files.add(CopiedFile(projectName = ID, path = "Info.plist.xml", original = path("generator", "ios", "Info.plist.xml"))) project.files.add(SourceFile(projectName = ID, fileName = "robovm.properties", content = """app.version=${project.advanced.version} app.id=${project.basic.rootPackage} app.mainclass=${project.basic.rootPackage}.ios.IOSLauncher app.executable=IOSLauncher app.build=1 app.name=${project.basic.name}""")) project.files.add(SourceFile(projectName = ID, fileName = "robovm.xml", content = """<config> <executableName>${'$'}{app.executable}</executableName> <mainClass>${'$'}{app.mainclass}</mainClass> <os>ios</os> <arch>thumbv7</arch> <target>ios</target> <iosInfoPList>Info.plist.xml</iosInfoPList> <resources> <resource> <directory>../assets</directory> <includes> <include>**</include> </includes> <skipPngCrush>true</skipPngCrush> </resource> <resource> <directory>data</directory> </resource> </resources> <forceLinkClasses> <pattern>com.badlogic.gdx.scenes.scene2d.ui.*</pattern> <pattern>com.badlogic.gdx.graphics.g3d.particles.**</pattern> <pattern>com.android.okhttp.HttpHandler</pattern> <pattern>com.android.okhttp.HttpsHandler</pattern> <pattern>com.android.org.conscrypt.**</pattern> <pattern>com.android.org.bouncycastle.jce.provider.BouncyCastleProvider</pattern> <pattern>com.android.org.bouncycastle.jcajce.provider.keystore.BC${'$'}Mappings</pattern> <pattern>com.android.org.bouncycastle.jcajce.provider.keystore.bc.BcKeyStoreSpi</pattern> <pattern>com.android.org.bouncycastle.jcajce.provider.keystore.bc.BcKeyStoreSpi${'$'}Std</pattern> <pattern>com.android.org.bouncycastle.jce.provider.PKIXCertPathValidatorSpi</pattern> <pattern>com.android.org.bouncycastle.crypto.digests.AndroidDigestFactoryOpenSSL</pattern> <pattern>org.apache.harmony.security.provider.cert.DRLCertFactory</pattern> <pattern>org.apache.harmony.security.provider.crypto.CryptoProvider</pattern> </forceLinkClasses> <libs> <lib>z</lib> </libs> <frameworks> <framework>UIKit</framework> <framework>OpenGLES</framework> <framework>QuartzCore</framework> <framework>CoreGraphics</framework> <framework>OpenAL</framework> <framework>AudioToolbox</framework> <framework>AVFoundation</framework> </frameworks> </config>""")) // Copying data images: arrayOf("Default.png", "[email protected]", "Default@2x~ipad.png", "[email protected]", "[email protected]", "[email protected]", "Default-1024w-1366h@2x~ipad.png", "Default~ipad.png", "Icon.png", "[email protected]", "Icon-72.png", "[email protected]").forEach { project.files.add(CopiedFile(projectName = ID, path = path("data", it), original = path("generator", "ios", "data", it))) } // Including reflected classes: if (project.reflectedClasses.isNotEmpty() || project.reflectedPackages.isNotEmpty()) { project.files.add(SourceFile(projectName = ID, sourceFolderPath = path("src", "main", "resources"), packageName = "META-INF.robovm.ios", fileName = "robovm.xml", content = """<config> <forceLinkClasses> ${project.reflectedPackages.joinToString(separator = "\n") { " <pattern>${it}.**</pattern>" }} ${project.reflectedClasses.joinToString(separator = "\n") { " <pattern>${it}</pattern>" }} </forceLinkClasses> </config>""")) } } } class iOSGradleFile(val project: Project) : GradleFile(iOS.ID) { init { dependencies.add("project(':${Core.ID}')") addDependency("com.mobidevelop.robovm:robovm-rt:\$robovmVersion") addDependency("com.mobidevelop.robovm:robovm-cocoatouch:\$robovmVersion") addDependency("com.badlogicgames.gdx:gdx-backend-robovm:\$gdxVersion") addDependency("com.badlogicgames.gdx:gdx-platform:\$gdxVersion:natives-ios") } override fun getContent() = """apply plugin: 'robovm' [compileJava, compileTestJava]*.options*.encoding = 'UTF-8' ext { mainClassName = "${project.basic.rootPackage}.ios.IOSLauncher" } launchIPhoneSimulator.dependsOn build launchIPadSimulator.dependsOn build launchIOSDevice.dependsOn build createIPA.dependsOn build eclipse.project { name = appName + "-ios" natures 'org.robovm.eclipse.RoboVMNature' } dependencies { ${joinDependencies(dependencies)}} """ }
unlicense
68a9a5af268e2cc62a0d35f725424679
38.676471
139
0.697739
3.688312
false
false
false
false
infinum/android_dbinspector
dbinspector/src/main/kotlin/com/infinum/dbinspector/ui/shared/delegates/LifecycleConnectionDelegate.kt
1
2158
package com.infinum.dbinspector.ui.shared.delegates import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import androidx.fragment.app.Fragment import androidx.lifecycle.Lifecycle import androidx.lifecycle.LifecycleObserver import androidx.lifecycle.LifecycleOwner import com.infinum.dbinspector.ui.Presentation import com.infinum.dbinspector.ui.shared.base.lifecycle.LifecycleConnection import kotlin.properties.ReadOnlyProperty import kotlin.reflect.KProperty internal class LifecycleConnectionDelegate( private val owner: LifecycleOwner, val lifecycleConnectionFactory: (Bundle?) -> LifecycleConnection ) : ReadOnlyProperty<LifecycleOwner, LifecycleConnection>, LifecycleObserver { private var connection: LifecycleConnection? = null override fun getValue(thisRef: LifecycleOwner, property: KProperty<*>): LifecycleConnection { val existingConnection = connection return when { existingConnection != null -> existingConnection else -> { if ( owner .lifecycle .currentState .isAtLeast(Lifecycle.State.INITIALIZED).not() ) { error("Owner has not passed created yet.") } val extras = when (thisRef) { is Fragment -> (thisRef as? Fragment)?.activity?.intent?.extras is AppCompatActivity -> thisRef.intent?.extras else -> null } lifecycleConnectionFactory(extras).also { this.connection = it } } } } } internal fun LifecycleOwner.lifecycleConnection( lifecycleConnectionFactory: (Bundle?) -> LifecycleConnection = { LifecycleConnection( databaseName = it?.getString(Presentation.Constants.Keys.DATABASE_NAME), databasePath = it?.getString(Presentation.Constants.Keys.DATABASE_PATH), schemaName = it?.getString(Presentation.Constants.Keys.SCHEMA_NAME) ) } ) = LifecycleConnectionDelegate(this, lifecycleConnectionFactory)
apache-2.0
1e807046aeb5b18f5f830dc573f03d97
36.859649
97
0.66126
5.785523
false
false
false
false
programingjd/okserver
src/coroutines/kotlin/info/jdavid/ok/server/CoroutineDispatcher.kt
1
5079
package info.jdavid.ok.server import kotlinx.coroutines.experimental.launch import kotlinx.coroutines.experimental.nio.aAccept import kotlinx.coroutines.experimental.runBlocking import java.net.InetAddress import java.net.InetSocketAddress import java.net.StandardSocketOptions import java.nio.channels.AlreadyBoundException import java.nio.channels.AsynchronousServerSocketChannel import java.nio.channels.AsynchronousSocketChannel import kotlin.concurrent.thread import info.jdavid.ok.server.Logger.logger import kotlinx.coroutines.experimental.nio.aRead import okio.BufferedSource import okio.ByteString import java.io.IOException import java.net.SocketTimeoutException import java.nio.charset.Charset import java.util.concurrent.TimeUnit class CoroutineDispatcher : Dispatcher<AsynchronousServerSocketChannel>() { override fun initSockets(insecurePort: Int, securePort: Int, https: Https?, address: InetAddress?) { if (insecurePort > 0) { val insecureSocket = AsynchronousServerSocketChannel.open() insecureSocket.setOption(StandardSocketOptions.SO_REUSEADDR, true) try { insecureSocket.bind(InetSocketAddress(address, insecurePort)) } catch (e: AlreadyBoundException) { logger.warn("Could not bind to port ${insecurePort}.", e) } this.insecureSocket = insecureSocket } if (securePort > 0 && https != null) { val secureSocket = AsynchronousServerSocketChannel.open() secureSocket.setOption(StandardSocketOptions.SO_REUSEADDR, true) try { secureSocket.bind(InetSocketAddress(address, securePort)) } catch (e: AlreadyBoundException) { logger.warn("Could not bind to port ${securePort}.", e) } this.secureSocket = secureSocket } } override fun start() {} override fun shutdown() {} override fun loop(socket: AsynchronousServerSocketChannel?, secure: Boolean, insecureOnly: Boolean, https: Https?, hostname: String?, maxRequestSize: Long, keepAliveStrategy: KeepAliveStrategy, requestHandler: RequestHandler) { thread { if (socket != null) { runBlocking { socket.use { while (true) { try { val channel = socket.aAccept() launch(context) { channel.use { Request(channel, secure, insecureOnly, https, hostname, maxRequestSize, keepAliveStrategy, requestHandler).serve() } } } catch (e: IOException) { if (!socket.isOpen()) break logger.warn(secure.ifElse("HTTPS", "HTTP"), e) } } } } } }.start() } private fun <T> Boolean.ifElse(ifValue: T, elseValue: T): T { return if (this) ifValue else elseValue } private class Request(private val channel: AsynchronousSocketChannel, private val secure: Boolean, private val insecureOnly: Boolean, private val https: Https?, private val hostname: String?, private val maxRequestSize: Long, private val keepAliveStrategy: KeepAliveStrategy, private val requestHandler: RequestHandler) { suspend fun serve() { if (secure) { assert(https != null) } else { serveHttp1(channel, false, insecureOnly) } } private fun useSocket(reuse: Int, strategy: KeepAliveStrategy): Boolean { val timeout = strategy.timeout(reuse) if (timeout <= 0) { return reuse == 0 } else { return true } } suspend fun serveHttp1(channel: AsynchronousSocketChannel, secure: Boolean, insecureOnly: Boolean) { try { val clientIp = (channel.remoteAddress as InetSocketAddress).address.hostAddress var reuseCounter = 0 while (useSocket(reuseCounter++, keepAliveStrategy)) { var availableRequestSize = maxRequestSize // todo } } catch (ignore: SocketTimeoutException) {} catch (e: Exception) { logger.warn(e.message, e) } } } private val ASCII = Charset.forName("ASCII") private fun crlf(input: BufferedSource, limit: Long): Long { var index: Long = 0L while (true) { index = input.indexOf('\r'.toByte(), index, limit) if (index == -1L) return -1L if (input.indexOf('\n'.toByte(), index + 1L, index + 2L) != -1L) return index ++index } } @Throws(IOException::class) private fun readRequestLine(input: BufferedSource): ByteString? { val index = crlf(input, 4096) if (index == -1L) return null val requestLine = input.readByteString(index) input.skip(2L) return requestLine } }
apache-2.0
08e0ed6941275249dda5156feab1bcb1
30.351852
102
0.609569
4.888354
false
false
false
false
alex-tavella/MooV
feature/movie-details/impl/src/main/java/br/com/moov/moviedetails/viewmodel/MovieDetailViewModel.kt
1
3836
/* * Copyright 2020 Alex Almeida Tavella * * 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 br.com.moov.moviedetails.viewmodel import androidx.lifecycle.ViewModel import br.com.core.android.BaseViewModel import br.com.core.android.UiEvent import br.com.core.android.UiModel import br.com.core.android.ViewModelKey import br.com.moov.bookmark.movie.BookmarkMovieUseCase import br.com.moov.bookmark.movie.UnBookmarkMovieUseCase import br.com.moov.moviedetails.di.MovieDetailScope import br.com.moov.moviedetails.domain.GetMovieDetailUseCase import br.com.moov.moviedetails.domain.MovieDetail import com.squareup.anvil.annotations.ContributesMultibinding import javax.inject.Inject private const val ERROR_MESSAGE_DEFAULT = "An error has occurred, please try again later" @ContributesMultibinding(MovieDetailScope::class, ViewModel::class) @ViewModelKey(MovieDetailViewModel::class) class MovieDetailViewModel @Inject constructor( private val getMovieDetail: GetMovieDetailUseCase, private val bookmarkMovie: BookmarkMovieUseCase, private val unBookmarkMovie: UnBookmarkMovieUseCase ) : BaseViewModel<MovieDetailUiEvent, MovieDetailUiModel>() { override suspend fun processUiEvent(uiEvent: MovieDetailUiEvent) { when (uiEvent) { is MovieDetailUiEvent.EnterScreen -> { handleEnterScreen(uiEvent) } is MovieDetailUiEvent.MovieFavoritedUiEvent -> { handleMovieFavorited(uiEvent) } } } private suspend fun handleEnterScreen(uiEvent: MovieDetailUiEvent.EnterScreen) { emitUiModel(MovieDetailUiModel(loading = true)) val result = getMovieDetail(uiEvent.movieId) emitUiModel( MovieDetailUiModel( loading = false, movie = result.getOrNull(), error = getMovieDetailsErrorMessage() ) ) } private fun getMovieDetailsErrorMessage(): Throwable { return Exception(ERROR_MESSAGE_DEFAULT) } private suspend fun handleMovieFavorited(uiEvent: MovieDetailUiEvent.MovieFavoritedUiEvent) { val result = if (uiEvent.favorited) { bookmarkMovie(uiEvent.movie.id) .map { uiEvent.movie.copy(isBookmarked = true) } .mapError { bookmarkFailErrorMessage() } } else { unBookmarkMovie(uiEvent.movie.id) .map { uiEvent.movie.copy(isBookmarked = false) } .mapError { unBookmarkFailErrorMessage() } } emitUiModel( MovieDetailUiModel( movie = result.getOrNull(), error = result.errorOrNull() ) ) } private fun bookmarkFailErrorMessage(): Throwable { return Exception(ERROR_MESSAGE_DEFAULT) } private fun unBookmarkFailErrorMessage(): Throwable { return Exception(ERROR_MESSAGE_DEFAULT) } } class MovieDetailUiModel( val loading: Boolean = false, val movie: MovieDetail? = null, error: Throwable? = null ) : UiModel(error) sealed class MovieDetailUiEvent : UiEvent() { class EnterScreen(val movieId: Int) : MovieDetailUiEvent() data class MovieFavoritedUiEvent( val movie: MovieDetail, val favorited: Boolean ) : MovieDetailUiEvent() }
apache-2.0
188ca002dbc9d183948569e1555d5f8e
34.850467
97
0.695255
4.807018
false
false
false
false
recurly/recurly-client-android
AndroidSdk/src/main/java/com/recurly/androidsdk/presentation/view/RecurlyCVV.kt
1
8510
package com.recurly.androidsdk.presentation.view import android.content.Context import android.content.res.ColorStateList import android.graphics.Typeface import android.text.Editable import android.text.InputFilter import android.text.TextWatcher import android.util.AttributeSet import android.view.LayoutInflater import androidx.constraintlayout.widget.ConstraintLayout import androidx.core.content.ContextCompat import com.recurly.androidsdk.R import com.recurly.androidsdk.data.model.CreditCardData import com.recurly.androidsdk.databinding.RecurlyCvvCodeBinding import com.recurly.androidsdk.domain.RecurlyDataFormatter import com.recurly.androidsdk.domain.RecurlyInputValidator class RecurlyCVV @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0 ) : ConstraintLayout(context, attrs, defStyleAttr) { private var textColor: Int private var errorTextColor: Int private var hintColor: Int private var boxColor: Int private var errorBoxColor: Int private var focusedBoxColor: Int private var correctCVVInput = true private val maxCVVLength: Int = 3 private var binding: RecurlyCvvCodeBinding = RecurlyCvvCodeBinding.inflate(LayoutInflater.from(context), this) /** * All the color are initialized as Int, this is to make ir easier to handle the texts colors change */ init { layoutParams = LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT) textColor = ContextCompat.getColor(context, R.color.recurly_black) errorTextColor = ContextCompat.getColor(context, R.color.recurly_error_red) boxColor = ContextCompat.getColor(context, R.color.recurly_gray_stroke) errorBoxColor = ContextCompat.getColor(context, R.color.recurly_error_red_blur) focusedBoxColor = ContextCompat.getColor(context, R.color.recurly_focused_blue) hintColor = ContextCompat.getColor(context, R.color.recurly_gray_stroke) cvvInputValidator() } /** * This fun changes the placeholder text according to the parameter received * @param cvvPlaceholder Placeholder text for cvv code field */ fun setPlaceholder(cvvPlaceholder: String) { if (!cvvPlaceholder.trim().isEmpty()) binding.recurlyTextInputLayoutIndividualCvvCode.hint = cvvPlaceholder } /** * This fun changes the placeholder color according to the parameter received * @param color you should sent the color like ContextCompat.getColor(context, R.color.your-color) */ fun setPlaceholderColor(color: Int) { if (RecurlyInputValidator.validateColor(color)) { hintColor = color var colorState: ColorStateList = RecurlyInputValidator.getColorState(color) binding.recurlyTextInputLayoutIndividualCvvCode.placeholderTextColor = colorState } } /** * This fun changes the text color according to the parameter received * @param color you should sent the color like ContextCompat.getColor(context, R.color.your-color) */ fun setTextColor(color: Int) { if (RecurlyInputValidator.validateColor(color)) { textColor = color binding.recurlyTextInputEditIndividualCvvCode.setTextColor(color) } } /** * This fun changes the text color according to the parameter received * @param color you should sent the color like ContextCompat.getColor(context, R.color.your-color) */ fun setTextErrorColor(color: Int) { if (RecurlyInputValidator.validateColor(color)) errorTextColor = color } /** * This fun changes the font of the input field according to the parameter received * @param newFont non null Typeface * @param style style as int */ fun setFont(newFont: Typeface, style: Int) { binding.recurlyTextInputEditIndividualCvvCode.setTypeface(newFont, style) binding.recurlyTextInputLayoutIndividualCvvCode.typeface = newFont } /** * This fun validates if the input is complete and is valid, this means it follows a cvv code digits length * @return true if the input is correctly filled, false if it is not */ fun validateData(): Boolean { correctCVVInput = binding.recurlyTextInputEditIndividualCvvCode.text.toString().length == maxCVVLength changeColors() return correctCVVInput } /** * This fun will highlight the CVV as it have an error, you can use this * for tokenization validations or if you need to highlight this field with an error */ fun setCvvError(){ correctCVVInput = false changeColors() } /** * This fun changes the text color and the field highlight according at if it is correct or not */ private fun changeColors() { if (correctCVVInput) { binding.recurlyTextInputLayoutIndividualCvvCode.error = null binding.recurlyTextInputEditIndividualCvvCode.setTextColor(textColor) } else { binding.recurlyTextInputLayoutIndividualCvvCode.error = " " binding.recurlyTextInputEditIndividualCvvCode.setTextColor( errorTextColor ) } } /** *This is an internal fun that validates the input as it is introduced, it is separated in two parts: * If it is focused or not, and if it has text changes. * * When it has text changes calls to different input validators from RecurlyInputValidator * and according to the response of the input validator it replaces the text and * changes text color according if has errors or not * * When it changes the focus of the view it validates if the field is correctly filled, and then * saves the input data */ private fun cvvInputValidator() { binding.recurlyTextInputEditIndividualCvvCode.addTextChangedListener(object : TextWatcher { override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) { binding.recurlyTextInputEditIndividualCvvCode.filters = arrayOf<InputFilter>(InputFilter.LengthFilter(CreditCardData.getCvvLength())) binding.recurlyTextInputLayoutIndividualCvvCode.error = null binding.recurlyTextInputEditIndividualCvvCode.setTextColor(textColor) } override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) { } override fun afterTextChanged(s: Editable?) { if (s != null) { if (s.toString().isNotEmpty()) { val oldValue = s.toString() val formattedCVV = RecurlyInputValidator.regexSpecialCharacters( s.toString(), "0-9" ) binding.recurlyTextInputEditIndividualCvvCode.removeTextChangedListener(this) s.replace(0, oldValue.length, formattedCVV) binding.recurlyTextInputEditIndividualCvvCode.addTextChangedListener(this) correctCVVInput = formattedCVV.length == CreditCardData.getCvvLength() CreditCardData.setCvvCode( RecurlyDataFormatter.getCvvCode( formattedCVV, correctCVVInput ) ) } else { correctCVVInput = true changeColors() } } } }) binding.recurlyTextInputEditIndividualCvvCode.setOnFocusChangeListener { v, hasFocus -> if (!hasFocus) { CreditCardData.setCvvCode( RecurlyDataFormatter.getCvvCode( binding.recurlyTextInputEditIndividualCvvCode.text.toString(), correctCVVInput ) ) changeColors() } else { binding.recurlyTextInputEditIndividualCvvCode.filters = arrayOf<InputFilter>(InputFilter.LengthFilter(CreditCardData.getCvvLength())) } } } }
mit
371f70846b266673f3a231e331bc378a
40.348259
111
0.643361
5.673333
false
false
false
false