repo_name
stringlengths
7
79
path
stringlengths
8
206
copies
stringclasses
36 values
size
stringlengths
2
6
content
stringlengths
55
523k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
7.18
99.5
line_max
int64
16
979
alpha_frac
float64
0.3
0.87
ratio
float64
2.01
8.07
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
farmerbb/Notepad
app/src/main/java/com/farmerbb/notepad/ui/previews/EditNotePreview.kt
1
2411
/* Copyright 2021 Braden Farmer * * 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.farmerbb.notepad.ui.previews import androidx.compose.material.MaterialTheme import androidx.compose.material.Scaffold import androidx.compose.material.TopAppBar import androidx.compose.runtime.Composable import androidx.compose.ui.res.colorResource import androidx.compose.ui.tooling.preview.Preview import com.farmerbb.notepad.R import com.farmerbb.notepad.model.Note import com.farmerbb.notepad.model.NoteContents import com.farmerbb.notepad.model.NoteMetadata import com.farmerbb.notepad.ui.components.AppBarText import com.farmerbb.notepad.ui.components.BackButton import com.farmerbb.notepad.ui.components.DeleteButton import com.farmerbb.notepad.ui.components.NoteViewEditMenu import com.farmerbb.notepad.ui.components.SaveButton import com.farmerbb.notepad.ui.content.EditNoteContent import java.util.Date @Composable private fun EditNote(note: Note) { Scaffold( topBar = { TopAppBar( navigationIcon = { BackButton() }, title = { AppBarText(note.title) }, backgroundColor = colorResource(id = R.color.primary), actions = { SaveButton() DeleteButton() NoteViewEditMenu() } ) }, content = { EditNoteContent(note.text) } ) } @Preview @Composable fun EditNotePreview() = MaterialTheme { EditNote( note = Note( metadata = NoteMetadata( metadataId = -1, title = "Title", date = Date(), hasDraft = false ), contents = NoteContents( contentsId = -1, text = "This is some text", draftText = null ) ) ) }
apache-2.0
1fc6a3add1a66f0ba0b06206d30d1df9
31.16
75
0.651597
4.506542
false
false
false
false
fhanik/spring-security
config/src/main/kotlin/org/springframework/security/config/web/servlet/AuthorizeRequestsDsl.kt
3
10630
/* * Copyright 2002-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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 org.springframework.security.config.web.servlet import org.springframework.http.HttpMethod import org.springframework.security.config.annotation.web.builders.HttpSecurity import org.springframework.security.config.annotation.web.configurers.ExpressionUrlAuthorizationConfigurer import org.springframework.security.web.util.matcher.AnyRequestMatcher import org.springframework.security.web.util.matcher.RequestMatcher import org.springframework.util.ClassUtils /** * A Kotlin DSL to configure [HttpSecurity] request authorization using idiomatic Kotlin code. * * @author Eleftheria Stein * @since 5.3 */ class AuthorizeRequestsDsl : AbstractRequestMatcherDsl() { private val authorizationRules = mutableListOf<AuthorizationRule>() private val HANDLER_MAPPING_INTROSPECTOR = "org.springframework.web.servlet.handler.HandlerMappingIntrospector" private val MVC_PRESENT = ClassUtils.isPresent( HANDLER_MAPPING_INTROSPECTOR, AuthorizeRequestsDsl::class.java.classLoader) private val PATTERN_TYPE = if (MVC_PRESENT) PatternType.MVC else PatternType.ANT /** * Adds a request authorization rule. * * @param matches the [RequestMatcher] to match incoming requests against * @param access the SpEL expression to secure the matching request * (i.e. "hasAuthority('ROLE_USER') and hasAuthority('ROLE_SUPER')") */ fun authorize(matches: RequestMatcher = AnyRequestMatcher.INSTANCE, access: String = "authenticated") { authorizationRules.add(MatcherAuthorizationRule(matches, access)) } /** * Adds a request authorization rule for an endpoint matching the provided * pattern. * If Spring MVC is on the classpath, it will use an MVC matcher. * If Spring MVC is not an the classpath, it will use an ant matcher. * The MVC will use the same rules that Spring MVC uses for matching. * For example, often times a mapping of the path "/path" will match on * "/path", "/path/", "/path.html", etc. * If the current request will not be processed by Spring MVC, a reasonable default * using the pattern as an ant pattern will be used. * * @param pattern the pattern to match incoming requests against. * @param access the SpEL expression to secure the matching request * (i.e. "hasAuthority('ROLE_USER') and hasAuthority('ROLE_SUPER')") */ fun authorize(pattern: String, access: String = "authenticated") { authorizationRules.add(PatternAuthorizationRule(pattern = pattern, patternType = PATTERN_TYPE, rule = access)) } /** * Adds a request authorization rule for an endpoint matching the provided * pattern. * If Spring MVC is on the classpath, it will use an MVC matcher. * If Spring MVC is not an the classpath, it will use an ant matcher. * The MVC will use the same rules that Spring MVC uses for matching. * For example, often times a mapping of the path "/path" will match on * "/path", "/path/", "/path.html", etc. * If the current request will not be processed by Spring MVC, a reasonable default * using the pattern as an ant pattern will be used. * * @param method the HTTP method to match the income requests against. * @param pattern the pattern to match incoming requests against. * @param access the SpEL expression to secure the matching request * (i.e. "hasAuthority('ROLE_USER') and hasAuthority('ROLE_SUPER')") */ fun authorize(method: HttpMethod, pattern: String, access: String = "authenticated") { authorizationRules.add(PatternAuthorizationRule(pattern = pattern, patternType = PATTERN_TYPE, httpMethod = method, rule = access)) } /** * Adds a request authorization rule for an endpoint matching the provided * pattern. * If Spring MVC is on the classpath, it will use an MVC matcher. * If Spring MVC is not an the classpath, it will use an ant matcher. * The MVC will use the same rules that Spring MVC uses for matching. * For example, often times a mapping of the path "/path" will match on * "/path", "/path/", "/path.html", etc. * If the current request will not be processed by Spring MVC, a reasonable default * using the pattern as an ant pattern will be used. * * @param pattern the pattern to match incoming requests against. * @param servletPath the servlet path to match incoming requests against. This * only applies when using an MVC pattern matcher. * @param access the SpEL expression to secure the matching request * (i.e. "hasAuthority('ROLE_USER') and hasAuthority('ROLE_SUPER')") */ fun authorize(pattern: String, servletPath: String, access: String = "authenticated") { authorizationRules.add(PatternAuthorizationRule(pattern = pattern, patternType = PATTERN_TYPE, servletPath = servletPath, rule = access)) } /** * Adds a request authorization rule for an endpoint matching the provided * pattern. * If Spring MVC is on the classpath, it will use an MVC matcher. * If Spring MVC is not an the classpath, it will use an ant matcher. * The MVC will use the same rules that Spring MVC uses for matching. * For example, often times a mapping of the path "/path" will match on * "/path", "/path/", "/path.html", etc. * If the current request will not be processed by Spring MVC, a reasonable default * using the pattern as an ant pattern will be used. * * @param method the HTTP method to match the income requests against. * @param pattern the pattern to match incoming requests against. * @param servletPath the servlet path to match incoming requests against. This * only applies when using an MVC pattern matcher. * @param access the SpEL expression to secure the matching request * (i.e. "hasAuthority('ROLE_USER') and hasAuthority('ROLE_SUPER')") */ fun authorize(method: HttpMethod, pattern: String, servletPath: String, access: String = "authenticated") { authorizationRules.add(PatternAuthorizationRule(pattern = pattern, patternType = PATTERN_TYPE, servletPath = servletPath, httpMethod = method, rule = access)) } /** * Specify that URLs require a particular authority. * * @param authority the authority to require (i.e. ROLE_USER, ROLE_ADMIN, etc). * @return the SpEL expression "hasAuthority" with the given authority as a * parameter */ fun hasAuthority(authority: String) = "hasAuthority('$authority')" /** * Specify that URLs requires any of a number authorities. * * @param authorities the authorities to require (i.e. ROLE_USER, ROLE_ADMIN, etc). * @return the SpEL expression "hasAnyAuthority" with the given authorities as a * parameter */ fun hasAnyAuthority(vararg authorities: String): String { val anyAuthorities = authorities.joinToString("','") return "hasAnyAuthority('$anyAuthorities')" } /** * Specify that URLs require a particular role. * * @param role the role to require (i.e. USER, ADMIN, etc). * @return the SpEL expression "hasRole" with the given role as a * parameter */ fun hasRole(role: String) = "hasRole('$role')" /** * Specify that URLs requires any of a number roles. * * @param roles the roles to require (i.e. USER, ADMIN, etc). * @return the SpEL expression "hasAnyRole" with the given roles as a * parameter */ fun hasAnyRole(vararg roles: String): String { val anyRoles = roles.joinToString("','") return "hasAnyRole('$anyRoles')" } /** * Specify that URLs are allowed by anyone. */ val permitAll = "permitAll" /** * Specify that URLs are allowed by anonymous users. */ val anonymous = "anonymous" /** * Specify that URLs are allowed by users that have been remembered. */ val rememberMe = "rememberMe" /** * Specify that URLs are not allowed by anyone. */ val denyAll = "denyAll" /** * Specify that URLs are allowed by any authenticated user. */ val authenticated = "authenticated" /** * Specify that URLs are allowed by users who have authenticated and were not * "remembered". */ val fullyAuthenticated = "fullyAuthenticated" internal fun get(): (ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry) -> Unit { return { requests -> authorizationRules.forEach { rule -> when (rule) { is MatcherAuthorizationRule -> requests.requestMatchers(rule.matcher).access(rule.rule) is PatternAuthorizationRule -> { when (rule.patternType) { PatternType.ANT -> requests.antMatchers(rule.httpMethod, rule.pattern).access(rule.rule) PatternType.MVC -> requests.mvcMatchers(rule.httpMethod, rule.pattern) .apply { if(rule.servletPath != null) servletPath(rule.servletPath) } .access(rule.rule) } } } } } } }
apache-2.0
571f450d61e53cd703ff771776a779c3
43.663866
117
0.631326
4.847241
false
false
false
false
jdiazcano/modulartd
editor/core/src/main/kotlin/com/jdiazcano/modulartd/beans/Unit.kt
1
1651
package com.jdiazcano.modulartd.beans import com.jdiazcano.modulartd.ResourceManager data class Unit( override var name: String, override var resource: Resource, override var rotationAngle: Float = 0F, override var script: String = "", override var animationTimer: Float = 0.2F, var movementSpeed: Float = 1F, var hitPoints: Float = 1F, var armor: Float = 0F, var invisible: Boolean = false, var air: Boolean = false, var antiStun: Boolean = false, var antiSlow: Boolean = false, var livesTaken: Int = 1, var hpRegenPerSecond: Float = 0f, var drop: MutableMap<Coin, Int> = hashMapOf(), override var sounds: MutableMap<UnitEvent, Resource> = UnitEvent.values.associateBy({it}, {ResourceManager.NO_SOUND}).toMutableMap() ): MapObject, Scriptable, Sounded<UnitEvent> /** * Events that can occur to an unit. This will go later to the scripting language because each one of these * enum items will map to a method that will be executed when the action happens. But if someone doesn't want * to go into that mess, (s)he can just play a sound. */ enum class UnitEvent { /** * Fired when the unit spawns */ ON_SPAWN, /** * Fired when the unit dies */ ON_DEATH, /** * Fired when an unit enters a new region. */ ON_REGION, /** * Fired when the unit reaches the last region. */ ON_FINAL, /** * Fired when this unit takes damage */ ON_DAMAGE, ; companion object { val values = values() } }
apache-2.0
a72e7560a718825bb728400d9595a3f4
28.5
109
0.612962
4.15869
false
false
false
false
SirLYC/Android-Gank-Share
app/src/main/java/com/lyc/gank/utils/LoadState.kt
1
2978
package com.lyc.gank.utils import android.support.annotation.CheckResult import com.lyc.gank.utils.LoadState.Empty.loadMore /** * Created by hgj on 04/01/2018. * * LoadState state transition diagram: * * +----------------+ * | Empty (init) | * +----------------+ * result(true) | | result(false) * +-------------------------+ | * v v * +---------------+ result(true) +----------------+ +-------------+ * | HasMore | <-------------- | NoMore | | Error | * +---------------+ +----------------+ +-------------+ * | ^ ^ ^ | * | | result(true) | result(false) error | | * | | | | | * | | +----------------+ | | * | +--------------------- | | --------------+ | * | | Loading | | * | loadMore | | loadMore | * +----------------------------> | | <---------------------+ * +----------------+ * */ sealed class LoadState { @CheckResult open fun loadMore(): LoadState? = null @CheckResult open fun result(hasMore: Boolean): LoadState? = null @CheckResult open fun error(msg: String): LoadState? = null /** * init state: empty stub, [loadMore] action is disabled * * next state: [HasMore] [NoMore] */ object Empty : LoadState() { override fun result(hasMore: Boolean) = if (hasMore) HasMore else NoMore } /** * has more data to load after loading * * previous state: [Empty], [Loading] * next state: [Loading] */ object HasMore : LoadState() { override fun loadMore() = Loading } /** * no more data to load after loading * * previous state: [Empty], [Loading] * no next state: [HasMore] */ object NoMore : LoadState() { override fun result(hasMore: Boolean) = if (hasMore) HasMore else null } /** * loading * * previous state: [HasMore], [Error] * next state: [HasMore], [NoMore], [Error] */ object Loading : LoadState() { override fun result(hasMore: Boolean) = if (hasMore) HasMore else NoMore override fun error(msg: String) = Error(msg) } /** * error occurs after loading * * previous state: [Loading] * next state: [Loading] */ class Error(val msg: String) : LoadState() { override fun loadMore() = Loading } }
apache-2.0
f01853a4db5ffd2c15508a1df8985344
33.627907
83
0.374748
4.726984
false
false
false
false
Maccimo/intellij-community
platform/remoteDev-util/src/com/intellij/remoteDev/downloader/CodeWithMeGuestLauncher.kt
4
4665
package com.intellij.remoteDev.downloader import com.intellij.openapi.application.ModalityState import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.progress.Task.Backgroundable import com.intellij.openapi.project.Project import com.intellij.openapi.rd.createLifetime import com.intellij.openapi.ui.Messages import com.intellij.openapi.util.NlsContexts import com.intellij.remoteDev.RemoteDevUtilBundle import com.intellij.remoteDev.util.UrlUtil import com.intellij.util.application import com.intellij.util.fragmentParameters import com.jetbrains.rd.util.lifetime.Lifetime import org.jetbrains.annotations.ApiStatus import java.nio.file.Path import java.util.concurrent.ConcurrentHashMap @ApiStatus.Experimental object CodeWithMeGuestLauncher { private val LOG = logger<CodeWithMeGuestLauncher>() private val alreadyDownloading = ConcurrentHashMap.newKeySet<String>() fun downloadCompatibleClientAndLaunch(project: Project?, url: String, @NlsContexts.DialogTitle product: String, onDone: (Lifetime) -> Unit) { if (!application.isDispatchThread) { // starting a task from background will call invokeLater, but with wrong modality, so do it ourselves application.invokeLater({ downloadCompatibleClientAndLaunch(project, url, product, onDone) }, ModalityState.any()) return } val uri = UrlUtil.parseOrShowError(url, product) ?: return if (!alreadyDownloading.add(url)) { LOG.info("Already downloading a client for $url") return } ProgressManager.getInstance().run(object : Backgroundable(project, RemoteDevUtilBundle.message("launcher.title"), true) { private var clientLifetime : Lifetime = Lifetime.Terminated override fun run(progressIndicator: ProgressIndicator) { try { val sessionInfo = when (uri.scheme) { "tcp", "gwws" -> { val clientBuild = uri.fragmentParameters["cb"] ?: error("there is no client build in url") val jreBuild = uri.fragmentParameters["jb"] ?: error("there is no jre build in url") val unattendedMode = uri.fragmentParameters["jt"] != null CodeWithMeClientDownloader.createSessionInfo(clientBuild, jreBuild, unattendedMode) } "http", "https" -> { progressIndicator.text = RemoteDevUtilBundle.message("launcher.get.client.info") ThinClientSessionInfoFetcher.getSessionUrl(uri) } else -> { error("scheme '${uri.scheme} is not supported'") } } val pair = CodeWithMeClientDownloader.downloadClientAndJdk(sessionInfo, progressIndicator) if (pair == null) return clientLifetime = runDownloadedClient( lifetime = project?.createLifetime() ?: Lifetime.Eternal, pathToClient = pair.first, pathToJre = pair.second, urlForThinClient = url, product = product, progressIndicator = progressIndicator ) } catch (t: Throwable) { LOG.warn(t) application.invokeLater({ Messages.showErrorDialog( RemoteDevUtilBundle.message("error.url.issue", t.message ?: "Unknown"), product) }, ModalityState.any()) } finally { alreadyDownloading.remove(url) } } override fun onSuccess() = onDone.invoke(clientLifetime) override fun onCancel() = Unit }) } fun runDownloadedClient(lifetime: Lifetime, pathToClient: Path, pathToJre: Path, urlForThinClient: String, @NlsContexts.DialogTitle product: String, progressIndicator: ProgressIndicator?): Lifetime { // todo: offer to connect as-is? try { progressIndicator?.text = RemoteDevUtilBundle.message("launcher.launch.client") progressIndicator?.text2 = pathToClient.toString() val thinClientLifetime = CodeWithMeClientDownloader.runCwmGuestProcessFromDownload(lifetime, urlForThinClient, pathToClient, pathToJre) // Wait a bit until process will be launched and only after that finish task Thread.sleep(3000) return thinClientLifetime } catch (t: Throwable) { Logger.getInstance(javaClass).warn(t) application.invokeLater { Messages.showErrorDialog( RemoteDevUtilBundle.message("error.guest.run.issue", t.message ?: "Unknown"), product) } return Lifetime.Terminated } } }
apache-2.0
614cb8f7c5869bc03086630fa0776dd6
38.542373
143
0.689389
4.884817
false
false
false
false
k9mail/k-9
app/core/src/main/java/com/fsck/k9/message/html/DividerReplacer.kt
2
1046
package com.fsck.k9.message.html internal object DividerReplacer : TextToHtml.HtmlModifier { private const val SIMPLE_DIVIDER = "[-=_]{3,}" private const val ASCII_SCISSORS = "(?:-{2,}\\s?(?:>[%8]|[%8]<)\\s?-{2,})+" private val PATTERN = Regex( "(?:^|\\n)" + "(?:" + "\\s*" + "(?:" + SIMPLE_DIVIDER + "|" + ASCII_SCISSORS + ")" + "\\s*" + "(?:\\n|$)" + ")+" ) override fun findModifications(text: CharSequence): List<HtmlModification> { return PATTERN.findAll(text).map { matchResult -> Divider(matchResult.range.start, matchResult.range.endInclusive + 1) }.toList() } class Divider(startIndex: Int, endIndex: Int) : HtmlModification.Replace(startIndex, endIndex) { override fun replace(textToHtml: TextToHtml) { textToHtml.appendHtml("<hr>") } override fun toString(): String { return "Divider{startIndex=$startIndex, endIndex=$endIndex}" } } }
apache-2.0
a52b7b9f136cf5ff6a5035ba468ee347
32.741935
100
0.543977
4.11811
false
false
false
false
blindpirate/gradle
subprojects/kotlin-dsl/src/testFixtures/kotlin/org/gradle/kotlin/dsl/fixtures/SimplifiedKotlinScriptEvaluator.kt
1
7679
/* * Copyright 2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gradle.kotlin.dsl.fixtures import com.nhaarman.mockito_kotlin.doReturn import com.nhaarman.mockito_kotlin.mock import org.gradle.api.internal.file.temp.GradleUserHomeTemporaryFileProvider import org.gradle.api.internal.initialization.ClassLoaderScope import org.gradle.api.internal.project.ProjectInternal import org.gradle.configuration.DefaultImportsReader import org.gradle.groovy.scripts.ScriptSource import org.gradle.internal.Describables import org.gradle.internal.classloader.ClasspathUtil import org.gradle.internal.classpath.ClassPath import org.gradle.internal.classpath.DefaultClassPath import org.gradle.internal.hash.HashCode import org.gradle.internal.hash.Hashing import org.gradle.internal.hash.TestHashCodes import org.gradle.internal.resource.StringTextResource import org.gradle.internal.service.DefaultServiceRegistry import org.gradle.internal.service.ServiceRegistry import org.gradle.kotlin.dsl.execution.CompiledScript import org.gradle.kotlin.dsl.execution.Interpreter import org.gradle.kotlin.dsl.execution.ProgramId import org.gradle.kotlin.dsl.execution.ProgramTarget import org.gradle.kotlin.dsl.support.ImplicitImports import org.gradle.kotlin.dsl.support.KotlinScriptHost import org.gradle.plugin.management.internal.PluginRequests import java.io.File import java.net.URLClassLoader /** * Evaluates the given Kotlin [script] against the given [target] writing compiled classes * to sub-directories of [baseCacheDir]. */ fun eval( script: String, target: Any, baseCacheDir: File, baseTempDir: File, scriptCompilationClassPath: ClassPath = testRuntimeClassPath, scriptRuntimeClassPath: ClassPath = ClassPath.EMPTY ) { SimplifiedKotlinScriptEvaluator( baseCacheDir, baseTempDir, scriptCompilationClassPath, scriptRuntimeClassPath = scriptRuntimeClassPath ).use { it.eval(script, target) } } /** * A simplified Service Registry, suitable for cheaper testing of the DSL outside of Gradle. */ private class SimplifiedKotlinDefaultServiceRegistry( private val baseTempDir: File, ) : DefaultServiceRegistry() { init { register { add(GradleUserHomeTemporaryFileProvider::class.java, GradleUserHomeTemporaryFileProvider { baseTempDir }) } } } /** * A simplified Kotlin script evaluator, suitable for cheaper testing of the DSL outside Gradle. */ private class SimplifiedKotlinScriptEvaluator( private val baseCacheDir: File, private val baseTempDir: File, private val scriptCompilationClassPath: ClassPath, private val serviceRegistry: ServiceRegistry = SimplifiedKotlinDefaultServiceRegistry(baseTempDir), private val scriptRuntimeClassPath: ClassPath = ClassPath.EMPTY ) : AutoCloseable { fun eval(script: String, target: Any, topLevelScript: Boolean = false) { Interpreter(InterpreterHost()).eval( target, scriptSourceFor(script), Hashing.md5().hashString(script), mock(), targetScope, baseScope, topLevelScript ) } override fun close() { classLoaders.forEach(URLClassLoader::close) } private val classLoaders = mutableListOf<URLClassLoader>() private val parentClassLoader = mock<ClassLoader>() private val baseScope = mock<ClassLoaderScope>(name = "baseScope") { on { exportClassLoader } doReturn parentClassLoader } private val targetScopeExportClassLoader = mock<ClassLoader>() private val targetScope = mock<ClassLoaderScope>(name = "targetScope") { on { parent } doReturn baseScope on { exportClassLoader } doReturn targetScopeExportClassLoader } private fun scriptSourceFor(script: String): ScriptSource = mock { on { fileName } doReturn "script.gradle.kts" on { shortDisplayName } doReturn Describables.of("<test script>") on { resource } doReturn StringTextResource("<test script>", script) } private inner class InterpreterHost : Interpreter.Host { override fun serviceRegistryFor(programTarget: ProgramTarget, target: Any): ServiceRegistry = serviceRegistry override fun cachedClassFor(programId: ProgramId): CompiledScript? = null override fun cache(specializedProgram: CompiledScript, programId: ProgramId) = Unit override fun cachedDirFor( scriptHost: KotlinScriptHost<*>, templateId: String, sourceHash: HashCode, compilationClassPath: ClassPath, accessorsClassPath: ClassPath, initializer: (File) -> Unit ): File = baseCacheDir.resolve(sourceHash.toString()).resolve(templateId).also { cacheDir -> cacheDir.mkdirs() initializer(cacheDir) } override fun compilationClassPathOf(classLoaderScope: ClassLoaderScope): ClassPath = scriptCompilationClassPath override fun pluginAccessorsFor(scriptHost: KotlinScriptHost<*>): ClassPath = ClassPath.EMPTY override fun startCompilerOperation(description: String): AutoCloseable = mock() override fun loadClassInChildScopeOf( classLoaderScope: ClassLoaderScope, childScopeId: String, location: File, className: String, accessorsClassPath: ClassPath ): CompiledScript = DummyCompiledScript( classLoaderFor(scriptRuntimeClassPath + DefaultClassPath.of(location)) .also { classLoaders += it } .loadClass(className) ) override fun applyPluginsTo(scriptHost: KotlinScriptHost<*>, pluginRequests: PluginRequests) = Unit override fun applyBasePluginsTo(project: ProjectInternal) = Unit override fun setupEmbeddedKotlinFor(scriptHost: KotlinScriptHost<*>) = Unit override fun closeTargetScopeOf(scriptHost: KotlinScriptHost<*>) = Unit override fun hashOf(classPath: ClassPath): HashCode = TestHashCodes.hashCodeFrom(0) override fun runCompileBuildOperation(scriptPath: String, stage: String, action: () -> String): String = action() override fun onScriptClassLoaded(scriptSource: ScriptSource, specializedProgram: Class<*>) = Unit override val implicitImports: List<String> get() = ImplicitImports(DefaultImportsReader()).list } } class DummyCompiledScript(override val program: Class<*>) : CompiledScript { override val classPath: ClassPath get() = ClassPath.EMPTY override fun onReuse() { } override fun equals(other: Any?) = when { other === this -> true other == null || other.javaClass != this.javaClass -> false else -> program == (other as DummyCompiledScript).program } } val testRuntimeClassPath: ClassPath by lazy { ClasspathUtil.getClasspath(SimplifiedKotlinScriptEvaluator::class.java.classLoader) }
apache-2.0
cf83aaedf2ffa1da5c926c93b6826835
33.128889
117
0.709858
4.999349
false
false
false
false
firebase/FirebaseUI-Android
internal/lint/src/test/java/com/firebaseui/lint/internal/NonGlobalIdDetectorTest.kt
1
2437
package com.firebaseui.lint.internal import com.android.tools.lint.checks.infrastructure.TestFiles.xml import com.android.tools.lint.checks.infrastructure.TestLintTask import com.firebaseui.lint.internal.NonGlobalIdDetector.Companion.NON_GLOBAL_ID import org.junit.Test import java.io.File class NonGlobalIdDetectorTest { // Nasty hack to make lint tests pass on Windows. For some reason, lint doesn't // automatically find the Android SDK in its standard path on Windows. This hack looks // through the system properties to find the path defined in `local.properties` and then // sets lint's SDK home to that path if it's found. private val sdkPath = System.getProperty("java.library.path").split(';').find { it.contains("SDK", true) } fun configuredLint(): TestLintTask = TestLintTask.lint().apply { sdkHome(File(sdkPath ?: return@apply)) } @Test fun `Passes on valid view id`() { configuredLint() .files(xml("res/layout/layout.xml", """ |<RelativeLayout | xmlns:android="http://schemas.android.com/apk/res/android" | android:id="@+id/valid"/>""".trimMargin())) .issues(NON_GLOBAL_ID) .run() .expectClean() } @Test fun `Fails on invalid view id`() { configuredLint() .files(xml("res/layout/layout.xml", """ |<ScrollView | xmlns:android="http://schemas.android.com/apk/res/android" | android:id="@id/invalid"/>""".trimMargin())) .issues(NON_GLOBAL_ID) .run() .expect(""" |res/layout/layout.xml:3: Error: Use of non-global @id in layout file, consider using @+id instead for compatibility with aapt1. [NonGlobalIdInLayout] | android:id="@id/invalid"/> | ~~~~~~~~~~~~~~~~~~~~~~~~ |1 errors, 0 warnings""".trimMargin()) .expectFixDiffs(""" |Fix for res/layout/layout.xml line 2: Fix id: |@@ -3 +3 |- android:id="@id/invalid"/> |@@ -4 +3 |+ android:id="@+id/invalid"/> |""".trimMargin()) } }
apache-2.0
182b1f45911cbdd6706e0fd66e71e569
41.754386
174
0.528108
4.598113
false
true
false
false
Hexworks/zircon
zircon.core/src/commonMain/kotlin/org/hexworks/zircon/api/builder/component/ListItemBuilder.kt
1
1166
package org.hexworks.zircon.api.builder.component import org.hexworks.zircon.api.component.ListItem import org.hexworks.zircon.api.component.builder.base.ComponentWithTextBuilder import org.hexworks.zircon.internal.component.impl.DefaultListItem import org.hexworks.zircon.internal.component.renderer.DefaultListItemRenderer import org.hexworks.zircon.internal.component.withNewLinesStripped import org.hexworks.zircon.internal.dsl.ZirconDsl import kotlin.jvm.JvmStatic @Suppress("UNCHECKED_CAST") @ZirconDsl class ListItemBuilder private constructor() : ComponentWithTextBuilder<ListItem, ListItemBuilder>( initialRenderer = DefaultListItemRenderer(), initialText = "", reservedSpace = 2 ) { override fun build(): ListItem { return DefaultListItem( componentMetadata = createMetadata(), renderingStrategy = createRenderingStrategy(), textProperty = fixedTextProperty, ).attachListeners() } override fun createCopy() = newBuilder() .withProps(props.copy()) .withText(text) companion object { @JvmStatic fun newBuilder() = ListItemBuilder() } }
apache-2.0
264833d945579b14b4ece2e738550899
31.388889
98
0.740995
4.838174
false
false
false
false
wordpress-mobile/WordPress-Android
WordPress/src/main/java/org/wordpress/android/ui/stories/prefs/StoriesPrefs.kt
1
10666
package org.wordpress.android.ui.stories.prefs import android.annotation.SuppressLint import android.content.Context import android.net.Uri import androidx.preference.PreferenceManager import com.wordpress.stories.compose.story.StoryFrameItem import com.wordpress.stories.compose.story.StoryFrameItem.BackgroundSource.FileBackgroundSource import com.wordpress.stories.compose.story.StoryFrameItem.BackgroundSource.UriBackgroundSource import com.wordpress.stories.compose.story.StorySerializerUtils import org.wordpress.android.fluxc.model.LocalOrRemoteId.LocalId import org.wordpress.android.fluxc.model.LocalOrRemoteId.RemoteId import javax.inject.Inject import javax.inject.Singleton @Singleton class StoriesPrefs @Inject constructor( private val context: Context ) { companion object { private const val KEY_STORIES_SLIDE_INCREMENTAL_ID = "incremental_id" private const val KEY_PREFIX_STORIES_SLIDE_ID = "story_slide_id-" private const val KEY_PREFIX_TEMP_MEDIA_ID = "t-" private const val KEY_PREFIX_LOCAL_MEDIA_ID = "l-" private const val KEY_PREFIX_REMOTE_MEDIA_ID = "r-" } private fun buildSlideKey(siteId: Long, mediaId: RemoteId): String { return KEY_PREFIX_STORIES_SLIDE_ID + siteId.toString() + "-" + KEY_PREFIX_REMOTE_MEDIA_ID + mediaId.value.toString() } private fun buildSlideKey(siteId: Long, mediaId: LocalId): String { return KEY_PREFIX_STORIES_SLIDE_ID + siteId.toString() + "-" + KEY_PREFIX_LOCAL_MEDIA_ID + mediaId.value.toString() } private fun buildSlideKey(siteId: Long, tempId: TempId): String { return KEY_PREFIX_STORIES_SLIDE_ID + siteId.toString() + "-" + KEY_PREFIX_TEMP_MEDIA_ID + tempId.id } @SuppressLint("ApplySharedPref") @Synchronized fun getNewIncrementalTempId(): Long { var currentIncrementalId = getIncrementalTempId() currentIncrementalId++ val editor = PreferenceManager.getDefaultSharedPreferences(context).edit() editor.putLong(KEY_STORIES_SLIDE_INCREMENTAL_ID, currentIncrementalId) editor.commit() return currentIncrementalId } private fun getIncrementalTempId(): Long { return PreferenceManager.getDefaultSharedPreferences(context).getLong( KEY_STORIES_SLIDE_INCREMENTAL_ID, 0 ) } fun checkSlideIdExists(siteId: Long, mediaId: RemoteId): Boolean { val slideIdKey = buildSlideKey(siteId, mediaId) return PreferenceManager.getDefaultSharedPreferences(context).contains(slideIdKey) } private fun checkSlideIdExists(siteId: Long, tempId: TempId): Boolean { val slideIdKey = buildSlideKey(siteId, tempId) return PreferenceManager.getDefaultSharedPreferences(context).contains(slideIdKey) } private fun checkSlideIdExists(siteId: Long, localId: LocalId): Boolean { val slideIdKey = buildSlideKey(siteId, localId) return PreferenceManager.getDefaultSharedPreferences(context).contains(slideIdKey) } private fun checkSlideOriginalBackgroundMediaExists(siteId: Long, mediaId: RemoteId): Boolean { return checkSlideOriginalBackgroundMediaExists(getSlideWithRemoteId(siteId, mediaId)) } private fun checkSlideOriginalBackgroundMediaExists(siteId: Long, mediaId: TempId): Boolean { return checkSlideOriginalBackgroundMediaExists(getSlideWithTempId(siteId, mediaId)) } private fun checkSlideOriginalBackgroundMediaExists(siteId: Long, mediaId: LocalId): Boolean { return checkSlideOriginalBackgroundMediaExists(getSlideWithLocalId(siteId, mediaId)) } private fun checkSlideOriginalBackgroundMediaExists(storyFrameItem: StoryFrameItem?): Boolean { storyFrameItem?.let { frame -> // now check the background media exists or is accessible on this device frame.source.let { source -> if (source is FileBackgroundSource) { source.file?.let { return it.exists() } ?: return false } else if (source is UriBackgroundSource) { source.contentUri?.let { return isUriAccessible(it) } ?: return false } } } return false } @Suppress("ReturnCount", "PrintStackTrace", "ForbiddenComment") private fun isUriAccessible(uri: Uri): Boolean { if (uri.toString().startsWith("http")) { // TODO: assume it'll be accessible - we'll figure out later // potentially force external download using MediaUtils.downloadExternalMedia() here to ensure return true } try { context.contentResolver.openInputStream(uri)?.let { it.close() return true } } catch (e: java.lang.Exception) { e.printStackTrace() } return false } private fun saveSlide(slideIdKey: String, storySlideJson: String) { val editor = PreferenceManager.getDefaultSharedPreferences(context).edit() editor.putString(slideIdKey, storySlideJson) editor.apply() } fun isValidSlide(siteId: Long, mediaId: RemoteId): Boolean { return checkSlideIdExists(siteId, mediaId) && checkSlideOriginalBackgroundMediaExists(siteId, mediaId) } fun isValidSlide(siteId: Long, tempId: TempId): Boolean { return checkSlideIdExists(siteId, tempId) && checkSlideOriginalBackgroundMediaExists(siteId, tempId) } fun isValidSlide(siteId: Long, localId: LocalId): Boolean { return checkSlideIdExists(siteId, localId) && checkSlideOriginalBackgroundMediaExists(siteId, localId) } private fun getSlideJson(slideIdKey: String): String? { return PreferenceManager.getDefaultSharedPreferences(context).getString(slideIdKey, null) } fun getSlideWithRemoteId(siteId: Long, mediaId: RemoteId): StoryFrameItem? { val jsonSlide = getSlideJson(buildSlideKey(siteId, mediaId)) jsonSlide?.let { return StorySerializerUtils.deserializeStoryFrameItem(jsonSlide) } ?: return null } fun getSlideWithLocalId(siteId: Long, mediaId: LocalId): StoryFrameItem? { val jsonSlide = getSlideJson(buildSlideKey(siteId, mediaId)) jsonSlide?.let { return StorySerializerUtils.deserializeStoryFrameItem(jsonSlide) } ?: return null } fun getSlideWithTempId(siteId: Long, tempId: TempId): StoryFrameItem? { val jsonSlide = getSlideJson(buildSlideKey(siteId, tempId)) jsonSlide?.let { return StorySerializerUtils.deserializeStoryFrameItem(jsonSlide) } ?: return null } fun saveSlideWithTempId(siteId: Long, tempId: TempId, storyFrameItem: StoryFrameItem) { val slideIdKey = buildSlideKey(siteId, tempId) saveSlide(slideIdKey, StorySerializerUtils.serializeStoryFrameItem(storyFrameItem)) } fun saveSlideWithLocalId(siteId: Long, mediaId: LocalId, storyFrameItem: StoryFrameItem) { val slideIdKey = buildSlideKey(siteId, mediaId) saveSlide(slideIdKey, StorySerializerUtils.serializeStoryFrameItem(storyFrameItem)) } fun saveSlideWithRemoteId(siteId: Long, mediaId: RemoteId, storyFrameItem: StoryFrameItem) { val slideIdKey = buildSlideKey(siteId, mediaId) saveSlide(slideIdKey, StorySerializerUtils.serializeStoryFrameItem(storyFrameItem)) } fun deleteSlideWithTempId(siteId: Long, tempId: TempId) { val slideIdKey = buildSlideKey(siteId, tempId) val editor = PreferenceManager.getDefaultSharedPreferences(context).edit() editor.remove(slideIdKey) editor.apply() } fun deleteSlideWithLocalId(siteId: Long, mediaId: LocalId) { val slideIdKey = buildSlideKey(siteId, mediaId) val editor = PreferenceManager.getDefaultSharedPreferences(context).edit() editor.remove(slideIdKey) editor.apply() } fun deleteSlideWithRemoteId(siteId: Long, mediaId: RemoteId) { val slideIdKey = buildSlideKey(siteId, mediaId) PreferenceManager.getDefaultSharedPreferences(context).edit().apply { remove(slideIdKey) apply() } } // Phase 2: this method is likely used after a first phase in which a local media which only has a temporary id has // then be replaced by a local id. At this point, we now have a remote Id and we can replace the local // media id with the remote media id. fun replaceLocalMediaIdKeyedSlideWithRemoteMediaIdKeyedSlide( localIdKey: Int, remoteIdKey: Long, localSiteId: Long ) { // look for the slide saved with the local id key (mediaFile.id), and re-convert to mediaId. getSlideWithLocalId( localSiteId, LocalId(localIdKey) )?.let { it.id = remoteIdKey.toString() // update the StoryFrameItem id to hold the same value as the remote mediaID saveSlideWithRemoteId( localSiteId, RemoteId(remoteIdKey), // use the new mediaId as key it ) // now delete the old entry deleteSlideWithLocalId( localSiteId, LocalId(localIdKey) ) } } // Phase 1: this method is likely used at the beginning when a local media which only has a temporary id needs now // to be assigned with a localMediaId. At a later point when the media is uploaded to the server, it will be // assigned a remote Id which will replace this localId. fun replaceTempMediaIdKeyedSlideWithLocalMediaIdKeyedSlide( tempId: TempId, localId: LocalId, localSiteId: Long ): StoryFrameItem? { // look for the slide saved with the local id key (mediaFile.id), and re-convert to mediaId. getSlideWithTempId( localSiteId, tempId )?.let { it.id = localId.value.toString() saveSlideWithLocalId( localSiteId, localId, // use the new localId as key it ) // now delete the old entry deleteSlideWithTempId( localSiteId, tempId ) return it } return null } data class TempId(val id: String) }
gpl-2.0
101ec134435ad14c0334f8e38e4464ef
39.401515
119
0.661448
4.686292
false
false
false
false
RadiationX/ForPDA
app/src/main/java/forpdateam/ru/forpda/entity/remote/forum/ForumRules.kt
1
430
package forpdateam.ru.forpda.entity.remote.forum import java.util.ArrayList /** * Created by radiationx on 16.10.17. */ class ForumRules { val items = mutableListOf<Item>() var html: String? = null var date: String? = null fun addItem(item: Item) { this.items.add(item) } class Item { var number: String? = null var text: String? = null var isHeader = false } }
gpl-3.0
c601372310d5edbc7c01f7e5ae632c45
16.916667
48
0.606977
3.644068
false
false
false
false
mdaniel/intellij-community
platform/platform-impl/src/com/intellij/openapi/ui/FrameWrapper.kt
2
14190
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.openapi.ui import com.intellij.application.options.RegistryManager import com.intellij.ide.ui.UISettings.Companion.setupAntialiasing import com.intellij.openapi.Disposable import com.intellij.openapi.actionSystem.CommonDataKeys import com.intellij.openapi.actionSystem.CommonShortcuts import com.intellij.openapi.actionSystem.DataProvider import com.intellij.openapi.actionSystem.ex.ActionUtil import com.intellij.openapi.actionSystem.impl.MouseGestureManager import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.options.advanced.AdvancedSettings import com.intellij.openapi.project.Project import com.intellij.openapi.project.ProjectManager import com.intellij.openapi.project.ProjectManagerListener import com.intellij.openapi.ui.popup.util.PopupUtil import com.intellij.openapi.util.* import com.intellij.openapi.wm.* import com.intellij.openapi.wm.ex.IdeFocusTraversalPolicy import com.intellij.openapi.wm.ex.IdeFrameEx import com.intellij.openapi.wm.ex.WindowManagerEx import com.intellij.openapi.wm.impl.* import com.intellij.openapi.wm.impl.LinuxIdeMenuBar.Companion.doBindAppMenuOfParent import com.intellij.openapi.wm.impl.customFrameDecorations.header.CustomFrameDialogContent import com.intellij.ui.* import com.intellij.ui.mac.touchbar.TouchbarSupport import com.intellij.util.ui.ImageUtil import com.intellij.util.ui.UIUtil import com.jetbrains.JBR import org.jetbrains.annotations.NonNls import java.awt.* import java.awt.event.ActionListener import java.awt.event.KeyEvent import java.awt.event.WindowAdapter import java.awt.event.WindowEvent import java.nio.file.Path import java.util.concurrent.CompletableFuture import java.util.function.Supplier import javax.swing.* open class FrameWrapper @JvmOverloads constructor(project: Project?, @param:NonNls protected open val dimensionKey: String? = null, private val isDialog: Boolean = false, @NlsContexts.DialogTitle var title: String = "", open var component: JComponent? = null) : Disposable, DataProvider { open var preferredFocusedComponent: JComponent? = null private var images: List<Image> = emptyList() private var isCloseOnEsc = false private var onCloseHandler: BooleanGetter? = null private var frame: Window? = null private var project: Project? = null private var isDisposing = false var isDisposed = false private set protected var statusBar: StatusBar? = null set(value) { field?.let { Disposer.dispose(it) } field = value } init { project?.let { setProject(it) } } fun setProject(project: Project) { this.project = project ApplicationManager.getApplication().messageBus.connect(this).subscribe(ProjectManager.TOPIC, object : ProjectManagerListener { override fun projectClosing(project: Project) { if (project === [email protected]) { close() } } }) } open fun show() { show(true) } fun createContents() { val frame = getFrame() if (frame is JFrame) { frame.defaultCloseOperation = WindowConstants.DO_NOTHING_ON_CLOSE } else { (frame as JDialog).defaultCloseOperation = WindowConstants.DO_NOTHING_ON_CLOSE } frame.addWindowListener(object : WindowAdapter() { override fun windowClosing(e: WindowEvent) { close() } }) UIUtil.decorateWindowHeader((frame as RootPaneContainer).rootPane) if (frame is JFrame) { val handlerProvider = Supplier { FullScreeSupport.NEW.apply("com.intellij.ui.mac.MacFullScreenSupport") } ToolbarUtil.setTransparentTitleBar(frame, frame.rootPane, handlerProvider) { runnable -> Disposer.register(this, Disposable { runnable.run() }) } } val focusListener = object : WindowAdapter() { override fun windowOpened(e: WindowEvent) { val focusManager = IdeFocusManager.getInstance(project) val toFocus = focusManager.getLastFocusedFor(e.window) ?: preferredFocusedComponent ?: focusManager.getFocusTargetFor(component!!) if (toFocus != null) { focusManager.requestFocus(toFocus, true) } } } frame.addWindowListener(focusListener) if (RegistryManager.getInstance().`is`("ide.perProjectModality")) { frame.isAlwaysOnTop = true } Disposer.register(this, Disposable { frame.removeWindowListener(focusListener) }) if (isCloseOnEsc) { addCloseOnEsc(frame as RootPaneContainer) } if (IdeFrameDecorator.isCustomDecorationActive()) { component?.let { component = /*UIUtil.findComponentOfType(it, EditorsSplitters::class.java)?.let { if(frame !is JFrame) null else { val header = CustomHeader.createMainFrameHeader(frame, IdeMenuBar.createMenuBar()) getCustomContentHolder(frame, it, header) } } ?:*/ CustomFrameDialogContent.getCustomContentHolder(frame, it) } } frame.contentPane.add(component!!, BorderLayout.CENTER) if (frame is JFrame) { frame.title = title } else { (frame as JDialog).title = title } if (images.isEmpty()) { AppUIUtil.updateWindowIcon(frame) } else { // unwrap the image before setting as frame's icon frame.iconImages = images.map { ImageUtil.toBufferedImage(it) } } if (SystemInfoRt.isLinux && frame is JFrame && GlobalMenuLinux.isAvailable()) { val parentFrame = WindowManager.getInstance().getFrame(project) if (parentFrame != null) { doBindAppMenuOfParent(frame, parentFrame) } } } fun show(restoreBounds: Boolean) { createContents() val frame = getFrame() val state = dimensionKey?.let { getWindowStateService(project).getState(it, frame) } if (restoreBounds) { loadFrameState(state) } if (SystemInfoRt.isMac) { TouchbarSupport.showWindowActions(this, frame) } frame.isVisible = true } fun close() { if (isDisposed || (onCloseHandler != null && !onCloseHandler!!.get())) { return } // if you remove this line problems will start happen on Mac OS X // 2 projects opened, call Cmd+D on the second opened project and then Esc. // Weird situation: 2nd IdeFrame will be active, but focus will be somewhere inside the 1st IdeFrame // App is unusable until Cmd+Tab, Cmd+tab frame?.isVisible = false Disposer.dispose(this) } override fun dispose() { if (isDisposed) { return } val frame = frame val statusBar = statusBar this.frame = null preferredFocusedComponent = null project = null component = null images = emptyList() isDisposed = true if (statusBar != null) { Disposer.dispose(statusBar) } if (frame != null) { frame.isVisible = false val rootPane = (frame as RootPaneContainer).rootPane frame.removeAll() DialogWrapper.cleanupRootPane(rootPane) if (frame is IdeFrame) { MouseGestureManager.getInstance().remove(frame) } frame.dispose() DialogWrapper.cleanupWindowListeners(frame) } } private fun addCloseOnEsc(frame: RootPaneContainer) { val rootPane = frame.rootPane val closeAction = ActionListener { if (!PopupUtil.handleEscKeyEvent()) { close() } } rootPane.registerKeyboardAction(closeAction, KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), JComponent.WHEN_IN_FOCUSED_WINDOW) ActionUtil.registerForEveryKeyboardShortcut(rootPane, closeAction, CommonShortcuts.getCloseActiveWindow()) } fun getFrame(): Window { assert(!isDisposed) { "Already disposed!" } var result = frame if (result == null) { val parent = WindowManager.getInstance().getIdeFrame(project)!! result = if (isDialog) createJDialog(parent) else createJFrame(parent) frame = result } return result } val isActive: Boolean get() = frame?.isActive == true protected open fun createJFrame(parent: IdeFrame): JFrame = MyJFrame(this, parent) protected open fun createJDialog(parent: IdeFrame): JDialog = MyJDialog(this, parent) protected open fun getNorthExtension(key: String?): IdeRootPaneNorthExtension? = null override fun getData(@NonNls dataId: String): Any? { return if (CommonDataKeys.PROJECT.`is`(dataId)) project else null } private fun getDataInner(@NonNls dataId: String): Any? { return when { CommonDataKeys.PROJECT.`is`(dataId) -> project else -> getData(dataId) } } fun closeOnEsc() { isCloseOnEsc = true } fun setImage(image: Image?) { setImages(listOfNotNull(image)) } fun setImages(value: List<Image>?) { images = value ?: emptyList() } fun setOnCloseHandler(value: BooleanGetter?) { onCloseHandler = value } protected open fun loadFrameState(state: WindowState?) { val frame = getFrame() if (state == null) { val ideFrame = WindowManagerEx.getInstanceEx().getIdeFrame(project) if (ideFrame != null) { frame.bounds = ideFrame.suggestChildFrameBounds() } } else { state.applyTo(frame) } (frame as RootPaneContainer).rootPane.revalidate() } private class MyJFrame(private var owner: FrameWrapper, private val parent: IdeFrame) : JFrame(), DataProvider, IdeFrame.Child, IdeFrameEx { private var frameTitle: String? = null private var fileTitle: String? = null private var file: Path? = null init { FrameState.setFrameStateListener(this) glassPane = IdeGlassPaneImpl(getRootPane(), true) if (SystemInfoRt.isMac && !(SystemInfo.isMacSystemMenu && java.lang.Boolean.getBoolean("mac.system.menu.singleton"))) { jMenuBar = IdeMenuBar.createMenuBar().setFrame(this) } MouseGestureManager.getInstance().add(this) focusTraversalPolicy = IdeFocusTraversalPolicy() } override fun isInFullScreen() = false override fun toggleFullScreen(state: Boolean): CompletableFuture<*> = CompletableFuture.completedFuture(null) override fun addNotify() { if (IdeFrameDecorator.isCustomDecorationActive()) { JBR.getCustomWindowDecoration().setCustomDecorationEnabled(this, true) } super.addNotify() } override fun getComponent(): JComponent = getRootPane() override fun getStatusBar(): StatusBar? { return (if (owner.isDisposing) null else owner.statusBar) ?: parent.statusBar } override fun suggestChildFrameBounds(): Rectangle = parent.suggestChildFrameBounds() override fun getProject() = parent.project override fun notifyProjectActivation() = parent.notifyProjectActivation() override fun setFrameTitle(title: String) { frameTitle = title updateTitle() } override fun setFileTitle(fileTitle: String?, ioFile: Path?) { this.fileTitle = fileTitle file = ioFile updateTitle() } override fun getNorthExtension(key: String): IdeRootPaneNorthExtension? { return owner.getNorthExtension(key) } override fun getBalloonLayout(): BalloonLayout? { return null } private fun updateTitle() { if (AdvancedSettings.getBoolean("ide.show.fileType.icon.in.titleBar")) { // this property requires java.io.File rootPane.putClientProperty("Window.documentFile", file?.toFile()) } val builder = StringBuilder() ProjectFrameHelper.appendTitlePart(builder, frameTitle) ProjectFrameHelper.appendTitlePart(builder, fileTitle) title = builder.toString() } override fun dispose() { val owner = owner if (owner.isDisposing) { return } owner.isDisposing = true Disposer.dispose(owner) super.dispose() rootPane = null menuBar = null } override fun getData(dataId: String): Any? { return when { IdeFrame.KEY.`is`(dataId) -> this owner.isDisposing -> null else -> owner.getDataInner(dataId) } } override fun paint(g: Graphics) { setupAntialiasing(g) super.paint(g) } } fun setLocation(location: Point) { getFrame().location = location } fun setSize(size: Dimension?) { getFrame().size = size } private class MyJDialog(private val owner: FrameWrapper, private val parent: IdeFrame) : JDialog(ComponentUtil.getWindow(parent.component)), DataProvider, IdeFrame.Child { override fun getComponent(): JComponent = getRootPane() override fun getStatusBar(): StatusBar? = null override fun getBalloonLayout(): BalloonLayout? = null override fun suggestChildFrameBounds(): Rectangle = parent.suggestChildFrameBounds() override fun getProject(): Project? = parent.project override fun notifyProjectActivation() = parent.notifyProjectActivation() init { glassPane = IdeGlassPaneImpl(getRootPane()) getRootPane().putClientProperty("Window.style", "small") background = UIUtil.getPanelBackground() MouseGestureManager.getInstance().add(this) focusTraversalPolicy = IdeFocusTraversalPolicy() } override fun setFrameTitle(title: String) { setTitle(title) } override fun dispose() { if (owner.isDisposing) { return } owner.isDisposing = true Disposer.dispose(owner) super.dispose() rootPane = null } override fun getData(dataId: String): Any? { return when { IdeFrame.KEY.`is`(dataId) -> this owner.isDisposing -> null else -> owner.getDataInner(dataId) } } override fun paint(g: Graphics) { setupAntialiasing(g) super.paint(g) } } } private fun getWindowStateService(project: Project?): WindowStateService { return if (project == null) WindowStateService.getInstance() else WindowStateService.getInstance(project) }
apache-2.0
f4207354a9ff50d0e637a3c0450f9047
29.915033
173
0.684919
4.819973
false
false
false
false
mdaniel/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/AddEmptyArgumentListFix.kt
1
1430
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.quickfix import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import org.jetbrains.kotlin.diagnostics.Diagnostic import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.codeinsight.api.classic.quickfixes.KotlinQuickFixAction import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.utils.addToStdlib.safeAs class AddEmptyArgumentListFix(callExpression: KtCallExpression) : KotlinQuickFixAction<KtCallExpression>(callExpression) { override fun getText() = KotlinBundle.message("add.empty.argument.list") override fun getFamilyName() = text override fun invoke(project: Project, editor: Editor?, file: KtFile) { val callExpression = this.element ?: return val calleeExpression = callExpression.calleeExpression ?: return val emptyArgumentList = KtPsiFactory(callExpression).createValueArgumentListByPattern("()") callExpression.addAfter(emptyArgumentList, calleeExpression) } companion object : KotlinSingleIntentionActionFactory() { override fun createAction(diagnostic: Diagnostic) = diagnostic.psiElement.parent.safeAs<KtCallExpression>()?.let { AddEmptyArgumentListFix(it) } } }
apache-2.0
02a326b160db40c4af83fca1e6eb5def
50.107143
158
0.783217
4.965278
false
false
false
false
JavaEden/Orchid-Core
plugins/OrchidSourceDoc/src/test/kotlin/setupHelpers.kt
2
3632
package com.eden.orchid.sourcedoc import com.eden.orchid.strikt.pageWasRendered import com.eden.orchid.testhelpers.OrchidIntegrationTest import com.eden.orchid.testhelpers.TestResults import strikt.api.Assertion const val separator = "{\"type\": \"separator\"}" fun Assertion.Builder<TestResults>.withDefaultSourcedocPages(): Assertion.Builder<TestResults> { return this .pageWasRendered("/assets/css/orchidSourceDoc.css") { } .pageWasRendered("/favicon.ico") { } } fun themeMenuModulesSetup(type: String) : String { return """ |{ | "type": "sourcedocModules", | "moduleType": "${type}doc", | "asSubmenu": true, | "submenuTitle": "${type.capitalize()} Modules" |} """.trimMargin() } fun themeMenuKindSetup(type: String, nodeKind: String, name: String? = null) : String { return if(name != null) { """ |{ | "type": "sourcedocPages", | "moduleType": "${type}doc", | "moduleName": "$name", | "node": "$nodeKind", | "asSubmenu": true, | "submenuTitle": "Module ${name.capitalize()} ${type.capitalize()}doc ${nodeKind.capitalize()}" |} """.trimMargin() } else { """ |{ | "type": "sourcedocPages", | "moduleType": "${type}doc", | "node": "$nodeKind", | "asSubmenu": true, | "submenuTitle": "${type.capitalize()}doc ${nodeKind.capitalize()}" |} """.trimMargin() } } fun themeMenuKindSetup(type: String, nodeKinds: List<String>, name: String? = null) : String { return nodeKinds.joinToString(",") { themeMenuKindSetup(type, it, name) } } fun themeMenuAllKindsSetup(type: String, nodeKind: String, name: String? = null) : String { return if(name != null) { """ |{ | "type": "sourcedocPages", | "moduleType": "${type}doc", | "moduleName": "$name", | "asSubmenu": true, | "submenuTitle": "Module ${name.capitalize()} ${type.capitalize()}doc ${nodeKind.capitalize()}" |} """.trimMargin() } else { """ |{ | "type": "sourcedocPages", | "moduleType": "${type}doc", | "asSubmenu": true, | "submenuTitle": "${type.capitalize()}doc ${nodeKind.capitalize()}" |} """.trimMargin() } } fun themeMenuAllKindsSetup(type: String, nodeKinds: List<String>, name: String? = null) : String { return nodeKinds.joinToString(",") { themeMenuAllKindsSetup(type, it, name) } } fun sourceDocPagesSetup() : String { return """ |{ | "pages": { | "summaryComponents": [ | { | "type": "sourceDocSummary" | } | ], | "menu": [ | { | "type": "sourcedocPageLinks", | "includeItems": false | }, | { | "type": "separator" | }, | { | "type": "sourcedocPageLinks", | "includeItems": true | }, | { | "type": "separator" | }, | { | "type": "sourcedocPageLinks", | "includeItems": true, | "itemTitleType": "SIGNATURE" | } | ] | } |} |""".trimMargin() }
mit
21933c25c441e3176b818eeeabbac776
29.779661
107
0.470815
4.198844
false
true
false
false
GunoH/intellij-community
platform/platform-impl/src/com/intellij/openapi/util/registry/RegistryManagerImpl.kt
3
3404
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.openapi.util.registry import com.intellij.diagnostic.runActivity import com.intellij.ide.AppLifecycleListener import com.intellij.openapi.Disposable import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.components.PersistentStateComponent import com.intellij.openapi.components.SettingsCategory import com.intellij.openapi.components.State import com.intellij.openapi.components.Storage import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.diagnostic.logger import com.intellij.util.ArrayUtilRt import org.jdom.Element import org.jetbrains.annotations.ApiStatus import java.util.* @State(name = "Registry", storages = [Storage("ide.general.xml")], useLoadedStateAsExisting = false, category = SettingsCategory.SYSTEM) @ApiStatus.Internal internal class RegistryManagerImpl : PersistentStateComponent<Element>, RegistryManager, Disposable { init { runActivity("registry keys adding") { RegistryKeyBean.addKeysFromPlugins() } Registry.setValueChangeListener(object : RegistryValueListener { override fun afterValueChanged(value: RegistryValue) { ApplicationManager.getApplication().messageBus.syncPublisher( RegistryManager.TOPIC).afterValueChanged(value) } }) // EarlyAccessRegistryManager cannot access AppLifecycleListener ApplicationManager.getApplication().messageBus.simpleConnect().subscribe(AppLifecycleListener.TOPIC, object : AppLifecycleListener { override fun appWillBeClosed(isRestart: Boolean) { try { EarlyAccessRegistryManager.syncAndFlush() } catch (e: Throwable) { Logger.getInstance(RegistryManagerImpl::class.java).error(e) } } }) } override fun dispose() { Registry.setValueChangeListener(null) } override fun `is`(key: String): Boolean { return Registry._getWithoutStateCheck(key).asBoolean() } override fun intValue(key: String) = Registry._getWithoutStateCheck(key).asInteger() override fun stringValue(key: String) = Registry._getWithoutStateCheck(key).asString() override fun intValue(key: String, defaultValue: Int): Int { return try { Registry._getWithoutStateCheck(key).asInteger() } catch (ignore: MissingResourceException) { defaultValue } } override fun get(key: String) = Registry._getWithoutStateCheck(key) override fun getState() = Registry.getInstance().state override fun noStateLoaded() { Registry.markAsLoaded() } override fun loadState(state: Element) { log(Registry.loadState(state) ?: return) } private fun log(userProperties: Map<String, String>) { if (userProperties.size <= (if (userProperties.containsKey("ide.firstStartup")) 1 else 0)) { return } val keys = ArrayUtilRt.toStringArray(userProperties.keys) Arrays.sort(keys) val builder = StringBuilder("Registry values changed by user: ") for (key in keys) { if ("ide.firstStartup" == key) { continue } builder.append(key).append(" = ").append(userProperties[key]).append(", ") } logger<RegistryManager>().info(builder.substring(0, builder.length - 2)) } fun getAll(): List<RegistryValue> { return Registry.getAll() } }
apache-2.0
84ad5725fabfeeafc773e6e801269094
33.393939
136
0.733549
4.538667
false
false
false
false
GunoH/intellij-community
plugins/kotlin/idea/tests/testData/findUsages/kotlin/conventions/components/memberComponentFun.0.kt
5
520
// PSI_ELEMENT: org.jetbrains.kotlin.psi.KtFunction // OPTIONS: usages open class X { operator fun <caret>component1(): Int = 0 operator fun component2(): Int = 1 fun foo() { val (x, y) = this } } open class Y : X() open class Z : Y() { fun bar() { val (x, y) = this } } fun f() = X() fun g() = Y() fun h() = Z() fun test() { val (x, y) = f() val (x1, y1) = g() val (x2, y2) = h() } // FIR_COMPARISON // IGNORE_FIR_LOG // FIR_COMPARISON_WITH_DISABLED_COMPONENTS
apache-2.0
90f3904605b73e18d7d4ff72cf9d1a74
14.787879
51
0.528846
2.780749
false
false
false
false
ClearVolume/scenery
src/test/kotlin/graphics/scenery/tests/examples/advanced/MultiBoxInstancedExample.kt
2
3783
package graphics.scenery.tests.examples.advanced import org.joml.Vector3f import graphics.scenery.* import graphics.scenery.backends.Renderer import graphics.scenery.numerics.Random import graphics.scenery.Mesh import graphics.scenery.attribute.material.Material import kotlin.concurrent.thread /** * Demo animating multiple boxes with instancing. * * @author Ulrik Günther <[email protected]> */ class MultiBoxInstancedExample : SceneryBase("MultiBoxInstancedExample") { override fun init() { renderer = hub.add(Renderer.createRenderer(hub, applicationName, scene, windowWidth, windowHeight)) val cam: Camera = DetachedHeadCamera() with(cam) { spatial { position = Vector3f(10.0f, 10.0f, 10.0f) } perspectiveCamera(60.0f, windowWidth, windowHeight, 1.0f, 1000.0f) scene.addChild(this) } val boundaryWidth = 50.0 val boundaryHeight = 50.0 val container = Mesh() val b = Box(Vector3f(0.7f, 0.7f, 0.7f)) b.name = "boxmaster" b.setMaterial(ShaderMaterial.fromFiles("DefaultDeferredInstanced.vert", "DefaultDeferred.frag")) { diffuse = Vector3f(1.0f, 1.0f, 1.0f) ambient = Vector3f(1.0f, 1.0f, 1.0f) specular = Vector3f(1.0f, 1.0f, 1.0f) metallic = 0.0f roughness = 1.0f } val bInstanced = InstancedNode(b) scene.addChild(bInstanced) (0 until (boundaryWidth * boundaryHeight * boundaryHeight).toInt()).map { val inst = bInstanced.addInstance() inst.name = "Box_$it" inst.addAttribute(Material::class.java, b.material()) val k: Double = it.rem(boundaryWidth) val j: Double = (it / boundaryWidth).rem(boundaryHeight) val i: Double = it / (boundaryWidth * boundaryHeight) inst.spatial { position = Vector3f(Math.floor(i).toFloat(), Math.floor(j).toFloat(), Math.floor(k).toFloat()) } inst.parent = container inst } val lights = (0..20).map { PointLight(radius = 250.0f) }.map { it.spatial { position = Random.random3DVectorFromRange(-100.0f, 100.0f) } it.emissionColor = Vector3f(1.0f, 1.0f, 1.0f) it.intensity = Random.randomFromRange(0.1f, 0.5f) it } lights.forEach { scene.addChild(it) } val hullbox = Box(Vector3f(100.0f, 100.0f, 100.0f)) hullbox.spatial { position = Vector3f(0.0f, 0.0f, 0.0f) } hullbox.name = "hullbox" hullbox.material { ambient = Vector3f(0.6f, 0.6f, 0.6f) diffuse = Vector3f(0.4f, 0.4f, 0.4f) specular = Vector3f(0.0f, 0.0f, 0.0f) cullingMode = Material.CullingMode.Front } scene.addChild(hullbox) thread { while (running) { container.spatial { rotation.rotateXYZ(0.001f, 0.001f, 0.0f) needsUpdateWorld = true needsUpdate = true updateWorld(true, false) } val inst = bInstanced.addInstance() inst.spatial { position = Random.random3DVectorFromRange(-40.0f, 40.0f) } inst.parent = container bInstanced.instances.removeAt(kotlin.random.Random.nextInt(bInstanced.instances.size - 1)) Thread.sleep(20) } } } companion object { @JvmStatic fun main(args: Array<String>) { MultiBoxInstancedExample().main() } } }
lgpl-3.0
90d3cca9e0e8cfa1d6dd46a5410493c6
30.781513
110
0.558964
3.875
false
false
false
false
bozaro/git-lfs-java
gitlfs-client/src/test/kotlin/ru/bozaro/gitlfs/client/HttpRecord.kt
1
5270
package ru.bozaro.gitlfs.client import com.google.common.base.Utf8 import com.google.common.io.BaseEncoding import org.apache.http.HttpEntityEnclosingRequest import org.apache.http.HttpResponse import org.apache.http.ProtocolVersion import org.apache.http.client.methods.CloseableHttpResponse import org.apache.http.client.methods.HttpUriRequest import org.apache.http.entity.ByteArrayEntity import org.apache.http.message.BasicHttpResponse import org.apache.http.protocol.HTTP import java.io.ByteArrayOutputStream import java.nio.charset.StandardCharsets import java.util.* /** * HTTP request-response pair for testing. * * @author Artem V. Navrotskiy */ class HttpRecord { val request: Request val response: Response constructor(request: HttpUriRequest, response: HttpResponse) { this.request = Request(request) this.response = Response(response) } private constructor() { request = Request() response = Response() } class Response { private val statusCode: Int private val statusText: String private val headers: TreeMap<String, String> private val body: ByteArray? internal constructor() { statusCode = 0 statusText = "" headers = TreeMap() body = null } internal constructor(response: HttpResponse) { statusCode = response.statusLine.statusCode statusText = response.statusLine.reasonPhrase headers = TreeMap() for (header in response.allHeaders) { headers[header.name] = header.value } ByteArrayOutputStream().use { stream -> response.entity.writeTo(stream) body = stream.toByteArray() response.entity = ByteArrayEntity(body) } } fun toHttpResponse(): CloseableHttpResponse { val response = CloseableBasicHttpResponse(ProtocolVersion("HTTP", 1, 0), statusCode, statusText) for ((key, value) in headers) response.addHeader(key, value) if (body != null) response.entity = ByteArrayEntity(body) return response } override fun toString(): String { val sb = StringBuilder() sb.append("HTTP/1.0 ").append(statusCode).append(" ").append(statusText).append("\n") for ((key, value) in headers) { sb.append(key).append(": ").append(value).append("\n") } if (body != null) { sb.append("\n").append(asString(body)) } return sb.toString() } } private class CloseableBasicHttpResponse( ver: ProtocolVersion, code: Int, reason: String ) : BasicHttpResponse(ver, code, reason), CloseableHttpResponse { override fun close() { // noop } } class Request { private val href: String private val method: String private val headers: TreeMap<String, String> private val body: ByteArray? internal constructor() { href = "" method = "" headers = TreeMap() body = null } internal constructor(request: HttpUriRequest) { href = request.uri.toString() method = request.method headers = TreeMap() val entityRequest = if (request is HttpEntityEnclosingRequest) request else null val entity = entityRequest?.entity if (entity != null) { if (entity.isChunked || entity.contentLength < 0) { request.addHeader(HTTP.TRANSFER_ENCODING, HTTP.CHUNK_CODING) } else { request.addHeader(HTTP.CONTENT_LEN, entity.contentLength.toString()) } val contentType = entity.contentType if (contentType != null) { headers[contentType.name] = contentType.value } ByteArrayOutputStream().use { buffer -> entity.writeTo(buffer) body = buffer.toByteArray() } entityRequest.entity = ByteArrayEntity(body) } else { body = null } for (header in request.allHeaders) { headers[header.name] = header.value } headers.remove(HTTP.TARGET_HOST) headers.remove(HTTP.USER_AGENT) } override fun toString(): String { val sb = StringBuilder() sb.append(method).append(" ").append(href).append("\n") for ((key, value) in headers) { sb.append(key).append(": ").append(value).append("\n") } if (body != null) { sb.append("\n").append(asString(body)) } return sb.toString() } } companion object { private fun asString(data: ByteArray): String { return if (Utf8.isWellFormed(data)) { String(data, StandardCharsets.UTF_8) } else { BaseEncoding.base16().encode(data) } } } }
lgpl-3.0
df31be7a5d95be59e2e6c7a3ac7347a6
31.9375
108
0.564137
4.971698
false
false
false
false
AshishKayastha/Movie-Guide
app/src/main/kotlin/com/ashish/movieguide/ui/movie/list/MovieDelegateAdapter.kt
1
1733
package com.ashish.movieguide.ui.movie.list import android.support.v7.widget.RecyclerView import android.view.ViewGroup import com.ashish.movieguide.data.models.Movie import com.ashish.movieguide.ui.base.recyclerview.BaseContentHolder import com.ashish.movieguide.ui.common.adapter.OnItemClickListener import com.ashish.movieguide.ui.common.adapter.RemoveListener import com.ashish.movieguide.ui.common.adapter.ViewType import com.ashish.movieguide.ui.common.adapter.ViewTypeDelegateAdapter import com.ashish.movieguide.utils.extensions.applyText import com.ashish.movieguide.utils.extensions.getPosterUrl import com.ashish.movieguide.utils.extensions.getYearOnly /** * Created by Ashish on Dec 30. */ class MovieDelegateAdapter( private val layoutId: Int, private var onItemClickListener: OnItemClickListener? ) : ViewTypeDelegateAdapter, RemoveListener { override fun onCreateViewHolder(parent: ViewGroup) = MovieHolder(parent) override fun onBindViewHolder(holder: RecyclerView.ViewHolder, item: ViewType) { (holder as MovieHolder).bindData(item as Movie) } override fun removeListener() { onItemClickListener = null } inner class MovieHolder(parent: ViewGroup) : BaseContentHolder<Movie>(parent, layoutId) { override fun bindData(item: Movie) = with(item) { contentTitle.applyText(title) contentSubtitle.applyText(releaseDate.getYearOnly()) ratingLabel?.setRating(if (rating != null && rating > 0) rating else voteAverage) super.bindData(item) } override fun getItemClickListener() = onItemClickListener override fun getImageUrl(item: Movie) = item.posterPath.getPosterUrl() } }
apache-2.0
dab957590dc56971027d11e2f4347a08
36.695652
93
0.755915
4.513021
false
false
false
false
android/project-replicator
code/codegen/src/main/kotlin/com/android/gradle/replicator/resgen/util/ResgenConstants.kt
1
2656
package com.android.gradle.replicator.resgen.util import com.android.gradle.replicator.parsing.ArgsParser import java.io.File // Immutable constants const val NUMBER_OF_ID_CHARACTERS = 4 //Number of base characters to use on unique identifiers class ResgenConstants (propertyFile: File? = null) { data class VectorImageConstants ( val MAX_VECTOR_IMAGE_SIZE_SMALL: Int, val MAX_VECTOR_IMAGE_SIZE_MEDIUM: Int, val MAX_VECTOR_IMAGE_SIZE_LARGE: Int) data class ValuesConstants ( val MAX_VALUES: Int, val MAX_ARRAY_ELEMENTS: Int, val MAX_STRING_WORD_COUNT: Int, val MAX_DIMENSION: Int) { val POSSIBLE_COLOR_DIGITS: List<Int> = listOf(3, 4, 6, 8) val DIMENSION_UNITS: List<String> = listOf("dp", "sp", "pt", "px", "mm", "in") } val vectorImage: VectorImageConstants val values: ValuesConstants init { val parser = ArgsParser() // Vector drawables val maxVectorImageSizeSmall = parser.option(propertyName = "maxVectorImageSizeSmall", argc = 1) val maxVectorImageSizeMedium = parser.option(propertyName = "maxVectorImageSizeMedium", argc = 1) val maxVectorImageSizeLarge = parser.option(propertyName = "maxVectorImageSizeLarge", argc = 1) // Values val maxValues = parser.option(propertyName = "maxValues", argc = 1) val maxArrayElements = parser.option(propertyName = "maxArrayElements", argc = 1) val maxStringWordCount = parser.option(propertyName = "maxStringWordCount", argc = 1) val maxDimension = parser.option(propertyName = "maxDimension", argc = 1) // Use default values if no property file exists propertyFile?.let { parser.parsePropertyFile(it) } // random(1, 2) is the same as requesting only the number 1, so to get the REAL max we need to add 1 vectorImage = VectorImageConstants( MAX_VECTOR_IMAGE_SIZE_SMALL = (maxVectorImageSizeSmall.orNull?.first?.toInt() ?: 100) + 1, MAX_VECTOR_IMAGE_SIZE_MEDIUM = (maxVectorImageSizeMedium.orNull?.first?.toInt() ?: 150) + 1, MAX_VECTOR_IMAGE_SIZE_LARGE = (maxVectorImageSizeLarge.orNull?.first?.toInt() ?: 200) + 1 ) // same as above values = ValuesConstants( MAX_VALUES = (maxValues.orNull?.first?.toInt() ?: 21) + 1, MAX_ARRAY_ELEMENTS = (maxArrayElements.orNull?.first?.toInt() ?: 20) + 1, MAX_STRING_WORD_COUNT = (maxStringWordCount.orNull?.first?.toInt() ?: 20) + 1, MAX_DIMENSION = (maxDimension.orNull?.first?.toInt() ?: 2048) + 1 ) } }
apache-2.0
3acd16f117e3ff7eff40a7ddaf105734
42.557377
108
0.648343
3.883041
false
false
false
false
retomerz/intellij-community
platform/script-debugger/debugger-ui/src/LineBreakpointManager.kt
3
9690
/* * Copyright 2000-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.debugger import com.intellij.icons.AllIcons import com.intellij.openapi.util.Key import com.intellij.openapi.util.Ref import com.intellij.util.SmartList import com.intellij.util.containers.putValue import com.intellij.util.containers.remove import com.intellij.xdebugger.XSourcePosition import com.intellij.xdebugger.breakpoints.XLineBreakpoint import gnu.trove.THashMap import gnu.trove.THashSet import org.jetbrains.concurrency.Promise import org.jetbrains.concurrency.resolvedPromise import java.util.concurrent.atomic.AtomicBoolean private val IDE_TO_VM_BREAKPOINTS_KEY = Key.create<THashMap<XLineBreakpoint<*>, MutableList<Breakpoint>>>("ideToVmBreakpoints") abstract class LineBreakpointManager(internal val debugProcess: DebugProcessImpl<*>) { protected val vmToIdeBreakpoints = THashMap<Breakpoint, MutableList<XLineBreakpoint<*>>>() private val runToLocationBreakpoints = THashSet<Breakpoint>() private val lock = Object() open fun isAnyFirstLineBreakpoint(breakpoint: Breakpoint) = false private val breakpointResolvedListenerAdded = AtomicBoolean() fun setBreakpoint(vm: Vm, breakpoint: XLineBreakpoint<*>) { val target = synchronized (lock) { IDE_TO_VM_BREAKPOINTS_KEY.get(vm)?.let { it.get(breakpoint) } } if (target == null) { setBreakpoint(vm, breakpoint, debugProcess.getLocationsForBreakpoint(vm, breakpoint)) } else { val breakpointManager = vm.breakpointManager for (vmBreakpoint in target) { if (!vmBreakpoint.enabled) { vmBreakpoint.enabled = true breakpointManager.flush(vmBreakpoint) .rejected { debugProcess.session.updateBreakpointPresentation(breakpoint, AllIcons.Debugger.Db_invalid_breakpoint, it.message) } } } } } fun removeBreakpoint(vm: Vm, breakpoint: XLineBreakpoint<*>, temporary: Boolean): Promise<*> { val disable = temporary && debugProcess.mainVm!!.breakpointManager.getMuteMode() !== BreakpointManager.MUTE_MODE.NONE beforeBreakpointRemoved(breakpoint, disable) return doRemoveBreakpoint(vm, breakpoint, disable) } protected open fun beforeBreakpointRemoved(breakpoint: XLineBreakpoint<*>, disable: Boolean) { } fun doRemoveBreakpoint(vm: Vm, breakpoint: XLineBreakpoint<*>, disable: Boolean = false): Promise<*> { var vmBreakpoints: Collection<Breakpoint> = emptySet() synchronized (lock) { if (disable) { val list = IDE_TO_VM_BREAKPOINTS_KEY.get(vm)?.let { it.get(breakpoint) } ?: return resolvedPromise() val iterator = list.iterator() vmBreakpoints = list while (iterator.hasNext()) { val vmBreakpoint = iterator.next() if ((vmToIdeBreakpoints.get(vmBreakpoint)?.size ?: -1) > 1) { // we must not disable vm breakpoint - it is used for another ide breakpoints iterator.remove() } } } else { vmBreakpoints = IDE_TO_VM_BREAKPOINTS_KEY.get(vm)?.let { it.remove(breakpoint) } ?: return resolvedPromise() if (!vmBreakpoints.isEmpty()) { for (vmBreakpoint in vmBreakpoints) { vmToIdeBreakpoints.remove(vmBreakpoint, breakpoint) if (vmToIdeBreakpoints.containsKey(vmBreakpoint)) { // we must not remove vm breakpoint - it is used for another ide breakpoints return resolvedPromise() } } } } } if (vmBreakpoints.isEmpty()) { return resolvedPromise() } val breakpointManager = vm.breakpointManager val promises = SmartList<Promise<*>>() if (disable) { for (vmBreakpoint in vmBreakpoints) { vmBreakpoint.enabled = false promises.add(breakpointManager.flush(vmBreakpoint)) } } else { for (vmBreakpoint in vmBreakpoints) { promises.add(breakpointManager.remove(vmBreakpoint)) } } return Promise.all(promises) } fun setBreakpoint(vm: Vm, breakpoint: XLineBreakpoint<*>, locations: List<Location>, promiseRef: Ref<Promise<out Breakpoint>>? = null) { if (locations.isEmpty()) { return } val vmBreakpoints = SmartList<Breakpoint>() for (location in locations) { doSetBreakpoint(vm, breakpoint, location, false, promiseRef)?.let { vmBreakpoints.add(it) } } synchronized (lock) { var list = IDE_TO_VM_BREAKPOINTS_KEY.get(vm) if (list == null) { list = vm.putUserDataIfAbsent(IDE_TO_VM_BREAKPOINTS_KEY, THashMap()) } list.put(breakpoint, vmBreakpoints) for (vmBreakpoint in vmBreakpoints) { vmToIdeBreakpoints.putValue(vmBreakpoint, breakpoint) } } } protected fun doSetBreakpoint(vm: Vm, breakpoint: XLineBreakpoint<*>?, location: Location, isTemporary: Boolean, promiseRef: Ref<Promise<out Breakpoint>>? = null): Breakpoint? { if (breakpointResolvedListenerAdded.compareAndSet(false, true)) { vm.breakpointManager.addBreakpointListener(object : BreakpointListener { override fun resolved(breakpoint: Breakpoint) { synchronized (lock) { vmToIdeBreakpoints[breakpoint] }?.let { for (ideBreakpoint in it) { debugProcess.session.updateBreakpointPresentation(ideBreakpoint, AllIcons.Debugger.Db_verified_breakpoint, null) } } } override fun errorOccurred(breakpoint: Breakpoint, errorMessage: String?) { if (isAnyFirstLineBreakpoint(breakpoint)) { return } if (synchronized (lock) { runToLocationBreakpoints.remove(breakpoint) }) { debugProcess.session.reportError("Cannot run to cursor: $errorMessage") return } synchronized (lock) { vmToIdeBreakpoints.get(breakpoint) } ?.let { for (ideBreakpoint in it) { debugProcess.session.updateBreakpointPresentation(ideBreakpoint, AllIcons.Debugger.Db_invalid_breakpoint, errorMessage) } } } override fun nonProvisionalBreakpointRemoved(breakpoint: Breakpoint) { synchronized (lock) { vmToIdeBreakpoints.remove(breakpoint)?.let { for (ideBreakpoint in it) { IDE_TO_VM_BREAKPOINTS_KEY.get(vm)?.let { it.remove(ideBreakpoint, breakpoint) } } it } } ?.let { for (ideBreakpoint in it) { setBreakpoint(vm, ideBreakpoint, debugProcess.getLocationsForBreakpoint(vm, ideBreakpoint)) } } } }) } val breakpointManager = vm.breakpointManager val target = createTarget(breakpoint, breakpointManager, location, isTemporary) checkDuplicates(target, location, breakpointManager)?.let { promiseRef?.set(resolvedPromise(it)) return it } return breakpointManager.setBreakpoint(target, location.line, location.column, location.url, breakpoint?.conditionExpression?.expression, promiseRef = promiseRef) } protected abstract fun createTarget(breakpoint: XLineBreakpoint<*>?, breakpointManager: BreakpointManager, location: Location, isTemporary: Boolean): BreakpointTarget protected open fun checkDuplicates(newTarget: BreakpointTarget, location: Location, breakpointManager: BreakpointManager): Breakpoint? = null fun runToLocation(position: XSourcePosition, vm: Vm) { val addedBreakpoints = doRunToLocation(position) if (addedBreakpoints.isEmpty()) { return } synchronized (lock) { runToLocationBreakpoints.addAll(addedBreakpoints) } debugProcess.resume(vm) } protected abstract fun doRunToLocation(position: XSourcePosition): List<Breakpoint> fun isRunToCursorBreakpoints(breakpoints: List<Breakpoint>) = synchronized (runToLocationBreakpoints) { runToLocationBreakpoints.containsAll(breakpoints) } fun isRunToCursorBreakpoint(breakpoint: Breakpoint) = synchronized (runToLocationBreakpoints) { runToLocationBreakpoints.contains(breakpoint) } fun updateAllBreakpoints(vm: Vm) { val array = synchronized (lock) { IDE_TO_VM_BREAKPOINTS_KEY.get(vm)?.let { it.keys.toTypedArray() } } ?: return for (breakpoint in array) { removeBreakpoint(vm, breakpoint, false) setBreakpoint(vm, breakpoint) } } fun removeAllBreakpoints(vm: Vm): Promise<*> { synchronized (lock) { IDE_TO_VM_BREAKPOINTS_KEY.get(vm)?.let { it.clear() } vmToIdeBreakpoints.clear() runToLocationBreakpoints.clear() } return vm.breakpointManager.removeAll() } fun clearRunToLocationBreakpoints(vm: Vm) { var breakpoints = synchronized (lock) { if (runToLocationBreakpoints.isEmpty) { return@clearRunToLocationBreakpoints } var breakpoints = runToLocationBreakpoints.toArray<Breakpoint>(arrayOfNulls<Breakpoint>(runToLocationBreakpoints.size)) runToLocationBreakpoints.clear() breakpoints } val breakpointManager = vm.breakpointManager for (breakpoint in breakpoints) { breakpointManager.remove(breakpoint) } } }
apache-2.0
962f7a1c34d4b0af1b4bbb1f5e17cabe
37.764
179
0.689267
4.906329
false
false
false
false
mdanielwork/intellij-community
plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/intentions/elements/CreateFieldAction.kt
6
5393
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.groovy.annotator.intentions.elements import com.intellij.codeInsight.daemon.QuickFixBundle.message import com.intellij.codeInsight.daemon.impl.quickfix.CreateFromUsageBaseFix.positionCursor import com.intellij.codeInsight.daemon.impl.quickfix.CreateFromUsageBaseFix.startTemplate import com.intellij.codeInsight.template.Template import com.intellij.codeInsight.template.TemplateEditingAdapter import com.intellij.lang.jvm.JvmModifier import com.intellij.lang.jvm.actions.* import com.intellij.openapi.application.runWriteAction import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.psi.PsiDocumentManager import com.intellij.psi.PsiFile import com.intellij.psi.PsiType import com.intellij.psi.codeStyle.CodeStyleManager import com.intellij.psi.presentation.java.ClassPresentationUtil.getNameForClass import com.intellij.psi.util.PsiTreeUtil import com.intellij.psi.util.PsiUtil import org.jetbrains.plugins.groovy.annotator.intentions.GroovyCreateFieldFromUsageHelper import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElementFactory import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrField import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrTypeDefinition import org.jetbrains.plugins.groovy.lang.psi.impl.synthetic.GroovyScriptClass import org.jetbrains.plugins.groovy.lang.psi.util.GroovyCommonClassNames internal class CreateFieldAction( target: GrTypeDefinition, request: CreateFieldRequest, private val constantField: Boolean ) : CreateFieldActionBase(target, request), JvmGroupIntentionAction { override fun getActionGroup(): JvmActionGroup = if (constantField) CreateConstantActionGroup else CreateFieldActionGroup override fun getText(): String { val what = request.fieldName val where = getNameForClass(target, false) return if (constantField) { message("create.constant.from.usage.full.text", what, where) } else { message("create.field.from.usage.full.text", what, where) } } override fun invoke(project: Project, editor: Editor?, file: PsiFile?) { GroovyFieldRenderer(project, constantField, target, request).doRender() } } internal val constantModifiers = setOf( JvmModifier.STATIC, JvmModifier.FINAL ) private class GroovyFieldRenderer( val project: Project, val constantField: Boolean, val targetClass: GrTypeDefinition, val request: CreateFieldRequest ) { val helper = GroovyCreateFieldFromUsageHelper() val typeConstraints = createConstraints(project, request.fieldType).toTypedArray() private val modifiersToRender: Collection<JvmModifier> get() { return if (constantField) { if (targetClass.isInterface) { // interface fields are public static final implicitly, so modifiers don't have to be rendered request.modifiers - constantModifiers - visibilityModifiers } else { // render static final explicitly request.modifiers + constantModifiers } } else { // render as is request.modifiers } } fun doRender() { var field = renderField() field = insertField(field) startTemplate(field) } private fun renderField(): GrField { val elementFactory = GroovyPsiElementFactory.getInstance(project) val field = elementFactory.createField(request.fieldName, PsiType.INT) // clean template modifiers field.modifierList?.let { list -> list.firstChild?.let { list.deleteChildRange(it, list.lastChild) } } // setup actual modifiers for (modifier in modifiersToRender.map(JvmModifier::toPsiModifier)) { PsiUtil.setModifierProperty(field, modifier, true) } if (targetClass is GroovyScriptClass) field.modifierList?.addAnnotation(GroovyCommonClassNames.GROOVY_TRANSFORM_FIELD) if (constantField) { field.initializerGroovy = elementFactory.createExpressionFromText("0", null) } return field } private fun insertField(field: GrField): GrField { return helper.insertFieldImpl(targetClass, field, null) } private fun startTemplate(field: GrField) { val targetFile = targetClass.containingFile ?: return val newEditor = positionCursor(field.project, targetFile, field) ?: return val substitutor = request.targetSubstitutor.toPsiSubstitutor(project) val template = helper.setupTemplateImpl(field, typeConstraints, targetClass, newEditor, null, constantField, substitutor) val listener = MyTemplateListener(project, newEditor, targetFile) startTemplate(newEditor, template, project, listener, null) } } private class MyTemplateListener(val project: Project, val editor: Editor, val file: PsiFile) : TemplateEditingAdapter() { override fun templateFinished(template: Template, brokenOff: Boolean) { PsiDocumentManager.getInstance(project).commitDocument(editor.document) val offset = editor.caretModel.offset val psiField = PsiTreeUtil.findElementOfClassAtOffset(file, offset, GrField::class.java, false) ?: return runWriteAction { CodeStyleManager.getInstance(project).reformat(psiField) } editor.caretModel.moveToOffset(psiField.textRange.endOffset - 1) } }
apache-2.0
acff0bfe1f02b2054134cd28d66eef5f
37.248227
140
0.767106
4.661193
false
false
false
false
mdanielwork/intellij-community
plugins/java-decompiler/plugin/test/org/jetbrains/java/decompiler/IdeaDecompilerTest.kt
3
9125
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.java.decompiler import com.intellij.JavaTestUtil import com.intellij.codeInsight.daemon.impl.IdentifierHighlighterPassFactory import com.intellij.codeInsight.navigation.actions.GotoDeclarationAction import com.intellij.execution.filters.LineNumbersMapping import com.intellij.ide.highlighter.ArchiveFileType import com.intellij.ide.structureView.StructureViewBuilder import com.intellij.ide.structureView.impl.java.JavaAnonymousClassesNodeProvider import com.intellij.ide.structureView.newStructureView.StructureViewComponent import com.intellij.openapi.application.PluginPathManager import com.intellij.openapi.fileEditor.FileEditorManager import com.intellij.openapi.fileEditor.ex.FileEditorManagerEx import com.intellij.openapi.fileEditor.impl.EditorHistoryManager import com.intellij.openapi.fileTypes.StdFileTypes import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.util.registry.Registry import com.intellij.openapi.util.registry.RegistryValue import com.intellij.openapi.vfs.* import com.intellij.pom.Navigatable import com.intellij.psi.PsiCompiledFile import com.intellij.psi.PsiManager import com.intellij.psi.impl.compiled.ClsFileImpl import com.intellij.testFramework.PlatformTestUtil import com.intellij.testFramework.fixtures.LightCodeInsightFixtureTestCase import com.intellij.util.io.URLUtil class IdeaDecompilerTest : LightCodeInsightFixtureTestCase() { override fun setUp() { super.setUp() myFixture.testDataPath = "${PluginPathManager.getPluginHomePath("java-decompiler")}/plugin/testData" } override fun tearDown() { try { FileEditorManagerEx.getInstanceEx(project).closeAllFiles() EditorHistoryManager.getInstance(project).removeAllFiles() } finally { super.tearDown() } } fun testSimple() { val file = getTestFile("${PlatformTestUtil.getRtJarPath()}!/java/lang/String.class") val decompiled = IdeaDecompiler().getText(file).toString() assertTrue(decompiled, decompiled.startsWith("${IdeaDecompiler.BANNER}package java.lang;\n")) assertTrue(decompiled, decompiled.contains("public final class String")) assertTrue(decompiled, decompiled.contains("@deprecated")) assertTrue(decompiled, decompiled.contains("private static class CaseInsensitiveComparator")) assertFalse(decompiled, decompiled.contains("/* compiled code */")) assertFalse(decompiled, decompiled.contains("synthetic")) } fun testStubCompatibility() { val visitor = MyFileVisitor(psiManager) Registry.get("decompiler.dump.original.lines").withValue(true) { VfsUtilCore.visitChildrenRecursively(getTestFile("${JavaTestUtil.getJavaTestDataPath()}/psi/cls/mirror"), visitor) VfsUtilCore.visitChildrenRecursively(getTestFile("${PluginPathManager.getPluginHomePath("java-decompiler")}/engine/testData/classes"), visitor) VfsUtilCore.visitChildrenRecursively(getTestFile("${PlatformTestUtil.getRtJarPath()}!/java/lang"), visitor) } } fun testNavigation() { myFixture.openFileInEditor(getTestFile("Navigation.class")) doTestNavigation(11, 14, 14, 10) // to "m2()" doTestNavigation(15, 21, 14, 17) // to "int i" doTestNavigation(16, 28, 15, 13) // to "int r" } private fun doTestNavigation(line: Int, column: Int, expectedLine: Int, expectedColumn: Int) { val target = GotoDeclarationAction.findTargetElement(project, myFixture.editor, offset(line, column)) as Navigatable target.navigate(true) val expected = offset(expectedLine, expectedColumn) assertEquals(expected, myFixture.caretOffset) } private fun offset(line: Int, column: Int): Int = myFixture.editor.document.getLineStartOffset(line - 1) + column - 1 fun testHighlighting() { myFixture.openFileInEditor(getTestFile("Navigation.class")) IdentifierHighlighterPassFactory.doWithHighlightingEnabled { myFixture.editor.caretModel.moveToOffset(offset(11, 14)) // m2(): usage, declaration assertEquals(2, myFixture.doHighlighting().size) myFixture.editor.caretModel.moveToOffset(offset(14, 10)) // m2(): usage, declaration assertEquals(2, myFixture.doHighlighting().size) myFixture.editor.caretModel.moveToOffset(offset(14, 17)) // int i: usage, declaration assertEquals(2, myFixture.doHighlighting().size) myFixture.editor.caretModel.moveToOffset(offset(15, 21)) // int i: usage, declaration assertEquals(2, myFixture.doHighlighting().size) myFixture.editor.caretModel.moveToOffset(offset(15, 13)) // int r: usage, declaration assertEquals(2, myFixture.doHighlighting().size) myFixture.editor.caretModel.moveToOffset(offset(16, 28)) // int r: usage, declaration assertEquals(2, myFixture.doHighlighting().size) myFixture.editor.caretModel.moveToOffset(offset(19, 24)) // throws: declaration, m4() call assertEquals(2, myFixture.doHighlighting().size) } } fun testLineNumberMapping() { Registry.get("decompiler.use.line.mapping").withValue(true) { val file = getTestFile("LineNumbers.class") assertNull(file.getUserData(LineNumbersMapping.LINE_NUMBERS_MAPPING_KEY)) IdeaDecompiler().getText(file) val mapping = file.getUserData(LineNumbersMapping.LINE_NUMBERS_MAPPING_KEY)!! assertEquals(11, mapping.bytecodeToSource(3)) assertEquals(3, mapping.sourceToBytecode(11)) assertEquals(23, mapping.bytecodeToSource(13)) assertEquals(13, mapping.sourceToBytecode(23)) assertEquals(-1, mapping.bytecodeToSource(1000)) assertEquals(-1, mapping.sourceToBytecode(1000)) } } fun testPerformance() { val decompiler = IdeaDecompiler() val file = getTestFile("${PlatformTestUtil.getRtJarPath()}!/javax/swing/JTable.class") PlatformTestUtil.startPerformanceTest("decompiling JTable.class", 10000) { decompiler.getText(file) }.assertTiming() } fun testStructureView() { val file = getTestFile("StructureView.class") file.parent.children ; file.parent.refresh(false, true) // inner classes checkStructure(file, """ -StructureView.class -StructureView -B B() build(int): StructureView StructureView() getData(): int setData(int): void data: int""") (PsiManager.getInstance(project).findFile(file) as? PsiCompiledFile)?.decompiledPsiFile checkStructure(file, """ -StructureView.java -StructureView -B B() -build(int): StructureView -${'$'}1 class initializer StructureView() getData(): int setData(int): void data: int""") } private fun checkStructure(file: VirtualFile, s: String) { val editor = FileEditorManager.getInstance(project).openFile(file, false)[0] val builder = StructureViewBuilder.PROVIDER.getStructureViewBuilder(StdFileTypes.CLASS, file, project)!! val svc = builder.createStructureView(editor, project) as StructureViewComponent Disposer.register(myFixture.testRootDisposable, svc) svc.setActionActive(JavaAnonymousClassesNodeProvider.ID, true) PlatformTestUtil.expandAll(svc.tree) PlatformTestUtil.assertTreeEqual(svc.tree, s.trimIndent()) } private fun getTestFile(name: String): VirtualFile { val path = if (FileUtil.isAbsolute(name)) name else "${myFixture.testDataPath}/${name}" val fs = if (path.contains(URLUtil.JAR_SEPARATOR)) StandardFileSystems.jar() else StandardFileSystems.local() return fs.refreshAndFindFileByPath(path)!! } private fun RegistryValue.withValue(testValue: Boolean, block: () -> Unit) { val currentValue = asBoolean() try { setValue(testValue) block() } finally { setValue(currentValue) } } private class MyFileVisitor(private val psiManager: PsiManager) : VirtualFileVisitor<Any>() { override fun visitFile(file: VirtualFile): Boolean { if (file.isDirectory) { println(file.path) } else if (file.fileType === StdFileTypes.CLASS && !file.name.contains('$')) { val decompiled = (psiManager.findFile(file)!! as ClsFileImpl).mirror.text assertTrue(file.path, decompiled.startsWith(IdeaDecompiler.BANNER) || file.name.endsWith("-info.class")) // check that no mapped line number is on an empty line val prefix = "// " decompiled.split("\n").dropLastWhile(String::isEmpty).toTypedArray().forEach { s -> val pos = s.indexOf(prefix) if (pos == 0 && prefix.length < s.length && Character.isDigit(s[prefix.length])) { fail("Incorrect line mapping in file " + file.path + " line: " + s) } } } else if (ArchiveFileType.INSTANCE == file.fileType) { val jarRoot = JarFileSystem.getInstance().getRootByLocal(file) if (jarRoot != null) { VfsUtilCore.visitChildrenRecursively(jarRoot, this) } } return true } } }
apache-2.0
b3d6580b347f7f786a1bb7b7000ea0b9
42.251185
149
0.725918
4.681888
false
true
false
false
alexxxdev/kGen
src/ru/alexxxdev/kGen/ClassSpec.kt
1
3733
package ru.alexxxdev.kGen import ru.alexxxdev.kGen.FieldSpec.PropertyType import ru.alexxxdev.kGen.FieldSpec.PropertyType.READONLY import ru.alexxxdev.kGen.FieldSpec.ValueType import ru.alexxxdev.kGen.FieldSpec.ValueType.NOTNULL /** * Created by alexxxdev on 28.02.17. */ class ClassSpec(val kind: Kind, internal val name: String) : IAppendable { enum class Kind { CLASS, INTERFACE, OBJECT } private var imports = mutableListOf<TypeName>() private var fields = mutableListOf<FieldSpec>() private var methods = mutableListOf<MethodSpec>() private var parameterized = mutableListOf<ParameterizedName>() private var modifiers: Array<Modifier> = emptyArray() val listImports get() = this.imports.distinctBy { (it as ru.alexxxdev.kGen.ClassName).canonicalName } operator fun Modifier.unaryPlus() { modifiers = modifiers.plus(this) } operator fun ParameterizedName.unaryPlus() { parameterized.add(this) } fun field(name: String, propertyType: PropertyType = READONLY, valueType: ValueType = NOTNULL, init: FieldSpec.() -> String) = addField(FieldSpec(name, propertyType, valueType), init) fun method(name: String, vararg mods: Modifier, init: MethodSpec.() -> Unit) = addMethod(MethodSpec(name), mods = *mods, init = init) private fun addMethod(methodSpec: MethodSpec, vararg mods: Modifier, init: MethodSpec.() -> Unit): MethodSpec { methodSpec.init() mods.forEach { methodSpec.addModificator(it) } methodSpec.build() methods.add(methodSpec) return methodSpec } private fun addField(fieldSpec: FieldSpec, init: FieldSpec.() -> String): FieldSpec { fieldSpec.initializer = fieldSpec.init() fieldSpec.build() fields.add(fieldSpec) return fieldSpec } fun build() { methods.forEach { imports.addAll(it.listImports) } fields.forEach { imports.addAll(it.listImports) } } override fun writeTo(codeWriter: CodeWriter) { modifiers.forEach { when (it) { Modifier.DEFAULT -> { } else -> { codeWriter.out("${it.name.toLowerCase()} ") } } } when (kind) { ClassSpec.Kind.CLASS -> codeWriter.out("class $name") ClassSpec.Kind.INTERFACE -> codeWriter.out("interface $name") ClassSpec.Kind.OBJECT -> codeWriter.out("object $name") } if (parameterized.isNotEmpty()) { codeWriter.out("<") parameterized.forEachIndexed { index, parameterizedName -> if (index > 0) codeWriter.out(",") if (parameterizedName.name == null) { parameterizedName.className?.let { codeWriter.out(it.name) } } else { codeWriter.out(parameterizedName.name) parameterizedName.className?.let { codeWriter.out(": ${it.name}") } } } codeWriter.out(">") } codeWriter.out("{") codeWriter.indent() fields.sortedBy { it.name } .forEach { codeWriter.out("\n") it.writeTo(codeWriter) } methods.sortedBy { it.name } .forEach { codeWriter.out("\n\n") it.writeTo(codeWriter) } codeWriter.unindent() codeWriter.out("\n") codeWriter.out("}") } }
apache-2.0
a1ad17bed351684ab07b8c1aa950cd90
30.108333
187
0.560675
4.841764
false
false
false
false
android/privacy-codelab
PhotoLog_start/src/main/java/com/example/photolog_start/PhotoGrid.kt
1
2665
/* * Copyright (C) 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.photolog_start import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.aspectRatio import androidx.compose.foundation.layout.width import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Close import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.FilledTonalIconButton import androidx.compose.material3.Icon import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.unit.dp import coil.compose.AsyncImage import java.io.File @OptIn(ExperimentalMaterial3Api::class) @Composable fun PhotoGrid( modifier: Modifier, photos: List<File>, onRemove: ((photo: File) -> Unit)? = null ) { Row(modifier) { repeat(MAX_LOG_PHOTOS_LIMIT) { index -> val file = photos.getOrNull(index) if (file == null) { Box(Modifier.weight(1f)) } else { Box( contentAlignment = Alignment.TopEnd, modifier = Modifier .weight(1f) .clip(RoundedCornerShape(10.dp)) .aspectRatio(1f) ) { AsyncImage( model = file, contentDescription = null, contentScale = ContentScale.Crop ) if (onRemove != null) { FilledTonalIconButton(onClick = { onRemove(file) }) { Icon(Icons.Filled.Close, null) } } } } Spacer(Modifier.width(8.dp)) } } }
apache-2.0
596d0e9f3a8775d2739d2cd38bec5e24
34.078947
77
0.637523
4.610727
false
false
false
false
MasoodFallahpoor/InfoCenter
InfoCenter/src/main/java/com/fallahpoor/infocenter/Utils.kt
1
2450
/* Copyright (C) 2014-2016 Masood Fallahpoor This file is part of Info Center. Info Center 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. Info Center 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 Info Center. If not, see <http://www.gnu.org/licenses/>. */ package com.fallahpoor.infocenter import android.content.Context import android.text.TextUtils import java.util.* /** * This class provides utility methods for other classes. */ class Utils(private val context: Context) { val locale: Locale = Locale("fa", "IR") // Converts and formats the given number of bytes to MB or GB fun getFormattedSize(size: Long): String { if (size < 0) { return context.getString(R.string.unknown) } val mb = size / 1048576L val gb: Double val MB = context.getString(R.string.sub_item_mb) val GB = context.getString(R.string.sub_item_gb) val fmtSize: String if (mb < 1024) { fmtSize = String.format(locale, "%d", mb) + " " + MB } else { gb = mb.toDouble() / 1024 fmtSize = String.format(locale, "%.2f", gb) + " " + GB } return fmtSize } // end method getFormattedSize // Converts and formats the given frequency from Hz to MHz or GHz fun getFormattedFrequency(frequency: String): String { if (TextUtils.isEmpty(frequency)) { return context.getString(R.string.unknown) } val frequencyDbl = java.lang.Long.valueOf(frequency).toDouble() / 1000 val MHz = context.getString(R.string.cpu_sub_item_mhz) val GHz = context.getString(R.string.cpu_sub_item_ghz) val fmtFrequency: String fmtFrequency = if (frequencyDbl < 1000) { String.format(locale, "%.0f %s", frequencyDbl, MHz) } else { String.format(locale, "%.1f %s", frequencyDbl / 1000, GHz) } return fmtFrequency } } // end class Utils
gpl-3.0
b8ebcd66738f3cde39816e9ae1d5366c
30.012658
78
0.642041
4.049587
false
false
false
false
DreierF/MyTargets
app/src/main/java/de/dreier/mytargets/features/training/details/TrainingViewModel.kt
1
2579
/* * Copyright (C) 2018 Florian Dreier * * This file is part of MyTargets. * * MyTargets is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 * as published by the Free Software Foundation. * * MyTargets 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. */ package de.dreier.mytargets.features.training.details import android.app.Application import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.Transformations import de.dreier.mytargets.app.ApplicationInstance import de.dreier.mytargets.base.db.RoundRepository import de.dreier.mytargets.shared.models.db.Round import de.dreier.mytargets.shared.models.db.Training import de.dreier.mytargets.utils.LiveDataUtil2 class TrainingViewModel(app: Application) : AndroidViewModel(app) { val trainingId = MutableLiveData<Long?>() val training: LiveData<Training> val rounds: LiveData<List<Round>> val trainingAndRounds: LiveData<Pair<Training, List<Round>>> private val trainingDAO = ApplicationInstance.db.trainingDAO() private val roundDAO = ApplicationInstance.db.roundDAO() private val roundRepository = RoundRepository(ApplicationInstance.db) init { training = Transformations.switchMap(trainingId) { id -> if (id == null) { null } else { trainingDAO.loadTrainingLive(id) } } rounds = Transformations.switchMap(trainingId) { id -> if (id == null) { null } else { roundDAO.loadRoundsLive(id) } } trainingAndRounds = LiveDataUtil2<Training, List<Round>, Pair<Training, List<Round>>>().map( training, rounds ) { training, rounds -> Pair(training, rounds) } } fun setTrainingId(trainingId: Long?) { this.trainingId.value = trainingId } fun setTrainingComment(comment: String) { trainingDAO.updateComment(trainingId.value!!, comment) } fun deleteRound(item: Round): () -> Round { val round = roundRepository.loadAugmentedRound(item) roundDAO.deleteRound(item) return { roundRepository.insertRound(round) item } } }
gpl-2.0
c1eab2ac57dd8810450abc26c393d4d0
31.2375
100
0.674292
4.500873
false
false
false
false
olegarx/restler
restler-integration-tests/src/main/kotlin/org/restler/integration/Controller.kt
2
4755
package org.restler.integration import org.springframework.scheduling.annotation.Async import org.springframework.scheduling.annotation.AsyncResult import org.springframework.security.core.context.SecurityContextHolder import org.springframework.util.FileCopyUtils import org.springframework.web.bind.annotation.* import org.springframework.web.context.request.async.DeferredResult import org.springframework.web.multipart.MultipartFile import java.io.BufferedOutputStream import java.io.File import java.io.FileOutputStream import java.util.* import java.util.concurrent.Callable import java.util.concurrent.Future import java.util.stream.Collectors import kotlin.concurrent.thread @RestController open class Controller : ControllerApi { var filesDirectory: String; init { var root = File("").canonicalPath filesDirectory = "$root/files"; var directory = File(filesDirectory) if(!(directory.exists() && directory.isDirectory)) { directory.mkdir() } } @RequestMapping("get") override fun publicGet() = "OK" @RequestMapping("secured/get") override fun securedGet() = "Secure OK" @RequestMapping("forceLogout") override fun logout(): String { SecurityContextHolder.getContext().authentication.isAuthenticated = false return "OK" } @RequestMapping("getDeferred") fun deferredGet(): DeferredResult<String> { var deferredResult = DeferredResult<String>() thread { Thread.sleep(1000) deferredResult.setResult("Deferred OK") } return deferredResult } @RequestMapping("getCallable") override fun callableGet(): Callable<String> { return Callable ( fun(): String { Thread.sleep(1000) return "Callable OK" } ) } @Async @RequestMapping("getFuture") override fun futureGet(): Future<String> { Thread.sleep(1000) return AsyncResult<String>("Future OK") } @RequestMapping("getWithVariable/{title}") override fun getWithVariable(@PathVariable(value = "title") title: String, @RequestParam(value = "name") name: String): String { return name } @RequestMapping("console") override fun console(@RequestParam(value = "text") text: String) { System.out.println(text); } @RequestMapping("throwException") @Throws(Throwable::class) override fun throwException(@RequestParam exceptionClass: String): String { throw Class.forName(exceptionClass).asSubclass(Throwable::class.java).newInstance() } @RequestMapping("listOfStrings") override fun getListOfStrings() = listOf("item1", "item2") private val simpleDto1 = SimpleDto("1", "dto1") private val simpleDto2 = SimpleDto("2", "dto2") @RequestMapping("listOfDtos") override fun getListOfDtos() = listOf(simpleDto1, simpleDto2) @RequestMapping("setOfDtos") override fun getSetOfDtos() = setOf(simpleDto1, simpleDto2) @RequestMapping("mapOfDtos") override fun getMapOfDtos() = mapOf("1" to simpleDto1, "2" to simpleDto2) @RequestMapping("isNull") override fun isNull(@RequestParam(value = "str", required = false) str: String?) = str === null @RequestMapping("valueOf") override fun valueOf(@RequestParam(value = "str", required = false) str: String?) = when (str) { null -> "The Null" "" -> "Empty string object" else -> "String object with value: $str" } @RequestMapping("void") override fun returnVoid() {} @RequestMapping("postBody", method = arrayOf(RequestMethod.POST)) override fun postBody(@RequestBody body: Any) = body @RequestMapping(method = arrayOf(RequestMethod.GET), value = "/upload") fun provideUploadInfo(): List<String> { var filesFolder = File("$filesDirectory/"); var fileNames = Arrays.stream(filesFolder.listFiles()) .map({ it.name }) .collect(Collectors.toList<String>()) return fileNames; } @RequestMapping(method = arrayOf(RequestMethod.POST), value = "/upload") override fun fileUpload(@RequestParam("name") name: String, @RequestParam("file") file: MultipartFile): String { if (!file.isEmpty) { try { var stream = BufferedOutputStream(FileOutputStream(File("$filesDirectory/$name"))); FileCopyUtils.copy(file.inputStream, stream); stream.close(); return "Success" } catch (e: Exception) { return "Failed to upload $name => " + e.message; } } return "File is empty." } }
apache-2.0
033190dcd215fa577d7a789d956b06fe
30.912752
132
0.651525
4.580925
false
false
false
false
google/intellij-community
platform/lang-impl/src/com/intellij/workspaceModel/ide/impl/legacyBridge/module/ModuleBridgeLoaderService.kt
1
4871
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.workspaceModel.ide.impl.legacyBridge.module import com.intellij.diagnostic.Activity import com.intellij.diagnostic.StartUpMeasurer import com.intellij.diagnostic.runActivity import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.EDT import com.intellij.openapi.components.ComponentManagerEx import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.module.ModuleManager import com.intellij.openapi.project.Project import com.intellij.openapi.project.impl.ProjectServiceContainerInitializedListener import com.intellij.openapi.projectRoots.ProjectJdkTable import com.intellij.openapi.roots.ProjectRootManager import com.intellij.openapi.roots.libraries.LibraryTablesRegistrar import com.intellij.platform.PlatformProjectOpenProcessor.Companion.PROJECT_LOADED_FROM_CACHE_BUT_HAS_NO_MODULES import com.intellij.workspaceModel.ide.JpsProjectLoadedListener import com.intellij.workspaceModel.ide.WorkspaceModel import com.intellij.workspaceModel.ide.WorkspaceModelTopics import com.intellij.workspaceModel.ide.impl.WorkspaceModelImpl import com.intellij.workspaceModel.ide.impl.jps.serialization.JpsProjectModelSynchronizer import com.intellij.workspaceModel.ide.impl.legacyBridge.library.ProjectLibraryTableBridgeImpl import com.intellij.workspaceModel.ide.impl.legacyBridge.project.ProjectRootManagerBridge import com.intellij.workspaceModel.storage.bridgeEntities.api.ModuleEntity import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext private class ModuleBridgeLoaderService : ProjectServiceContainerInitializedListener { companion object { private val LOG = logger<ModuleBridgeLoaderService>() } private suspend fun loadModules(project: Project, activity: Activity?) { val componentManager = project as ComponentManagerEx val childActivity = activity?.startChild("modules instantiation") // ModuleManagerComponentBridge calls WorkspaceModel in init - getting entityStorage componentManager.getServiceAsync(WorkspaceModel::class.java).await() val moduleManager = componentManager.getServiceAsync(ModuleManager::class.java).await() as ModuleManagerComponentBridge val entities = moduleManager.entityStore.current.entities(ModuleEntity::class.java) moduleManager.loadModules(entities) childActivity?.setDescription("modules count: ${moduleManager.modules.size}") childActivity?.end() runActivity("libraries instantiation") { (LibraryTablesRegistrar.getInstance().getLibraryTable(project) as ProjectLibraryTableBridgeImpl).loadLibraries() } activity?.end() } override suspend fun execute(project: Project) { val projectModelSynchronizer = JpsProjectModelSynchronizer.getInstance(project) val componentManagerEx = project as ComponentManagerEx val workspaceModel = componentManagerEx.getServiceAsync(WorkspaceModel::class.java).await() as WorkspaceModelImpl if (workspaceModel.loadedFromCache) { val activity = StartUpMeasurer.startActivity("modules loading with cache") if (projectModelSynchronizer.hasNoSerializedJpsModules()) { LOG.warn("Loaded from cache, but no serialized modules found. " + "Workspace model cache will be ignored, project structure will be recreated.") workspaceModel.ignoreCache() // sets `WorkspaceModelImpl#loadedFromCache` to `false` project.putUserData(PROJECT_LOADED_FROM_CACHE_BUT_HAS_NO_MODULES, true) } loadModules(project, activity) } else { LOG.info("Workspace model loaded without cache. Loading real project state into workspace model. ${Thread.currentThread()}") val activity = StartUpMeasurer.startActivity("modules loading without cache") val storeToEntitySources = projectModelSynchronizer.loadProjectToEmptyStorage(project) projectModelSynchronizer.applyLoadedStorage(storeToEntitySources) project.messageBus.syncPublisher(JpsProjectLoadedListener.LOADED).loaded() loadModules(project, activity) } runActivity("tracked libraries setup") { // required for setupTrackedLibrariesAndJdks - make sure that it is created to avoid blocking of EDT val jdkTableDeferred = (ApplicationManager.getApplication() as ComponentManagerEx).getServiceAsync(ProjectJdkTable::class.java) val projectRootManager = componentManagerEx.getServiceAsync(ProjectRootManager::class.java).await() as ProjectRootManagerBridge jdkTableDeferred.join() withContext(Dispatchers.EDT) { ApplicationManager.getApplication().runWriteAction { projectRootManager.setupTrackedLibrariesAndJdks() } } } WorkspaceModelTopics.getInstance(project).notifyModulesAreLoaded() } }
apache-2.0
b6af85f0d3cb8345fb8ddd632ac16b8a
53.133333
133
0.804763
5.28308
false
false
false
false
JetBrains/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/SpecifySuperTypeFix.kt
1
5719
// 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.quickfix import com.intellij.openapi.command.CommandProcessor import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.openapi.ui.popup.JBPopupFactory import com.intellij.openapi.ui.popup.ListPopupStep import com.intellij.openapi.ui.popup.PopupStep import com.intellij.openapi.ui.popup.util.BaseListPopupStep import org.jetbrains.kotlin.diagnostics.Diagnostic import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.analyzeAsReplacement import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.codeinsight.api.classic.quickfixes.KotlinQuickFixAction import org.jetbrains.kotlin.idea.refactoring.fqName.fqName import org.jetbrains.kotlin.idea.util.application.executeWriteCommand import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.getQualifiedExpressionForReceiver import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.types.typeUtil.isSubtypeOf class SpecifySuperTypeFix( superExpression: KtSuperExpression, private val superTypes: List<String> ) : KotlinQuickFixAction<KtSuperExpression>(superExpression) { override fun getText() = KotlinBundle.message("intention.name.specify.supertype") override fun getFamilyName() = text override fun invoke(project: Project, editor: Editor?, file: KtFile) { if (editor == null) return val superExpression = element ?: return CommandProcessor.getInstance().runUndoTransparentAction { if (superTypes.size == 1) { superExpression.specifySuperType(superTypes.first()) } else { JBPopupFactory .getInstance() .createListPopup(createListPopupStep(superExpression, superTypes)) .showInBestPositionFor(editor) } } } private fun KtSuperExpression.specifySuperType(superType: String) { project.executeWriteCommand(KotlinBundle.message("intention.name.specify.supertype")) { val label = this.labelQualifier?.text ?: "" replace(KtPsiFactory(project).createExpression("super<$superType>$label")) } } private fun createListPopupStep(superExpression: KtSuperExpression, superTypes: List<String>): ListPopupStep<*> { return object : BaseListPopupStep<String>(KotlinBundle.message("popup.title.choose.supertype"), superTypes) { override fun isAutoSelectionEnabled() = false override fun onChosen(selectedValue: String, finalChoice: Boolean): PopupStep<*>? { if (finalChoice) { superExpression.specifySuperType(selectedValue) } return PopupStep.FINAL_CHOICE } } } companion object : KotlinSingleIntentionActionFactory() { override fun createAction(diagnostic: Diagnostic): KotlinQuickFixAction<KtSuperExpression>? { val superExpression = diagnostic.psiElement as? KtSuperExpression ?: return null val qualifiedExpression = superExpression.getQualifiedExpressionForReceiver() ?: return null val selectorExpression = qualifiedExpression.selectorExpression ?: return null val containingClassOrObject = superExpression.getStrictParentOfType<KtClassOrObject>() ?: return null val superTypeListEntries = containingClassOrObject.superTypeListEntries if (superTypeListEntries.isEmpty()) return null val context = superExpression.analyze(BodyResolveMode.PARTIAL) val superTypes = superTypeListEntries.mapNotNull { val typeReference = it.typeReference ?: return@mapNotNull null val typeElement = it.typeReference?.typeElement ?: return@mapNotNull null val kotlinType = context[BindingContext.TYPE, typeReference] ?: return@mapNotNull null typeElement to kotlinType } if (superTypes.size != superTypeListEntries.size) return null val psiFactory = KtPsiFactory(superExpression.project) val superTypesForSuperExpression = superTypes.mapNotNull { (typeElement, kotlinType) -> if (superTypes.any { it.second != kotlinType && it.second.isSubtypeOf(kotlinType) }) return@mapNotNull null val fqName = kotlinType.fqName ?: return@mapNotNull null val fqNameAsString = fqName.asString() val name = if (typeElement.text.startsWith(fqNameAsString)) fqNameAsString else fqName.shortName().asString() val newQualifiedExpression = psiFactory.createExpressionByPattern("super<$name>.$0", selectorExpression, reformat = false) val newContext = newQualifiedExpression.analyzeAsReplacement(qualifiedExpression, context) if (newQualifiedExpression.getResolvedCall(newContext)?.resultingDescriptor == null) return@mapNotNull null if (newContext.diagnostics.noSuppression().forElement(newQualifiedExpression).isNotEmpty()) return@mapNotNull null name } if (superTypesForSuperExpression.isEmpty()) return null return SpecifySuperTypeFix(superExpression, superTypesForSuperExpression) } } }
apache-2.0
99d10377ddea968fee9aaaef336026f6
52.448598
158
0.718307
5.684891
false
false
false
false
lovehuang/RangeDownload
app/src/main/java/downloader/wxy/com/rangedownloader/DownLoadThread.kt
1
1610
package downloader.wxy.com.rangedownloader import android.content.Context import java.io.InputStream import java.io.RandomAccessFile import java.net.HttpURLConnection import java.net.URL /** * Created by wangxiaoyan on 2017/8/20. */ class DownLoadThread internal constructor(private val mContext: Context, private val mEntity: DownLoadEntity, private val mListener: DownloadListener) : Thread() { override fun run() { super.run() var urlConnection: HttpURLConnection var randomFile: RandomAccessFile var inputStream: InputStream try { val url = URL("http://www.baidu.com") urlConnection = url.openConnection() as HttpURLConnection urlConnection.connectTimeout = 3000 urlConnection.requestMethod = "GET" urlConnection.requestMethod = "HEAD" urlConnection.allowUserInteraction = true; urlConnection.connect(); //设置下载位置 val start = mEntity.currentLength if (mEntity.totalLength != 0) { //第一次没必要设置断点续传 urlConnection.setRequestProperty("Range", "bytes=" + start + "-" + mEntity.totalLength) } var length = -1 if (urlConnection.responseCode / 100 == 2) { //获得文件长度 length = urlConnection.contentLength } if (length <= 0) { return } } catch (e: Exception) { e.printStackTrace() } finally { //流的回收逻辑略 } } }
apache-2.0
654c5aa954197a30c369d1a740c3a48a
30.591837
163
0.599483
4.763077
false
false
false
false
StepicOrg/stepik-android
app/src/main/java/org/stepik/android/view/catalog/ui/adapter/delegate/SpecializationListAdapterDelegate.kt
1
3237
package org.stepik.android.view.catalog.ui.adapter.delegate import android.view.View import android.view.ViewGroup import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.LinearSnapHelper import androidx.recyclerview.widget.RecyclerView import kotlinx.android.extensions.LayoutContainer import kotlinx.android.synthetic.main.item_specialization_list.* import org.stepic.droid.R import org.stepik.android.domain.catalog.model.CatalogSpecialization import org.stepik.android.presentation.course_list_redux.model.CatalogBlockStateWrapper import org.stepik.android.view.base.ui.adapter.layoutmanager.TableLayoutManager import org.stepik.android.view.catalog.model.CatalogItem import ru.nobird.app.core.model.cast import ru.nobird.android.ui.adapterdelegates.AdapterDelegate import ru.nobird.android.ui.adapterdelegates.DelegateViewHolder import ru.nobird.android.ui.adapters.DefaultDelegateAdapter class SpecializationListAdapterDelegate( private val onOpenLinkInWeb: (String) -> Unit ) : AdapterDelegate<CatalogItem, DelegateViewHolder<CatalogItem>>() { private val sharedViewPool = RecyclerView.RecycledViewPool() override fun isForViewType(position: Int, data: CatalogItem): Boolean = data is CatalogItem.Block && data.catalogBlockStateWrapper is CatalogBlockStateWrapper.SpecializationList override fun onCreateViewHolder(parent: ViewGroup): DelegateViewHolder<CatalogItem> = SpecializationListViewHolder(createView(parent, R.layout.item_specialization_list)) private inner class SpecializationListViewHolder( override val containerView: View ) : DelegateViewHolder<CatalogItem>(containerView), LayoutContainer { private val adapter = DefaultDelegateAdapter<CatalogSpecialization>() .also { it += SpecializationAdapterDelegate(onOpenLinkInWeb = onOpenLinkInWeb) } init { val rowCount = context.resources.getInteger(R.integer.specializations_default_rows) specializationListRecycler.layoutManager = TableLayoutManager( context, horizontalSpanCount = context.resources.getInteger(R.integer.specializations_default_columns), verticalSpanCount = rowCount, orientation = LinearLayoutManager.HORIZONTAL, reverseLayout = false ) specializationListRecycler.setRecycledViewPool(sharedViewPool) specializationListRecycler.setHasFixedSize(true) specializationListRecycler.adapter = adapter val snapHelper = LinearSnapHelper() snapHelper.attachToRecyclerView(specializationListRecycler) specializationInfoAction.setOnClickListener { onOpenLinkInWeb(context.getString(R.string.specialization_url)) } } override fun onBind(data: CatalogItem) { val specializationList = data .cast<CatalogItem.Block>() .catalogBlockStateWrapper .cast<CatalogBlockStateWrapper.SpecializationList>() adapter.items = specializationList.content.specializations } } }
apache-2.0
674bcfcf07cc133b862a119e506a6ad4
44.605634
114
0.733704
5.431208
false
false
false
false
KoaGex/ImageBattleFx
ImageBattleFx/src/main/java/org/imagebattle/chooser/RandomChooser.kt
1
704
package org.imagebattle.chooser import javafx.util.Pair import org.apache.logging.log4j.LogManager import org.imagebattle.TransitiveDiGraph import java.io.File import java.util.Random class RandomChooser(pGraph: TransitiveDiGraph) : ACandidateChooser(pGraph) { val logger = LogManager.getLogger(); override fun doGetNextCandidates(): Pair<File, File> { val start = System.currentTimeMillis(); val candidateCount = graph.getCalculatedCandidateCount(); val nextInt: Long = Random().nextInt(candidateCount).toLong(); val pair = graph.getCandidateStream().skip(nextInt).findAny().get(); val end = System.currentTimeMillis(); logger.trace("time needed: {}", end - start); return pair; } }
gpl-3.0
4ff5e3c5b0fa507d202438ff37fb0f7c
31.045455
76
0.764205
3.764706
false
false
false
false
TeMoMuKo/AutoStopRace
app/src/main/java/pl/temomuko/autostoprace/domain/repository/LocationsRepository.kt
2
1673
package pl.temomuko.autostoprace.domain.repository import pl.temomuko.autostoprace.data.remote.AsrService import pl.temomuko.autostoprace.data.remote.TeamNotFoundException import pl.temomuko.autostoprace.data.remote.model.CreateLocationRequest import pl.temomuko.autostoprace.data.remote.model.LocationEntity import pl.temomuko.autostoprace.domain.MultipartCreator import pl.temomuko.autostoprace.domain.model.LocationRecord import rx.Single import javax.inject.Inject class LocationsRepository @Inject constructor( private val asrService: AsrService, private val multipartCreator: MultipartCreator ) { fun postLocation(locationRecord: LocationRecord): Single<LocationEntity> { val createLocationRequest = CreateLocationRequest( latitude = locationRecord.latitude, longitude = locationRecord.longitude, message = locationRecord.message?.ifBlank { null } ) val imageMultipart = locationRecord.imageUri?.let { multipartCreator.createImageMultipartFromUri(it) } return asrService.addLocation( locationRequest = createLocationRequest, image = imageMultipart ) } fun getTeamLocations(teamNumber: Long): Single<List<LocationRecord>> { return asrService.getTeamLocations(teamNumber) .map { locations -> locations.map { it.toLocationRecord() } } .onErrorResumeNext(Single.error(TeamNotFoundException())) } fun getUserTeamLocations(): Single<List<LocationRecord>> { return asrService.getUserTeamLocations() .map { locations -> locations.map { it.toLocationRecord() } } } }
apache-2.0
2b2f539dd6aae0b36f8014f172cad134
38.833333
78
0.728631
4.267857
false
false
false
false
HTWDD/HTWDresden
app/src/main/java/de/htwdd/htwdresden/ui/views/fragments/StudyGroupFragment.kt
1
5195
package de.htwdd.htwdresden.ui.views.fragments import android.annotation.SuppressLint import android.os.Bundle import android.os.Handler import android.view.View import androidx.core.os.bundleOf import androidx.fragment.app.Fragment import androidx.navigation.fragment.findNavController import com.afollestad.materialdialogs.LayoutMode import com.afollestad.materialdialogs.MaterialDialog import com.afollestad.materialdialogs.bottomsheets.BottomSheet import com.afollestad.materialdialogs.list.listItems import de.htwdd.htwdresden.R import de.htwdd.htwdresden.interfaces.Swipeable import de.htwdd.htwdresden.ui.models.StudyCourse import de.htwdd.htwdresden.ui.models.StudyGroup import de.htwdd.htwdresden.ui.models.StudyYear import de.htwdd.htwdresden.ui.viewmodels.fragments.StudyGroupViewModel import de.htwdd.htwdresden.utils.extensions.* import kotlinx.android.synthetic.main.fragment_study_group.* import kotlin.properties.Delegates.observable @SuppressLint("SetTextI18n") class StudyGroupFragment: Fragment(R.layout.fragment_study_group), Swipeable { companion object { const val ARG_IS_BOARDING = "isBoarding" private var delegate: SwipeDelegate? = null fun newInstance(delegate: SwipeDelegate? = null) = StudyGroupFragment().apply { [email protected] = delegate arguments = bundleOf(ARG_IS_BOARDING to true) } } private val viewModel by lazy { getViewModel<StudyGroupViewModel>() } inner class State { val years = ArrayList<StudyYear>() var year: StudyYear? by observable<StudyYear?>(null) { _, _, newValue -> btnMajor.isEnabled = newValue != null major = null tvS.text = "${newValue?.studyYear?.plus(2000)}" } val majors: ArrayList<StudyCourse> get() { if (years.isEmpty() || year == null) { return ArrayList() } return years.first { it.studyYear == year?.studyYear }.studyCourses.filter { it.name.isNotEmpty() }.toCollection(ArrayList()) } var major: StudyCourse? by observable<StudyCourse?>(null) { _, _, newValue -> btnGroup.isEnabled = newValue != null group = null tvMajor.text = if (newValue == null) { "" } else { "${newValue.studyCourse} | ${newValue.name}" } } val groups: ArrayList<StudyGroup> get() { if (majors.isEmpty() || major == null) { return ArrayList() } return majors.first { it.studyCourse == major?.studyCourse }.studyGroups.toCollection(ArrayList()) } var group: StudyGroup? by observable<StudyGroup?>(null) { _, _, newValue -> tvGroup.text = if (newValue == null) { "" } else { "${newValue.studyGroup} | ${newValue.name}" } if (year != null && major != null && newValue != null) { Handler().postDelayed({ viewModel.saveToken("${year?.studyYear}:${major?.studyCourse}:${newValue.studyGroup}:${newValue.name}") if (arguments?.getBoolean(ARG_IS_BOARDING) == false) { findNavController().popBackStack() } else { delegate?.moveNext() } }, 750) } } } private val state by lazy { State() } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) setup() } private fun setup() { btnLater.toggle(arguments?.getBoolean(ARG_IS_BOARDING) == false) viewModel .request() .runInUiThread() .subscribe { weak { self -> self.state.years.apply { clear() addAll(it) } self.btnYear.isEnabled = it.isNotEmpty() } } .addTo(disposeBag) btnYear.click { MaterialDialog(context!!, BottomSheet(LayoutMode.WRAP_CONTENT)).show { title(R.string.year) listItems(items = state.years.map { "${it.studyYear + 2000}"}, selection = { _, index, _ -> state.year = state.years[index] }) } } btnMajor.click { MaterialDialog(context!!, BottomSheet(LayoutMode.WRAP_CONTENT)).show { title(R.string.major) listItems(items = state.majors.map { "${it.studyCourse} | ${it.name.defaultWhenNull("---")}" }) { _, index, _ -> state.major = state.majors[index] } } } btnGroup.click { MaterialDialog(context!!, BottomSheet(LayoutMode.WRAP_CONTENT)).show { title(R.string.group) listItems(items = state.groups.map { "${it.studyGroup} | ${it.name.defaultWhenNull("---")}" }) { _, index, _ -> state.group = state.groups[index] } } } btnLater.click { findNavController().popBackStack() } } }
mit
716c3ed7b37a9351c22659ca54adaa7f
38.664122
145
0.580366
4.655018
false
false
false
false
leafclick/intellij-community
java/java-impl/src/com/intellij/codeInsight/daemon/problems/ProblemAnalyzer.kt
1
6811
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.codeInsight.daemon.problems import com.intellij.codeInsight.daemon.DaemonCodeAnalyzer import com.intellij.codeInsight.daemon.problems.SnapshotUpdater.Companion.api import com.intellij.codeInsight.daemon.problems.ui.ProjectProblemsView import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.ReadAction import com.intellij.openapi.components.Service import com.intellij.openapi.components.service import com.intellij.openapi.fileEditor.FileEditor import com.intellij.openapi.fileEditor.FileEditorManagerEvent import com.intellij.openapi.fileEditor.FileEditorManagerListener import com.intellij.openapi.project.DumbService import com.intellij.openapi.project.Project import com.intellij.openapi.roots.FileIndexUtil import com.intellij.openapi.startup.StartupActivity import com.intellij.openapi.util.registry.Registry import com.intellij.openapi.vfs.VirtualFile import com.intellij.openapi.vfs.VirtualFileManager import com.intellij.openapi.vfs.newvfs.BulkFileListener import com.intellij.openapi.vfs.newvfs.events.VFileCreateEvent import com.intellij.openapi.vfs.newvfs.events.VFileDeleteEvent import com.intellij.openapi.vfs.newvfs.events.VFileEvent import com.intellij.openapi.vfs.newvfs.events.VFileMoveEvent import com.intellij.pom.Navigatable import com.intellij.psi.* import com.intellij.psi.search.GlobalSearchScope internal data class Change(val prevMember: Member?, val curMember: Member?, val containingFile: PsiFile) internal data class Problem(val file: VirtualFile, val message: String?, val place: Navigatable) @Service class ProblemAnalyzer(private val project: Project) : DaemonCodeAnalyzer.DaemonListener, BulkFileListener, FileEditorManagerListener { private val psiManager = PsiManager.getInstance(project) private val usageSink = UsageSink(project) init { DumbService.getInstance(project).runWhenSmart { val connection = project.messageBus.connect() connection.subscribe(DaemonCodeAnalyzer.DAEMON_EVENT_TOPIC, this) connection.subscribe(FileEditorManagerListener.FILE_EDITOR_MANAGER, this) connection.subscribe(VirtualFileManager.VFS_CHANGES, this) } } override fun daemonFinished(fileEditors: MutableCollection<FileEditor>) { fileEditors.mapNotNull { it.file }.forEach { analyzeFile(it) } } override fun selectionChanged(event: FileEditorManagerEvent) { val file = event.newFile ?: return if (!FileIndexUtil.isJavaSourceFile(project, file)) return val psiFile = psiManager.findFile(file) as? PsiClassOwner ?: return val scope = psiFile.useScope as? GlobalSearchScope ?: return DumbService.getInstance(project).smartInvokeLater { reportBrokenUsages(psiFile, scope, false) } } override fun before(events: MutableList<out VFileEvent>) { val problemsView = ProjectProblemsView.SERVICE.getInstance(project) for (event in events) { if (event !is VFileDeleteEvent && event !is VFileMoveEvent) continue val file = event.file ?: continue if (!FileIndexUtil.isJavaSourceFile(project, file)) continue var psiFile = psiManager.findFile(file) as? PsiClassOwner ?: continue problemsView.removeProblems(file) val scope = psiFile.useScope as? GlobalSearchScope ?: continue psiFile = psiFile.copy() as? PsiClassOwner ?: continue DumbService.getInstance(project).smartInvokeLater { reportBrokenUsages(psiFile, scope, true) } } } override fun after(events: MutableList<out VFileEvent>) { for (event in events) { if (event !is VFileCreateEvent && event !is VFileMoveEvent) continue val file = event.file ?: continue if (!FileIndexUtil.isJavaSourceFile(project, file)) continue val psiFile = psiManager.findFile(file) as? PsiClassOwner ?: continue val scope = psiFile.useScope as? GlobalSearchScope ?: continue DumbService.getInstance(project).smartInvokeLater { reportBrokenUsages(psiFile, scope, false) } } } private fun reportBrokenUsages(psiFile: PsiClassOwner, scope: GlobalSearchScope, isRemoved: Boolean) { if (!psiFile.isValid && !isRemoved) return val changes = api(psiFile).mapNotNullTo(mutableSetOf()) { memberChange(it, psiFile, scope, isRemoved) } reportProblems(changes) } private fun memberChange(psiMember: PsiMember, containingFile: PsiFile, scope: GlobalSearchScope, isRemoved: Boolean): Change? { val member = Member.create(psiMember, scope) ?: return null return if (isRemoved) Change(member, null, containingFile) else Change(null, member, containingFile) } private fun analyzeFile(file: VirtualFile) { if (!file.isValid || !FileIndexUtil.isJavaSourceFile(project, file)) return val psiFile = psiManager.findFile(file) as? PsiClassOwner ?: return for (psiClass in psiFile.classes) { val changes = SnapshotUpdater.update(psiClass) if (changes.isEmpty()) continue reportProblems(changes) } } private fun reportProblems(changes: Set<Change>) { val problemsView = ProjectProblemsView.SERVICE.getInstance(project) problemsView.executor().execute { val problems = ReadAction.nonBlocking<List<Problem>> { val problems = mutableListOf<Problem>() for ((prevMember, curMember, containingFile) in changes) { if (project.isDisposed) return@nonBlocking emptyList() val problemsAfterChange = usageSink.checkUsages(prevMember, curMember, containingFile) if (problemsAfterChange != null) problems.addAll(problemsAfterChange) } return@nonBlocking problems }.executeSynchronously() if (problems.isEmpty()) return@execute ApplicationManager.getApplication().invokeLater { updateProblems(problems, problemsView) } } } private fun updateProblems(newProblems: List<Problem>, problemsView: ProjectProblemsView) { val problemsByFile: Map<VirtualFile, MutableMap<Navigatable, String?>> = newProblems.groupingBy { it.file }.aggregate { _, acc, el, _ -> val newAcc = acc ?: mutableMapOf() newAcc[el.place] = el.message newAcc } for ((file, updatedProblems) in problemsByFile) { problemsView.getProblems(file).forEach { if (it is PsiElement && !it.isValid) problemsView.removeProblems(file, it) } for ((place, message) in updatedProblems) { problemsView.removeProblems(file, place) if (message != null) problemsView.addProblem(file, message, place) } } } class MyStartupActivity : StartupActivity { override fun runActivity(project: Project) { if (!Registry.`is`("project.problems.view")) return project.service<ProblemAnalyzer>() } } }
apache-2.0
df98322b2cd27c3c1bf874305628d1cf
45.340136
140
0.754808
4.617627
false
false
false
false
zdary/intellij-community
platform/platform-impl/src/com/intellij/idea/ApplicationLoader.kt
1
17202
// 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. @file:JvmName("ApplicationLoader") @file:ApiStatus.Internal package com.intellij.idea import com.intellij.diagnostic.* import com.intellij.diagnostic.StartUpMeasurer.Activities import com.intellij.diagnostic.StartUpMeasurer.startActivity import com.intellij.icons.AllIcons import com.intellij.ide.* import com.intellij.ide.plugins.IdeaPluginDescriptorImpl import com.intellij.ide.plugins.PluginManagerCore import com.intellij.ide.plugins.StartupAbortedException import com.intellij.openapi.application.* import com.intellij.openapi.application.ex.ApplicationEx import com.intellij.openapi.application.ex.ApplicationManagerEx import com.intellij.openapi.application.impl.ApplicationImpl import com.intellij.openapi.components.stateStore import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.extensions.PluginDescriptor import com.intellij.openapi.progress.EmptyProgressIndicator import com.intellij.openapi.progress.ProcessCanceledException import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.progress.util.AbstractProgressIndicatorBase import com.intellij.openapi.ui.DialogEarthquakeShaker import com.intellij.openapi.util.IconLoader import com.intellij.openapi.util.SystemInfoRt import com.intellij.openapi.util.SystemPropertyBean import com.intellij.openapi.wm.WindowManager import com.intellij.serviceContainer.ComponentManagerImpl import com.intellij.ui.AnimatedIcon import com.intellij.ui.AppIcon import com.intellij.ui.mac.foundation.Foundation import com.intellij.ui.mac.touchbar.TouchBarsManager import com.intellij.util.PlatformUtils import com.intellij.util.TimeoutUtil import com.intellij.util.io.createDirectories import com.intellij.util.io.storage.HeavyProcessLatch import com.intellij.util.lang.ZipFilePool import com.intellij.util.ui.AsyncProcessIcon import net.miginfocom.layout.PlatformDefaults import org.jetbrains.annotations.ApiStatus import java.awt.EventQueue import java.io.IOException import java.nio.charset.StandardCharsets import java.nio.file.Files import java.nio.file.Path import java.util.concurrent.* import java.util.function.BiFunction import kotlin.system.exitProcess private val SAFE_JAVA_ENV_PARAMETERS = arrayOf(JetBrainsProtocolHandler.REQUIRED_PLUGINS_KEY) @Suppress("SSBasedInspection") private val LOG = Logger.getInstance("#com.intellij.idea.ApplicationLoader") fun initApplication(rawArgs: List<String>, prepareUiFuture: CompletionStage<*>) { val initAppActivity = StartupUtil.startupStart.endAndStart(Activities.INIT_APP) val loadAndInitPluginFutureActivity = initAppActivity.startChild("plugin descriptor init waiting") val loadAndInitPluginFuture = PluginManagerCore.initPlugins(StartupUtil::class.java.classLoader) loadAndInitPluginFuture.thenRun(loadAndInitPluginFutureActivity::end) // use main thread, avoid thread switching (prepareUiFuture as CompletableFuture<*>).join() val args = processProgramArguments(rawArgs) EventQueue.invokeLater { runActivity("create app") { val isInternal = java.lang.Boolean.getBoolean(ApplicationManagerEx.IS_INTERNAL_PROPERTY) ApplicationImpl(isInternal, false, Main.isHeadless(), Main.isCommandLine()) { app -> loadAndInitPluginFuture .thenAcceptAsync({ plugins -> runActivity("app component registration") { app.registerComponents(plugins, app, null) } if (args.isEmpty()) { startApp(app, IdeStarter(), initAppActivity, plugins, args) } else { // `ApplicationStarter` is an extension, so to find a starter extensions must be registered first findCustomAppStarterAndStart(plugins, args, app, initAppActivity) } if (!Main.isHeadless()) { ForkJoinPool.commonPool().execute { runActivity("icons preloading") { if (isInternal) { IconLoader.setStrictGlobally(true) } AsyncProcessIcon("") AnimatedIcon.Blinking(AllIcons.Ide.FatalError) AnimatedIcon.FS() } runActivity("migLayout") { // IDEA-170295 PlatformDefaults.setLogicalPixelBase(PlatformDefaults.BASE_FONT_SIZE) } } } }, { if (EventQueue.isDispatchThread()) ForkJoinPool.commonPool().execute(it) else it.run() }) .exceptionally { StartupAbortedException.processException(it) null } } } } } private fun startApp(app: ApplicationImpl, starter: ApplicationStarter, initAppActivity: Activity, plugins: List<IdeaPluginDescriptorImpl>, args: List<String>) { // initSystemProperties or RegistryKeyBean.addKeysFromPlugins maybe not yet performed, // but it is ok because registry is not and should be not used initConfigurationStore(app) val preloadSyncServiceFuture = preloadServices(plugins, app, activityPrefix = "") val placeOnEventQueueActivity = initAppActivity.startChild(Activities.PLACE_ON_EVENT_QUEUE) val loadComponentInEdtFuture = CompletableFuture.runAsync({ placeOnEventQueueActivity.end() val indicator = if (SplashManager.SPLASH_WINDOW == null) { null } else object : EmptyProgressIndicator() { override fun setFraction(fraction: Double) { SplashManager.SPLASH_WINDOW.showProgress(fraction) } } app.loadComponents(indicator) }, Executor(app::invokeLater)) if (!app.isHeadlessEnvironment && SystemInfoRt.isMac) { ForkJoinPool.commonPool().execute(Runnable { // ensure that TouchBarsManager is loaded before WelcomeFrame/project // do not wait completion - it is thread safe and not required for application start runActivity("mac touchbar") { if (app.isDisposed) { return@Runnable } Foundation.init() if (app.isDisposed) { return@Runnable } TouchBarsManager.initialize() } }) } CompletableFuture.allOf(loadComponentInEdtFuture, preloadSyncServiceFuture, StartupUtil.getServerFuture()) .thenComposeAsync({ val pool = ForkJoinPool.commonPool() val future = CompletableFuture.runAsync({ initAppActivity.runChild("app initialized callback") { ForkJoinTask.invokeAll(callAppInitialized(app)) } }, pool) if (!app.isUnitTestMode && !app.isHeadlessEnvironment && java.lang.Boolean.parseBoolean(System.getProperty("enable.activity.preloading", "true"))) { pool.execute { executePreloadActivities(app) } } pool.execute { runActivity("create locator file") { createAppLocatorFile() } } if (!Main.isLightEdit()) { // this functionality should be used only by plugin functionality that is used after start-up pool.execute { runActivity("system properties setting") { SystemPropertyBean.initSystemProperties() } } } future }, Executor { // if `loadComponentInEdtFuture` is completed after `preloadSyncServiceFuture`, // then this task will be executed in EDT, so force execution out of EDT if (app.isDispatchThread) { ForkJoinPool.commonPool().execute(it) } else { it.run() } }) .thenRun { if (!app.isHeadlessEnvironment) { addActivateAndWindowsCliListeners() } initAppActivity.end() if (starter.requiredModality == ApplicationStarter.NOT_IN_EDT) { starter.main(args) // no need to use pool once plugins are loaded ZipFilePool.POOL = null } else { // backward compatibility ApplicationManager.getApplication().invokeLater { (TransactionGuard.getInstance() as TransactionGuardImpl).performUserActivity { starter.main(args) } } } } .exceptionally { StartupAbortedException.processException(it) null } } private fun findCustomAppStarterAndStart(plugins: List<IdeaPluginDescriptorImpl>, args: List<String>, app: ApplicationImpl, initAppActivity: Activity) { val starter = findStarter(args.first()) ?: if (PlatformUtils.getPlatformPrefix() == "LightEdit") IdeStarter.StandaloneLightEditStarter() else IdeStarter() if (Main.isHeadless() && !starter.isHeadless) { val commandName = starter.commandName val message = IdeBundle.message( "application.cannot.start.in.a.headless.mode", when { starter is IdeStarter -> 0 commandName != null -> 1 else -> 2 }, commandName, starter.javaClass.name, if (args.isEmpty()) 0 else 1, args.joinToString(" ") ) Main.showMessage(IdeBundle.message("main.startup.error"), message, true) exitProcess(Main.NO_GRAPHICS) } starter.premain(args) startApp(app, starter, initAppActivity, plugins, args) } fun createAppLocatorFile() { val locatorFile = Path.of(PathManager.getSystemPath(), ApplicationEx.LOCATOR_FILE_NAME) try { locatorFile.parent?.createDirectories() Files.writeString(locatorFile, PathManager.getHomePath(), StandardCharsets.UTF_8) } catch (e: IOException) { LOG.warn("Can't store a location in '$locatorFile'", e) } } @JvmOverloads fun preloadServices(plugins: List<IdeaPluginDescriptorImpl>, container: ComponentManagerImpl, activityPrefix: String, onlyIfAwait: Boolean = false): CompletableFuture<Void?> { val result = container.preloadServices(plugins, activityPrefix, onlyIfAwait) fun logError(future: CompletableFuture<Void?>): CompletableFuture<Void?> { return future .whenComplete { _, error -> if (error != null && error !is ProcessCanceledException) { StartupAbortedException.processException(error) } } } logError(result.first) return logError(result.second) } private fun addActivateAndWindowsCliListeners() { StartupUtil.addExternalInstanceListener { rawArgs -> LOG.info("External instance command received") val (args, currentDirectory) = if (rawArgs.isEmpty()) emptyList<String>() to null else rawArgs.subList(1, rawArgs.size) to rawArgs[0] val result = handleExternalCommand(args, currentDirectory) result.future } StartupUtil.LISTENER = BiFunction { currentDirectory, args -> LOG.info("External Windows command received") if (args.isEmpty()) { return@BiFunction 0 } val result = handleExternalCommand(args.toList(), currentDirectory) CliResult.unmap(result.future, Main.ACTIVATE_ERROR).exitCode } ApplicationManager.getApplication().messageBus.connect().subscribe(AppLifecycleListener.TOPIC, object : AppLifecycleListener { override fun appWillBeClosed(isRestart: Boolean) { StartupUtil.addExternalInstanceListener { CliResult.error(Main.ACTIVATE_DISPOSING, IdeBundle.message("activation.shutting.down")) } StartupUtil.LISTENER = BiFunction { _, _ -> Main.ACTIVATE_DISPOSING } } }) } private fun handleExternalCommand(args: List<String>, currentDirectory: String?): CommandLineProcessorResult { val result = CommandLineProcessor.processExternalCommandLine(args, currentDirectory) ApplicationManager.getApplication().invokeLater { if (result.hasError) { result.showErrorIfFailed() } else { val windowManager = WindowManager.getInstance() if (result.project == null) { windowManager.findVisibleFrame()?.let { frame -> frame.toFront() DialogEarthquakeShaker.shake(frame) } } else { windowManager.getFrame(result.project)?.let { AppIcon.getInstance().requestFocus() } } } } return result } fun findStarter(key: String) = ApplicationStarter.EP_NAME.iterable.find { it == null || it.commandName == key } fun initConfigurationStore(app: ApplicationImpl) { var activity = startActivity("beforeApplicationLoaded") val configPath = PathManager.getConfigDir() for (listener in ApplicationLoadListener.EP_NAME.iterable) { try { (listener ?: break).beforeApplicationLoaded(app, configPath) } catch (e: ProcessCanceledException) { throw e } catch (e: Throwable) { LOG.error(e) } } activity = activity.endAndStart("init app store") // we set it after beforeApplicationLoaded call, because app store can depend on stream provider state app.stateStore.setPath(configPath) StartUpMeasurer.setCurrentState(LoadingState.CONFIGURATION_STORE_INITIALIZED) activity.end() } /** * The method looks for `-Dkey=value` program arguments and stores some of them in system properties. * We should use it for a limited number of safe keys; one of them is a list of IDs of required plugins. * * @see SAFE_JAVA_ENV_PARAMETERS */ @Suppress("SpellCheckingInspection") private fun processProgramArguments(args: List<String>): List<String> { if (args.isEmpty()) { return emptyList() } val arguments = mutableListOf<String>() for (arg in args) { if (arg.startsWith("-D")) { val keyValue = arg.substring(2).split('=') if (keyValue.size == 2 && SAFE_JAVA_ENV_PARAMETERS.contains(keyValue[0])) { System.setProperty(keyValue[0], keyValue[1]) continue } } if (!CommandLineArgs.isKnownArgument(arg)) { arguments.add(arg) } } return arguments } fun callAppInitialized(app: ApplicationImpl): List<ForkJoinTask<*>> { val extensionArea = app.extensionArea val extensionPoint = extensionArea.getExtensionPoint<ApplicationInitializedListener>("com.intellij.applicationInitializedListener") val result = ArrayList<ForkJoinTask<*>>(extensionPoint.size()) extensionPoint.processImplementations(/* shouldBeSorted = */ false) { supplier, _ -> result.add(ForkJoinTask.adapt { try { supplier.get()?.componentsInitialized() } catch (e: Throwable) { LOG.error(e) } }) } extensionPoint.reset() return result } private fun checkHeavyProcessRunning() { if (HeavyProcessLatch.INSTANCE.isRunning) { TimeoutUtil.sleep(1) } } private fun executePreloadActivity(activity: PreloadingActivity, descriptor: PluginDescriptor?, app: ApplicationImpl) { checkHeavyProcessRunning() val indicator = AbstractProgressIndicatorBase() if (app.isDisposed) { return } val isDebugEnabled = LOG.isDebugEnabled ProgressManager.getInstance().executeProcessUnderProgress({ val measureActivity = if (descriptor == null) { null } else { StartUpMeasurer.startActivity(activity.javaClass.name, ActivityCategory.PRELOAD_ACTIVITY, descriptor.pluginId.idString) } try { indicator.start() activity.preload(object : AbstractProgressIndicatorBase() { override fun checkCanceled() { checkHeavyProcessRunning() indicator.checkCanceled() } override fun isCanceled() = indicator.isCanceled || app.isDisposed }) if (isDebugEnabled) { LOG.debug("${activity.javaClass.name} finished") } } catch (ignore: ProcessCanceledException) { return@executeProcessUnderProgress } finally { measureActivity?.end() if (indicator.isRunning) { indicator.stop() } } }, indicator) } private fun executePreloadActivities(app: ApplicationImpl) { val activity = StartUpMeasurer.startActivity("preloading activity executing", ActivityCategory.DEFAULT) val list = mutableListOf<Pair<PreloadingActivity, PluginDescriptor>>() val extensionPoint = app.extensionArea.getExtensionPoint<PreloadingActivity>("com.intellij.preloadingActivity") extensionPoint.processImplementations(/* shouldBeSorted = */ false) { supplier, pluginDescriptor -> val preloadingActivity: PreloadingActivity try { preloadingActivity = supplier.get() ?: return@processImplementations } catch (e: Throwable) { LOG.error(e) return@processImplementations } list.add(Pair(preloadingActivity, pluginDescriptor)) } extensionPoint.reset() if (list.isEmpty()) { return } // don't execute as one long task, make sure that other more important tasks maybe executed in between ForkJoinPool.commonPool().execute(object : Runnable { private var index = 0 override fun run() { if (app.isDisposed) { return } val item = list.get(index++) executePreloadActivity(item.first, item.second, app) if (index == list.size || app.isDisposed) { activity.end() } else { ForkJoinPool.commonPool().execute(this) } } }) }
apache-2.0
b39076612c7cb2a96dcccd272bebcac5
33.894523
140
0.689222
4.737538
false
false
false
false
VREMSoftwareDevelopment/WiFiAnalyzer
app/src/main/kotlin/com/vrem/wifianalyzer/wifi/model/Strength.kt
1
1819
/* * WiFiAnalyzer * Copyright (C) 2015 - 2022 VREM Software Development <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package com.vrem.wifianalyzer.wifi.model import androidx.annotation.ColorRes import androidx.annotation.DrawableRes import com.vrem.wifianalyzer.R enum class Strength(@DrawableRes val imageResource: Int, @ColorRes val colorResource: Int) { ZERO(R.drawable.ic_signal_wifi_0_bar, R.color.error), ONE(R.drawable.ic_signal_wifi_1_bar, R.color.warning), TWO(R.drawable.ic_signal_wifi_2_bar, R.color.warning), THREE(R.drawable.ic_signal_wifi_3_bar, R.color.success), FOUR(R.drawable.ic_signal_wifi_4_bar, R.color.success); fun weak(): Boolean = ZERO == this companion object { const val colorResourceDefault: Int = R.color.regular fun calculate(level: Int): Strength { val enumValues: Array<Strength> = enumValues() return enumValues[calculateSignalLevel(level, enumValues.size)] } fun reverse(strength: Strength): Strength { val enumValues: Array<Strength> = enumValues() return enumValues[enumValues.size - strength.ordinal - 1] } } }
gpl-3.0
1018c4c49d401ccd6d50ba2ea034a394
37.723404
92
0.71193
3.997802
false
false
false
false
Raizlabs/DBFlow
lib/src/main/kotlin/com/dbflow5/database/DatabaseCallback.kt
1
1338
package com.dbflow5.database /** * Description: Provides callbacks for [OpenHelper] methods */ interface DatabaseCallback { /** * Called when the DB is opened * * @param database The database that is opened */ fun onOpen(database: DatabaseWrapper) = Unit /** * Called when the DB is created * * @param database The database that is created */ fun onCreate(database: DatabaseWrapper) = Unit /** * Called when the DB is upgraded. * * @param database The database that is upgraded * @param oldVersion The previous DB version * @param newVersion The new DB version */ fun onUpgrade(database: DatabaseWrapper, oldVersion: Int, newVersion: Int) = Unit /** * Called when DB is downgraded. Note that this may not be supported by all implementations of the DB. * * @param databaseWrapper The database downgraded. * @param oldVersion The old. higher version. * @param newVersion The new lower version. */ fun onDowngrade(databaseWrapper: DatabaseWrapper, oldVersion: Int, newVersion: Int) = Unit /** * Called when DB connection is being configured. Useful for checking foreign key support or enabling * write-ahead-logging. */ fun onConfigure(db: DatabaseWrapper) = Unit }
mit
a8e649c99862980204a25f55691a2932
28.733333
106
0.659193
4.744681
false
false
false
false
JuliusKunze/kotlin-native
backend.native/tests/external/stdlib/collections/ArraysTest/sort.kt
2
2854
import kotlin.test.* fun <T> assertArrayNotSameButEquals(expected: Array<out T>, actual: Array<out T>, message: String = "") { assertTrue(expected !== actual && expected contentEquals actual, message) } fun assertArrayNotSameButEquals(expected: IntArray, actual: IntArray, message: String = "") { assertTrue(expected !== actual && expected contentEquals actual, message) } fun assertArrayNotSameButEquals(expected: LongArray, actual: LongArray, message: String = "") { assertTrue(expected !== actual && expected contentEquals actual, message) } fun assertArrayNotSameButEquals(expected: ShortArray, actual: ShortArray, message: String = "") { assertTrue(expected !== actual && expected contentEquals actual, message) } fun assertArrayNotSameButEquals(expected: ByteArray, actual: ByteArray, message: String = "") { assertTrue(expected !== actual && expected contentEquals actual, message) } fun assertArrayNotSameButEquals(expected: DoubleArray, actual: DoubleArray, message: String = "") { assertTrue(expected !== actual && expected contentEquals actual, message) } fun assertArrayNotSameButEquals(expected: FloatArray, actual: FloatArray, message: String = "") { assertTrue(expected !== actual && expected contentEquals actual, message) } fun assertArrayNotSameButEquals(expected: CharArray, actual: CharArray, message: String = "") { assertTrue(expected !== actual && expected contentEquals actual, message) } fun assertArrayNotSameButEquals(expected: BooleanArray, actual: BooleanArray, message: String = "") { assertTrue(expected !== actual && expected contentEquals actual, message) } fun box() { val intArr = intArrayOf(5, 2, 1, 9, 80, Int.MIN_VALUE, Int.MAX_VALUE) intArr.sort() assertArrayNotSameButEquals(intArrayOf(Int.MIN_VALUE, 1, 2, 5, 9, 80, Int.MAX_VALUE), intArr) intArr.sortDescending() assertArrayNotSameButEquals(intArrayOf(Int.MAX_VALUE, 80, 9, 5, 2, 1, Int.MIN_VALUE), intArr) val longArr = longArrayOf(200, 2, 1, 4, 3, Long.MIN_VALUE, Long.MAX_VALUE) longArr.sort() assertArrayNotSameButEquals(longArrayOf(Long.MIN_VALUE, 1, 2, 3, 4, 200, Long.MAX_VALUE), longArr) longArr.sortDescending() assertArrayNotSameButEquals(longArrayOf(Long.MAX_VALUE, 200, 4, 3, 2, 1, Long.MIN_VALUE), longArr) val charArr = charArrayOf('d', 'c', 'E', 'a', '\u0000', '\uFFFF') charArr.sort() assertArrayNotSameButEquals(charArrayOf('\u0000', 'E', 'a', 'c', 'd', '\uFFFF'), charArr) charArr.sortDescending() assertArrayNotSameButEquals(charArrayOf('\uFFFF', 'd', 'c', 'a', 'E', '\u0000'), charArr) val strArr = arrayOf("9", "80", "all", "Foo") strArr.sort() assertArrayNotSameButEquals(arrayOf("80", "9", "Foo", "all"), strArr) strArr.sortDescending() assertArrayNotSameButEquals(arrayOf("all", "Foo", "9", "80"), strArr) }
apache-2.0
6412c35f175c82ab3e83eb8d882f6ab7
43.59375
105
0.70953
4.130246
false
false
false
false
JuliusKunze/kotlin-native
runtime/src/main/kotlin/kotlin/text/regex/Lexer.kt
2
37140
/* * 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. */ /* * 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. */ // TODO: Licenses. package kotlin.text.regex // Access to the decomposition tables. ========================================================================= /** Gets canonical class for given codepoint from decomposition mappings table. */ @SymbolName("Kotlin_text_regex_getCanonicalClassInternal") external private fun getCanonicalClassInternal(ch: Int): Int /** Check if the given character is in table of single decompositions. */ @SymbolName("Kotlin_text_regex_hasSingleCodepointDecompositionInternal") external private fun hasSingleCodepointDecompositionInternal(ch: Int): Boolean /** Returns a decomposition for a given codepoint. */ @SymbolName("Kotlin_text_regex_getDecompositionInternal") external private fun getDecompositionInternal(ch: Int): IntArray? /** * Decomposes the given string represented as an array of codepoints. Saves the decomposition into [outputCodepoints] array. * Returns the length of the decomposition. */ @SymbolName("Kotlin_text_regex_decomposeString") external private fun decomposeString(inputCodePoints: IntArray, inputLength: Int, outputCodePoints: IntArray): Int // ============================================================================================================= /** * This is base class for special tokens like character classes and quantifiers. */ internal abstract class SpecialToken { /** * Returns the type of the token, may return following values: * TOK_CHARCLASS - token representing character class; * TOK_QUANTIFIER - token representing quantifier; */ abstract val type: Type enum class Type { CHARCLASS, QUANTIFIER } } internal class Lexer(val patternString: String, flags: Int) { // The property is set in the init block after some transformations over the pattern string. private val pattern: CharArray var flags = flags private set // Modes =========================================================================================================== enum class Mode { PATTERN, RANGE, ESCAPE } /** * Mode: whether the lexer processes character range ([Mode.RANGE]), escaped sequence ([Mode.RANGE]) * or any other part of a regex ([PATTERN]). */ var mode = Mode.PATTERN private set /** When in [Mode.ESCAPE] mode, this field will save the previous one */ private var savedMode = Mode.PATTERN fun setModeWithReread(value: Mode) { if(value == Mode.PATTERN || value == Mode.RANGE) { mode = value } if (mode == Mode.PATTERN) { reread() } } // Tokens ========================================================================================================== internal var lookBack: Int = 0 // Previous char read. private set internal var currentChar: Int = 0 // Current character read. Returns 0 if there is no more characters. private set internal var lookAhead: Int = 0 // Next character. private set internal var curSpecialToken: SpecialToken? = null // Current special token (e.g. quantifier) private set internal var lookAheadSpecialToken: SpecialToken? = null // Next special token private set // Indices in the pattern. private var index = 0 // Current char being processed index. private var prevNonWhitespaceIndex = 0 // Previous non-whitespace character index. private var curTokenIndex = 0 // Current token start index. private var lookAheadTokenIndex = 0 // Next token index. init { var processedPattern = patternString if (flags and Pattern.LITERAL > 0) { processedPattern = Pattern.quote(patternString) } else if (flags and Pattern.CANON_EQ > 0) { processedPattern = Lexer.normalize(patternString) } this.pattern = processedPattern.toCharArray().copyOf(processedPattern.length + 2) this.pattern[this.pattern.size - 1] = 0.toChar() this.pattern[this.pattern.size - 2] = 0.toChar() // Read first two tokens. movePointer() movePointer() } // Character checks ================================================================================================ /** Returns true, if current token is special, i.e. quantifier, or other compound token. */ val isSpecial: Boolean get() = curSpecialToken != null val isQuantifier: Boolean get() = isSpecial && curSpecialToken!!.type == SpecialToken.Type.QUANTIFIER val isNextSpecial: Boolean get() = lookAheadSpecialToken != null private fun Int.isSurrogatePair() : Boolean { val high = (this ushr 16).toChar() val low = this.toChar() return high.isHighSurrogate() && low.isLowSurrogate() } private fun Char.isLineSeparator(): Boolean = this == '\n' || this == '\r' || this == '\u0085' || this.toInt() or 1 == '\u2029'.toInt() /** Checks if there are any characters in the pattern. */ fun isEmpty(): Boolean = currentChar == 0 && lookAhead == 0 && index >= pattern.size && !isSpecial /** Return true if the current character is letter, false otherwise .*/ fun isLetter(): Boolean = !isEmpty() && !isSpecial && isLetter(currentChar) /** Check if the current char is high/low surrogate. */ fun isHighSurrogate(): Boolean = currentChar in 0xDBFF..0xD800 fun isLowSurrogate(): Boolean = currentChar in 0xDFFF..0xDC00 fun isSurrogate(): Boolean = isHighSurrogate() || isLowSurrogate() /** * Restores flags for Lexer * @param flags */ fun restoreFlags(flags: Int) { this.flags = flags lookAhead = currentChar lookAheadSpecialToken = curSpecialToken // curTokenIndex is an index of closing bracket ')' index = curTokenIndex + 1 lookAheadTokenIndex = curTokenIndex movePointer() } override fun toString(): String { return patternString } // Processing index moving ========================================================================================= /** Returns current character and moves string index to the next one. */ operator fun next(): Int { movePointer() return lookBack } /** Returns current special token and moves string index to the next one */ fun nextSpecial(): SpecialToken? { val res = curSpecialToken movePointer() return res } /** * Reread current character. May be required if a previous token changes mode * to one with different character interpretation. */ private fun reread() { lookAhead = currentChar lookAheadSpecialToken = curSpecialToken index = lookAheadTokenIndex lookAheadTokenIndex = curTokenIndex movePointer() } /** * Returns the next character index to read and moves pointer to the next one. * If comments flag is on this method will skip comments and whitespaces. * * The following actions are equivalent if comments flag is off: * currentChar = pattern[index++] == currentChar = pattern[nextIndex] */ private fun nextIndex(): Int { prevNonWhitespaceIndex = index if (flags and Pattern.COMMENTS != 0) { skipComments() } else { index++ } return prevNonWhitespaceIndex } /** Skips comments and whitespaces */ private fun skipComments(): Int { val length = pattern.size - 2 index++ do { while (index < length && pattern[index].isWhitespace()) { index++ } if (index < length && pattern[index] == '#') { index++ while (index < length && !pattern[index].isLineSeparator()) { index++ } } else { return index } } while (true) } /** * Returns the next code point in the pattern string. */ private fun nextCodePoint(): Int { val high = pattern[nextIndex()] // nextIndex skips comments and whitespaces if comments flag is on. if (high.isHighSurrogate()) { // Low and high chars may be delimited by spaces. val lowExpectedIndex = prevNonWhitespaceIndex + 1 if (lowExpectedIndex < pattern.size) { val low = pattern[lowExpectedIndex] if (low.isLowSurrogate()) { nextIndex() return Char.toCodePoint(high, low) } } } return high.toInt() } /** * Moves pointer one position right. Saves the current character to [lookBack], * [lookAhead] to the current one and finally read one more to [lookAhead]. */ private fun movePointer() { // swap pointers lookBack = currentChar currentChar = lookAhead curSpecialToken = lookAheadSpecialToken curTokenIndex = lookAheadTokenIndex lookAheadTokenIndex = index var reread: Boolean do { // Read the next character, analyze it and construct a token. lookAhead = if (index < pattern.size) nextCodePoint() else 0 lookAheadSpecialToken = null if (mode == Mode.ESCAPE) { processInEscapeMode() } reread = when (mode) { Mode.PATTERN -> processInPatternMode() Mode.RANGE -> processInRangeMode() else -> false } } while (reread) } // Special functions called from [movePointer] function to process chars in different modes ======================== /** * Processing an escaped sequence like "\Q foo \E". Just skip a character if it is not \E. * Returns whether we need to reread the character or not */ private fun processInEscapeMode(): Boolean { if (lookAhead == '\\'.toInt()) { // Need not care about supplementary code points here. val lookAheadChar: Char = if (index < pattern.size) pattern[nextIndex()] else '\u0000' lookAhead = lookAheadChar.toInt() if (lookAheadChar == 'E') { // If \E found - change the mode to the previous one and shift to the next char. mode = savedMode lookAhead = if (index <= pattern.size - 2) nextCodePoint() else 0 } else { // If \ have no E - make a step back and return. lookAhead = '\\'.toInt() index = prevNonWhitespaceIndex } } return false } /** Processes a next character in [Mode.PATTERN] mode. Returns whether we need to reread the character or not */ private fun processInPatternMode(): Boolean { if (lookAhead.isSurrogatePair()) { return false } val lookAheadChar = lookAhead.toChar() if (lookAheadChar == '\\') { return processEscapedChar() } // TODO: Look like we can create a quantifier here. when (lookAheadChar) { // Quantifier (*, +, ?). '+', '*', '?' -> { val mode = if (index < pattern.size) pattern[index] else '*' // look at the next character to determine if the mode is greedy, reluctant or possessive. when (mode) { '+' -> { lookAhead = lookAhead or Lexer.QMOD_POSSESSIVE; nextIndex() } '?' -> { lookAhead = lookAhead or Lexer.QMOD_RELUCTANT; nextIndex() } else -> lookAhead = lookAhead or Lexer.QMOD_GREEDY } } // Quantifier ({x,y}). '{' -> lookAheadSpecialToken = processQuantifier() // $. '$' -> lookAhead = CHAR_DOLLAR // A group or a special construction. '(' -> { if (pattern[index] != '?') { // Group lookAhead = CHAR_LEFT_PARENTHESIS } else { // Special constructs (non-capturing groups, look ahead/look behind etc). nextIndex() var char = pattern[index] var isLookBehind = false do { if (!isLookBehind) { when (char) { // Look ahead or an atomic group. '!' -> { lookAhead = CHAR_NEG_LOOKAHEAD; nextIndex() } '=' -> { lookAhead = CHAR_POS_LOOKAHEAD; nextIndex() } '>' -> { lookAhead = CHAR_ATOMIC_GROUP; nextIndex() } // Positive / negaitve look behind - need to check the next char. '<' -> { nextIndex() char = pattern[index] isLookBehind = true } // Flags. else -> { lookAhead = readFlags() // We return `res = res or 1 shl 8` from readFlags() if we read (?idmsux-idmsux) if (lookAhead >= 256) { // Just flags (no non-capturing group with them). Erase auxiliary bit. lookAhead = lookAhead and 0xff flags = lookAhead lookAhead = lookAhead shl 16 lookAhead = CHAR_FLAGS or lookAhead } else { // A non-capturing group with flags: (?<flags>:Foo) flags = lookAhead lookAhead = lookAhead shl 16 lookAhead = CHAR_NONCAP_GROUP or lookAhead } } } } else { // Process the second char for look behind construction. isLookBehind = false when (char) { '!' -> { lookAhead = CHAR_NEG_LOOKBEHIND; nextIndex() } '=' -> { lookAhead = CHAR_POS_LOOKBEHIND; nextIndex() } else -> throw PatternSyntaxException() } } } while (isLookBehind) } } ')' -> lookAhead = CHAR_RIGHT_PARENTHESIS '[' -> { lookAhead = CHAR_LEFT_SQUARE_BRACKET; mode = Mode.RANGE } '^' -> lookAhead = CHAR_CARET '|' -> lookAhead = CHAR_VERTICAL_BAR '.' -> lookAhead = CHAR_DOT } return false } /** Processes a character inside a range. Returns whether we need to reread the character or not */ private fun processInRangeMode(): Boolean { if (lookAhead.isSurrogatePair()) { return false } val lookAheadChar = lookAhead.toChar() when (lookAheadChar) { '\\' -> return processEscapedChar() '[' -> lookAhead = CHAR_LEFT_SQUARE_BRACKET ']' -> lookAhead = CHAR_RIGHT_SQUARE_BRACKET '^' -> lookAhead = CHAR_CARET '&' -> lookAhead = CHAR_AMPERSAND '-' -> lookAhead = CHAR_HYPHEN } return false } /** Processes an escaped (\x) character in any mode. Returns whether we need to reread the character or not */ private fun processEscapedChar() : Boolean { lookAhead = if (index < pattern.size - 2) nextCodePoint() else throw PatternSyntaxException() // The current code point cannot be a surrogate pair because it is an escaped special one. // Cast it to char or just skip it as if we pass through the else branch of the when below. if (lookAhead.isSurrogatePair()) { return false } val lookAheadChar = lookAhead.toChar() when (lookAheadChar) { // Character class. 'P', 'p' -> { val cs = parseCharClassName() val negative = lookAheadChar == 'P' lookAheadSpecialToken = AbstractCharClass.getPredefinedClass(cs, negative) lookAhead = 0 } // Word/whitespace/digit. 'w', 's', 'd', 'W', 'S', 'D' -> { lookAheadSpecialToken = AbstractCharClass.getPredefinedClass( fromCharArray(pattern, prevNonWhitespaceIndex, 1), false ) lookAhead = 0 } // Enter in ESCAPE mode. Skip this \Q symbol. 'Q' -> { savedMode = mode mode = Mode.ESCAPE return true } // Special characters like tab, new line etc. 't' -> lookAhead = '\t'.toInt() 'n' -> lookAhead = '\n'.toInt() 'r' -> lookAhead = '\r'.toInt() 'f' -> lookAhead = '\u000C'.toInt() 'a' -> lookAhead = '\u0007'.toInt() 'e' -> lookAhead = '\u001B'.toInt() // Back references to capturing groups. '1', '2', '3', '4', '5', '6', '7', '8', '9' -> { if (mode == Mode.PATTERN) { lookAhead = 0x80000000.toInt() or lookAhead // Captured group reference is 0x80...<group number> } } // A literal: octal, hex, or hex unicode. '0' -> lookAhead = readOctals() 'x' -> lookAhead = readHex(2) 'u' -> lookAhead = readHex(4) // Special characters like EOL, EOI etc 'b' -> lookAhead = CHAR_WORD_BOUND 'B' -> lookAhead = CHAR_NONWORD_BOUND 'A' -> lookAhead = CHAR_START_OF_INPUT 'G' -> lookAhead = CHAR_PREVIOUS_MATCH 'Z' -> lookAhead = CHAR_END_OF_LINE 'z' -> lookAhead = CHAR_END_OF_INPUT // \cx - A control character corresponding to x. 'c' -> { if (index < pattern.size - 2) { //need not care about supplementary codepoints here lookAhead = pattern[nextIndex()].toInt() and 0x1f } else { // TODO: Add messages to the exceptions. throw PatternSyntaxException() } } 'C', 'E', 'F', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'R', 'T', 'U', 'V', 'X', 'Y', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'o', 'q', 'y' -> throw PatternSyntaxException() } return false } /** Process [lookAhead] in assumption that it's quantifier. */ private fun processQuantifier(): Quantifier { assert(lookAhead == '{'.toInt()) val sb = StringBuilder(4) var min = -1 var max = -1 // Obtain a min value. var char: Char = if (index < pattern.size) pattern[nextIndex()] else throw PatternSyntaxException() while (char != '}') { if (char == ',' && min < 0) { try { val minParsed = sb.toString().toInt() min = if (minParsed >= 0) minParsed else throw PatternSyntaxException() sb.length = 0 } catch (nfe: NumberFormatException) { throw PatternSyntaxException() } } else { sb.append(char) } char = if (index < pattern.size) pattern[nextIndex()] else break } if (char != '}') { throw PatternSyntaxException() } // Obtain a max value, if it exists if (sb.isNotEmpty()) { try { val maxParsed = sb.toString().toInt() max = if (maxParsed >= 0) maxParsed else throw PatternSyntaxException() if (min < 0) { min = max } } catch (nfe: NumberFormatException) { throw PatternSyntaxException() } } if (min < 0 || max >=0 && max < min) { throw PatternSyntaxException() } val mod = if (index < pattern.size) pattern[index] else '*' when (mod) { '+' -> { lookAhead = Lexer.QUANT_COMP_P; nextIndex() } '?' -> { lookAhead = Lexer.QUANT_COMP_R; nextIndex() } else -> lookAhead = Lexer.QUANT_COMP } return Quantifier(min, max) } // Reading methods for specific tokens ============================================================================= /** Process expression flags given with (?idmsux-idmsux). Returns the flags processed. */ private fun readFlags(): Int { var positive = true var result = flags while (index < pattern.size) { val char = pattern[index] when (char) { '-' -> { if (!positive) { throw PatternSyntaxException() } positive = false } 'i' -> result = if (positive) result or Pattern.CASE_INSENSITIVE else result xor Pattern.CASE_INSENSITIVE and result 'd' -> result = if (positive) result or Pattern.UNIX_LINES else result xor Pattern.UNIX_LINES and result 'm' -> result = if (positive) result or Pattern.MULTILINE else result xor Pattern.MULTILINE and result 's' -> result = if (positive) result or Pattern.DOTALL else result xor Pattern.DOTALL and result // We don't support UNICODE_CASE. /*'u' -> result = if (positive) result or Pattern.UNICODE_CASE else result xor Pattern.UNICODE_CASE and result*/ 'x' -> result = if (positive) result or Pattern.COMMENTS else result xor Pattern.COMMENTS and result ':' -> { nextIndex() return result } ')' -> { nextIndex() return result or (1 shl 8) } } nextIndex() } throw PatternSyntaxException() } /** Parse character classes names and verifies correction of the syntax */ private fun parseCharClassName(): String { val sb = StringBuilder(10) if (index < pattern.size - 2) { // one symbol family if (pattern[index] != '{') { return "Is${pattern[nextIndex()]}" } nextIndex() // Skip '{' var char = pattern[nextIndex()] while (index < pattern.size - 2 && char != '}') { sb.append(char) char = pattern[nextIndex()] } if (char != '}') throw PatternSyntaxException() } if (sb.isEmpty()) throw PatternSyntaxException() val res = sb.toString() return when { res.length == 1 -> "Is$res" res.length > 3 && (res.startsWith("Is") || res.startsWith("In")) -> res.substring(2) else -> res } } /** Process hexadecimal integer. */ private fun readHex(max: Int): Int { val builder = StringBuilder(max) val length = pattern.size - 2 var i = 0 while (i < max && index < length) { builder.append(pattern[nextIndex()]) i++ } if (i == max) { try { return builder.toString().toInt(16) } catch (e: NumberFormatException) {} } throw PatternSyntaxException() } /** Process octal integer. */ private fun readOctals(): Int { val length = pattern.size - 2 var result = 0 var digit = digitOf(pattern[index], 8) if (digit == -1) { throw PatternSyntaxException() } val max = if (digit > 3) 2 else 3 var i = 0 while (i < max && index < length && digit != -1) { result *= 8 result += digit nextIndex() digit = digitOf(pattern[index], 8) i++ } return result } companion object { // Special characters. val CHAR_DOLLAR = 0xe0000000.toInt() or '$'.toInt() val CHAR_RIGHT_PARENTHESIS = 0xe0000000.toInt() or ')'.toInt() val CHAR_LEFT_SQUARE_BRACKET = 0xe0000000.toInt() or '['.toInt() val CHAR_RIGHT_SQUARE_BRACKET = 0xe0000000.toInt() or ']'.toInt() val CHAR_CARET = 0xe0000000.toInt() or '^'.toInt() val CHAR_VERTICAL_BAR = 0xe0000000.toInt() or '|'.toInt() val CHAR_AMPERSAND = 0xe0000000.toInt() or '&'.toInt() val CHAR_HYPHEN = 0xe0000000.toInt() or '-'.toInt() val CHAR_DOT = 0xe0000000.toInt() or '.'.toInt() val CHAR_LEFT_PARENTHESIS = 0x80000000.toInt() or '('.toInt() val CHAR_NONCAP_GROUP = 0xc0000000.toInt() or '('.toInt() val CHAR_POS_LOOKAHEAD = 0xe0000000.toInt() or '('.toInt() val CHAR_NEG_LOOKAHEAD = 0xf0000000.toInt() or '('.toInt() val CHAR_POS_LOOKBEHIND = 0xf8000000.toInt() or '('.toInt() val CHAR_NEG_LOOKBEHIND = 0xfc000000.toInt() or '('.toInt() val CHAR_ATOMIC_GROUP = 0xfe000000.toInt() or '('.toInt() val CHAR_FLAGS = 0xff000000.toInt() or '('.toInt() val CHAR_START_OF_INPUT = 0x80000000.toInt() or 'A'.toInt() val CHAR_WORD_BOUND = 0x80000000.toInt() or 'b'.toInt() val CHAR_NONWORD_BOUND = 0x80000000.toInt() or 'B'.toInt() val CHAR_PREVIOUS_MATCH = 0x80000000.toInt() or 'G'.toInt() val CHAR_END_OF_INPUT = 0x80000000.toInt() or 'z'.toInt() val CHAR_END_OF_LINE = 0x80000000.toInt() or 'Z'.toInt() // Quantifier modes. val QMOD_GREEDY = 0xe0000000.toInt() val QMOD_RELUCTANT = 0xc0000000.toInt() val QMOD_POSSESSIVE = 0x80000000.toInt() // Quantifiers. val QUANT_STAR = QMOD_GREEDY or '*'.toInt() val QUANT_STAR_P = QMOD_POSSESSIVE or '*'.toInt() val QUANT_STAR_R = QMOD_RELUCTANT or '*'.toInt() val QUANT_PLUS = QMOD_GREEDY or '+'.toInt() val QUANT_PLUS_P = QMOD_POSSESSIVE or '+'.toInt() val QUANT_PLUS_R = QMOD_RELUCTANT or '+'.toInt() val QUANT_ALT = QMOD_GREEDY or '?'.toInt() val QUANT_ALT_P = QMOD_POSSESSIVE or '?'.toInt() val QUANT_ALT_R = QMOD_RELUCTANT or '?'.toInt() val QUANT_COMP = QMOD_GREEDY or '{'.toInt() val QUANT_COMP_P = QMOD_POSSESSIVE or '{'.toInt() val QUANT_COMP_R = QMOD_RELUCTANT or '{'.toInt() /** Returns true if [ch] is a plain token. */ fun isLetter(ch: Int): Boolean { // All supplementary codepoints have integer value that is >= 0. return ch >= 0 } private fun String.codePointAt(index: Int): Int { val high = this[index] if (high.isHighSurrogate() && index + 1 < this.length) { val low = this[index + 1] if (low.isLowSurrogate()) { return Char.toCodePoint(high, low) } } return high.toInt() } // Decomposition =============================================================================================== // Maximum length of decomposition. val MAX_DECOMPOSITION_LENGTH = 4 // Maximum length of Hangul decomposition. Note that MAX_HANGUL_DECOMPOSITION_LENGTH <= MAX_DECOMPOSITION_LENGTH. val MAX_HANGUL_DECOMPOSITION_LENGTH = 3 /* * Following constants are needed for Hangul canonical decomposition. * Hangul decomposition algorithm and constants are taken according * to description at http://www.unicode.org/versions/Unicode4.0.0/ch03.pdf * "3.12 Conjoining Jamo Behavior" */ val SBase = 0xAC00 val LBase = 0x1100 val VBase = 0x1161 val TBase = 0x11A7 val SCount = 11172 val LCount = 19 val VCount = 21 val TCount = 28 val NCount = 588 // Access to the decomposition tables. ========================================================================= /** Gets canonical class for given codepoint from decomposition mappings table. */ fun getCanonicalClass(ch: Int): Int = getCanonicalClassInternal(ch) /** Tests Unicode codepoint if it is a boundary of decomposed Unicode codepoint. */ fun isDecomposedCharBoundary(ch: Int): Boolean = getCanonicalClass(ch) == 0 /** Tests if given codepoint is a canonical decomposition of another codepoint. */ fun hasSingleCodepointDecomposition(ch: Int): Boolean = hasSingleCodepointDecompositionInternal(ch) /** Tests if given codepoint has canonical decomposition and given codepoint's canonical class is not 0. */ fun hasDecompositionNonNullCanClass(ch: Int): Boolean = (ch == 0x0340) or (ch == 0x0341) or (ch == 0x0343) or (ch == 0x0344) /** Gets decomposition for given codepoint from decomposition mappings table. */ fun getDecomposition(ch: Int): IntArray? = getDecompositionInternal(ch) // ============================================================================================================= /** * Normalize given string. */ fun normalize(input: String): String { val inputChars = input.toCharArray() val inputLength = inputChars.size var inputCodePointsIndex = 0 var decompHangulIndex = 0 //codePoints of input val inputCodePoints = IntArray(inputLength) //result of canonical decomposition of input var resCodePoints = IntArray(inputLength * MAX_DECOMPOSITION_LENGTH) //current symbol's codepoint var ch: Int //current symbol's decomposition var decomp: IntArray? //result of canonical and Hangul decomposition of input val decompHangul: IntArray //result of canonical decomposition of input in UTF-16 encoding val result = StringBuilder() var i = 0 while (i < inputLength) { ch = input.codePointAt(i) inputCodePoints[inputCodePointsIndex++] = ch i += if (Char.isSupplementaryCodePoint(ch)) 2 else 1 } // Canonical decomposition based on mappings in decomposition table. var resCodePointsIndex = decomposeString(inputCodePoints, inputCodePointsIndex, resCodePoints) // Canonical ordering. // See http://www.unicode.org/reports/tr15/#Decomposition for details resCodePoints = Lexer.getCanonicalOrder(resCodePoints, resCodePointsIndex) // Decomposition for Hangul syllables. // See http://www.unicode.org/reports/tr15/#Hangul for details decompHangul = IntArray(resCodePoints.size) @Suppress("NAME_SHADOWING") for (i in 0..resCodePointsIndex - 1) { val curSymb = resCodePoints[i] decomp = getHangulDecomposition(curSymb) if (decomp == null) { decompHangul[decompHangulIndex++] = curSymb } else { // Note that Hangul decompositions have length that is equal 2 or 3. decompHangul[decompHangulIndex++] = decomp[0] decompHangul[decompHangulIndex++] = decomp[1] if (decomp.size == 3) { decompHangul[decompHangulIndex++] = decomp[2] } } } // Translating into UTF-16 encoding @Suppress("NAME_SHADOWING") for (i in 0..decompHangulIndex - 1) { result.append(Char.toChars(decompHangul[i])) } return result.toString() } /** * Rearrange codepoints in [inputInts] according to canonical order. Return an array with rearranged codepoints. */ fun getCanonicalOrder(inputInts: IntArray, length: Int): IntArray { val inputLength = if (length < inputInts.size) length else inputInts.size /* * Simple bubble-sort algorithm. Note that many codepoints have 0 canonical class, so this algorithm works * almost lineary in overwhelming majority of cases. This is due to specific of Unicode combining * classes and codepoints. */ for (i in 1..inputLength - 1) { var j = i - 1 val iCanonicalClass = getCanonicalClass(inputInts[i]) val ch: Int if (iCanonicalClass == 0) { continue } while (j > -1) { if (getCanonicalClass(inputInts[j]) > iCanonicalClass) { j = j - 1 } else { break } } ch = inputInts[i] for (k in i downTo j + 1 + 1) { inputInts[k] = inputInts[k - 1] } inputInts[j + 1] = ch } return inputInts } /** * Gets decomposition for given Hangul syllable. * This is an implementation of Hangul decomposition algorithm * according to http://www.unicode.org/versions/Unicode4.0.0/ch03.pdf "3.12 Conjoining Jamo Behavior". */ fun getHangulDecomposition(ch: Int): IntArray? { val SIndex = ch - SBase if (SIndex < 0 || SIndex >= SCount) { return null } else { val L = LBase + SIndex / NCount val V = VBase + SIndex % NCount / TCount var T = SIndex % TCount val decomp: IntArray if (T == 0) { decomp = intArrayOf(L, V) } else { T = TBase + T decomp = intArrayOf(L, V, T) } return decomp } } } }
apache-2.0
deedb007713e6e66b1a2c15a5ac6c673
38.46865
179
0.512843
4.84983
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/fir-low-level-api/src/org/jetbrains/kotlin/idea/fir/low/level/api/trasformers/FirDesignatedImplicitTypesTransformerForIDE.kt
2
3126
/* * Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.fir.low.level.api.trasformers import org.jetbrains.kotlin.fir.FirSession import org.jetbrains.kotlin.fir.declarations.FirDeclaration import org.jetbrains.kotlin.fir.declarations.FirResolvePhase import org.jetbrains.kotlin.fir.expressions.FirStatement import org.jetbrains.kotlin.fir.resolve.ResolutionMode import org.jetbrains.kotlin.fir.resolve.ScopeSession import org.jetbrains.kotlin.fir.resolve.transformers.body.resolve.FirImplicitAwareBodyResolveTransformer import org.jetbrains.kotlin.fir.resolve.transformers.body.resolve.ImplicitBodyResolveComputationSession import org.jetbrains.kotlin.fir.resolve.transformers.body.resolve.createReturnTypeCalculatorForIDE import org.jetbrains.kotlin.fir.visitors.CompositeTransformResult import org.jetbrains.kotlin.fir.visitors.compose import org.jetbrains.kotlin.idea.fir.low.level.api.element.builder.FirIdeDesignatedBodyResolveTransformerForReturnTypeCalculator import org.jetbrains.kotlin.idea.fir.low.level.api.element.builder.FirTowerDataContextCollector internal class FirDesignatedImplicitTypesTransformerForIDE( private val designation: Iterator<FirDeclaration>, targetDeclaration: FirDeclaration, session: FirSession, scopeSession: ScopeSession, private val towerDataContextCollector: FirTowerDataContextCollector?, implicitBodyResolveComputationSession: ImplicitBodyResolveComputationSession = ImplicitBodyResolveComputationSession(), ) : FirImplicitAwareBodyResolveTransformer( session, implicitBodyResolveComputationSession = implicitBodyResolveComputationSession, phase = FirResolvePhase.IMPLICIT_TYPES_BODY_RESOLVE, implicitTypeOnly = true, scopeSession = scopeSession, returnTypeCalculator = createReturnTypeCalculatorForIDE( session, scopeSession, implicitBodyResolveComputationSession, ::FirIdeDesignatedBodyResolveTransformerForReturnTypeCalculator ) ) { private val phaseReplaceOracle = PhaseReplaceOracle(targetDeclaration) override fun transformDeclarationContent(declaration: FirDeclaration, data: ResolutionMode): CompositeTransformResult<FirDeclaration> { if (designation.hasNext()) phaseReplaceOracle.transformDeclarationInside(designation.next()) { it.visitNoTransform(this, data) return declaration.compose() } return super.transformDeclarationContent(declaration, data) } override fun needReplacePhase(firDeclaration: FirDeclaration): Boolean = phaseReplaceOracle.needReplacePhase(firDeclaration) override fun onBeforeStatementResolution(statement: FirStatement) { towerDataContextCollector?.addStatementContext(statement, context.towerDataContext) } override fun onBeforeDeclarationContentResolve(declaration: FirDeclaration) { towerDataContextCollector?.addDeclarationContext(declaration, context.towerDataContext) } }
apache-2.0
f80c3a324ef037005d64f97909602f20
50.245902
139
0.818618
4.729198
false
false
false
false
edvin/kdbc
src/test/kotlin/no/tornado/kdbc/tests/CustomerTests.kt
1
1732
package no.tornado.kdbc.tests import kdbc.Insert import kdbc.Query import kdbc.Update import no.tornado.kdbc.tests.models.Customer import no.tornado.kdbc.tests.tables.CUSTOMER class InsertCustomer(customer: Customer) : Insert() { val c = CUSTOMER() init { insert(c) { c.name `=` customer.name c.uuid `=` customer.uuid } generatedKeys { customer.id = getInt(1) } } } class InsertCustomersInBatch(customers: List<Customer>) : Insert() { val c = CUSTOMER() init { // H2 Does not support generated keys in batch, so we can't retrieve them with `generatedKeys { }` here batch(customers) { customer -> insert(c) { c.name `=` customer.name c.uuid `=` customer.uuid } } } } class SelectFirstCustomerByName : Query<Customer>() { val c = CUSTOMER() init { select(c) from(c) + "ORDER BY ${c.name} DESC LIMIT 1" } } fun main(args: Array<String>) { println(SelectFirstCustomerByName().render()) } class SelectCustomer : Query<Customer>() { val c = CUSTOMER() init { select(c) from(c) } override fun get() = Customer(c) fun byId(id: Int) = firstOrNull { where { c.id `=` id } } } class UpdateCustomer(customer: Customer) : Update() { val c = CUSTOMER() init { update(c) { c.name `=` customer.name } where { c.id `=` customer.id } } } class DeleteCustomer(id: Int) : Query<Customer>() { val c = CUSTOMER() init { delete(c) { c.id `=` id } } }
apache-2.0
42389318868a6a5c661278f1aa75b6a8
18.255556
111
0.5306
3.740821
false
false
false
false
smmribeiro/intellij-community
platform/configuration-store-impl/src/ProjectStoreBridge.kt
1
11208
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.configurationStore import com.intellij.concurrency.ConcurrentCollectionFactory import com.intellij.openapi.components.* import com.intellij.openapi.components.impl.ModulePathMacroManager import com.intellij.openapi.components.impl.ProjectPathMacroManager import com.intellij.openapi.components.impl.stores.FileStorageCoreUtil import com.intellij.openapi.components.impl.stores.IProjectStore import com.intellij.openapi.project.Project import com.intellij.openapi.util.JDOMUtil import com.intellij.openapi.util.Pair import com.intellij.openapi.util.SystemInfoRt import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.vfs.VirtualFileManager import com.intellij.project.stateStore import com.intellij.util.PathUtil import com.intellij.util.containers.HashingStrategy import com.intellij.util.io.systemIndependentPath import com.intellij.workspaceModel.ide.impl.jps.serialization.* import org.jdom.Element import org.jetbrains.jps.util.JpsPathUtil import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.ConcurrentMap import java.util.function.Supplier class ProjectStoreBridge(private val project: Project) : ModuleSavingCustomizer { override fun createSaveSessionProducerManager(): ProjectSaveSessionProducerManager { return ProjectWithModulesSaveSessionProducerManager(project) } override fun saveModules(projectSaveSessionManager: SaveSessionProducerManager, store: IProjectStore) { val writer = JpsStorageContentWriter(projectSaveSessionManager as ProjectWithModulesSaveSessionProducerManager, store, project) project.getComponent(JpsProjectModelSynchronizer::class.java).saveChangedProjectEntities(writer) } override fun commitModuleComponents(projectSaveSessionManager: SaveSessionProducerManager, moduleStore: ComponentStoreImpl, moduleSaveSessionManager: SaveSessionProducerManager) { (projectSaveSessionManager as ProjectWithModulesSaveSessionProducerManager).commitComponents(moduleStore, moduleSaveSessionManager) } } private class JpsStorageContentWriter(private val session: ProjectWithModulesSaveSessionProducerManager, private val store: IProjectStore, private val project: Project) : JpsFileContentWriter { override fun saveComponent(fileUrl: String, componentName: String, componentTag: Element?) { val filePath = JpsPathUtil.urlToPath(fileUrl) if (FileUtil.extensionEquals(filePath, "iml")) { session.setModuleComponentState(filePath, componentName, componentTag) } else if (isExternalModuleFile(filePath)) { session.setExternalModuleComponentState(FileUtil.getNameWithoutExtension(PathUtil.getFileName(filePath)), componentName, componentTag) } else { val stateStorage = getProjectStateStorage(filePath, store, project) ?: return val producer = session.getProducer(stateStorage) if (producer is DirectoryBasedSaveSessionProducer) { producer.setFileState(PathUtil.getFileName(filePath), componentName, componentTag?.children?.first()) } else { producer?.setState(null, componentName, componentTag) } } } override fun getReplacePathMacroMap(fileUrl: String): PathMacroMap { val filePath = JpsPathUtil.urlToPath(fileUrl) return if (FileUtil.extensionEquals(filePath, "iml") || isExternalModuleFile(filePath)) { ModulePathMacroManager.createInstance(Supplier { filePath }).replacePathMap } else { ProjectPathMacroManager.getInstance(project).replacePathMap } } } private val MODULE_FILE_STORAGE_ANNOTATION = FileStorageAnnotation(StoragePathMacros.MODULE_FILE, false) private class ProjectWithModulesSaveSessionProducerManager(project: Project) : ProjectSaveSessionProducerManager(project) { companion object { private val NULL_ELEMENT = Element("null") } private val internalModuleComponents: ConcurrentMap<String, ConcurrentHashMap<String, Element>> = if (!SystemInfoRt.isFileSystemCaseSensitive) ConcurrentCollectionFactory.createConcurrentMap(HashingStrategy.caseInsensitive()) else ConcurrentCollectionFactory.createConcurrentMap() private val externalModuleComponents = ConcurrentHashMap<String, ConcurrentHashMap<String, Element>>() fun setModuleComponentState(imlFilePath: String, componentName: String, componentTag: Element?) { val componentToElement = internalModuleComponents.computeIfAbsent(imlFilePath) { ConcurrentHashMap() } componentToElement[componentName] = componentTag ?: NULL_ELEMENT } fun setExternalModuleComponentState(moduleFileName: String, componentName: String, componentTag: Element?) { val componentToElement = externalModuleComponents.computeIfAbsent(moduleFileName) { ConcurrentHashMap() } componentToElement[componentName] = componentTag ?: NULL_ELEMENT } fun commitComponents(moduleStore: ComponentStoreImpl, moduleSaveSessionManager: SaveSessionProducerManager) { fun commitToStorage(storageSpec: Storage, componentToElement: Map<String, Element>) { val storage = moduleStore.storageManager.getStateStorage(storageSpec) val producer = moduleSaveSessionManager.getProducer(storage) if (producer != null) { componentToElement.forEach { (componentName, componentTag) -> producer.setState(null, componentName, if (componentTag === NULL_ELEMENT) null else componentTag) } } } val moduleFilePath = moduleStore.storageManager.expandMacro(StoragePathMacros.MODULE_FILE) val internalComponents = internalModuleComponents[moduleFilePath.systemIndependentPath] if (internalComponents != null) { commitToStorage(MODULE_FILE_STORAGE_ANNOTATION, internalComponents) } val moduleFileName = FileUtil.getNameWithoutExtension(moduleFilePath.fileName.toString()) val externalComponents = externalModuleComponents[moduleFileName] if (externalComponents != null) { val providerFactory = StreamProviderFactory.EP_NAME.getExtensions(project).firstOrNull() if (providerFactory != null) { val storageSpec = providerFactory.getOrCreateStorageSpec(StoragePathMacros.MODULE_FILE) commitToStorage(storageSpec, externalComponents) } } } } internal class StorageJpsConfigurationReader(private val project: Project, private val baseDirUrl: String) : JpsFileContentReaderWithCache { @Volatile private var fileContentCachingReader: CachingJpsFileContentReader? = null override fun loadComponent(fileUrl: String, componentName: String, customModuleFilePath: String?): Element? { val filePath = JpsPathUtil.urlToPath(fileUrl) if (componentName == "") { //this is currently used for loading Eclipse project configuration from .classpath file val file = VirtualFileManager.getInstance().findFileByUrl(fileUrl) return file?.inputStream?.use { JDOMUtil.load(it) } } if (FileUtil.extensionEquals(filePath, "iml") || isExternalModuleFile(filePath)) { //todo fetch data from ModuleStore (https://jetbrains.team/p/wm/issues/51) return getCachingReader().loadComponent(fileUrl, componentName, customModuleFilePath) } else { val storage = getProjectStateStorage(filePath, project.stateStore, project) ?: return null val stateMap = storage.getStorageData() return if (storage is DirectoryBasedStorageBase) { val elementContent = stateMap.getElement(PathUtil.getFileName(filePath)) if (elementContent != null) { Element(FileStorageCoreUtil.COMPONENT).setAttribute(FileStorageCoreUtil.NAME, componentName).addContent(elementContent) } else { null } } else { stateMap.getElement(componentName) } } } private fun getCachingReader(): CachingJpsFileContentReader { val reader = fileContentCachingReader ?: CachingJpsFileContentReader(baseDirUrl) if (fileContentCachingReader == null) { fileContentCachingReader = reader } return reader } override fun getExpandMacroMap(fileUrl: String): ExpandMacroToPathMap { val filePath = JpsPathUtil.urlToPath(fileUrl) if (FileUtil.extensionEquals(filePath, "iml") || isExternalModuleFile(filePath)) { return getCachingReader().getExpandMacroMap(fileUrl) } else { return PathMacroManager.getInstance(project).expandMacroMap } } override fun clearCache() { fileContentCachingReader = null } } fun getProjectStateStorage(filePath: String, store: IProjectStore, project: Project): StateStorageBase<StateMap>? { val storageSpec = getStorageSpec(filePath, project) ?: return null @Suppress("UNCHECKED_CAST") return store.storageManager.getStateStorage(storageSpec) as StateStorageBase<StateMap> } private fun getStorageSpec(filePath: String, project: Project): Storage? { val collapsedPath: String val splitterClass: Class<out StateSplitterEx> val fileName = PathUtil.getFileName(filePath) val parentPath = PathUtil.getParentPath(filePath) val parentFileName = PathUtil.getFileName(parentPath) if (FileUtil.extensionEquals(filePath, "ipr") || fileName == "misc.xml" && parentFileName == ".idea") { collapsedPath = "\$PROJECT_FILE$" splitterClass = StateSplitterEx::class.java } else { if (parentFileName == Project.DIRECTORY_STORE_FOLDER) { collapsedPath = fileName splitterClass = StateSplitterEx::class.java } else { val grandParentPath = PathUtil.getParentPath(parentPath) collapsedPath = parentFileName splitterClass = FakeDirectoryBasedStateSplitter::class.java if (PathUtil.getFileName(grandParentPath) != Project.DIRECTORY_STORE_FOLDER) { val providerFactory = StreamProviderFactory.EP_NAME.getExtensions(project).firstOrNull() ?: return null if (parentFileName == "project") { if (fileName == "libraries.xml" || fileName == "artifacts.xml") { val inProjectStorage = FileStorageAnnotation(FileUtil.getNameWithoutExtension(fileName), false, splitterClass) val componentName = if (fileName == "libraries.xml") "libraryTable" else "ArtifactManager" return providerFactory.getOrCreateStorageSpec(fileName, StateAnnotation(componentName, inProjectStorage)) } if (fileName == "modules.xml") { return providerFactory.getOrCreateStorageSpec(fileName) } } error("$filePath is not under .idea directory and not under external system cache") } } } return FileStorageAnnotation(collapsedPath, false, splitterClass) } /** * This fake implementation is used to force creating directory based storage in StateStorageManagerImpl.createStateStorage */ private class FakeDirectoryBasedStateSplitter : StateSplitterEx() { override fun splitState(state: Element): MutableList<Pair<Element, String>> { throw AssertionError() } }
apache-2.0
b5440f1a7af8077754c03157115f8fc8
46.291139
144
0.751784
5.252109
false
true
false
false
cout970/Modeler
src/main/kotlin/com/cout970/reactive/internal/nested/NestedDemo.kt
1
6149
package com.cout970.reactive.internal.nested import com.cout970.reactive.core.* import com.cout970.reactive.dsl.* import com.cout970.reactive.internal.demoWindow import com.cout970.reactive.nodes.child import com.cout970.reactive.nodes.div import com.cout970.reactive.nodes.label import com.cout970.reactive.nodes.style import org.joml.Vector2f import org.liquidengine.legui.style.color.ColorConstants fun main(args: Array<String>) { demoWindow { env -> Renderer.render(env.frame.container) { child(NestedComponent::class) } } } data class PositionProps(val pos: Vector2f) : RProps class NestedComponent : RStatelessComponent<EmptyProps>() { override fun componentWillUnmount() { println("componentWillUnmount: NestedComponent") } override fun componentDidMount() { println("componentDidMount: NestedComponent") } override fun RBuilder.render() = div("NestedComponent") { style { sizeX = 256f sizeY = 256f } child(ForceUpdateButton::class, ForceUpdateButton.Props(Vector2f(0f, 0f), { rerender() })) child(StateTesterComponent::class, PositionProps(Vector2f(128f, 0f))) label("Level 1") { style { posY = 128f sizeX = 32f sizeY = 32f } } child(MoreNestedComponent::class, PositionProps(Vector2f(128f, 128f))) } } class MoreNestedComponent : RStatelessComponent<PositionProps>() { override fun componentWillUnmount() { println("componentWillUnmount: MoreNestedComponent") } override fun componentDidMount() { println("componentDidMount: MoreNestedComponent") } override fun RBuilder.render() = div("MoreNestedComponent") { style { position.set(props.pos) sizeX = 128f sizeY = 128f } child(ForceUpdateButton::class, ForceUpdateButton.Props(Vector2f(0f, 0f), { rerender() })) child(StateTesterComponent::class, PositionProps(Vector2f(64f, 0f))) label("Level 2") { style { posY = 64f sizeX = 32f sizeY = 32f } } child(EvenMoreNestedComponent::class, PositionProps(Vector2f(64f, 64f))) } } class EvenMoreNestedComponent : RStatelessComponent<PositionProps>() { override fun componentWillUnmount() { println("componentWillUnmount: EvenMoreNestedComponent") } override fun componentDidMount() { println("componentDidMount: EvenMoreNestedComponent") } override fun RBuilder.render() = div("EvenMoreNestedComponent") { style { position.set(props.pos) sizeX = 64f sizeY = 64f } child(ForceUpdateButton::class, ForceUpdateButton.Props(Vector2f(0f, 0f), { rerender() })) child(StateTesterComponent::class, PositionProps(Vector2f(32f, 0f))) label("Level 3") { style { posY = 32f sizeX = 32f sizeY = 32f } } } } class StateTesterComponent : RStatelessComponent<PositionProps>() { override fun componentWillUnmount() { println("componentWillUnmount: StateTesterComponent") } override fun componentDidMount() { println("componentDidMount: StateTesterComponent") } override fun RBuilder.render() = div("Tester") { style { position.set(props.pos) sizeX = 32f sizeY = 64f } child(ExampleToggleButton::class, PositionProps(Vector2f(0f, 0f))) child(ForceUpdateButton::class, ForceUpdateButton.Props(Vector2f(0f, 32f), { rerender() })) } } class ExampleToggleButton : RComponent<PositionProps, ExampleToggleButton.State>() { override fun getInitialState() = State(false) override fun componentWillUnmount() { println("componentWillUnmount: ExampleToggleButton") } override fun componentDidMount() { println("componentDidMount: ExampleToggleButton") } override fun RBuilder.render() = div("ToggleButton") { style { backgroundColor { if (state.on) ColorConstants.green() else ColorConstants.red() } borderRadius(0f) position.set(props.pos) sizeX = 32f sizeY = 32f } if (state.on) { div("OnlyOn") { style { sizeX = 16f sizeY = 32f } child(CounterButton::class) } } onClick { setState { State(!on) } } } data class State(val on: Boolean) : RState } class CounterButton : RComponent<EmptyProps, CounterButton.State>() { override fun getInitialState() = State(0) override fun componentWillUnmount() { println("componentWillUnmount: CounterButton") } override fun componentDidMount() { println("componentDidMount: CounterButton") } override fun RBuilder.render() = label(state.count.toString(), "CounterButton") { style { backgroundColor { ColorConstants.lightBlack() } borderRadius(0f) style.textColor = ColorConstants.white() sizeX = 16f sizeY = 32f } onClick { setState { State(count + 1) } } } data class State(val count: Int) : RState } class ForceUpdateButton : RStatelessComponent<ForceUpdateButton.Props>() { override fun componentWillUnmount() { println("componentWillUnmount: ForceUpdateButton") } override fun componentDidMount() { println("componentDidMount: ForceUpdateButton") } override fun RBuilder.render() = div("ForceUpdateButton") { style { backgroundColor { ColorConstants.blue() } borderRadius(0f) position.set(props.pos) sizeX = 32f sizeY = 32f } onClick { props.callback() } } data class Props(val pos: Vector2f, val callback: () -> Unit) : RProps }
gpl-3.0
764040c6246a1854b175f40ba53277f0
26.207965
99
0.606928
4.370291
false
false
false
false
tensorflow/examples
lite/codelabs/digit_classifier/android/finish/app/src/main/java/org/tensorflow/lite/codelabs/digitclassifier/MainActivity.kt
1
3426
/* Copyright 2019 The TensorFlow Authors. 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 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ package org.tensorflow.lite.codelabs.digitclassifier import android.annotation.SuppressLint import android.graphics.Color import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import android.util.Log import android.view.MotionEvent import android.widget.Button import android.widget.TextView import com.divyanshu.draw.widget.DrawView class MainActivity : AppCompatActivity() { private var drawView: DrawView? = null private var clearButton: Button? = null private var predictedTextView: TextView? = null private var digitClassifier = DigitClassifier(this) @SuppressLint("ClickableViewAccessibility") override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // Setup view instances. drawView = findViewById(R.id.draw_view) drawView?.setStrokeWidth(70.0f) drawView?.setColor(Color.WHITE) drawView?.setBackgroundColor(Color.BLACK) clearButton = findViewById(R.id.clear_button) predictedTextView = findViewById(R.id.predicted_text) // Setup clear drawing button. clearButton?.setOnClickListener { drawView?.clearCanvas() predictedTextView?.text = getString(R.string.prediction_text_placeholder) } // Setup classification trigger so that it classify after every stroke drew. drawView?.setOnTouchListener { _, event -> // As we have interrupted DrawView's touch event, // we first need to pass touch events through to the instance for the drawing to show up. drawView?.onTouchEvent(event) // Then if user finished a touch event, run classification if (event.action == MotionEvent.ACTION_UP) { classifyDrawing() } true } // Setup digit classifier. digitClassifier .initialize() .addOnFailureListener { e -> Log.e(TAG, "Error to setting up digit classifier.", e) } } override fun onDestroy() { // Sync DigitClassifier instance lifecycle with MainActivity lifecycle, // and free up resources (e.g. TF Lite instance) once the activity is destroyed. digitClassifier.close() super.onDestroy() } private fun classifyDrawing() { val bitmap = drawView?.getBitmap() if ((bitmap != null) && (digitClassifier.isInitialized)) { digitClassifier .classifyAsync(bitmap) .addOnSuccessListener { resultText -> predictedTextView?.text = resultText } .addOnFailureListener { e -> predictedTextView?.text = getString( R.string.classification_error_message, e.localizedMessage ) Log.e(TAG, "Error classifying drawing.", e) } } } companion object { private const val TAG = "MainActivity" } }
apache-2.0
4ac6c4d354b48113f39b5224080e327e
33.606061
95
0.704612
4.686731
false
false
false
false
kivensolo/UiUsingListView
library/network/src/main/java/com/zeke/reactivehttp/base/BaseReactiveActivity.kt
1
2055
package com.zeke.reactivehttp.base import android.app.ProgressDialog import android.content.Context import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import androidx.lifecycle.LifecycleOwner import androidx.lifecycle.lifecycleScope import com.zeke.reactivehttp.viewmodel.IUIActionEventObserver import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Job /** * @Author: leavesC * @Date: 2020/10/22 10:27 * @Desc: * 提供的一个默认 BaseActivity,其实现了 IUIActionEventObserver 接口,用于提供一些默认参数和默认行为, * 例如 CoroutineScope 和 showLoading。 * * 当中包含与系统和用户交互的逻辑,其负责响应 BaseReactiveViewModel 中的数据变化, * 提供了和 BaseReactiveViewModel 进行绑定的方法。 * * 外部也可以自己实现IUIActionEventObserver 接口 */ open class BaseReactiveActivity : AppCompatActivity(), IUIActionEventObserver { override val lifecycleSupportedScope: CoroutineScope get() = lifecycleScope override val lContext: Context? get() = this override val lLifecycleOwner: LifecycleOwner get() = this private var loadDialog: ProgressDialog? = null override fun showLoading(job: Job?) { dismissLoading() loadDialog = ProgressDialog(lContext).apply { setCancelable(true) setCanceledOnTouchOutside(false) //用于实现当弹窗销毁的时候同时取消网络请求 // setOnDismissListener { // job?.cancel() // } show() } } override fun dismissLoading() { loadDialog?.takeIf { it.isShowing }?.dismiss() loadDialog = null } override fun showToast(msg: String) { if (msg.isNotBlank()) { Toast.makeText(this, msg, Toast.LENGTH_SHORT).show() } } override fun finishView() { finish() } override fun onDestroy() { super.onDestroy() dismissLoading() } }
gpl-2.0
68b237d84320d0459fab14e5fa37df52
24.971831
79
0.674986
4.217391
false
false
false
false
androidx/androidx
glance/glance-appwidget/integration-tests/template-demos/src/main/java/androidx/glance/appwidget/template/demos/SingleEntityDemoWidget.kt
3
4468
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.glance.appwidget.template.demos import android.content.Context import androidx.compose.runtime.Composable import androidx.datastore.preferences.core.Preferences import androidx.datastore.preferences.core.booleanPreferencesKey import androidx.glance.GlanceId import androidx.glance.GlanceTheme import androidx.glance.ImageProvider import androidx.glance.action.ActionParameters import androidx.glance.appwidget.GlanceAppWidget import androidx.glance.appwidget.GlanceAppWidgetReceiver import androidx.glance.appwidget.action.ActionCallback import androidx.glance.appwidget.action.actionRunCallback import androidx.glance.appwidget.state.updateAppWidgetState import androidx.glance.appwidget.template.GlanceTemplateAppWidget import androidx.glance.appwidget.template.SingleEntityTemplate import androidx.glance.currentState import androidx.glance.template.ActionBlock import androidx.glance.template.HeaderBlock import androidx.glance.template.ImageBlock import androidx.glance.template.SingleEntityTemplateData import androidx.glance.template.TemplateImageWithDescription import androidx.glance.template.TemplateText import androidx.glance.template.TemplateTextButton import androidx.glance.template.TextBlock import androidx.glance.template.TextType /** * Demo app widget using [SingleEntityTemplate] to define layout. */ class SingleEntityDemoWidget : GlanceTemplateAppWidget() { @Composable override fun TemplateContent() { GlanceTheme { SingleEntityTemplate( SingleEntityTemplateData( headerBlock = HeaderBlock( text = TemplateText("Single Entity Demo", TextType.Title), icon = TemplateImageWithDescription( ImageProvider(R.drawable.ic_widgets), "Header icon" ), ), textBlock = TextBlock( text1 = TemplateText( getTitle(currentState<Preferences>()[ToggleKey] == true), TextType.Title ), text2 = TemplateText("Subtitle", TextType.Label), text3 = TemplateText( "Body Lorem ipsum dolor sit amet, consectetur adipiscing elit", TextType.Body ), priority = 0, ), imageBlock = ImageBlock( images = listOf( TemplateImageWithDescription( ImageProvider(R.drawable.palm_leaf), "Compose image" ) ), priority = 1, ), actionBlock = ActionBlock( actionButtons = listOf( TemplateTextButton( actionRunCallback<SEButtonAction>(), "Toggle title" ), ), ), ) ) } } } class SingleEntityWidgetReceiver : GlanceAppWidgetReceiver() { override val glanceAppWidget: GlanceAppWidget = SingleEntityDemoWidget() } class SEButtonAction : ActionCallback { override suspend fun onAction( context: Context, glanceId: GlanceId, parameters: ActionParameters ) { updateAppWidgetState(context, glanceId) { it[ToggleKey] = it[ToggleKey] != true } SingleEntityDemoWidget().update(context, glanceId) } } private val ToggleKey = booleanPreferencesKey("title_toggled_key") private fun getTitle(toggled: Boolean) = if (toggled) "Title2" else "Title1"
apache-2.0
e77a031d62aaeb0fcd920c3a245acf04
38.539823
100
0.626902
5.468788
false
false
false
false
androidx/androidx
room/room-compiler-processing/src/main/java/androidx/room/compiler/processing/javac/JavacTypeElement.kt
3
9137
/* * Copyright (C) 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.room.compiler.processing.javac import androidx.room.compiler.codegen.XClassName import androidx.room.compiler.codegen.XTypeName import androidx.room.compiler.processing.XEnumEntry import androidx.room.compiler.processing.XEnumTypeElement import androidx.room.compiler.processing.XFieldElement import androidx.room.compiler.processing.XHasModifiers import androidx.room.compiler.processing.XMemberContainer import androidx.room.compiler.processing.XMethodElement import androidx.room.compiler.processing.XNullability import androidx.room.compiler.processing.XTypeElement import androidx.room.compiler.processing.XTypeParameterElement import androidx.room.compiler.processing.collectAllMethods import androidx.room.compiler.processing.collectFieldsIncludingPrivateSupers import androidx.room.compiler.processing.filterMethodsByConfig import androidx.room.compiler.processing.javac.kotlin.KotlinMetadataElement import androidx.room.compiler.processing.util.MemoizedSequence import com.google.auto.common.MoreElements import com.google.auto.common.MoreTypes import com.squareup.javapoet.ClassName import com.squareup.kotlinpoet.javapoet.JClassName import javax.lang.model.element.ElementKind import javax.lang.model.element.TypeElement import javax.lang.model.type.TypeKind import javax.lang.model.util.ElementFilter internal sealed class JavacTypeElement( env: JavacProcessingEnv, override val element: TypeElement ) : JavacElement(env, element), XTypeElement, XHasModifiers by JavacHasModifiers(element) { override val name: String get() = element.simpleName.toString() @Suppress("UnstableApiUsage") override val packageName: String get() = MoreElements.getPackage(element).qualifiedName.toString() val kotlinMetadata by lazy { KotlinMetadataElement.createFor(element) } override val qualifiedName by lazy { element.qualifiedName.toString() } @Deprecated( "Use asClassName().toJavaPoet() to be clear the name is for JavaPoet.", replaceWith = ReplaceWith( "asClassName().toJavaPoet()", "androidx.room.compiler.codegen.toJavaPoet" ) ) override val className: ClassName by lazy { xClassName.java } private val xClassName: XClassName by lazy { XClassName( JClassName.get(element), XTypeName.UNAVAILABLE_KTYPE_NAME, XNullability.NONNULL ) } override fun asClassName() = xClassName override val enclosingElement: XMemberContainer? by lazy { enclosingTypeElement } override val typeParameters: List<XTypeParameterElement> by lazy { element.typeParameters.mapIndexed { index, typeParameter -> val typeArgument = kotlinMetadata?.kmType?.typeArguments?.get(index) JavacTypeParameterElement(env, this, typeParameter, typeArgument) } } override val closestMemberContainer: JavacTypeElement get() = this override val enclosingTypeElement: XTypeElement? by lazy { element.enclosingType(env) } private val _declaredFields by lazy { ElementFilter.fieldsIn(element.enclosedElements) .filterNot { it.kind == ElementKind.ENUM_CONSTANT } .map { JavacFieldElement( env = env, element = it, ) } } private val allMethods = MemoizedSequence { collectAllMethods(this) } private val allFieldsIncludingPrivateSupers = MemoizedSequence { collectFieldsIncludingPrivateSupers(this) } override fun getAllMethods(): Sequence<XMethodElement> = allMethods override fun getAllFieldsIncludingPrivateSupers() = allFieldsIncludingPrivateSupers override fun getDeclaredFields(): List<XFieldElement> { return _declaredFields } override fun isKotlinObject() = kotlinMetadata?.isObject() == true || kotlinMetadata?.isCompanionObject() == true override fun isCompanionObject() = kotlinMetadata?.isCompanionObject() == true override fun isDataClass() = kotlinMetadata?.isDataClass() == true override fun isValueClass() = kotlinMetadata?.isValueClass() == true override fun isFunctionalInterface() = kotlinMetadata?.isFunctionalInterface() == true override fun isExpect() = kotlinMetadata?.isExpect() == true override fun isAnnotationClass(): Boolean { return kotlinMetadata?.isAnnotationClass() ?: (element.kind == ElementKind.ANNOTATION_TYPE) } override fun isClass(): Boolean { return kotlinMetadata?.isClass() ?: (element.kind == ElementKind.CLASS) } override fun isNested(): Boolean { return element.enclosingType(env) != null } override fun isInterface(): Boolean { return kotlinMetadata?.isInterface() ?: (element.kind == ElementKind.INTERFACE) } override fun findPrimaryConstructor(): JavacConstructorElement? { val primarySignature = kotlinMetadata?.findPrimaryConstructorSignature() ?: return null return getConstructors().firstOrNull { primarySignature == it.descriptor } } private val _declaredMethods by lazy { ElementFilter.methodsIn(element.enclosedElements).map { JavacMethodElement( env = env, element = it ) }.filterMethodsByConfig(env) } override fun getDeclaredMethods(): List<JavacMethodElement> { return _declaredMethods } override fun getConstructors(): List<JavacConstructorElement> { return ElementFilter.constructorsIn(element.enclosedElements).map { JavacConstructorElement( env = env, element = it ) } } override fun getSuperInterfaceElements(): List<XTypeElement> { return element.interfaces.map { env.wrapTypeElement(MoreTypes.asTypeElement(it)) } } override fun getEnclosedTypeElements(): List<XTypeElement> { return ElementFilter.typesIn(element.enclosedElements).map { env.wrapTypeElement(it) } } override val type: JavacDeclaredType by lazy { env.wrap( typeMirror = element.asType(), kotlinType = kotlinMetadata?.kmType, elementNullability = element.nullability ) } override val superClass: JavacType? by lazy { // javac models non-existing types as TypeKind.NONE but we prefer to make it nullable. // just makes more sense and safer as we don't need to check for none. // The result value is a JavacType instead of JavacDeclaredType to gracefully handle // cases where super is an error type. val superClass = element.superclass if (superClass.kind == TypeKind.NONE) { null } else { env.wrap<JavacType>( typeMirror = superClass, kotlinType = kotlinMetadata?.superType, elementNullability = element.nullability ) } } override val superInterfaces by lazy { element.interfaces.map { val element = MoreTypes.asTypeElement(it) env.wrap<JavacType>( typeMirror = it, kotlinType = KotlinMetadataElement.createFor(element)?.kmType, elementNullability = element.nullability ) } } class DefaultJavacTypeElement( env: JavacProcessingEnv, element: TypeElement ) : JavacTypeElement(env, element) class JavacEnumTypeElement( env: JavacProcessingEnv, element: TypeElement ) : JavacTypeElement(env, element), XEnumTypeElement { init { check(element.kind == ElementKind.ENUM) } override val entries: Set<XEnumEntry> by lazy { element.enclosedElements.filter { it.kind == ElementKind.ENUM_CONSTANT }.mapTo(mutableSetOf()) { JavacEnumEntry(env, it, this) } } } companion object { fun create( env: JavacProcessingEnv, typeElement: TypeElement ): JavacTypeElement { return when (typeElement.kind) { ElementKind.ENUM -> JavacEnumTypeElement(env, typeElement) else -> DefaultJavacTypeElement(env, typeElement) } } } }
apache-2.0
25e4877b21da6e1248adb92bffb21a22
33.479245
95
0.671993
5.13892
false
false
false
false
androidx/androidx
compose/foundation/foundation/src/commonMain/kotlin/androidx/compose/foundation/selection/Toggleable.kt
3
8831
/* * Copyright 2018 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.foundation.selection import androidx.compose.foundation.Indication import androidx.compose.foundation.LocalIndication import androidx.compose.foundation.clickable import androidx.compose.foundation.interaction.MutableInteractionSource import androidx.compose.foundation.interaction.PressInteraction import androidx.compose.runtime.remember import androidx.compose.ui.Modifier import androidx.compose.ui.composed import androidx.compose.ui.platform.debugInspectorInfo import androidx.compose.ui.platform.inspectable import androidx.compose.ui.semantics.Role import androidx.compose.ui.semantics.semantics import androidx.compose.ui.semantics.toggleableState import androidx.compose.ui.state.ToggleableState /** * Configure component to make it toggleable via input and accessibility events * * This version has no [MutableInteractionSource] or [Indication] parameters, default indication from * [LocalIndication] will be used. To specify [MutableInteractionSource] or [Indication], use another * overload. * * @sample androidx.compose.foundation.samples.ToggleableSample * * @see [Modifier.triStateToggleable] if you require support for an indeterminate state. * * @param value whether Toggleable is on or off * @param enabled whether or not this [toggleable] will handle input events and appear * enabled for semantics purposes * @param role the type of user interface element. Accessibility services might use this * to describe the element or do customizations * @param onValueChange callback to be invoked when toggleable is clicked, * therefore the change of the state in requested. */ fun Modifier.toggleable( value: Boolean, enabled: Boolean = true, role: Role? = null, onValueChange: (Boolean) -> Unit ) = composed( inspectorInfo = debugInspectorInfo { name = "toggleable" properties["value"] = value properties["enabled"] = enabled properties["role"] = role properties["onValueChange"] = onValueChange } ) { Modifier.toggleable( value = value, interactionSource = remember { MutableInteractionSource() }, indication = LocalIndication.current, enabled = enabled, role = role, onValueChange = onValueChange ) } /** * Configure component to make it toggleable via input and accessibility events. * * This version requires both [MutableInteractionSource] and [Indication] to work properly. Use another * overload if you don't need these parameters. * * @sample androidx.compose.foundation.samples.ToggleableSample * * @see [Modifier.triStateToggleable] if you require support for an indeterminate state. * * @param value whether Toggleable is on or off * @param interactionSource [MutableInteractionSource] that will be used to emit * [PressInteraction.Press] when this toggleable is being pressed. * @param indication indication to be shown when modified element is pressed. Be default, * indication from [LocalIndication] will be used. Pass `null` to show no indication, or * current value from [LocalIndication] to show theme default * @param enabled whether or not this [toggleable] will handle input events and appear * enabled for semantics purposes * @param role the type of user interface element. Accessibility services might use this * to describe the element or do customizations * @param onValueChange callback to be invoked when toggleable is clicked, * therefore the change of the state in requested. */ fun Modifier.toggleable( value: Boolean, interactionSource: MutableInteractionSource, indication: Indication?, enabled: Boolean = true, role: Role? = null, onValueChange: (Boolean) -> Unit ) = inspectable( inspectorInfo = debugInspectorInfo { name = "toggleable" properties["value"] = value properties["interactionSource"] = interactionSource properties["indication"] = indication properties["enabled"] = enabled properties["role"] = role properties["onValueChange"] = onValueChange } ) { Modifier.triStateToggleable( state = ToggleableState(value), enabled = enabled, interactionSource = interactionSource, indication = indication, role = role, onClick = { onValueChange(!value) } ) } /** * Configure component to make it toggleable via input and accessibility events with three * states: On, Off and Indeterminate. * * TriStateToggleable should be used when there are dependent Toggleables associated to this * component and those can have different values. * * This version has no [MutableInteractionSource] or [Indication] parameters, default indication * from [LocalIndication] will be used. To specify [MutableInteractionSource] or [Indication], * use another overload. * * @sample androidx.compose.foundation.samples.TriStateToggleableSample * * @see [Modifier.toggleable] if you want to support only two states: on and off * * @param state current value for the component * @param enabled whether or not this [triStateToggleable] will handle input events and * appear enabled for semantics purposes * @param role the type of user interface element. Accessibility services might use this * to describe the element or do customizations * @param onClick will be called when user clicks the toggleable. */ fun Modifier.triStateToggleable( state: ToggleableState, enabled: Boolean = true, role: Role? = null, onClick: () -> Unit ) = composed( inspectorInfo = debugInspectorInfo { name = "triStateToggleable" properties["state"] = state properties["enabled"] = enabled properties["role"] = role properties["onClick"] = onClick } ) { Modifier.triStateToggleable( state = state, interactionSource = remember { MutableInteractionSource() }, indication = LocalIndication.current, enabled = enabled, role = role, onClick = onClick ) } /** * Configure component to make it toggleable via input and accessibility events with three * states: On, Off and Indeterminate. * * TriStateToggleable should be used when there are dependent Toggleables associated to this * component and those can have different values. * * This version requires both [MutableInteractionSource] and [Indication] to work properly. Use another * overload if you don't need these parameters. * * @sample androidx.compose.foundation.samples.TriStateToggleableSample * * @see [Modifier.toggleable] if you want to support only two states: on and off * * @param state current value for the component * @param interactionSource [MutableInteractionSource] that will be used to emit * [PressInteraction.Press] when this triStateToggleable is being pressed. * @param indication indication to be shown when modified element is pressed. Be default, * indication from [LocalIndication] will be used. Pass `null` to show no indication, or * current value from [LocalIndication] to show theme default * @param enabled whether or not this [triStateToggleable] will handle input events and * appear enabled for semantics purposes * @param role the type of user interface element. Accessibility services might use this * to describe the element or do customizations * @param onClick will be called when user clicks the toggleable. */ fun Modifier.triStateToggleable( state: ToggleableState, interactionSource: MutableInteractionSource, indication: Indication?, enabled: Boolean = true, role: Role? = null, onClick: () -> Unit ) = inspectable( inspectorInfo = debugInspectorInfo { name = "triStateToggleable" properties["state"] = state properties["enabled"] = enabled properties["role"] = role properties["interactionSource"] = interactionSource properties["indication"] = indication properties["onClick"] = onClick } ) { clickable( interactionSource = interactionSource, indication = indication, enabled = enabled, role = role, onClick = onClick ).semantics { this.toggleableState = state } }
apache-2.0
5accf407d8a38bda90e574fd7310259f
37.903084
103
0.73242
4.807295
false
false
false
false
androidx/androidx
core/core-splashscreen/src/androidTest/java/androidx/core/splashscreen/test/SplashScreenTestUtils.kt
3
3682
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.core.splashscreen.test import android.app.Instrumentation import android.content.ComponentName import android.content.Context import android.content.Intent import android.os.Bundle import androidx.test.core.app.ApplicationProvider import androidx.test.platform.app.InstrumentationRegistry import androidx.test.uiautomator.By import androidx.test.uiautomator.UiDevice import androidx.test.uiautomator.Until import org.hamcrest.core.IsNull import org.hamcrest.MatcherAssert.assertThat import org.junit.Assert import kotlin.reflect.KClass private const val SPLASH_SCREEN_STYLE_ICON = 1 private const val KEY_SPLASH_SCREEN_STYLE: String = "android.activity.splashScreenStyle" private const val BASIC_SAMPLE_PACKAGE: String = "androidx.core.splashscreen.test" private const val LAUNCH_TIMEOUT: Long = 5000 /** * Start an activity simulating a launch from the launcher * to ensure the splash screen is shown */ fun startActivityWithSplashScreen( activityClass: KClass<out SplashScreenTestControllerHolder>, device: UiDevice, intentModifier: ((Intent) -> Unit)? = null ): SplashScreenTestController { // Start from the home screen device.pressHome() // Wait for launcher val launcherPackage: String = device.launcherPackageName assertThat(launcherPackage, IsNull.notNullValue()) device.wait( Until.hasObject(By.pkg(launcherPackage).depth(0)), LAUNCH_TIMEOUT ) // Launch the app val context = ApplicationProvider.getApplicationContext<Context>() val baseIntent = context.packageManager.getLaunchIntentForPackage( BASIC_SAMPLE_PACKAGE ) val intent = Intent(baseIntent).apply { component = ComponentName(BASIC_SAMPLE_PACKAGE, activityClass.qualifiedName!!) intentModifier?.invoke(this) } val monitor = object : Instrumentation.ActivityMonitor( activityClass.qualifiedName!!, Instrumentation.ActivityResult(0, Intent()), false ) { override fun onStartActivity(intent: Intent?): Instrumentation.ActivityResult? { return if (intent?.component?.packageName == BASIC_SAMPLE_PACKAGE) { Instrumentation.ActivityResult(0, Intent()) } else { null } } } InstrumentationRegistry.getInstrumentation().addMonitor(monitor) context.startActivity( intent, // Force the splash screen to be shown with an icon Bundle().apply { putInt(KEY_SPLASH_SCREEN_STYLE, SPLASH_SCREEN_STYLE_ICON) } ) Assert.assertTrue( device.wait( Until.hasObject(By.pkg(BASIC_SAMPLE_PACKAGE).depth(0)), LAUNCH_TIMEOUT ) ) val splashScreenTestActivity = monitor.waitForActivityWithTimeout(LAUNCH_TIMEOUT) as SplashScreenTestControllerHolder? if (splashScreenTestActivity == null) { Assert.fail( activityClass.simpleName!! + " was not launched after " + "$LAUNCH_TIMEOUT ms" ) } return splashScreenTestActivity!!.controller }
apache-2.0
454ec67b55a90acb8a90e4d295050de6
34.747573
95
0.71673
4.70844
false
true
false
false
nrizzio/Signal-Android
app/src/main/java/org/thoughtcrime/securesms/mediasend/v2/text/TextStoryPostCreationViewModel.kt
1
4800
package org.thoughtcrime.securesms.mediasend.v2.text import android.graphics.Bitmap import android.graphics.Typeface import android.net.Uri import android.os.Bundle import androidx.annotation.ColorInt import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import io.reactivex.rxjava3.core.Observable import io.reactivex.rxjava3.core.Single import io.reactivex.rxjava3.disposables.CompositeDisposable import io.reactivex.rxjava3.schedulers.Schedulers import io.reactivex.rxjava3.subjects.BehaviorSubject import io.reactivex.rxjava3.subjects.Subject import org.signal.core.util.logging.Log import org.thoughtcrime.securesms.contacts.paged.ContactSearchKey import org.thoughtcrime.securesms.dependencies.ApplicationDependencies import org.thoughtcrime.securesms.fonts.TextFont import org.thoughtcrime.securesms.fonts.TextToScript import org.thoughtcrime.securesms.fonts.TypefaceCache import org.thoughtcrime.securesms.linkpreview.LinkPreview import org.thoughtcrime.securesms.mediasend.v2.text.send.TextStoryPostSendRepository import org.thoughtcrime.securesms.mediasend.v2.text.send.TextStoryPostSendResult import org.thoughtcrime.securesms.util.livedata.Store class TextStoryPostCreationViewModel(private val repository: TextStoryPostSendRepository, private val identityChangesSince: Long = System.currentTimeMillis()) : ViewModel() { private val store = Store(TextStoryPostCreationState()) private val textFontSubject: Subject<TextFont> = BehaviorSubject.create() private val temporaryBodySubject: Subject<String> = BehaviorSubject.createDefault("") private val disposables = CompositeDisposable() private val internalTypeface = MutableLiveData<Typeface>() val state: LiveData<TextStoryPostCreationState> = store.stateLiveData val typeface: LiveData<Typeface> = internalTypeface init { textFontSubject.onNext(store.state.textFont) val scriptGuess = temporaryBodySubject.observeOn(Schedulers.io()).map { TextToScript.guessScript(it) } Observable.combineLatest(textFontSubject, scriptGuess, ::Pair) .observeOn(Schedulers.io()) .distinctUntilChanged() .switchMapSingle { (textFont, script) -> TypefaceCache.get(ApplicationDependencies.getApplication(), textFont, script) } .subscribeOn(Schedulers.io()) .subscribe { internalTypeface.postValue(it) } } fun compressToBlob(bitmap: Bitmap): Single<Uri> { return repository.compressToBlob(bitmap) } override fun onCleared() { disposables.clear() } fun saveToInstanceState(outState: Bundle) { outState.putParcelable(TEXT_STORY_INSTANCE_STATE, store.state) } fun restoreFromInstanceState(inState: Bundle) { if (inState.containsKey(TEXT_STORY_INSTANCE_STATE)) { val state: TextStoryPostCreationState = inState.getParcelable(TEXT_STORY_INSTANCE_STATE)!! textFontSubject.onNext(store.state.textFont) store.update { state } } } fun getBody(): CharSequence { return store.state.body } @ColorInt fun getTextColor(): Int { return store.state.textColor } fun setTextColor(@ColorInt textColor: Int) { store.update { it.copy(textColor = textColor) } } fun setBody(body: CharSequence) { store.update { it.copy(body = body) } } fun setAlignment(textAlignment: TextAlignment) { store.update { it.copy(textAlignment = textAlignment) } } fun setTextScale(scale: Int) { store.update { it.copy(textScale = scale) } } fun setTextColorStyle(textColorStyle: TextColorStyle) { store.update { it.copy(textColorStyle = textColorStyle) } } fun setTextFont(textFont: TextFont) { textFontSubject.onNext(textFont) store.update { it.copy(textFont = textFont) } } fun cycleBackgroundColor() { store.update { it.copy(backgroundColor = TextStoryBackgroundColors.cycleBackgroundColor(it.backgroundColor)) } } fun setLinkPreview(url: String?) { store.update { it.copy(linkPreviewUri = url) } } fun setTemporaryBody(temporaryBody: String) { temporaryBodySubject.onNext(temporaryBody) } fun send(contacts: Set<ContactSearchKey>, linkPreview: LinkPreview?): Single<TextStoryPostSendResult> { return repository.send( contacts, store.state, linkPreview, identityChangesSince ) } class Factory(private val repository: TextStoryPostSendRepository) : ViewModelProvider.Factory { override fun <T : ViewModel> create(modelClass: Class<T>): T { return modelClass.cast(TextStoryPostCreationViewModel(repository)) as T } } companion object { private val TAG = Log.tag(TextStoryPostCreationViewModel::class.java) private const val TEXT_STORY_INSTANCE_STATE = "text.story.instance.state" } }
gpl-3.0
c5541606d49e88a3bc780288c1431720
33.042553
174
0.767708
4.336043
false
false
false
false
SimpleMobileTools/Simple-Notes
app/src/main/kotlin/com/simplemobiletools/notes/pro/activities/MainActivity.kt
1
52323
package com.simplemobiletools.notes.pro.activities import android.annotation.SuppressLint import android.app.Activity import android.content.ActivityNotFoundException import android.content.Context import android.content.Intent import android.content.pm.ShortcutInfo import android.graphics.drawable.Icon import android.graphics.drawable.LayerDrawable import android.net.Uri import android.os.Bundle import android.print.PrintAttributes import android.print.PrintManager import android.text.method.ArrowKeyMovementMethod import android.text.method.LinkMovementMethod import android.util.TypedValue import android.view.ActionMode import android.view.Gravity import android.view.MenuItem import android.view.inputmethod.EditorInfo import android.webkit.WebResourceRequest import android.webkit.WebView import android.webkit.WebViewClient import android.widget.ImageView import android.widget.TextView import android.widget.Toast import com.simplemobiletools.commons.dialogs.* import com.simplemobiletools.commons.extensions.* import com.simplemobiletools.commons.helpers.* import com.simplemobiletools.commons.models.FAQItem import com.simplemobiletools.commons.models.FileDirItem import com.simplemobiletools.commons.models.RadioItem import com.simplemobiletools.commons.models.Release import com.simplemobiletools.commons.views.MyEditText import com.simplemobiletools.notes.pro.BuildConfig import com.simplemobiletools.notes.pro.R import com.simplemobiletools.notes.pro.adapters.NotesPagerAdapter import com.simplemobiletools.notes.pro.databases.NotesDatabase import com.simplemobiletools.notes.pro.dialogs.* import com.simplemobiletools.notes.pro.extensions.* import com.simplemobiletools.notes.pro.fragments.TextFragment import com.simplemobiletools.notes.pro.helpers.* import com.simplemobiletools.notes.pro.models.Note import kotlinx.android.synthetic.main.activity_main.* import java.io.File import java.io.FileOutputStream import java.io.OutputStream import java.nio.charset.Charset import java.util.* class MainActivity : SimpleActivity() { private val EXPORT_FILE_SYNC = 1 private val EXPORT_FILE_NO_SYNC = 2 private val IMPORT_FILE_SYNC = 1 private val IMPORT_FILE_NO_SYNC = 2 private val PICK_OPEN_FILE_INTENT = 1 private val PICK_EXPORT_FILE_INTENT = 2 private val PICK_IMPORT_NOTES_INTENT = 3 private val PICK_EXPORT_NOTES_INTENT = 4 private lateinit var mCurrentNote: Note private var mNotes = ArrayList<Note>() private var mAdapter: NotesPagerAdapter? = null private var noteViewWithTextSelected: MyEditText? = null private var saveNoteButton: MenuItem? = null private var wasInit = false private var storedEnableLineWrap = true private var showSaveButton = false private var showUndoButton = false private var showRedoButton = false private var searchIndex = 0 private var searchMatches = emptyList<Int>() private var isSearchActive = false private lateinit var searchQueryET: MyEditText private lateinit var searchPrevBtn: ImageView private lateinit var searchNextBtn: ImageView private lateinit var searchClearBtn: ImageView override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) appLaunched(BuildConfig.APPLICATION_ID) setupOptionsMenu() refreshMenuItems() searchQueryET = findViewById(R.id.search_query) searchPrevBtn = findViewById(R.id.search_previous) searchNextBtn = findViewById(R.id.search_next) searchClearBtn = findViewById(R.id.search_clear) initViewPager(intent.getLongExtra(OPEN_NOTE_ID, -1L)) pager_title_strip.setTextSize(TypedValue.COMPLEX_UNIT_PX, getPercentageFontSize()) pager_title_strip.layoutParams.height = (pager_title_strip.height + resources.getDimension(R.dimen.activity_margin) * 2 * (config.fontSizePercentage / 100f)).toInt() checkWhatsNewDialog() checkIntents(intent) storeStateVariables() if (config.showNotePicker && savedInstanceState == null) { displayOpenNoteDialog() } wasInit = true checkAppOnSDCard() setupSearchButtons() } override fun onResume() { super.onResume() setupToolbar(main_toolbar) if (storedEnableLineWrap != config.enableLineWrap) { initViewPager() } refreshMenuItems() pager_title_strip.apply { setTextSize(TypedValue.COMPLEX_UNIT_PX, getPercentageFontSize()) setGravity(Gravity.CENTER_VERTICAL) setNonPrimaryAlpha(0.4f) setTextColor(getProperTextColor()) } updateTextColors(view_pager) checkShortcuts() search_wrapper.setBackgroundColor(getProperPrimaryColor()) val contrastColor = getProperPrimaryColor().getContrastColor() arrayListOf(searchPrevBtn, searchNextBtn, searchClearBtn).forEach { it.applyColorFilter(contrastColor) } } override fun onPause() { super.onPause() storeStateVariables() } override fun onDestroy() { super.onDestroy() if (!isChangingConfigurations) { NotesDatabase.destroyInstance() } } private fun refreshMenuItems() { val multipleNotesExist = mNotes.size > 1 val isCurrentItemChecklist = isCurrentItemChecklist() main_toolbar.menu.apply { val areButtonsVisible = (showRedoButton || showUndoButton) && mCurrentNote.type == NoteType.TYPE_TEXT.value findItem(R.id.undo).apply { isVisible = areButtonsVisible isEnabled = showUndoButton && mCurrentNote.type == NoteType.TYPE_TEXT.value icon?.alpha = if (isEnabled) 255 else 127 } findItem(R.id.redo).apply { isVisible = areButtonsVisible isEnabled = showRedoButton && mCurrentNote.type == NoteType.TYPE_TEXT.value icon?.alpha = if (isEnabled) 255 else 127 } } main_toolbar.menu.apply { findItem(R.id.rename_note).isVisible = multipleNotesExist findItem(R.id.open_note).isVisible = multipleNotesExist findItem(R.id.delete_note).isVisible = multipleNotesExist findItem(R.id.export_all_notes).isVisible = multipleNotesExist && !isQPlus() findItem(R.id.export_notes).isVisible = multipleNotesExist && isQPlus() findItem(R.id.open_search).isVisible = !isCurrentItemChecklist findItem(R.id.remove_done_items).isVisible = isCurrentItemChecklist findItem(R.id.sort_checklist).isVisible = isCurrentItemChecklist findItem(R.id.import_folder).isVisible = !isQPlus() findItem(R.id.import_notes).isVisible = isQPlus() findItem(R.id.lock_note).isVisible = mNotes.isNotEmpty() && (::mCurrentNote.isInitialized && !mCurrentNote.isLocked()) findItem(R.id.unlock_note).isVisible = mNotes.isNotEmpty() && (::mCurrentNote.isInitialized && mCurrentNote.isLocked()) saveNoteButton = findItem(R.id.save_note) saveNoteButton!!.isVisible = !config.autosaveNotes && showSaveButton && (::mCurrentNote.isInitialized && mCurrentNote.type == NoteType.TYPE_TEXT.value) } pager_title_strip.beVisibleIf(multipleNotesExist) } private fun setupOptionsMenu() { main_toolbar.setOnMenuItemClickListener { menuItem -> if (config.autosaveNotes && menuItem.itemId != R.id.undo && menuItem.itemId != R.id.redo) { saveCurrentNote(false) } val fragment = getCurrentFragment() when (menuItem.itemId) { R.id.open_search -> fragment?.handleUnlocking { openSearch() } R.id.open_note -> displayOpenNoteDialog() R.id.save_note -> fragment?.handleUnlocking { saveNote() } R.id.undo -> undo() R.id.redo -> redo() R.id.new_note -> displayNewNoteDialog() R.id.rename_note -> fragment?.handleUnlocking { displayRenameDialog() } R.id.share -> fragment?.handleUnlocking { shareText() } R.id.lock_note -> lockNote() R.id.unlock_note -> unlockNote() R.id.open_file -> tryOpenFile() R.id.import_folder -> openFolder() R.id.export_as_file -> fragment?.handleUnlocking { tryExportAsFile() } R.id.export_all_notes -> tryExportAllNotes() R.id.export_notes -> tryExportNotes() R.id.import_notes -> tryImportNotes() R.id.print -> fragment?.handleUnlocking { printText() } R.id.delete_note -> fragment?.handleUnlocking { displayDeleteNotePrompt() } R.id.settings -> launchSettings() R.id.about -> launchAbout() R.id.remove_done_items -> fragment?.handleUnlocking { removeDoneItems() } R.id.sort_checklist -> fragment?.handleUnlocking { displaySortChecklistDialog() } else -> return@setOnMenuItemClickListener false } return@setOnMenuItemClickListener true } } // https://code.google.com/p/android/issues/detail?id=191430 quickfix override fun onActionModeStarted(mode: ActionMode?) { super.onActionModeStarted(mode) if (wasInit) { currentNotesView()?.apply { if (config.clickableLinks || movementMethod is LinkMovementMethod) { movementMethod = ArrowKeyMovementMethod.getInstance() noteViewWithTextSelected = this } } } } override fun onActionModeFinished(mode: ActionMode?) { super.onActionModeFinished(mode) if (config.clickableLinks) { noteViewWithTextSelected?.movementMethod = LinkMovementMethod.getInstance() } } override fun onBackPressed() { if (!config.autosaveNotes && mAdapter?.anyHasUnsavedChanges() == true) { ConfirmationAdvancedDialog(this, "", R.string.unsaved_changes_warning, R.string.save, R.string.discard) { if (it) { mAdapter?.saveAllFragmentTexts() } super.onBackPressed() } } else if (isSearchActive) { closeSearch() } else { super.onBackPressed() } } override fun onNewIntent(intent: Intent) { super.onNewIntent(intent) val wantedNoteId = intent.getLongExtra(OPEN_NOTE_ID, -1L) view_pager.currentItem = getWantedNoteIndex(wantedNoteId) checkIntents(intent) } override fun onActivityResult(requestCode: Int, resultCode: Int, resultData: Intent?) { super.onActivityResult(requestCode, resultCode, resultData) if (requestCode == PICK_OPEN_FILE_INTENT && resultCode == RESULT_OK && resultData != null && resultData.data != null) { importUri(resultData.data!!) } else if (requestCode == PICK_EXPORT_FILE_INTENT && resultCode == Activity.RESULT_OK && resultData != null && resultData.data != null && mNotes.isNotEmpty()) { val takeFlags = Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION applicationContext.contentResolver.takePersistableUriPermission(resultData.data!!, takeFlags) showExportFilePickUpdateDialog(resultData.dataString!!, getCurrentNoteValue()) } else if (requestCode == PICK_EXPORT_NOTES_INTENT && resultCode == Activity.RESULT_OK && resultData != null && resultData.data != null) { val outputStream = contentResolver.openOutputStream(resultData.data!!) exportNotesTo(outputStream) } else if (requestCode == PICK_IMPORT_NOTES_INTENT && resultCode == Activity.RESULT_OK && resultData != null && resultData.data != null) { importNotesFrom(resultData.data!!) } } private fun isCurrentItemChecklist() = if (::mCurrentNote.isInitialized) mCurrentNote.type == NoteType.TYPE_CHECKLIST.value else false @SuppressLint("NewApi") private fun checkShortcuts() { val appIconColor = config.appIconColor if (isNougatMR1Plus() && config.lastHandledShortcutColor != appIconColor) { val newTextNote = getNewTextNoteShortcut(appIconColor) val newChecklist = getNewChecklistShortcut(appIconColor) try { shortcutManager.dynamicShortcuts = Arrays.asList(newTextNote, newChecklist) config.lastHandledShortcutColor = appIconColor } catch (ignored: Exception) { } } } @SuppressLint("NewApi") private fun getNewTextNoteShortcut(appIconColor: Int): ShortcutInfo { val shortLabel = getString(R.string.text_note) val longLabel = getString(R.string.new_text_note) val drawable = resources.getDrawable(R.drawable.shortcut_plus) (drawable as LayerDrawable).findDrawableByLayerId(R.id.shortcut_plus_background).applyColorFilter(appIconColor) val bmp = drawable.convertToBitmap() val intent = Intent(this, MainActivity::class.java) intent.action = Intent.ACTION_VIEW intent.putExtra(NEW_TEXT_NOTE, true) return ShortcutInfo.Builder(this, SHORTCUT_NEW_TEXT_NOTE) .setShortLabel(shortLabel) .setLongLabel(longLabel) .setIcon(Icon.createWithBitmap(bmp)) .setIntent(intent) .build() } @SuppressLint("NewApi") private fun getNewChecklistShortcut(appIconColor: Int): ShortcutInfo { val shortLabel = getString(R.string.checklist) val longLabel = getString(R.string.new_checklist) val drawable = resources.getDrawable(R.drawable.shortcut_check) (drawable as LayerDrawable).findDrawableByLayerId(R.id.shortcut_plus_background).applyColorFilter(appIconColor) val bmp = drawable.convertToBitmap() val intent = Intent(this, MainActivity::class.java) intent.action = Intent.ACTION_VIEW intent.putExtra(NEW_CHECKLIST, true) return ShortcutInfo.Builder(this, SHORTCUT_NEW_CHECKLIST) .setShortLabel(shortLabel) .setLongLabel(longLabel) .setIcon(Icon.createWithBitmap(bmp)) .setIntent(intent) .build() } private fun checkIntents(intent: Intent) { intent.apply { if (action == Intent.ACTION_SEND && type == MIME_TEXT_PLAIN) { getStringExtra(Intent.EXTRA_TEXT)?.let { handleTextIntent(it) intent.removeExtra(Intent.EXTRA_TEXT) } } if (action == Intent.ACTION_VIEW) { val realPath = intent.getStringExtra(REAL_FILE_PATH) val isFromHistory = intent.flags and Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY != 0 if (!isFromHistory) { if (realPath != null && hasPermission(PERMISSION_READ_STORAGE)) { val file = File(realPath) handleUri(Uri.fromFile(file)) } else if (intent.getBooleanExtra(NEW_TEXT_NOTE, false)) { val newTextNote = Note(null, getCurrentFormattedDateTime(), "", NoteType.TYPE_TEXT.value, "", PROTECTION_NONE, "") addNewNote(newTextNote) } else if (intent.getBooleanExtra(NEW_CHECKLIST, false)) { val newChecklist = Note(null, getCurrentFormattedDateTime(), "", NoteType.TYPE_CHECKLIST.value, "", PROTECTION_NONE, "") addNewNote(newChecklist) } else { handleUri(data!!) } } intent.removeCategory(Intent.CATEGORY_DEFAULT) intent.action = null intent.removeExtra(NEW_CHECKLIST) intent.removeExtra(NEW_TEXT_NOTE) } } } private fun storeStateVariables() { config.apply { storedEnableLineWrap = enableLineWrap } } private fun handleTextIntent(text: String) { NotesHelper(this).getNotes { val notes = it val list = arrayListOf<RadioItem>().apply { add(RadioItem(0, getString(R.string.create_new_note))) notes.forEachIndexed { index, note -> add(RadioItem(index + 1, note.title)) } } RadioGroupDialog(this, list, -1, R.string.add_to_note) { if (it as Int == 0) { displayNewNoteDialog(text) } else { updateSelectedNote(notes[it - 1].id!!) addTextToCurrentNote(if (mCurrentNote.value.isEmpty()) text else "\n$text") } } } } private fun handleUri(uri: Uri) { NotesHelper(this).getNoteIdWithPath(uri.path!!) { if (it != null && it > 0L) { updateSelectedNote(it) return@getNoteIdWithPath } NotesHelper(this).getNotes { mNotes = it importUri(uri) } } } private fun initViewPager(wantedNoteId: Long? = null) { NotesHelper(this).getNotes { notes -> notes.filter { it.shouldBeUnlocked(this) } .forEach(::removeProtection) mNotes = notes mCurrentNote = mNotes[0] mAdapter = NotesPagerAdapter(supportFragmentManager, mNotes, this) view_pager.apply { adapter = mAdapter currentItem = getWantedNoteIndex(wantedNoteId) config.currentNoteId = mCurrentNote.id!! onPageChangeListener { mCurrentNote = mNotes[it] config.currentNoteId = mCurrentNote.id!! refreshMenuItems() } } if (!config.showKeyboard || mCurrentNote.type == NoteType.TYPE_CHECKLIST.value) { hideKeyboard() } refreshMenuItems() } } private fun setupSearchButtons() { searchQueryET.onTextChangeListener { searchTextChanged(it) } searchPrevBtn.setOnClickListener { goToPrevSearchResult() } searchNextBtn.setOnClickListener { goToNextSearchResult() } searchClearBtn.setOnClickListener { closeSearch() } view_pager.onPageChangeListener { currentTextFragment?.removeTextWatcher() currentNotesView()?.let { noteView -> noteView.text!!.clearBackgroundSpans() } closeSearch() currentTextFragment?.setTextWatcher() } searchQueryET.setOnEditorActionListener(TextView.OnEditorActionListener { _, actionId, _ -> if (actionId == EditorInfo.IME_ACTION_SEARCH) { searchNextBtn.performClick() return@OnEditorActionListener true } false }) } private fun searchTextChanged(text: String) { currentNotesView()?.let { noteView -> currentTextFragment?.removeTextWatcher() noteView.text!!.clearBackgroundSpans() if (text.isNotBlank() && text.length > 1) { searchMatches = noteView.value.searchMatches(text) noteView.highlightText(text, getProperPrimaryColor()) } currentTextFragment?.setTextWatcher() if (searchMatches.isNotEmpty()) { noteView.requestFocus() noteView.setSelection(searchMatches.getOrNull(searchIndex) ?: 0) } searchQueryET.postDelayed({ searchQueryET.requestFocus() }, 50) } } private fun goToPrevSearchResult() { currentNotesView()?.let { noteView -> if (searchIndex > 0) { searchIndex-- } else { searchIndex = searchMatches.lastIndex } selectSearchMatch(noteView) } } private fun goToNextSearchResult() { currentNotesView()?.let { noteView -> if (searchIndex < searchMatches.lastIndex) { searchIndex++ } else { searchIndex = 0 } selectSearchMatch(noteView) } } private fun getCurrentFragment() = mAdapter?.getFragment(view_pager.currentItem) private val currentTextFragment: TextFragment? get() = mAdapter?.textFragment(view_pager.currentItem) private fun selectSearchMatch(editText: MyEditText) { if (searchMatches.isNotEmpty()) { editText.requestFocus() editText.setSelection(searchMatches.getOrNull(searchIndex) ?: 0) } else { hideKeyboard() } } private fun openSearch() { isSearchActive = true search_wrapper.beVisible() showKeyboard(searchQueryET) currentNotesView()?.let { noteView -> noteView.requestFocus() noteView.setSelection(0) } searchQueryET.postDelayed({ searchQueryET.requestFocus() }, 250) } private fun closeSearch() { searchQueryET.text?.clear() isSearchActive = false search_wrapper.beGone() } private fun getWantedNoteIndex(wantedNoteId: Long?): Int { intent.removeExtra(OPEN_NOTE_ID) val noteIdToOpen = if (wantedNoteId == null || wantedNoteId == -1L) config.currentNoteId else wantedNoteId return getNoteIndexWithId(noteIdToOpen) } private fun currentNotesView() = if (view_pager == null) { null } else { mAdapter?.getCurrentNotesView(view_pager.currentItem) } private fun displayRenameDialog() { RenameNoteDialog(this, mCurrentNote, getCurrentNoteText()) { mCurrentNote = it initViewPager(mCurrentNote.id) } } private fun updateSelectedNote(id: Long) { config.currentNoteId = id if (mNotes.isEmpty()) { NotesHelper(this).getNotes { mNotes = it updateSelectedNote(id) } } else { val index = getNoteIndexWithId(id) view_pager.currentItem = index mCurrentNote = mNotes[index] } } private fun displayNewNoteDialog(value: String = "", title: String? = null, path: String = "", setChecklistAsDefault: Boolean = false) { NewNoteDialog(this, title, setChecklistAsDefault) { it.value = value it.path = path addNewNote(it) } } private fun addNewNote(note: Note) { NotesHelper(this).insertOrUpdateNote(note) { val newNoteId = it showSaveButton = false showUndoButton = false showRedoButton = false initViewPager(newNoteId) updateSelectedNote(newNoteId) view_pager.onGlobalLayout { mAdapter?.focusEditText(getNoteIndexWithId(newNoteId)) } } } private fun launchSettings() { hideKeyboard() startActivity(Intent(applicationContext, SettingsActivity::class.java)) } private fun launchAbout() { val licenses = LICENSE_RTL val faqItems = arrayListOf( FAQItem(R.string.faq_1_title_commons, R.string.faq_1_text_commons), FAQItem(R.string.faq_1_title, R.string.faq_1_text) ) if (!resources.getBoolean(R.bool.hide_google_relations)) { faqItems.add(FAQItem(R.string.faq_2_title_commons, R.string.faq_2_text_commons)) faqItems.add(FAQItem(R.string.faq_6_title_commons, R.string.faq_6_text_commons)) faqItems.add(FAQItem(R.string.faq_7_title_commons, R.string.faq_7_text_commons)) faqItems.add(FAQItem(R.string.faq_10_title_commons, R.string.faq_10_text_commons)) } startAboutActivity(R.string.app_name, licenses, BuildConfig.VERSION_NAME, faqItems, true) } private fun tryOpenFile() { hideKeyboard() if (hasPermission(PERMISSION_READ_STORAGE)) { openFile() } else { Intent(Intent.ACTION_OPEN_DOCUMENT).apply { addCategory(Intent.CATEGORY_OPENABLE) type = "text/*" try { startActivityForResult(this, PICK_OPEN_FILE_INTENT) } catch (e: ActivityNotFoundException) { toast(R.string.system_service_disabled, Toast.LENGTH_LONG) } catch (e: Exception) { showErrorToast(e) } } } } private fun openFile() { FilePickerDialog(this, canAddShowHiddenButton = true) { checkFile(it, true) { ensureBackgroundThread { val fileText = it.readText().trim() val checklistItems = fileText.parseChecklistItems() if (checklistItems != null) { val title = it.absolutePath.getFilenameFromPath().substringBeforeLast('.') val note = Note(null, title, fileText, NoteType.TYPE_CHECKLIST.value, "", PROTECTION_NONE, "") runOnUiThread { OpenFileDialog(this, it.path) { displayNewNoteDialog(note.value, title = it.title, it.path, setChecklistAsDefault = true) } } } else { runOnUiThread { OpenFileDialog(this, it.path) { displayNewNoteDialog(it.value, title = it.title, it.path) } } } } } } } private fun checkFile(path: String, checkTitle: Boolean, onChecksPassed: (file: File) -> Unit) { val file = File(path) if (path.isMediaFile()) { toast(R.string.invalid_file_format) } else if (file.length() > 1000 * 1000) { toast(R.string.file_too_large) } else if (checkTitle && mNotes.any { it.title.equals(path.getFilenameFromPath(), true) }) { toast(R.string.title_taken) } else { onChecksPassed(file) } } private fun checkUri(uri: Uri, onChecksPassed: () -> Unit) { val inputStream = try { contentResolver.openInputStream(uri) ?: return } catch (e: Exception) { showErrorToast(e) return } if (inputStream.available() > 1000 * 1000) { toast(R.string.file_too_large) } else { onChecksPassed() } } private fun openFolder(path: String, onChecksPassed: (file: File) -> Unit) { val file = File(path) if (file.isDirectory) { onChecksPassed(file) } } private fun importUri(uri: Uri) { when (uri.scheme) { "file" -> openPath(uri.path!!) "content" -> { val realPath = getRealPathFromURI(uri) if (hasPermission(PERMISSION_READ_STORAGE)) { if (realPath != null) { openPath(realPath) } else { R.string.unknown_error_occurred } } else if (realPath != null && realPath != "") { checkFile(realPath, false) { addNoteFromUri(uri, realPath.getFilenameFromPath()) } } else { checkUri(uri) { addNoteFromUri(uri) } } } } } private fun addNoteFromUri(uri: Uri, filename: String? = null) { val noteTitle = when { filename?.isEmpty() == false -> filename uri.toString().startsWith("content://") -> getFilenameFromContentUri(uri) ?: getNewNoteTitle() else -> getNewNoteTitle() } val inputStream = contentResolver.openInputStream(uri) val content = inputStream?.bufferedReader().use { it!!.readText() } val checklistItems = content.parseChecklistItems() // if we got here by some other app invoking the file open intent, we have no permission for updating the original file itself // we can do it only after using "Export as file" or "Open file" from our app val canSyncNoteWithFile = if (hasPermission(PERMISSION_WRITE_STORAGE)) { true } else { try { val takeFlags = Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION applicationContext.contentResolver.takePersistableUriPermission(uri, takeFlags) true } catch (e: Exception) { false } } val noteType = if (checklistItems != null) NoteType.TYPE_CHECKLIST.value else NoteType.TYPE_TEXT.value if (!canSyncNoteWithFile) { val note = Note(null, noteTitle, content, noteType, "", PROTECTION_NONE, "") displayNewNoteDialog(note.value, title = noteTitle, "") } else { val items = arrayListOf( RadioItem(IMPORT_FILE_SYNC, getString(R.string.update_file_at_note)), RadioItem(IMPORT_FILE_NO_SYNC, getString(R.string.only_import_file_content)) ) RadioGroupDialog(this, items) { val syncFile = it as Int == IMPORT_FILE_SYNC val path = if (syncFile) uri.toString() else "" val note = Note(null, noteTitle, content, noteType, "", PROTECTION_NONE, "") displayNewNoteDialog(note.value, title = noteTitle, path) } } } private fun openPath(path: String) { checkFile(path, false) { val title = path.getFilenameFromPath() try { val fileText = it.readText().trim() val checklistItems = fileText.parseChecklistItems() val note = if (checklistItems != null) { Note(null, title.substringBeforeLast('.'), fileText, NoteType.TYPE_CHECKLIST.value, "", PROTECTION_NONE, "") } else { Note(null, title, "", NoteType.TYPE_TEXT.value, path, PROTECTION_NONE, "") } if (mNotes.any { it.title.equals(note.title, true) }) { note.title += " (file)" } addNewNote(note) } catch (e: Exception) { showErrorToast(e) } } } private fun openFolder() { handlePermission(PERMISSION_READ_STORAGE) { hasPermission -> if (hasPermission) { FilePickerDialog(this, pickFile = false, canAddShowHiddenButton = true) { openFolder(it) { ImportFolderDialog(this, it.path) { NotesHelper(this).getNotes { mNotes = it showSaveButton = false initViewPager() } } } } } else { toast(R.string.no_storage_permissions) } } } private fun getNewNoteTitle(): String { val base = getString(R.string.text_note) var i = 1 while (true) { val tryTitle = "$base $i" if (mNotes.none { it.title == tryTitle }) { return tryTitle } i++ } } private fun tryExportAsFile() { hideKeyboard() if (hasPermission(PERMISSION_WRITE_STORAGE)) { exportAsFile() } else { Intent(Intent.ACTION_CREATE_DOCUMENT).apply { type = "text/*" putExtra(Intent.EXTRA_TITLE, "${mCurrentNote.title.removeSuffix(".txt")}.txt") addCategory(Intent.CATEGORY_OPENABLE) try { startActivityForResult(this, PICK_EXPORT_FILE_INTENT) } catch (e: ActivityNotFoundException) { toast(R.string.system_service_disabled, Toast.LENGTH_LONG) } catch (e: Exception) { showErrorToast(e) } } } } private fun exportAsFile() { ExportFileDialog(this, mCurrentNote) { val textToExport = if (mCurrentNote.type == NoteType.TYPE_TEXT.value) getCurrentNoteText() else mCurrentNote.value if (textToExport == null || textToExport.isEmpty()) { toast(R.string.unknown_error_occurred) } else if (mCurrentNote.type == NoteType.TYPE_TEXT.value) { showExportFilePickUpdateDialog(it, textToExport) } else { tryExportNoteValueToFile(it, mCurrentNote.title, textToExport, true) } } } private fun tryExportNotes() { hideKeyboard() val fileName = "${getString(R.string.notes)}_${getCurrentFormattedDateTime()}" Intent(Intent.ACTION_CREATE_DOCUMENT).apply { type = EXPORT_MIME_TYPE putExtra(Intent.EXTRA_TITLE, fileName) addCategory(Intent.CATEGORY_OPENABLE) try { startActivityForResult(this, PICK_EXPORT_NOTES_INTENT) } catch (e: ActivityNotFoundException) { toast(R.string.system_service_disabled, Toast.LENGTH_LONG) } catch (e: Exception) { showErrorToast(e) } } } private fun exportNotesTo(outputStream: OutputStream?) { toast(R.string.exporting) ensureBackgroundThread { val notesExporter = NotesExporter(this) notesExporter.exportNotes(outputStream) { val toastId = when (it) { NotesExporter.ExportResult.EXPORT_OK -> R.string.exporting_successful else -> R.string.exporting_failed } toast(toastId) } } } private fun tryImportNotes() { hideKeyboard() Intent(Intent.ACTION_GET_CONTENT).apply { addCategory(Intent.CATEGORY_OPENABLE) type = EXPORT_MIME_TYPE try { startActivityForResult(this, PICK_IMPORT_NOTES_INTENT) } catch (e: ActivityNotFoundException) { toast(R.string.system_service_disabled, Toast.LENGTH_LONG) } catch (e: Exception) { showErrorToast(e) } } } private fun importNotes(path: String, filename: String) { toast(R.string.importing) ensureBackgroundThread { NotesImporter(this).importNotes(path, filename) { toast( when (it) { NotesImporter.ImportResult.IMPORT_OK -> R.string.importing_successful NotesImporter.ImportResult.IMPORT_PARTIAL -> R.string.importing_some_entries_failed else -> R.string.no_items_found } ) initViewPager() } } } private fun importNotesFrom(uri: Uri) { when (uri.scheme) { "file" -> importNotes(uri.path!!, uri.path!!.getFilenameFromPath()) "content" -> { val tempFile = getTempFile("messages", "backup.txt") if (tempFile == null) { toast(R.string.unknown_error_occurred) return } try { val filename = getFilenameFromUri(uri) val inputStream = contentResolver.openInputStream(uri) val out = FileOutputStream(tempFile) inputStream!!.copyTo(out) importNotes(tempFile.absolutePath, filename) } catch (e: Exception) { showErrorToast(e) } } else -> toast(R.string.invalid_file_format) } } private fun showExportFilePickUpdateDialog(exportPath: String, textToExport: String) { val items = arrayListOf( RadioItem(EXPORT_FILE_SYNC, getString(R.string.update_file_at_note)), RadioItem(EXPORT_FILE_NO_SYNC, getString(R.string.only_export_file_content)) ) RadioGroupDialog(this, items) { val syncFile = it as Int == EXPORT_FILE_SYNC tryExportNoteValueToFile(exportPath, mCurrentNote.title, textToExport, true) { exportedSuccessfully -> if (exportedSuccessfully) { if (syncFile) { mCurrentNote.path = exportPath mCurrentNote.value = "" } else { mCurrentNote.path = "" mCurrentNote.value = textToExport } getPagerAdapter().updateCurrentNoteData(view_pager.currentItem, mCurrentNote.path, mCurrentNote.value) NotesHelper(this).insertOrUpdateNote(mCurrentNote) } } } } private fun tryExportAllNotes() { handlePermission(PERMISSION_WRITE_STORAGE) { if (it) { exportAllNotes() } else { toast(R.string.no_storage_permissions) } } } private fun exportAllNotes() { ExportFilesDialog(this, mNotes) { parent, extension -> val items = arrayListOf( RadioItem(EXPORT_FILE_SYNC, getString(R.string.update_file_at_note)), RadioItem(EXPORT_FILE_NO_SYNC, getString(R.string.only_export_file_content)) ) RadioGroupDialog(this, items) { val syncFile = it as Int == EXPORT_FILE_SYNC var failCount = 0 NotesHelper(this).getNotes { mNotes = it mNotes.filter { !it.isLocked() }.forEachIndexed { index, note -> val filename = if (extension.isEmpty()) note.title else "${note.title}.$extension" val file = File(parent, filename) if (!filename.isAValidFilename()) { toast(String.format(getString(R.string.filename_invalid_characters_placeholder, filename))) } else { val noteStoredValue = note.getNoteStoredValue(this) ?: "" tryExportNoteValueToFile(file.absolutePath, mCurrentNote.title, note.value, false) { exportedSuccessfully -> if (exportedSuccessfully) { if (syncFile) { note.path = file.absolutePath note.value = "" } else { note.path = "" note.value = noteStoredValue } NotesHelper(this).insertOrUpdateNote(note) } if (mCurrentNote.id == note.id) { mCurrentNote.value = note.value mCurrentNote.path = note.path getPagerAdapter().updateCurrentNoteData(view_pager.currentItem, mCurrentNote.path, mCurrentNote.value) } if (!exportedSuccessfully) { failCount++ } if (index == mNotes.size - 1) { toast(if (failCount == 0) R.string.exporting_successful else R.string.exporting_some_entries_failed) } } } } } } } } fun tryExportNoteValueToFile(path: String, title: String, content: String, showSuccessToasts: Boolean, callback: ((success: Boolean) -> Unit)? = null) { if (path.startsWith("content://")) { exportNoteValueToUri(Uri.parse(path), title, content, showSuccessToasts, callback) } else { handlePermission(PERMISSION_WRITE_STORAGE) { if (it) { exportNoteValueToFile(path, content, showSuccessToasts, callback) } } } } private fun exportNoteValueToFile(path: String, content: String, showSuccessToasts: Boolean, callback: ((success: Boolean) -> Unit)? = null) { try { if (File(path).isDirectory) { toast(R.string.name_taken) return } if (needsStupidWritePermissions(path)) { handleSAFDialog(path) { val document = if (File(path).exists()) { getDocumentFile(path) ?: return@handleSAFDialog } else { val parent = getDocumentFile(File(path).parent) ?: return@handleSAFDialog parent.createFile("", path.getFilenameFromPath())!! } contentResolver.openOutputStream(document.uri)!!.apply { val byteArray = content.toByteArray(Charset.forName("UTF-8")) write(byteArray, 0, byteArray.size) flush() close() } if (showSuccessToasts) { noteExportedSuccessfully(path.getFilenameFromPath()) } callback?.invoke(true) } } else { val file = File(path) file.writeText(content) if (showSuccessToasts) { noteExportedSuccessfully(path.getFilenameFromPath()) } callback?.invoke(true) } } catch (e: Exception) { showErrorToast(e) callback?.invoke(false) } } private fun exportNoteValueToUri(uri: Uri, title: String, content: String, showSuccessToasts: Boolean, callback: ((success: Boolean) -> Unit)? = null) { try { val outputStream = contentResolver.openOutputStream(uri, "rwt") outputStream!!.bufferedWriter().use { out -> out.write(content) } if (showSuccessToasts) { noteExportedSuccessfully(title) } callback?.invoke(true) } catch (e: Exception) { showErrorToast(e) callback?.invoke(false) } } private fun noteExportedSuccessfully(title: String) { val message = String.format(getString(R.string.note_exported_successfully), title) toast(message) } fun noteSavedSuccessfully(title: String) { if (config.displaySuccess) { val message = String.format(getString(R.string.note_saved_successfully), title) toast(message) } } private fun printText() { try { val webView = WebView(this) webView.webViewClient = object : WebViewClient() { override fun shouldOverrideUrlLoading(view: WebView, request: WebResourceRequest) = false override fun onPageFinished(view: WebView, url: String) { createWebPrintJob(view) } } webView.loadData(getPrintableText().replace("#", "%23"), "text/plain", "UTF-8") } catch (e: Exception) { showErrorToast(e) } } private fun createWebPrintJob(webView: WebView) { val jobName = mCurrentNote.title val printAdapter = webView.createPrintDocumentAdapter(jobName) (getSystemService(Context.PRINT_SERVICE) as? PrintManager)?.apply { print(jobName, printAdapter, PrintAttributes.Builder().build()) } } private fun getPagerAdapter() = view_pager.adapter as NotesPagerAdapter private fun getCurrentNoteText() = getPagerAdapter().getCurrentNoteViewText(view_pager.currentItem) private fun getCurrentNoteValue(): String { return if (mCurrentNote.type == NoteType.TYPE_TEXT.value) { getCurrentNoteText() ?: "" } else { getPagerAdapter().getNoteChecklistItems(view_pager.currentItem) ?: "" } } private fun getPrintableText(): String { return if (mCurrentNote.type == NoteType.TYPE_TEXT.value) { getCurrentNoteText() ?: "" } else { var printableText = "" getPagerAdapter().getNoteChecklistRawItems(view_pager.currentItem)?.forEach { printableText += "${it.title}\n\n" } printableText } } private fun addTextToCurrentNote(text: String) = getPagerAdapter().appendText(view_pager.currentItem, text) private fun saveCurrentNote(force: Boolean) { getPagerAdapter().saveCurrentNote(view_pager.currentItem, force) if (mCurrentNote.type == NoteType.TYPE_CHECKLIST.value) { mCurrentNote.value = getPagerAdapter().getNoteChecklistItems(view_pager.currentItem) ?: "" } } private fun displayDeleteNotePrompt() { DeleteNoteDialog(this, mCurrentNote) { deleteNote(it, mCurrentNote) } } fun deleteNote(deleteFile: Boolean, note: Note) { if (mNotes.size <= 1 || note != mCurrentNote) { return } if (!deleteFile) { doDeleteNote(mCurrentNote, deleteFile) } else { handleSAFDialog(mCurrentNote.path) { doDeleteNote(mCurrentNote, deleteFile) } } } private fun doDeleteNote(note: Note, deleteFile: Boolean) { ensureBackgroundThread { notesDB.deleteNote(note) widgetsDB.deleteNoteWidgets(note.id!!) refreshNotes(note, deleteFile) } } private fun refreshNotes(note: Note, deleteFile: Boolean) { NotesHelper(this).getNotes { mNotes = it val firstNoteId = mNotes[0].id updateSelectedNote(firstNoteId!!) if (config.widgetNoteId == note.id) { config.widgetNoteId = mCurrentNote.id!! updateWidgets() } initViewPager() if (deleteFile) { deleteFile(FileDirItem(note.path, note.title)) { if (!it) { toast(R.string.unknown_error_occurred) } } } if (it.size == 1 && config.showNotePicker) { config.showNotePicker = false } } } private fun displayOpenNoteDialog() { OpenNoteDialog(this) { noteId, newNote -> if (newNote == null) { updateSelectedNote(noteId) } else { addNewNote(newNote) } } } private fun saveNote() { saveCurrentNote(true) showSaveButton = false refreshMenuItems() } private fun undo() { mAdapter?.undo(view_pager.currentItem) } private fun redo() { mAdapter?.redo(view_pager.currentItem) } private fun getNoteIndexWithId(id: Long): Int { for (i in 0 until mNotes.count()) { if (mNotes[i].id == id) { mCurrentNote = mNotes[i] return i } } return 0 } private fun shareText() { val text = if (mCurrentNote.type == NoteType.TYPE_TEXT.value) getCurrentNoteText() else mCurrentNote.value if (text == null || text.isEmpty()) { toast(R.string.cannot_share_empty_text) return } val res = resources val shareTitle = res.getString(R.string.share_via) Intent().apply { action = Intent.ACTION_SEND putExtra(Intent.EXTRA_SUBJECT, mCurrentNote.title) putExtra(Intent.EXTRA_TEXT, text) type = "text/plain" startActivity(Intent.createChooser(this, shareTitle)) } } private fun lockNote() { ConfirmationDialog(this, "", R.string.locking_warning, R.string.ok, R.string.cancel) { SecurityDialog(this, "", SHOW_ALL_TABS) { hash, type, success -> if (success) { mCurrentNote.protectionHash = hash mCurrentNote.protectionType = type NotesHelper(this).insertOrUpdateNote(mCurrentNote) { refreshMenuItems() } } } } } private fun unlockNote() { performSecurityCheck( protectionType = mCurrentNote.protectionType, requiredHash = mCurrentNote.protectionHash, successCallback = { _, _ -> removeProtection(mCurrentNote) } ) } private fun removeProtection(note: Note) { note.protectionHash = "" note.protectionType = PROTECTION_NONE NotesHelper(this).insertOrUpdateNote(note) { if (note == mCurrentNote) { getCurrentFragment()?.apply { shouldShowLockedContent = true checkLockState() } refreshMenuItems() } } } fun currentNoteTextChanged(newText: String, showUndo: Boolean, showRedo: Boolean) { if (!isSearchActive) { var shouldRecreateMenu = false if (showUndo != showUndoButton) { showUndoButton = showUndo shouldRecreateMenu = true } if (showRedo != showRedoButton) { showRedoButton = showRedo shouldRecreateMenu = true } if (!config.autosaveNotes) { showSaveButton = newText != mCurrentNote.value if (showSaveButton != saveNoteButton?.isVisible) { shouldRecreateMenu = true } } if (shouldRecreateMenu) { refreshMenuItems() } } } private fun checkWhatsNewDialog() { arrayListOf<Release>().apply { add(Release(25, R.string.release_25)) add(Release(28, R.string.release_28)) add(Release(29, R.string.release_29)) add(Release(39, R.string.release_39)) add(Release(45, R.string.release_45)) add(Release(49, R.string.release_49)) add(Release(51, R.string.release_51)) add(Release(57, R.string.release_57)) add(Release(62, R.string.release_62)) add(Release(64, R.string.release_64)) add(Release(67, R.string.release_67)) add(Release(81, R.string.release_81)) add(Release(86, R.string.release_86)) checkWhatsNew(this, BuildConfig.VERSION_CODE) } } private fun removeDoneItems() { getPagerAdapter().removeDoneCheckListItems(view_pager.currentItem) } private fun displaySortChecklistDialog() { SortChecklistDialog(this) { getPagerAdapter().refreshChecklist(view_pager.currentItem) } } }
gpl-3.0
ad2df9d0012e8f3d09ec2e8d9930849f
36.561378
168
0.565201
4.908349
false
false
false
false
TeamNewPipe/NewPipe
app/src/main/java/org/schabi/newpipe/error/ErrorUtil.kt
1
7273
package org.schabi.newpipe.error import android.app.Activity import android.app.PendingIntent import android.content.Context import android.content.Intent import android.graphics.Color import android.view.View import android.widget.Toast import androidx.core.app.NotificationCompat import androidx.core.app.NotificationManagerCompat import androidx.fragment.app.Fragment import com.google.android.material.snackbar.Snackbar import org.schabi.newpipe.R import org.schabi.newpipe.util.PendingIntentCompat /** * This class contains all of the methods that should be used to let the user know that an error has * occurred in the least intrusive way possible for each case. This class is for unexpected errors, * for handled errors (e.g. network errors) use e.g. [ErrorPanelHelper] instead. * - Use a snackbar if the exception is not critical and it happens in a place where a root view * is available. * - Use a notification if the exception happens inside a background service (player, subscription * import, ...) or there is no activity/fragment from which to extract a root view. * - Finally use the error activity only as a last resort in case the exception is critical and * happens in an open activity (since the workflow would be interrupted anyway in that case). */ class ErrorUtil { companion object { private const val ERROR_REPORT_NOTIFICATION_ID = 5340681 /** * Starts a new error activity allowing the user to report the provided error. Only use this * method directly as a last resort in case the exception is critical and happens in an open * activity (since the workflow would be interrupted anyway in that case). So never use this * for background services. * * @param context the context to use to start the new activity * @param errorInfo the error info to be reported */ @JvmStatic fun openActivity(context: Context, errorInfo: ErrorInfo) { context.startActivity(getErrorActivityIntent(context, errorInfo)) } /** * Show a bottom snackbar to the user, with a report button that opens the error activity. * Use this method if the exception is not critical and it happens in a place where a root * view is available. * * @param context will be used to obtain the root view if it is an [Activity]; if no root * view can be found an error notification is shown instead * @param errorInfo the error info to be reported */ @JvmStatic fun showSnackbar(context: Context, errorInfo: ErrorInfo) { val rootView = if (context is Activity) context.findViewById<View>(R.id.content) else null showSnackbar(context, rootView, errorInfo) } /** * Show a bottom snackbar to the user, with a report button that opens the error activity. * Use this method if the exception is not critical and it happens in a place where a root * view is available. * * @param fragment will be used to obtain the root view if it has a connected [Activity]; if * no root view can be found an error notification is shown instead * @param errorInfo the error info to be reported */ @JvmStatic fun showSnackbar(fragment: Fragment, errorInfo: ErrorInfo) { var rootView = fragment.view if (rootView == null && fragment.activity != null) { rootView = fragment.requireActivity().findViewById(R.id.content) } showSnackbar(fragment.requireContext(), rootView, errorInfo) } /** * Shortcut to calling [showSnackbar] with an [ErrorInfo] of type [UserAction.UI_ERROR] */ @JvmStatic fun showUiErrorSnackbar(context: Context, request: String, throwable: Throwable) { showSnackbar(context, ErrorInfo(throwable, UserAction.UI_ERROR, request)) } /** * Shortcut to calling [showSnackbar] with an [ErrorInfo] of type [UserAction.UI_ERROR] */ @JvmStatic fun showUiErrorSnackbar(fragment: Fragment, request: String, throwable: Throwable) { showSnackbar(fragment, ErrorInfo(throwable, UserAction.UI_ERROR, request)) } /** * Create an error notification. Tapping on the notification opens the error activity. Use * this method if the exception happens inside a background service (player, subscription * import, ...) or there is no activity/fragment from which to extract a root view. * * @param context the context to use to show the notification * @param errorInfo the error info to be reported; the error message * [ErrorInfo.messageStringId] will be shown in the notification * description */ @JvmStatic fun createNotification(context: Context, errorInfo: ErrorInfo) { val notificationBuilder: NotificationCompat.Builder = NotificationCompat.Builder( context, context.getString(R.string.error_report_channel_id) ) .setSmallIcon(R.drawable.ic_bug_report) .setContentTitle(context.getString(R.string.error_report_notification_title)) .setContentText(context.getString(errorInfo.messageStringId)) .setAutoCancel(true) .setContentIntent( PendingIntentCompat.getActivity( context, 0, getErrorActivityIntent(context, errorInfo), PendingIntent.FLAG_UPDATE_CURRENT ) ) NotificationManagerCompat.from(context) .notify(ERROR_REPORT_NOTIFICATION_ID, notificationBuilder.build()) // since the notification is silent, also show a toast, otherwise the user is confused Toast.makeText(context, R.string.error_report_notification_toast, Toast.LENGTH_SHORT) .show() } private fun getErrorActivityIntent(context: Context, errorInfo: ErrorInfo): Intent { val intent = Intent(context, ErrorActivity::class.java) intent.putExtra(ErrorActivity.ERROR_INFO, errorInfo) intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) return intent } private fun showSnackbar(context: Context, rootView: View?, errorInfo: ErrorInfo) { if (rootView == null) { // fallback to showing a notification if no root view is available createNotification(context, errorInfo) } else { Snackbar.make(rootView, R.string.error_snackbar_message, Snackbar.LENGTH_LONG) .setActionTextColor(Color.YELLOW) .setAction(context.getString(R.string.error_snackbar_action).uppercase()) { openActivity(context, errorInfo) }.show() } } } }
gpl-3.0
87bb9c8ee6b4423e18696f1b5beafaf6
46.535948
102
0.632064
5.172831
false
false
false
false
vovagrechka/fucking-everything
phizdets/phizdetsc/src/org/jetbrains/kotlin/js/translate/intrinsic/operation/StringPlusCharBOIF.kt
1
3447
/* * Copyright 2010-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.kotlin.js.translate.intrinsic.operation import com.google.common.collect.ImmutableSet import org.jetbrains.kotlin.builtins.KotlinBuiltIns import org.jetbrains.kotlin.descriptors.FunctionDescriptor import org.jetbrains.kotlin.js.backend.ast.JsBinaryOperation import org.jetbrains.kotlin.js.backend.ast.JsExpression import org.jetbrains.kotlin.js.translate.context.TranslationContext import org.jetbrains.kotlin.js.translate.intrinsic.functions.factories.TopLevelFIF import org.jetbrains.kotlin.js.translate.operation.OperatorTable import org.jetbrains.kotlin.js.translate.utils.JsAstUtils import org.jetbrains.kotlin.js.translate.utils.PsiUtils.getOperationToken import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.KtBinaryExpression import org.jetbrains.kotlin.types.KotlinType object StringPlusCharBOIF : BinaryOperationIntrinsicFactory { private object StringPlusCharIntrinsic : AbstractBinaryOperationIntrinsic() { override fun apply(expression: KtBinaryExpression, left: JsExpression, right: JsExpression, context: TranslationContext): JsExpression { val operator = OperatorTable.getBinaryOperator(getOperationToken(expression)) return JsBinaryOperation(operator, left, JsAstUtils.charToString(right)) } } private object StringPlusAnyIntrinsic : AbstractBinaryOperationIntrinsic() { override fun apply(expression: KtBinaryExpression, left: JsExpression, right: JsExpression, context: TranslationContext): JsExpression { val operator = OperatorTable.getBinaryOperator(getOperationToken(expression)) return JsBinaryOperation(operator, left, TopLevelFIF.TO_STRING.apply(right, listOf(), context)) } } private object StringPlusStringIntrinsic : AbstractBinaryOperationIntrinsic() { override fun apply(expression: KtBinaryExpression, left: JsExpression, right: JsExpression, context: TranslationContext): JsExpression { val operator = OperatorTable.getBinaryOperator(getOperationToken(expression)) return JsBinaryOperation(operator, left, right) } } override fun getSupportTokens() = ImmutableSet.of(KtTokens.PLUS) override fun getIntrinsic(descriptor: FunctionDescriptor, leftType: KotlinType?, rightType: KotlinType?): BinaryOperationIntrinsic? { if (KotlinBuiltIns.isString(leftType) && rightType != null) { if (KotlinBuiltIns.isCharOrNullableChar(rightType)) { return StringPlusCharIntrinsic } if (KotlinBuiltIns.isStringOrNullableString(rightType)) { return StringPlusStringIntrinsic } if (KotlinBuiltIns.isAnyOrNullableAny(rightType)) { return StringPlusAnyIntrinsic } } return null } }
apache-2.0
a22a4cc80e13db4ae219a94513c80da8
46.219178
144
0.752829
4.882436
false
false
false
false
GunoH/intellij-community
platform/workspaceModel/storage/gen/com/intellij/workspaceModel/storage/bridgeEntities/FileCopyPackagingElementEntityImpl.kt
2
11201
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.workspaceModel.storage.bridgeEntities 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.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.extractOneToAbstractManyParent import com.intellij.workspaceModel.storage.impl.updateOneToAbstractManyParentOfChild import com.intellij.workspaceModel.storage.url.VirtualFileUrl import org.jetbrains.deft.ObjBuilder import org.jetbrains.deft.Type import org.jetbrains.deft.annotations.Abstract import org.jetbrains.deft.annotations.Child @GeneratedCodeApiVersion(1) @GeneratedCodeImplVersion(1) open class FileCopyPackagingElementEntityImpl(val dataSource: FileCopyPackagingElementEntityData) : FileCopyPackagingElementEntity, WorkspaceEntityBase() { companion object { internal val PARENTENTITY_CONNECTION_ID: ConnectionId = ConnectionId.create(CompositePackagingElementEntity::class.java, PackagingElementEntity::class.java, ConnectionId.ConnectionType.ONE_TO_ABSTRACT_MANY, true) val connections = listOf<ConnectionId>( PARENTENTITY_CONNECTION_ID, ) } override val parentEntity: CompositePackagingElementEntity? get() = snapshot.extractOneToAbstractManyParent(PARENTENTITY_CONNECTION_ID, this) override val filePath: VirtualFileUrl get() = dataSource.filePath override val renamedOutputFileName: String? get() = dataSource.renamedOutputFileName override val entitySource: EntitySource get() = dataSource.entitySource override fun connectionIdList(): List<ConnectionId> { return connections } class Builder(result: FileCopyPackagingElementEntityData?) : ModifiableWorkspaceEntityBase<FileCopyPackagingElementEntity, FileCopyPackagingElementEntityData>( result), FileCopyPackagingElementEntity.Builder { constructor() : this(FileCopyPackagingElementEntityData()) override fun applyToBuilder(builder: MutableEntityStorage) { if (this.diff != null) { if (existsInBuilder(builder)) { this.diff = builder return } else { error("Entity FileCopyPackagingElementEntity is already created in a different builder") } } this.diff = builder this.snapshot = builder addToBuilder() this.id = getEntityData().createEntityId() // After adding entity data to the builder, we need to unbind it and move the control over entity data to builder // Builder may switch to snapshot at any moment and lock entity data to modification this.currentEntityData = null // Process linked entities that are connected without a builder processLinkedEntities(builder) checkInitialization() // TODO uncomment and check failed tests } fun checkInitialization() { val _diff = diff if (!getEntityData().isEntitySourceInitialized()) { error("Field WorkspaceEntity#entitySource should be initialized") } if (!getEntityData().isFilePathInitialized()) { error("Field FileOrDirectoryPackagingElementEntity#filePath 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 FileCopyPackagingElementEntity if (this.entitySource != dataSource.entitySource) this.entitySource = dataSource.entitySource if (this.filePath != dataSource.filePath) this.filePath = dataSource.filePath if (this.renamedOutputFileName != dataSource?.renamedOutputFileName) this.renamedOutputFileName = dataSource.renamedOutputFileName if (parents != null) { val parentEntityNew = parents.filterIsInstance<CompositePackagingElementEntity?>().singleOrNull() if ((parentEntityNew == null && this.parentEntity != null) || (parentEntityNew != null && this.parentEntity == null) || (parentEntityNew != null && this.parentEntity != null && (this.parentEntity as WorkspaceEntityBase).id != (parentEntityNew as WorkspaceEntityBase).id)) { this.parentEntity = parentEntityNew } } } override var entitySource: EntitySource get() = getEntityData().entitySource set(value) { checkModificationAllowed() getEntityData(true).entitySource = value changedProperty.add("entitySource") } override var parentEntity: CompositePackagingElementEntity? get() { val _diff = diff return if (_diff != null) { _diff.extractOneToAbstractManyParent(PARENTENTITY_CONNECTION_ID, this) ?: this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)] as? CompositePackagingElementEntity } else { this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)] as? CompositePackagingElementEntity } } 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.updateOneToAbstractManyParentOfChild(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") } override var filePath: VirtualFileUrl get() = getEntityData().filePath set(value) { checkModificationAllowed() getEntityData(true).filePath = value changedProperty.add("filePath") val _diff = diff if (_diff != null) index(this, "filePath", value) } override var renamedOutputFileName: String? get() = getEntityData().renamedOutputFileName set(value) { checkModificationAllowed() getEntityData(true).renamedOutputFileName = value changedProperty.add("renamedOutputFileName") } override fun getEntityClass(): Class<FileCopyPackagingElementEntity> = FileCopyPackagingElementEntity::class.java } } class FileCopyPackagingElementEntityData : WorkspaceEntityData<FileCopyPackagingElementEntity>() { lateinit var filePath: VirtualFileUrl var renamedOutputFileName: String? = null fun isFilePathInitialized(): Boolean = ::filePath.isInitialized override fun wrapAsModifiable(diff: MutableEntityStorage): WorkspaceEntity.Builder<FileCopyPackagingElementEntity> { val modifiable = FileCopyPackagingElementEntityImpl.Builder(null) modifiable.diff = diff modifiable.snapshot = diff modifiable.id = createEntityId() return modifiable } override fun createEntity(snapshot: EntityStorage): FileCopyPackagingElementEntity { return getCached(snapshot) { val entity = FileCopyPackagingElementEntityImpl(this) entity.snapshot = snapshot entity.id = createEntityId() entity } } override fun getEntityInterface(): Class<out WorkspaceEntity> { return FileCopyPackagingElementEntity::class.java } override fun serialize(ser: EntityInformation.Serializer) { } override fun deserialize(de: EntityInformation.Deserializer) { } override fun createDetachedEntity(parents: List<WorkspaceEntity>): WorkspaceEntity { return FileCopyPackagingElementEntity(filePath, entitySource) { this.renamedOutputFileName = [email protected] this.parentEntity = parents.filterIsInstance<CompositePackagingElementEntity>().singleOrNull() } } override fun getRequiredParents(): List<Class<out WorkspaceEntity>> { val res = mutableListOf<Class<out WorkspaceEntity>>() return res } override fun equals(other: Any?): Boolean { if (other == null) return false if (this.javaClass != other.javaClass) return false other as FileCopyPackagingElementEntityData if (this.entitySource != other.entitySource) return false if (this.filePath != other.filePath) return false if (this.renamedOutputFileName != other.renamedOutputFileName) return false return true } override fun equalsIgnoringEntitySource(other: Any?): Boolean { if (other == null) return false if (this.javaClass != other.javaClass) return false other as FileCopyPackagingElementEntityData if (this.filePath != other.filePath) return false if (this.renamedOutputFileName != other.renamedOutputFileName) return false return true } override fun hashCode(): Int { var result = entitySource.hashCode() result = 31 * result + filePath.hashCode() result = 31 * result + renamedOutputFileName.hashCode() return result } override fun hashCodeIgnoringEntitySource(): Int { var result = javaClass.hashCode() result = 31 * result + filePath.hashCode() result = 31 * result + renamedOutputFileName.hashCode() return result } override fun collectClassUsagesData(collector: UsedClassesCollector) { this.filePath?.let { collector.add(it::class.java) } collector.sameForAllEntities = false } }
apache-2.0
1968e88b507f43a1f01aef6bc26d69c7
40.485185
281
0.715561
5.648512
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/core/src/org/jetbrains/kotlin/idea/statistics/KotlinIDEGradleActionsFUSCollector.kt
2
2237
// 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.statistics import com.intellij.internal.statistic.eventLog.EventLogGroup import com.intellij.internal.statistic.eventLog.events.EventFields import com.intellij.internal.statistic.service.fus.collectors.CounterUsagesCollector import com.intellij.internal.statistic.utils.getPluginInfoById import com.intellij.openapi.project.Project import org.jetbrains.kotlin.idea.KotlinPluginUtil class KotlinIDEGradleActionsFUSCollector : CounterUsagesCollector() { override fun getGroup(): EventLogGroup = GROUP companion object { private val GROUP = EventLogGroup("kotlin.ide.gradle", 1) private val pluginInfo = getPluginInfoById(KotlinPluginUtil.KOTLIN_PLUGIN_ID) private val allowedTargets = listOf( "kotlin-android", "kotlin-platform-common", "kotlin-platform-js", "kotlin-platform-jvm", "MPP.androidJvm", "MPP.androidJvm.android", "MPP.common", "MPP.common.metadata", "MPP.js", "MPP.js.js", "MPP.jvm", "MPP.jvm.jvm", "MPP.jvm.jvmWithJava", "MPP.native", "MPP.native.androidNativeArm32", "MPP.native.androidNativeArm64", "MPP.native.iosArm32", "MPP.native.iosArm64", "MPP.native.iosX64", "MPP.native.linuxArm32Hfp", "MPP.native.linuxArm64", "MPP.native.linuxMips32", "MPP.native.linuxMipsel32", "MPP.native.linuxX64", "MPP.native.macosX64", "MPP.native.mingwX64", "MPP.native.mingwX86", "MPP.native.wasm32", "MPP.native.zephyrStm32f4Disco", "unknown" ) private val importEvent = GROUP.registerEvent( "Import", EventFields.String("target", allowedTargets), EventFields.PluginInfo ) fun logImport(project: Project?, target: String) = importEvent.log(project, target, pluginInfo) } }
apache-2.0
9a4b7a7e6db04a010676545a550e1aae
36.283333
158
0.627179
4.277247
false
false
false
false
smmribeiro/intellij-community
platform/service-container/src/com/intellij/serviceContainer/ConstructorParameterResolver.kt
3
5045
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.serviceContainer import com.intellij.diagnostic.PluginException import com.intellij.openapi.components.ComponentManager import com.intellij.openapi.extensions.PluginId import org.picocontainer.ComponentAdapter import java.lang.reflect.Constructor @Suppress("ReplaceJavaStaticMethodWithKotlinAnalog") private val badAppLevelClasses = java.util.Set.of( "com.intellij.execution.executors.DefaultDebugExecutor", "org.apache.http.client.HttpClient", "org.apache.http.impl.client.CloseableHttpClient", "com.intellij.openapi.project.Project" ) internal class ConstructorParameterResolver { fun isResolvable(componentManager: ComponentManagerImpl, requestorKey: Any, requestorClass: Class<*>, requestorConstructor: Constructor<*>, expectedType: Class<*>, pluginId: PluginId, isExtensionSupported: Boolean): Boolean { if (expectedType === ComponentManager::class.java || findTargetAdapter(componentManager, expectedType, requestorKey, requestorClass, requestorConstructor, pluginId) != null) { return true } return isExtensionSupported && componentManager.extensionArea.findExtensionByClass(expectedType) != null } fun resolveInstance(componentManager: ComponentManagerImpl, requestorKey: Any, requestorClass: Class<*>, requestorConstructor: Constructor<*>, expectedType: Class<*>, pluginId: PluginId): Any? { if (expectedType === ComponentManager::class.java) { return componentManager } if (isLightService(expectedType)) { throw PluginException( "Do not use constructor injection for light services (requestorClass=$requestorClass, requestedService=$expectedType)", pluginId ) } val adapter = findTargetAdapter(componentManager, expectedType, requestorKey, requestorClass, requestorConstructor, pluginId) ?: return handleUnsatisfiedDependency(componentManager, requestorClass, expectedType, pluginId) return when { adapter is BaseComponentAdapter -> { // project level service Foo wants application level service Bar - adapter component manager should be used instead of current adapter.getInstance(adapter.componentManager, null) } componentManager.parent == null -> adapter.getComponentInstance(componentManager) else -> componentManager.getComponentInstance(adapter.componentKey) } } private fun handleUnsatisfiedDependency(componentManager: ComponentManagerImpl, requestorClass: Class<*>, expectedType: Class<*>, pluginId: PluginId): Any? { val extension = componentManager.extensionArea.findExtensionByClass(expectedType) ?: return null val message = "Do not use constructor injection to get extension instance (requestorClass=${requestorClass.name}, extensionClass=${expectedType.name})" val app = componentManager.getApplication() @Suppress("SpellCheckingInspection") if (app != null && app.isUnitTestMode && pluginId.idString != "org.jetbrains.kotlin" && pluginId.idString != "Lombook Plugin") { throw PluginException(message, pluginId) } else { LOG.warn(message) } return extension } } private fun findTargetAdapter(componentManager: ComponentManagerImpl, expectedType: Class<*>, requestorKey: Any, requestorClass: Class<*>, requestorConstructor: Constructor<*>, @Suppress("UNUSED_PARAMETER") pluginId: PluginId): ComponentAdapter? { val byKey = componentManager.getComponentAdapter(expectedType) if (byKey != null && requestorKey != byKey.componentKey) { return byKey } val className = expectedType.name if (componentManager.parent == null) { if (badAppLevelClasses.contains(className)) { return null } } else if (className == "com.intellij.configurationStore.StreamProvider" || className == "com.intellij.openapi.roots.LanguageLevelModuleExtensionImpl" || className == "com.intellij.openapi.roots.impl.CompilerModuleExtensionImpl" || className == "com.intellij.openapi.roots.impl.JavaModuleExternalPathsImpl") { return null } if (componentManager.isGetComponentAdapterOfTypeCheckEnabled) { LOG.error(PluginException("getComponentAdapterOfType is used to get ${expectedType.name} (requestorClass=${requestorClass.name}, requestorConstructor=${requestorConstructor})." + "\n\nProbably constructor should be marked as NonInjectable.", pluginId)) } return componentManager.getComponentAdapterOfType(expectedType) ?: componentManager.parent?.getComponentAdapterOfType(expectedType) }
apache-2.0
125e66f6201a1baf11d561ed53b70c68
47.057143
182
0.70109
5.483696
false
false
false
false
LouisCAD/Splitties
modules/dimensions/src/androidMain/kotlin/splitties/dimensions/Dimensions.kt
1
1642
/* * Copyright 2019 Louis Cognault Ayeva Derman. Use of this source code is governed by the Apache 2.0 license. */ @file:Suppress("NOTHING_TO_INLINE") package splitties.dimensions import android.content.Context import android.view.View /** Converts Device Independent Pixels to pixels. Returns an `Int` or a `Float` based on [value]'s type. */ inline fun Context.dip(value: Int): Int = (value * resources.displayMetrics.density).toInt() /** Converts Device Independent Pixels to pixels. Returns an `Int` or a `Float` based on [value]'s type. */ inline fun Context.dip(value: Float): Float = (value * resources.displayMetrics.density) /** Converts Device Independent Pixels to pixels. Returns an `Int` or a `Float` based on [value]'s type. */ inline fun View.dip(value: Int): Int = context.dip(value) /** Converts Device Independent Pixels to pixels. Returns an `Int` or a `Float` based on [value]'s type. */ inline fun View.dip(value: Float): Float = context.dip(value) /** Converts Device Independent Pixels to pixels. Returns an `Int` or a `Float` based on [value]'s type. */ inline fun Context.dp(value: Int): Int = dip(value) /** Converts Device Independent Pixels to pixels. Returns an `Int` or a `Float` based on [value]'s type. */ inline fun Context.dp(value: Float): Float = dip(value) /** Converts Device Independent Pixels to pixels. Returns an `Int` or a `Float` based on [value]'s type. */ inline fun View.dp(value: Int): Int = context.dip(value) /** Converts Device Independent Pixels to pixels. Returns an `Int` or a `Float` based on [value]'s type. */ inline fun View.dp(value: Float): Float = context.dip(value)
apache-2.0
c41cb241c69f0756886e4b5e94d5498d
45.914286
109
0.72229
3.585153
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/KotlinBundle.kt
5
978
// 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 import org.jetbrains.annotations.Nls import org.jetbrains.annotations.NonNls import org.jetbrains.annotations.PropertyKey import org.jetbrains.kotlin.util.AbstractKotlinBundle @NonNls private const val BUNDLE = "messages.KotlinBundle" object KotlinBundle : AbstractKotlinBundle(BUNDLE) { @Nls @JvmStatic fun message(@NonNls @PropertyKey(resourceBundle = BUNDLE) key: String, vararg params: Any): String = getMessage(key, *params) @Nls @JvmStatic fun htmlMessage(@NonNls @PropertyKey(resourceBundle = BUNDLE) key: String, vararg params: Any): String = getMessage(key, *params).withHtml() @Nls @JvmStatic fun lazyMessage(@PropertyKey(resourceBundle = BUNDLE) key: String, vararg params: Any): () -> String = { getMessage(key, *params) } }
apache-2.0
b398b1db080ff9069d58e10894836d11
38.16
158
0.748466
4.270742
false
false
false
false
xmartlabs/bigbang
ui/src/main/java/com/xmartlabs/bigbang/ui/common/recyclerview/BaseRecyclerViewAdapter.kt
1
11982
package com.xmartlabs.bigbang.ui.common.recyclerview import android.support.annotation.CallSuper import android.support.annotation.LayoutRes import android.support.annotation.MainThread import android.support.v7.util.DiffUtil import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import io.reactivex.Single import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.disposables.Disposable import io.reactivex.schedulers.Schedulers import java.util.ArrayList /** * A Base RecyclerViewAdapter with already implemented functions such as * Setting, removing, adding items, getting its count among others. */ abstract class BaseRecyclerViewAdapter : RecyclerView.Adapter<RecyclerView.ViewHolder>() { protected val items = ArrayList<Element>() private val types = ArrayList<RecycleItemType<*, *>>() private var updateElementsDisposable: Disposable? = null open protected class Element(var type: RecycleItemType<*, *>, var item: Any) protected fun inflateView(parent: ViewGroup, @LayoutRes layoutResId: Int): View { val layoutInflater = LayoutInflater.from(parent.context) return layoutInflater.inflate(layoutResId, parent, false) } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = types[viewType].onCreateViewHolder(parent) /** * Removes an item from the data and any registered observers of its removal. * * @param item the item to be removed. */ @MainThread fun <T> removeItem(item: T) { items.withIndex() .filter { it.value.item == item } .sortedByDescending { it.index } .forEach { items.removeAt(it.index) notifyItemRemoved(it.index) } } /** * Removes an item from the data and any registered observers of its removal. * * @param index the index of the item to be removed. */ @MainThread fun removeItemAtIndex(index: Int) { if (index < items.size) { items.removeAt(index) notifyItemRemoved(index) } } /** * Removes a list of items from the data and any registered observers of its removal. * * @param items the list of items to be removed. */ @MainThread fun removeItems(items: List<Any>) = items.distinct().forEach(this::removeItem) /** * Adds an item to the data for the recycler view without notifying any registered observers that an item has been * added. * * @param type The type of the item. * * * @param item The item to be added. * * * @param addTypeIfNeeded A boolean specifying if the item type has to be added to the type collection. * * If this parameter is true, the type will be added only if it wasn't added yet. */ protected fun <T : RecycleItemType<*, *>> addItemWithoutNotifying(type: T, item: Any, addTypeIfNeeded: Boolean) { addItemWithoutNotifying(items.size, type, item, addTypeIfNeeded) } /** * Adds an item to the data for the recycler view without notifying any registered observers that an item has been * added. * * @param index The index at which the specified items are to be inserted. * * * @param type The type of the item. * * * @param item The item to be added. * * * @param addTypeIfNeeded A boolean specifying if the item type has to be added to the type collection. * * If this parameter is true, the type will be added only if it wasn't added yet. */ private fun <T : RecycleItemType<*, *>> addItemWithoutNotifying(index: Int, type: T, item: Any, addTypeIfNeeded: Boolean) { val element = Element(type, item) items.add(index, element) if (addTypeIfNeeded) { addItemTypeIfNeeded(type) } } /** * Add the type to the collection type only if it is needed. * * @param type The type to be added. */ private fun <T : RecycleItemType<*, *>> addItemTypeIfNeeded(type: T) { if (!types.contains(type)) { types.add(type) } } /** * Adds an item to the data for the recycler view and notifies any registered observers that an item has been added. * * @param type The type of the item. * * * @param item The item to be added. */ @MainThread protected fun <T : RecycleItemType<*, *>> addItem(type: T, item: Any) { addItemWithoutNotifying(type, item, true) notifyItemInserted(items.size - 1) } /** * Adds items to the data for the recycler view and notifies any registered observers that the items has been added. * * @param index The index at which the specified items are to be inserted. * * * @param type The type of the item. * * * @param items The items that will be the data for the recycler view. * * * @return if items was successfully added. */ @MainThread protected fun <T : RecycleItemType<*, *>> addItems(index: Int, type: T, items: List<*>?): Boolean { if (items == null || items.isEmpty()) { return false } val lastItemCount = itemCount items.filterNotNull().forEachIndexed { pos, element -> addItemWithoutNotifying(pos + index, type, element, false) } addItemTypeIfNeeded(type) notifyItemRangeInserted(index, itemCount - lastItemCount) return true } /** * Adds items to the data for the recycler view and notifies any registered observers that the items has been added. * * @param type The type of the items. * * * @param items the items that will be the data for the recycler view. * * * @return if item was successfully added. */ @MainThread protected fun <T : RecycleItemType<*, *>> addItems(type: T, items: List<Any>): Boolean { if (items.isEmpty()) { return false } val lastItemCount = itemCount items.forEach { addItemWithoutNotifying(type, it, false) } addItemTypeIfNeeded(type) if (lastItemCount == 0) { notifyDataSetChanged() } else { notifyItemRangeInserted(lastItemCount, itemCount - lastItemCount) } return true } /** * Sets the items data for the recycler view and notifying any registered observers that the data set has * changed. It uses a function that calculates the difference between the old and the new items * in order to improve the update process. * * Items compare will be executed on a secondary thread * * @param type Type of items. * * * @param newItems The items tobe set. * * * @param areItemsTheSame A function which checks that two items are the same. * * * @param areContentTheSame A function which checks that the content of two items are the same. */ protected fun <T : RecycleItemType<*, *>> setItems(type: T, newItems: List<*>, areItemsTheSame: (Any, Any) -> Boolean, areContentTheSame: (Any, Any) -> Boolean) { if (newItems.isEmpty()) { clearAll() notifyDataSetChanged() return } if (updateElementsDisposable != null && !updateElementsDisposable!!.isDisposed) { updateElementsDisposable!!.dispose() } val newElements = newItems .filterNotNull() .map { item -> Element(type, item) } updateElementsDisposable = Single .fromCallable { DiffUtil.calculateDiff(getUpdateDiffCallback(items, newElements, areItemsTheSame, areContentTheSame)) } .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe { diffResult -> items.clear() items.addAll(newElements) addItemTypeIfNeeded(type) diffResult.dispatchUpdatesTo(this) } } /** * Sets the items data for the recycler view and notifying any registered observers that the data set has * changed. It uses a function that calculates the difference between the old and the new items * in order to improve the update process. * * Items compare will be executed on a secondary thread * * @param newElements The elements to be set. * * @param areItemsTheSame A function which checks that two items are the same. * * @param areContentTheSame A function which checks that the content of two items are the same. */ protected fun setElements(newElements: List<Element>, areItemsTheSame: (Any, Any) -> Boolean, areContentTheSame: (Any, Any) -> Boolean) { if (newElements.isEmpty()) { clearAll() notifyDataSetChanged() return } if (updateElementsDisposable != null && !updateElementsDisposable!!.isDisposed) { updateElementsDisposable!!.dispose() } updateElementsDisposable = Single .fromCallable { DiffUtil.calculateDiff(getUpdateDiffCallback(items, newElements, areItemsTheSame, areContentTheSame)) } .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe { diffResult -> newElements .map { it.type } .distinct() .forEach { addItemTypeIfNeeded(it) } items.clear() items.addAll(newElements) diffResult.dispatchUpdatesTo(this) } } private fun getUpdateDiffCallback( oldItems: List<Element>, newItems: List<Element>, areItemsTheSame: (Any, Any) -> Boolean, areContentTheSame: (Any, Any) -> Boolean): DiffUtil.Callback { return object : DiffUtil.Callback() { override fun getOldListSize() = oldItems.size override fun getNewListSize() = newItems.size override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int) = areItemsTheSame(oldItems[oldItemPosition].item, newItems[newItemPosition].item) override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int) = areContentTheSame(oldItems[oldItemPosition].item, newItems[newItemPosition].item) } } /** * Sets the items data for the recycler view and notifies any registered observers that the data set has * changed. * * @param type Type of items. * * * @param newItems The items tobe added. */ @MainThread protected fun <T : RecycleItemType<*, *>> setItems(type: T, newItems: List<Any>) { items.clear() addItems(type, newItems) } /** * Gets all the items count, including dividers. * * @return number of total items. */ override fun getItemCount(): Int = items.size @CallSuper override fun onBindViewHolder(viewHolder: RecyclerView.ViewHolder, position: Int) { val element = items[position] val item = element.item @Suppress("UNCHECKED_CAST") (element.type as? RecycleItemType<Any, RecyclerView.ViewHolder>)?.onBindViewHolder(viewHolder, item, position) @Suppress("UNCHECKED_CAST") (viewHolder as? BindingItemViewHolder<Any>)?.bindItem(element.item) } /** * Gets the item type. * * @param position of the item among all items conforming the recycler view. * * * @return item divider type. */ override fun getItemViewType(position: Int) = types.indexOf(items[position].type) /** Removes all items and notifies that the data has changed. */ @MainThread fun clearAll() { items.clear() notifyDataSetChanged() } /** * Removes all items in the recyclerView of a specified type. * * @param itemType The specified type of items to be removed. */ @MainThread fun clearItems(itemType: RecycleItemType<*, out RecyclerView.ViewHolder>) { val itemsToRemove = items .filter { it.type == itemType } .map(Element::item) removeItems(itemsToRemove) } }
apache-2.0
f4dfa951cd949ea38d3de07c42c30850
33.136752
127
0.652228
4.63162
false
false
false
false
PhoenixDevTeam/Phoenix-for-VK
app/src/main/java/biz/dealnote/messenger/Extensions.kt
1
2544
package biz.dealnote.messenger import android.database.Cursor import android.database.sqlite.SQLiteDatabase import biz.dealnote.messenger.util.RxUtils import io.reactivex.Completable import io.reactivex.Flowable import io.reactivex.Observable import io.reactivex.Single import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.disposables.Disposable import io.reactivex.functions.Consumer import io.reactivex.schedulers.Schedulers fun <T : Any> Single<T>.fromIOToMain(): Single<T> = subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()) fun <T : Any> Single<T>.subscribeIOAndIgnoreResults(): Disposable = subscribeOn(Schedulers.io()).subscribe(RxUtils.ignore(), RxUtils.ignore()) fun <T : Any> Flowable<T>.toMainThread(): Flowable<T> = observeOn(AndroidSchedulers.mainThread()) fun <T : Any> Observable<T>.toMainThread(): Observable<T> = observeOn(AndroidSchedulers.mainThread()) fun Completable.fromIOToMain(): Completable = subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()) fun SQLiteDatabase.query(tablename: String, columns: Array<String>, where: String?, args: Array<String>?): Cursor = query(tablename, columns, where, args, null, null, null) fun SQLiteDatabase.query(tablename: String, columns: Array<String>): Cursor = query(tablename, columns, null, null) fun Cursor.getNullableInt(columnName: String): Int? = getColumnIndex(columnName).let { if (isNull(it)) null else getInt(it) } fun Cursor.getInt(columnName: String): Int = getInt(getColumnIndex(columnName)) fun Cursor.getBoolean(columnName: String): Boolean = getInt(getColumnIndex(columnName)) == 1 fun Cursor.getLong(columnName: String): Long? = getColumnIndex(columnName).let { if (isNull(it)) null else getLong(it) } fun Cursor.getString(columnName: String): String? = getString(getColumnIndex(columnName)) fun Disposable.notDisposed(): Boolean = !isDisposed fun <T: Any> Collection<T>?.nullOrEmpty(): Boolean = if(this == null) true else size == 0 fun <T: Any> Collection<T>?.nonEmpty(): Boolean = if(this == null) false else size > 0 fun CharSequence?.nonEmpty(): Boolean = if(this == null) false else length > 0 fun <T : Any> Flowable<T>.subscribeIgnoreErrors(consumer: Consumer<in T>): Disposable = subscribe(consumer, RxUtils.ignore()) fun <T : Any> Single<T>.subscribeIgnoreErrors(consumer: Consumer<in T>): Disposable = subscribe(consumer, RxUtils.ignore()) fun Completable.subscribeIOAndIgnoreResults(): Disposable = subscribeOn(Schedulers.io()).subscribe(RxUtils.dummy(), RxUtils.ignore())
gpl-3.0
d5a12daec08df3b16ad1632192907f4a
48.901961
172
0.773192
3.975
false
false
false
false
aurae/PermissionsDispatcher
test-v13/src/test/java/permissions/dispatcher/test_v13/Extensions.kt
1
2933
package permissions.dispatcher.test import android.annotation.SuppressLint import android.app.Fragment import android.content.Context import android.content.pm.PackageManager import android.os.Build import android.os.Process import android.support.v13.app.FragmentCompat import android.support.v4.app.AppOpsManagerCompat import android.support.v4.content.PermissionChecker import android.support.v7.app.AppCompatActivity import org.mockito.Matchers import org.mockito.Matchers.any import org.mockito.Matchers.anyString import org.powermock.api.mockito.PowerMockito import java.lang.reflect.Field import java.lang.reflect.Modifier fun mockCheckSelfPermission(result: Boolean) { val value = if (result) PackageManager.PERMISSION_GRANTED else PackageManager.PERMISSION_DENIED PowerMockito.`when`(PermissionChecker.checkSelfPermission(any(Context::class.java), anyString())).thenReturn(value) } @SuppressLint("NewApi") fun mockShouldShowRequestPermissionRationaleFragment(result: Boolean) { PowerMockito.`when`(FragmentCompat.shouldShowRequestPermissionRationale(any(Fragment::class.java), anyString())).thenReturn(result) } fun mockGetActivity(fragment: Fragment, result: AppCompatActivity) { PowerMockito.`when`(fragment.activity).thenReturn(result) } fun getRequestCameraConstant(clazz: Class<*>): Int { val field = clazz.getDeclaredField("REQUEST_SHOWCAMERA") field.isAccessible = true return field.getInt(null) } fun getPermissionRequestConstant(clazz: Class<*>): Array<String> { val field = clazz.getDeclaredField("PERMISSION_SHOWCAMERA") field.isAccessible = true return field.get(null) as Array<String> } fun overwriteCustomManufacture(manufactureText: String = "Xiaomi") { val modifiersField = Field::class.java.getDeclaredField("modifiers") modifiersField.isAccessible = true val manufacture = Build::class.java.getDeclaredField("MANUFACTURER") manufacture.isAccessible = true modifiersField.setInt(manufacture, manufacture.modifiers and Modifier.FINAL.inv()) manufacture.set(null, manufactureText) } fun overwriteCustomSdkInt(sdkInt: Int = 23) { val modifiersField = Field::class.java.getDeclaredField("modifiers") modifiersField.isAccessible = true val field = Build.VERSION::class.java.getDeclaredField("SDK_INT") field.isAccessible = true modifiersField.setInt(field, field.modifiers and Modifier.FINAL.inv()) field.set(null, sdkInt) } fun testForXiaomi() { overwriteCustomManufacture() overwriteCustomSdkInt() } fun mockPermissionToOp(result: String?) { PowerMockito.`when`(AppOpsManagerCompat.permissionToOp(anyString())).thenReturn(result) } fun mockMyUid() { PowerMockito.`when`(Process.myUid()).thenReturn(1) } fun mockNoteOp(result: Int) { mockMyUid() PowerMockito.`when`(AppOpsManagerCompat.noteOp(any(Context::class.java), anyString(), Matchers.anyInt(), anyString())).thenReturn(result) }
apache-2.0
56148d4f5c28a8a6ea4cef89abb985ea
34.780488
141
0.783498
4.269287
false
false
false
false
getsentry/raven-java
sentry-logback/src/test/kotlin/io/sentry/logback/SentryAppenderTest.kt
1
14018
package io.sentry.logback import ch.qos.logback.classic.Level import ch.qos.logback.classic.LoggerContext import ch.qos.logback.core.status.Status import com.nhaarman.mockitokotlin2.any import com.nhaarman.mockitokotlin2.anyOrNull import com.nhaarman.mockitokotlin2.mock import com.nhaarman.mockitokotlin2.verify import com.nhaarman.mockitokotlin2.whenever import io.sentry.ITransportFactory import io.sentry.Sentry import io.sentry.SentryLevel import io.sentry.SentryOptions import io.sentry.test.checkEvent import io.sentry.transport.ITransport import java.time.Instant import java.time.LocalDateTime import java.time.ZoneId import kotlin.test.AfterTest import kotlin.test.BeforeTest import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertFalse import kotlin.test.assertNotNull import kotlin.test.assertNull import kotlin.test.assertTrue import org.awaitility.kotlin.await import org.slf4j.Logger import org.slf4j.LoggerFactory import org.slf4j.MDC import org.slf4j.MarkerFactory class SentryAppenderTest { private class Fixture(dsn: String? = "http://key@localhost/proj", minimumBreadcrumbLevel: Level? = null, minimumEventLevel: Level? = null) { val logger: Logger = LoggerFactory.getLogger(SentryAppenderTest::class.java) val loggerContext = LoggerFactory.getILoggerFactory() as LoggerContext val transportFactory = mock<ITransportFactory>() val transport = mock<ITransport>() val utcTimeZone: ZoneId = ZoneId.of("UTC") init { whenever(this.transportFactory.create(any(), any())).thenReturn(transport) val appender = SentryAppender() val options = SentryOptions() options.dsn = dsn appender.setOptions(options) appender.setMinimumBreadcrumbLevel(minimumBreadcrumbLevel) appender.setMinimumEventLevel(minimumEventLevel) appender.context = loggerContext appender.setTransportFactory(transportFactory) val rootLogger = loggerContext.getLogger(Logger.ROOT_LOGGER_NAME) rootLogger.level = Level.TRACE rootLogger.addAppender(appender) appender.start() loggerContext.start() } } private lateinit var fixture: Fixture @AfterTest fun `stop logback`() { fixture.loggerContext.stop() Sentry.close() } @BeforeTest fun `clear MDC`() { MDC.clear() } @Test fun `does not initialize Sentry if Sentry is already enabled`() { fixture = Fixture() Sentry.init { it.dsn = "http://key@localhost/proj" it.environment = "manual-environment" it.setTransportFactory(fixture.transportFactory) } fixture.logger.error("testing environment field") await.untilAsserted { verify(fixture.transport).send(checkEvent { event -> assertEquals("manual-environment", event.environment) }, anyOrNull()) } } @Test fun `converts message`() { fixture = Fixture(minimumEventLevel = Level.DEBUG) fixture.logger.debug("testing message conversion {}, {}", 1, 2) await.untilAsserted { verify(fixture.transport).send(checkEvent { event -> assertNotNull(event.message) { message -> assertEquals("testing message conversion 1, 2", message.formatted) assertEquals("testing message conversion {}, {}", message.message) assertEquals(listOf("1", "2"), message.params) } assertEquals("io.sentry.logback.SentryAppenderTest", event.logger) }, anyOrNull()) } } @Test fun `event date is in UTC`() { fixture = Fixture(minimumEventLevel = Level.DEBUG) val utcTime = LocalDateTime.now(fixture.utcTimeZone) fixture.logger.debug("testing event date") await.untilAsserted { verify(fixture.transport).send(checkEvent { event -> val eventTime = Instant.ofEpochMilli(event.timestamp.time) .atZone(fixture.utcTimeZone) .toLocalDateTime() assertTrue { eventTime.plusSeconds(1).isAfter(utcTime) } assertTrue { eventTime.minusSeconds(1).isBefore(utcTime) } }, anyOrNull()) } } @Test fun `converts trace log level to Sentry level`() { fixture = Fixture(minimumEventLevel = Level.TRACE) fixture.logger.trace("testing trace level") await.untilAsserted { verify(fixture.transport).send(checkEvent { event -> assertEquals(SentryLevel.DEBUG, event.level) }, anyOrNull()) } } @Test fun `converts debug log level to Sentry level`() { fixture = Fixture(minimumEventLevel = Level.DEBUG) fixture.logger.debug("testing debug level") await.untilAsserted { verify(fixture.transport).send(checkEvent { event -> assertEquals(SentryLevel.DEBUG, event.level) }, anyOrNull()) } } @Test fun `converts info log level to Sentry level`() { fixture = Fixture(minimumEventLevel = Level.INFO) fixture.logger.info("testing info level") await.untilAsserted { verify(fixture.transport).send(checkEvent { event -> assertEquals(SentryLevel.INFO, event.level) }, anyOrNull()) } } @Test fun `converts warn log level to Sentry level`() { fixture = Fixture(minimumEventLevel = Level.WARN) fixture.logger.warn("testing warn level") await.untilAsserted { verify(fixture.transport).send(checkEvent { event -> assertEquals(SentryLevel.WARNING, event.level) }, anyOrNull()) } } @Test fun `converts error log level to Sentry level`() { fixture = Fixture(minimumEventLevel = Level.ERROR) fixture.logger.error("testing error level") await.untilAsserted { verify(fixture.transport).send(checkEvent { event -> assertEquals(SentryLevel.ERROR, event.level) }, anyOrNull()) } } @Test fun `attaches thread information`() { fixture = Fixture(minimumEventLevel = Level.WARN) fixture.logger.warn("testing thread information") await.untilAsserted { verify(fixture.transport).send(checkEvent { event -> assertNotNull(event.getExtra("thread_name")) }, anyOrNull()) } } @Test fun `sets tags from MDC`() { fixture = Fixture(minimumEventLevel = Level.WARN) MDC.put("key", "value") fixture.logger.warn("testing MDC tags") await.untilAsserted { verify(fixture.transport).send(checkEvent { event -> assertEquals(mapOf("key" to "value"), event.contexts["MDC"]) }, anyOrNull()) } } @Test fun `ignore set tags with null values from MDC`() { fixture = Fixture(minimumEventLevel = Level.WARN) MDC.put("key1", null) MDC.put("key2", "value") fixture.logger.warn("testing MDC tags") await.untilAsserted { verify(fixture.transport).send(checkEvent { event -> assertNotNull(event.contexts["MDC"]) { val contextData = it as Map<*, *> assertNull(contextData["key1"]) assertEquals("value", contextData["key2"]) } }, anyOrNull()) } } @Test fun `does not set MDC if all context entries are null`() { fixture = Fixture(minimumEventLevel = Level.WARN) MDC.put("key1", null) MDC.put("key2", null) fixture.logger.warn("testing MDC tags") await.untilAsserted { verify(fixture.transport).send(checkEvent { event -> assertNull(event.contexts["MDC"]) }, anyOrNull()) } } @Test fun `does not create MDC context when no MDC tags are set`() { fixture = Fixture(minimumEventLevel = Level.WARN) fixture.logger.warn("testing without MDC tags") await.untilAsserted { verify(fixture.transport).send(checkEvent { event -> assertFalse(event.contexts.containsKey("MDC")) }, anyOrNull()) } } @Test fun `attaches marker information`() { fixture = Fixture(minimumEventLevel = Level.WARN) val sqlMarker = MarkerFactory.getDetachedMarker("SQL") sqlMarker.add(MarkerFactory.getDetachedMarker("SQL_UPDATE")) sqlMarker.add(MarkerFactory.getDetachedMarker("SQL_QUERY")) fixture.logger.warn(sqlMarker, "testing marker tags") await.untilAsserted { verify(fixture.transport).send(checkEvent { event -> assertEquals("SQL [ SQL_UPDATE, SQL_QUERY ]", event.getExtra("marker")) }, anyOrNull()) } } @Test fun `sets SDK version`() { fixture = Fixture(minimumEventLevel = Level.INFO) fixture.logger.info("testing sdk version") await.untilAsserted { verify(fixture.transport).send(checkEvent { event -> assertNotNull(event.sdk) { assertEquals(BuildConfig.SENTRY_LOGBACK_SDK_NAME, it.name) assertEquals(BuildConfig.VERSION_NAME, it.version) assertNotNull(it.packages) assertTrue(it.packages!!.any { pkg -> "maven:io.sentry:sentry-logback" == pkg.name && BuildConfig.VERSION_NAME == pkg.version }) } }, anyOrNull()) } } @Test fun `attaches breadcrumbs with level higher than minimumBreadcrumbLevel`() { fixture = Fixture(minimumBreadcrumbLevel = Level.DEBUG, minimumEventLevel = Level.WARN) val utcTime = LocalDateTime.now(fixture.utcTimeZone) fixture.logger.debug("this should be a breadcrumb #1") fixture.logger.info("this should be a breadcrumb #2") fixture.logger.warn("testing message with breadcrumbs") await.untilAsserted { verify(fixture.transport).send(checkEvent { event -> assertNotNull(event.breadcrumbs) { breadcrumbs -> assertEquals(2, breadcrumbs.size) val breadcrumb = breadcrumbs[0] val breadcrumbTime = Instant.ofEpochMilli(event.timestamp.time) .atZone(fixture.utcTimeZone) .toLocalDateTime() assertTrue { breadcrumbTime.plusSeconds(1).isAfter(utcTime) } assertTrue { breadcrumbTime.minusSeconds(1).isBefore(utcTime) } assertEquals("this should be a breadcrumb #1", breadcrumb.message) assertEquals("io.sentry.logback.SentryAppenderTest", breadcrumb.category) assertEquals(SentryLevel.DEBUG, breadcrumb.level) } }, anyOrNull()) } } @Test fun `does not attach breadcrumbs with level lower than minimumBreadcrumbLevel`() { fixture = Fixture(minimumBreadcrumbLevel = Level.INFO, minimumEventLevel = Level.WARN) fixture.logger.debug("this should NOT be a breadcrumb") fixture.logger.info("this should be a breadcrumb") fixture.logger.warn("testing message with breadcrumbs") await.untilAsserted { verify(fixture.transport).send(checkEvent { event -> assertNotNull(event.breadcrumbs) { breadcrumbs -> assertEquals(1, breadcrumbs.size) assertEquals("this should be a breadcrumb", breadcrumbs[0].message) } }, anyOrNull()) } } @Test fun `attaches breadcrumbs for default appender configuration`() { fixture = Fixture() fixture.logger.debug("this should not be a breadcrumb as the level is lower than the minimum INFO") fixture.logger.info("this should be a breadcrumb") fixture.logger.warn("this should not be sent as the event but be a breadcrumb") fixture.logger.error("this should be sent as the event") await.untilAsserted { verify(fixture.transport).send(checkEvent { event -> assertNotNull(event.breadcrumbs) { breadcrumbs -> assertEquals(2, breadcrumbs.size) assertEquals("this should be a breadcrumb", breadcrumbs[0].message) assertEquals("this should not be sent as the event but be a breadcrumb", breadcrumbs[1].message) } }, anyOrNull()) } } @Test fun `uses options set in properties file`() { fixture = Fixture() fixture.logger.error("some event") await.untilAsserted { verify(fixture.transport).send(checkEvent { event -> assertEquals("release from sentry.properties", event.release) }, anyOrNull()) } } @Test fun `does not initialize Sentry when environment variable with DSN is passed through environment variable that is not set`() { // environment variables referenced in the logback.xml that are not set in the OS, have value "ENV_NAME_IS_UNDEFINED" fixture = Fixture(dsn = "DSN_IS_UNDEFINED", minimumEventLevel = Level.DEBUG) assertTrue(fixture.loggerContext.statusManager.copyOfStatusList.none { it.level == Status.WARN }) } @Test fun `does initialize Sentry when DSN is not set`() { System.setProperty("sentry.dsn", "http://key@localhost/proj") fixture = Fixture(dsn = null, minimumEventLevel = Level.DEBUG) assertTrue(Sentry.isEnabled()) System.clearProperty("sentry.dsn") } }
bsd-3-clause
515cdd645bf3a4f9bc16ec848b6fab73
35.505208
144
0.612998
4.779407
false
true
false
false
shiftize/CalendarView
calendarview/src/main/kotlin/com/shiftize/calendarview/DayView.kt
1
2866
package com.shiftize.calendarview import android.content.Context import android.graphics.Color import android.graphics.drawable.ShapeDrawable import android.graphics.drawable.shapes.OvalShape import android.view.Gravity import android.view.ViewGroup import android.widget.LinearLayout import android.widget.RelativeLayout import android.widget.TextView import java.util.* class DayView : RelativeLayout { var dayText: TextView? = null var day: Int? = 1 set(value) { dayText?.text = value.toString() } var textColor: Int set(value) { dayText?.setTextColor(value) } get() { if (dayText == null) { return Color.rgb(0, 0, 0) } else { return dayText!!.currentTextColor } } var textSize: Float = 20.0f set(value) { dayText?.textSize = value } private val drawable: ShapeDrawable = ShapeDrawable() var textHighlightedColor: Int = Color.TRANSPARENT set(value) { drawable.paint.color = value drawable.invalidateSelf() } var dotContainer: LinearLayout? = null var agendaList: List<Agenda> = ArrayList() set(value) { setDotViews(value) } constructor(context: Context): super(context) { setUp() } /** * set up DayView */ fun setUp() { removeAllViews() dayText = TextView(context) dayText?.text = day.toString() dayText?.textSize = textSize dayText?.setTextColor(Color.parseColor(context.getString(R.color.default_text))) drawable.paint.color = textHighlightedColor drawable.shape = OvalShape() dayText?.background = drawable dayText?.post { dayText?.width = dayText!!.height } dayText?.gravity = Gravity.CENTER dayText?.setPadding(3, 3, 3, 3) val textLayoutParams = LayoutParams(LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT) textLayoutParams.addRule(RelativeLayout.CENTER_HORIZONTAL) textLayoutParams.topMargin = 6 this.addView(dayText, textLayoutParams) dotContainer = LinearLayout(context) dotContainer?.orientation = LinearLayout.HORIZONTAL dotContainer?.setGravity(Gravity.CENTER) val dotContainerLayoutParams = LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT) dotContainerLayoutParams.addRule(RelativeLayout.CENTER_IN_PARENT) setDotViews(agendaList) this.addView(dotContainer, dotContainerLayoutParams) } private fun setDotViews(agendaList: List<Agenda>) { dotContainer?.removeAllViews() val dotView = DotView(context) dotView.agendaList = agendaList dotContainer?.addView(dotView) } }
apache-2.0
88838350244d0211a95743d5a98fad59
30.494505
107
0.644103
4.607717
false
false
false
false
batagliao/onebible.android
app/src/main/java/com/claraboia/bibleandroid/adapters/TranslationLocalRecyclerAdapter.kt
1
1879
package com.claraboia.bibleandroid.adapters import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.claraboia.bibleandroid.BibleApplication import com.claraboia.bibleandroid.R import com.claraboia.bibleandroid.helpers.CheatSheet import com.claraboia.bibleandroid.models.BibleTranslation import kotlinx.android.synthetic.main.layout_translation_local_item.view.* /** * Created by lucasbatagliao on 23/12/16. */ class TranslationLocalRecyclerAdapter(val click: (translation: BibleTranslation) -> Unit) : RecyclerView.Adapter<TranslationLocalRecyclerAdapter.TranslationViewHolder>() { inner class TranslationViewHolder(itemView: View?) : RecyclerView.ViewHolder(itemView) { fun bind(translation: BibleTranslation){ itemView.item_translationName.text = translation.name itemView.item_translationAbbrev.text = translation.abbreviation itemView.item_translationSize.text = translation.fileSize.toString() + "MB" itemView.item_translationDelete.setOnClickListener { click.invoke(translation) } CheatSheet.setup(itemView.item_translationDelete) } } fun notifyChanged() { notifyDataSetChanged() } override fun getItemCount(): Int { return BibleApplication.instance.localBibles.size } override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): TranslationViewHolder { val inflater = LayoutInflater.from(parent?.context) val view = inflater.inflate(R.layout.layout_translation_local_item, parent, false) return TranslationViewHolder(view) } override fun onBindViewHolder(holder: TranslationViewHolder?, position: Int) { holder?.bind(BibleApplication.instance.localBibles[position]) } }
apache-2.0
04b026f3b45b1dd135426b0427b902f7
36.58
171
0.742416
4.732997
false
false
false
false
softappeal/yass
kotlin/yass/main/ch/softappeal/yass/remote/session/Session.kt
1
5829
package ch.softappeal.yass.remote.session import ch.softappeal.yass.* import ch.softappeal.yass.remote.* import java.util.* import java.util.concurrent.* import java.util.concurrent.atomic.* interface Connection { /** Called if a packet has to be written out. */ @Throws(Exception::class) fun write(packet: Packet) /** Called once if the connection has been closed. */ @Throws(Exception::class) fun closed() } class SessionClosedException : RuntimeException() abstract class Session : Client(), AutoCloseable { private lateinit var _connection: Connection val connection: Connection get() = _connection private lateinit var server: Server private val closed = AtomicBoolean(true) val isClosed get() = closed.get() /** note: it's not worth to use [ConcurrentHashMap] here */ private val requestNumber2invocation = Collections.synchronizedMap(HashMap<Int, ClientInvocation>(16)) private val nextRequestNumber = AtomicInteger(EndRequestNumber) internal fun iCreated(connection: Connection) { server = server() _connection = connection closed.set(false) dispatchOpened { try { opened() } catch (e: Exception) { close(e) } } } /** Called if a session has been opened. Must call [action] (possibly in an own thread). */ @Throws(Exception::class) protected abstract fun dispatchOpened(action: () -> Unit) /** Called for an incoming request. Must call [action] (possibly in an own thread). */ @Throws(Exception::class) protected abstract fun dispatchService(invocation: ServiceInvocation, action: () -> Unit) /** Gets the server of this session. Called only once after creation of session. */ @Throws(Exception::class) protected open fun server(): Server = EmptyServer @Throws(Exception::class) protected open fun opened() { // empty } /** If ([exception] == null) regular close else reason for close. */ @Throws(Exception::class) protected open fun closed(exception: Exception?) { // empty } override fun close() = iClose(true, null) private fun settlePendingInvocations() { for (invocation in requestNumber2invocation.values.toList()) try { invocation.settle(ExceptionReply(SessionClosedException())) } catch (ignore: Exception) { } } internal fun iClose(sendEnd: Boolean, exception: Exception?) { if (closed.getAndSet(true)) return try { try { settlePendingInvocations() } finally { closed(exception) } if (sendEnd) _connection.write(EndPacket) } finally { _connection.closed() } } private fun closeThrow(e: Exception) { addSuppressed(e) { close(e) } throw e } private fun serviceInvoke(requestNumber: Int, request: Request) { val invocation = server.invocation(true, request) dispatchService(invocation) { try { invocation.invoke { reply -> if (!invocation.methodMapping.oneWay) { try { _connection.write(Packet(requestNumber, reply)) } catch (e: Exception) { closeThrow(e) } } } } catch (e: Exception) { closeThrow(e) } } } internal fun iReceived(packet: Packet) { try { if (packet.isEnd) { iClose(false, null) return } when (val message = packet.message) { is Request -> serviceInvoke(packet.requestNumber, message) is Reply -> requestNumber2invocation.remove(packet.requestNumber)!!.settle(message) } } catch (e: Exception) { closeThrow(e) } } final override fun invoke(invocation: ClientInvocation) { if (isClosed) throw SessionClosedException() try { invocation.invoke(true) { request -> try { var requestNumber: Int do { // we can't use END_REQUEST_NUMBER as regular requestNumber requestNumber = nextRequestNumber.incrementAndGet() } while (requestNumber == EndRequestNumber) if (!invocation.methodMapping.oneWay) { requestNumber2invocation[requestNumber] = invocation if (isClosed) settlePendingInvocations() // needed due to race conditions } _connection.write(Packet(requestNumber, request)) } catch (e: Exception) { closeThrow(e) } } } catch (e: Exception) { closeThrow(e) } } } /** Must be called if communication has failed. This method is idempotent. */ fun Session.close(e: Exception) = iClose(false, e) /** * Must be called if a packet has been received. * It must also be called if [Packet.isEnd]; however, it must not be called again after that. */ fun Session.received(packet: Packet) = iReceived(packet) fun Session.created(connection: Connection) = iCreated(connection) typealias SessionFactory = () -> Session open class SimpleSession(protected val dispatchExecutor: Executor) : Session() { override fun dispatchOpened(action: () -> Unit) = dispatchExecutor.execute { action() } override fun dispatchService(invocation: ServiceInvocation, action: () -> Unit) = dispatchExecutor.execute { action() } }
bsd-3-clause
ec8bef3b240cc7f17226d18d4aad6c04
32.119318
106
0.584834
4.845387
false
false
false
false
serorigundam/numeri3
app/src/main/kotlin/net/ketc/numeri/util/rx/AutoDisposable.kt
1
1270
package net.ketc.numeri.util.rx import io.reactivex.Scheduler import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.disposables.Disposable import java.util.* interface AutoDisposable { fun addDisposable(disposable: Disposable) fun removeDisposable(disposable: Disposable) fun dispose() fun Disposable.autoDispose() = addDisposable(this) /** * do not need to call [autoDispose] when using this method. */ fun <T> singleTask(scheduler: Scheduler, observeOn: Scheduler = AndroidSchedulers.mainThread(), task: () -> T) = singleTask(scheduler, observeOn, this, task) } fun Disposable.autoDispose(autoDisposable: AutoDisposable) = autoDisposable.addDisposable(this) class AutoDisposableImpl : AutoDisposable { private val disposableList = ArrayList<Disposable>() override fun addDisposable(disposable: Disposable) { if (!disposableList.contains(disposable)) { disposableList.add(disposable) } } override fun removeDisposable(disposable: Disposable) { if (!disposable.isDisposed) { disposable.dispose() } disposableList.remove(disposable) } override fun dispose() { disposableList.forEach(Disposable::dispose) } }
mit
53fe732dee9473fe1e741bd7b5708908
30.775
161
0.714173
4.669118
false
false
false
false
BlueBoxWare/LibGDXPlugin
src/main/kotlin/com/gmail/blueboxware/libgdxplugin/filetypes/skin/findUsages/ClassImplicitUsageProvider.kt
1
2711
/* * Copyright 2022 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. */ package com.gmail.blueboxware.libgdxplugin.filetypes.skin.findUsages import com.gmail.blueboxware.libgdxplugin.filetypes.skin.LibGDXSkinFileType import com.gmail.blueboxware.libgdxplugin.filetypes.skin.psi.SkinFile import com.gmail.blueboxware.libgdxplugin.utils.isLibGDXProject import com.intellij.codeInsight.daemon.ImplicitUsageProvider import com.intellij.psi.PsiClass import com.intellij.psi.PsiElement import com.intellij.psi.PsiManager import com.intellij.psi.search.FileTypeIndex import com.intellij.psi.util.CachedValueProvider import com.intellij.psi.util.CachedValuesManager import org.jetbrains.kotlin.idea.search.allScope import org.jetbrains.kotlin.psi.KtClass class ClassImplicitUsageProvider : ImplicitUsageProvider { override fun isImplicitUsage(element: PsiElement): Boolean { if (!element.project.isLibGDXProject()) { return false } return CachedValuesManager.getCachedValue(element) { val fqName = (element as? PsiClass)?.qualifiedName ?: (element as? KtClass)?.fqName?.asString() ?: return@getCachedValue CachedValueProvider.Result.create(false, element) var found = false FileTypeIndex.processFiles(LibGDXSkinFileType.INSTANCE, { virtualFile -> (PsiManager.getInstance(element.project).findFile(virtualFile) as? SkinFile)?.let { skinFile -> skinFile.getClassSpecifications().forEach { classSpec -> classSpec.className.let { className -> if (className.value.plainName == fqName) { found = true return@processFiles true } } } } true }, element.project.allScope()) return@getCachedValue CachedValueProvider.Result.create(found, element) } } override fun isImplicitRead(element: PsiElement): Boolean = false override fun isImplicitWrite(element: PsiElement): Boolean = false }
apache-2.0
079385790868245b249dd8af516ab0fb
36.652778
111
0.678347
4.974312
false
false
false
false
Szewek/Minecraft-Flux
src/main/java/szewek/mcflux/fluxable/EntityActionEnergy.kt
1
1662
package szewek.mcflux.fluxable import net.minecraft.entity.EntityCreature import net.minecraft.entity.effect.EntityLightningBolt import net.minecraft.entity.monster.EntityCreeper import net.minecraft.entity.monster.EntityPigZombie import net.minecraft.entity.passive.EntityPig import net.minecraft.init.Items import net.minecraft.inventory.EntityEquipmentSlot import net.minecraft.item.ItemStack import szewek.mcflux.util.EnergyCapable class EntityActionEnergy(private val creature: EntityCreature) : EnergyCapable() { private var charged = false override fun getEnergy() = 0L override fun getEnergyCapacity() = 1L override fun canInputEnergy() = !charged override fun canOutputEnergy() = false override fun inputEnergy(amount: Long, simulate: Boolean): Long { if (!simulate && !charged) { if (creature is EntityPig) { val pigman = EntityPigZombie(creature.world) pigman.setItemStackToSlot(EntityEquipmentSlot.MAINHAND, ItemStack(Items.GOLDEN_AXE)) pigman.setLocationAndAngles(creature.posX, creature.posY, creature.posZ, creature.rotationYaw, creature.rotationPitch) pigman.setNoAI(creature.isAIDisabled()) if (creature.hasCustomName()) { pigman.customNameTag = creature.getCustomNameTag() pigman.alwaysRenderNameTag = creature.getAlwaysRenderNameTag() } creature.world.spawnEntity(pigman) creature.setDead() } else if (creature is EntityCreeper) creature.onStruckByLightning(EntityLightningBolt(creature.world, creature.posX, creature.posY, creature.posZ, true)) charged = true return 1 } return if (charged) 0L else 1L } override fun outputEnergy(amount: Long, sim: Boolean) = 0L }
mit
784722f1cd238bf475fbcd505a942042
37.651163
122
0.783995
3.551282
false
false
false
false
gradle/gradle
build-logic/packaging/src/main/kotlin/gradlebuild/packaging/GradleDistributionSpecs.kt
3
4255
/* * Copyright 2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package gradlebuild.packaging import gradlebuild.basics.repoRoot import org.gradle.api.Project import org.gradle.kotlin.dsl.* import java.io.File object GradleDistributionSpecs { /** * The binary distribution containing everything needed to run Gradle (and nothing else). */ fun Project.binDistributionSpec() = copySpec { val gradleScriptPath by configurations.getting val coreRuntimeClasspath by configurations.getting val runtimeClasspath by configurations.getting val runtimeApiInfoJar by tasks.getting from("${repoRoot()}/LICENSE") from("src/toplevel") into("bin") { from(gradleScriptPath) fileMode = Integer.parseInt("0755", 8) } into("lib") { from(runtimeApiInfoJar) from(coreRuntimeClasspath) into("plugins") { from(runtimeClasspath - coreRuntimeClasspath) } } } /** * The binary distribution enriched with the sources for the classes and an offline version of Gradle's documentation (without samples). */ fun Project.allDistributionSpec() = copySpec { val sourcesPath by configurations.getting val docsPath by configurations.getting with(binDistributionSpec()) from(sourcesPath.incoming.artifactView { lenient(true) }.files) { eachFile { val subprojectFolder = file.containingSubprojectFolder(listOf("src", "main", "java").size + relativeSourcePath.segments.size) val leadingSegments = relativePath.segments.size - relativeSourcePath.segments.size relativePath = relativeSourcePath.prepend("src", subprojectFolder.name).prepend(*(relativePath.segments.subArray(leadingSegments))) includeEmptyDirs = false } } into("docs") { from(docsPath) exclude("samples/**") } } /** * Offline version of the complete documentation of Gradle. */ fun Project.docsDistributionSpec() = copySpec { val docsPath by configurations.getting from("${repoRoot()}/LICENSE") from("src/toplevel") into("docs") { from(docsPath) } } /** * All the source code of the project such that a complete build can be performed from the sources. */ fun Project.srcDistributionSpec() = copySpec { from(repoRoot().file("gradlew")) { fileMode = Integer.parseInt("0755", 8) } from(repoRoot()) { listOf( "build-logic-commons", "build-logic-commons/*", "build-logic", "build-logic/*", "build-logic-settings", "build-logic-settings/*", "subprojects/*" ).forEach { include("$it/*.gradle") include("$it/*.gradle.kts") include("$it/src/") } include("*.gradle.kts") include("gradle.properties") include("build-logic/gradle.properties") include("gradle/") include("wrapper/") include("gradlew.bat") include("version.txt") include("released-versions.json") exclude("**/.gradle/") } } private fun File.containingSubprojectFolder(relativePathLenght: Int): File = if (relativePathLenght == 0) this else this.parentFile.containingSubprojectFolder(relativePathLenght - 1) private fun Array<String>.subArray(toIndex: Int) = listOf(*this).subList(0, toIndex).toTypedArray() }
apache-2.0
cf2eba5bac510163fe675455e2cb210d
33.314516
147
0.616451
4.780899
false
false
false
false
elect86/modern-jogl-examples
src/main/kotlin/main/tut02/fragPosition.kt
2
3080
package main.tut02 import com.jogamp.newt.event.KeyEvent import com.jogamp.opengl.GL.* import com.jogamp.opengl.GL2ES2 import com.jogamp.opengl.GL2ES3.GL_COLOR import com.jogamp.opengl.GL3 import com.jogamp.opengl.util.glsl.ShaderProgram import glNext.* import main.framework.Framework import uno.buffer.destroyBuffers import uno.buffer.floatBufferOf import uno.buffer.intBufferBig import uno.glsl.shaderCodeOf /** * Created by GBarbieri on 21.02.2017. */ fun main(args: Array<String>) { FragPosition_().setup("Tutorial 02 - Fragment Position") } class FragPosition_ : Framework() { var theProgram = 0 val vertexBufferObject = intBufferBig(1) val vao = intBufferBig(1) val vertexData = floatBufferOf( +0.75f, +0.75f, 0.0f, 1.0f, +0.75f, -0.75f, 0.0f, 1.0f, -0.75f, -0.75f, 0.0f, 1.0f) override fun init(gl: GL3) = with(gl) { initializeProgram(gl) initializeVertexBuffer(gl) glGenVertexArray(vao) glBindVertexArray(vao) } fun initializeProgram(gl: GL3) { theProgram = shaderProgramOf(gl, javaClass, "tut02", "frag-position.vert", "frag-position.frag") } fun shaderProgramOf(gl: GL2ES2, context: Class<*>, vararg strings: String): Int = with(gl) { val shaders = if (strings[0].contains('.')) strings.toList() else { val root = if (strings[0].endsWith('/')) strings[0] else strings[0] + '/' strings.drop(1).map { root + it } } val shaderProgram = ShaderProgram() val shaderCodes = shaders.map { shaderCodeOf(gl, context, it) } shaderCodes.forEach { shaderProgram.add(gl, it, System.err) } shaderProgram.link(gl, System.err) shaderCodes.forEach { glDetachShader(shaderProgram.program(), it.id()) glDeleteShader(it.id()) } return shaderProgram.program() } fun initializeVertexBuffer(gl: GL3) = with(gl) { glGenBuffer(vertexBufferObject) glBindBuffer(GL_ARRAY_BUFFER, vertexBufferObject) glBufferData(GL_ARRAY_BUFFER, vertexData, GL_STATIC_DRAW) glBindBuffer(GL_ARRAY_BUFFER) } override fun display(gl: GL3) = with(gl) { glClearBufferf(GL_COLOR) glUseProgram(theProgram) glBindBuffer(GL_ARRAY_BUFFER, vertexBufferObject) glEnableVertexAttribArray(glf.pos4) glVertexAttribPointer(glf.pos4) glDrawArrays(3) glDisableVertexAttribArray(glf.pos4) glUseProgram() } public override fun reshape(gl: GL3, w: Int, h: Int) = with(gl) { glViewport(w, h) } override fun end(gl: GL3) = with(gl) { glDeleteProgram(theProgram) glDeleteBuffer(vertexBufferObject) glDeleteVertexArray(vao) destroyBuffers(vertexBufferObject, vao, vertexData) } override fun keyPressed(keyEvent: KeyEvent) { when (keyEvent.keyCode) { KeyEvent.VK_ESCAPE -> quit() } } }
mit
71b2fa6769659265aa3ab410bb75fc44
25.324786
104
0.625974
3.979328
false
false
false
false
michael1011/blogdroid
app/src/main/java/at/michael1011/blogdroid/Main.kt
1
10879
package at.michael1011.blogdroid import android.app.ProgressDialog import android.content.Intent import android.content.SharedPreferences import android.os.Bundle import android.preference.PreferenceManager import android.support.design.widget.FloatingActionButton import android.support.design.widget.Snackbar import android.support.v4.content.ContextCompat import android.support.v4.widget.SwipeRefreshLayout import android.support.v7.app.AppCompatActivity import android.support.v7.widget.DividerItemDecoration import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.RecyclerView import android.text.Html import android.util.Log import android.view.Menu import android.view.MenuItem import android.view.View import android.widget.TextView import at.michael1011.blogdroid.database.Database import at.michael1011.blogdroid.database.DatabaseHelper import at.michael1011.blogdroid.database.Post import at.michael1011.blogdroid.explorer.Explorer import com.android.volley.AuthFailureError import com.android.volley.Request import com.android.volley.RequestQueue import com.android.volley.Response import com.android.volley.toolbox.StringRequest import com.android.volley.toolbox.Volley import org.json.JSONObject import java.text.SimpleDateFormat import java.util.* // todo: improve error handling // When the boolean "refresh" is added to the Intent of this activity the refresh function is called class Main : AppCompatActivity() { private val logTag = Main::class.java.simpleName var db: DatabaseHelper? = null var queue: RequestQueue? = null var swipe: SwipeRefreshLayout? = null var adapter: PostsAdapter? = null var darkTheme = false var posts = ArrayList<Post>() override fun onCreate(bundle: Bundle?) { super.onCreate(bundle) prefs = PreferenceManager.getDefaultSharedPreferences(this) if (prefs!!.getString(getString(R.string.prefsUrl), "")!!.isEmpty()) { Log.d(logTag, "Not logged in yet. Opening Login activity") startActivity(Intent(this, Login::class.java)) finish() } darkTheme = checkForDarkTheme(this) setContentView(R.layout.main_activity) db = DatabaseHelper(this) queue = Volley.newRequestQueue(this) swipe = findViewById(R.id.main_swipe) as SwipeRefreshLayout swipe!!.setColorSchemeColors(ContextCompat.getColor(this, R.color.colorPrimary), ContextCompat.getColor(this, R.color.colorPrimaryDark), ContextCompat.getColor(this, R.color.colorAccent)) swipe!!.setOnRefreshListener { refresh() } val recycler = findViewById(R.id.main_recycler) as RecyclerView posts = Database.getAllPosts(db!!.readableDatabase) adapter = PostsAdapter(posts) val layoutManager = LinearLayoutManager(this) val itemDec = DividerItemDecoration(this, layoutManager.orientation) recycler.addItemDecoration(itemDec) recycler.layoutManager = layoutManager recycler.adapter = adapter val fab = findViewById(R.id.main_fab) as FloatingActionButton recycler.addOnScrollListener(object : RecyclerView.OnScrollListener() { override fun onScrolled(recyclerView: RecyclerView?, dx: Int, dy: Int) { super.onScrolled(recyclerView, dx, dy) if (dy > 0) { fab.hide() } else if (dy < 0) { fab.show() } } }) fab.setOnClickListener { view -> Log.i(logTag, "Opening new post") startActivity(Intent(view.context, Editor::class.java)) } if (darkTheme) { swipe!!.setProgressBackgroundColorSchemeColor(ContextCompat.getColor(this, R.color.darkToolbar)) fab.setColorFilter(ContextCompat.getColor(this, R.color.darkToolbar)) } if (intent.getBooleanExtra("refresh", false) || Application.syncOnStart) { Application.syncOnStart = false refresh() } } // Is used in combination with the Editor override fun onStart() { super.onStart() if (prefs!!.getBoolean(getString(R.string.prefsDarkTheme), false) != darkTheme) { recreate() } if (refresh) { refresh = false refresh() } } override fun onCreateOptionsMenu(menu: Menu): Boolean { menuInflater.inflate(R.menu.main_menu, menu) return super.onCreateOptionsMenu(menu) } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { R.id.main_explorer -> startActivity(Intent(this, Explorer::class.java)) R.id.main_settings -> startActivity(Intent(this, Settings::class.java)) R.id.main_logout -> { val edit = prefs!!.edit() edit.remove(getString(R.string.prefsUrl)) edit.remove(getString(R.string.prefsCredentials)) edit.apply() startActivity(Intent(this, Login::class.java)) finish() } } return super.onOptionsItemSelected(item) } private fun refresh() { Log.i(logTag, "Updating posts...") swipe!!.isRefreshing = true val url = prefs!!.getString(getString(R.string.prefsUrl), "") + "api/v1/posts" val request = object : StringRequest(Request.Method.GET, url, Response.Listener<String> { response -> try { Log.v(logTag, "Response: " + response) val json = JSONObject(response) if (json.getBoolean("Auth")) { val dbWrite = db!!.writableDatabase dbWrite.execSQL("DELETE FROM " + Database.tableName) posts.clear() val jsonPosts = json.getJSONArray("Response") for (i in 0..jsonPosts.length() - 1) { val jsonPost = jsonPosts.getJSONObject(i) val rawDate = jsonPost.getString("Date") // rawDate could look like this: 2016-12-25T12:43:39Z val date = Main.dateParser.parse(rawDate.substring(0, rawDate.length - 1).replace("T", " ")) val post = Post(jsonPost.getString("Title"), date, jsonPost.getBoolean("Draft"), jsonPost.getString("Content")) Log.v(logTag, "Adding post '" + post.title + "' to database") Database.addPost(post, dbWrite) posts.add(post) } dbWrite.close() adapter!!.notifyDataSetChanged() swipe!!.isRefreshing = false return@Listener } else { Log.d(logTag, "The credentials aren't correct anymore") } } catch (e: Exception) { e.printStackTrace() Log.d(logTag, "Failed to parse response") } swipe!!.isRefreshing = false showSnackBar(findViewById(R.id.main_swipe), darkTheme, R.string.unknownError) }, Response.ErrorListener { error -> try { Log.i(logTag, "Request failed with code: " + error.networkResponse.statusCode) } catch (e: Exception) { Log.i(logTag, "Request failed") Log.d(logTag, "Trying to get information from the request threw: ", e) } swipe!!.isRefreshing = false showSnackBar(findViewById(R.id.main_swipe), darkTheme, R.string.unknownError) }) { @Throws(AuthFailureError::class) override fun getHeaders(): Map<String, String> { val headers = HashMap<String, String>() headers.put("Authorization", "Basic " + prefs!!.getString(getString(R.string.prefsCredentials), "")!!) return headers } } queue!!.add(request) } companion object { val dateParser = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault()) val dateFormatter = SimpleDateFormat("dd/MM/yyyy", Locale.getDefault()) var refresh = false var prefs: SharedPreferences? = null fun checkForDarkTheme(activity: AppCompatActivity): Boolean { if (prefs!!.getBoolean(activity.getString(R.string.prefsDarkTheme), false)) { if (activity.localClassName == "at.michael1011.blogdroid.Login") { activity.setTheme(R.style.AppTheme_Dark_Login) } else { activity.setTheme(R.style.AppTheme_Dark) val actionBar = activity.supportActionBar val actionBarTitle = "<font color='#424242'>" + actionBar!!.title + "</font>" // Sorry for that @Suppress("DEPRECATION") if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) { actionBar.title = Html.fromHtml(actionBarTitle, Html.FROM_HTML_MODE_LEGACY) } else { actionBar.title = Html.fromHtml(actionBarTitle) } actionBar.setHomeAsUpIndicator(R.drawable.arrow_black) actionBar.themedContext.setTheme(R.style.AppTheme_Dark_Toolbar) } return true } return false } fun showLoadingDialog(activity: AppCompatActivity, title: String, message: String, darkTheme: Boolean = false): ProgressDialog { val dialog: ProgressDialog if (activity.localClassName == "at.michael1011.blogdroid.Login" && !darkTheme) { dialog = ProgressDialog(activity, R.style.AppTheme_Login_Dialog) } else { dialog = ProgressDialog(activity) } dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER) dialog.setCancelable(false) dialog.setTitle(title) dialog.setMessage(message) dialog.show() return dialog } fun showSnackBar(view: View, darkTheme: Boolean, message: Int) { val snackBar = Snackbar.make(view, message, Snackbar.LENGTH_SHORT) val snackBarText = snackBar.view.findViewById(android.support.design.R.id.snackbar_text) as TextView var textColor = R.color.white if (darkTheme) { textColor = R.color.textColorDark } snackBarText.setTextColor(ContextCompat.getColor(view.context, textColor)) snackBar.show() } } }
mit
0db9dd839328f42a753f93f37e004087
31.768072
136
0.602261
4.841567
false
false
false
false
lvtanxi/TanxiNote
app/src/main/java/com/lv/note/widget/WuWebView.kt
1
6927
package com.lv.note.widget import android.content.Context import android.content.Intent import android.net.Uri import android.net.http.SslError import android.os.Message import android.support.v4.content.ContextCompat import android.support.v7.app.AlertDialog import android.util.AttributeSet import android.view.KeyEvent import android.view.View import android.webkit.* import android.widget.AbsoluteLayout import android.widget.ProgressBar import android.widget.TextView import com.lv.note.R import com.lv.note.util.ToastUtils /** * User: 吕勇 * Date: 2016-04-29 * Time: 12:39 * Description:WuWebView */ class WuWebView(context: Context, attrs: AttributeSet) : WebView(context, attrs) { private var progressBar: ProgressBar? = null private var titleTv: TextView? = null private var mMap: Map<String, String>? = null private var mLoadFinish: WebViewLoadInterface? = null private var mBuilder: AlertDialog.Builder? = null init { initWebView() } /** * 初始化WebView */ private fun initWebView() { clearCache(true) progressBar = ProgressBar(context, null, android.R.attr.progressBarStyleHorizontal) progressBar!!.progressDrawable = ContextCompat.getDrawable(context, R.drawable.webview_progress_bar) progressBar!!.layoutParams = AbsoluteLayout.LayoutParams(AbsoluteLayout.LayoutParams.MATCH_PARENT, 5, 0, 0) addView(progressBar) val webSettings = this.settings webSettings.javaScriptEnabled = true webSettings.javaScriptCanOpenWindowsAutomatically = true webSettings.useWideViewPort = true//关键点 webSettings.defaultTextEncodingName = "utf-8" webSettings.domStorageEnabled = true webSettings.loadWithOverviewMode = true webSettings.allowFileAccess = true webSettings.layoutAlgorithm = WebSettings.LayoutAlgorithm.SINGLE_COLUMN requestFocus() requestFocusFromTouch() setWebChromeClient(MyWebChromeClient()) setWebViewClient(MyWebViewClient()) setDownloadListener(MyWebViewDownLoadListener()) } override fun onDetachedFromWindow() { mMap = null mLoadFinish = null progressBar = null super.onDetachedFromWindow() } override fun loadUrl(url: String) { super.loadUrl(url, mMap) } override fun loadUrl(url: String, additionalHttpHeaders: Map<String, String>) { super.loadUrl(url, additionalHttpHeaders) this.mMap = additionalHttpHeaders } /** * 显示标题的view * @param title textview */ fun setTitleView(title: TextView) { this.titleTv = title } /** * 设置加载字符串 * @param data */ fun loadTextData(data: String) { loadData(data, "text/html", "utf-8") } inner class MyWebChromeClient : WebChromeClient() { override fun onReceivedTitle(view: WebView, title: String) { super.onReceivedTitle(view, title) if (null != titleTv) titleTv!!.text = title } override fun onProgressChanged(view: WebView, newProgress: Int) { progressBar?.let { if (newProgress == 100) { progressBar!!.visibility = View.GONE } else { if (progressBar!!.visibility == View.GONE) progressBar!!.visibility = View.VISIBLE progressBar!!.progress = newProgress } } super.onProgressChanged(view, newProgress) } override fun onJsConfirm(view: WebView?, url: String?, message: String?, result: JsResult?): Boolean { if (null == mBuilder) { mBuilder = AlertDialog.Builder(context) mBuilder!!.setTitle("檀溪提示您:") mBuilder!!.setCancelable(false) mBuilder!!.setPositiveButton("确定") { dialog, which -> result!!.confirm() } mBuilder!!.setNegativeButton("取消") { dialog, which -> result!!.cancel() } mBuilder!!.setOnKeyListener { dialogInterface, i, keyEvent -> true} } mBuilder!!.setMessage(message) mBuilder!!.create() mBuilder!!.show() return true } override fun onJsAlert(view: WebView, url: String, message: String, result: JsResult): Boolean { ToastUtils.textToastError(view.context, message) result.confirm() return true } } private inner class MyWebViewDownLoadListener : DownloadListener { override fun onDownloadStart(url: String, userAgent: String, contentDisposition: String, mimetype: String, contentLength: Long) { val uri = Uri.parse(url) val intent = Intent(Intent.ACTION_VIEW, uri) context.startActivity(intent) } } inner class MyWebViewClient : WebViewClient() { override fun onReceivedSslError(view: WebView, handler: SslErrorHandler, error: SslError) { handler.proceed()//接受证书 } override fun onPageFinished(view: WebView, url: String) { super.onPageFinished(view, url) if (null != mLoadFinish) mLoadFinish!!.onLoadFinish() } override fun onFormResubmission(view: WebView?, dontResend: Message?, resend: Message?) { resend?.sendToTarget() super.onFormResubmission(view, dontResend, resend) } override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean { if (url.startsWith("tel:")) { val intent = Intent(Intent.ACTION_VIEW, Uri.parse(url)) context.startActivity(intent) return true } else if (url.startsWith("http") && view.hitTestResult == null) { view.loadUrl(url);// 自身加载新连接不做外部跳转 return true; } return false } } override fun onScrollChanged(l: Int, t: Int, oldl: Int, oldt: Int) { val lp = progressBar!!.layoutParams as AbsoluteLayout.LayoutParams lp.x = l lp.y = t progressBar!!.layoutParams = lp super.onScrollChanged(l, t, oldl, oldt) } fun setLoadFinish(loadInterface: WebViewLoadInterface) { mLoadFinish = loadInterface } /** * 返回按键监听 */ override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean { if (keyCode == KeyEvent.KEYCODE_BACK && this.canGoBack()) { this.goBack() if (null != mLoadFinish) mLoadFinish!!.onBack() return true } return super.onKeyDown(keyCode, event) } interface WebViewLoadInterface { fun onLoadFinish() fun onBack() } }
apache-2.0
331a660789e4e140bc90abce7ab10a9c
31.032864
137
0.617324
4.734906
false
false
false
false
manami-project/manami
manami-app/src/main/kotlin/io/github/manamiproject/manami/app/migration/DefaultMetaDataMigrationHandler.kt
1
7926
package io.github.manamiproject.manami.app.migration import io.github.manamiproject.manami.app.cache.* import io.github.manamiproject.manami.app.cache.Caches import io.github.manamiproject.manami.app.commands.GenericReversibleCommand import io.github.manamiproject.manami.app.commands.history.CommandHistory import io.github.manamiproject.manami.app.commands.history.DefaultCommandHistory import io.github.manamiproject.manami.app.events.EventBus import io.github.manamiproject.manami.app.events.SimpleEventBus import io.github.manamiproject.manami.app.lists.Link import io.github.manamiproject.manami.app.lists.animelist.AnimeListEntry import io.github.manamiproject.manami.app.lists.ignorelist.IgnoreListEntry import io.github.manamiproject.manami.app.lists.watchlist.WatchListEntry import io.github.manamiproject.manami.app.state.InternalState import io.github.manamiproject.manami.app.state.State import io.github.manamiproject.modb.core.config.Hostname import io.github.manamiproject.modb.core.models.Anime internal class DefaultMetaDataMigrationHandler( private val cache: AnimeCache = Caches.defaultAnimeCache, private val eventBus: EventBus = SimpleEventBus, private val commandHistory: CommandHistory = DefaultCommandHistory, private val state: State = InternalState, ) : MetaDataMigrationHandler { override fun checkMigration(metaDataProviderFrom: Hostname, metaDataProviderTo: Hostname) { require(cache.availableMetaDataProvider.contains(metaDataProviderFrom)) { "MetaDataProvider [$metaDataProviderFrom] is not supported." } require(cache.availableMetaDataProvider.contains(metaDataProviderTo)) { "MetaDataProvider [$metaDataProviderTo] is not supported." } val animeList = state.animeList().filter { it.link is Link }.filter { it.link.asLink().uri.host == metaDataProviderFrom } val watchList = state.watchList().filter { it.link.asLink().uri.host == metaDataProviderFrom } val ignoreList = state.ignoreList().filter { it.link.asLink().uri.host == metaDataProviderFrom } val totalNumberOfTasks = animeList.size + watchList.size + ignoreList.size val animeListEntriesWithoutMapping = mutableListOf<AnimeListEntry>() val animeListEntiresMultipleMappings = mutableMapOf<AnimeListEntry, Set<Link>>() val animeListMappings = mutableMapOf<AnimeListEntry, Link>() animeList.forEachIndexed { index, animeListEntry -> val newMetaDataProviderLinks = cache.mapToMetaDataProvider(animeListEntry.link.asLink().uri, metaDataProviderTo) when { newMetaDataProviderLinks.isEmpty() -> animeListEntriesWithoutMapping.add(animeListEntry) newMetaDataProviderLinks.size > 1 -> { val cacheEntries = newMetaDataProviderLinks.map { cache.fetch(it) as PresentValue<Anime>}.map { it.value }.flatMap { it.sources }.map { Link(it) } animeListEntiresMultipleMappings[animeListEntry] = cacheEntries.toSet() } else -> { val cacheEntry = cache.fetch(newMetaDataProviderLinks.first()) as PresentValue<Anime> animeListMappings[animeListEntry] = Link(cacheEntry.value.sources.first()) } } eventBus.post(MetaDataMigrationProgressEvent(index + 1, totalNumberOfTasks)) } val watchListEntriesWithoutMapping = mutableListOf<WatchListEntry>() val watchListEntiresMultipleMappings = mutableMapOf<WatchListEntry, Set<Link>>() val watchListMappings = mutableMapOf<WatchListEntry, Link>() watchList.forEachIndexed { index, watchListEntry -> val newMetaDataProviderLinks = cache.mapToMetaDataProvider(watchListEntry.link.asLink().uri, metaDataProviderTo) when { newMetaDataProviderLinks.isEmpty() -> watchListEntriesWithoutMapping.add(watchListEntry) newMetaDataProviderLinks.size > 1 -> { val cacheEntries = newMetaDataProviderLinks.map { cache.fetch(it) as PresentValue<Anime>}.map { it.value }.flatMap { it.sources }.map { Link(it) } watchListEntiresMultipleMappings[watchListEntry] = cacheEntries.toSet() } else -> { val cacheEntry = cache.fetch(newMetaDataProviderLinks.first()) as PresentValue<Anime> watchListMappings[watchListEntry] = Link(cacheEntry.value.sources.first()) } } eventBus.post(MetaDataMigrationProgressEvent(animeList.size + index + 1, totalNumberOfTasks)) } val ignoreListEntriesWithoutMapping = mutableListOf<IgnoreListEntry>() val ignoreListEntiresMultipleMappings = mutableMapOf<IgnoreListEntry, Set<Link>>() val ignoreListMappings = mutableMapOf<IgnoreListEntry, Link>() ignoreList.forEachIndexed { index, ignoreListEntry -> val newMetaDataProviderLinks = cache.mapToMetaDataProvider(ignoreListEntry.link.asLink().uri, metaDataProviderTo) when { newMetaDataProviderLinks.isEmpty() -> ignoreListEntriesWithoutMapping.add(ignoreListEntry) newMetaDataProviderLinks.size > 1 -> { val cacheEntries = newMetaDataProviderLinks.map { cache.fetch(it) as PresentValue<Anime>}.map { it.value }.flatMap { it.sources }.map { Link(it) } ignoreListEntiresMultipleMappings[ignoreListEntry] = cacheEntries.toSet() } else -> { val cacheEntry = cache.fetch(newMetaDataProviderLinks.first()) as PresentValue<Anime> ignoreListMappings[ignoreListEntry] = Link(cacheEntry.value.sources.first()) } } eventBus.post(MetaDataMigrationProgressEvent(animeList.size + watchList.size + index + 1, totalNumberOfTasks)) } eventBus.post( MetaDataMigrationResultEvent( animeListEntriesWithoutMapping = animeListEntriesWithoutMapping, animeListEntiresMultipleMappings = animeListEntiresMultipleMappings, animeListMappings = animeListMappings, watchListEntriesWithoutMapping = watchListEntriesWithoutMapping, watchListEntiresMultipleMappings = watchListEntiresMultipleMappings, watchListMappings = watchListMappings, ignoreListEntriesWithoutMapping = ignoreListEntriesWithoutMapping, ignoreListEntiresMultipleMappings = ignoreListEntiresMultipleMappings, ignoreListMappings = ignoreListMappings, ) ) } override fun migrate( animeListMappings: Map<AnimeListEntry, Link>, watchListMappings: Map<WatchListEntry, Link>, ignoreListMappings: Map<IgnoreListEntry, Link>, ) { GenericReversibleCommand( state = state, commandHistory = commandHistory, command = CmdMigrateEntries( animeListMappings = animeListMappings, watchListMappings = watchListMappings, ignoreListMappings = ignoreListMappings, ) ).execute() } override fun removeUnmapped( animeListEntriesWithoutMapping: Collection<AnimeListEntry>, watchListEntriesWithoutMapping: Collection<WatchListEntry>, ignoreListEntriesWithoutMapping: Collection<IgnoreListEntry>, ) { GenericReversibleCommand( state = state, commandHistory = commandHistory, command = CmdRemoveUnmappedMigrationEntries( animeListEntriesWithoutMapping = animeListEntriesWithoutMapping, watchListEntriesWithoutMapping = watchListEntriesWithoutMapping, ignoreListEntriesWithoutMapping = ignoreListEntriesWithoutMapping, ) ).execute() } }
agpl-3.0
cc72a7639482b6a6af041c067f9cdd1d
52.92517
166
0.696442
5.217907
false
false
false
false
cketti/k-9
mail/common/src/main/java/com/fsck/k9/mail/ssl/LocalKeyStore.kt
1
5803
package com.fsck.k9.mail.ssl import com.fsck.k9.logging.Timber import java.io.File import java.io.FileInputStream import java.io.FileNotFoundException import java.io.FileOutputStream import java.io.IOException import java.security.KeyStore import java.security.KeyStoreException import java.security.NoSuchAlgorithmException import java.security.cert.Certificate import java.security.cert.CertificateException import java.security.cert.X509Certificate private const val KEY_STORE_FILE_VERSION = 1 private val PASSWORD = charArrayOf() class LocalKeyStore(private val directoryProvider: KeyStoreDirectoryProvider) { private var keyStoreFile: File? = null private val keyStoreDirectory: File by lazy { directoryProvider.getDirectory() } private val keyStore: KeyStore? by lazy { initializeKeyStore() } @Synchronized private fun initializeKeyStore(): KeyStore? { upgradeKeyStoreFile() val file = getKeyStoreFile(KEY_STORE_FILE_VERSION) if (file.length() == 0L) { /* * The file may be empty (e.g., if it was created with * File.createTempFile). We can't pass an empty file to * Keystore.load. Instead, we let it be created anew. */ if (file.exists() && !file.delete()) { Timber.d("Failed to delete empty keystore file: %s", file.absolutePath) } } val fileInputStream = try { FileInputStream(file) } catch (e: FileNotFoundException) { // If the file doesn't exist, that's fine, too null } return try { keyStoreFile = file KeyStore.getInstance(KeyStore.getDefaultType()).apply { load(fileInputStream, PASSWORD) } } catch (e: Exception) { Timber.e(e, "Failed to initialize local key store") // Use of the local key store is effectively disabled. keyStoreFile = null null } finally { fileInputStream?.close() } } private fun upgradeKeyStoreFile() { if (KEY_STORE_FILE_VERSION > 0) { // Blow away version "0" because certificate aliases have changed. val versionZeroFile = getKeyStoreFile(0) if (versionZeroFile.exists() && !versionZeroFile.delete()) { Timber.d("Failed to delete old key-store file: %s", versionZeroFile.absolutePath) } } } @Synchronized @Throws(CertificateException::class) fun addCertificate(host: String, port: Int, certificate: X509Certificate?) { val keyStore = this.keyStore ?: throw CertificateException("Certificate not added because key store not initialized") try { keyStore.setCertificateEntry(getCertKey(host, port), certificate) } catch (e: KeyStoreException) { throw CertificateException("Failed to add certificate to local key store", e) } writeCertificateFile() } private fun writeCertificateFile() { val keyStore = requireNotNull(this.keyStore) FileOutputStream(keyStoreFile).use { keyStoreStream -> try { keyStore.store(keyStoreStream, PASSWORD) } catch (e: FileNotFoundException) { throw CertificateException("Unable to write KeyStore: ${e.message}", e) } catch (e: CertificateException) { throw CertificateException("Unable to write KeyStore: ${e.message}", e) } catch (e: IOException) { throw CertificateException("Unable to write KeyStore: ${e.message}", e) } catch (e: NoSuchAlgorithmException) { throw CertificateException("Unable to write KeyStore: ${e.message}", e) } catch (e: KeyStoreException) { throw CertificateException("Unable to write KeyStore: ${e.message}", e) } } } @Synchronized fun isValidCertificate(certificate: Certificate, host: String, port: Int): Boolean { val keyStore = this.keyStore ?: return false return try { val storedCert = keyStore.getCertificate(getCertKey(host, port)) if (storedCert == null) { Timber.v("Couldn't find a stored certificate for %s:%d", host, port) false } else if (storedCert != certificate) { Timber.v( "Stored certificate for %s:%d doesn't match.\nExpected:\n%s\nActual:\n%s", host, port, storedCert, certificate ) false } else { Timber.v("Stored certificate for %s:%d matches the server certificate", host, port) true } } catch (e: KeyStoreException) { Timber.w(e, "Error reading from KeyStore") false } } @Synchronized fun deleteCertificate(oldHost: String, oldPort: Int) { val keyStore = this.keyStore ?: return try { keyStore.deleteEntry(getCertKey(oldHost, oldPort)) writeCertificateFile() } catch (e: KeyStoreException) { // Ignore: most likely there was no cert. found } catch (e: CertificateException) { Timber.e(e, "Error updating the local key store file") } } private fun getKeyStoreFile(version: Int): File { return if (version < 1) { File(keyStoreDirectory, "KeyStore.bks") } else { File(keyStoreDirectory, "KeyStore_v$version.bks") } } private fun getCertKey(host: String, port: Int): String { return "$host:$port" } }
apache-2.0
7a3f944fc52a2431fb66fd5ce7b3e869
34.820988
100
0.594692
4.807788
false
false
false
false
lice-lang/lice
src/test/kotlin/org/lice/FeatureTest.kt
1
12219
package org.lice import org.jetbrains.annotations.TestOnly import org.junit.Assert.assertEquals import org.junit.Test import java.math.BigDecimal import java.math.BigInteger import java.util.* /** * Demos for language feature * Created by ice1000 on 2017/4/1. * * @author ice1000 */ @TestOnly class FeatureTest { /** * test for string literals */ @Test(timeout = 1000) fun test1() { //language=Lice """(print "fuck")""" evalTo null //language=Lice """"lover~lover~fucker~fucker~"""" evalTo "lover~lover~fucker~fucker~" } /** * test for primitives literals */ @Test(timeout = 1000) fun test2() { //language=Lice "(print 233666)" evalTo null //language=Lice "233666" evalTo 233666 //language=Lice "233666.0" evalTo 233666F //language=Lice "233666.0000000000000000000000000000000" evalTo 233666.0 //language=Lice "true".shouldBeTrue() //language=Lice "false".shouldBeFalse() //language=Lice "null".shouldBeNull() } /** * test for plus minus times devide */ @Test(timeout = 1000) fun test3() { //language=Lice "(+ 1 (+ 1 2 3))" evalTo 7 //language=Lice "(- 1 (+ 1 2 3))" evalTo -5 //language=Lice "(* 4 (+ 2 3))" evalTo 20 //language=Lice "(+)" evalTo 0 //language=Lice "(-)" evalTo 0 //language=Lice "(* 4 (+ 2 3))" evalTo 20 } /** * test for big integers */ @Test(timeout = 1000) fun test4() { //language=Lice "(+ 10000000000000000000000000000000N 233)" evalTo BigInteger("10000000000000000000000000000233") //language=Lice "(- 10000000000000000000000000000000N 233)" evalTo BigInteger("9999999999999999999999999999767") //language=Lice "(* 10000000000000000000000000000000N 233)" evalTo BigInteger("2330000000000000000000000000000000") //language=Lice "(/ 10000000000000000000000000000000N 233)" evalTo BigInteger("42918454935622317596566523605") //language=Lice "(% 10000000000000000000000000000000N 233)" evalTo BigInteger("35") "0xDBEN" evalTo BigInteger(0xDBE.toString()) } /** * test for big decimals */ @Test(timeout = 1000) fun test5() { //language=Lice "(+ 10000000000000000000000000000000N 0.233)" evalTo BigDecimal("10000000000000000000000000000000.233") //language=Lice "(+ 100000000000000000000000000M 1)" evalTo BigDecimal("100000000000000000000000001") //language=Lice "(- 10000000000000000000000000000000N 0.233)" evalTo BigDecimal("9999999999999999999999999999999.767") //language=Lice "(- 100000000000000000000000000M 1)" evalTo BigDecimal("99999999999999999999999999") //language=Lice "(* 10000000000000000000000000000000N 0.233)" evalTo BigDecimal("2330000000000000000000000000000.000") //language=Lice "(* 100000000000000000000000000M 1)" evalTo BigDecimal("100000000000000000000000000") //language=Lice "(/ 10000000000000000000000000000000N 0.233)" evalTo BigDecimal("42918454935622317596566523605150") //language=Lice "(/ 100000000000000000000000000M 1)" evalTo BigDecimal("100000000000000000000000000") //language=Lice "(% 10000000000000000000000000000000N 0.233)" evalTo BigDecimal("0.05") //language=Lice "(% 100000000000000000000000000M 1)" evalTo BigDecimal("0") } /** * comparision */ @Test(timeout = 1000) fun test6() { //language=Lice "(>= 9 8 7 7 6 6 6 5 4 3 1 -1)".shouldBeTrue() //language=Lice "(>= 9 8 7 7 6 6 6 5 8 3 1 -1)".shouldBeFalse() } /** * string connection */ @Test(timeout = 1000) fun test7() { //language=Lice """ (str-con "boy" "Next" "Door") """ evalTo "boyNextDoor" //language=Lice """ (format "%s%s%s" "boy" "Next" "Door") """ evalTo "boyNextDoor" } /** * parsing string */ @Test(timeout = 1000) fun test8() { //language=Lice """ (str->int "0xDBE") """ evalTo 0xDBE } /** * string evaluation */ @Test(timeout = 1000) fun test9() { //language=Lice """ (eval "(+ 1 1)") """ evalTo 2 } /** * run/begin block */ @Test(timeout = 1000) fun test10() { //language=Lice "(|> (+ 1 1) (+ 2 2))" evalTo 4 } /** * force running */ @Test(timeout = 1000) fun test11() { //language=Lice "(force|> (+ () ()))".shouldBeNull() //language=Lice "()".shouldBeNull() } /** * variable */ @Test(timeout = 1000) fun test12() { //language=Lice """ (-> ice1000 233) ice1000 """ evalTo 233 } /** * function */ @Test(timeout = 1000) fun test13() { //language=Lice """ (defexpr ice1000 233) (ice1000) """ evalTo 233 //language=Lice """ (defexpr ice1000 a a) (ice1000 233) """ evalTo 233 } /** * recursion */ @Test(timeout = 1000) fun test14() { //language=TEXT """ (def gcd a b (if (=== b 0) a (gcd b (% a b)))) (gcd 15 20) """ evalTo 5 //language=TEXT """ (def in? ls a (> (count ls a) 0)) (def fib n (if (> 2 n) 1 (+ (fib (- n 1)) (fib (- n 2))))) (fib 10) """ evalTo 89 } /** * if condition */ @Test(timeout = 1000) fun test15() { //language=Lice "(if (>= 9 8 7 7 6 6 6 5 4 3 1 -1) 1 (+ 1 1))" evalTo 1 //language=Lice "(if (>= 9 8 7 7 6 6 6 5 8 3 1 -1) 1 (+ 1 1))" evalTo 2 } /** * when condition */ @Test(timeout = 1000) fun test16() { """(when (!== 1 1), 233 (=== 1 1), 666 )""" evalTo 666 """(when (!== 1 1), 233 (=== 2 1), 666 123 )""" evalTo 123 } /** * while loop */ @Test(timeout = 1000) fun test17() { //language=Lice """ (def exp-mod a b m (|> (-> ret 1) (while (!= 0 b) (|> (if (!= 0 (& b 1)) (-> ret (% (* a ret) m))) (-> b (/ b 2)) (-> a (% (* a a) m)))) ret)) (exp-mod 23 2 26) """ evalTo 9 } /** * lazy evaluation */ @Test fun test18() { //language=Lice """ (deflazy fuck a b b) (-> lover 233) (fuck (-> lover 666) null) lover """ evalTo 233 //language=Lice """ (def fuck a b b) (-> lover 233) (fuck (-> lover 666) null) lover """ evalTo 666 //language=Lice """ (deflazy fuck a b (|> b b)) (-> lover 233) (fuck null (-> lover (+ lover 1))) """ evalTo 233 + 1 } /** * assignment */ @Test(timeout = 1000) fun test19() { //language=Lice """ (-> ice1k 233) ice1k """ evalTo 233 } /** * literals */ @Test(timeout = 1000) fun test20() { //language=Lice "null".shouldBeNull() //language=Lice "true".shouldBeTrue() //language=Lice "false".shouldBeFalse() } @Test(timeout = 1000) fun test21() { Lice.run("12a") Lice.run("fun") } /** * trigonometric */ @Test(timeout = 1000) fun test22() { val r = Random(System.currentTimeMillis()) .nextDouble() //language=Lice assertEquals(Math.sin(r), Lice.run("(sin ${BigDecimal(r).toPlainString()})") as Double, 1e-10) } /** * nested expression */ @Test(timeout = 1000) fun test25() { //language=Lice "((((2))))" evalTo 2 //language=Lice "(if true 0 1)" evalTo 0 } /** * returning an expression */ @Test(timeout = 1000) fun test26() { //language=Lice "((if false * /) 11 11)" evalTo 1 //language=Lice "((if true * /) 11 11)" evalTo 121 } /* * (((if true + -)) 11 11) * ((+) 11 11) * (+ 11 11) * 22 */ @Test(timeout = 1000) fun test27() { //language=Lice "((if true + -) 11 11)" evalTo 22 //language=Lice "((if true + -) 11 11)" evalTo 22 } /** * yes, it's true! * lambda expression! */ @Test(timeout = 1000) fun test28() { //language=Lice "((lambda a b (+ a b)) 120 230)" evalTo 120 + 230 //language=Lice "((lambda a b (* a b)) 120 230)" evalTo 120 * 230 //language=Lice "((lambda a (+ a a)) 233)" evalTo 466 } /** * yes, it's true! * expr(call by name) and lazy(call by need)! */ @Test(timeout = 1000) fun test29() { //language=Lice """ ((lazy unused "any-val") (|> (def side-effect true) 233)) (def? side-effect) """.shouldBeFalse() //language=Lice """ (-> side-effect 10) ((expr used-twice (+ used-twice used-twice)) (|> (-> side-effect (+ side-effect 1)) 233)) side-effect """ evalTo 12 //language=Lice """ (-> side-effect 10) ((lambda used-twice (+ used-twice used-twice)) (|> (-> side-effect (+ side-effect 1)) 233)) side-effect """ evalTo 11 } /** * function as parameter */ @Test(timeout = 1000) fun test31() { //language=Lice """ (defexpr fuck op (op true 1 2)) (fuck if) """ evalTo 1 //language=Lice """ (deflazy unless condition a b (if condition b a)) (defexpr fuck op (op true 1 2)) (fuck unless) """ evalTo 2 //language=Lice """ (defexpr fuck op (op 1 2 3 4)) (fuck +) """ evalTo 10 } /** * expr will keep the parameter everywhere * lazy will eval params when first invoked * lambda will eval params before invoked * * conclusion: if you want to pass 'function' * as parameter, please use 'expr'. */ @Test(timeout = 1000) fun test32() { //language=Lice "((expr op (op 1 2)) +)" evalTo 3 //language=Lice "((lazy op (op 1 2)) +)" evalTo 3 //language=Lice "((lambda op (op 1 2)) +)" evalTo 3 //language=Lice """ (def fun a b (+ (* a a) (* b b))) ((lambda op (op 3 4)) fun) """ evalTo 25 } /** * lambda as parameter * * sample: defining a fold */ @Test(timeout = 1000) fun test33() { //language=Lice "((lambda op (op 1 2)) (lambda a b (+ a b)))" evalTo 3 //language=Lice "((lambda op (op 3 4)) (lambda a b (+ (* a a) (* b b))))" evalTo 25 } @Test fun test34() { //language=Lice """(format "Hello, %s", 233)""" evalTo "Hello, 233" //language=Lice "(int->hex 12)" evalTo "0x${12.toString(16)}" //language=Lice "(int->oct 12)" evalTo "0o${12.toString(8)}" //language=Lice "(int->bin 12)" evalTo "0b${12.toString(2)}" //language=Lice val randNum = Lice.run("(rand)") as Double //language=Lice "(sqrt $randNum)" evalTo Math.sqrt(randNum) //language=Lice "(log $randNum)" evalTo Math.log(randNum) //language=Lice "(log10 $randNum)" evalTo Math.log10(randNum) //language=Lice "(sin $randNum)" evalTo Math.sin(randNum) //language=Lice "(sinh $randNum)" evalTo Math.sinh(randNum) //language=Lice "(asin $randNum)" evalTo Math.asin(randNum) //language=Lice "(cos $randNum)" evalTo Math.cos(randNum) //language=Lice "(cosh $randNum)" evalTo Math.cosh(randNum) //language=Lice "(acos $randNum)" evalTo Math.acos(randNum) //language=Lice "(tan $randNum)" evalTo Math.tan(randNum) //language=Lice "(atan $randNum)" evalTo Math.atan(randNum) //language=Lice "(tanh $randNum)" evalTo Math.tanh(randNum) //language=Lice "(exp $randNum)" evalTo Math.exp(randNum) //language=Lice "(| $randNum $randNum)" evalTo (randNum.toInt() or randNum.toInt()) //language=Lice "(& $randNum $randNum)" evalTo (randNum.toInt() and randNum.toInt()) //language=Lice "(^ $randNum $randNum)" evalTo (randNum.toInt() xor randNum.toInt()) } @Test fun test35() { val randListOrigin = (0..((Math.random() * 200 + 100).toInt())).map { (Math.random() * 10000).toInt() } val randList = randListOrigin.joinToString(" ").let { "(list $it)" } val randList2Origin = (0..((Math.random() * 200 + 100).toInt())).map { (Math.random() * 10000).toInt() } val randList2 = randList2Origin.joinToString(" ").let { "(list $it)" } //language=Lice "(type $randList)" evalTo randListOrigin::class.java //language=Lice "(size $randList)" evalTo randListOrigin.size //language=Lice "(reverse $randList)" evalTo randListOrigin.reversed() //language=Lice "(!! $randList 0)" evalTo randListOrigin.first() //language=Lice "([| $randList)" evalTo randListOrigin.first() //language=Lice "(|] $randList)" evalTo randListOrigin.drop(1) //language=Lice "(last $randList)" evalTo randListOrigin.last() //language=Lice "(subtract $randList $randList2)" evalTo randListOrigin.subtract(randList2Origin) //language=Lice "(intersect $randList $randList2)" evalTo randListOrigin.intersect(randList2Origin) //language=Lice "(last $randList)" evalTo randListOrigin.last() //language=Lice "(++ $randList $randList)" evalTo randListOrigin + randListOrigin //language=Lice "(sort $randList $randList)" evalTo randListOrigin.sorted() //language=Lice "(count $randList 2)" evalTo randListOrigin.count { it == 2 } //language=Lice "(split (->str 123) 2)" evalTo "123".split("2") //language=Lice "(!! (array 1 2 3) 0)" evalTo 1 } }
gpl-3.0
2c42aa60d82f5c5ab1dbf4c96ace4007
19.536134
106
0.613307
2.76761
false
true
false
false
guillaume-chs/LeCompteEstBon
src/main/kotlin/business/Solver.kt
1
5666
package business /** * main.kotlin.Solver for {@link business.LeCompteEstBon} game. * * @author Guillaume Chanson * @version 1.0 */ class Solver(val toGuess: Int, val numbers: IntArray) { // L'ensemble des partitions de plaquettes private var nbCounter = 0 private val nbNumbers = numbers.size private val allNbrPossibilities = Array(factoriel(nbNumbers)) { IntArray(nbNumbers) } // L'alphabet des opérateurs private var opCounter = 0 private val alphabet = charArrayOf('+', '-', '*', '/') private val tempAllOpPossibilities = Array(Math.pow(alphabet.size.toDouble(), nbNumbers - 1.0).toInt()) { CharArray(nbNumbers - 1) } // Best solution private var closest = 0 private var closestPath = "" /** * A first naive algorithm to "brute-force" find a solution (or closest one). */ fun naiveAlgorithm() { println("\n*** Solving ... ***") // On trouve toutes les permutations permute(numbers, 0) // On calcule toutes les combinaison de signe possibleStrings(nbNumbers - 1, alphabet, "") // TODO : enlever les doublons (priorités, parenthèses ...) // On rajoute un "+" devant toutes les combinaisons calculées (afin de calculer facilement toutes les possibilités plus tard) val allOpPossibilities = Array(Math.pow(alphabet.size.toDouble(), (nbNumbers - 1).toDouble()).toInt()) { CharArray(nbNumbers) } for (i in allOpPossibilities.indices) { for (j in 0..allOpPossibilities[0].size - 1) { if (j == 0) allOpPossibilities[i][0] = '+' else allOpPossibilities[i][j] = tempAllOpPossibilities[i][j - 1] } } var tries = 0 var rejected = 0 // Calcule toutes les possibilités de jeu mainloop@ for (op in allOpPossibilities) { triesloop@ for (i in allNbrPossibilities.indices) { var tmpResult = 0 var tmpPath = "" for (j in 0..nbNumbers - 1) { tries++ val result = calcule(op[j], tmpResult, allNbrPossibilities[i][j]) if (result - Math.round(result) != 0.0F) { rejected++ break@triesloop } tmpResult = Math.round(result) tmpPath = tmpPath + op[j] + Integer.toString(allNbrPossibilities[i][j]) if (Math.abs(tmpResult - toGuess) < Math.abs(closest - toGuess)) { closest = tmpResult closestPath = tmpPath if (closest == toGuess) { break@mainloop } } } } } if (closest == toGuess) { println("Le compte est bon ! $closestPath") } else { println("Le plus proche : $closest avec $closestPath") } println("\nOverall, $tries tries have been attempted, of which $rejected have been rejected") } /** * Calcule le factoriel du nombre entier positif donné. * * @param n paramètre de la fonction factoriel * @return le factoriel de {@code n} */ private fun factoriel(n: Int): Int = if (n <= 0) 1 else (1..n).reduce({ a, b -> a * b }) /** * Calcule toutes les combinaisons possibles et les ajoute dans {@code allNbrPossibilities}. * * @param input Le tableau de nombre dont on cherche les combinaisons * @param startindex Un index de départ (mettre 0 par défaut) */ private fun permute(input: IntArray, startindex: Int) { // End of recursion if (input.size == startindex + 1) { allNbrPossibilities[nbCounter] = input.copyOf() nbCounter++ return } for (i in startindex..input.size - 1) { val tmp = input.copyOf() tmp[i] = input[startindex] tmp[startindex] = input[i] permute(tmp, startindex + 1) } } /** * Prend le caractère d'un opérateur et deux nombres, puis calcule le resultat. * * @param op L'opérateur * @param nbr1 Nombre 1 * @param nbr2 Nombre 2 * @return Le résultat de l'opération */ private fun calcule(op: Char, nbr1: Int, nbr2: Int): Float { val n1 = nbr1.toFloat() val n2 = nbr2.toFloat() return when (op) { '+' -> n1 + n2 '-' -> n1 - n2 '*' -> n1 * n2 '/' -> n1 / n2 else -> throw IllegalArgumentException(op + " is not recognized") } } /** * Prend un alphabet, la longeur maximum des combinaisons, une chaine de caractère vide et modifie tempAllOpPossibilities * pour qu'il devienne un tableau de toutes les combinaisons de l'alphabet. * {a,b} , 3, "" => [aaa, aab, abb, bbb, bba, baa]. * * @param maxLength La longueur maximales des combinaisons * @param alphabet Un alphabet de symbole * @param curr Une chaine vide (utile pour la recursion) */ private fun possibleStrings(maxLength: Int, alphabet: CharArray, curr: String) { // End of recursion if (curr.length == maxLength) { tempAllOpPossibilities[opCounter] = curr.toCharArray() opCounter++ return } // Add each letter from the alphabet and process again for (a in alphabet) { possibleStrings(maxLength, alphabet, curr + a) } } }
gpl-3.0
357ae69e194566414c13a2948b6b51b6
33.457317
136
0.551504
3.883162
false
false
false
false
ericberman/MyFlightbookAndroid
app/src/main/java/com/myflightbook/android/webservices/MFBSoap.kt
1
6264
/* 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.webservices import android.content.Context import org.ksoap2.serialization.SoapObject import org.ksoap2.serialization.SoapSerializationEnvelope import com.myflightbook.android.R import org.ksoap2.SoapEnvelope import model.MFBConstants import org.ksoap2.transport.HttpTransportSE import org.ksoap2.HeaderProperty import android.net.ConnectivityManager import android.net.ConnectivityManager.NetworkCallback import android.net.Network import android.net.NetworkCapabilities import java.lang.Exception import java.lang.NullPointerException import java.util.* open class MFBSoap internal constructor() { var lastError = "" private var mMethodname = "" private var mRequest: SoapObject? = null interface MFBSoapProgressUpdate { fun notifyProgress(percentageComplete: Int, szMsg: String?) } @JvmField var mProgress: MFBSoapProgressUpdate? = null fun setMethod(szMethod: String): SoapObject { mMethodname = szMethod val obj = SoapObject(NAMESPACE, szMethod) mRequest = obj return obj } open fun addMappings(e: SoapSerializationEnvelope) {} enum class NetworkStatus { Unknown, Online, Offline } fun invoke(c: Context?): Any? { if (c == null) throw NullPointerException("null Context passed to Invoke") lastError = "" var o: Any? if (!isOnline(c)) { lastError = c.getString(R.string.errNoInternet) return null } if (mMethodname.isEmpty()) { lastError = "No method name specified" return null } if (mRequest == null) { lastError = "No request object set" return null } val envelope = SoapSerializationEnvelope(SoapEnvelope.VER11) envelope.dotNet = true // envelope.implicitTypes = true; addMappings(envelope) envelope.setOutputSoapObject(mRequest) val url = "https://" + MFBConstants.szIP + "/logbook/public/webservice.asmx" val androidHttpTransport = HttpTransportSE(url) androidHttpTransport.debug = MFBConstants.fIsDebug try { val headerList: MutableList<HeaderProperty?> = ArrayList() val l = Locale.getDefault() val szLocale = String.format("%s-%s", l.language, l.country) val hp = HeaderProperty("accept-language", szLocale) headerList.add(hp) androidHttpTransport.call(NAMESPACE + mMethodname, envelope, headerList) o = envelope.response } catch (e: Exception) { var szFault = e.message if (szFault == null) szFault = c.getString(R.string.errorSoapError) else if (szFault.contains(MFBConstants.szFaultSeparator)) { szFault = szFault.substring(szFault.lastIndexOf(MFBConstants.szFaultSeparator) + MFBConstants.szFaultSeparator.length) .replace("System.Exception: ", "") val iStartStackTrace = szFault.indexOf("\n ") if (iStartStackTrace > 0) szFault = szFault.substring(0, iStartStackTrace) } lastError = szFault o = null } // Un-comment one or the other lines above - if debug is true - to view raw XML: // String sRequestDump = androidHttpTransport.requestDump; // String sResponseDump = androidHttpTransport.responseDump; return o } companion object { const val NAMESPACE = "http://myflightbook.com/" private var mlastOnlineStatus = NetworkStatus.Unknown @JvmStatic fun startListeningNetwork(ctx: Context) { try { val connectivityManager = ctx.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager connectivityManager.registerDefaultNetworkCallback(object : NetworkCallback() { override fun onAvailable(network: Network) { mlastOnlineStatus = NetworkStatus.Online } override fun onLost(network: Network) { mlastOnlineStatus = NetworkStatus.Offline } } ) } catch (e: Exception) { mlastOnlineStatus = NetworkStatus.Unknown } } @JvmStatic fun isOnline(ctx: Context?): Boolean { // use the cached value, if it's known if (mlastOnlineStatus != NetworkStatus.Unknown) return mlastOnlineStatus == NetworkStatus.Online val result: Boolean val connectivityManager = ctx?.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager val networkCapabilities = connectivityManager.activeNetwork ?: return false val actNw = connectivityManager.getNetworkCapabilities(networkCapabilities) ?: return false result = when { actNw.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) -> true actNw.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) -> true actNw.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET) -> true else -> false } mlastOnlineStatus = if (result) NetworkStatus.Online else NetworkStatus.Offline return result } } }
gpl-3.0
a287dcf73357cc41c4ca1e85a6bbc16d
38.651899
128
0.640964
4.940063
false
false
false
false
chinachen01/android-demo
app/src/main/kotlin/com/example/chenyong/android_demo/view/PathPainterEffect.kt
1
1519
package com.example.chenyong.android_demo.view import android.animation.ValueAnimator import android.content.Context import android.graphics.* import android.util.AttributeSet import android.view.View import android.view.animation.AccelerateInterpolator /** * Created by focus on 17/2/6. */ class PathPainterEffect(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : View(context, attrs, defStyleAttr),View.OnClickListener{ override fun onClick(v: View?) { animator.start() } constructor(context: Context?, attrs: AttributeSet?) : this(context, attrs, 0) constructor(context: Context?) : this(context, null) val pathMeasure = PathMeasure() val path = Path() val paint = Paint() val animator:ValueAnimator = ValueAnimator.ofFloat(0f, 1f) init { path.reset() path.moveTo(100f, 100f) path.lineTo(100f, 500f) path.lineTo(300f, 300f) path.lineTo(100f, 100f) path.close() pathMeasure.setPath(path, true) val length = pathMeasure.length animator.interpolator = AccelerateInterpolator() animator.addUpdateListener { animator -> kotlin.run { var fraction = animator.animatedValue as Float var dashEffect = DashPathEffect(floatArrayOf(length,length),fraction) paint.setPathEffect(dashEffect) invalidate() } } } override fun onDraw(canvas: Canvas?) { super.onDraw(canvas) canvas?.drawPath(path, paint) } }
apache-2.0
374cb6ee63232383773b3ca81af645d1
31.340426
142
0.673469
4.278873
false
false
false
false
Phakx/my_movie_db
movie-db-service/src/main/java/de/bke/movie/Movie.kt
1
868
package de.bke.movie import de.bke.actor.Actor import de.bke.base.BaseEntity import javax.persistence.Entity import javax.persistence.FetchType import javax.persistence.ManyToMany /** * Created by bkeucher on 12.02.16. * check: * https://github.com/ebean-orm/avaje-ebeanorm-examples/tree/master/e-kotlin-maven/src/main/java/org/example/domain */ @Entity class Movie() : BaseEntity() { var title: String? = null var original_title: String? = null var production_year: Int? = null var owned: Boolean = false var wanted: Boolean = false var genre: String? = null @ManyToMany(mappedBy = "movies", fetch = FetchType.LAZY) var actors: MutableList<Actor>? = null fun addActor(actor: Actor) { if (actors != null) { actors!!.add(actor) } else { actors = mutableListOf(actor) } } }
mit
f23f724a54aaf1e07546e0f6867051de
24.558824
115
0.662442
3.616667
false
false
false
false
thanhnbt/kovert
vertx-example/src/main/kotlin/uy/kohesive/kovert/vertx/sample/App.kt
1
3839
package uy.kohesive.kovert.vertx.sample import com.typesafe.config.Config import io.vertx.ext.web.Router import nl.komponents.kovenant.functional.bind import org.slf4j.Logger import uy.klutter.config.typesafe.KonfigAndInjektMain import uy.klutter.config.typesafe.KonfigRegistrar import uy.klutter.config.typesafe.ReferenceConfig import uy.klutter.config.typesafe.jdk7.FileConfig import uy.klutter.config.typesafe.loadConfig import uy.klutter.vertx.VertxWithSlf4jInjektables import uy.kohesive.injekt.Injekt import uy.kohesive.injekt.api.* import uy.kohesive.kovert.core.HttpVerb import uy.kohesive.kovert.core.KovertConfig import uy.kohesive.kovert.vertx.bindController import uy.kohesive.kovert.vertx.boot.KovertVerticle import uy.kohesive.kovert.vertx.boot.KovertVerticleModule import uy.kohesive.kovert.vertx.boot.KovertVertx import uy.kohesive.kovert.vertx.boot.KovertVertxModule import java.nio.file.Path import java.nio.file.Paths public class App(val configFile: Path) { companion object { @JvmStatic public fun main(args: Array<String>) { if (args.size != 1) { println("Invalid usage. ConfigFile parameter is required!") println() println(" usage: App <configFile>") println() println("There is a sample config file in web/sample.conf under the root of this sample project") println() System.exit(-1) } App(Paths.get(args[0])).start() } } // injection setup is done in a nested object to control the order of instantiation AFTER the configFile member is available val injektMain = object : KonfigAndInjektMain() { override fun configFactory(): Config { return loadConfig(FileConfig(configFile), ReferenceConfig()) } override fun KonfigRegistrar.registerConfigurables() { // configuration for launching vertx, we could also pass configuration in directly to the constructor of KovertVertx importModule("kovert.vertx", KovertVertxModule) // configuration for kovert as a verticle, we could also pass configuration in directly to the constructor of KovertVerticle importModule("kovert.server", KovertVerticleModule) } override fun InjektRegistrar.registerInjectables() { // includes jackson ObjectMapper to match compatibility with Vertx, app logging via Vertx facade to Slf4j importModule(VertxWithSlf4jInjektables) // everything Kovert wants importModule(KovertVertxModule) importModule(KovertVerticleModule) // our controllers like to use services importModule(MockAuthService.Injektables) importModule(MockPeopleService.Injektables) importModule(MockCompanyService.Injektables) } } public fun start() { // we use the pattern findSomething so add that as a alias for HTTP GET KovertConfig.addVerbAlias("find", HttpVerb.GET) val LOG: Logger = Injekt.logger(this) val apiMountPoint = "api" val initControllers = fun Router.(): Unit { // bind the controller classes bindController(PeopleController(), apiMountPoint) bindController(CompanyController(), apiMountPoint) } val configFileLocation = configFile.getParent() // make things relative to the config file location // startup synchronously... KovertVertx.start(workingDir = configFileLocation) bind { vertx -> KovertVerticle.deploy(vertx, routerInit = initControllers) } success { deploymentId -> LOG.warn("Deployment complete.") } fail { error -> LOG.error("Deployment failed!", error) } } }
mit
ed98c6322646e17c567255bbfeaeb917
42.134831
136
0.687419
4.681707
false
true
false
false
lanhuaguizha/Christian
app/src/main/java/com/christian/nav/home/DiscipleChildFragment.kt
1
17453
package com.christian.nav.home import android.content.Context import android.os.Bundle import android.view.* import android.view.animation.AnimationUtils import android.widget.Toast import androidx.annotation.NonNull import androidx.recyclerview.widget.RecyclerView import com.christian.R import com.christian.common.* import com.christian.common.data.Gospel import com.christian.databinding.ItemChatBinding import com.christian.databinding.ItemDiscipleBinding import com.christian.nav.* import com.christian.nav.disciple.ChatItemView import com.christian.nav.gospel.DiscipleItemView import com.christian.util.ChristianUtil import com.christian.view.ItemDecoration import com.firebase.ui.firestore.FirestoreRecyclerAdapter import com.firebase.ui.firestore.FirestoreRecyclerOptions import com.google.firebase.firestore.Query import kotlinx.android.synthetic.main.fragment_disciple_child.view.* import org.jetbrains.anko.debug open class DiscipleChildFragment : androidx.fragment.app.Fragment(), NavContract.INavFragment { var mPosition = -1 override fun onSaveInstanceState(outState: Bundle) { } // // override fun onGospelSelected(gospel: DocumentSnapshot) { // // Go to the details page for the selected restaurant // gospelId = gospel.id // val intent = Intent([email protected], NavDetailActivity::class.java) // intent.putExtra(toolbarTitle, gospel.data?.get("subtitle").toString()) // startActivity(intent) // } private lateinit var query: Query lateinit var navActivity: NavActivity private lateinit var ctx: Context // private lateinit var navAdapter: NavItemPresenter<*> lateinit var v: View var navId = -1 init { debug { "look at init times" } } /** * It is the first place application code can run where the fragment is ready to be used */ override fun onAttach(context: Context) { super.onAttach(context) navActivity = context as NavActivity ctx = context debug { "onAttach" } } private var isInitView = false private var isVisibled = false override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { //包含菜单到所在Activity // setHasOptionsMenu(true) v = inflater.inflate(R.layout.fragment_disciple_child, container, false) isInitView = true isCanLoadData() return v } override fun setUserVisibleHint(isVisibleToUser: Boolean) { super.setUserVisibleHint(isVisibleToUser) //isVisibleToUser这个boolean值表示:该Fragment的UI 用户是否可见,获取该标志记录下来 if (isVisibleToUser) { isVisibled = true isCanLoadData() } else { isVisibled = false /*if (::navActivity.isInitialized) { navActivity.hideFab() }*/ } } private fun isCanLoadData() { //所以条件是view初始化完成并且对用户可见 if (isInitView && isVisibled) { initView() //防止重复加载数据 isInitView = false isVisibled = false } } override fun initView() { // v.ll_click_reload.setOnClickListener { // v.pb_nav.visibility = View.VISIBLE // v.pb_nav.isIndeterminate = true // v.ll_click_reload.visibility = View.GONE // sortByTimeReverse() // } // when (navId) { // VIEW_ME -> { // initPortrait() // } // } // if (navId == VIEW_GOSPEL) { // v.vp1_nav.visibility = View.VISIBLE // v.srl_nav.visibility = View.GONE // v.pb_nav.visibility = View.GONE // initVp(navActivity.tabTitleList) // } else { // v.vp1_nav.visibility = View.GONE v.srl_nav.visibility = View.VISIBLE // initSrl() // } initRv() v.pb_nav.isIndeterminate = true v.disciple_child_rv.setProgressBar(v.pb_nav) v.disciple_child_rv.setFloatingActionButton(navActivity) } private fun initSrl() { } private fun initPortrait() { // Glide.with(navActivity).load(R.drawable.me).into(navActivity.iv_nav_item_small) } private lateinit var navFragment: DiscipleChildFragment private var pageSelectedPosition: Int = -1 /*private fun initVp(tabTitleList: ArrayList<String>) { vp1_nav.viewPager = navActivity.vp_nav navChildFragmentPagerAdapter = NavChildFragmentPagerAdapter(childFragmentManager, tabTitleList, FragmentStatePagerAdapter.BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT ) v.vp1_nav.adapter = navChildFragmentPagerAdapter navActivity.tl_nav.setupWithViewPager(v.vp1_nav)//将TabLayout和ViewPager关联起来 v.vp1_nav.addOnPageChangeListener(object : ViewPager.OnPageChangeListener { override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) { } override fun onPageSelected(position: Int) { pageSelectedPosition = position navFragment = navChildFragmentPagerAdapter.currentFragment } override fun onPageScrollStateChanged(state: Int) { } }) }*/ var isPageTop: Boolean = true var isPageBottom: Boolean = false private lateinit var gospelAdapter: FirestoreRecyclerAdapter<Gospel, RecyclerView.ViewHolder> override fun onDestroyView() { super.onDestroyView() if (::gospelAdapter.isInitialized) gospelAdapter.stopListening() } private fun initRv() { // when (navId) { // VIEW_HOME -> { v.disciple_child_rv.addItemDecoration(ItemDecoration(top = ChristianUtil.dpToPx(64))) loadGospelsFromTabId(navId) gospelAdapter.startListening() v.disciple_child_rv.adapter = gospelAdapter // } // VIEW_GOSPEL -> { // Gospel不在这里控制,在下面的id从4..69的地方控制 // } // VIEW_DISCIPLE -> { // Disciple不在这里控制,有自己的DiscipleFragment // } // VIEW_ME -> { // v.fragment_nav_rv.addItemDecoration(ItemDecoration(resources.getDimension(R.dimen.search_margin_horizontal).toInt())) // meAdapter = firestoreRecyclerAdapter() // meAdapter.startListening() // v.fragment_nav_rv.adapter = meAdapter // } // in 4..69 -> { // Gospel Page's Fragment's navId // v.fragment_nav_rv.addItemDecoration(ItemDecoration(top = ChristianUtil.dpToPx(64))) // // loadGospelsFromTabId(navId) // } // } val onScrollListener = object : HidingScrollListener(v.disciple_child_rv) { override fun onHide() { isPageTop = false isPageBottom = false // controlOverScroll(navActivity, navActivity.abl_nav, navActivity.verticalOffset) } override fun onShow() { isPageTop = false isPageBottom = false // controlOverScroll(navActivity, navActivity.abl_nav, navActivity.verticalOffset) } override fun onTop() { isPageTop = true } override fun onBottom() { isPageBottom = true // controlOverScroll(navActivity, navActivity.abl_nav, navActivity.verticalOffset) } } v.disciple_child_rv.clearOnScrollListeners() v.disciple_child_rv.addOnScrollListener(onScrollListener) val controller = AnimationUtils.loadLayoutAnimation(navActivity, R.anim.layout_animation_up_from_bottom) // v.fragment_nav_rv.layoutAnimation = controller } /** * Loads gospels at different tab in Gospel Page */ private fun loadGospelsFromTabId(navId: Int) { /* = navActivity.firestore.collection("gospels") .orderBy("createTime", Query.Direction.DESCENDING)*/ // .orderBy("classify", Query.Direction.DESCENDING).orderBy("title", Query.Direction.DESCENDING) when (navId) { 0 -> query = firestore.collection(DISCIPLE_EN) .orderBy("createTime", Query.Direction.DESCENDING) 1 -> query = firestore.collection(DISCIPLE_ZH) .orderBy("createTime", Query.Direction.DESCENDING) } val options = FirestoreRecyclerOptions.Builder<Gospel>() // .setLifecycleOwner(this@NavFragment) .setQuery(query, Gospel::class.java) .build() gospelAdapter = object : FirestoreRecyclerAdapter<Gospel, RecyclerView.ViewHolder>(options) { override fun getItemViewType(position: Int): Int { return when { getItem(position).title.isEmpty() -> { VIEW_TYPE_CHAT } else -> { VIEW_TYPE_GOSPEL } } } @NonNull override fun onCreateViewHolder(@NonNull parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder { when(viewType) { 0 -> { val view = LayoutInflater.from(parent.context) .inflate(R.layout.item_disciple, parent, false) val binding = ItemDiscipleBinding.bind(view) return DiscipleItemView(binding, navActivity, navId) } 1 -> { val view = LayoutInflater.from(parent.context) .inflate(R.layout.item_chat, parent, false) val binding = ItemChatBinding.bind(view) return ChatItemView(binding, navActivity, navId) } else -> { val view = LayoutInflater.from(parent.context) .inflate(R.layout.item_disciple, parent, false) val binding = ItemDiscipleBinding.bind(view) return DiscipleItemView(binding, navActivity, navId) } } } override fun onBindViewHolder(@NonNull holder: RecyclerView.ViewHolder, position: Int, @NonNull model: Gospel ) { when { model.title.isEmpty() -> { applyViewHolderAnimation(holder as ChatItemView) holder.bind(navId, model) } else -> { applyViewHolderAnimation(holder as DiscipleItemView) holder.bind(navId, model) } } } override fun onDataChanged() { super.onDataChanged() v.pb_nav.visibility = View.GONE v.pb_nav.isIndeterminate = false if (itemCount == 0) { // v.ll_click_reload.visibility = View.VISIBLE } else { // v.ll_click_reload.visibility = View.GONE v.disciple_child_rv.scheduleLayoutAnimation() } } } v.disciple_child_rv.adapter = gospelAdapter } /*private fun firestoreRecyclerAdapter(): FirestoreRecyclerAdapter<Setting, NavItemView> { val query = navActivity.firestore.collection("mes").orderBy("id", Query.Direction.ASCENDING) val options = FirestoreRecyclerOptions.Builder<Setting>() .setQuery(query, Setting::class.java) // .setLifecycleOwner(navActivity) .build() return object : FirestoreRecyclerAdapter<Setting, NavItemView>(options) { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): NavItemView { val view = LayoutInflater.from(parent.context) .inflate(R.layout.nav_item_me, parent, false) val binding = NavItemMeBinding.bind(view) return NavItemView(binding, navActivity) } override fun onBindViewHolder(holder: NavItemView, position: Int, model: Setting) { holder.bind(model) if (position >= 2) { holder.containerView.visibility = View.GONE } } override fun onDataChanged() { // If there are no chat messages, show a view that invites the user to add a message. // mEmptyListMessage.setVisibility(if (itemCount == 0) View.VISIBLE else View.GONE) pb_nav.visibility = View.GONE if (itemCount == 0) { } else { fragment_nav_rv.scheduleLayoutAnimation() } } } }*/ fun showToast(message: String) { Toast.makeText(navActivity, message, Toast.LENGTH_SHORT).show(); } fun showFab() { // navActivity.showFAB() // if (navId == 1 && cv_nav_frag.visibility == View.GONE) { // cv_nav_frag.visibility = View.VISIBLE // val fadeIn = AnimationUtils.loadAnimation(context, R.anim.abc_fade_in) // cv_nav_frag.startAnimation(fadeIn) // } } fun hideFab() { // navActivity.hideFab() // if (navId == 1 && cv_nav_frag.visibility == View.VISIBLE) { // val fadeOut = AnimationUtils.loadAnimation(context, R.anim.abc_fade_out) // cv_nav_frag.startAnimation(fadeOut) // cv_nav_frag.visibility = View.GONE // } } // // private fun runLayoutAnimation(recyclerView: androidx.recyclerview.widget.RecyclerView) { // val animation = AnimationUtils.loadLayoutAnimation(recyclerView.context, R.anim.layout_animation_from_right) // recyclerView.layoutAnimation = animation // recyclerView.gospelAdapter?.notifyDataSetChanged() // recyclerView.scheduleLayoutAnimation() // } override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { super.onCreateOptionsMenu(menu, inflater) inflater.inflate(R.menu.menu_home_sort, menu) } fun sortByNameReverse() { val query = if (navId == 0) { firestore.collection(DISCIPLE_EN) .orderBy("title", Query.Direction.DESCENDING) } else { firestore.collection(DISCIPLE_ZH) .orderBy("title", Query.Direction.DESCENDING) } val options = FirestoreRecyclerOptions.Builder<Gospel>() // .setLifecycleOwner(this@NavFragment) .setQuery(query, Gospel::class.java) .build() gospelAdapter.updateOptions(options) } fun sortByTimeReverse() { val query = if (navId == 0) { firestore.collection(DISCIPLE_EN) .orderBy("createTime", Query.Direction.DESCENDING) } else { firestore.collection(DISCIPLE_ZH) .orderBy("createTime", Query.Direction.DESCENDING) } val options = FirestoreRecyclerOptions.Builder<Gospel>() // .setLifecycleOwner(this@NavFragment) .setQuery(query, Gospel::class.java) .build() gospelAdapter.updateOptions(options) } fun sortByName() { val query = if (navId == 0) { firestore.collection(DISCIPLE_EN) .orderBy("title", Query.Direction.ASCENDING) } else { firestore.collection(DISCIPLE_ZH) .orderBy("title", Query.Direction.ASCENDING) } val options = FirestoreRecyclerOptions.Builder<Gospel>() // .setLifecycleOwner(this@NavFragment) .setQuery(query, Gospel::class.java) .build() gospelAdapter.updateOptions(options) } fun sortByTime() { val query = if (navId == 0) { firestore.collection(DISCIPLE_EN) .orderBy("createTime", Query.Direction.ASCENDING) } else { firestore.collection(DISCIPLE_ZH) .orderBy("createTime", Query.Direction.ASCENDING) } val options = FirestoreRecyclerOptions.Builder<Gospel>() // .setLifecycleOwner(this@NavFragment) .setQuery(query, Gospel::class.java) .build() gospelAdapter.updateOptions(options) } fun applyViewHolderAnimation(holder: DiscipleItemView) { if (holder.adapterPosition > mPosition) { holder.animateItemView(holder.itemView) mPosition = holder.adapterPosition } } fun applyViewHolderAnimation(holder: ChatItemView) { if (holder.adapterPosition > mPosition) { holder.animateItemView(holder.itemView) mPosition = holder.adapterPosition } } }
gpl-3.0
5b29ccdae810f52020cab30642c5733e
35.294118
135
0.578003
4.72899
false
false
false
false
thanhnbt/kovert
vertx-jdk8/src/test/kotlin/uy/kohesive/kovert/vertx/Helpers.kt
1
3417
package uy.kohesive.kovert.vertx.test import io.vertx.core.http.HttpClient import io.vertx.core.http.HttpClientRequest import io.vertx.core.http.HttpHeaders import io.vertx.core.http.HttpMethod import nl.komponents.kovenant.Deferred import nl.komponents.kovenant.Promise import nl.komponents.kovenant.deferred import uy.klutter.core.jdk.* import kotlin.test.assertEquals data class HttpClientResult(val statusCode: Int, val statusMessage: String, val body: String?) public fun HttpClientRequest.promise(): Promise<HttpClientResult, Throwable> { val deferred = deferred<HttpClientResult, Throwable>() return promise({}, deferred) } public fun HttpClientRequest.promise(init: HttpClientRequest.()->Unit): Promise<HttpClientResult, Throwable> { val deferred = deferred<HttpClientResult, Throwable>() return promise(init, deferred) } public fun HttpClientRequest.promise(init: HttpClientRequest.()->Unit, deferred: Deferred<HttpClientResult, Throwable>): Promise<HttpClientResult, Throwable> { try { handler { response -> response.bodyHandler { buff -> deferred.resolve(HttpClientResult(response.statusCode(), response.statusMessage(), if (buff.length() == 0) null else String(buff.getBytes()))) } } exceptionHandler { ex -> deferred.reject(ex) } with (this) { init() } end() } catch (ex: Exception) { deferred.reject(ex) } return deferred.promise } public fun HttpClient.promiseRequest(verb: HttpMethod, requestUri: String, init: HttpClientRequest.()->Unit): Promise<HttpClientResult, Throwable> { val deferred = deferred<HttpClientResult, Throwable>() try { return this.request(verb, requestUri).promise(init, deferred) } catch (ex: Throwable) { deferred.reject(ex) } return deferred.promise } public fun HttpClient.promiseRequestAbs(verb: HttpMethod, requestUri: String, init: HttpClientRequest.()->Unit): Promise<HttpClientResult, Throwable> { val deferred = deferred<HttpClientResult, Throwable>() try { return this.requestAbs(verb, requestUri).promise(init, deferred) } catch (ex: Throwable) { deferred.reject(ex) } return deferred.promise } public fun HttpClient.testServer(verb: HttpMethod, path: String, assertStatus: Int = 200, assertResponse: String? = null, writeJson: String? = null) { val result = promiseRequest(verb, "${path.mustStartWith('/')}", { if (writeJson != null) { putHeader(HttpHeaders.CONTENT_TYPE, "application/json") setChunked(true) write(writeJson) } }).get() assertEquals(assertStatus, result.statusCode, "Eror with ${verb} at ${path}") assertEquals(assertResponse, result.body, "Eror with ${verb} at ${path}") } public fun HttpClient.testServerAltContentType(verb: HttpMethod, path: String, assertStatus: Int = 200, assertResponse: String? = null, writeJson: String? = null) { val result = promiseRequest(verb, "${path.mustStartWith('/')}", { if (writeJson != null) { putHeader(HttpHeaders.CONTENT_TYPE, "application/json; charset=utf-8") setChunked(true) write(writeJson) } }).get() assertEquals(assertStatus, result.statusCode, "Eror with ${verb} at ${path}") assertEquals(assertResponse, result.body, "Eror with ${verb} at ${path}") }
mit
b56ae59595866ca989e2598e75721059
37.840909
164
0.690079
4.218519
false
false
false
false
Shynixn/PetBlocks
petblocks-core/src/main/kotlin/com/github/shynixn/petblocks/core/logic/business/commandexecutor/PlayerPetActionCommandExecutorImpl.kt
1
4516
package com.github.shynixn.petblocks.core.logic.business.commandexecutor import com.github.shynixn.petblocks.api.business.command.PlayerCommand import com.github.shynixn.petblocks.api.business.enumeration.Permission import com.github.shynixn.petblocks.api.business.localization.Messages import com.github.shynixn.petblocks.api.business.service.* import com.github.shynixn.petblocks.core.logic.business.extension.mergeArgs import com.google.inject.Inject /** * Created by Shynixn 2019. * <p> * Version 1.2 * <p> * MIT License * <p> * Copyright (c) 2019 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 PlayerPetActionCommandExecutorImpl @Inject constructor( private val petActionService: PetActionService, private val guiService: GUIService, private val proxyService: ProxyService, private val configurationService: ConfigurationService, private val persistencePetMetaService: PersistencePetMetaService ) : PlayerCommand { /** * Gets called when the given [player] executes the defined command with the given [args]. */ override fun <P> onPlayerExecuteCommand(player: P, args: Array<out String>): Boolean { if (!persistencePetMetaService.hasPetMeta(player)) { return true } if (args.size == 1 && args[0].equals("call", true)) { if (!checkForPermission(player, Permission.CALL)) { return true } petActionService.callPet(player) return true } if (args.size == 1 && args[0].equals("toggle", true)) { if (!checkForPermission(player, Permission.TOGGLE)) { return true } petActionService.togglePet(player) return true } if (args.size >= 2 && args[0].equals("rename", true)) { if (!checkForPermission(player, Permission.RENAME)) { return true } petActionService.renamePet(player, mergeArgs(args)) return true } if (args.size == 2 && args[0].equals("skin", true)) { if (!checkForPermission(player, Permission.CUSTOMHEAD)) { return true } petActionService.changePetSkin(player, args[1]) return true } if (args.size == 1) { if (!checkForPermission(player, Permission.GUI)) { return true } val pathPermission = configurationService.findValue<String>("commands.petblock.permission") + "." + args[0] if (!checkForPermission(player, pathPermission)) { return true } guiService.open(player, args[0]) return true } if (!checkForPermission(player, Permission.GUI)) { return true } guiService.open(player) return true } /** * Permission check. */ private fun <P> checkForPermission(player: P, permission: Permission): Boolean { return checkForPermission(player, permission.permission) } /** * Permission check. */ private fun <P> checkForPermission(player: P, permission: String): Boolean { val hasPermission = proxyService.hasPermission(player, permission) if (!hasPermission) { proxyService.sendMessage(player, Messages.prefix + Messages.noPermissionMessage) } return hasPermission } }
apache-2.0
d47ee218db022c779a21098e14760d39
33.746154
119
0.65279
4.641316
false
false
false
false
square/leakcanary
shark-hprof/src/main/java/shark/StreamingRecordReaderAdapter.kt
2
10296
package shark import shark.HprofRecord.HeapDumpEndRecord import shark.HprofRecord.HeapDumpRecord import shark.HprofRecord.HeapDumpRecord.GcRootRecord import shark.HprofRecord.HeapDumpRecord.HeapDumpInfoRecord import shark.HprofRecord.HeapDumpRecord.ObjectRecord import shark.HprofRecord.HeapDumpRecord.ObjectRecord.ClassDumpRecord import shark.HprofRecord.HeapDumpRecord.ObjectRecord.InstanceDumpRecord import shark.HprofRecord.HeapDumpRecord.ObjectRecord.ObjectArrayDumpRecord import shark.HprofRecord.HeapDumpRecord.ObjectRecord.PrimitiveArrayDumpRecord import shark.HprofRecord.LoadClassRecord import shark.HprofRecord.StackFrameRecord import shark.HprofRecord.StackTraceRecord import shark.HprofRecord.StringRecord import shark.HprofRecordTag.CLASS_DUMP import shark.HprofRecordTag.HEAP_DUMP_END import shark.HprofRecordTag.HEAP_DUMP_INFO import shark.HprofRecordTag.INSTANCE_DUMP import shark.HprofRecordTag.LOAD_CLASS import shark.HprofRecordTag.OBJECT_ARRAY_DUMP import shark.HprofRecordTag.PRIMITIVE_ARRAY_DUMP import shark.HprofRecordTag.ROOT_DEBUGGER import shark.HprofRecordTag.ROOT_FINALIZING import shark.HprofRecordTag.ROOT_INTERNED_STRING import shark.HprofRecordTag.ROOT_JAVA_FRAME import shark.HprofRecordTag.ROOT_JNI_GLOBAL import shark.HprofRecordTag.ROOT_JNI_LOCAL import shark.HprofRecordTag.ROOT_JNI_MONITOR import shark.HprofRecordTag.ROOT_MONITOR_USED import shark.HprofRecordTag.ROOT_NATIVE_STACK import shark.HprofRecordTag.ROOT_REFERENCE_CLEANUP import shark.HprofRecordTag.ROOT_STICKY_CLASS import shark.HprofRecordTag.ROOT_THREAD_BLOCK import shark.HprofRecordTag.ROOT_THREAD_OBJECT import shark.HprofRecordTag.ROOT_UNKNOWN import shark.HprofRecordTag.ROOT_UNREACHABLE import shark.HprofRecordTag.ROOT_VM_INTERNAL import shark.HprofRecordTag.STACK_FRAME import shark.HprofRecordTag.STACK_TRACE import shark.HprofRecordTag.STRING_IN_UTF8 import java.util.EnumSet import kotlin.reflect.KClass /** * Wraps a [StreamingHprofReader] to provide a higher level API that streams [HprofRecord] * instances. */ class StreamingRecordReaderAdapter(private val streamingHprofReader: StreamingHprofReader) { /** * Obtains a new source to read all hprof records from and calls [listener] back for each record * that matches one of the provided [recordTypes]. * * @return the number of bytes read from the source */ @Suppress("ComplexMethod", "LongMethod", "NestedBlockDepth") fun readRecords( recordTypes: Set<KClass<out HprofRecord>>, listener: OnHprofRecordListener ): Long { val recordTags = recordTypes.asHprofTags() return streamingHprofReader.readRecords( recordTags ) { tag, length, reader -> when (tag) { STRING_IN_UTF8 -> { val recordPosition = reader.bytesRead val record = reader.readStringRecord(length) listener.onHprofRecord(recordPosition, record) } LOAD_CLASS -> { val recordPosition = reader.bytesRead val record = reader.readLoadClassRecord() listener.onHprofRecord(recordPosition, record) } STACK_FRAME -> { val recordPosition = reader.bytesRead val record = reader.readStackFrameRecord() listener.onHprofRecord(recordPosition, record) } STACK_TRACE -> { val recordPosition = reader.bytesRead val record = reader.readStackTraceRecord() listener.onHprofRecord(recordPosition, record) } ROOT_UNKNOWN -> { val recordPosition = reader.bytesRead val record = reader.readUnknownGcRootRecord() listener.onHprofRecord(recordPosition, GcRootRecord(record)) } ROOT_JNI_GLOBAL -> { val recordPosition = reader.bytesRead val gcRootRecord = reader.readJniGlobalGcRootRecord() listener.onHprofRecord(recordPosition, GcRootRecord(gcRootRecord)) } ROOT_JNI_LOCAL -> { val recordPosition = reader.bytesRead val gcRootRecord = reader.readJniLocalGcRootRecord() listener.onHprofRecord(recordPosition, GcRootRecord(gcRootRecord)) } ROOT_JAVA_FRAME -> { val recordPosition = reader.bytesRead val gcRootRecord = reader.readJavaFrameGcRootRecord() listener.onHprofRecord(recordPosition, GcRootRecord(gcRootRecord)) } ROOT_NATIVE_STACK -> { val recordPosition = reader.bytesRead val gcRootRecord = reader.readNativeStackGcRootRecord() listener.onHprofRecord(recordPosition, GcRootRecord(gcRootRecord)) } ROOT_STICKY_CLASS -> { val recordPosition = reader.bytesRead val gcRootRecord = reader.readStickyClassGcRootRecord() listener.onHprofRecord(recordPosition, GcRootRecord(gcRootRecord)) } ROOT_THREAD_BLOCK -> { val recordPosition = reader.bytesRead val gcRootRecord = reader.readThreadBlockGcRootRecord() listener.onHprofRecord(recordPosition, GcRootRecord(gcRootRecord)) } ROOT_MONITOR_USED -> { val recordPosition = reader.bytesRead val gcRootRecord = reader.readMonitorUsedGcRootRecord() listener.onHprofRecord(recordPosition, GcRootRecord(gcRootRecord)) } ROOT_THREAD_OBJECT -> { val recordPosition = reader.bytesRead val gcRootRecord = reader.readThreadObjectGcRootRecord() listener.onHprofRecord(recordPosition, GcRootRecord(gcRootRecord)) } ROOT_INTERNED_STRING -> { val recordPosition = reader.bytesRead val gcRootRecord = reader.readInternedStringGcRootRecord() listener.onHprofRecord(recordPosition, GcRootRecord(gcRootRecord)) } ROOT_FINALIZING -> { val recordPosition = reader.bytesRead val gcRootRecord = reader.readFinalizingGcRootRecord() listener.onHprofRecord(recordPosition, GcRootRecord(gcRootRecord)) } ROOT_DEBUGGER -> { val recordPosition = reader.bytesRead val gcRootRecord = reader.readDebuggerGcRootRecord() listener.onHprofRecord(recordPosition, GcRootRecord(gcRootRecord)) } ROOT_REFERENCE_CLEANUP -> { val recordPosition = reader.bytesRead val gcRootRecord = reader.readReferenceCleanupGcRootRecord() listener.onHprofRecord(recordPosition, GcRootRecord(gcRootRecord)) } ROOT_VM_INTERNAL -> { val recordPosition = reader.bytesRead val gcRootRecord = reader.readVmInternalGcRootRecord() listener.onHprofRecord(recordPosition, GcRootRecord(gcRootRecord)) } ROOT_JNI_MONITOR -> { val recordPosition = reader.bytesRead val gcRootRecord = reader.readJniMonitorGcRootRecord() listener.onHprofRecord(recordPosition, GcRootRecord(gcRootRecord)) } ROOT_UNREACHABLE -> { val recordPosition = reader.bytesRead val gcRootRecord = reader.readUnreachableGcRootRecord() listener.onHprofRecord(recordPosition, GcRootRecord(gcRootRecord)) } CLASS_DUMP -> { val recordPosition = reader.bytesRead val record = reader.readClassDumpRecord() listener.onHprofRecord(recordPosition, record) } INSTANCE_DUMP -> { val recordPosition = reader.bytesRead val record = reader.readInstanceDumpRecord() listener.onHprofRecord(recordPosition, record) } OBJECT_ARRAY_DUMP -> { val recordPosition = reader.bytesRead val arrayRecord = reader.readObjectArrayDumpRecord() listener.onHprofRecord(recordPosition, arrayRecord) } PRIMITIVE_ARRAY_DUMP -> { val recordPosition = reader.bytesRead val record = reader.readPrimitiveArrayDumpRecord() listener.onHprofRecord(recordPosition, record) } HEAP_DUMP_INFO -> { val recordPosition = reader.bytesRead val record = reader.readHeapDumpInfoRecord() listener.onHprofRecord(recordPosition, record) } HEAP_DUMP_END -> { val recordPosition = reader.bytesRead val record = HeapDumpEndRecord listener.onHprofRecord(recordPosition, record) } else -> error("Unexpected heap dump tag $tag at position ${reader.bytesRead}") } } } companion object { fun StreamingHprofReader.asStreamingRecordReader() = StreamingRecordReaderAdapter(this) fun Set<KClass<out HprofRecord>>.asHprofTags(): EnumSet<HprofRecordTag> { val recordTypes = this return if (HprofRecord::class in recordTypes) { EnumSet.allOf(HprofRecordTag::class.java) } else { EnumSet.noneOf(HprofRecordTag::class.java).apply { if (StringRecord::class in recordTypes) { add(STRING_IN_UTF8) } if (LoadClassRecord::class in recordTypes) { add(LOAD_CLASS) } if (HeapDumpEndRecord::class in recordTypes) { add(HEAP_DUMP_END) } if (StackFrameRecord::class in recordTypes) { add(STACK_FRAME) } if (StackTraceRecord::class in recordTypes) { add(STACK_TRACE) } if (HeapDumpInfoRecord::class in recordTypes) { add(HEAP_DUMP_INFO) } val readAllHeapDumpRecords = HeapDumpRecord::class in recordTypes if (readAllHeapDumpRecords || GcRootRecord::class in recordTypes) { addAll(HprofRecordTag.rootTags) } val readAllObjectRecords = readAllHeapDumpRecords || ObjectRecord::class in recordTypes if (readAllObjectRecords || ClassDumpRecord::class in recordTypes) { add(CLASS_DUMP) } if (readAllObjectRecords || InstanceDumpRecord::class in recordTypes) { add(INSTANCE_DUMP) } if (readAllObjectRecords || ObjectArrayDumpRecord::class in recordTypes) { add(OBJECT_ARRAY_DUMP) } if (readAllObjectRecords || PrimitiveArrayDumpRecord::class in recordTypes) { add(PRIMITIVE_ARRAY_DUMP) } } } } } }
apache-2.0
3720f3094a946ad35f3478f1aaf31ea5
37.706767
98
0.685509
4.746888
false
false
false
false
facebook/litho
codelabs/textinput-keyboard/app/src/main/java/com/facebook/litho/codelab/textinput/ClockDrawable.kt
1
3013
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * 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.facebook.litho.codelab.textinput import android.graphics.Canvas import android.graphics.Color import android.graphics.ColorFilter import android.graphics.Paint import android.graphics.PixelFormat import android.graphics.drawable.Drawable class ClockDrawable : Drawable() { companion object { const val ONE_MINUTE = 60L * 1000 const val ONE_HOUR = 60 * ONE_MINUTE const val TWELVE_HOURS = 12 * ONE_HOUR } private val paintThin = buildPaint(6) private val paintMedium = buildPaint(9) private val paintWide = buildPaint(12) private var longHandAngle = 0 private var shortHandAngle = 0 var radius = 0 private fun buildPaint(strokeWidthPx: Int): Paint { return Paint().apply { color = Color.BLACK isAntiAlias = true style = Paint.Style.STROKE strokeWidth = strokeWidthPx.toFloat() } } private fun drawHand( canvas: Canvas, degrees: Float, length: Int, paint: Paint, centerX: Float, centerY: Float ) { // Save and then rotate canvas canvas.run { val savedCount = save() rotate(degrees, centerX, centerY) // Draw a hand drawLine(centerX, centerY, centerX, centerY - length, paint) // Restore canvas restoreToCount(savedCount) } } fun setTime(timeMillis: Long) { val inHourProgress = timeMillis.toFloat() % ONE_HOUR / ONE_HOUR longHandAngle = (360 * inHourProgress).toInt() val inTwelveHoursProgress = timeMillis.toFloat() / TWELVE_HOURS shortHandAngle = (360 * inTwelveHoursProgress).toInt() } override fun draw(canvas: Canvas) { val bounds = bounds canvas.run { val saveCount = save() translate(bounds.left.toFloat(), bounds.top.toFloat()) drawCircle(radius.toFloat(), radius.toFloat(), radius.toFloat(), paintWide) drawHand( this, longHandAngle.toFloat(), radius * 2 / 3, paintThin, radius.toFloat(), radius.toFloat()) drawHand( this, shortHandAngle.toFloat(), radius / 3, paintMedium, radius.toFloat(), radius.toFloat()) restoreToCount(saveCount) } } override fun setAlpha(alpha: Int) {} override fun setColorFilter(colorFilter: ColorFilter?) {} override fun getOpacity(): Int { return PixelFormat.OPAQUE } }
apache-2.0
b2ca897763e0ab2df453e5e0fe0bf3a1
25.429825
81
0.664786
4.237693
false
false
false
false
anton-okolelov/intellij-rust
src/test/kotlin/org/rust/ide/annotator/fixes/ConvertToTyUsingFromTraitFixTest.kt
1
1873
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.ide.annotator.fixes import org.rust.ide.inspections.RsExperimentalChecksInspection import org.rust.ide.inspections.RsInspectionsTestBase class ConvertToTyUsingFromTraitFixTest : RsInspectionsTestBase(RsExperimentalChecksInspection()) { override fun getProjectDescriptor() = WithStdlibRustProjectDescriptor fun `test B from A when impl From A for B is available`() = checkFixByText("Convert to B using `From` trait", """ struct A{} struct B{} impl From<A> for B { fn from(item: A) -> Self {B{}} } fn main () { let b: B = <error>A {}<caret></error>; } """, """ struct A{} struct B{} impl From<A> for B { fn from(item: A) -> Self {B{}} } fn main () { let b: B = B::from(A {}); } """) fun `test no fix when impl From A for B is not available`() = checkFixIsUnavailable("Convert to B using `From` trait", """ struct A{} struct B{} struct C{} impl From<A> for C { fn from(item: A) -> Self {C{}} } fn main () { let b: B = <error>A {}<caret></error>; } """) fun `test From impl provided by std lib`() = checkFixByText("Convert to u32 using `From` trait", """ fn main () { let x: u32 = <error>'X'<caret></error>; } """, """ fn main () { let x: u32 = u32::from('X'); } """) fun `test From impl for generic type`() = checkFixByText ("Convert to Vec<u8> using `From` trait", """ fn main () { let v: Vec<u8> = <error>String::new()<caret></error>; } """, """ fn main () { let v: Vec<u8> = Vec::from(String::new()); } """) }
mit
30e0f1b0e4a2c48d4736740491ed122a
26.955224
126
0.531767
3.877847
false
true
false
false
Deletescape-Media/Lawnchair
lawnchair/src/app/lawnchair/theme/color/ColorTokenUtils.kt
1
602
package app.lawnchair.theme.color import android.content.Context import app.lawnchair.preferences.PreferenceManager fun ColorToken.setAlpha(alpha: Float) = SetAlphaColorToken(this, alpha) fun ColorToken.setLStar(lStar: Double) = SetLStarColorToken(this, lStar) fun ColorToken.withContext(transform: ColorToken.(Context) -> ColorToken) = WithContextColorToken(this, transform) inline fun ColorToken.withPreferences( crossinline transform: ColorToken.(PreferenceManager) -> ColorToken ) = withContext { context -> val prefs = PreferenceManager.getInstance(context) transform(this, prefs) }
gpl-3.0
aaf84f3560182e0173962ac1c0ba8d57
42
114
0.802326
4.067568
false
false
false
false
xfournet/intellij-community
plugins/copyright/src/com/maddyhome/idea/copyright/CopyrightProfile.kt
1
2177
// 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.maddyhome.idea.copyright import com.intellij.configurationStore.SerializableScheme import com.intellij.configurationStore.serializeObjectInto import com.intellij.openapi.components.BaseState import com.intellij.openapi.options.ExternalizableScheme import com.intellij.util.xmlb.annotations.OptionTag import com.intellij.util.xmlb.annotations.Transient import com.maddyhome.idea.copyright.pattern.EntityUtil import org.jdom.Element @JvmField val DEFAULT_COPYRIGHT_NOTICE: String = EntityUtil.encode( "Copyright (c) \$today.year. Lorem ipsum dolor sit amet, consectetur adipiscing elit. \n" + "Morbi non lorem porttitor neque feugiat blandit. Ut vitae ipsum eget quam lacinia accumsan. \n" + "Etiam sed turpis ac ipsum condimentum fringilla. Maecenas magna. \n" + "Proin dapibus sapien vel ante. Aliquam erat volutpat. Pellentesque sagittis ligula eget metus. \n" + "Vestibulum commodo. Ut rhoncus gravida arcu. ") class CopyrightProfile @JvmOverloads constructor(profileName: String? = null) : ExternalizableScheme, BaseState(), SerializableScheme { // ugly name to preserve compatibility // must be not private because otherwise binding is not created for private accessor @Suppress("MemberVisibilityCanBePrivate") @get:OptionTag("myName") var profileName by string() var notice by property(DEFAULT_COPYRIGHT_NOTICE) var keyword by property(EntityUtil.encode("Copyright")) var allowReplaceRegexp by string() @Deprecated("use allowReplaceRegexp instead", ReplaceWith("")) var allowReplaceKeyword by string() init { // otherwise will be as default value and name will be not serialized this.profileName = profileName } // ugly name to preserve compatibility @Transient override fun getName() = profileName ?: "" override fun setName(value: String) { profileName = value } override fun toString() = profileName ?: "" override fun writeScheme(): Element { val element = Element("copyright") serializeObjectInto(this, element) return element } }
apache-2.0
d6517afb6e0780b28014207ef79ea9dd
39.314815
140
0.771245
4.194605
false
false
false
false
walkingice/momome
app/src/main/java/org/zeroxlab/momome/impl/MainActivity.kt
1
9882
/* * Authored By Julian Chu <[email protected]> * * Copyright (c) 2012 0xlab.org - http://0xlab.org/ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.zeroxlab.momome.impl import android.content.Intent import android.os.Bundle import android.text.InputType import android.util.Log import android.view.View import android.widget.AdapterView import android.widget.AdapterView.OnItemClickListener import android.widget.ListView import android.widget.Toast import android.widget.ViewSwitcher import com.u1aryz.android.lib.newpopupmenu.PopupMenu import org.zeroxlab.momome.Momo import org.zeroxlab.momome.MomoApp import org.zeroxlab.momome.MomoModel import org.zeroxlab.momome.R import org.zeroxlab.momome.data.Item import org.zeroxlab.momome.widget.BasicInputDialog import org.zeroxlab.momome.widget.EditableActivity import org.zeroxlab.momome.widget.EditableAdapter import org.zeroxlab.momome.widget.ItemAdapter class MainActivity : EditableActivity(), Momo, EditableAdapter.EditListener<Item> { lateinit var mListView: ListView lateinit var mHint: View lateinit var mLTSwitcher: ViewSwitcher // left-top lateinit var mRTSwitcher: ViewSwitcher // right-top lateinit var mAdapter: ItemAdapter lateinit var mDialogListener: DialogListener lateinit var mStatusListener: MomoModel.StatusListener lateinit var mItemClickListener: ItemClickListener override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.main) initViews() mDialogListener = DialogListener() mStatusListener = StatusListener() val model = MomoApp.getModel() mAdapter = ItemAdapter(this) mAdapter.setListener(this) mListView.adapter = mAdapter mItemClickListener = ItemClickListener() mListView.onItemClickListener = mItemClickListener doReload() } override fun onDestroy() { super.onDestroy() onStopEdit() closeModel() } override fun onNewIntent(newIntent: Intent) { /* 1) singleTask launch mode * 2) clearTaskOnLaunch * when set both of them, onNewIntent meanse * re-enter this activity from HomeScreen or other * application. Locl model to protect data. */ MomoApp.getModel().addListener(mStatusListener) closeModel() } public override fun onResume() { super.onResume() MomoApp.getModel().addListener(mStatusListener) updateVisibilityByStatus(MomoApp.getModel().status()) } public override fun onPause() { super.onPause() MomoApp.getModel().removeListener(mStatusListener) } private fun initViews() { mListView = findViewById(R.id.main_list_view) as ListView mHint = findViewById(R.id.main_hint) mLTSwitcher = findViewById(R.id.main_lt_switcher) as ViewSwitcher mRTSwitcher = findViewById(R.id.main_rt_switcher) as ViewSwitcher } private fun launchEntryActivity(key: String) { val intent = Intent(this, EntryActivity::class.java) intent.putExtra(Momo.CROSS_ITEM_KEY, key) startActivity(intent) } private fun closeModel() { val model = MomoApp.getModel() if (model.status() == Momo.DataStatus.OK) { model.save() model.lock() mAdapter.notifyDataSetChanged() } } fun onClickAdd(v: View) { val model = MomoApp.getModel() if (model.status() == Momo.DataStatus.OK || model.status() == Momo.DataStatus.FILE_IS_EMPTY) { getNewItemName() } } fun onClickSettings(v: View) { val i = Intent(this, PrefMain::class.java) startActivity(i) } fun onClickEdit(v: View) { val model = MomoApp.getModel() if (model.status() == Momo.DataStatus.OK || model.status() == Momo.DataStatus.FILE_IS_EMPTY) { super.toggleEditing() } } fun onClickDone(v: View) { super.toggleEditing() } fun onClickMore(v: View) { val fLock = 0 val fSettings = 1 val menu = PopupMenu(this) menu.add(fLock, R.string.lockaction) menu.add(fSettings, R.string.settings) menu.setHeaderTitle("More options") menu.setOnItemSelectedListener { item -> if (item.itemId == fLock) { onClickReload(v) } else if (item.itemId == fSettings) { onClickSettings(v) } } menu.show(v) } fun onClickReload(v: View) { val model = MomoApp.getModel() if (model.status() == Momo.DataStatus.OK) { closeModel() } else { doReload() } } override fun onEdit(item: Item) { renameItem(item) } override fun onDelete(item: Item) { val model = MomoApp.getModel() model.removeItem(item) mAdapter.notifyDataSetChanged() } override fun onStartEdit() { mLTSwitcher.showNext() mRTSwitcher.showNext() mAdapter.setEditing(true) mListView.onItemClickListener = null mListView.invalidateViews() } override fun onStopEdit() { mLTSwitcher.showNext() mRTSwitcher.showNext() mAdapter.setEditing(false) mListView.onItemClickListener = mItemClickListener mListView.invalidateViews() } private fun doReload() { val model = MomoApp.getModel() if (model.status() == Momo.DataStatus.NO_PASSWORD || model.status() == Momo.DataStatus.FILE_CANNOT_ACCESS || model.status() == Momo.DataStatus.PASSWORD_WRONG) { askForPassword() } } private fun askForPassword() { var msg = super.getString(R.string.main_dialog_unlock) if (!MomoApp.getModel().internalFileExists()) { Log.d(Momo.TAG, "not exist?") msg = super.getString(R.string.main_dialog_init) } val dialog = BasicInputDialog(this, msg) dialog.setInputType(InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_PASSWORD) dialog.setListener(DIALOG_PASSWORD, mDialogListener) dialog.show() } private fun renameItem(item: Item) { val dialog = BasicInputDialog(this, super.getString(R.string.main_dialog_rename_item)) dialog.setDefaultText(item.title) dialog.setExtra(item) dialog.setListener(DIALOG_RENAME, mDialogListener) dialog.show() } private fun getNewItemName() { val dialog = BasicInputDialog(this, super.getString(R.string.main_dialog_add_item)) dialog.setListener(DIALOG_ADD_ITEM, mDialogListener) dialog.show() } private fun onEnteredPassword(password: CharSequence) { val model = MomoApp.getModel() model.unlock(password) /* FIXME: it should detect PASSWORD_WRONG ONLY*/ if (model.status() == Momo.DataStatus.PASSWORD_WRONG || model.status() == Momo.DataStatus.FILE_CANNOT_ACCESS) { Toast.makeText(this, "Decrypt failed", Toast.LENGTH_LONG).show() } } private fun onRenameItem(name: CharSequence, item: Item) { item.title = name.toString() MomoApp.getModel().save() mAdapter.notifyDataSetChanged() } private fun onAddItem(name: CharSequence) { val item = Item(name.toString()) MomoApp.getModel().addItem(item) MomoApp.getModel().save() mAdapter.notifyDataSetChanged() } private fun updateVisibilityByStatus(status: Momo.DataStatus) { if (status == Momo.DataStatus.OK || status == Momo.DataStatus.FILE_IS_EMPTY) { mAdapter.notifyDataSetChanged() mHint.visibility = View.GONE mListView.visibility = View.VISIBLE } else { mHint.visibility = View.VISIBLE mListView.visibility = View.GONE } } inner class ItemClickListener : OnItemClickListener { override fun onItemClick(a: AdapterView<*>, v: View, pos: Int, id: Long) { val item = mAdapter.getItem(pos) as Item launchEntryActivity(item.id) } } inner class DialogListener : BasicInputDialog.InputListener { override fun onInput(id: Int, input: CharSequence, extra: Any?) { if (input.toString() == "") { return // do nothing if user input nothing } else if (id == DIALOG_PASSWORD) { onEnteredPassword(input) } else if (id == DIALOG_RENAME) { if (extra != null && extra is Item) { onRenameItem(input, (extra as Item?)!!) } } else if (id == DIALOG_ADD_ITEM) { onAddItem(input) } } override fun onCancelInput(id: Int, extra: Any) {} } private inner class StatusListener : MomoModel.StatusListener { override fun onStatusChanged(now: Momo.DataStatus) { val model = MomoApp.getModel() updateVisibilityByStatus(model.status()) } } companion object { private val DIALOG_PASSWORD = 0xFF01 private val DIALOG_RENAME = 0xFF02 private val DIALOG_ADD_ITEM = 0xFF03 } }
apache-2.0
754fe1f648737d37498c187ef92643ed
31.4
119
0.634892
4.300261
false
false
false
false
inv3rse/ProxerTv
app/src/main/java/com/inverse/unofficial/proxertv/ui/details/SeriesDetailsRowPresenter.kt
1
7550
package com.inverse.unofficial.proxertv.ui.details import android.support.v17.leanback.widget.ArrayObjectAdapter import android.support.v17.leanback.widget.HorizontalGridView import android.support.v17.leanback.widget.ItemBridgeAdapter import android.support.v17.leanback.widget.RowPresenter import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Button import android.widget.ImageView import android.widget.TextView import com.bumptech.glide.Glide import com.bumptech.glide.load.resource.drawable.GlideDrawable import com.bumptech.glide.request.RequestListener import com.bumptech.glide.request.target.Target import com.inverse.unofficial.proxertv.R import com.inverse.unofficial.proxertv.model.Series import com.inverse.unofficial.proxertv.model.SeriesList import com.inverse.unofficial.proxertv.model.ServerConfig import com.inverse.unofficial.proxertv.ui.details.SeriesDetailsRowPresenter.SeriesDetailsRow import com.inverse.unofficial.proxertv.ui.util.getStringRes import java.lang.Exception import kotlin.properties.Delegates /** * Presenter for a [SeriesDetailsRow]. The layout is based on the * [android.support.v17.leanback.widget.DetailsOverviewRowPresenter]. */ class SeriesDetailsRowPresenter(var selectSeriesDetailsRowListener: SeriesDetailsRowListener?) : RowPresenter() { val pagePresenter = PageSelectionPresenter() var seriesList: SeriesList = SeriesList.NONE var coverReadyListener: (() -> Unit)? = null init { headerPresenter = null selectEffectEnabled = false } override fun dispatchItemSelectedListener(vh: ViewHolder?, selected: Boolean) { super.dispatchItemSelectedListener(vh, selected) } override fun createRowViewHolder(parent: ViewGroup): ViewHolder { val view = LayoutInflater.from(parent.context).inflate(R.layout.view_series_details, parent, false) return DetailsViewHolder(view) } override fun onBindRowViewHolder(vh: ViewHolder, item: Any?) { super.onBindRowViewHolder(vh, item) if (item is SeriesDetailsRow) { vh as DetailsViewHolder // store the item to unbind the page change listener later vh.item = item vh.titleTextView.text = item.series.name vh.descriptionTextView.text = item.series.description vh.genresTextView.text = item.series.genres vh.selectListButton.setText(seriesList.getStringRes()) vh.selectListButton.setOnClickListener { selectSeriesDetailsRowListener?.onSelectListClicked(item) } if (item.series.pages() > 1) { vh.pagesView.visibility = View.VISIBLE val pagesAdapter = ArrayObjectAdapter(pagePresenter) pagesAdapter.addAll(0, createPageSelectionList(item.series.pages(), item.currentPageNumber)) val bridgeAdapter = ItemBridgeAdapter(pagesAdapter) bridgeAdapter.setAdapterListener(object : ItemBridgeAdapter.AdapterListener() { override fun onBind(viewHolder: ItemBridgeAdapter.ViewHolder) { super.onBind(viewHolder) viewHolder.presenter.setOnClickListener( viewHolder.viewHolder, { selectSeriesDetailsRowListener?.onPageSelected(item, (viewHolder.item as PageSelection)) }) } override fun onUnbind(viewHolder: ItemBridgeAdapter.ViewHolder) { super.onUnbind(viewHolder) viewHolder.presenter.setOnClickListener(viewHolder.viewHolder, null) } }) vh.pagesGridView.adapter = bridgeAdapter // react to item page selection change vh.pageSelectionChangeListener = item.addPageSelectionChangeListener { vh.pagesGridView.itemAnimator = null // disable the change animation pagesAdapter.clear() pagesAdapter.addAll(0, createPageSelectionList(item.series.pages(), it)) } } else { vh.pagesView.visibility = View.INVISIBLE } Glide.with(vh.view.context) .load(ServerConfig.coverUrl(item.series.id)) .centerCrop() .listener(object : RequestListener<String?, GlideDrawable?> { override fun onException(e: Exception?, model: String?, target: Target<GlideDrawable?>?, isFirstResource: Boolean): Boolean { return false } override fun onResourceReady(resource: GlideDrawable?, model: String?, target: Target<GlideDrawable?>?, isFromMemoryCache: Boolean, isFirstResource: Boolean): Boolean { vh.view.post { coverReadyListener?.invoke() } return false } }) .into(vh.coverImageView) } } override fun onUnbindRowViewHolder(vh: ViewHolder) { vh as DetailsViewHolder Glide.clear(vh.coverImageView) // remove the page selection change listener if it exists vh.pageSelectionChangeListener?.let { vh.item?.removePageSelectionChangeListener(it) } vh.pageSelectionChangeListener = null vh.item = null super.onUnbindRowViewHolder(vh) } private fun createPageSelectionList(numPages: Int, currentPage: Int): List<PageSelection> { return IntProgression .fromClosedRange(1, numPages, 1) .map { PageSelection(it, it == currentPage) } } /** * Presentable series details row */ class SeriesDetailsRow( val series: Series, selectedPageNumber: Int = 1) { private val listeners = mutableSetOf<(Int) -> Unit>() var currentPageNumber: Int by Delegates.observable(selectedPageNumber, { _, _, new -> listeners.forEach { it(new) } }) fun addPageSelectionChangeListener(listener: (Int) -> Unit): (Int) -> Unit { listeners.add(listener) return listener } fun removePageSelectionChangeListener(listener: (Int) -> Unit) { listeners.remove(listener) } } /** * Interface for page selection click events */ interface SeriesDetailsRowListener { fun onSelectListClicked(seriesRow: SeriesDetailsRow) fun onPageSelected(seriesRow: SeriesDetailsRow, selection: PageSelection) } /** * ViewHolder for the series details row */ private class DetailsViewHolder(view: View) : RowPresenter.ViewHolder(view) { val coverImageView = view.findViewById(R.id.series_details_cover) as ImageView val titleTextView = view.findViewById(R.id.series_detail_title) as TextView val descriptionTextView = view.findViewById(R.id.series_detail_description) as TextView val genresTextView = view.findViewById(R.id.series_details_genres) as TextView val pagesView: View = view.findViewById(R.id.series_detail_pages_view) val pagesGridView = view.findViewById(R.id.series_detail_pages) as HorizontalGridView val selectListButton = view.findViewById(R.id.series_details_select_list_button) as Button var item: SeriesDetailsRow? = null var pageSelectionChangeListener: ((Int) -> Unit)? = null } }
mit
7e22433a169af8d7ae13bb7c1dfed098
42.148571
192
0.660662
4.954068
false
false
false
false
googlecodelabs/tv-watchnext
step_final/src/main/java/com/example/android/watchnextcodelab/presenter/DetailsDescriptionPresenter.kt
4
1835
/* * 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 com.example.android.watchnextcodelab.presenter import android.support.v17.leanback.widget.AbstractDetailsDescriptionPresenter import com.example.android.watchnextcodelab.model.Movie import java.util.Locale import java.util.concurrent.TimeUnit class DetailsDescriptionPresenter : AbstractDetailsDescriptionPresenter() { override fun onBindDescription(viewHolder: AbstractDetailsDescriptionPresenter.ViewHolder, item: Any) { val (_, title, description, duration) = item as Movie viewHolder.title.text = title viewHolder.subtitle.text = getDurationLabel(duration) viewHolder.body.text = description } private fun getDurationLabel(duration: Long): String { val seconds = TimeUnit.SECONDS.convert(duration, TimeUnit.MILLISECONDS) % 60 val minutes = TimeUnit.MINUTES.convert(duration, TimeUnit.MILLISECONDS) % 60 val hours = TimeUnit.HOURS.convert(duration, TimeUnit.MILLISECONDS) return if (hours > 0) { String.format(Locale.getDefault(), "%d hours %d min", hours, minutes) } else { String.format(Locale.getDefault(), "%d min %d sec", minutes, seconds) } } }
apache-2.0
1cc0b0269e6e6eeddd0f3b40467ed6ae
38.891304
100
0.716621
4.598997
false
false
false
false
FredJul/TaskGame
TaskGame/src/main/java/net/fred/taskgame/utils/NavigationUtils.kt
1
1414
/* * Copyright (c) 2012-2017 Frederic Julian * * 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:></http:>//www.gnu.org/licenses/>. */ package net.fred.taskgame.utils import net.fred.taskgame.models.Category object NavigationUtils { val TASKS = "-2" val FINISHED_TASKS = "-1" /** * Returns actual navigation status */ var navigation: String get() = PrefUtils.getString(PrefUtils.PREF_NAVIGATION, TASKS) set(newNavigation) = PrefUtils.putString(PrefUtils.PREF_NAVIGATION, newNavigation) val isDisplayingACategory: Boolean get() = navigation.length > 2 /** * Checks if passed parameters is the category user is actually navigating in */ fun isDisplayingCategory(category: Category?): Boolean { return category != null && navigation == category.id } }
gpl-3.0
a3729e6f2bb07eaa79b79bd9fc92c792
31.136364
90
0.704385
4.259036
false
false
false
false
OurFriendIrony/MediaNotifier
app/src/main/kotlin/uk/co/ourfriendirony/medianotifier/clients/rawg/game/get/GameGetRating.kt
1
742
package uk.co.ourfriendirony.medianotifier.clients.rawg.game.get import com.fasterxml.jackson.annotation.* @JsonInclude(JsonInclude.Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) @JsonPropertyOrder("id", "title", "count", "percent") class GameGetRating { @get:JsonProperty("id") @set:JsonProperty("id") @JsonProperty("id") var id: Int? = null @get:JsonProperty("title") @set:JsonProperty("title") @JsonProperty("title") var title: String? = null @get:JsonProperty("count") @set:JsonProperty("count") @JsonProperty("count") var count: Int? = null @get:JsonProperty("percent") @set:JsonProperty("percent") @JsonProperty("percent") var percent: Double? = null }
apache-2.0
e2b8156f50e854605f8e024704293c84
25.535714
64
0.684636
3.864583
false
false
false
false
myungo/playground
jbasic/exam-kotlin/src/main/kotlin/basic/extension/stringutil.kt
1
629
package basic.extension // Receiver Type: String / Receiver Object : this val String.lastChar : Char get() = get(length - 1) var StringBuilder.lastChar : Char get() = get(length-1) set(value: Char) = this.setCharAt(length - 1, value) fun <T> Collection<T>.joinToString( separator: String = ", ", prefix: String = "", postfix: String = "," ) : String { val result = StringBuilder(prefix); for ((index, element) in this.withIndex()) { if (index > 0) result.append(separator) result.append(element) } result.append(postfix) return result.toString() }
gpl-2.0
fee8cf8408c37865c1baaee7d49ea424
24.16
56
0.615262
3.766467
false
false
false
false
abdodaoud/Merlin
app/src/main/java/com/abdodaoud/merlin/util/AlarmReceiver.kt
1
3618
package com.abdodaoud.merlin.util import android.app.PendingIntent import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.graphics.BitmapFactory import android.media.RingtoneManager import android.net.Uri import android.support.v4.app.NotificationCompat import android.support.v4.app.NotificationManagerCompat import com.abdodaoud.merlin.R import com.abdodaoud.merlin.domain.commands.RequestFactCommand import com.abdodaoud.merlin.extensions.maxDate import com.abdodaoud.merlin.extensions.parseMessage import com.abdodaoud.merlin.extensions.zeroedTime import com.abdodaoud.merlin.ui.activities.MainActivity class AlarmReceiver : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { val notificationId = 1 val result = RequestFactCommand().execute(1, System.currentTimeMillis().zeroedTime().maxDate()) val message = result.dailyFact[0].title val source = result.dailyFact[0].url val contentIntent = PendingIntent.getActivity(context, 0, Intent(context, MainActivity::class.java) .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP), 0) val sourceIntent = PendingIntent.getActivity(context, 0, Intent(Intent.ACTION_VIEW, Uri.parse(source)), PendingIntent.FLAG_CANCEL_CURRENT) val sendIntent = Intent(Intent.ACTION_SEND).putExtra(Intent.EXTRA_TEXT, message.parseMessage()).setType("text/plain") val shareIntent = PendingIntent.getActivity(context, 0, sendIntent, PendingIntent.FLAG_CANCEL_CURRENT) // Create a WearableExtender to add functionality for wearables val wearableExtender = NotificationCompat.WearableExtender() .setBackground(BitmapFactory.decodeResource(context.resources, R.drawable.wearable_background)) // TODO: Just add favourite feature to wear and not source and share // .addAction(NotificationCompat.Action(R.mipmap.ic_notification_share_wear, // context.getString(R.string.action_share), shareIntent)) // .addAction(NotificationCompat.Action(R.mipmap.ic_notification_source_wear, // context.getString(R.string.action_source), sourceIntent)) val notificationBuilder = NotificationCompat.Builder(context) .setSmallIcon(R.mipmap.ic_notification) .setContentTitle(context.getString(R.string.app_name)) .setContentText(message) .setWhen(System.currentTimeMillis()) .setAutoCancel(true) .setTicker(message) .setStyle(NotificationCompat.BigTextStyle().bigText(message)) .setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)) .setContentIntent(contentIntent) .addAction(R.mipmap.ic_notification_share, context.getString(R.string.action_share), shareIntent) .addAction(R.mipmap.ic_notification_source, context.getString(R.string.action_source), sourceIntent) // TODO: Add favourite feature .extend(wearableExtender) // Get an instance of the NotificationManager service val notificationManager = NotificationManagerCompat.from(context) // Build the notification and issues it with notification manager. notificationManager.notify(notificationId, notificationBuilder.build()) } }
mit
c8280b4d4a1f6438c20476a2bf6c2a84
48.575342
97
0.685738
4.96978
false
false
false
false
TheFallOfRapture/Morph
src/main/kotlin/com/morph/engine/graphics/Colors.kt
2
2497
package com.morph.engine.graphics data class Color @JvmOverloads constructor(var red: Float, var green: Float, var blue: Float, var alpha: Float = 1f) { operator fun times(k: Float): Color { return Color(red * k, green * k, blue * k) } operator fun plus(c: Color): Color { return Color(red + c.red, green + c.green, blue + c.blue) } fun clamp(): Color { val red = Math.max(0f, Math.min(1f, this.red)) val green = Math.max(0f, Math.min(1f, this.green)) val blue = Math.max(0f, Math.min(1f, this.blue)) return Color(red, green, blue) } fun alphaBlend(dst: Color): Color { val red = this.red * alpha + dst.red * (1f - alpha) val green = this.green * alpha + dst.green * (1f - alpha) val blue = this.blue * alpha + dst.blue * (1f - alpha) return Color(red, green, blue, 1f) } fun setRGB(c: Color) { this.red = c.red this.green = c.green this.blue = c.blue } fun toFloatArray(): FloatArray = floatArrayOf(red, green, blue, alpha) fun toDoubleArray(): DoubleArray = doubleArrayOf(red.toDouble(), green.toDouble(), blue.toDouble(), alpha.toDouble()) } object Colors { @JvmStatic fun fromARGBHex(argb: Int): Color { val alpha = (argb and -0x1000000 shr 24) / 256f val red = (argb and 0x00ff0000 shr 16) / 256f val green = (argb and 0x0000ff00 shr 8) / 256f val blue = (argb and 0x000000ff) / 256f return Color(red, green, blue, alpha) } @JvmStatic @JvmOverloads fun fromRGBHex(rgb: Int, alpha: Float = 1f): Color { val red = (rgb and 0xff0000 shr 16) / 256f val green = (rgb and 0x00ff00 shr 8) / 256f val blue = (rgb and 0x0000ff) / 256f return Color(red, green, blue, alpha) } @JvmStatic fun Color.toARGBHex(): Int { val alpha = Math.floor((alpha * 0xff).toDouble()).toInt() val red = Math.floor((red * 0xff).toDouble()).toInt() val green = Math.floor((green * 0xff).toDouble()).toInt() val blue = Math.floor((blue * 0xff).toDouble()).toInt() return alpha shl 24 or (red shl 16) or (green shl 8) or blue } @JvmStatic fun Color.toRGBHex(): Int { val red = Math.floor((red * 0xff).toDouble()).toInt() val green = Math.floor((green * 0xff).toDouble()).toInt() val blue = Math.floor((blue * 0xff).toDouble()).toInt() return red shl 16 or (green shl 8) or blue } }
mit
0f11b5e3a91cc9e286f6616524ca8b96
34.169014
121
0.593112
3.458449
false
false
false
false
alter-ego/unisannio-reboot
app/src/main/java/solutions/alterego/android/unisannio/Faculties.kt
1
2958
package solutions.alterego.android.unisannio import solutions.alterego.android.unisannio.R.string import solutions.alterego.android.unisannio.map.UniPoint import solutions.alterego.android.unisannio.map.UnisannioGeoData import solutions.alterego.android.unisannio.repository.ArticleParser import solutions.alterego.android.unisannio.repository.Parser import solutions.alterego.android.unisannio.scienze.ScienzeDetailParser import solutions.alterego.android.unisannio.interfaces.Parser as OldParser class Faculty( val hearderImage: Int, val name: String /* Ingegneria */, val website: String /* https://www.ding.unisannio.it/ */, val mapMarkers: List<UniPoint>, val sections: List<Section>, val detailParser: OldParser<String>? = null ) data class Section( val titleResource: Int /* Avvisi Studenti */, val url: String /* https://www.ding.unisannio.it/en/avvisi-com/avvisi-didattica# */, val parser: Parser ) val Dst = Faculty( hearderImage = 0, name = "Scienze e Tecnologia", website = "http://www.dstunisannio.it/", mapMarkers = UnisannioGeoData.SCIENZE(), sections = listOf( Section( string.title_activity_scienze, "http://www.dstunisannio.it/index.php/didattica?format=feed&type=rss", ArticleParser() ) ), detailParser = ScienzeDetailParser() ) val Giurisprudenza = Faculty( 0, "Giurisprudenza", URLS.GIURISPRUDENZA, UnisannioGeoData.GIURISPRUDENZA(), listOf( Section( titleResource = string.title_activity_giurisprudenza, url = "http://www.giurisprudenza.unisannio.it/index.php?option=com_rss&catid=2", parser = ArticleParser() ) ) ) //val AteneoFaculty = Faculty( // R.string.ateneo, // URLS.ATENEO, // UnisannioGeoData.ATENEO(), // listOf( // Section( // R.string.title_activity_ateneo, // URLS.ATENEO_NEWS, // AteneoAvvisiParser() // ), // Section( // R.string.title_activity_ateneo_studenti, // URLS.ATENEO_STUDENTI_NEWS, // AteneoAvvisiParser() // ) // ) //) //val IngegneriaFaculty = Faculty( // R.string.ingegneria, // URLS.INGEGNERIA, // UnisannioGeoData.INGEGNERIA(), // listOf( // Section( // R.string.title_activity_ingegneria_avvisi_studenti, // URLS.INGEGNERIA_NEWS_STUDENTI, // IngegneriaAvvisiStudentiParser() // ), // Section( // R.string.title_activity_ingegneria_dipartimento, // URLS.INGEGNERIA_NEWS_DIPARTIMENTO, // IngegneriaAvvisiDipartimentoParser() // ) // ) //) //val SeaFaculty = Faculty( // R.string.sea, // URLS.SEA, // UnisannioGeoData.SEA(), // listOf( // Section( // R.string.title_activity_sea, // URLS.SEA_NEWS, // SeaParser() // ) // ) //)
apache-2.0
16af36d1efa00f5a2898201d49034285
28
92
0.629817
3.190939
false
false
false
false
blackbbc/Tucao
app/src/main/kotlin/me/sweetll/tucao/business/personal/viewmodel/ChangePasswordViewModel.kt
1
2896
package me.sweetll.tucao.business.personal.viewmodel import com.trello.rxlifecycle2.kotlin.bindToLifecycle import io.reactivex.schedulers.Schedulers import me.sweetll.tucao.base.BaseViewModel import me.sweetll.tucao.business.home.event.RefreshPersonalEvent import me.sweetll.tucao.business.personal.fragment.ChangePasswordFragment import me.sweetll.tucao.extension.NonNullObservableField import me.sweetll.tucao.extension.sanitizeHtml import org.greenrobot.eventbus.EventBus import org.jsoup.nodes.Document class ChangePasswordViewModel(val fragment: ChangePasswordFragment): BaseViewModel() { val oldPassword = NonNullObservableField("") val oldError = NonNullObservableField("") val newPassword = NonNullObservableField("") val newError = NonNullObservableField("") val renewPassword = NonNullObservableField("") val renewError = NonNullObservableField("") var hasError = false fun save() { hasError = false oldError.set("") newError.set("") renewError.set("") if (oldPassword.get().length < 6 || oldPassword.get().length > 20) { hasError = true oldError.set("密码应在6-20位之间") } if (newPassword.get() != renewPassword.get()) { hasError = true newError.set("两次输入的密码不一致") renewError.set("两次输入的密码不一致") } if (newPassword.get().length < 6 || newPassword.get().length > 20) { hasError = true newError.set("密码应在6-20位之间") } if (renewPassword.get().length < 6 || renewPassword.get().length > 20) { hasError = true renewError.set("密码应在6-20位之间") } if (hasError) return rawApiService.changePassword(oldPassword.get(), newPassword.get(), renewPassword.get()) .bindToLifecycle(fragment) .subscribeOn(Schedulers.io()) .sanitizeHtml { parseSaveResult(this) } .map { (code, msg) -> if (code == 0) { Object() } else { throw Error(msg) } } .subscribe({ user.invalidate() EventBus.getDefault().post(RefreshPersonalEvent()) fragment.saveSuccess() }, { error -> error.printStackTrace() fragment.saveFailed(error.message ?: "修改密码失败") }) } private fun parseSaveResult(doc: Document):Pair<Int, String> { val result = doc.body().text() if ("成功" in result) { return Pair(0, "") } else { return Pair(1, result) } } }
mit
87d60080d49d469afa5ca982251e5698
31.917647
95
0.56862
4.671119
false
false
false
false