repo_name
stringlengths
7
81
path
stringlengths
6
242
copies
stringclasses
55 values
size
stringlengths
2
6
content
stringlengths
55
737k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
5.44
99.8
line_max
int64
15
979
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.93
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
kai0masanari/Forcelayout
forcelayout/src/main/kotlin/jp/kai/forcelayout/properties/GraphStyle.kt
1
491
package jp.kai.forcelayout.properties import android.graphics.Color /** * Created by kai on 2017/05/14. */ object GraphStyle { /** node */ var isImgDraw: Boolean = true var nodesWidth: Int = 150 var roundSize: Int = 5 var nodeColor: Int = Color.BLACK /** link */ var linkWidth: Float = 5.0f var linkColor: Int = Color.BLACK /** label */ var fontSize: Float = 30.0f var fontColor: Int = Color.BLACK val defaultColor: Int = Color.BLACK }
apache-2.0
4b7d673e8eb0706bc40852fca782f17e
18.68
39
0.633401
3.557971
false
false
false
false
siosio/intellij-community
platform/xdebugger-impl/src/com/intellij/xdebugger/impl/ui/XDebugSessionTab2.kt
1
13809
// 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.xdebugger.impl.ui import com.intellij.debugger.ui.DebuggerContentInfo import com.intellij.execution.runners.ExecutionEnvironment import com.intellij.execution.ui.layout.LayoutAttractionPolicy import com.intellij.execution.ui.layout.PlaceInGrid import com.intellij.icons.AllIcons import com.intellij.ide.actions.TabListAction import com.intellij.ide.util.PropertiesComponent import com.intellij.openapi.Disposable import com.intellij.openapi.actionSystem.* import com.intellij.openapi.ui.PersistentThreeComponentSplitter import com.intellij.openapi.util.Disposer import com.intellij.openapi.wm.ToolWindowId import com.intellij.openapi.wm.ToolWindowManager import com.intellij.openapi.wm.ToolWindowType import com.intellij.openapi.wm.ex.ToolWindowEx import com.intellij.openapi.wm.ex.ToolWindowManagerListener import com.intellij.ui.JBColor import com.intellij.ui.content.ContentManagerEvent import com.intellij.ui.content.ContentManagerListener import com.intellij.util.ui.JBUI import com.intellij.util.ui.UIUtil import com.intellij.xdebugger.* import com.intellij.xdebugger.impl.XDebugSessionImpl import com.intellij.xdebugger.impl.actions.XDebuggerActions import com.intellij.xdebugger.impl.frame.* import com.intellij.xdebugger.impl.ui.tree.XDebuggerTree import com.intellij.xdebugger.impl.ui.tree.nodes.XDebuggerTreeNode import java.awt.Component import java.awt.Container import javax.swing.Icon import javax.swing.LayoutFocusTraversalPolicy import javax.swing.event.AncestorEvent import javax.swing.event.AncestorListener class XDebugSessionTab2( session: XDebugSessionImpl, icon: Icon?, environment: ExecutionEnvironment? ) : XDebugSessionTab(session, icon, environment, false) { companion object { private const val threadsIsVisibleKey = "threadsIsVisibleKey" private const val debuggerContentId = "DebuggerView" } private val project = session.project private var threadsIsVisible get() = PropertiesComponent.getInstance(project).getBoolean(threadsIsVisibleKey, true) set(value) = PropertiesComponent.getInstance(project).setValue(threadsIsVisibleKey, value, true) private val lifetime = Disposer.newDisposable() private val splitter = PersistentThreeComponentSplitter(false, true, "DebuggerViewTab", lifetime, project, 0.35f, 0.3f) private val xThreadsFramesView = XThreadsFramesView(myProject) private var variables: XVariablesView? = null private val toolWindow get() = ToolWindowManager.getInstance(project).getToolWindow(ToolWindowId.DEBUG) private val focusTraversalPolicy = MyFocusTraversalPolicy() init { // value from com.intellij.execution.ui.layout.impl.GridImpl splitter.setMinSize(48) splitter.isFocusCycleRoot = true splitter.isFocusTraversalPolicyProvider = true splitter.focusTraversalPolicy = focusTraversalPolicy session.addSessionListener(object : XDebugSessionListener { override fun sessionStopped() { UIUtil.invokeLaterIfNeeded { splitter.saveProportions() Disposer.dispose(lifetime) } } }) project.messageBus.connect(lifetime).subscribe(XDebuggerManager.TOPIC, object : XDebuggerManagerListener { override fun processStarted(debugProcess: XDebugProcess) { UIUtil.invokeLaterIfNeeded { if (debugProcess.session != null && debugProcess.session != session) { splitter.saveProportions() } } } override fun currentSessionChanged(previousSession: XDebugSession?, currentSession: XDebugSession?) { UIUtil.invokeLaterIfNeeded { if (previousSession == session) { splitter.saveProportions() xThreadsFramesView.saveUiState() } else if (currentSession == session) splitter.restoreProportions() } } override fun processStopped(debugProcess: XDebugProcess) { UIUtil.invokeLaterIfNeeded { splitter.saveProportions() xThreadsFramesView.saveUiState() if (debugProcess.session == session) Disposer.dispose(lifetime) } } }) val ancestorListener = object : AncestorListener { override fun ancestorAdded(event: AncestorEvent?) { if (XDebuggerManager.getInstance(project).currentSession == session) { splitter.restoreProportions() } } override fun ancestorRemoved(event: AncestorEvent?) { if (XDebuggerManager.getInstance(project).currentSession == session) { splitter.saveProportions() xThreadsFramesView.saveUiState() } } override fun ancestorMoved(event: AncestorEvent?) { } } toolWindow?.component?.addAncestorListener(ancestorListener) Disposer.register(lifetime, Disposable { toolWindow?.component?.removeAncestorListener(ancestorListener) }) var oldToolWindowType: ToolWindowType? = null project.messageBus.connect(lifetime).subscribe(ToolWindowManagerListener.TOPIC, object : ToolWindowManagerListener { override fun stateChanged(toolWindowManager: ToolWindowManager) { if (oldToolWindowType == toolWindow?.type) return setHeaderState() oldToolWindowType = toolWindow?.type } }) } override fun getWatchesContentId() = debuggerContentId override fun getFramesContentId() = debuggerContentId override fun addVariablesAndWatches(session: XDebugSessionImpl) { val variablesView: XVariablesView? val watchesView: XVariablesView? val layoutDisposable = Disposer.newDisposable(ui.contentManager, "debugger layout disposable") if (isWatchesInVariables) { variablesView = XWatchesViewImpl2(session, true, true, layoutDisposable) registerView(DebuggerContentInfo.VARIABLES_CONTENT, variablesView) variables = variablesView watchesView = null myWatchesView = variablesView } else { variablesView = XVariablesView(session) registerView(DebuggerContentInfo.VARIABLES_CONTENT, variablesView) variables = variablesView watchesView = XWatchesViewImpl2(session, false, true, layoutDisposable) registerView(DebuggerContentInfo.WATCHES_CONTENT, watchesView) myWatchesView = watchesView } splitter.apply { innerComponent = variablesView.panel lastComponent = watchesView?.panel } UIUtil.removeScrollBorder(splitter) splitter.revalidate() splitter.repaint() updateTraversalPolicy() } private fun updateTraversalPolicy() { focusTraversalPolicy.components = getComponents().asSequence().toList() } override fun initDebuggerTab(session: XDebugSessionImpl) { val framesView = xThreadsFramesView registerView(DebuggerContentInfo.FRAME_CONTENT, framesView) framesView.setThreadsVisible(threadsIsVisible) splitter.firstComponent = xThreadsFramesView.mainPanel addVariablesAndWatches(session) val name = debuggerContentId val content = myUi.createContent(name, splitter, XDebuggerBundle.message("xdebugger.debugger.tab.title"), AllIcons.Toolwindows.ToolWindowDebugger, framesView.defaultFocusedComponent).apply { isCloseable = false } myUi.addContent(content, 0, PlaceInGrid.left, false) ui.defaults.initContentAttraction(debuggerContentId, XDebuggerUIConstants.LAYOUT_VIEW_BREAKPOINT_CONDITION, LayoutAttractionPolicy.FocusOnce()) toolWindow?.let { val contentManager = it.contentManager val listener = object : ContentManagerListener { override fun contentAdded(event: ContentManagerEvent) { setHeaderState() } override fun contentRemoved(event: ContentManagerEvent) { setHeaderState() } } contentManager.addContentManagerListener(listener) Disposer.register(lifetime, Disposable { contentManager.removeContentManagerListener(listener) }) } setHeaderState() } private fun getComponents(): Iterator<Component> { return iterator { if (threadsIsVisible) yield(xThreadsFramesView.threads) yield(xThreadsFramesView.frames) val vars = variables ?: return@iterator yield(vars.defaultFocusedComponent) if (!isWatchesInVariables) yield(myWatchesView.defaultFocusedComponent) } } private fun setHeaderState() { toolWindow?.let { toolWindow -> if (toolWindow !is ToolWindowEx) return@let val singleContent = toolWindow.contentManager.contents.singleOrNull() val headerVisible = toolWindow.isHeaderVisible val topRightToolbar = DefaultActionGroup().apply { if (headerVisible) return@apply addAll(toolWindow.decorator.headerToolbar.actions.filter { it != null && it !is TabListAction }) } myUi.options.setTopRightToolbar(topRightToolbar, ActionPlaces.DEBUGGER_TOOLBAR) val topMiddleToolbar = DefaultActionGroup().apply { if (singleContent == null || headerVisible) return@apply add(object : AnAction(XDebuggerBundle.message("session.tab.close.debug.session"), null, AllIcons.Actions.Close) { override fun actionPerformed(e: AnActionEvent) { toolWindow.contentManager.removeContent(singleContent, true) } }) addSeparator() } myUi.options.setTopMiddleToolbar(topMiddleToolbar, ActionPlaces.DEBUGGER_TOOLBAR) toolWindow.decorator.isHeaderVisible = headerVisible if (toolWindow.decorator.isHeaderVisible) { toolWindow.component.border = null toolWindow.component.invalidate() toolWindow.component.repaint() } else if (toolWindow.component.border == null) { UIUtil.addBorder(toolWindow.component, JBUI.Borders.customLine(JBColor.border(), 1, 0, 0, 0)) } } } private val ToolWindowEx.isHeaderVisible get() = (type != ToolWindowType.DOCKED) || contentManager.contents.singleOrNull() == null override fun registerAdditionalActions(leftToolbar: DefaultActionGroup, topLeftToolbar: DefaultActionGroup, settings: DefaultActionGroup) { leftToolbar.apply { val constraints = Constraints(Anchor.BEFORE, XDebuggerActions.VIEW_BREAKPOINTS) add(object : ToggleAction() { override fun setSelected(e: AnActionEvent, state: Boolean) { if (threadsIsVisible != state) { threadsIsVisible = state updateTraversalPolicy() } xThreadsFramesView.setThreadsVisible(state) Toggleable.setSelected(e.presentation, state) } override fun isSelected(e: AnActionEvent) = threadsIsVisible override fun update(e: AnActionEvent) { e.presentation.icon = AllIcons.Actions.SplitVertically if (threadsIsVisible) { e.presentation.text = XDebuggerBundle.message("session.tab.hide.threads.view") } else { e.presentation.text = XDebuggerBundle.message("session.tab.show.threads.view") } setSelected(e, threadsIsVisible) } }, constraints) add(ActionManager.getInstance().getAction(XDebuggerActions.FRAMES_TOP_TOOLBAR_GROUP), constraints) add(Separator.getInstance(), constraints) } super.registerAdditionalActions(leftToolbar, topLeftToolbar, settings) } override fun dispose() { Disposer.dispose(lifetime) super.dispose() } class MyFocusTraversalPolicy : LayoutFocusTraversalPolicy() { var components: List<Component> = listOf() override fun getLastComponent(aContainer: Container?): Component { if (components.isNotEmpty()) return components.last().prepare() return super.getLastComponent(aContainer) } override fun getFirstComponent(aContainer: Container?): Component { if (components.isNotEmpty()) return components.first().prepare() return super.getFirstComponent(aContainer) } override fun getComponentAfter(aContainer: Container?, aComponent: Component?): Component { if (aComponent == null) return super.getComponentAfter(aContainer, aComponent) val index = components.indexOf(aComponent) if (index < 0 || index > components.lastIndex) return super.getComponentAfter(aContainer, aComponent) for (i in components.indices) { val component = components[(index + i + 1) % components.size] if (isEmpty(component)) continue return component.prepare() } return components[index + 1].prepare() } override fun getComponentBefore(aContainer: Container?, aComponent: Component?): Component { if (aComponent == null) return super.getComponentBefore(aContainer, aComponent) val index = components.indexOf(aComponent) if (index < 0 || index > components.lastIndex) return super.getComponentBefore(aContainer, aComponent) for (i in components.indices) { val component = components[(components.size + index - i - 1) % components.size] if (isEmpty(component)) continue return component.prepare() } return components[index - 1].prepare() } private fun Component.prepare(): Component { if (this is XDebuggerTree && this.selectionCount == 0){ val child = root.children.firstOrNull() as? XDebuggerTreeNode ?: return this selectionPath = child.path } return this } private fun isEmpty(component: Component): Boolean { return when (component) { is XDebuggerThreadsList -> component.isEmpty is XDebuggerFramesList -> component.isEmpty is XDebuggerTree -> component.isEmpty else -> false; } } } }
apache-2.0
a6f89b87d35fb38cfbb6f4224f44a1da
34.684755
194
0.718155
5.228701
false
false
false
false
vovagrechka/fucking-everything
phizdets/phizdetsc/src/org/jetbrains/kotlin/js/inline/context/NamingContext.kt
3
2009
/* * Copyright 2010-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.kotlin.js.inline.context import org.jetbrains.kotlin.js.backend.ast.* import org.jetbrains.kotlin.js.backend.ast.metadata.synthetic import java.util.ArrayList import java.util.IdentityHashMap import org.jetbrains.kotlin.js.translate.utils.JsAstUtils import org.jetbrains.kotlin.js.inline.util.replaceNames class NamingContext( private val scope: JsScope, private val statementContext: JsContext<JsStatement> ) { private val renamings = IdentityHashMap<JsName, JsExpression>() private val declarations = ArrayList<JsVars>() private var addedDeclarations = false fun applyRenameTo(target: JsNode): JsNode { if (!addedDeclarations) { statementContext.addPrevious(declarations) addedDeclarations = true } return replaceNames(target, renamings) } fun replaceName(name: JsName, replacement: JsExpression) { assert(!renamings.containsKey(name)) { "$name has been renamed already" } renamings.put(name, replacement) } fun getFreshName(candidate: String): JsName = scope.declareFreshName(candidate) fun getTemporaryName(candidate: String): JsName = scope.declareTemporaryName(candidate) fun newVar(name: JsName, value: JsExpression? = null) { val vars = JsAstUtils.newVar(name, value) vars.synthetic = true declarations.add(vars) } }
apache-2.0
bf6fca99cf4d5f6286357d1e8b9dabd2
31.934426
91
0.723743
4.21174
false
false
false
false
jwren/intellij-community
platform/platform-impl/src/com/intellij/openapi/wm/impl/welcomeScreen/projectActions/EditProjectGroupAction.kt
1
2618
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.openapi.wm.impl.welcomeScreen.projectActions import com.intellij.ide.IdeBundle import com.intellij.ide.RecentProjectsManager import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.ui.InputValidatorEx import com.intellij.openapi.ui.Messages import com.intellij.openapi.wm.impl.welcomeScreen.recentProjects.ProjectsGroupItem import com.intellij.util.castSafelyTo /** * @author Konstantin Bulenkov */ class EditProjectGroupAction : RecentProjectsWelcomeScreenActionBase() { override fun actionPerformed(event: AnActionEvent) { val group = getSelectedItem(event).castSafelyTo<ProjectsGroupItem>() ?: return val tree = getTree(event) ?: return val name = Messages.showInputDialog(tree, IdeBundle.message("label.enter.group.name"), IdeBundle.message("dialog.title.change.group.name"), null, group.displayName(), object : InputValidatorEx { override fun getErrorText(inputString: String): String? { val text = inputString.trim() if (text.isEmpty()) return IdeBundle.message("error.name.cannot.be.empty") if (!checkInput(text)) return IdeBundle.message("error.group.already.exists", text) return null } override fun checkInput(inputString: String): Boolean { val text = inputString.trim() if (text == group.displayName()) return true for (projectGroup in RecentProjectsManager.getInstance().groups) { if (projectGroup.name == inputString) { return false } } return true } }) if (name != null) { group.group.name = name } } override fun update(event: AnActionEvent) { val item = getSelectedItem(event) ?: return event.presentation.isEnabledAndVisible = item is ProjectsGroupItem } }
apache-2.0
1c97beb9e8b17b5617006481530669ee
49.365385
127
0.52903
6.088372
false
false
false
false
GunoH/intellij-community
platform/lang-impl/src/com/intellij/lang/documentation/ide/impl/DocumentationPage.kt
8
4176
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. @file:Suppress("TestOnlyProblems") // KTIJ-19938 package com.intellij.lang.documentation.ide.impl import com.intellij.lang.documentation.ContentUpdater import com.intellij.lang.documentation.DocumentationContentData import com.intellij.lang.documentation.LinkData import com.intellij.lang.documentation.ide.ui.UISnapshot import com.intellij.lang.documentation.ide.ui.UIState import com.intellij.lang.documentation.impl.DocumentationRequest import com.intellij.lang.documentation.impl.computeDocumentation import com.intellij.openapi.project.IndexNotReadyException import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.* internal class DocumentationPage(val request: DocumentationRequest) { private val myContentFlow = MutableStateFlow<DocumentationPageContent?>(null) val contentFlow: SharedFlow<DocumentationPageContent?> = myContentFlow.asSharedFlow() val currentContent: DocumentationPageContent.Content? get() = myContentFlow.value as? DocumentationPageContent.Content /** * @return `true` if some content was loaded, `false` if content is empty */ suspend fun waitForContent(): Boolean { return myContentFlow.filterNotNull().first() is DocumentationPageContent.Content } suspend fun loadPage() { val data = try { computeDocumentation(request.targetPointer) } catch (e: IndexNotReadyException) { null // normal situation, nothing to do } if (data == null) { myContentFlow.value = DocumentationPageContent.Empty return } val uiState = data.anchor?.let(UIState::ScrollToAnchor) ?: UIState.Reset myContentFlow.value = DocumentationPageContent.Content(data.content, data.links, uiState) update(data.updates, data.links) } suspend fun updatePage(contentUpdater: ContentUpdater) { val pageContent = checkNotNull(currentContent) val (html, imageResolver) = pageContent.content val updates = contentUpdater.contentUpdates(html).map { DocumentationContentData(it, imageResolver) } update(updates, pageContent.links) } private suspend fun update(updates: Flow<DocumentationContentData>, links: LinkData) { updates.flowOn(Dispatchers.IO).collectLatest { myContentFlow.value = DocumentationPageContent.Content(it, links, uiState = null) } } /** * @return whether the page was restored */ fun restorePage(snapshot: UISnapshot): Boolean { when (val pageContent = myContentFlow.value) { null -> { // This can happen in the following scenario: // 1. Show doc. // 2. Click a link, a new page will open and start loading. // 3. Invoke the Back action during "Fetching..." message. // At this point the request from link is cancelled, but stored in the forward stack of the history. // 4. Invoke the Forward action. // The page is taken from forward stack, but it was never loaded. // Here we reload that cancelled request again return false } is DocumentationPageContent.Empty -> { // nothing to do here return true } is DocumentationPageContent.Content -> { // Consider the following steps: // 1. Open doc with anchor. // 2. Select some link with Tab. // 3. Activate the link, a new page will open. // 4. Go back, the previous page is restored, its last computed UI state is UIState.ScrollToAnchor. // Expected: scroll state and selected link from 2 are restored. // Without the following line: the doc scrolls to the anchor, computed in 1. // Regardless of last computed UIState, we always want to restore the snapshot. myContentFlow.value = pageContent.copy(uiState = UIState.RestoreFromSnapshot(snapshot)) return true } } } } internal sealed class DocumentationPageContent { object Empty : DocumentationPageContent() data class Content( val content: DocumentationContentData, val links: LinkData, val uiState: UIState?, ) : DocumentationPageContent() }
apache-2.0
39bcd93521543e8ea1effe8b7fb492ad
38.396226
120
0.71863
4.772571
false
false
false
false
GunoH/intellij-community
plugins/markdown/core/src/org/intellij/plugins/markdown/extensions/CleanupExtensionsExternalFilesAction.kt
6
1712
package org.intellij.plugins.markdown.extensions import com.intellij.openapi.actionSystem.ActionUpdateThread import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.progress.runModalTask import com.intellij.util.application import org.intellij.plugins.markdown.MarkdownBundle import org.intellij.plugins.markdown.settings.MarkdownExtensionsSettings import org.intellij.plugins.markdown.ui.MarkdownNotifications internal class CleanupExtensionsExternalFilesAction: AnAction() { override fun actionPerformed(event: AnActionEvent) { runModalTask(MarkdownBundle.message("Markdown.Extensions.CleanupExternalFiles.task.title"), event.project, cancellable = false) { val extensions = MarkdownExtensionsUtil.collectExtensionsWithExternalFiles() val pathManager = ExtensionsExternalFilesPathManager.getInstance() for (extension in extensions) { pathManager.cleanupExternalFiles(extension) } MarkdownExtensionsSettings.getInstance().extensionsEnabledState.clear() val publisher = application.messageBus.syncPublisher(MarkdownExtensionsSettings.ChangeListener.TOPIC) publisher.extensionsSettingsChanged(fromSettingsDialog = false) MarkdownNotifications.showInfo( project = event.project, id = "markdown.extensions.external.files.cleanup", title = MarkdownBundle.message("Markdown.Extensions.CleanupExternalFiles.notification.title"), message = MarkdownBundle.message("Markdown.Extensions.CleanupExternalFiles.notification.text"), ) } } override fun getActionUpdateThread(): ActionUpdateThread { return ActionUpdateThread.BGT } }
apache-2.0
dcde6f4d7160c34492dfddfa6da6c818
47.914286
133
0.80257
5.417722
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/tests/testData/shortenRefs/removeCompanionRefInCalleeExpression.kt
13
353
interface Factory { operator fun invoke(i: Int): IntPredicate companion object { inline operator fun invoke(crossinline f: (Int) -> IntPredicate) = object : Factory { override fun invoke(i: Int) = f(i) } } } <selection>fun foo(): Factory = Factory.Companion { k -> IntPredicate { n -> n % k == 0 } }</selection>
apache-2.0
1c6c8f32a0df0c5ea754b8e72c56450a
31.181818
103
0.606232
4.104651
false
false
false
false
smmribeiro/intellij-community
plugins/devkit/devkit-tests/src/org/jetbrains/idea/devkit/testAssistant/TestDataReferenceTestCase.kt
12
1354
// 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.idea.devkit.testAssistant import com.intellij.openapi.vfs.VirtualFile import com.intellij.psi.PsiFile import com.intellij.psi.PsiReference import com.intellij.psi.util.PsiUtilCore import junit.framework.TestCase abstract class TestDataReferenceTestCase : TestDataPathTestCase() { override fun setUp() { super.setUp() myFixture.addClass("package com.intellij.testFramework; public @interface TestDataPath { String value(); }") myFixture.addClass("package com.intellij.testFramework; public @interface TestDataFile { }") } fun assertResolvedTo(virtualFile: VirtualFile, referenceTest: String) { val fileSystemItem = PsiUtilCore.findFileSystemItem(project, virtualFile) TestCase.assertEquals(fileSystemItem, myFixture.file.getReferenceForText(referenceTest).resolve()) } fun PsiFile.getReferenceForText(text: String): PsiReference { val textPosition = this.text.indexOf(text).also { if (it == -1) throw AssertionError("text \"$text\" not found in \"$name\" ") } return findReferenceAt(textPosition + (text.length) / 2) ?: throw AssertionError( "reference not found at \"$name\" for text \"$text\" position = $textPosition " ) } }
apache-2.0
f14909ad6ea5b704d9872e663d8ed71d
42.709677
140
0.751108
4.312102
false
true
false
false
smmribeiro/intellij-community
plugins/settings-sync/src/com/intellij/settingsSync/SettingsSyncBridge.kt
1
6673
package com.intellij.settingsSync import com.intellij.openapi.Disposable import com.intellij.openapi.application.Application import com.intellij.openapi.diagnostic.logger import com.intellij.util.Alarm import com.intellij.util.concurrency.annotations.RequiresBackgroundThread import com.intellij.util.containers.ContainerUtil import com.intellij.util.ui.update.MergingUpdateQueue import com.intellij.util.ui.update.Update import org.jetbrains.annotations.TestOnly import org.jetbrains.annotations.VisibleForTesting import java.util.concurrent.TimeUnit /** * Handles events about settings change both from the current IDE, and from the server, merges the settings, logs them, * and provides the combined data to clients: both to the IDE and to the server. */ internal class SettingsSyncBridge(application: Application, parentDisposable: Disposable, private val settingsLog: SettingsLog, private val ideUpdater: SettingsSyncIdeUpdater, private val remoteCommunicator: SettingsSyncRemoteCommunicator, private val updateChecker: SettingsSyncUpdateChecker ) { private val pendingEvents = ContainerUtil.createConcurrentList<SyncSettingsEvent>() private val queue = MergingUpdateQueue("SettingsSyncBridge", 1000, true, null, parentDisposable, null, Alarm.ThreadToUse.POOLED_THREAD). apply { setRestartTimerOnAdd(true) } private val updateObject = object : Update(1) { // all requests are always merged override fun run() { processPendingEvents() // todo what if here a new event is added; probably synchronization is needed between pPE and adding to the queue } } init { queue.queue(object: Update(0) { override fun run() { initializeLog() } }) application.messageBus.connect(parentDisposable).subscribe(SETTINGS_CHANGED_TOPIC, object : SettingsChangeListener { override fun settingChanged(event: SyncSettingsEvent) { pendingEvents.add(event) queue.queue(updateObject) } }) } private fun initializeLog() { val newRepository = settingsLog.initialize() if (newRepository) { remoteCommunicator.push(settingsLog.collectCurrentSnapshot()) // todo handle non-successful result } } @RequiresBackgroundThread private fun processPendingEvents() { val previousIdePosition = settingsLog.getIdePosition() val previousCloudPosition = settingsLog.getCloudPosition() var pushToCloudRequired = false while (pendingEvents.isNotEmpty()) { val event = pendingEvents.removeAt(0) if (event is SyncSettingsEvent.IdeChange) { settingsLog.applyIdeState(event.snapshot) } else if (event is SyncSettingsEvent.CloudChange) { settingsLog.applyCloudState(event.snapshot) } else if (event is SyncSettingsEvent.PushRequest) { pushToCloudRequired = true } } val newIdePosition = settingsLog.getIdePosition() val newCloudPosition = settingsLog.getCloudPosition() val masterPosition: SettingsLog.Position if (newIdePosition != previousIdePosition || newCloudPosition != previousCloudPosition) { // move master to the actual position. It can be a fast-forward to either ide, or cloud changes, or it can be a merge masterPosition = settingsLog.advanceMaster() } else { // there were only fake events without actual changes to the repository => master doesn't need to be changed either masterPosition = settingsLog.getMasterPosition() } if (newIdePosition != masterPosition) { // master has advanced further that ide => the ide needs to be updated val pushResult: SettingsSyncPushResult = pushToIde(settingsLog.collectCurrentSnapshot()) LOG.info("Result of pushing settings to the IDE: $pushResult") when (pushResult) { SettingsSyncPushResult.Success -> settingsLog.setIdePosition(masterPosition) is SettingsSyncPushResult.Error -> { // todo notify only in case of explicit sync invocation, otherwise update some SettingsSyncStatus notifySettingsSyncError(title = SettingsSyncBundle.message("notification.title.apply.error"), message = pushResult.message) } SettingsSyncPushResult.Rejected -> { // In the case of reject we'll just "wait" for the next update event: // it will be processed in the next session anyway if (pendingEvents.none { it is SyncSettingsEvent.IdeChange }) { // todo schedule update } } } } if (pushToCloudRequired || newCloudPosition != masterPosition) { val pushResult: SettingsSyncPushResult = pushToCloud(settingsLog.collectCurrentSnapshot()) LOG.info("Result of pushing settings to the cloud: $pushResult") when (pushResult) { SettingsSyncPushResult.Success -> settingsLog.setCloudPosition(masterPosition) is SettingsSyncPushResult.Error -> { // todo notify only in case of explicit sync invocation, otherwise update some SettingsSyncStatus notifySettingsSyncError(SettingsSyncBundle.message("notification.title.push.error"), pushResult.message) } SettingsSyncPushResult.Rejected -> { // todo add protection against potential infinite reject-update-reject cycle // (it would indicate some problem, but still shouldn't cycle forever) // In the case of reject we'll just "wait" for the next update event: // it will be processed in the next session anyway if (pendingEvents.none { it is SyncSettingsEvent.CloudChange }) { // not to wait for too long, schedule an update right away unless it has already been scheduled updateChecker.scheduleUpdateFromServer() } } } } } private fun pushToCloud(settingsSnapshot: SettingsSnapshot): SettingsSyncPushResult { return remoteCommunicator.push(settingsSnapshot) } private fun pushToIde(settingsSnapshot: SettingsSnapshot): SettingsSyncPushResult { ideUpdater.settingsLogged(settingsSnapshot) return SettingsSyncPushResult.Success // todo } @TestOnly fun waitForAllExecuted(timeout: Long, timeUnit: TimeUnit) { queue.waitForAllExecuted(timeout, timeUnit) } @VisibleForTesting internal fun suspendEventProcessing() { queue.suspend() } @VisibleForTesting internal fun resumeEventProcessing() { queue.resume() } companion object { val LOG = logger<SettingsSyncBridge>() } }
apache-2.0
afdf9956d27e708407e7d3564a4602c1
39.448485
138
0.704181
5.291832
false
false
false
false
mr-max/anko
dsl/testData/functional/sdk23/ServicesTest.kt
2
7406
public val Context.accessibilityManager: android.view.accessibility.AccessibilityManager get() = getSystemService(Context.ACCESSIBILITY_SERVICE) as android.view.accessibility.AccessibilityManager public val Context.accountManager: android.accounts.AccountManager get() = getSystemService(Context.ACCOUNT_SERVICE) as android.accounts.AccountManager public val Context.activityManager: android.app.ActivityManager get() = getSystemService(Context.ACTIVITY_SERVICE) as android.app.ActivityManager public val Context.alarmManager: android.app.AlarmManager get() = getSystemService(Context.ALARM_SERVICE) as android.app.AlarmManager public val Context.appOpsManager: android.app.AppOpsManager get() = getSystemService(Context.APP_OPS_SERVICE) as android.app.AppOpsManager public val Context.audioManager: android.media.AudioManager get() = getSystemService(Context.AUDIO_SERVICE) as android.media.AudioManager public val Context.batteryManager: android.os.BatteryManager get() = getSystemService(Context.BATTERY_SERVICE) as android.os.BatteryManager public val Context.bluetoothManager: android.bluetooth.BluetoothManager get() = getSystemService(Context.BLUETOOTH_SERVICE) as android.bluetooth.BluetoothManager public val Context.cameraManager: android.hardware.camera2.CameraManager get() = getSystemService(Context.CAMERA_SERVICE) as android.hardware.camera2.CameraManager public val Context.captioningManager: android.view.accessibility.CaptioningManager get() = getSystemService(Context.CAPTIONING_SERVICE) as android.view.accessibility.CaptioningManager public val Context.carrierConfigManager: android.telephony.CarrierConfigManager get() = getSystemService(Context.CARRIER_CONFIG_SERVICE) as android.telephony.CarrierConfigManager public val Context.clipboardManager: android.text.ClipboardManager get() = getSystemService(Context.CLIPBOARD_SERVICE) as android.text.ClipboardManager public val Context.connectivityManager: android.net.ConnectivityManager get() = getSystemService(Context.CONNECTIVITY_SERVICE) as android.net.ConnectivityManager public val Context.consumerIrManager: android.hardware.ConsumerIrManager get() = getSystemService(Context.CONSUMER_IR_SERVICE) as android.hardware.ConsumerIrManager public val Context.devicePolicyManager: android.app.admin.DevicePolicyManager get() = getSystemService(Context.DEVICE_POLICY_SERVICE) as android.app.admin.DevicePolicyManager public val Context.displayManager: android.hardware.display.DisplayManager get() = getSystemService(Context.DISPLAY_SERVICE) as android.hardware.display.DisplayManager public val Context.downloadManager: android.app.DownloadManager get() = getSystemService(Context.DOWNLOAD_SERVICE) as android.app.DownloadManager public val Context.fingerprintManager: android.hardware.fingerprint.FingerprintManager get() = getSystemService(Context.FINGERPRINT_SERVICE) as android.hardware.fingerprint.FingerprintManager public val Context.inputMethodManager: android.view.inputmethod.InputMethodManager get() = getSystemService(Context.INPUT_METHOD_SERVICE) as android.view.inputmethod.InputMethodManager public val Context.inputManager: android.hardware.input.InputManager get() = getSystemService(Context.INPUT_SERVICE) as android.hardware.input.InputManager public val Context.keyguardManager: android.app.KeyguardManager get() = getSystemService(Context.KEYGUARD_SERVICE) as android.app.KeyguardManager public val Context.locationManager: android.location.LocationManager get() = getSystemService(Context.LOCATION_SERVICE) as android.location.LocationManager public val Context.mediaProjectionManager: android.media.projection.MediaProjectionManager get() = getSystemService(Context.MEDIA_PROJECTION_SERVICE) as android.media.projection.MediaProjectionManager public val Context.mediaSessionManager: android.media.session.MediaSessionManager get() = getSystemService(Context.MEDIA_SESSION_SERVICE) as android.media.session.MediaSessionManager public val Context.midiManager: android.media.midi.MidiManager get() = getSystemService(Context.MIDI_SERVICE) as android.media.midi.MidiManager public val Context.networkStatsManager: android.app.usage.NetworkStatsManager get() = getSystemService(Context.NETWORK_STATS_SERVICE) as android.app.usage.NetworkStatsManager public val Context.nfcManager: android.nfc.NfcManager get() = getSystemService(Context.NFC_SERVICE) as android.nfc.NfcManager public val Context.notificationManager: android.app.NotificationManager get() = getSystemService(Context.NOTIFICATION_SERVICE) as android.app.NotificationManager public val Context.nsdManager: android.net.nsd.NsdManager get() = getSystemService(Context.NSD_SERVICE) as android.net.nsd.NsdManager public val Context.powerManager: android.os.PowerManager get() = getSystemService(Context.POWER_SERVICE) as android.os.PowerManager public val Context.printManager: android.print.PrintManager get() = getSystemService(Context.PRINT_SERVICE) as android.print.PrintManager public val Context.restrictionsManager: android.content.RestrictionsManager get() = getSystemService(Context.RESTRICTIONS_SERVICE) as android.content.RestrictionsManager public val Context.searchManager: android.app.SearchManager get() = getSystemService(Context.SEARCH_SERVICE) as android.app.SearchManager public val Context.sensorManager: android.hardware.SensorManager get() = getSystemService(Context.SENSOR_SERVICE) as android.hardware.SensorManager public val Context.storageManager: android.os.storage.StorageManager get() = getSystemService(Context.STORAGE_SERVICE) as android.os.storage.StorageManager public val Context.telecomManager: android.telecom.TelecomManager get() = getSystemService(Context.TELECOM_SERVICE) as android.telecom.TelecomManager public val Context.telephonyManager: android.telephony.TelephonyManager get() = getSystemService(Context.TELEPHONY_SERVICE) as android.telephony.TelephonyManager public val Context.tvInputManager: android.media.tv.TvInputManager get() = getSystemService(Context.TV_INPUT_SERVICE) as android.media.tv.TvInputManager public val Context.uiModeManager: android.app.UiModeManager get() = getSystemService(Context.UI_MODE_SERVICE) as android.app.UiModeManager public val Context.usageStatsManager: android.app.usage.UsageStatsManager get() = getSystemService(Context.USAGE_STATS_SERVICE) as android.app.usage.UsageStatsManager public val Context.usbManager: android.hardware.usb.UsbManager get() = getSystemService(Context.USB_SERVICE) as android.hardware.usb.UsbManager public val Context.userManager: android.os.UserManager get() = getSystemService(Context.USER_SERVICE) as android.os.UserManager public val Context.wallpaperManager: android.app.WallpaperManager get() = getSystemService(Context.WALLPAPER_SERVICE) as android.app.WallpaperManager public val Context.wifiP2pManager: android.net.wifi.p2p.WifiP2pManager get() = getSystemService(Context.WIFI_P2P_SERVICE) as android.net.wifi.p2p.WifiP2pManager public val Context.wifiManager: android.net.wifi.WifiManager get() = getSystemService(Context.WIFI_SERVICE) as android.net.wifi.WifiManager public val Context.windowManager: android.view.WindowManager get() = getSystemService(Context.WINDOW_SERVICE) as android.view.WindowManager
apache-2.0
66dea0bee37d7cf84eb59df2a3f13f46
53.065693
113
0.825547
4.732268
false
false
false
false
dreampany/framework
frame/src/main/kotlin/com/dreampany/framework/ui/vm/BaseViewModel.kt
1
15695
package com.dreampany.framework.ui.vm import android.app.Application import androidx.lifecycle.* import androidx.lifecycle.Observer import com.dreampany.framework.data.enums.Action import com.dreampany.framework.data.enums.NetworkState import com.dreampany.framework.ui.enums.UiMode import com.dreampany.framework.ui.enums.UiState import com.dreampany.framework.data.model.Event import com.dreampany.framework.data.model.Response import com.dreampany.framework.misc.* import com.dreampany.framework.misc.exception.EmptyException import com.dreampany.framework.misc.exception.ExtraException import com.dreampany.framework.misc.exception.MultiException import com.dreampany.framework.util.AndroidUtil import com.dreampany.network.data.model.Network import io.reactivex.Maybe import io.reactivex.disposables.CompositeDisposable import io.reactivex.disposables.Disposable import io.reactivex.subjects.PublishSubject import java.io.IOException import java.util.* /** * Created by Hawladar Roman on 5/22/2018. * BJIT Group * [email protected] */ /** * B2 - B1 = Added * B1 - B2 = Removed * B1 - Removed = Updated * * T = Model * X = Ui Model Item * Y = UiTask<T> */ abstract class BaseViewModel<T, X, Y> protected constructor( application: Application, protected val rx: RxMapper, protected val ex: AppExecutors, protected val rm: ResponseMapper ) : AndroidViewModel(application), LifecycleOwner/*, Observer<X>*/ { private val lifecycleRegistry: LifecycleRegistry var uiMap: SmartMap<String, X> var uiCache: SmartCache<String, X> var uiFavorites: Set<T> var uiSelects: Set<T> var titleOwner: LifecycleOwner? = null var subtitleOwner: LifecycleOwner? = null var uiModeOwner: LifecycleOwner? = null var uiStateOwner: LifecycleOwner? = null var eventOwner: LifecycleOwner? = null var favoriteOwner: LifecycleOwner? = null var selectOwner: LifecycleOwner? = null var singleOwner: LifecycleOwner? = null var multipleOwner: LifecycleOwner? = null var singleOwners: MutableList<LifecycleOwner> = mutableListOf() var multipleOwners: MutableList<LifecycleOwner> = mutableListOf() var multipleOwnersOfString: MutableList<LifecycleOwner> = mutableListOf() var multipleOwnersOfNetwork: MutableList<LifecycleOwner> = mutableListOf() val disposables: CompositeDisposable val ioDisposables: CompositeDisposable var singleDisposable: Disposable? = null var multipleDisposable: Disposable? = null var multipleDisposableOfString: Disposable? = null val liveTitle: SingleLiveEvent<String> val liveSubtitle: SingleLiveEvent<String> val uiMode: SingleLiveEvent<UiMode> val uiState: SingleLiveEvent<UiState> val event: SingleLiveEvent<Event> val favorite: MutableLiveData<X> val select: MutableLiveData<X> val input: PublishSubject<Response<X>> val inputs: PublishSubject<Response<List<X>>> val inputsOfString: PublishSubject<Response<List<String>>> val inputsOfNetwork: PublishSubject<Response<List<Network>>> val output: MutableLiveData<Response<X>> val outputs: MutableLiveData<Response<List<X>>> val outputsOfString: MutableLiveData<Response<List<String>>> val outputsOfNetwork: MutableLiveData<Response<List<Network>>> var task: Y? = null var networkEvent: NetworkState val itemOffset: Int = 4 var focus: Boolean = false init { lifecycleRegistry = LifecycleRegistry(this) lifecycleRegistry.setCurrentState(Lifecycle.State.INITIALIZED) //register(this) disposables = CompositeDisposable() ioDisposables = CompositeDisposable() uiMode = SingleLiveEvent() uiState = SingleLiveEvent() event = SingleLiveEvent() liveTitle = SingleLiveEvent() liveSubtitle = SingleLiveEvent() favorite = MutableLiveData() select = MutableLiveData() input = PublishSubject.create() inputs = PublishSubject.create() inputsOfString = PublishSubject.create() inputsOfNetwork = PublishSubject.create() output = rx.toLiveData(input, ioDisposables) outputs = rx.toLiveData(inputs, ioDisposables) outputsOfString = rx.toLiveData(inputsOfString, ioDisposables) outputsOfNetwork = rx.toLiveData(inputsOfNetwork, ioDisposables) uiMap = SmartMap.newMap() uiCache = SmartCache.newCache() uiFavorites = Collections.synchronizedSet<T>(HashSet<T>()) uiSelects = Collections.synchronizedSet<T>(HashSet<T>()) networkEvent = NetworkState.NONE uiMode.value = UiMode.MAIN uiState.value = UiState.DEFAULT uiMap.clear() uiCache.clear() } override fun getLifecycle(): Lifecycle { return lifecycleRegistry } protected open fun getTitle(): Maybe<String> { TODO("not implemented") } protected open fun getSubtitle(): Maybe<String> { TODO("not implemented") } override fun onCleared() { clear() ioDisposables.clear() super.onCleared() } open fun clear() { lifecycleRegistry.setCurrentState(Lifecycle.State.DESTROYED) titleOwner?.let { liveTitle.removeObservers(it) } subtitleOwner?.let { liveSubtitle.removeObservers(it) } uiModeOwner?.let { uiMode.removeObservers(it) } uiStateOwner?.let { uiState.removeObservers(it) } eventOwner?.let { event.removeObservers(it) } favoriteOwner?.let { favorite.removeObservers(it) } selectOwner?.let { select.removeObservers(it) } singleOwner?.let { output.removeObservers(it) } multipleOwner?.let { outputs.removeObservers(it) } for (owner in singleOwners) { owner.let { output.removeObservers(it) } } for (owner in multipleOwners) { owner.let { outputs.removeObservers(it) } } for (owner in multipleOwnersOfString) { owner.let { outputsOfString.removeObservers(it) } } for (owner in multipleOwnersOfNetwork) { owner.let { outputsOfNetwork.removeObservers(it) } } singleOwners.clear() multipleOwners.clear() multipleOwnersOfString.clear() multipleOwnersOfNetwork.clear() removeSingleSubscription() removeMultipleSubscription() removeMultipleSubscriptionOfString() uiMap.clear() uiCache.clear() clearUiState() } open fun clearUiState() { updateUiState(UiState.DEFAULT) } open fun clearInput() { input.onNext(Response.responseEmpty(null)) inputs.onNext(Response.responseEmpty(null)) } open fun clearOutput() { output.value = null outputs.value = null } fun hasSelection(): Boolean { return uiSelects.isNotEmpty() } open fun hasFocus(): Boolean { return focus } fun onFavorite(t: X?) { favorite.value = t } fun onSelect(t: X?) { select.value = t } fun observeTitle(owner: LifecycleOwner, observer: Observer<String>) { titleOwner = owner liveTitle.observe(owner, observer) } fun observeSubtitle(owner: LifecycleOwner, observer: Observer<String>) { subtitleOwner = owner liveSubtitle.observe(owner, observer) } fun <T> observe(owner: LifecycleOwner, observer: Observer<T>, event: SingleLiveEvent<T>) { event.reObserve(owner, observer) } fun <T> observe(owner: LifecycleOwner, observer: Observer<T>, event: MutableLiveData<T>) { event.reObserve(owner, observer) } fun observeUiMode(owner: LifecycleOwner, observer: Observer<UiMode>) { uiModeOwner = owner uiMode.reObserve(owner, observer) } fun observeUiState(owner: LifecycleOwner, observer: Observer<UiState>) { uiStateOwner = owner uiState.reObserve(owner, observer) } fun observeEvent(owner: LifecycleOwner, observer: Observer<Event>) { eventOwner = owner event.reObserve(owner, observer) } fun observeOutput(owner: LifecycleOwner, observer: Observer<Response<X>>) { postEmpty(null as X) singleOwners.add(owner) output.reObserve(owner, observer) } fun observeOutputs(owner: LifecycleOwner, observer: Observer<Response<List<X>>>) { postEmpty(null as List<X>?) multipleOwners.add(owner) outputs.reObserve(owner, observer) } fun observeOutputsOfString(owner: LifecycleOwner, observer: Observer<Response<List<String>>>) { multipleOwnersOfString.add(owner) outputsOfString.reObserve(owner, observer) } fun observeOutputsOfNetwork( owner: LifecycleOwner, observer: Observer<Response<List<Network>>> ) { multipleOwnersOfNetwork.add(owner) outputsOfNetwork.reObserve(owner, observer) } fun observeFavorite(owner: LifecycleOwner, observer: Observer<X>) { favoriteOwner = owner favorite.reObserve(owner, observer) } fun observeSelect(owner: LifecycleOwner, observer: Observer<X>) { selectOwner = owner select.reObserve(owner, observer) } fun hasDisposable(disposable: Disposable?): Boolean { return disposable != null && !disposable.isDisposed } fun hasSingleDisposable(): Boolean { return hasDisposable(singleDisposable) } fun hasMultipleDisposable(): Boolean { return hasDisposable(multipleDisposable) } fun addSingleSubscription(disposable: Disposable) { singleDisposable = disposable addSubscription(disposable) } fun addMultipleSubscription(disposable: Disposable) { multipleDisposable = disposable addSubscription(disposable) } fun addMultipleSubscriptionOfString(disposable: Disposable) { multipleDisposableOfString = disposable addSubscription(disposable) } fun addSubscription(disposable: Disposable) { disposables.add(disposable) } fun addSubscription(vararg disposables: Disposable) { this.disposables.addAll(*disposables) } fun removeSingleSubscription() { removeSubscription(singleDisposable) } fun removeMultipleSubscription() { removeSubscription(multipleDisposable) } fun removeMultipleSubscriptionOfString() { removeSubscription(multipleDisposableOfString) } fun removeSubscription(disposable: Disposable?): Boolean { disposable?.let { if (it.isDisposed) { return this.disposables.delete(it) } else { return this.disposables.remove(it) } } return false; } fun loadTitle() { val disposable = rx.backToMain(getTitle()).subscribe({ liveTitle.setValue(it) }) addSubscription(disposable) } fun loadSubtitle() { val disposable = rx.backToMain(getSubtitle()).subscribe({ liveSubtitle.setValue(it) }) addSubscription(disposable) } /* open fun getItemsWithoutId(): Flowable<List<T>>? { return null } open fun getRepeatWhenSeconds(): Int { return 0 } fun loads(): Disposable? { if (hasMultipleDisposable()) { return multipleDisposable } var items = getItemsWithoutId() val repeatWhen = getRepeatWhenSeconds() if (items != null) { rxMapper.backToMain<List<T>>(items) if (repeatWhen != 0) { items.repeatWhen({ completed -> completed.delay(10, TimeUnit.SECONDS) }) } items.doOnSubscribe({ subscription -> postProgressMultiple(true) }) val disposable = items.subscribe({ this.postResultWithProgress(it) }, { this.postFailures(it) }) addSubscription(disposable) } return null }*/ fun takeAction(important: Boolean, disposable: Disposable?): Boolean { if (important) { removeSubscription(disposable) } if (hasDisposable(disposable)) { notifyUiState() return false } return true } fun updateUiMode(mode: UiMode?) { mode?.let { uiMode.value = it } } fun updateUiState(state: UiState?) { state?.let { uiState.value = it } } fun notifyUiMode() { updateUiMode(uiMode.value) } fun notifyUiState() { updateUiState(uiState.value) } fun postProgress(loading: Boolean) { updateUiState(if (loading) UiState.SHOW_PROGRESS else UiState.HIDE_PROGRESS) } fun postFailure(error: Throwable) { if (!hasSingleDisposable()) { } rm.response(input, error) } fun postFailure(error: Throwable, withProgress: Boolean) { if (!hasSingleDisposable()) { } if (withProgress) { rm.responseWithProgress(input, error) } else { rm.response(input, error) } } fun postFailures(error: Throwable) { if (!hasMultipleDisposable()) { } rm.response(inputs, error) } fun postFailures(error: Throwable, withProgress: Boolean) { if (!hasMultipleDisposable()) { } if (withProgress) { rm.responseWithProgress(inputs, error) } else { rm.response(inputs, error) } } fun postResult(action: Action, data: X) { rm.response(input, action, data) } fun postResult(action: Action, data: X, withProgress: Boolean) { if (withProgress) { rm.responseWithProgress(input, action, data) } else { rm.response(input, action, data) } } fun postResult(action: Action, data: List<X>) { rm.response(inputs, action, data) } fun postResultOfString(action: Action, data: List<String>) { rm.response(inputsOfString, action, data) } fun postResult(action: Action, data: List<X>, withProgress: Boolean) { if (withProgress) { rm.responseWithProgress(inputs, action, data) } else { rm.response(inputs, action, data) } } fun postEmpty(data: X?) { rm.responseEmpty(input, data) } fun postEmpty(data: X?, withProgress: Boolean) { if (withProgress) { rm.responseEmptyWithProgress(input, data) } else { rm.responseEmpty(input, data) } } fun postEmpty(data: List<X>?) { rm.responseEmpty(inputs, data) } fun postEmpty(data: List<X>?, withProgress: Boolean) { if (withProgress) { rm.responseEmptyWithProgress(inputs, data) } else { rm.responseEmpty(inputs, data) } } fun postFavorite(data: X) { favorite.value = data } fun processProgress(loading: Boolean) { if (loading) { updateUiState(UiState.SHOW_PROGRESS) } else { updateUiState(UiState.HIDE_PROGRESS) } } fun processFailure(error: Throwable) { if (error is IOException || error.cause is IOException) { updateUiState(UiState.OFFLINE) } else if (error is EmptyException) { updateUiState(UiState.EMPTY) } else if (error is ExtraException) { updateUiState(UiState.EXTRA) } else if (error is MultiException) { for (e in error.errors) { processFailure(e) } } } fun speak(text: String) { AndroidUtil.speak(text); } }
apache-2.0
a1347bf05f656c48185b6656473cec2f
29.184615
108
0.645365
4.743125
false
false
false
false
intrigus/jtransc
jtransc-intellij-plugin/jps-plugin/src/com/jtransc/intellij/plugin/JTranscBuilderService.kt
1
3555
package com.jtransc.intellij.plugin import com.jtransc.AllBuild import com.jtransc.JTranscVersion import com.jtransc.ast.AstBuildSettings import com.jtransc.ast.AstTypes import com.jtransc.gen.haxe.HaxeTarget import org.jetbrains.jps.ModuleChunk import org.jetbrains.jps.builders.DirtyFilesHolder import org.jetbrains.jps.builders.java.JavaSourceRootDescriptor import org.jetbrains.jps.incremental.* import org.jetbrains.jps.incremental.messages.BuildMessage import org.jetbrains.jps.incremental.messages.CompilerMessage import org.jetbrains.jps.model.java.JpsJavaExtensionService import org.jetbrains.jps.model.library.JpsOrderRootType import org.jetbrains.jps.model.module.JpsLibraryDependency import org.jetbrains.jps.model.module.JpsModule import org.jetbrains.jps.model.module.JpsModuleDependency import java.util.* class JTranscBuilderService : BuilderService() { override fun createModuleLevelBuilders(): MutableList<out ModuleLevelBuilder> { return arrayListOf(object : ModuleLevelBuilder(BuilderCategory.CLASS_POST_PROCESSOR) { override fun getPresentableName(): String { return "JTranscModuleBuilder" } override fun build(context: CompileContext, chunk: ModuleChunk, dirtyFilesHolder: DirtyFilesHolder<JavaSourceRootDescriptor, ModuleBuildTarget>?, outputConsumer: OutputConsumer): ExitCode { context.markNonIncremental(chunk.representativeTarget()) fun warn(message: String) { context.processMessage(CompilerMessage("JTransc", BuildMessage.Kind.WARNING, message)) } //File("c:/projects/lol.txt").writeText("JTranscBuilderService!") //println("build!") //return ExitCode.ABORT warn("JTranscBuilderService: message!") var doneSomething = false val classPaths = chunk.modules.flatMap { getClassPaths(it) } for (classPath in classPaths) { warn("classPath: $classPath") } // val build = AllBuild( HaxeTarget, classPaths = classPaths, entryPoint = "Test", output = "C:/temp/output.js", targetDirectory = "C:/temp", subtarget = "js", settings = AstBuildSettings( jtranscVersion = JTranscVersion.getVersion() ), types = AstTypes() ) val result = build.buildWithoutRunning() println(result) /* for (module in chunk.modules) { warn("CHUNK: $module") val classPaths = getClassPaths(module) doneSomething = true //doneSomething = doneSomething or build.perform(module, chunk.representativeTarget()) if (context.cancelStatus.isCanceled) { return ModuleLevelBuilder.ExitCode.ABORT } } */ //context.projectDescriptor.project.runConfigurations.first(). return if (doneSomething) ExitCode.OK else ExitCode.NOTHING_DONE } }) } fun getClassPaths(module: JpsModule, visited: HashSet<JpsModule> = hashSetOf()): List<String> { if (module in visited) return listOf() visited += module val out = arrayListOf<String>() val moduleTargetDirectory = JpsJavaExtensionService.getInstance().getOutputDirectory(module, false); if (moduleTargetDirectory != null) { out += moduleTargetDirectory.absolutePath } for (dep in module.dependenciesList.dependencies) { when (dep) { is JpsModuleDependency -> { val module = dep.module if (module != null) out.addAll(getClassPaths(module, visited)) } is JpsLibraryDependency -> { val library = dep.library if (library != null) { for (root in library.getRoots(JpsOrderRootType.COMPILED)) { out.add(root.url) } } } } } return out } }
apache-2.0
9ed14c222f75f731d9a3a9721bd80cfb
31.327273
192
0.731083
4.021493
false
false
false
false
seventhroot/elysium
bukkit/rpk-locks-bukkit/src/main/kotlin/com/rpkit/locks/bukkit/database/table/RPKLockedBlockTable.kt
1
5243
package com.rpkit.locks.bukkit.database.table import com.rpkit.core.database.Database import com.rpkit.core.database.Table import com.rpkit.locks.bukkit.RPKLocksBukkit import com.rpkit.locks.bukkit.database.jooq.rpkit.Tables.RPKIT_LOCKED_BLOCK import com.rpkit.locks.bukkit.lock.RPKLockedBlock import org.bukkit.block.Block import org.ehcache.config.builders.CacheConfigurationBuilder import org.ehcache.config.builders.ResourcePoolsBuilder import org.jooq.impl.DSL.constraint import org.jooq.impl.SQLDataType class RPKLockedBlockTable(database: Database, private val plugin: RPKLocksBukkit): Table<RPKLockedBlock>(database, RPKLockedBlock::class) { private val cache = if (plugin.config.getBoolean("caching.rpkit_locked_block.id.enabled")) { database.cacheManager.createCache("rpk-locks-bukkit.rpkit_locked_block.id", CacheConfigurationBuilder.newCacheConfigurationBuilder(Int::class.javaObjectType, RPKLockedBlock::class.java, ResourcePoolsBuilder.heap(plugin.config.getLong("caching.rpkit_locked_block.id.size")))) } else { null } override fun create() { database.create .createTableIfNotExists(RPKIT_LOCKED_BLOCK) .column(RPKIT_LOCKED_BLOCK.ID, SQLDataType.INTEGER.identity(true)) .column(RPKIT_LOCKED_BLOCK.WORLD, SQLDataType.VARCHAR(256)) .column(RPKIT_LOCKED_BLOCK.X, SQLDataType.INTEGER) .column(RPKIT_LOCKED_BLOCK.Y, SQLDataType.INTEGER) .column(RPKIT_LOCKED_BLOCK.Z, SQLDataType.INTEGER) .constraints( constraint("pk_rpkit_locked_block").primaryKey(RPKIT_LOCKED_BLOCK.ID) ) .execute() } override fun applyMigrations() { if (database.getTableVersion(this) == null) { database.setTableVersion(this, "1.1.0") } } override fun insert(entity: RPKLockedBlock): Int { database.create .insertInto( RPKIT_LOCKED_BLOCK, RPKIT_LOCKED_BLOCK.WORLD, RPKIT_LOCKED_BLOCK.X, RPKIT_LOCKED_BLOCK.Y, RPKIT_LOCKED_BLOCK.Z ) .values( entity.block.world.name, entity.block.x, entity.block.y, entity.block.z ) .execute() val id = database.create.lastID().toInt() entity.id = id cache?.put(id, entity) return id } override fun update(entity: RPKLockedBlock) { database.create .update(RPKIT_LOCKED_BLOCK) .set(RPKIT_LOCKED_BLOCK.WORLD, entity.block.world.name) .set(RPKIT_LOCKED_BLOCK.X, entity.block.x) .set(RPKIT_LOCKED_BLOCK.Y, entity.block.y) .set(RPKIT_LOCKED_BLOCK.Z, entity.block.z) .where(RPKIT_LOCKED_BLOCK.ID.eq(entity.id)) .execute() cache?.put(entity.id, entity) } override fun get(id: Int): RPKLockedBlock? { if (cache?.containsKey(id) == true) { return cache[id] } else { val result = database.create .select( RPKIT_LOCKED_BLOCK.WORLD, RPKIT_LOCKED_BLOCK.X, RPKIT_LOCKED_BLOCK.Y, RPKIT_LOCKED_BLOCK.Z ) .from(RPKIT_LOCKED_BLOCK) .where(RPKIT_LOCKED_BLOCK.ID.eq(id)) .fetchOne() ?: return null val block = plugin.server.getWorld(result.get(RPKIT_LOCKED_BLOCK.WORLD))?.getBlockAt( result.get(RPKIT_LOCKED_BLOCK.X), result.get(RPKIT_LOCKED_BLOCK.Y), result.get(RPKIT_LOCKED_BLOCK.Z) ) if (block == null) { database.create .deleteFrom(RPKIT_LOCKED_BLOCK) .where(RPKIT_LOCKED_BLOCK.ID.eq(id)) .execute() cache?.remove(id) return null } val lockedBlock = RPKLockedBlock( id, block ) cache?.put(id, lockedBlock) return lockedBlock } } fun get(block: Block): RPKLockedBlock? { val result = database.create .select(RPKIT_LOCKED_BLOCK.ID) .from(RPKIT_LOCKED_BLOCK) .where(RPKIT_LOCKED_BLOCK.WORLD.eq(block.world.name)) .and(RPKIT_LOCKED_BLOCK.X.eq(block.x)) .and(RPKIT_LOCKED_BLOCK.Y.eq(block.y)) .and(RPKIT_LOCKED_BLOCK.Z.eq(block.z)) .fetchOne() ?: return null return get(result[RPKIT_LOCKED_BLOCK.ID]) } override fun delete(entity: RPKLockedBlock) { database.create .deleteFrom(RPKIT_LOCKED_BLOCK) .where(RPKIT_LOCKED_BLOCK.ID.eq(entity.id)) .execute() cache?.remove(entity.id) } }
apache-2.0
a36cd6783f3be5017f16316404e21338
38.134328
139
0.545489
4.515935
false
true
false
false
paoloach/zdomus
temperature_monitor/app/src/main/java/it/achdjian/paolo/temperaturemonitor/domusEngine/rest/RequestAttributes.kt
1
1734
package it.achdjian.paolo.temperaturemonitor.domusEngine.rest import android.util.Log import com.fasterxml.jackson.core.type.TypeReference import it.achdjian.paolo.temperaturemonitor.domusEngine.AttributeCoord import it.achdjian.paolo.temperaturemonitor.domusEngine.DomusEngine import it.achdjian.paolo.temperaturemonitor.domusEngine.MessageType import java.io.IOException /** * Created by Paolo Achdjian on 18/05/16. */ class RequestAttributes(val coord: AttributeCoord, val domusEngineRest: DomusEngineRest, val domusEngine: DomusEngine) : ZigbeeRunnable() { override fun run() { val builder = StringBuilder("/devices/"). append(Integer.toString(coord.networkdId, 16)). append("/endpoint/"). append(Integer.toString(coord.endpointId, 16)). append("/cluster/in/"). append(Integer.toString(coord.clusterId, 16)). append("/attributes?id="). append(coord.attributeId) Log.d(TAG, builder.toString()) val body = domusEngineRest.get(builder.toString()) if (body.isNotBlank()) { try { val jsonAttributes = MAPPER.readValue<List<JSonAttribute>>(body, object : TypeReference<List<JSonAttribute>>() {}) val attributes = Attributes(coord.networkdId, coord.endpointId, coord.clusterId, jsonAttributes) domusEngine.handler.sendMessage(domusEngine.handler.obtainMessage(MessageType.NEW_ATTRIBUTES, attributes)) }catch (e: IOException) { Log.e(TAG, "Error parsing response for ${coord}", e) Log.e(TAG, "Response: " + body) e.printStackTrace() } } } }
gpl-2.0
d7e96b0b919a158446f262d65d858c08
44.631579
139
0.654556
4.750685
false
false
false
false
BILLyTheLiTTle/KotlinExperiments
src/main/kotlin/basics/Enums.kt
1
3463
package basics /* PARADIGM 3 In case I import something from Kotlin packages I could import anything apart from classes. I could import public functions are variables. Here I import the constant values of the Planet class */ import basics.Planet.* /** * Created by Tsapalos on 29/06/17. * Those examples are stolen from Java! * https://docs.oracle.com/javase/tutorial/java/javaOO/enum.html */ /* PARADIGM 1 Simple enum class example */ enum class Day{ SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY } /* PARADIGM 2 Complicated enum class example */ enum class Planet (val mass: Double, val radius: Double) { MERCURY (3.303e+23, 2.4397e6), VENUS (4.869e+24, 6.0518e6), EARTH (5.976e+24, 6.37814e6), MARS (6.421e+23, 3.3972e6), JUPITER (1.9e+27, 7.1492e7), SATURN (5.688e+26, 6.0268e7), URANUS (8.686e+25, 2.5559e7), NEPTUNE (1.024e+26, 2.4746e7); // The only position a semicolon truly needed! private val g: Double = 6.67300e-11 //Java has this as static but static variable declaration is in another package fun surfaceGravity() = g * mass / (radius * radius) fun surfaceWeight(otherMass: Double): Double = otherMass * surfaceGravity() } /* PARADIGM 4 Use the enum class Day to show the "when" expression in action with enums! */ fun showFeelingsOfTheDay (today: Day)= when (today) { Day.MONDAY -> "Thanks God, I will go to work again" Day.TUESDAY, Day.WEDNESDAY -> "I miss Monday so much" Day.THURSDAY -> "One more day to have a boring weekend" Day.FRIDAY -> "What an productive week!" Day.SATURDAY -> "What to do with my life now?" Day.SUNDAY -> "Finally, 24 hours left for the Monday!" } /* PARADIGM 5 Using "when" with arbitrary objects */ fun showMixedFeelings (day1: Day, day2: Day) = when (setOf(day1, day2)) { setOf(Day.SATURDAY, Day.SUNDAY) -> "I don't need these 2 days" else -> "At least we are going to work" } /* PARADIGM 6 "When" without argument */ fun showRealFeelingsOfTheDay (today: Day): String { val feeling = when { (today == Day.MONDAY) -> "Thanks God, I will go to work again" (today == Day.TUESDAY) || (today == Day.WEDNESDAY) -> "I miss Monday so much" (today == Day.THURSDAY) -> "One more day to have a boring weekend" (today == Day.FRIDAY) -> "What an productive week!" (today == Day.SATURDAY) -> "What to do with my life now?" (today == Day.SUNDAY) -> "Finally, 24 hours left for the Monday!" else -> "Let me work all day long" } return feeling+"\nBoss is still watching me, guys!" } fun main(args: Array<String>){ // PARADIGM 1 println("PARADIGM 1") val myFavoriteDay = Day.MONDAY if(myFavoriteDay == Day.MONDAY){ println("Really? Are you human?") } // PARADIGM 2, 3 println("\nPARADIGM 2, 3") val myEarthWeight = 82.0 // Thanks Kotlin for keeping my weight immutable (it is val, remember?)! You are so kind! val mass = myEarthWeight / EARTH.surfaceGravity() println("My weight in Mars is: ${MARS.surfaceWeight(mass)}") // PARADIGM 4 println("\nPARADIGM 4") println(showFeelingsOfTheDay(Day.WEDNESDAY)) // PARADIGM 5 println("\nPARADIGM 5") println(showMixedFeelings(Day.SUNDAY, Day.SATURDAY)) // PARADIGM 6 println("\nPARADIGM 6") println(showRealFeelingsOfTheDay(Day.SUNDAY)) }
gpl-3.0
2d9916406aa22d65dcaa8fb72d170bce
31.679245
119
0.650014
3.49798
false
false
false
false
hazuki0x0/YuzuBrowser
module/ui/src/main/java/jp/hazuki/yuzubrowser/ui/settings/fragment/YuzuBasePreferenceFragment.kt
1
3186
/* * Copyright (C) 2017-2020 Hazuki * * 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 jp.hazuki.yuzubrowser.ui.settings.fragment import android.os.Bundle import android.text.TextUtils import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.preference.Preference import androidx.preference.PreferenceFragmentCompat import androidx.preference.PreferenceScreen import jp.hazuki.yuzubrowser.ui.PREFERENCE_FILE_NAME import jp.hazuki.yuzubrowser.ui.R abstract class YuzuBasePreferenceFragment : PreferenceFragmentCompat() { var preferenceResId: Int = 0 private set abstract fun onCreateYuzuPreferences(savedInstanceState: Bundle?, rootKey: String?) override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) { preferenceManager.sharedPreferencesName = PREFERENCE_FILE_NAME onCreateYuzuPreferences(savedInstanceState, rootKey) } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { return try { super.onCreateView(inflater, container, savedInstanceState) } finally { activity?.let { preferenceManager.sharedPreferencesName = PREFERENCE_FILE_NAME val a = it.theme.obtainStyledAttributes(intArrayOf(android.R.attr.listDivider)) val divider = a.getDrawable(0) a.recycle() setDivider(divider) } } } override fun onResume() { super.onResume() val activity = activity ?: return preferenceScreen?.run { val key = arguments?.getString(ARG_PREFERENCE_ROOT) val title = if (!key.isNullOrEmpty()) findPreference<Preference>(key)?.title ?: title else title activity.title = if (TextUtils.isEmpty(title)) getText(R.string.pref_settings) else title } } override fun addPreferencesFromResource(preferencesResId: Int) { super.addPreferencesFromResource(preferencesResId) this.preferenceResId = preferencesResId } override fun setPreferencesFromResource(preferencesResId: Int, key: String?) { super.setPreferencesFromResource(preferencesResId, key) this.preferenceResId = preferencesResId } open fun onPreferenceStartScreen(pref: PreferenceScreen): Boolean = false protected fun openFragment(fragment: PreferenceFragmentCompat) { requireActivity().supportFragmentManager.beginTransaction() .replace(R.id.container, fragment) .addToBackStack(null) .commit() } }
apache-2.0
646778f6de0f05a3f3c52b8ddbbc2641
36.046512
116
0.706529
5.08134
false
false
false
false
spinnaker/kork
kork-plugins/src/main/kotlin/com/netflix/spinnaker/kork/plugins/sdk/httpclient/Ok3HttpClient.kt
3
3540
/* * Copyright 2020 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.spinnaker.kork.plugins.sdk.httpclient import com.fasterxml.jackson.databind.ObjectMapper import com.netflix.spinnaker.kork.exceptions.IntegrationException import com.netflix.spinnaker.kork.plugins.api.httpclient.HttpClient import com.netflix.spinnaker.kork.plugins.api.httpclient.Request import com.netflix.spinnaker.kork.plugins.api.httpclient.Response import java.io.IOException import okhttp3.Headers import okhttp3.HttpUrl import okhttp3.MediaType import okhttp3.OkHttpClient import okhttp3.RequestBody import org.slf4j.LoggerFactory /** * An OkHttp3 [HttpClient] implementation. */ class Ok3HttpClient( internal val name: String, internal val baseUrl: String, private val client: OkHttpClient, private val objectMapper: ObjectMapper ) : HttpClient { private val log by lazy { LoggerFactory.getLogger(javaClass) } override fun get(request: Request): Response { return doRequest(request) { it.get() } } override fun post(request: Request): Response { return doRequest(request) { it.post(request.okHttpRequestBody()) } } override fun put(request: Request): Response { return doRequest(request) { it.put(request.okHttpRequestBody()) } } override fun delete(request: Request): Response { return doRequest(request) { if (request.body == null) { it.delete() } else { it.delete(request.okHttpRequestBody()) } } } override fun patch(request: Request): Response { return doRequest(request) { it.patch(request.okHttpRequestBody()) } } private fun doRequest(request: Request, builderCallback: (okhttp3.Request.Builder) -> Unit): Response { val okRequest = requestBuilder(request) .apply(builderCallback) .build() return try { client.newCall(okRequest).execute().use { it.toGenericResponse() } } catch (io: IOException) { log.error("${okRequest.tag()} request failed", io) Ok3Response( objectMapper = objectMapper, response = null, exception = io ) } } private fun requestBuilder(request: Request): okhttp3.Request.Builder { val url = (baseUrl + request.path).replace("//", "/") val httpUrlBuilder = HttpUrl.parse(url)?.newBuilder() ?: throw IntegrationException("Unable to parse url '$baseUrl'") request.queryParams.forEach { httpUrlBuilder.addQueryParameter(it.key, it.value) } return okhttp3.Request.Builder() .tag("$name.${request.name}") .url(httpUrlBuilder.build()) .headers(Headers.of(request.headers)) } private fun Request.okHttpRequestBody(): RequestBody = RequestBody.create(MediaType.parse(contentType), objectMapper.writeValueAsString(body)) private fun okhttp3.Response.toGenericResponse(): Response { return Ok3Response( objectMapper = objectMapper, response = this, exception = null ) } }
apache-2.0
0aa648887f46e3592529ec3380e80dc3
28.5
105
0.702825
4.301337
false
false
false
false
grote/Transportr
app/src/main/java/de/grobox/transportr/locations/LineAdapter.kt
1
1807
/* * Transportr * * Copyright (c) 2013 - 2021 Torsten Grote * * This program is Free Software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package de.grobox.transportr.locations import android.view.LayoutInflater import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import de.grobox.transportr.R import de.grobox.transportr.ui.LineView import de.schildbach.pte.dto.Line internal class LineAdapter : RecyclerView.Adapter<LineViewHolder>() { private var lines: List<Line> = emptyList() override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): LineViewHolder { val v = LayoutInflater.from(parent.context).inflate(R.layout.list_item_line, parent, false) as LineView return LineViewHolder(v) } override fun onBindViewHolder(holder: LineViewHolder, position: Int) { holder.bind(lines[position]) } override fun getItemCount() = lines.size fun swapLines(linesToSwap: List<Line>) { lines = linesToSwap notifyDataSetChanged() } } internal class LineViewHolder(private val lineView: LineView) : RecyclerView.ViewHolder(lineView) { fun bind(line: Line) = lineView.setLine(line) }
gpl-3.0
7085860d97ef688ca6af51ae57f0533f
30.701754
111
0.722745
4.144495
false
false
false
false
ilya-g/kotlinx.collections.immutable
benchmarks/commonMain/src/benchmarks/immutablePercentage.kt
1
510
/* * Copyright 2016-2019 JetBrains s.r.o. * Use of this source code is governed by the Apache 2.0 License that can be found in the LICENSE.txt file. */ package benchmarks import kotlin.math.floor const val IP_100 = "100.0" const val IP_99_09 = "99.09" const val IP_95 = "95.0" const val IP_70 = "70.0" const val IP_50 = "50.0" const val IP_30 = "30.0" const val IP_0 = "0.0" fun immutableSize(size: Int, immutablePercentage: Double): Int { return floor(size * immutablePercentage / 100.0).toInt() }
apache-2.0
b1a919b9e50859b39d83cbc5fccca088
23.333333
107
0.688235
2.931034
false
false
false
false
jmiecz/YelpBusinessExample
app/src/main/java/net/mieczkowski/yelpbusinessexample/controllers/search/SearchController.kt
1
8884
package net.mieczkowski.yelpbusinessexample.controllers.search import android.graphics.Color import android.location.Location import android.os.Bundle import android.support.v7.widget.LinearLayoutManager import android.view.View import android.widget.Toast import com.bluelinelabs.conductor.ControllerChangeHandler import com.bluelinelabs.conductor.ControllerChangeType import io.reactivex.Completable import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.disposables.Disposable import kotlinx.android.synthetic.main.controller_search.view.* import net.mieczkowski.dal.cache.models.PreviousSearch import net.mieczkowski.dal.exts.observeOnMain import net.mieczkowski.dal.services.businessLookupService.BusinessLookupService import net.mieczkowski.dal.services.businessLookupService.models.BusinessLookupRequest import net.mieczkowski.dal.services.businessLookupService.models.MyLocation import net.mieczkowski.dal.services.businessLookupService.models.YelpBusiness import net.mieczkowski.dal.services.locationService.LocationService import net.mieczkowski.yelpbusinessexample.R import net.mieczkowski.yelpbusinessexample.controllers.base.BaseController import net.mieczkowski.yelpbusinessexample.exts.addDividerLine import net.mieczkowski.yelpbusinessexample.interfaces.PreviousSearchContract import net.mieczkowski.yelpbusinessexample.recyclerAdapters.searchBusiness.SearchBusinessAdapter import net.mieczkowski.yelpbusinessexample.recyclerAdapters.searchHistory.SearchHistoryAdapter import org.koin.standalone.inject import java.util.concurrent.TimeUnit /** * Created by Josh Mieczkowski on 10/19/2017. */ class SearchController(args: Bundle? = null) : BaseController(args), PreviousSearchContract { private val SEARCH_SAVE = "searchSave" private val CURRENT_QUERY = "currentQuery" private val locationService: LocationService by inject() private var locationDisposable: Disposable? = null private var myLocation: MyLocation? = null private val businessLookupService: BusinessLookupService by inject() private var businessDisposable: Disposable? = null private var searchHistoryAdapter: SearchHistoryAdapter? = null private var searchBusinessAdapter: SearchBusinessAdapter? = null private var currentSearch: String? = null private var currentQuery: String? = null private lateinit var searchViewHolder: SearchViewHolder override fun getLayoutID(): Int = R.layout.controller_search override fun onViewBound(view: View, savedViewState: Bundle?) { setTitle(null) setupToolbar(view) listenForLocation() setRecyclerView(view) view.layoutRefresh.setOnRefreshListener { searchForBusinesses(searchViewHolder.getSearchQuery()) } } private fun setupToolbar(view: View) { iToolbar.getSupportActionBar()?.apply { setDisplayHomeAsUpEnabled(true) setDisplayShowHomeEnabled(true) setHomeAsUpIndicator(R.drawable.ic_arrow_back_white_24dp) } iToolbar.getToolBar().setNavigationOnClickListener { router.popController(this) } searchViewHolder = SearchViewHolder(view.context) iToolbar.getToolBar().addView(searchViewHolder.view) searchViewHolder.setOnQuerySelected { query -> val previousSearch = PreviousSearch().apply { searchTerm = query } previousSearch.save() searchHistoryAdapter?.addQuery(previousSearch) searchForBusinesses(query) } searchViewHolder.setOnTextChange { newText -> if (newText.isEmpty()) { currentSearch = null setSearchHistoryAdapter() } } restoreSearchData() } override fun onSaveViewState(view: View, outState: Bundle) { super.onSaveViewState(view, outState) if (currentSearch?.isNotEmpty() == true) { outState.putString(SEARCH_SAVE, currentSearch) } else { val query = searchViewHolder.getSearchQuery() if (query.isNotEmpty()) outState.putString(CURRENT_QUERY, query) } } override fun onRestoreViewState(view: View, savedViewState: Bundle) { super.onRestoreViewState(view, savedViewState) currentSearch = null currentQuery = null if (savedViewState.containsKey(SEARCH_SAVE)) { currentSearch = savedViewState.getString(SEARCH_SAVE) } else if (savedViewState.containsKey(CURRENT_QUERY)) { currentQuery = savedViewState.getString(CURRENT_QUERY) } } override fun onDestroyView(view: View) { businessDisposable?.dispose() locationDisposable?.dispose() super.onDestroyView(view) } override fun onChangeStarted(changeHandler: ControllerChangeHandler, changeType: ControllerChangeType) { super.onChangeStarted(changeHandler, changeType) if(changeType == ControllerChangeType.POP_EXIT || changeType == ControllerChangeType.PUSH_EXIT){ iToolbar.getToolBar().removeView(searchViewHolder.view) }else{ restoreSearchData() } } override fun onPreviousSearchClicked(previousSearch: PreviousSearch) { searchViewHolder.setCurrentSearchQuery(previousSearch.searchTerm) searchForBusinesses(previousSearch.searchTerm) } private fun listenForLocation() { locationDisposable?.dispose() locationDisposable = locationService.getLocationObserver().subscribe({ setMyLocation(it) }, { it.printStackTrace() }) } private fun setMyLocation(location: Location) { myLocation = MyLocation(location.latitude, location.longitude) } private fun restoreSearchData() { currentSearch?.let { searchViewHolder.setCurrentSearchQuery(it) getCacheBusinesses(it) } ?: currentQuery?.let { searchViewHolder.setCurrentSearchQuery(it) setSearchHistoryAdapter() } } private fun getCacheBusinesses(currentSearch: String) { businessLookupService.cacheLookUpByName(currentSearch) .observeOn(AndroidSchedulers.mainThread()) .subscribe({ yelpBusinesses -> if (yelpBusinesses.isEmpty()) { searchForBusinesses(currentSearch) } else { setSearchBusinessAdapter(yelpBusinesses) } }, { it.printStackTrace() }) } private fun setRecyclerView(view: View) { view.recyclerView.let { it.layoutManager = LinearLayoutManager(applicationContext) it.addDividerLine { it.color(Color.LTGRAY) .sizeResId(R.dimen.divider) } } //TODO: Need to figure out what is causing this adapter to not load when controller starts Completable.timer(10, TimeUnit.MILLISECONDS) .observeOnMain() .subscribe { setSearchHistoryAdapter() } } private fun setSearchHistoryAdapter() { view?.layoutRefresh?.isEnabled = false if (searchHistoryAdapter == null) { searchHistoryAdapter = SearchHistoryAdapter.newInstance(this) } view?.recyclerView?.adapter = searchHistoryAdapter } private fun setSearchBusinessAdapter(YelpBusinesss: List<YelpBusiness>) { view?.layoutRefresh?.let { it.isRefreshing = false it.isEnabled = true } searchBusinessAdapter = SearchBusinessAdapter(YelpBusinesss, router) view?.recyclerView?.adapter = searchBusinessAdapter view?.requestFocus() } private fun searchForBusinesses(search: String) { currentSearch = search view?.layoutRefresh?.isRefreshing = true myLocation?.let { businessDisposable?.dispose() businessDisposable = businessLookupService.lookUpByName(BusinessLookupRequest(search, it)) .observeOnMain() .subscribe({ setSearchBusinessAdapter(it) }, { it.printStackTrace() setSearchBusinessAdapter(ArrayList()) }) } ?: let { Toast.makeText(applicationContext, "Grabbing your location, please wait.", Toast.LENGTH_LONG).show() locationService.getLocation() .observeOnMain() .subscribe({ setMyLocation(it) searchForBusinesses(search) }, { it.printStackTrace() }) } } }
apache-2.0
f7ac81ed7e5276b06a37ac198d164767
33.976378
112
0.666029
5.597984
false
false
false
false
ibinti/intellij-community
python/src/com/jetbrains/python/codeInsight/typing/PyTypeShed.kt
6
4940
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jetbrains.python.codeInsight.typing import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.PathManager import com.intellij.openapi.projectRoots.Sdk import com.intellij.openapi.vfs.StandardFileSystems import com.intellij.openapi.vfs.VfsUtilCore import com.intellij.openapi.vfs.VirtualFile import com.intellij.psi.util.QualifiedName import com.jetbrains.python.PythonHelpersLocator import com.jetbrains.python.packaging.PyPIPackageUtil import com.jetbrains.python.packaging.PyPackageManagers import com.jetbrains.python.packaging.PyPackageUtil import com.jetbrains.python.psi.LanguageLevel import com.jetbrains.python.sdk.PythonSdkType import java.io.File /** * Utilities for managing the local copy of the typeshed repository. * * The original Git repo is located [here](https://github.com/JetBrains/typeshed). * * @author vlan */ object PyTypeShed { private val ONLY_SUPPORTED_PY2_MINOR = 7 private val SUPPORTED_PY3_MINORS = 2..6 // TODO: Warn about unresolved `import typing` but still resolve it internally for type inference val WHITE_LIST = setOf("typing", "six", "__builtin__", "builtins", "exceptions", "types", "datetime") private val BLACK_LIST = setOf<String>() /** * Returns true if we allow to search typeshed for a stub for [name]. */ fun maySearchForStubInRoot(name: QualifiedName, root: VirtualFile, sdk : Sdk): Boolean { val topLevelPackage = name.firstComponent ?: return false if (topLevelPackage in BLACK_LIST) { return false } if (topLevelPackage !in WHITE_LIST) { return false } if (isInStandardLibrary(root)) { return true } if (isInThirdPartyLibraries(root)) { if (ApplicationManager.getApplication().isUnitTestMode) { return true } val pyPIPackages = PyPIPackageUtil.PACKAGES_TOPLEVEL[topLevelPackage] ?: emptyList() val packages = PyPackageManagers.getInstance().forSdk(sdk).packages ?: return true return PyPackageUtil.findPackage(packages, topLevelPackage) != null || pyPIPackages.any { PyPackageUtil.findPackage(packages, it) != null } } return false } /** * Returns the list of roots in typeshed for the Python language level of [sdk]. */ fun findRootsForSdk(sdk: Sdk): List<VirtualFile> { val level = PythonSdkType.getLanguageLevelForSdk(sdk) val dir = directory ?: return emptyList() return findRootsForLanguageLevel(level) .asSequence() .map { dir.findFileByRelativePath(it) } .filterNotNull() .toList() } /** * Returns the list of roots in typeshed for the specified Python language [level]. */ fun findRootsForLanguageLevel(level: LanguageLevel): List<String> { val minors = when (level.major) { 2 -> listOf(ONLY_SUPPORTED_PY2_MINOR) 3 -> SUPPORTED_PY3_MINORS.reversed().filter { it <= level.minor } else -> return emptyList() } return minors.map { "stdlib/${level.major}.$it" } + listOf("stdlib/${level.major}", "stdlib/2and3", "third_party/${level.major}", "third_party/2and3") } /** * Checks if the [file] is located inside the typeshed directory. */ fun isInside(file: VirtualFile): Boolean { val dir = directory return dir != null && VfsUtilCore.isAncestor(dir, file, true) } /** * The actual typeshed directory. */ val directory: VirtualFile? by lazy { val path = directoryPath ?: return@lazy null StandardFileSystems.local().findFileByPath(path) } val directoryPath: String? get() { val paths = listOf("${PathManager.getConfigPath()}/typeshed", "${PathManager.getConfigPath()}/../typeshed", PythonHelpersLocator.getHelperPath("typeshed")) return paths.asSequence() .filter { File(it).exists() } .firstOrNull() } /** * A shallow check for a [file] being located inside the typeshed third-party stubs. */ fun isInThirdPartyLibraries(file: VirtualFile) = "third_party" in file.path fun isInStandardLibrary(file: VirtualFile) = "stdlib" in file.path private val LanguageLevel.major: Int get() = this.version / 10 private val LanguageLevel.minor: Int get() = this.version % 10 }
apache-2.0
26b4eab1bedf134efd6d36cd9e7ecd05
34.285714
103
0.692105
4.340949
false
false
false
false
cnsgcu/KotlinKoans
src/v_builders/_36_ExtensionFunctionLiterals.kt
1
524
package v_builders import util.* fun todoTask36(): Nothing = TODO( """ Task 36. Read about extension function literals. You can declare `isEven` and `isOdd` as values, that can be called as extension functions. Complete the declarations below. """, documentation = doc36() ) fun task36(): List<Boolean> { val isEven: Int.() -> Boolean = { this % 2 == 0 } val isOdd: Int.() -> Boolean = { !isEven() } return listOf(42.isOdd(), 239.isOdd(), 294823098.isEven()) }
mit
b5e97a87809e3946d24fa0b9c38c2f3d
21.782609
98
0.604962
4
false
false
false
false
RocketChat/Rocket.Chat.Android
app/src/main/java/chat/rocket/android/chatroom/adapter/MessageReactionsAdapter.kt
2
6117
package chat.rocket.android.chatroom.adapter import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import androidx.core.content.ContextCompat import androidx.recyclerview.widget.RecyclerView import chat.rocket.android.R import chat.rocket.android.chatroom.uimodel.ReactionUiModel import chat.rocket.android.dagger.DaggerLocalComponent import chat.rocket.android.emoji.Emoji import chat.rocket.android.emoji.EmojiKeyboardListener import chat.rocket.android.emoji.EmojiPickerPopup import chat.rocket.android.emoji.EmojiReactionListener import chat.rocket.android.infrastructure.LocalRepository import com.bumptech.glide.Glide import kotlinx.android.synthetic.main.item_reaction.view.* import java.util.concurrent.CopyOnWriteArrayList import javax.inject.Inject class MessageReactionsAdapter : RecyclerView.Adapter<RecyclerView.ViewHolder>() { private val reactions = CopyOnWriteArrayList<ReactionUiModel>() var listener: EmojiReactionListener? = null override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder { val inflater = LayoutInflater.from(parent.context) val view: View return when (viewType) { ADD_REACTION_VIEW_TYPE -> { view = inflater.inflate(R.layout.item_add_reaction, parent, false) AddReactionViewHolder(view, listener) } else -> { view = inflater.inflate(R.layout.item_reaction, parent, false) ReactionViewHolder(view, listener) } } } override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) { if (holder is ReactionViewHolder) { holder.bind(reactions[position]) } else { holder as AddReactionViewHolder holder.bind(reactions.first().messageId) } } override fun getItemCount() = if (reactions.isEmpty()) 0 else reactions.size + 1 override fun getItemViewType(position: Int): Int { if (position == reactions.size) { return ADD_REACTION_VIEW_TYPE } return REACTION_VIEW_TYPE } fun addReactions(reactions: List<ReactionUiModel>) { this.reactions.clear() this.reactions.addAllAbsent(reactions) notifyItemRangeInserted(0, reactions.size) } fun clear() { val oldSize = reactions.size reactions.clear() notifyItemRangeRemoved(0, oldSize) } fun contains(reactionShortname: String) = reactions.firstOrNull { it.shortname == reactionShortname } != null class ReactionViewHolder( view: View, private val listener: EmojiReactionListener? ) : RecyclerView.ViewHolder(view), View.OnClickListener, View.OnLongClickListener { @Inject lateinit var localRepository: LocalRepository @Volatile lateinit var reaction: ReactionUiModel @Volatile var clickHandled = false init { DaggerLocalComponent.builder() .context(itemView.context) .build() .inject(this) } fun bind(reaction: ReactionUiModel) { clickHandled = false this.reaction = reaction with(itemView) { if (reaction.url.isNullOrEmpty()) { // The view at index 0 corresponds to the one to display unicode text emoji. view_flipper_reaction.displayedChild = 0 text_emoji.text = reaction.unicode } else { // The view at index 1 corresponds to the one to display custom emojis which are images. view_flipper_reaction.displayedChild = 1 val glideRequest = if (reaction.url!!.endsWith("gif", true)) { Glide.with(context).asGif() } else { Glide.with(context).asBitmap() } glideRequest.load(reaction.url).into(image_emoji) } val myself = localRepository.get(LocalRepository.CURRENT_USERNAME_KEY) if (reaction.usernames.contains(myself)) { val context = itemView.context text_count.setTextColor(ContextCompat.getColor(context, R.color.colorAccent)) } text_count.text = reaction.count.toString() view_flipper_reaction.setOnClickListener(this@ReactionViewHolder) text_count.setOnClickListener(this@ReactionViewHolder) view_flipper_reaction.setOnLongClickListener(this@ReactionViewHolder) text_count.setOnLongClickListener(this@ReactionViewHolder) } } override fun onClick(v: View) { synchronized(this) { if (!clickHandled) { clickHandled = true listener?.onReactionTouched(reaction.messageId, reaction.shortname) } } } override fun onLongClick(v: View?): Boolean { listener?.onReactionLongClicked(reaction.shortname, reaction.isCustom, reaction.url, reaction.usernames) return true } } class AddReactionViewHolder( view: View, private val listener: EmojiReactionListener? ) : RecyclerView.ViewHolder(view) { fun bind(messageId: String) { itemView as ImageView itemView.setOnClickListener { val emojiPickerPopup = EmojiPickerPopup(itemView.context) emojiPickerPopup.listener = object : EmojiKeyboardListener { override fun onEmojiAdded(emoji: Emoji) { listener?.onReactionAdded(messageId, emoji) } } emojiPickerPopup.show() } } } companion object { private const val REACTION_VIEW_TYPE = 0 private const val ADD_REACTION_VIEW_TYPE = 1 } }
mit
5b19edf5a0ac407ba10a9d4e8170fe7f
35.628743
116
0.621056
5.228205
false
false
false
false
joseph-roque/BowlingCompanion
app/src/main/java/ca/josephroque/bowlingcompanion/common/Android.kt
1
1887
package ca.josephroque.bowlingcompanion.common /* * Copyright 2017 Miguel Castiblanco * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import android.os.Handler import android.os.Looper import kotlin.coroutines.experimental.AbstractCoroutineContextElement import kotlin.coroutines.experimental.Continuation import kotlin.coroutines.experimental.ContinuationInterceptor /** * Android Continuation, guarantees that, when resumed, is on the UI Thread * Created by macastiblancot on 2/13/17. */ private class AndroidContinuation<in T>(val cont: Continuation<T>) : Continuation<T> by cont { override fun resume(value: T) { if (Looper.myLooper() == Looper.getMainLooper()) cont.resume(value) else Handler(Looper.getMainLooper()).post { cont.resume(value) } } override fun resumeWithException(exception: Throwable) { if (Looper.myLooper() == Looper.getMainLooper()) cont.resumeWithException(exception) else Handler(Looper.getMainLooper()).post { cont.resumeWithException(exception) } } } /** * Android context, provides an AndroidContinuation, executes everything on the UI Thread */ object Android : AbstractCoroutineContextElement(ContinuationInterceptor), ContinuationInterceptor { override fun <T> interceptContinuation(continuation: Continuation<T>): Continuation<T> = AndroidContinuation(continuation) }
mit
de9e0819b58149f84f4add9d6312df15
39.148936
100
0.757817
4.580097
false
false
false
false
TheFakeMontyOnTheRun/GiovanniTheExplorer
app/src/main/java/br/odb/giovanni/game/LevelFactory.kt
1
3069
package br.odb.giovanni.game import android.content.Context import android.content.res.Resources import br.odb.giovanni.R import kotlin.math.abs object LevelFactory { fun createRandomLevel(i: Int, j: Int, resources: Resources, context: Context): Level { val tilePaletteIndexes = intArrayOf(R.drawable.cave_floor2, R.drawable.cave_floor) val wallPaletteIndexes = intArrayOf(R.drawable.cave2, R.drawable.cave) val level = Level(i, j, resources, tilePaletteIndexes, wallPaletteIndexes) for (x in 0 until i) { level.setTileType(x, 0, Constants.BLOCKING_TILE) level.setTileType(x, j - 1, Constants.BLOCKING_TILE) } for (y in 0 until j) { level.setTileType(0, y, Constants.BLOCKING_TILE) level.setTileType(i - 1, y, Constants.BLOCKING_TILE) } level.miner = Miner(resources, context) level.motherMonster = arrayOfNulls(3) level.motherMonster[0] = MonsterMother(resources, context) level.motherMonster[1] = MonsterMother(resources, context) level.motherMonster[2] = MonsterMother(resources, context) level.dynamite = Dynamite(resources, context) var x: Int var y: Int for (c in 0..9) { x = abs(Math.random() * i).toInt() y = abs(Math.random() * j).toInt() positPillar(x, y, level, c) } for (c in 0..9) { x = abs(Math.random() * (i - 2)).toInt() + 1 y = abs(Math.random() * (j - 2)).toInt() + 1 level.setTileType(x, y, Constants.BLOCKING_TILE) } for (c in 0..6) { x = abs(Math.random() * (i - 2)).toInt() + 1 y = abs(Math.random() * (j - 2)).toInt() + 1 level.setTileType(x, y, Constants.NON_BLOCKING_TILE) } x = i / 2 y = j - 3 - 2 placeMonsterNest(5, 5, level, level.motherMonster[0]!!) placeMonsterNest(i - 5, j - 5, level, level.motherMonster[1]!!) placeMonsterNest(x, j / 2, level, level.motherMonster[2]!!) placeExit(x, y, level) return level } private fun placeExit(i: Int, j: Int, level: Level) { for (a in i - 4 until i + 4) { for (b in j - 4 until j + 4) { level.setTileType(a, b, Constants.NON_BLOCKING_TILE) } } level.setTileType(i - 1, j - 2, Constants.BLOCKING_TILE) level.setTileType(i, j - 2, Constants.BLOCKING_TILE) level.setTileType(i + 1, j - 2, Constants.BLOCKING_TILE) level.setTileType(i + 2, j - 2, Constants.BLOCKING_TILE) level.addActor(i.toFloat(), (j + 1).toFloat(), level.miner!!) level.setTileType(i, j + 4, Constants.NON_BLOCKING_TILE) level.addActor(i.toFloat(), (j + 4).toFloat(), level.dynamite!!) } private fun placeMonsterNest(i: Int, j: Int, level: Level, mm: MonsterMother) { for (a in i - 4 until i + 4) { for (b in j - 4 until j + 4) { level.setTileType(a, b, Constants.NON_BLOCKING_TILE) } } for (y in 1 until level.height - 1) { level.setTileType(i, y, Constants.NON_BLOCKING_TILE) } level.addActor(i.toFloat(), j.toFloat(), mm) } private fun positPillar(x: Int, y: Int, level: Level, radius: Int) { for (i in -radius / 2 until radius / 2) { for (j in -radius / 2 until radius / 2) { level.setTileType(x + i, y + j, Constants.BLOCKING_TILE) } } } }
bsd-3-clause
4b21cac8e2af0c31a0118ea49cef08ab
29.098039
87
0.655588
2.860205
false
false
false
false
RP-Kit/RPKit
bukkit/rpk-payments-bukkit/src/main/kotlin/com/rpkit/payments/bukkit/command/payment/PaymentCommand.kt
1
3671
/* * Copyright 2020 Ren Binden * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.rpkit.payments.bukkit.command.payment import com.rpkit.payments.bukkit.RPKPaymentsBukkit import org.bukkit.command.Command import org.bukkit.command.CommandExecutor import org.bukkit.command.CommandSender /** * Payment command. * Parent for all payment group management commands. */ class PaymentCommand(private val plugin: RPKPaymentsBukkit) : CommandExecutor { private val paymentCreateCommand = PaymentCreateCommand(plugin) private val paymentRemoveCommand = PaymentRemoveCommand(plugin) private val paymentInviteCommand = PaymentInviteCommand(plugin) private val paymentKickCommand = PaymentKickCommand(plugin) private val paymentJoinCommand = PaymentJoinCommand(plugin) private val paymentLeaveCommand = PaymentLeaveCommand(plugin) private val paymentWithdrawCommand = PaymentWithdrawCommand(plugin) private val paymentDepositCommand = PaymentDepositCommand(plugin) private val paymentListCommand = PaymentListCommand(plugin) private val paymentInfoCommand = PaymentInfoCommand(plugin) private val paymentSetCommand = PaymentSetCommand(plugin) override fun onCommand(sender: CommandSender, command: Command, label: String, args: Array<out String>): Boolean { if (args.isNotEmpty()) { val newArgs = args.drop(1).toTypedArray() when { args[0].equals("create", ignoreCase = true) -> return paymentCreateCommand.onCommand(sender, command, label, newArgs) args[0].equals("remove", ignoreCase = true) || args[0].equals("delete", ignoreCase = true) -> return paymentRemoveCommand.onCommand(sender, command, label, newArgs) args[0].equals("invite", ignoreCase = true) -> return paymentInviteCommand.onCommand(sender, command, label, newArgs) args[0].equals("kick", ignoreCase = true) -> return paymentKickCommand.onCommand(sender, command, label, newArgs) args[0].equals("join", ignoreCase = true) -> return paymentJoinCommand.onCommand(sender, command, label, newArgs) args[0].equals("leave", ignoreCase = true) -> return paymentLeaveCommand.onCommand(sender, command, label, newArgs) args[0].equals("withdraw", ignoreCase = true) -> return paymentWithdrawCommand.onCommand(sender, command, label, newArgs) args[0].equals("deposit", ignoreCase = true) -> return paymentDepositCommand.onCommand(sender, command, label, newArgs) args[0].equals("list", ignoreCase = true) -> return paymentListCommand.onCommand(sender, command, label, newArgs) args[0].equals("info", ignoreCase = true) -> return paymentInfoCommand.onCommand(sender, command, label, newArgs) args[0].equals("set", ignoreCase = true) -> return paymentSetCommand.onCommand(sender, command, label, newArgs) else -> sender.sendMessage(plugin.messages["payment-usage"]) } } else { sender.sendMessage(plugin.messages["payment-usage"]) } return true } }
apache-2.0
dc62c82cb9e5b1bb941e9728a81a0dc8
54.621212
144
0.709888
4.670483
false
false
false
false
RP-Kit/RPKit
bukkit/rpk-experience-bukkit/src/main/kotlin/com/rpkit/experience/bukkit/character/ExperienceField.kt
1
2157
/* * Copyright 2022 Ren Binden * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.rpkit.experience.bukkit.character import com.rpkit.characters.bukkit.character.RPKCharacter import com.rpkit.characters.bukkit.character.field.CharacterCardField import com.rpkit.core.service.Services import com.rpkit.experience.bukkit.RPKExperienceBukkit import com.rpkit.experience.bukkit.experience.RPKExperienceService import java.util.concurrent.CompletableFuture import java.util.logging.Level class ExperienceField(private val plugin: RPKExperienceBukkit) : CharacterCardField { override val name = "experience" override fun get(character: RPKCharacter): CompletableFuture<String> { return CompletableFuture.supplyAsync { val experienceService = Services[RPKExperienceService::class.java] ?: return@supplyAsync "" val characterExperience = experienceService.getExperience(character).join() val characterLevel = experienceService.getLevel(character).join() val currentExperience = (characterExperience - experienceService.getExperienceNeededForLevel(characterLevel)) val nextLevelExperience = experienceService.getExperienceNeededForLevel(characterLevel + 1) - experienceService.getExperienceNeededForLevel(characterLevel) return@supplyAsync "$currentExperience/$nextLevelExperience" }.exceptionally { exception -> plugin.logger.log(Level.SEVERE, "Failed to get experience character card field value", exception) throw exception } } }
apache-2.0
289b9697773269c70cfdf0ecc9ef4ef9
42.16
109
0.736208
5.123515
false
false
false
false
RP-Kit/RPKit
bukkit/rpk-trade-bukkit/src/main/kotlin/com/rpkit/trade/bukkit/listener/SignChangeListener.kt
1
2715
/* * Copyright 2021 Ren Binden * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.rpkit.trade.bukkit.listener import com.rpkit.core.service.Services import com.rpkit.economy.bukkit.currency.RPKCurrencyName import com.rpkit.economy.bukkit.currency.RPKCurrencyService import com.rpkit.trade.bukkit.RPKTradeBukkit import org.bukkit.ChatColor.GREEN import org.bukkit.Material import org.bukkit.event.EventHandler import org.bukkit.event.Listener import org.bukkit.event.block.SignChangeEvent /** * Sign change listener for trader signs. */ class SignChangeListener(private val plugin: RPKTradeBukkit) : Listener { @EventHandler fun onSignChange(event: SignChangeEvent) { if (event.getLine(0) != "[trader]") return if (!event.player.hasPermission("rpkit.trade.sign.trader.create")) { event.player.sendMessage(plugin.messages["no-permission-trader-create"]) return } if ((Material.matchMaterial(event.getLine(1) ?: "") == null && (event.getLine(1)?.matches(Regex("\\d+\\s+.*")) != true)) || Material.matchMaterial(event.getLine(1)?.replace(Regex("\\d+\\s+"), "") ?: "") == null) { event.block.breakNaturally() event.player.sendMessage(plugin.messages["trader-sign-invalid-material"]) return } if (event.getLine(2)?.matches(Regex("\\d+ \\| \\d+")) != true) { event.block.breakNaturally() event.player.sendMessage(plugin.messages["trader-sign-invalid-price"]) return } val currencyService = Services[RPKCurrencyService::class.java] if (currencyService == null) { event.block.breakNaturally() event.player.sendMessage(plugin.messages["no-currency-service"]) return } if (currencyService.getCurrency(RPKCurrencyName(event.getLine(3) ?: "")) == null) { event.block.breakNaturally() event.player.sendMessage(plugin.messages["trader-sign-invalid-currency"]) return } event.setLine(0, "$GREEN[trader]") event.player.sendMessage(plugin.messages["trader-sign-valid"]) } }
apache-2.0
1fda3cf7408237b59663b65a1f3666b1
39.537313
108
0.66372
4.248826
false
false
false
false
itachi1706/CheesecakeUtilities
app/src/main/java/com/itachi1706/cheesecakeutilities/modules/apkMirrorDownloader/APKMirrorActivity.kt
1
17629
package com.itachi1706.cheesecakeutilities.modules.apkMirrorDownloader import android.Manifest import android.animation.* import android.content.* import android.content.pm.PackageManager import android.content.res.ColorStateList import android.graphics.Bitmap import android.graphics.Color import android.graphics.LightingColorFilter import android.net.Uri import android.nfc.NdefMessage import android.nfc.NdefRecord import android.nfc.NfcAdapter import android.os.Build import android.os.Bundle import android.os.Handler import android.preference.PreferenceManager import android.view.View import android.view.animation.DecelerateInterpolator import android.webkit.WebChromeClient import android.webkit.WebView import android.widget.FrameLayout import android.widget.LinearLayout import android.widget.ProgressBar import android.widget.RelativeLayout import androidx.annotation.RequiresApi import androidx.core.app.ActivityCompat import androidx.swiperefreshlayout.widget.SwipeRefreshLayout import com.afollestad.materialdialogs.MaterialDialog import com.google.android.material.bottomnavigation.BottomNavigationView import com.google.android.material.floatingactionbutton.FloatingActionButton import com.itachi1706.cheesecakeutilities.BaseActivity import com.itachi1706.cheesecakeutilities.BuildConfig import com.itachi1706.cheesecakeutilities.modules.apkMirrorDownloader.interfaces.AsyncResponse import com.itachi1706.cheesecakeutilities.R import com.itachi1706.cheesecakeutilities.UtilitySettingsActivity import com.itachi1706.helperlib.utils.NotifyUserUtil import im.delight.android.webview.AdvancedWebView class APKMirrorActivity : BaseActivity(), AdvancedWebView.Listener, AsyncResponse { override val helpDescription: String get() = "A downloader utility to download APK files from APKMirror" companion object { private const val APKMIRROR_URL = "https://www.apkmirror.com/" private const val APKMIRROR_UPLOAD_URL = "https://www.apkmirror.com/apk-upload/" private val COLOR_STATES = arrayOf(intArrayOf(android.R.attr.state_checked), intArrayOf(-android.R.attr.state_checked)) } private var webView: AdvancedWebView? = null private var progressBar: ProgressBar? = null private var navigation: BottomNavigationView? = null private var fabSearch: FloatingActionButton? = null private var refreshLayout: SwipeRefreshLayout? = null private var webContainer: RelativeLayout? = null private var progressBarContainer: FrameLayout? = null private var firstLoadingView: LinearLayout? = null private var shortAnimDuration: Int? = null private var previsionThemeColor: Int = Color.parseColor("#FF8B14") private var sharedPreferences: SharedPreferences? = null private var triggerAction = true private var nfcAdapter: NfcAdapter? = null /** * Listens for user clicking on the tab again. We first check if the page is scrolled. If so we move to top, otherwise we refresh the page */ private val tabReselectListener = BottomNavigationView.OnNavigationItemReselectedListener { menuItem -> scrollOrReload(if (menuItem.itemId == R.id.navigation_home) APKMIRROR_URL else if (menuItem.itemId == R.id.navigation_upload) APKMIRROR_UPLOAD_URL else null) } private val tabSelectListener = BottomNavigationView.OnNavigationItemSelectedListener { menuItem -> if (triggerAction) { when (menuItem.itemId) { R.id.navigation_home -> selectNavigationItem(APKMIRROR_URL) //Home pressed R.id.navigation_upload -> selectNavigationItem(APKMIRROR_UPLOAD_URL) //Upload pressed R.id.navigation_settings -> startActivity(Intent(this@APKMirrorActivity, UtilitySettingsActivity::class.java)) //Settings pressed R.id.navigation_exit -> finish() } } triggerAction = true true } private val isWritePermissionGranted: Boolean get() = Build.VERSION.SDK_INT < 23 || checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED private val chromeClient = object : WebChromeClient() { override fun onProgressChanged(view: WebView, progress: Int) { //update the progressbar value val animation = ObjectAnimator.ofInt(progressBar!!, "progress", progress) animation.duration = 100 // 0.5 second animation.interpolator = DecelerateInterpolator() animation.start() } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) try { setTheme(R.style.AppTheme_NoActionBar) setContentView(R.layout.activity_main_apkmirror) //Views refreshLayout = findViewById(R.id.refresh_layout) progressBar = findViewById(R.id.main_progress_bar) navigation = findViewById(R.id.navigation) webContainer = findViewById(R.id.web_container) firstLoadingView = findViewById(R.id.first_loading_view) webView = findViewById(R.id.main_webview) fabSearch = findViewById(R.id.fab_search) progressBarContainer = findViewById(R.id.main_progress_bar_container) sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this) initSearchFab() nfcAdapter = NfcAdapter.getDefaultAdapter(this) shortAnimDuration = resources.getInteger(android.R.integer.config_shortAnimTime) initNavigation() val saveUrl = sharedPreferences!!.getBoolean("apkmirror_save_url", false) val url: String val link = intent val data = link.data url = data?.toString() ?: if (saveUrl) sharedPreferences!!.getString("apkmirror_last_url", APKMIRROR_URL)!! //App was opened from browser else APKMIRROR_URL //data is null which means it was launched normally initWebView(url) // Load Splash Screen (Hacky yes) firstLoadingView!!.visibility = View.VISIBLE firstLoadingView!!.bringToFront() Handler().postDelayed({ if (firstLoadingView!!.visibility == View.VISIBLE) { crossFade(firstLoadingView!!, webContainer!!) crossFade(null, navigation!!) } }, 2000) } catch (e: RuntimeException) { if (BuildConfig.DEBUG) e.printStackTrace() MaterialDialog.Builder(this).title(R.string.apkmirror_error).content(R.string.apkmirror_runtime_error_dialog_content) .positiveText(android.R.string.ok).neutralText(R.string.apkmirror_copy_log).onPositive { _, _ -> finish() }.onNeutral { _, _ -> // Gets a handle to the clipboard service. val clipboard = getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager // Creates a new text clip to put on the clipboard val clip = ClipData.newPlainText("log", e.toString()) clipboard.primaryClip = clip }.show() } } private fun initNavigation() { //Making the bottom navigation do something navigation!!.setOnNavigationItemSelectedListener(tabSelectListener) navigation!!.setOnNavigationItemReselectedListener(tabReselectListener) } private fun initSearchFab() { fabSearch!!.show() fabSearch!!.setOnClickListener { search() } } private fun initWebView(url: String) { webView!!.setListener(this, this) webView!!.addPermittedHostname("apkmirror.com") webView!!.webChromeClient = chromeClient webView!!.setUploadableFileTypes("application/vnd.android.package-archive") webView!!.loadUrl(url) refreshLayout!!.setOnRefreshListener { webView!!.reload() } } override fun onResume() { super.onResume() webView!!.onResume() if (navigation!!.selectedItemId == R.id.navigation_settings) navigation!!.selectedItemId = R.id.navigation_home } override fun onPause() { webView!!.onPause() super.onPause() } override fun onDestroy() { webView!!.onDestroy() super.onDestroy() } override fun onStop() { if (sharedPreferences!!.getBoolean("apkmirror_save_url", false) && webView!!.url != "apkmirror://settings") sharedPreferences!!.edit().putString("apkmirror_last_url", webView!!.url).apply() super.onStop() } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) webView!!.onActivityResult(requestCode, resultCode, data) } override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) webView!!.saveState(outState) } override fun onRestoreInstanceState(savedInstanceState: Bundle) { super.onRestoreInstanceState(savedInstanceState) webView!!.restoreState(savedInstanceState) } override fun onBackPressed() { if (webView != null && webView!!.url == APKMIRROR_UPLOAD_URL) navigation!!.selectedItemId = R.id.navigation_home // Go back to main else if (webView != null && webView!!.url == APKMIRROR_URL) super.onBackPressed() // Base URL so lets exit else if (webView != null) webView!!.goBack() // Back 1 page else { // Go back to main triggerAction = false navigation!!.selectedItemId = R.id.navigation_home } return } private fun runAsync(url: String) { //getting apps val pageAsync = PageAsync() pageAsync.response = this@APKMirrorActivity pageAsync.execute(url) } private fun search() { MaterialDialog.Builder(this).title(R.string.apkmirror_search).inputRange(1, 100).input(R.string.apkmirror_search, R.string.apkmirror_nothing) { _, _ -> }.onPositive { dialog, _ -> if (dialog.inputEditText != null) webView!!.loadUrl("https://www.apkmirror.com/?s=" + dialog.inputEditText!!.text) else NotifyUserUtil.createShortToast(this@APKMirrorActivity, getString(R.string.apkmirror_search_error)) }.negativeText(android.R.string.cancel).show() } private fun scrollOrReload(url: String?) { if (url == null) return if (webView!!.scrollY != 0) webView!!.scrollY = 0 else webView!!.loadUrl(url) } private fun selectNavigationItem(url: String) { webView!!.loadUrl(url) } private fun crossFade(toHide: View?, toShow: View) { toShow.alpha = 0f toShow.visibility = View.VISIBLE toShow.animate().alpha(1f).setDuration(shortAnimDuration!!.toLong()).setListener(null) toHide?.animate()?.alpha(0f)?.setDuration(shortAnimDuration!!.toLong())?.setListener(object : AnimatorListenerAdapter() { override fun onAnimationEnd(animation: Animator) { toHide.visibility = View.GONE } }) } private fun download(url: String, name: String) { if (!sharedPreferences!!.getBoolean("apkmirror_external_download", false)) { if (AdvancedWebView.handleDownload(this, url, name)) NotifyUserUtil.createShortToast(this@APKMirrorActivity, getString(R.string.apkmirror_download_started)) else NotifyUserUtil.createShortToast(this@APKMirrorActivity, getString(R.string.apkmirror_cant_download)) } else startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(url))) } override fun onProcessFinish(themeColor: Int) { // updating interface if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) changeUIColor(themeColor) previsionThemeColor = themeColor } @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) private fun changeUIColor(color: Int) { val anim = ValueAnimator.ofArgb(previsionThemeColor, color) anim.setEvaluator(ArgbEvaluator()) anim.addUpdateListener { valueAnimator -> progressBar!!.progressDrawable.colorFilter = LightingColorFilter(-0x1000000, valueAnimator.animatedValue as Int) setSystemBarColor(valueAnimator.animatedValue as Int) val toUpdate = ColorStateList(COLOR_STATES, intArrayOf(valueAnimator.animatedValue as Int, R.color.inactive_tabs)) navigation!!.itemTextColor = toUpdate navigation!!.itemIconTintList = toUpdate fabSearch!!.backgroundTintList = ColorStateList.valueOf(valueAnimator.animatedValue as Int) } anim.duration = resources.getInteger(android.R.integer.config_shortAnimTime).toLong() anim.start() refreshLayout!!.setColorSchemeColors(color, color, color) } @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) private fun setSystemBarColor(color: Int) { val clr: Int //this makes the color darker or uses nicer orange color if (color != Color.parseColor("#FF8B14")) { val hsv = FloatArray(3) Color.colorToHSV(color, hsv) hsv[2] *= 0.8f clr = Color.HSVToColor(hsv) } else clr = Color.parseColor("#F47D20") val window = [email protected] window.statusBarColor = clr } private fun setupNFC(url: String) { if (nfcAdapter != null) { // in case there is no NFC try { // create an NDEF message containing the current URL: val rec = NdefRecord.createUri(url) // url: current URL (String or Uri) val ndef = NdefMessage(rec) // make it available via Android Beam: nfcAdapter!!.setNdefPushMessage(ndef, this, this) } catch (e: IllegalStateException) { e.printStackTrace() } } } //WebView factory methods bellow override fun onPageStarted(url: String, favicon: Bitmap?) { if (!url.contains("https://www.apkmirror.com/wp-content/") || !url.contains("http://www.apkmirror.com/wp-content/")) { runAsync(url) setupNFC(url) //Updating bottom navigation if (navigation!!.selectedItemId == R.id.navigation_home) { if (url == APKMIRROR_UPLOAD_URL) { triggerAction = false navigation!!.selectedItemId = R.id.navigation_upload } } else if (navigation!!.selectedItemId == R.id.navigation_upload) { if (url != APKMIRROR_UPLOAD_URL) { triggerAction = false navigation!!.selectedItemId = R.id.navigation_home } } //Showing progress bar progressBarContainer!!.animate().alpha(1f).setDuration(resources.getInteger(android.R.integer.config_shortAnimTime).toLong()).setListener(object : AnimatorListenerAdapter() { override fun onAnimationStart(animation: Animator) { super.onAnimationStart(animation) progressBarContainer!!.visibility = View.VISIBLE } }) } } override fun onPageFinished(url: String) { progressBarContainer!!.animate().alpha(0f).setDuration(resources.getInteger(android.R.integer.config_longAnimTime).toLong()).setListener(object : AnimatorListenerAdapter() { override fun onAnimationEnd(animation: Animator) { super.onAnimationEnd(animation) progressBarContainer!!.visibility = View.GONE } }) if (refreshLayout!!.isRefreshing) refreshLayout!!.isRefreshing = false } override fun onPageError(errorCode: Int, description: String, failingUrl: String) { if (errorCode == -2) { MaterialDialog.Builder(this).title(R.string.apkmirror_error).content(getString(R.string.apkmirror_error_while_loading_page) + " " + failingUrl + "(" + errorCode + " " + description + ")") .positiveText(R.string.apkmirror_refresh).negativeText(android.R.string.cancel).neutralText("Dismiss").onPositive { dialog, _ -> webView!!.reload() dialog.dismiss() }.onNegative { _, _ -> finish() }.onNeutral { materialDialog, _ -> materialDialog.dismiss() }.show() } } override fun onDownloadRequested(url: String, suggestedFilename: String, mimeType: String, contentLength: Long, contentDisposition: String, userAgent: String) { if (isWritePermissionGranted) download(url, suggestedFilename) else MaterialDialog.Builder(this@APKMirrorActivity).title(R.string.apkmirror_write_permission).content(R.string.apkmirror_storage_access) .positiveText(R.string.apkmirror_request_permission).negativeText(android.R.string.cancel) .onPositive { _, _ -> ActivityCompat.requestPermissions(this@APKMirrorActivity, arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE), 1) } .show() } override fun onExternalPageRequest(url: String) { val browserIntent = Intent(Intent.ACTION_VIEW, Uri.parse(url)) startActivity(browserIntent) } }
mit
04a556fa3460c6d20cce67e6401f0392
42.744417
267
0.655511
5.049842
false
false
false
false
mmjang/ankihelper
folioreader/src/main/java/com/folioreader/view/FolioWebView.kt
1
31087
package com.folioreader.view import android.content.Context import android.content.Intent import android.graphics.Rect import android.graphics.drawable.BitmapDrawable import android.graphics.drawable.Drawable import android.os.Build import android.os.Bundle import android.os.Handler import android.os.Looper import android.support.annotation.RequiresApi import android.support.v4.content.ContextCompat import android.support.v4.view.GestureDetectorCompat import android.util.AttributeSet import android.util.DisplayMetrics import android.util.Log import android.view.* import android.view.ActionMode.Callback import android.view.ViewGroup.LayoutParams.WRAP_CONTENT import android.webkit.ConsoleMessage import android.webkit.JavascriptInterface import android.webkit.WebView import android.widget.PopupWindow import android.widget.Toast import com.folioreader.Config import com.folioreader.Constants import com.folioreader.R import com.folioreader.model.HighLight import com.folioreader.model.HighlightImpl.HighlightStyle import com.folioreader.model.sqlite.HighLightTable import com.folioreader.ui.folio.activity.FolioActivity import com.folioreader.ui.folio.activity.FolioActivityCallback import com.folioreader.ui.folio.fragment.DictionaryFragment import com.folioreader.ui.folio.fragment.FolioPageFragment import com.folioreader.util.AppUtil import com.folioreader.util.HighlightUtil import com.folioreader.util.UiUtil import dalvik.system.PathClassLoader import kotlinx.android.synthetic.main.text_selection.view.* import org.springframework.util.ReflectionUtils import java.lang.ref.WeakReference /** * @author by mahavir on 3/31/16. */ class FolioWebView : WebView { companion object { val LOG_TAG: String = FolioWebView::class.java.simpleName private const val IS_SCROLLING_CHECK_TIMER = 100 private const val IS_SCROLLING_CHECK_MAX_DURATION = 10000 @JvmStatic fun onWebViewConsoleMessage(cm: ConsoleMessage, LOG_TAG: String, msg: String): Boolean { when (cm.messageLevel()) { ConsoleMessage.MessageLevel.LOG -> { Log.v(LOG_TAG, msg) return true } ConsoleMessage.MessageLevel.DEBUG, ConsoleMessage.MessageLevel.TIP -> { Log.d(LOG_TAG, msg) return true } ConsoleMessage.MessageLevel.WARNING -> { Log.w(LOG_TAG, msg) return true } ConsoleMessage.MessageLevel.ERROR -> { Log.e(LOG_TAG, msg) return true } else -> return false } } } private var horizontalPageCount = 0 private var displayMetrics: DisplayMetrics? = null private var density: Float = 0.toFloat() private var mScrollListener: ScrollListener? = null private var mSeekBarListener: SeekBarListener? = null private lateinit var gestureDetector: GestureDetectorCompat private var eventActionDown: MotionEvent? = null private var pageWidthCssDp: Int = 0 private var pageWidthCssPixels: Float = 0.toFloat() private lateinit var webViewPager: WebViewPager private lateinit var uiHandler: Handler private lateinit var folioActivityCallback: FolioActivityCallback private lateinit var parentFragment: FolioPageFragment private var actionMode: ActionMode? = null private var textSelectionCb: TextSelectionCb? = null private var textSelectionCb2: TextSelectionCb2? = null private var selectionRect = Rect() private val popupRect = Rect() private var popupWindow = PopupWindow() private lateinit var viewTextSelection: View private var isScrollingCheckDuration: Int = 0 private var isScrollingRunnable: Runnable? = null private var oldScrollX: Int = 0 private var oldScrollY: Int = 0 private var lastTouchAction: Int = 0 private var destroyed: Boolean = false private var handleHeight: Int = 0 private var lastScrollType: LastScrollType? = null val contentHeightVal: Int get() = Math.floor((this.contentHeight * this.scale).toDouble()).toInt() val webViewHeight: Int get() = this.measuredHeight private enum class LastScrollType { USER, PROGRAMMATIC } @JavascriptInterface fun toggleSystemUI() { uiHandler.post { folioActivityCallback.toggleSystemUI() } } @JavascriptInterface fun isPopupShowing(): Boolean { return popupWindow.isShowing } private inner class HorizontalGestureListener : GestureDetector.SimpleOnGestureListener() { override fun onScroll(e1: MotionEvent, e2: MotionEvent, distanceX: Float, distanceY: Float): Boolean { //Log.d(LOG_TAG, "-> onScroll -> e1 = " + e1 + ", e2 = " + e2 + ", distanceX = " + distanceX + ", distanceY = " + distanceY); lastScrollType = LastScrollType.USER return false } override fun onFling(e1: MotionEvent, e2: MotionEvent, velocityX: Float, velocityY: Float): Boolean { //Log.d(LOG_TAG, "-> onFling -> e1 = " + e1 + ", e2 = " + e2 + ", velocityX = " + velocityX + ", velocityY = " + velocityY); if (!webViewPager.isScrolling) { // Need to complete the scroll as ViewPager thinks these touch events should not // scroll it's pages. //Log.d(LOG_TAG, "-> onFling -> completing scroll"); uiHandler.postDelayed({ // Delayed to avoid inconsistency of scrolling in WebView scrollTo(getScrollXPixelsForPage(webViewPager!!.currentItem), 0) }, 100) } lastScrollType = LastScrollType.USER return true } override fun onDown(event: MotionEvent): Boolean { //Log.v(LOG_TAG, "-> onDown -> " + event.toString()); eventActionDown = MotionEvent.obtain(event) [email protected](event) return true } } @JavascriptInterface fun dismissPopupWindow(): Boolean { Log.d(LOG_TAG, "-> dismissPopupWindow -> " + parentFragment.spineItem.href) val wasShowing = popupWindow.isShowing if (Looper.getMainLooper().thread == Thread.currentThread()) { popupWindow.dismiss() } else { uiHandler.post { popupWindow.dismiss() } } selectionRect = Rect() uiHandler.removeCallbacks(isScrollingRunnable) isScrollingCheckDuration = 0 return wasShowing } override fun destroy() { super.destroy() Log.d(LOG_TAG, "-> destroy") dismissPopupWindow() destroyed = true } private inner class VerticalGestureListener : GestureDetector.SimpleOnGestureListener() { override fun onScroll(e1: MotionEvent, e2: MotionEvent, distanceX: Float, distanceY: Float): Boolean { //Log.v(LOG_TAG, "-> onScroll -> e1 = " + e1 + ", e2 = " + e2 + ", distanceX = " + distanceX + ", distanceY = " + distanceY); lastScrollType = LastScrollType.USER return false } override fun onFling(e1: MotionEvent, e2: MotionEvent, velocityX: Float, velocityY: Float): Boolean { //Log.v(LOG_TAG, "-> onFling -> e1 = " + e1 + ", e2 = " + e2 + ", velocityX = " + velocityX + ", velocityY = " + velocityY); lastScrollType = LastScrollType.USER return false } } constructor(context: Context) : super(context) constructor(context: Context, attrs: AttributeSet) : super(context, attrs) constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr) private fun init() { Log.v(LOG_TAG, "-> init") uiHandler = Handler() displayMetrics = resources.displayMetrics density = displayMetrics!!.density gestureDetector = if (folioActivityCallback.direction == Config.Direction.HORIZONTAL) { GestureDetectorCompat(context, HorizontalGestureListener()) } else { GestureDetectorCompat(context, VerticalGestureListener()) } initViewTextSelection() } fun initViewTextSelection() { Log.v(LOG_TAG, "-> initViewTextSelection") val textSelectionMiddleDrawable = ContextCompat.getDrawable(context, R.drawable.abc_text_select_handle_middle_mtrl_dark) handleHeight = textSelectionMiddleDrawable?.intrinsicHeight ?: (24 * density).toInt() val config = AppUtil.getSavedConfig(context) val ctw = if (config.isNightMode) { ContextThemeWrapper(context, R.style.FolioNightTheme) } else { ContextThemeWrapper(context, R.style.FolioDayTheme) } viewTextSelection = LayoutInflater.from(ctw).inflate(R.layout.text_selection, null) viewTextSelection.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED) viewTextSelection.yellowHighlight.setOnClickListener { Log.v(LOG_TAG, "-> onClick -> yellowHighlight") onHighlightColorItemsClicked(HighlightStyle.Yellow, false) } viewTextSelection.greenHighlight.setOnClickListener { Log.v(LOG_TAG, "-> onClick -> greenHighlight") onHighlightColorItemsClicked(HighlightStyle.Green, false) } viewTextSelection.blueHighlight.setOnClickListener { Log.v(LOG_TAG, "-> onClick -> blueHighlight") onHighlightColorItemsClicked(HighlightStyle.Blue, false) } viewTextSelection.pinkHighlight.setOnClickListener { Log.v(LOG_TAG, "-> onClick -> pinkHighlight") onHighlightColorItemsClicked(HighlightStyle.Pink, false) } viewTextSelection.underlineHighlight.setOnClickListener { Log.v(LOG_TAG, "-> onClick -> underlineHighlight") onHighlightColorItemsClicked(HighlightStyle.Underline, false) } viewTextSelection.deleteHighlight.setOnClickListener { Log.v(LOG_TAG, "-> onClick -> deleteHighlight") dismissPopupWindow() loadUrl("javascript:clearSelection()") loadUrl("javascript:deleteThisHighlight()") } viewTextSelection.copySelection.setOnClickListener { dismissPopupWindow() loadUrl("javascript:onTextSelectionItemClicked(${it.id})") } viewTextSelection.shareSelection.setOnClickListener { dismissPopupWindow() loadUrl("javascript:onTextSelectionItemClicked(${it.id})") } viewTextSelection.defineSelection.setOnClickListener { dismissPopupWindow() loadUrl("javascript:onTextSelectionItemClicked(${it.id})") } viewTextSelection.helperSelection.setOnClickListener{ dismissPopupWindow() loadUrl("javascript:onHelperItemClicked()") } } @JavascriptInterface fun onTextSelectionItemClicked(id: Int, selectedText: String?) { uiHandler.post { loadUrl("javascript:clearSelection()") } when (id) { R.id.copySelection -> { Log.v(LOG_TAG, "-> onTextSelectionItemClicked -> copySelection -> $selectedText") UiUtil.copyToClipboard(context, selectedText) Toast.makeText(context, context.getString(R.string.copied), Toast.LENGTH_SHORT).show() } R.id.shareSelection -> { Log.v(LOG_TAG, "-> onTextSelectionItemClicked -> shareSelection -> $selectedText") UiUtil.share(context, selectedText) } R.id.defineSelection -> { Log.v(LOG_TAG, "-> onTextSelectionItemClicked -> defineSelection -> $selectedText") uiHandler.post { showDictDialog(selectedText) } } else -> { Log.w(LOG_TAG, "-> onTextSelectionItemClicked -> unknown id = $id") } } } @JavascriptInterface fun onInvokingAnkihelper(word: String, sentence: String){ if(sentence.isNullOrBlank()){ return }else{ var intent = Intent() intent.setAction(Intent.ACTION_SEND); intent.setClassName("com.mmjang.ankihelper", "com.mmjang.ankihelper.ui.popup.PopupActivity") intent.putExtra(Intent.EXTRA_TEXT, sentence) intent.putExtra("com.mmjang.ankihelper.target_word", word) intent.setType("text/plain") context.startActivity(intent) //onHighlightColorItemsClicked(HighlightStyle.Underline, false) } } private fun showDictDialog(selectedText: String?) { val dictionaryFragment = DictionaryFragment() val bundle = Bundle() bundle.putString(Constants.SELECTED_WORD, selectedText?.trim()) dictionaryFragment.arguments = bundle dictionaryFragment.show(parentFragment.fragmentManager, DictionaryFragment::class.java.name) } private fun onHighlightColorItemsClicked(style: HighlightStyle, isAlreadyCreated: Boolean) { parentFragment.highlight(style, isAlreadyCreated) dismissPopupWindow() } @JavascriptInterface fun deleteThisHighlight(id: String?) { Log.d(LOG_TAG, "-> deleteThisHighlight") if (id.isNullOrEmpty()) return val highlightImpl = HighLightTable.getHighlightForRangy(id) if (HighLightTable.deleteHighlight(id)) { val rangy = HighlightUtil.generateRangyString(parentFragment.pageName) uiHandler.post { parentFragment.loadRangy(rangy) } if (highlightImpl != null) { HighlightUtil.sendHighlightBroadcastEvent(context, highlightImpl, HighLight.HighLightAction.DELETE) } } } @JavascriptInterface fun setCompatMode(compatMode: String) { Log.v(LOG_TAG, "-> setCompatMode -> compatMode = $compatMode") if (compatMode == context.getString(R.string.back_compat)) { Log.e(LOG_TAG, "-> Web page loaded in Quirks mode. Please report to developer " + "for debugging with current EPUB file as many features might stop working " + "(ex. Horizontal scroll feature).") } } fun setParentFragment(parentFragment: FolioPageFragment) { this.parentFragment = parentFragment } fun setFolioActivityCallback(folioActivityCallback: FolioActivityCallback) { this.folioActivityCallback = folioActivityCallback init() } override fun onLayout(changed: Boolean, l: Int, t: Int, r: Int, b: Int) { super.onLayout(changed, l, t, r, b) pageWidthCssDp = Math.ceil((measuredWidth / density).toDouble()).toInt() pageWidthCssPixels = pageWidthCssDp * density } fun setScrollListener(listener: ScrollListener) { mScrollListener = listener } fun setSeekBarListener(listener: SeekBarListener) { mSeekBarListener = listener } override fun onTouchEvent(event: MotionEvent): Boolean { //Log.v(LOG_TAG, "-> onTouchEvent -> " + AppUtil.actionToString(event.getAction())); lastTouchAction = event.action return if (folioActivityCallback.direction == Config.Direction.HORIZONTAL) { computeHorizontalScroll(event) } else { computeVerticalScroll(event) } } private fun computeVerticalScroll(event: MotionEvent): Boolean { gestureDetector.onTouchEvent(event) return super.onTouchEvent(event) } private fun computeHorizontalScroll(event: MotionEvent): Boolean { //Log.v(LOG_TAG, "-> computeHorizontalScroll"); webViewPager.dispatchTouchEvent(event) val gestureReturn = gestureDetector.onTouchEvent(event) return if (gestureReturn) true else super.onTouchEvent(event) } fun getScrollXDpForPage(page: Int): Int { //Log.v(LOG_TAG, "-> getScrollXDpForPage -> page = " + page); return page * pageWidthCssDp } fun getScrollXPixelsForPage(page: Int): Int { //Log.v(LOG_TAG, "-> getScrollXPixelsForPage -> page = " + page); return Math.ceil((page * pageWidthCssPixels).toDouble()).toInt() } fun setHorizontalPageCount(horizontalPageCount: Int) { this.horizontalPageCount = horizontalPageCount uiHandler.post { webViewPager = (parent as View).findViewById(R.id.webViewPager) webViewPager.setHorizontalPageCount([email protected]) } } override fun scrollTo(x: Int, y: Int) { super.scrollTo(x, y) //Log.d(LOG_TAG, "-> scrollTo -> x = " + x); lastScrollType = LastScrollType.PROGRAMMATIC } override fun onScrollChanged(l: Int, t: Int, oldl: Int, oldt: Int) { if (mScrollListener != null) mScrollListener!!.onScrollChange(t) super.onScrollChanged(l, t, oldl, oldt) if (lastScrollType == LastScrollType.USER) { //Log.d(LOG_TAG, "-> onScrollChanged -> scroll initiated by user"); loadUrl(context.getString(R.string.make_search_results_invisible)) parentFragment.searchItemVisible = null } lastScrollType = null } interface ScrollListener { fun onScrollChange(percent: Int) } interface SeekBarListener { fun fadeInSeekBarIfInvisible() } private inner class TextSelectionCb : ActionMode.Callback { override fun onCreateActionMode(mode: ActionMode, menu: Menu): Boolean { Log.d(LOG_TAG, "-> onCreateActionMode") //mode.getMenuInflater().inflate(R.menu.menu_text_selection, menu); return true } override fun onPrepareActionMode(mode: ActionMode, menu: Menu): Boolean { Log.d(LOG_TAG, "-> onPrepareActionMode") loadUrl("javascript:getSelectionRect()") return false } override fun onActionItemClicked(mode: ActionMode, item: MenuItem): Boolean { Log.d(LOG_TAG, "-> onActionItemClicked") return false } override fun onDestroyActionMode(mode: ActionMode) { Log.d(LOG_TAG, "-> onDestroyActionMode") dismissPopupWindow() } } @RequiresApi(api = Build.VERSION_CODES.M) private inner class TextSelectionCb2 : ActionMode.Callback2() { override fun onCreateActionMode(mode: ActionMode, menu: Menu): Boolean { Log.d(LOG_TAG, "-> onCreateActionMode") //mode.getMenuInflater().inflate(R.menu.menu_text_selection, menu); menu.clear() return true } override fun onPrepareActionMode(mode: ActionMode, menu: Menu): Boolean { Log.d(LOG_TAG, "-> onPrepareActionMode") return false } override fun onActionItemClicked(mode: ActionMode, item: MenuItem): Boolean { Log.d(LOG_TAG, "-> onActionItemClicked") return false } override fun onDestroyActionMode(mode: ActionMode) { Log.d(LOG_TAG, "-> onDestroyActionMode") dismissPopupWindow() } override fun onGetContentRect(mode: ActionMode, view: View, outRect: Rect) { Log.d(LOG_TAG, "-> onGetContentRect") loadUrl("javascript:getSelectionRect()") } } override fun startActionMode(callback: Callback): ActionMode { Log.d(LOG_TAG, "-> startActionMode") textSelectionCb = TextSelectionCb() actionMode = super.startActionMode(textSelectionCb) actionMode?.finish() /*try { applyThemeColorToHandles() } catch (e: Exception) { Log.w(LOG_TAG, "-> startActionMode -> Failed to apply theme colors to selection " + "handles", e) }*/ return actionMode as ActionMode //Comment above code and uncomment below line for stock text selection //return super.startActionMode(callback) } @RequiresApi(api = Build.VERSION_CODES.M) override fun startActionMode(callback: Callback, type: Int): ActionMode { Log.d(LOG_TAG, "-> startActionMode") textSelectionCb2 = TextSelectionCb2() actionMode = super.startActionMode(textSelectionCb2, type) actionMode?.finish() /*try { applyThemeColorToHandles() } catch (e: Exception) { Log.w(LOG_TAG, "-> startActionMode -> Failed to apply theme colors to selection " + "handles", e) }*/ return actionMode as ActionMode //Comment above code and uncomment below line for stock text selection //return super.startActionMode(callback, type) } private fun applyThemeColorToHandles() { Log.v(LOG_TAG, "-> applyThemeColorToHandles") if (Build.VERSION.SDK_INT < 23) { val folioActivityRef: WeakReference<FolioActivity> = folioActivityCallback.activity val mWindowManagerField = ReflectionUtils.findField(FolioActivity::class.java, "mWindowManager") mWindowManagerField.isAccessible = true val mWindowManager = mWindowManagerField.get(folioActivityRef.get()) val windowManagerImplClass = Class.forName("android.view.WindowManagerImpl") val mGlobalField = ReflectionUtils.findField(windowManagerImplClass, "mGlobal") mGlobalField.isAccessible = true val mGlobal = mGlobalField.get(mWindowManager) val windowManagerGlobalClass = Class.forName("android.view.WindowManagerGlobal") val mViewsField = ReflectionUtils.findField(windowManagerGlobalClass, "mViews") mViewsField.isAccessible = true val mViews = mViewsField.get(mGlobal) as ArrayList<View> val config = AppUtil.getSavedConfig(context) for (view in mViews) { val handleViewClass = Class.forName("com.android.org.chromium.content.browser.input.HandleView") if (handleViewClass.isInstance(view)) { val mDrawableField = ReflectionUtils.findField(handleViewClass, "mDrawable") mDrawableField.isAccessible = true val mDrawable = mDrawableField.get(view) as BitmapDrawable UiUtil.setColorIntToDrawable(config.themeColor, mDrawable) } } } else { val folioActivityRef: WeakReference<FolioActivity> = folioActivityCallback.activity val mWindowManagerField = ReflectionUtils.findField(FolioActivity::class.java, "mWindowManager") mWindowManagerField.isAccessible = true val mWindowManager = mWindowManagerField.get(folioActivityRef.get()) val windowManagerImplClass = Class.forName("android.view.WindowManagerImpl") val mGlobalField = ReflectionUtils.findField(windowManagerImplClass, "mGlobal") mGlobalField.isAccessible = true val mGlobal = mGlobalField.get(mWindowManager) val windowManagerGlobalClass = Class.forName("android.view.WindowManagerGlobal") val mViewsField = ReflectionUtils.findField(windowManagerGlobalClass, "mViews") mViewsField.isAccessible = true val mViews = mViewsField.get(mGlobal) as ArrayList<View> val config = AppUtil.getSavedConfig(context) for (view in mViews) { val popupDecorViewClass = Class.forName("android.widget.PopupWindow\$PopupDecorView") if (!popupDecorViewClass.isInstance(view)) continue val mChildrenField = ReflectionUtils.findField(popupDecorViewClass, "mChildren") mChildrenField.isAccessible = true val mChildren = mChildrenField.get(view) as kotlin.Array<View> //val pathClassLoader = PathClassLoader("/system/app/Chrome/Chrome.apk", ClassLoader.getSystemClassLoader()) val pathClassLoader = PathClassLoader("/system/app/Chrome/Chrome.apk", folioActivityRef.get()?.classLoader) val popupTouchHandleDrawableClass = Class.forName("org.chromium.android_webview.PopupTouchHandleDrawable", true, pathClassLoader) //if (!popupTouchHandleDrawableClass.isInstance(mChildren[0])) // continue val mDrawableField = ReflectionUtils.findField(popupTouchHandleDrawableClass, "mDrawable") mDrawableField.isAccessible = true val mDrawable = mDrawableField.get(mChildren[0]) as Drawable UiUtil.setColorIntToDrawable(config.themeColor, mDrawable) } } } @JavascriptInterface fun setSelectionRect(left: Int, top: Int, right: Int, bottom: Int) { val currentSelectionRect: Rect val newLeft = (left * density).toInt() val newTop = (top * density).toInt() val newRight = (right * density).toInt() val newBottom = (bottom * density).toInt() currentSelectionRect = Rect(newLeft, newTop, newRight, newBottom) Log.d(LOG_TAG, "-> setSelectionRect -> $currentSelectionRect") computeTextSelectionRect(currentSelectionRect) } private fun computeTextSelectionRect(currentSelectionRect: Rect) { Log.v(LOG_TAG, "-> computeTextSelectionRect") val viewportRect = folioActivityCallback.viewportRect Log.d(LOG_TAG, "-> viewportRect -> $viewportRect") if (!Rect.intersects(viewportRect, currentSelectionRect)) { Log.i(LOG_TAG, "-> currentSelectionRect doesn't intersects viewportRect") uiHandler.post { popupWindow.dismiss() uiHandler.removeCallbacks(isScrollingRunnable) } return } Log.i(LOG_TAG, "-> currentSelectionRect intersects viewportRect") if (selectionRect == currentSelectionRect) { Log.i(LOG_TAG, "-> setSelectionRect -> currentSelectionRect is equal to previous " + "selectionRect so no need to computeTextSelectionRect and show popupWindow again") return } Log.i(LOG_TAG, "-> setSelectionRect -> currentSelectionRect is not equal to previous " + "selectionRect so computeTextSelectionRect and show popupWindow") selectionRect = currentSelectionRect val aboveSelectionRect = Rect(viewportRect) aboveSelectionRect.bottom = selectionRect.top - (8 * density).toInt() val belowSelectionRect = Rect(viewportRect) belowSelectionRect.top = selectionRect.bottom + handleHeight //Log.d(LOG_TAG, "-> aboveSelectionRect -> " + aboveSelectionRect); //Log.d(LOG_TAG, "-> belowSelectionRect -> " + belowSelectionRect); // Priority to show popupWindow will be as following - // 1. Show popupWindow below selectionRect, if space available // 2. Show popupWindow above selectionRect, if space available // 3. Show popupWindow in the middle of selectionRect //popupRect initialisation for belowSelectionRect popupRect.left = viewportRect.left popupRect.top = belowSelectionRect.top popupRect.right = popupRect.left + viewTextSelection.measuredWidth popupRect.bottom = popupRect.top + viewTextSelection.measuredHeight //Log.d(LOG_TAG, "-> Pre decision popupRect -> " + popupRect); val popupY: Int if (belowSelectionRect.contains(popupRect)) { Log.i(LOG_TAG, "-> show below") popupY = belowSelectionRect.top } else { // popupRect initialisation for aboveSelectionRect popupRect.top = aboveSelectionRect.top popupRect.bottom = popupRect.top + viewTextSelection.measuredHeight if (aboveSelectionRect.contains(popupRect)) { Log.i(LOG_TAG, "-> show above") popupY = aboveSelectionRect.bottom - popupRect.height() } else { Log.i(LOG_TAG, "-> show in middle") val popupYDiff = (viewTextSelection.measuredHeight - selectionRect.height()) / 2 popupY = selectionRect.top - popupYDiff } } val popupXDiff = (viewTextSelection.measuredWidth - selectionRect.width()) / 2 val popupX = selectionRect.left - popupXDiff popupRect.offsetTo(popupX, popupY) //Log.d(LOG_TAG, "-> Post decision popupRect -> " + popupRect); // Check if popupRect left side is going outside of the viewportRect if (popupRect.left < viewportRect.left) { popupRect.right += 0 - popupRect.left popupRect.left = 0 } // Check if popupRect right side is going outside of the viewportRect if (popupRect.right > viewportRect.right) { val dx = popupRect.right - viewportRect.right popupRect.left -= dx popupRect.right -= dx } uiHandler.post { showTextSelectionPopup() } } private fun showTextSelectionPopup() { Log.v(LOG_TAG, "-> showTextSelectionPopup") Log.d(LOG_TAG, "-> showTextSelectionPopup -> To be laid out popupRect -> $popupRect") popupWindow.dismiss() oldScrollX = scrollX oldScrollY = scrollY isScrollingRunnable = Runnable { uiHandler.removeCallbacks(isScrollingRunnable) val currentScrollX = scrollX val currentScrollY = scrollY val inTouchMode = lastTouchAction == MotionEvent.ACTION_DOWN || lastTouchAction == MotionEvent.ACTION_MOVE if (oldScrollX == currentScrollX && oldScrollY == currentScrollY && !inTouchMode) { Log.i(LOG_TAG, "-> Stopped scrolling, show Popup") popupWindow.dismiss() popupWindow = PopupWindow(viewTextSelection, WRAP_CONTENT, WRAP_CONTENT) popupWindow.isClippingEnabled = false popupWindow.showAtLocation(this@FolioWebView, Gravity.NO_GRAVITY, popupRect.left, popupRect.top) } else { Log.i(LOG_TAG, "-> Still scrolling, don't show Popup") oldScrollX = currentScrollX oldScrollY = currentScrollY isScrollingCheckDuration += IS_SCROLLING_CHECK_TIMER if (isScrollingCheckDuration < IS_SCROLLING_CHECK_MAX_DURATION && !destroyed) uiHandler.postDelayed(isScrollingRunnable, IS_SCROLLING_CHECK_TIMER.toLong()) } } uiHandler.removeCallbacks(isScrollingRunnable) isScrollingCheckDuration = 0 if (!destroyed) uiHandler.postDelayed(isScrollingRunnable, IS_SCROLLING_CHECK_TIMER.toLong()) } }
gpl-3.0
9c51597c2b9497f8c7b082d5667a1012
38.804097
137
0.64149
5.164811
false
false
false
false
robedmo/vlc-android
vlc-android/src/org/videolan/vlc/RendererDelegate.kt
1
3561
/***************************************************************************** * RendererDelegate.java * * Copyright © 2017 VLC authors and VideoLAN * * 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 2 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, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. */ package org.videolan.vlc import org.videolan.libvlc.RendererDiscoverer import org.videolan.libvlc.RendererItem import org.videolan.vlc.util.VLCInstance import java.util.* object RendererDelegate : RendererDiscoverer.EventListener, ExternalMonitor.NetworkObserver { private val TAG = "VLC/RendererDelegate" private val mDiscoverers = ArrayList<RendererDiscoverer>() val renderers = ArrayList<RendererItem>() private val mListeners = LinkedList<RendererListener>() private val mPlayers = LinkedList<RendererPlayer>() @Volatile private var started = false var selectedRenderer: RendererItem? = null private set init { ExternalMonitor.subscribeNetworkCb(this) } interface RendererListener { fun onRenderersChanged(empty: Boolean) } interface RendererPlayer { fun onRendererChanged(renderer: RendererItem?) } fun start() { if (started) return started = true val libVlc = VLCInstance.get() for (discoverer in RendererDiscoverer.list(libVlc)) { val rd = RendererDiscoverer(libVlc, discoverer.name) mDiscoverers.add(rd) rd.setEventListener(this) rd.start() } } fun stop() { if (!started) return started = false for (discoverer in mDiscoverers) discoverer.stop() clear() onRenderersChanged() for (player in mPlayers) player.onRendererChanged(null) } private fun clear() { mDiscoverers.clear() for (renderer in renderers) renderer.release() renderers.clear() } override fun onNetworkConnectionChanged(connected: Boolean) = if (connected) start() else stop() override fun onEvent(event: RendererDiscoverer.Event?) { when (event?.type) { RendererDiscoverer.Event.ItemAdded -> { renderers.add(event.item) } RendererDiscoverer.Event.ItemDeleted -> { renderers.remove(event.item); event.item.release() } else -> return } onRenderersChanged() } fun addListener(listener: RendererListener) = mListeners.add(listener) fun removeListener(listener: RendererListener) = mListeners.remove(listener) private fun onRenderersChanged() { for (listener in mListeners) listener.onRenderersChanged(renderers.isEmpty()) } fun selectRenderer(item: RendererItem?) { selectedRenderer = item for (player in mPlayers) player.onRendererChanged(item) } fun addPlayerListener(listener: RendererPlayer) = mPlayers.add(listener) fun removePlayerListener(listener: RendererPlayer) = mPlayers.remove(listener) }
gpl-2.0
dc7c15f602107ed951d1b62576717aa4
32.904762
106
0.678652
4.721485
false
false
false
false
joffrey-bion/hashcode-utils
src/test/kotlin/org/hildan/hashcode/utils/examples/satellites/SatellitesModel.kt
1
1001
package org.hildan.hashcode.utils.examples.satellites /** * Index of the latitude in an array of coordinates. */ const val LATITUDE = 0 /** * Index of the longitude in an array of coordinates. */ const val LONGITUDE = 1 class Simulation( val nTurns: Int, val satellites: Array<Satellite>, val collections: Array<ImageCollection> ) class ImageCollection(val value: Int) { var locations: Array<Location> = emptyArray() var ranges: Array<IntArray> = emptyArray() } class Location( var parentCollection: ImageCollection, latitude: Int, longitude: Int ) { var coords = IntArray(2).apply { this[LATITUDE] = latitude this[LONGITUDE] = longitude } } class Satellite( latitude: Int, longitude: Int, var latitudeVelocity: Int, val maxOrientationChangePerTurn: Int, val maxOrientationValue: Int ) { var position: IntArray = IntArray(2).apply { this[LATITUDE] = latitude this[LONGITUDE] = longitude } }
mit
12da218f99e017aa02dd9f104e74f5b7
20.76087
53
0.675325
3.894942
false
false
false
false
MaryDream/functions-commons
src/main/kotlin/com/marydream/functions/commons/math/MathUtils.kt
1
3913
/* * Copyright {2017} {MaryDream} * * 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.marydream.functions.commons.math import java.math.BigInteger import java.util.* /** * Utility For Maths that has some best algorithims implementations. */ object MathUtils { /** * Function To Check if a number Is Not prime or not * * * [this.isPrime] * * * @param n the number * * * @return the boolean */ fun notPrime(n: Long): Boolean = synchronized(MathUtils) { return !isPrime(n) } /** * Function To Check if a number Is prime based on * [ * Miller Rabin Primality Test ](https://en.wikipedia.org/wiki/Miller%E2%80%93Rabin_primality_test) * * * * . * @param n the num * * * @return the boolean */ fun isPrime(n: Long): Boolean { synchronized(MathUtils) { if (n == 0L || n == 1L) return false if (n == 2L) return true if (n % 2L == 0L) return false var s = n - 1L while (s % 2L == 0L) s /= 2 val rand = Random() for (i in 0..1) { val r = Math.abs(rand.nextLong()) val a = r % (n - 1) + 1 var temp = s var mod = modPow(a, temp, n) while (temp != n - 1 && mod != 1L && mod != n - 1L) { mod = mulMod(mod, mod, n) temp *= 2 } if (mod != n - 1 && temp % 2L == 0L) return false } return true } } /** * Function to calculate (a ^ b) % c * @param a the a * * * @param b the b * * * @param c the c * * * @return the long */ fun modPow(a: Long, b: Long, c: Long): Long { var res: Long = 1 for (i in 0..b - 1) { res *= a res %= c } return res % c } /** * Function to calculate (a * b) % c * @param a the a * * * @param b the b * * * @param mod the mod * * * @return the long */ fun mulMod(a: Long, b: Long, mod: Long): Long { return BigInteger.valueOf(a).multiply(BigInteger.valueOf(b)).mod(BigInteger.valueOf(mod)).toLong() } /** * Function to determine whether a number odd or not. * @param number the number * * * @return the boolean */ fun isOdd(number: Number): Boolean { return !isEven(number) } /** * Function to determine whether a number even or not. * @param number the number * * * @return the boolean */ fun isEven(number: Number): Boolean { return number.toLong() % 2L == 0L } /** * Function to determine whether a number negative or not. * @param number the number * * * @return the boolean */ fun isNegative(number: Number): Boolean { return !isPositive(number) } /** * Function to determine whether a number positive or not. * @param number the number * * * @return the boolean */ fun isPositive(number: Number): Boolean { return number.toLong() >= 0 } }// this is a utility class
apache-2.0
6f44286990f899a989a5c338a49247ac
22.859756
106
0.507539
3.952525
false
false
false
false
guardianproject/phoneypot
src/main/java/org/havenapp/main/ui/viewholder/AudioVH.kt
1
2515
package org.havenapp.main.ui.viewholder import android.content.Context import android.net.Uri import android.view.LayoutInflater import android.view.ViewGroup import android.widget.LinearLayout import android.widget.TextView import androidx.recyclerview.widget.RecyclerView import com.github.derlio.waveform.SimpleWaveformView import com.github.derlio.waveform.soundfile.SoundFile import nl.changer.audiowife.AudioWife import org.havenapp.main.R import org.havenapp.main.model.EventTrigger import org.havenapp.main.resources.IResourceManager import java.io.File /** * Created by Arka Prava Basu<[email protected]> on 21/02/19 **/ class AudioVH(private val resourceManager: IResourceManager, viewGroup: ViewGroup) : RecyclerView.ViewHolder(LayoutInflater.from(viewGroup.context) .inflate(R.layout.item_audio, viewGroup, false)) { private val indexNumber = itemView.findViewById<TextView>(R.id.index_number) private val audioTitle = itemView.findViewById<TextView>(R.id.title) private val audioDesc = itemView.findViewById<TextView>(R.id.item_audio_desc) private val waveFormView = itemView.findViewById<SimpleWaveformView>(R.id.item_sound) private val playerContainer = itemView.findViewById<LinearLayout>(R.id.item_player_container) fun bind(eventTrigger: EventTrigger, context: Context, position: Int) { indexNumber.text = "#${position + 1}" audioTitle.text = eventTrigger.getStringType(resourceManager) audioDesc.text = eventTrigger.time?.toLocaleString() ?: "" val inflater = context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater val fileSound = File(eventTrigger.path) try { val soundFile = SoundFile.create(fileSound.path, object : SoundFile.ProgressListener { var lastProgress = 0 override fun reportProgress(fractionComplete: Double): Boolean { val progress = (fractionComplete * 100).toInt() if (lastProgress == progress) { return true } lastProgress = progress return true } }) waveFormView.setAudioFile(soundFile) waveFormView.invalidate() } catch (e: Exception) { e.printStackTrace() } playerContainer.removeAllViews() AudioWife().init(context, Uri.fromFile(fileSound)).useDefaultUi(playerContainer, inflater) } }
gpl-3.0
da8caa1735f80578b7470f9af631bf7c
38.920635
98
0.69662
4.507168
false
false
false
false
JetBrains/resharper-unity
rider/src/main/kotlin/com/jetbrains/rider/plugins/unity/diff/UnityYamlAutomaticExternalMergeTool.kt
1
5843
package com.jetbrains.rider.plugins.unity.diff import com.intellij.diff.DiffManagerEx import com.intellij.diff.DiffRequestFactory import com.intellij.diff.contents.DiffContent import com.intellij.diff.contents.FileContent import com.intellij.diff.merge.MergeCallback import com.intellij.diff.merge.MergeRequest import com.intellij.diff.merge.MergeResult import com.intellij.diff.merge.ThreesideMergeRequest import com.intellij.diff.merge.external.AutomaticExternalMergeTool import com.intellij.diff.tools.external.ExternalDiffSettings import com.intellij.diff.tools.external.ExternalDiffToolUtil import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.project.Project import com.intellij.openapi.util.SystemInfo import com.intellij.openapi.vfs.VirtualFile import com.intellij.util.io.delete import com.intellij.util.io.exists import com.intellij.util.io.readBytes import com.jetbrains.rd.util.reactive.hasTrueValue import com.jetbrains.rd.util.reactive.valueOrThrow import com.jetbrains.rdclient.util.idea.toIOFile import com.jetbrains.rider.plugins.unity.ideaInterop.fileTypes.yaml.UnityYamlFileType import com.jetbrains.rider.plugins.unity.model.frontendBackend.frontendBackendModel import com.jetbrains.rider.plugins.unity.util.UnityInstallationFinder import com.jetbrains.rider.projectView.solution import java.nio.file.Paths class UnityYamlAutomaticExternalMergeTool: AutomaticExternalMergeTool { companion object { private val myLogger = Logger.getInstance(UnityYamlAutomaticExternalMergeTool::class.java) } override fun show(project: Project?, request: MergeRequest) { project ?: return val appDataPath = UnityInstallationFinder.getInstance(project).getApplicationContentsPath() ?: return val extension = when { SystemInfo.isWindows -> ".exe" else -> "" } val tempDir = System.getProperty("java.io.tmpdir") val premergedBase = Paths.get(tempDir).resolve("premergedBase_" + request.hashCode()) val premergedRight = Paths.get(tempDir).resolve("premergedRight_" + request.hashCode()) try { val isMergeTrustExitCode = true val mergeExePath = appDataPath.resolve("Tools/UnityYAMLMerge" + extension).toString() val mergeParametersFromBackend = project.solution.frontendBackendModel.backendSettings.mergeParameters.valueOrThrow val mergeParameters = if (mergeParametersFromBackend.contains(" -p ")) { "$mergeParametersFromBackend $premergedBase $premergedRight" } else { mergeParametersFromBackend } myLogger.info("PreMerge with $mergeExePath $mergeParameters") val externalTool = ExternalDiffSettings.ExternalTool(mergeExePath, mergeParameters, isMergeTrustExitCode = isMergeTrustExitCode, groupName = ExternalDiffSettings.ExternalToolGroup.MERGE_TOOL ) if (!tryExecuteMerge(project, externalTool, request as ThreesideMergeRequest)) { if (premergedBase.exists() && premergedRight.exists()) { myLogger.info("PreMerge partially successful. Call ShowMergeBuiltin on pre-merged.") val output: VirtualFile = (request.outputContent as FileContent).file val byteContents = listOf(output.toIOFile().readBytes(), premergedBase.readBytes(), premergedRight.readBytes()) val preMerged = DiffRequestFactory.getInstance().createMergeRequest(project, output, byteContents, request.title, request.contentTitles) MergeCallback.retarget(request, preMerged) DiffManagerEx.getInstance().showMergeBuiltin(project, preMerged) } else { myLogger.info("PreMerge unsuccessful. Call ShowMergeBuiltin.") DiffManagerEx.getInstance().showMergeBuiltin(project, request) } } } finally { if (premergedBase.exists()) premergedBase.delete() if (premergedRight.exists()) premergedRight.delete() } } private fun tryExecuteMerge(project: Project?, externalMergeTool: ExternalDiffSettings.ExternalTool, request: ThreesideMergeRequest): Boolean { // see reference impl "com.intellij.diff.tools.external.ExternalDiffToolUtil#executeMerge" request.onAssigned(true) try { if (ExternalDiffToolUtil.tryExecuteMerge(project, externalMergeTool, request, null)) { myLogger.info("Merge with external tool was fully successful. Apply result.") request.applyResult(MergeResult.RESOLVED) return true } return false } catch (e: Exception) { myLogger.error("UnityYamlMerge failed.", e) return false } finally { request.onAssigned(false) } } override fun canShow(project: Project?, request: MergeRequest): Boolean { project ?: return false if (!project.solution.frontendBackendModel.backendSettings.useUnityYamlMerge.hasTrueValue) return false if (request is ThreesideMergeRequest) { val outputContent = request.outputContent if (!canProcessOutputContent(outputContent)) return false val contents = request.contents if (contents.size != 3) return false for (content in contents) { if (!ExternalDiffToolUtil.canCreateFile(content!!)) return false } return true } return false } private fun canProcessOutputContent(content: DiffContent): Boolean { return content is FileContent && content.file.isInLocalFileSystem && content.file.fileType == UnityYamlFileType } }
apache-2.0
e198dfd47016967c7c5d93460a0a4a38
46.129032
156
0.697416
5.054498
false
false
false
false
DadosAbertosBrasil/android-radar-politico
app/src/main/kotlin/br/edu/ifce/engcomp/francis/radarpolitico/controllers/DeputadosSeguidosTabFragment.kt
1
3173
package br.edu.ifce.engcomp.francis.radarpolitico.controllers import android.app.Activity import android.content.Intent import android.os.Bundle import android.support.design.widget.FloatingActionButton import android.support.v4.app.Fragment import android.support.v7.widget.DefaultItemAnimator import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import br.edu.ifce.engcomp.francis.radarpolitico.R import br.edu.ifce.engcomp.francis.radarpolitico.miscellaneous.adapters.DeputadoRecyclerViewAdapter import br.edu.ifce.engcomp.francis.radarpolitico.miscellaneous.connection.database.DeputadoDAO import br.edu.ifce.engcomp.francis.radarpolitico.models.Deputado import java.util.* class DeputadosSeguidosTabFragment : Fragment() { lateinit var politicosRecyclerView: RecyclerView lateinit var fabAddDeputado: FloatingActionButton lateinit var adapter: DeputadoRecyclerViewAdapter internal var datasource: ArrayList<Deputado> private val addPoliticoIntentCode = 2011 init { datasource = ArrayList<Deputado>() } override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? { val rootView = inflater!!.inflate(R.layout.fragment_politicos, container, false) this.politicosRecyclerView = rootView.findViewById(R.id.politicos_recyler_view) as RecyclerView this.fabAddDeputado = rootView.findViewById(R.id.fab_add_politico) as FloatingActionButton this.initFabAddDeputado() this.initRecyclerView() this.retrieveDeputiesFromInternalDatabase() return rootView } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) if (requestCode == addPoliticoIntentCode && resultCode == Activity.RESULT_OK){ val deputadoAdded = data?.getBooleanExtra("DEPUTADO_ADDED", false) if (deputadoAdded == true){ retrieveDeputiesFromInternalDatabase() } } } private fun initRecyclerView() { val layoutManager = LinearLayoutManager(activity) adapter = DeputadoRecyclerViewAdapter(activity, this.datasource) this.politicosRecyclerView.setHasFixedSize(false) this.politicosRecyclerView.layoutManager = layoutManager this.politicosRecyclerView.adapter = adapter this.politicosRecyclerView.itemAnimator = DefaultItemAnimator() } private fun initFabAddDeputado() { this.fabAddDeputado.setOnClickListener { val intentAddPoliticosActivity = Intent(activity, AdicionarPoliticosActivity::class.java) startActivityForResult(intentAddPoliticosActivity, addPoliticoIntentCode) } } fun retrieveDeputiesFromInternalDatabase() { val deputyDAO = DeputadoDAO(activity) val deputies = deputyDAO.listAll() this.datasource.clear() this.datasource.addAll(deputies) this.adapter.notifyDataSetChanged() } }
gpl-2.0
708fad79535a4cff7a6284578174a892
36.329412
117
0.749448
4.866564
false
false
false
false
toastkidjp/Jitte
app/src/main/java/jp/toastkid/yobidashi/browser/history/ViewHolder.kt
1
2471
package jp.toastkid.yobidashi.browser.history import android.view.View import android.view.ViewGroup import androidx.core.view.isVisible import androidx.core.view.updateMargins import androidx.fragment.app.FragmentActivity import androidx.recyclerview.widget.RecyclerView import coil.load import jp.toastkid.lib.view.SwipeViewHolder import jp.toastkid.yobidashi.R import jp.toastkid.yobidashi.databinding.ItemViewHistoryBinding import java.io.File /** * @author toastkidjp */ internal class ViewHolder(private val binding: ItemViewHistoryBinding) : RecyclerView.ViewHolder(binding.root), SwipeViewHolder { private val buttonMargin = binding.root.resources .getDimensionPixelSize(R.dimen.button_margin) fun setText(text: String, url: String, time: String) { binding.title.text = text binding.url.text = url binding.time.text = time } fun setImage(faviconPath: String) { if (faviconPath.isEmpty()) { setDefaultIcon() return } binding.icon.load(File(faviconPath)) } private fun setDefaultIcon() { binding.icon.setImageResource(R.drawable.ic_history_black) } fun setOnClickBookmark(history: ViewHistory) { binding.bookmark.setOnClickListener { val context = binding.root.context if (context is FragmentActivity) { AddBookmarkDialogFragment.make(history.title, history.url).show( context.supportFragmentManager, AddBookmarkDialogFragment::class.java.simpleName ) } } } fun setOnClickAdd(history: ViewHistory, onClickAdd: (ViewHistory) -> Unit) { binding.delete.setOnClickListener { onClickAdd(history) } } override fun getFrontView(): View = binding.front override fun isButtonVisible(): Boolean = binding.delete.isVisible override fun showButton() { binding.delete.visibility = View.VISIBLE updateRightMargin(buttonMargin) } override fun hideButton() { binding.delete.visibility = View.INVISIBLE updateRightMargin(0) } private fun updateRightMargin(margin: Int) { val marginLayoutParams = binding.front.layoutParams as? ViewGroup.MarginLayoutParams marginLayoutParams?.rightMargin = margin binding.front.layoutParams = marginLayoutParams marginLayoutParams?.updateMargins() } }
epl-1.0
98a90a7e39d1e98664c640529dcf52dd
29.506173
92
0.686766
4.835616
false
false
false
false
fython/PackageTracker
mobile/src/main/kotlin/info/papdt/express/helper/event/EventIntents.kt
1
2063
package info.papdt.express.helper.event import android.content.Intent import android.os.Parcelable import androidx.recyclerview.widget.RecyclerView import info.papdt.express.helper.ACTION_PREFIX import info.papdt.express.helper.ACTION_REQUEST_DELETE_PACK import info.papdt.express.helper.EXTRA_DATA import info.papdt.express.helper.EXTRA_OLD_DATA import info.papdt.express.helper.model.Category import info.papdt.express.helper.model.Kuaidi100Package import me.drakeet.multitype.ItemViewBinder import kotlin.reflect.KClass object EventIntents { const val ACTION_REQUEST_DELETE_CATEGORY = "$ACTION_PREFIX.REQUEST_DELETE_CATEGORY" const val ACTION_SAVE_NEW_CATEGORY = "$ACTION_PREFIX.SAVE_NEW_CATEGORY" const val ACTION_SAVE_EDIT_CATEGORY = "$ACTION_PREFIX.SAVE_EDIT_CATEGORY" fun requestDeletePackage(data: Kuaidi100Package): Intent { val intent = Intent(ACTION_REQUEST_DELETE_PACK) intent.putExtra(EXTRA_DATA, data) return intent } fun requestDeleteCategory(data: Category): Intent { val intent = Intent(ACTION_REQUEST_DELETE_CATEGORY) intent.putExtra(EXTRA_DATA, data) return intent } fun saveNewCategory(data: Category): Intent { val intent = Intent(ACTION_SAVE_NEW_CATEGORY) intent.putExtra(EXTRA_DATA, data) return intent } fun saveEditCategory(oldData: Category, data: Category): Intent { val intent = Intent(ACTION_SAVE_EDIT_CATEGORY) intent.putExtra(EXTRA_OLD_DATA, oldData) intent.putExtra(EXTRA_DATA, data) return intent } fun <T, VH : RecyclerView.ViewHolder, B: ItemViewBinder<T, VH>> getItemOnClickActionName(clazz: KClass<B>): String { return clazz::java.name + ".ACTION_ON_CLICK" } fun <T : Parcelable, VH : RecyclerView.ViewHolder, B: ItemViewBinder<T, VH>> notifyItemOnClick(clazz: KClass<B>, data: T?): Intent { val intent = Intent(getItemOnClickActionName(clazz)) intent.putExtra(EXTRA_DATA, data) return intent } }
gpl-3.0
0397b5096c95506a96c47f6128e34be2
34.586207
87
0.712555
4.013619
false
false
false
false
xfournet/intellij-community
plugins/devkit/src/actions/MigrateModuleNamesInSourcesAction.kt
1
14028
/* * 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.idea.devkit.actions import com.intellij.icons.AllIcons import com.intellij.navigation.ItemPresentation import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.application.runWriteAction import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.editor.Editor import com.intellij.openapi.fileEditor.FileEditor import com.intellij.openapi.module.ModuleManager import com.intellij.openapi.module.impl.ModuleRenamingHistoryState import com.intellij.openapi.progress.EmptyProgressIndicator import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.project.Project import com.intellij.openapi.util.Factory import com.intellij.openapi.util.TextRange import com.intellij.openapi.vfs.LocalFileSystem import com.intellij.openapi.vfs.VfsUtil import com.intellij.openapi.vfs.VirtualFile import com.intellij.psi.PsiComment import com.intellij.psi.PsiFile import com.intellij.psi.PsiPlainText import com.intellij.psi.search.* import com.intellij.usageView.UsageInfo import com.intellij.usages.* import com.intellij.util.Processor import com.intellij.util.loadElement import com.intellij.util.xmlb.XmlSerializationException import com.intellij.util.xmlb.XmlSerializer import org.jetbrains.idea.devkit.util.PsiUtil import java.io.File import kotlin.experimental.or private val LOG = Logger.getInstance(MigrateModuleNamesInSourcesAction::class.java) /** * This is a temporary action to be used for migrating occurrences of module names in IntelliJ IDEA sources after massive module renaming. */ class MigrateModuleNamesInSourcesAction : AnAction("Find/Update Module Names in Sources...", "Find and migrate to the new scheme occurrences of module names in IntelliJ IDEA project sources", null) { override fun actionPerformed(e: AnActionEvent) { val project = e.project!! val viewPresentation = UsageViewPresentation().apply { tabText = "Occurrences of Module Names" toolwindowTitle = "Occurrences of Module Names" usagesString = "occurrences of module names" usagesWord = "occurrence" codeUsagesString = "Found Occurrences" isOpenInNewTab = true isCodeUsages = false isUsageTypeFilteringAvailable = true } val processPresentation = FindUsagesProcessPresentation(viewPresentation).apply { isShowNotFoundMessage = true isShowPanelIfOnlyOneUsage = true } val renamingScheme = try { LocalFileSystem.getInstance().refreshAndFindFileByIoFile( File(VfsUtil.virtualToIoFile(project.baseDir), "module-renaming-scheme.xml"))?.let { XmlSerializer.deserialize(loadElement(it.inputStream), ModuleRenamingHistoryState::class.java).oldToNewName } } catch (e: XmlSerializationException) { LOG.error(e) return } val moduleNames = renamingScheme?.keys?.toList() ?: ModuleManager.getInstance(project).modules.map { it.name } val targets = moduleNames.map(::ModuleNameUsageTarget).toTypedArray() val searcherFactory = Factory<UsageSearcher> { val processed = HashSet<Pair<VirtualFile, Int>>() UsageSearcher { consumer -> val usageInfoConsumer = Processor<UsageInfo> { if (processed.add(Pair(it.virtualFile!!, it.navigationRange!!.startOffset))) { consumer.process(UsageInfo2UsageAdapter(it)) } else true } processOccurrences(project, moduleNames, usageInfoConsumer) } } val listener = object : UsageViewManager.UsageViewStateListener { override fun usageViewCreated(usageView: UsageView) { if (renamingScheme == null) return val migrateOccurrences = Runnable { @Suppress("UNCHECKED_CAST") val usages = (usageView.usages - usageView.excludedUsages) as Set<UsageInfo2UsageAdapter> val usagesByFile = usages.groupBy { it.file } val progressIndicator = ProgressManager.getInstance().progressIndicator var i = 0 usagesByFile.forEach { (file, usages) -> progressIndicator?.fraction = (i++).toDouble() / usagesByFile.size try { usages.sortedByDescending { it.usageInfo.navigationRange!!.startOffset }.forEach { var range = it.usageInfo.navigationRange!! if (it.document.charsSequence[range.startOffset] in listOf('"', '\'')) range = TextRange(range.startOffset + 1, range.endOffset - 1) val oldName = it.document.charsSequence.subSequence(range.startOffset, range.endOffset).toString() if (oldName !in renamingScheme) throw RuntimeException("Unknown module $oldName") val newName = renamingScheme[oldName]!! runWriteAction { it.document.replaceString(range.startOffset, range.endOffset, newName) } } } catch (e: Exception) { throw RuntimeException("Cannot replace usage in ${file.presentableUrl}: ${e.message}", e) } } } usageView.addPerformOperationAction(migrateOccurrences, "Migrate Module Name Occurrences", "Cannot migrate occurrences", "Migrate Module Name Occurrences") } override fun findingUsagesFinished(usageView: UsageView?) { } } UsageViewManager.getInstance(project).searchAndShowUsages(targets, searcherFactory, processPresentation, viewPresentation, listener) } private fun processOccurrences(project: Project, moduleNames: List<String>, consumer: Processor<UsageInfo>) { val progress = ProgressManager.getInstance().progressIndicator ?: EmptyProgressIndicator() progress.text = "Searching for module names..." val scope = GlobalSearchScope.projectScope(project) val searchHelper = PsiSearchHelper.SERVICE.getInstance(project) fun Char.isModuleNamePart() = this.isJavaIdentifierPart() || this == '-' fun GlobalSearchScope.filter(filter: (VirtualFile) -> Boolean) = object: DelegatingGlobalSearchScope(this) { override fun contains(file: VirtualFile): Boolean { return filter(file) && super.contains(file) } } fun mayMentionModuleNames(text: String) = (text.contains("JpsProject") || text.contains("package com.intellij.testGuiFramework") || text.contains("getJarPathForClass")) && !text.contains("StandardLicenseUrls") fun VirtualFile.isBuildScript() = when (extension) { "gant" -> true "groovy" -> VfsUtil.loadText(this).contains("package org.jetbrains.intellij.build") "java" -> mayMentionModuleNames(VfsUtil.loadText(this)) "kt" -> mayMentionModuleNames(VfsUtil.loadText(this)) else -> false } fun processCodeUsages(moduleName: String, quotedString: String, groovyOnly: Boolean) { val ignoredMethods = listOf("getPluginHomePath(", "getPluginHome(", "getPluginHomePathRelative(", "dir(", "withProjectLibrary(", "directoryName = ") val quotedOccurrencesProcessor = TextOccurenceProcessor { element, offset -> if (element.text != quotedString) return@TextOccurenceProcessor true if (ignoredMethods.any { element.textRange.startOffset > it.length && element.containingFile.text.startsWith(it, element.textRange.startOffset - it.length) }) { return@TextOccurenceProcessor true } consumer.process(UsageInfo(element, offset, offset + quotedString.length)) } val literalsScope = if (moduleName in regularWordsUsedAsModuleNames + moduleNamesUsedAsIDs) scope.filter { it.isBuildScript() && !groovyOnly || it.extension in listOf("groovy", "gant") } else scope searchHelper.processElementsWithWord(quotedOccurrencesProcessor, literalsScope, quotedString, UsageSearchContext.IN_CODE or UsageSearchContext.IN_STRINGS, true) } fun processUsagesInStrings(moduleName: String, substring: String) { val quotedOccurrencesProcessor = TextOccurenceProcessor { element, offset -> val text = element.text if (text[0] == '"' && text.lastOrNull() == '"' || text[0] == '\'' && text.lastOrNull() == '\'') { consumer.process(UsageInfo(element, offset + substring.indexOf(moduleName), offset + substring.length)) } else { true } } searchHelper.processElementsWithWord(quotedOccurrencesProcessor, scope, substring, UsageSearchContext.IN_STRINGS, true) } for ((i, moduleName) in moduleNames.withIndex()) { progress.fraction = i.toDouble() / moduleNames.size progress.text2 = "Searching for \"$moduleName\"" processCodeUsages(moduleName, "\"$moduleName\"", groovyOnly = false) processCodeUsages(moduleName, "'$moduleName'", groovyOnly = true) if (moduleName != "resources") { processUsagesInStrings(moduleName, "production/$moduleName") processUsagesInStrings(moduleName, "test/$moduleName") } val plainOccurrencesProcessor = TextOccurenceProcessor { element, offset -> val endOffset = offset + moduleName.length if ((offset == 0 || element.text[offset - 1].isWhitespace()) && (endOffset == element.textLength || element.text[endOffset].isWhitespace()) && element is PsiPlainText) { consumer.process(UsageInfo(element, offset, endOffset)) } else true } val plainTextScope = if (moduleName in regularWordsUsedAsModuleNames + moduleNamesUsedAsIDs) scope.filter {it.name == "plugin-list.txt"} else scope searchHelper.processElementsWithWord(plainOccurrencesProcessor, plainTextScope, moduleName, UsageSearchContext.IN_PLAIN_TEXT, true) if (moduleName !in regularWordsUsedAsModuleNames) { val commentsOccurrencesProcessor = TextOccurenceProcessor { element, offset -> val endOffset = offset + moduleName.length if ((offset == 0 || !element.text[offset - 1].isModuleNamePart() && element.text[offset-1] != '.') && (endOffset == element.textLength || !element.text[endOffset].isModuleNamePart() && element.text[endOffset] != '/' && !(endOffset < element.textLength - 2 && element.text[endOffset] == '.' && element.text[endOffset+1].isLetter())) && element is PsiComment) { consumer.process(UsageInfo(element, offset, endOffset)) } else true } searchHelper.processElementsWithWord(commentsOccurrencesProcessor, scope, moduleName, UsageSearchContext.IN_COMMENTS, true) } } } override fun update(e: AnActionEvent) { e.presentation.isEnabledAndVisible = PsiUtil.isIdeaProject(e.project) } } private class ModuleNameUsageTarget(val moduleName: String) : UsageTarget, ItemPresentation { override fun getFiles() = null override fun getPresentation() = this override fun canNavigate() = false override fun getName() = "\"$moduleName\"" override fun findUsages() { throw UnsupportedOperationException() } override fun canNavigateToSource() = false override fun isReadOnly() = true override fun navigate(requestFocus: Boolean) { throw UnsupportedOperationException() } override fun findUsagesInEditor(editor: FileEditor) { } override fun highlightUsages(file: PsiFile, editor: Editor, clearHighlights: Boolean) { } override fun isValid() = true override fun update() { } override fun getPresentableText() = "Occurrences of \"$moduleName\"" override fun getLocationString() = null override fun getIcon(unused: Boolean) = AllIcons.Nodes.Module!! } private val regularWordsUsedAsModuleNames = setOf( "CloudBees", "AngularJS", "CloudFoundry", "CSS", "CFML", "Docker", "Dart", "EJS", "Guice", "Heroku", "Jade", "Kubernetes", "LiveEdit", "OpenShift", "Meteor", "NodeJS", "Perforce", "TFS", "WSL", "analyzer", "android", "ant", "annotations", "appcode", "artwork", "asp", "aspectj", "behat", "boot", "bootstrap", "build", "blade", "commandLineTool", "chronon", "codeception", "common", "commander", "copyright", "coverage", "dependencies", "designer", "ddmlib", "doxygen", "draw9patch", "drupal", "duplicates", "drools", "eclipse", "el", "emma", "editorconfig", "extensions", "flex", "gherkin", "flags", "freemarker", "github", "gradle", "haml", "graph", "icons", "idea", "images", "ipnb", "jira", "joomla", "jbpm", "json", "junit", "layoutlib", "less", "localization", "manifest", "main", "markdown", "maven", "ognl", "openapi", "ninepatch", "perflib", "observable", "phing", "php", "phpspec", "pixelprobe", "play", "profilers", "properties", "puppet", "postcss", "python", "quirksmode", "repository", "resources", "rs", "relaxng", "restClient", "rest", "ruby", "sass", "sdklib", "seam", "ssh", "spellchecker", "stylus", "swift", "terminal", "tomcat", "textmate", "testData", "testFramework", "testng", "testRunner", "twig", "util", "updater", "vaadin", "vagrant", "vuejs", "velocity", "weblogic", "websocket", "wizard", "ws", "wordPress", "xml", "xpath", "yaml", "usageView", "error-prone", "spy-js", "WebStorm", "javac2", "dsm", "clion", "phpstorm", "WebComponents" ) private val moduleNamesUsedAsIDs = setOf("spring-integration", "spring-aop", "spring-mvc", "spring-security", "spring-webflow", "git4idea", "dvlib", "hg4idea", "JsTestDriver", "ByteCodeViewer", "appcode-designer", "dsm", "flex", "google-app-engine", "phpstorm-workshop", "ruby-core", "ruby-slim", "spring-ws", "svn4idea", "Yeoman", "spring-batch", "spring-data", "sdk-common", "ui-designer")
apache-2.0
1b3d74bc1b76bc5b4eb1b7b9a3cfa61d
50.014545
232
0.680068
4.850622
false
false
false
false
mayuki/AgqrPlayer4Tv
AgqrPlayer4Tv/app/src/main/java/org/misuzilla/agqrplayer4tv/component/fragment/guidedstep/PlayConfirmationGuidedStepFragment.kt
1
4096
package org.misuzilla.agqrplayer4tv.component.fragment.guidedstep import android.app.AlarmManager import android.app.PendingIntent import android.content.Context import android.content.Intent import android.os.Bundle import android.support.v17.leanback.app.GuidedStepSupportFragment import android.support.v17.leanback.widget.GuidanceStylist import android.support.v17.leanback.widget.GuidedAction import org.misuzilla.agqrplayer4tv.R import org.misuzilla.agqrplayer4tv.component.activity.MainActivity import org.misuzilla.agqrplayer4tv.model.* /** * 再生か予約の確認画面のFragment */ class PlayConfirmationGuidedStepFragment : GuidedStepSupportFragment() { private val program: TimetableProgram by lazy { arguments!![ARG_PROGRAM] as TimetableProgram } private val canStartActivity: Boolean by lazy { arguments!![ARG_CAN_START_ACTIVITY] as Boolean } override fun onCreateGuidance(savedInstanceState: Bundle?): GuidanceStylist.Guidance { val isScheduled = Reservation.instance.isScheduled(program) return GuidanceStylist.Guidance(program.title, context!!.getString(R.string.play_confirmation_description) .format(program.personality, program.start.toShortString(), if (isScheduled) context!!.getString(R.string.play_confirmation_description_scheduled) else ""), context!!.getString(R.string.app_name), null) } override fun onCreateActions(actions: MutableList<GuidedAction>, savedInstanceState: Bundle?) { val isScheduled = Reservation.instance.isScheduled(program) if (canStartActivity) { actions.add(GuidedAction.Builder(context) .id(ACTION_OPEN_IMMEDIATELY.toLong()) .title(context!!.getString(R.string.play_confirmation_open_player)) .description(context!!.getString(R.string.play_confirmation_open_player_description)) .build()) } if (isScheduled) { actions.add(GuidedAction.Builder(context) .id(ACTION_CANCEL_TIMER.toLong()) .title(context!!.getString(R.string.play_confirmation_cancel_timer)) .description(context!!.getString(R.string.play_confirmation_cancel_timer_description)) .build()) } else { actions.add(GuidedAction.Builder(context) .id(ACTION_REGISTER_TIMER.toLong()) .title(context!!.getString(R.string.play_confirmation_set_timer)) .description(context!!.getString(R.string.play_confirmation_set_timer_description).format(program.start.toShortString())) .build()) } } override fun onGuidedActionClicked(action: GuidedAction) { val intent = Intent(context, MainActivity::class.java) when (action.id.toInt()) { ACTION_OPEN_IMMEDIATELY -> { startActivity(intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)) finishGuidedStepSupportFragments() } ACTION_REGISTER_TIMER -> { Reservation.instance.schedule(program) finishGuidedStepSupportFragments() } ACTION_CANCEL_TIMER -> { Reservation.instance.cancel(program) finishGuidedStepSupportFragments() } } } companion object { const val ACTION_OPEN_IMMEDIATELY = 0 const val ACTION_REGISTER_TIMER = 1 const val ACTION_CANCEL_TIMER = 2 const val ARG_PROGRAM = "Program" const val ARG_CAN_START_ACTIVITY = "CanStartActivity" fun createInstance(program: TimetableProgram, canStartActivity: Boolean): PlayConfirmationGuidedStepFragment { val fragment = PlayConfirmationGuidedStepFragment() fragment.arguments = Bundle().apply { putSerializable(ARG_PROGRAM, program) putBoolean(ARG_CAN_START_ACTIVITY, canStartActivity) } return fragment } } }
mit
0b46709bfb062d193689a502a0d6f11f
42.351064
180
0.655866
4.950182
false
false
false
false
mockito/mockito-kotlin
tests/src/test/kotlin/test/SpyTest.kt
1
3663
package test /* * The MIT License * * Copyright (c) 2016 Niek Haarman * Copyright (c) 2007 Mockito contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ import com.nhaarman.expect.expect import org.junit.After import org.junit.Test import org.mockito.Mockito import org.mockito.kotlin.* import java.util.* class SpyTest : TestBase() { private val interfaceInstance: MyInterface = MyClass() private val openClassInstance: MyClass = MyClass() private val closedClassInstance: ClosedClass = ClosedClass() @After override fun tearDown() { super.tearDown() Mockito.validateMockitoUsage() } @Test fun spyInterfaceInstance() { /* When */ val result = spy(interfaceInstance) /* Then */ expect(result).toNotBeNull() } @Test fun spyOpenClassInstance() { /* When */ val result = spy(openClassInstance) /* Then */ expect(result).toNotBeNull() } @Test fun doReturnWithSpy() { val date = spy(Date()) doReturn(123L).whenever(date).time expect(date.time).toBe(123L) } @Test fun doNothingWithSpy() { val date = spy(Date(0)) doNothing().whenever(date).time = 5L date.time = 5L expect(date.time).toBe(0L) } @Test(expected = IllegalArgumentException::class) fun doThrowWithSpy() { val date = spy(Date(0)) doThrow(IllegalArgumentException()).whenever(date).time date.time } @Test fun doCallRealMethodWithSpy() { val date = spy(Date(0)) doReturn(123L).whenever(date).time doCallRealMethod().whenever(date).time expect(date.time).toBe(0L) } @Test fun doReturnWithDefaultInstanceSpyStubbing() { val timeVal = 12L val dateSpy = spy<Date> { on { time } doReturn timeVal } expect(dateSpy.time).toBe(timeVal) } @Test fun doReturnWithSpyStubbing() { val timeVal = 15L val dateSpy = spy(Date(0)) { on { time } doReturn timeVal } expect(dateSpy.time).toBe(timeVal) } @Test fun passAnyStringToSpy() { /* Given */ val my = spy(MyClass()) /* When */ doReturn("mocked").whenever(my).foo(any()) /* Then */ expect(my.foo("hello")).toBe("mocked") } private interface MyInterface { fun foo(value: String): String } private open class MyClass : MyInterface { override fun foo(value: String): String = value } private class ClosedClass }
mit
ed85aadde489fffd73a0ab27e4143682
24.978723
80
0.641005
4.314488
false
true
false
false
yyued/CodeX-UIKit-Android
library/src/main/java/com/yy/codex/uikit/UITextField.kt
1
10577
package com.yy.codex.uikit import android.content.ClipData import android.content.ClipboardManager import android.content.Context import android.os.Build import android.support.annotation.RequiresApi import android.text.Editable import android.text.Layout import android.util.AttributeSet import android.view.KeyEvent import android.view.View import com.yy.codex.foundation.NSLog import java.util.* /** * Created by PonyCui_Home on 2017/2/3. */ class UITextField : UIControl, UITextInput.Delegate, UITextInputTraits { enum class ViewMode { Never, WhileEditing, UnlessEditing, Always } enum class BorderStyle { None, Line, RoundedRect } interface Delegate { fun shouldBeginEditing(textField: UITextField): Boolean fun didBeginEditing(textField: UITextField) fun shouldEndEditing(textField: UITextField): Boolean fun didEndEditing(textField: UITextField) fun shouldChangeCharactersInRange(textField: UITextField, inRange: NSRange, replacementString: String): Boolean fun shouldClear(textField: UITextField): Boolean fun shouldReturn(textField: UITextField): Boolean } constructor(context: Context, view: View) : super(context, view) {} constructor(context: Context) : super(context) {} constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {} constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {} @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int, defStyleRes: Int) : super(context, attrs, defStyleAttr, defStyleRes) {} var delegate: Delegate? = null var contentInsets: UIEdgeInsets = UIEdgeInsets(0.0, 6.0, 0.0, 6.0) set(value) { field = value resetLayouts() } var text: String? get() = input?.editor?.text.toString() set(value) { label.text = value input.editor?.text?.clear() input.editor?.text?.append(text) input.editor?.setSelection(value?.length ?: 0) } var attributedText: NSAttributedString? get() = label.attributedText set(value) { label.attributedText = value } var textColor: UIColor? get() = label.textColor set(value) { value?.let { label.textColor = it } } var font: UIFont? get() = label.font set(value) { value?.let { label.font = it } } var alignment: Layout.Alignment = Layout.Alignment.ALIGN_NORMAL set(value) { field = value resetLayouts() } var borderStyle: BorderStyle = BorderStyle.None set(value) { field = value when (value) { BorderStyle.None -> wantsLayer = false BorderStyle.Line -> { wantsLayer = true layer.borderWidth = 1.0 layer.borderColor = UIColor.blackColor } BorderStyle.RoundedRect -> { wantsLayer = true layer.borderWidth = 1.0 layer.borderColor = UIColor.blackColor.colorWithAlpha(0.3) layer.cornerRadius = 6.0 } } } var defaultTextAttributes: Map<String, Any>? = null var placeholder: String? = null set(value) { field = value setupPlaceholder() } var attributedPlaceholder: NSAttributedString? = null var clearsOnBeginEditing = false var editing: Boolean = false get() = isFirstResponder() var clearButton: UIView? = null internal set var clearButtonMode = ViewMode.Never set(value) { field = value resetClearView() } var leftView: UIView? = null set(value) { if (value == null) { field?.let(UIView::removeFromSuperview) } field = value resetLeftView() } var leftViewMode = ViewMode.Never set(value) { field = value resetLayouts() } var rightView: UIView? = null set(value) { if (value == null) { field?.let(UIView::removeFromSuperview) } field = value resetRightView() } var rightViewMode = ViewMode.Never set(value) { field = value resetLayouts() } var selection: NSRange? = null set(value) { field = value resetSelection() } override var keyboardType: UIKeyboardType = UIKeyboardType.Default override var returnKeyType: UIReturnKeyType = UIReturnKeyType.Default override var secureTextEntry: Boolean = false override fun init() { super.init() input = UITextInput() wrapper = UIView(context) addSubview(wrapper) label = UILabel(context) wrapper.addSubview(label) cursorView = UIView(context) cursorView.hidden = true label.addSubview(cursorView) } override fun didMoveToSuperview() { super.didMoveToSuperview() input.view = this } override fun becomeFirstResponder() { delegate?.let { if (!it.shouldBeginEditing(this)) { return } } super.becomeFirstResponder() removePlaceholder() if (clearsOnBeginEditing) { text = "" } input.beginEditing() showCursorView() resetLayouts() delegate?.let { it.didBeginEditing(this) } } override fun resignFirstResponder() { delegate?.let { if (!it.shouldEndEditing(this)) { return } } if (isFirstResponder()) { setupPlaceholder() selection = null input.endEditing() hideCursorView() } super.resignFirstResponder() resetLayouts() delegate?.let { it.didEndEditing(this) } } override fun onEvent(event: Event) { super.onEvent(event) if (event == UIControl.Event.TouchDown) { val menuVisible = UIMenuController.sharedMenuController.menuVisible if (menuVisible) { UIMenuController.sharedMenuController.setMenuVisible(false, true) } else { touchStartTimestamp = System.currentTimeMillis() touchStartInputPosition = input.cursorPosition } } else if (event == UIControl.Event.TouchUpInside) { if (!isFirstResponder()) { becomeFirstResponder() } else { if (selection == null && touchStartTimestamp + 300 > System.currentTimeMillis()) { if (touchStartInputPosition == input.cursorPosition) { showPositionMenu() } } } } } override fun onLongPressed(sender: UILongPressGestureRecognizer) { super.onLongPressed(sender) operateCursor(sender) } override fun onTapped(sender: UITapGestureRecognizer) { super.onTapped(sender) operateCursor(sender) } override fun keyboardPressDown(event: UIKeyEvent) { super.keyboardPressDown(event) if (event.keyCode == KeyEvent.KEYCODE_DEL) { input.delete(selection) } } override fun didChanged(onDelete: Boolean) { resetText(onDelete) selection?.let { selection = null } UIMenuController.sharedMenuController.setMenuVisible(false, true) } override fun shouldChange(range: NSRange, replacementString: String): Boolean { if (replacementString == "\n") { return false } delegate?.let { return it.shouldChangeCharactersInRange(this, range, replacementString) } return true } override fun shouldClear(): Boolean { delegate?.let { return it.shouldClear(this) } return true } override fun shouldReturn(): Boolean { delegate?.let { return it.shouldReturn(this) } return false } /* Content Props */ lateinit internal var input: UITextInput lateinit internal var wrapper: UIView lateinit internal var label: UILabel /* Cursor Private Props */ lateinit internal var cursorView: UIView internal var cursorOptID: Long = 0 internal var cursorViewAnimation: UIViewAnimation? = null internal var cursorMoveNextTiming: Long = 0 internal var cursorMovingPrevious = false internal var cursorMovingNext = false internal var touchStartTimestamp: Long = 0 internal var touchStartInputPosition: Int = 0 internal var selectionOperatingLeft = false internal var selectionOperatingRight = false private fun onChoose() { val textLength = label.text?.length ?: return if (input.cursorPosition >= 2) { selection = NSRange(input.cursorPosition - 2, 2) } else if (textLength > 0) { onChooseAll() } } private fun onChooseAll() { selection = NSRange(0, label.text?.length ?: 0) } private fun onCrop() { selection?.let { text?.substring(it.location, it.location + it.length)?.let { val manager = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager manager.primaryClip = ClipData.newPlainText(it, it) } input.delete(it) } } private fun onCopy() { selection?.let { text?.substring(it.location, it.location + it.length)?.let { val manager = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager manager.primaryClip = ClipData.newPlainText(it, it) } } } private fun onPaste() { val manager = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager if (manager.hasPrimaryClip() && manager.primaryClip.itemCount > 0) { manager.primaryClip.getItemAt(0).text?.let { input.editor?.text?.insert(input.cursorPosition, it) } } } }
gpl-3.0
5546a70d7a29b9b9252e886cce577520
28.627451
145
0.584476
4.91268
false
false
false
false
jtransc/jtransc
jtransc-core/src/com/jtransc/ast/treeshaking/TreeShaking.kt
1
15231
package com.jtransc.ast.treeshaking import com.jtransc.annotation.JTranscAddFileList import com.jtransc.annotation.JTranscKeepConstructors import com.jtransc.ast.* import com.jtransc.ast.template.CommonTagHandler import com.jtransc.error.invalidOp import com.jtransc.gen.TargetName import com.jtransc.plugin.JTranscPluginGroup import java.util.* fun TreeShaking(program: AstProgram, target: String, trace: Boolean, plugins: JTranscPluginGroup, initialClasses: List<String>, keepClasses: List<String>): AstProgram { // The unshaked program should be cached, in a per class basis, since it doesn't have information about other classes. val shaking = TreeShakingApi(program, target, trace, plugins) for (clazz in keepClasses) shaking.addBasicClass(clazz.fqname, "<KEEP_CLASS>") shaking.addMethod(shaking.main.ref, "<ENTRY>") //shaking.addMethod(program[FqName("java.lang.reflect.InvocationHandler")].getMethods("invoke").first().ref, "<ENTRY>") when (target) { // HACK "cpp" -> { val filecontent = program.resourcesVfs["cpp/Base.cpp"].readString() shaking.addTemplateReferences(filecontent, "java.lang.Object".fqname, templateReason = "<base target>: cpp/Base.cpp") } } return shaking.newprogram; } class TreeShakingApi( val oldprogram: AstProgram, val target: String, val trace: Boolean, val plugins: JTranscPluginGroup ) { val program = oldprogram val targetName = TargetName(target) val SHAKING_TRACE = trace val main = program[program.entrypoint].getMethodSure("main", AstTypeBuild { METHOD(VOID, ARRAY(STRING)) }.desc) val newprogram = AstProgram( program.configResourcesVfs, program.configEntrypoint, program.types, program.injector ).apply { this.lastClassId = oldprogram.lastClassId this.lastFieldId = oldprogram.lastFieldId this.lastMethodId = oldprogram.lastMethodId } val processed = hashSetOf<Any>() val newclasses = hashMapOf<FqName, AstClass>() val classtree = ClassTree(SHAKING_TRACE, newprogram) val classesWithKeepConstructors = oldprogram.classes.filter { it.annotationsList.contains<JTranscKeepConstructors>() }.map { it.name }.toSet() val actualClassesWithKeepConstructors = oldprogram.classes.filter { it.name in classesWithKeepConstructors || it.annotationsList.list.any { it.type.name in classesWithKeepConstructors } }.map { it.name }.toSet() // oldclazz.annotationsList.list.any { it.type.name in classesWithKeepConstructors }) val config = TRefConfig(TRefReason.TREESHAKING) fun addTemplateReferences(template: String, currentClass: FqName, templateReason: String) { val refs = GetTemplateReferences(oldprogram, template, currentClass, config) val reason = "template $templateReason" for (ref in refs) { if (SHAKING_TRACE) println("TEMPLATEREF: $ref") when (ref) { is CommonTagHandler.CLASS -> addBasicClass(ref.clazz.name, reason = reason) is CommonTagHandler.SINIT -> addBasicClass(ref.method.containingClass.name, reason = reason) is CommonTagHandler.CONSTRUCTOR -> { addBasicClass(ref.ref.classRef.name, reason = reason) addMethod(ref.method.ref, reason = reason) } is CommonTagHandler.FIELD -> { addBasicClass(ref.ref.classRef.name, reason = reason) addField(ref.field.ref, reason = reason) } is CommonTagHandler.METHOD -> { addBasicClass(ref.ref.classRef.name, reason = reason) addMethod(ref.method.ref, reason = reason) } } } } fun addFullClass(fqname: FqName, reason: Any? = null) { val oldclazz = program[fqname] //val newclazz = addBasicClass(fqname) for (method in oldclazz.methods) addMethod(method.ref, reason = "fullclass $fqname") for (field in oldclazz.fields) addField(field.ref, reason = "fullclass $fqname") } private fun _addMiniBasicClass(fqname: FqName, reason: Any? = null): AstClass { if (fqname !in newclasses) { if (SHAKING_TRACE) println("_addMiniBasicClass: $fqname. Reason: $reason") val oldclazz = program[fqname] val newclazz = AstClass( source = oldclazz.source, program = newprogram, name = fqname, modifiers = oldclazz.modifiers, extending = oldclazz.extending, implementing = oldclazz.implementing, annotations = oldclazz.annotations//, //classId = oldclazz.classId ) newclasses[fqname] = newclazz newprogram.add(newclazz) for (impl in oldclazz.implementing) _addMiniBasicClass(impl, reason = "implementing $fqname") if (oldclazz.extending != null) _addMiniBasicClass(oldclazz.extending, reason = "extending $fqname") classtree.add(newclazz) } return newclasses[fqname]!! } val initializedClasses = hashSetOf<FqName>() fun addBasicClass(fqname: FqName, reason: String): AstClass { if (fqname !in initializedClasses) { initializedClasses += fqname if (SHAKING_TRACE) println("addBasicClass: $fqname. Reason: $reason") val oldclazz = program[fqname] val newclazz = _addMiniBasicClass(fqname) plugins.onTreeShakingAddBasicClass(this, fqname, oldclazz, newclazz) for (impl in oldclazz.implementing) addBasicClass(impl, reason = "implementing $fqname") if (oldclazz.extending != null) addBasicClass(oldclazz.extending, reason = "extending $fqname") val relatedTypes = oldclazz.getAllRelatedTypes().map { it.name } val keepConstructors = relatedTypes.any { it in actualClassesWithKeepConstructors } if (keepConstructors) { for (constructor in oldclazz.constructors) { addMethod(constructor.ref, reason = "<method>@JTranscKeepConstructors") } //println("keepConstructors:") } if (oldclazz.keep) { addFullClass(fqname, reason = "$fqname+@JTranscKeep") } for (field in oldclazz.fields) { if (field.keep) addField(field.ref, reason = "<field>@JTranscKeep") } for (method in oldclazz.methods) { if (method.keep) addMethod(method.ref, reason = "<method>@JTranscKeep") } // Add static constructors for (method in oldclazz.methods.filter { it.isClassInit }) { addMethod(method.ref, reason = "static constructor <clinit> fqname") } addAnnotations(newclazz.annotationsList, reason = "class $fqname") //if (newclazz.fqname == "java.lang.Object") { // invalidOp //} //println(fqname) //for (file in newclazz.annotationsList.getAllTyped<JTranscAddFile>()) { for (file in newclazz.annotationsList.getTypedList(JTranscAddFileList::value)) { if (file.process && TargetName.matches(file.target, target)) { val possibleFiles = listOf(file.prepend, file.append, file.prependAppend, file.src) for (pf in possibleFiles.filter { !it.isNullOrEmpty() }) { val filecontent = program.resourcesVfs[pf].readString() addTemplateReferences(filecontent, fqname, templateReason = "JTranscAddFileList: $pf") } } } checkTreeNewClass(newclazz) } return newclasses[fqname]!! } fun addField(fieldRef: AstFieldRef, reason: String) { _addFieldFinal(fieldRef.resolve(program).ref, reason) } private fun _addFieldFinal(fieldRef: AstFieldRef, reason: String) { if (fieldRef in processed) return if (SHAKING_TRACE) println("addField: $fieldRef. Reason: $reason") processed += fieldRef val oldfield = oldprogram.get(fieldRef) val oldfieldRef = oldfield.ref val oldfield2 = oldfield.containingClass[oldfieldRef.withoutClass] addBasicClass(fieldRef.containingClass, reason = "field $fieldRef") val newclazz = addBasicClass(oldfield2.containingClass.name, reason = "field $fieldRef") if (oldfield2.refWithoutClass in newclazz.fieldsByInfo) { // Already added return } val newfield = AstField( containingClass = newclazz, //id = oldfield.id, name = oldfield.name, type = oldfield.type, annotations = oldfield.annotations, genericSignature = oldfield.genericSignature, modifiers = oldfield.modifiers, types = newprogram.types, desc = oldfield.desc, constantValue = oldfield.constantValue ) newclazz.add(newfield) plugins.onTreeShakingAddField(this, oldfield, newfield) addAnnotations(newfield.annotationsList, reason = "field $fieldRef") for (type in newfield.type.getRefTypesFqName()) { addBasicClass(type, reason = "field $fieldRef") } } fun addAnnotations(annotations: AstAnnotationList, reason: String) { //for (annotation in annotations.list) { for (annotation in annotations.listRuntime) { try { for (ref in annotation.getRefTypesFqName()) { addBasicClass(ref, "annotation $reason") } } catch (e: Throwable) { System.err.println("While adding annotations for ${annotations.containerRef}:") e.printStackTrace() } } } fun addMethod(methodRef: AstMethodRef, reason: String) { _addMethodFinal(methodRef.resolve(program).ref, reason) } private fun _addMethodFinal(methodRef: AstMethodRef, reason: String) { if (methodRef in processed) return if (SHAKING_TRACE) println("methodRef: $methodRef. Reason: $reason") processed += methodRef val oldmethod = program[methodRef] ?: invalidOp("Can't find $methodRef") val oldclazz = program[methodRef]?.containingClass ?: invalidOp("Can't find $methodRef : containingClass") val newclazz = addBasicClass(methodRef.containingClass, reason) val newmethod = AstMethod( containingClass = newclazz, //id = oldmethod.id, name = oldmethod.name, methodType = oldmethod.methodType, annotations = oldmethod.annotations, signature = oldmethod.signature, genericSignature = oldmethod.genericSignature, defaultTag = oldmethod.defaultTag, modifiers = oldmethod.modifiers, generateBody = oldmethod.generateBody, bodyRef = oldmethod.bodyRef, parameterAnnotations = oldmethod.parameterAnnotations ) //println(" -> ${oldmethod.dependencies.classes}") //if (methodRef.name == "testStaticTest1") println(methodRef) newclazz.add(newmethod) plugins.onTreeShakingAddMethod(this, oldmethod, newmethod) for (ref in methodRef.type.getRefTypesFqName()) addBasicClass(ref, reason = "$methodRef") for (methodBody in newmethod.annotationsList.getBodiesForTarget(targetName)) { addTemplateReferences(methodBody.value, methodRef.containingClass, "methodBody=$newmethod") } val callSite = newmethod.annotationsList.getCallSiteBodyForTarget(targetName) if (callSite != null) addTemplateReferences(callSite, methodRef.containingClass, "methodBodyCallSite=$newmethod") //if (methodRef.name == "_onKeyDownUp") { // val bodyDependencies = oldmethod.bodyDependencies // println(bodyDependencies) //} if (oldmethod.hasDependenciesInBody(targetName)) { for (dep in oldmethod.bodyDependencies.classes) addBasicClass(dep.name, reason = "dependenciesInBody $methodRef") for (dep in oldmethod.bodyDependencies.fields) addField(dep, reason = "dependenciesInBody $methodRef") for (dep in oldmethod.bodyDependencies.methods) addMethod(dep, reason = "dependenciesInBody $methodRef") } addAnnotations(newmethod.annotationsList, reason = "method $methodRef") for (paramAnnotation in newmethod.parameterAnnotations) { addAnnotations(AstAnnotationList(newmethod.ref, paramAnnotation), reason = "method $methodRef") } checkTreeNewMethod(newmethod) } // This should propagate methods to ancestors and descendants // @TODO: We should really include ancestors? Even when they are not referenced? For now, let's play it safe. private fun checkTreeNewClass(newclazz: AstClass) { // ancestors are known (descendants may not have been built completely) val relatedClasses = (listOf(newclazz) + newclazz.ancestors + newclazz.allInterfacesInAncestors + classtree.getDescendantsAndAncestors(newclazz)).distinct() val oldclazz = program[newclazz.name] //println(oldclazz.annotationsList.list) /* println("----------") println(newclazz.name) println(oldclazz.annotationsList.getTypedList(com.jtransc.annotation.JTranscAddFileList::value)) println(oldclazz.annotationsList.getAllTyped<JTranscAddFileList>()) */ for (addFile in oldclazz.annotationsList.getTargetAddFiles(target)) { for (filePath in addFile.filesToProcess()) { val filecontent = program.resourcesVfs[filePath].readString() if (SHAKING_TRACE) println("PROCESSNG(TargetAddFile::${newclazz.name}): $filePath") addTemplateReferences(filecontent, newclazz.name, templateReason = "TargetAddFile : ${newclazz.name}") } //println(":" + addFile.prependAppend) //println(":" + addFile.prepend) //println(":" + addFile.append) } val methodRefs = arrayListOf<AstMethodWithoutClassRef>() for (relatedClass in relatedClasses) { for (newmethod in relatedClass.methods) { if (!newmethod.isClassOrInstanceInit) methodRefs += newmethod.ref.nameDesc } } for (relatedClass in relatedClasses) { for (mref in methodRefs) { val rmethod = oldprogram[relatedClass.name].getMethod(mref) if (rmethod != null) addMethod(rmethod.ref, "checkTreeNewClass $newclazz") } } for (method in newclazz.methods) { //method.annotationsList } } // private fun checkTreeNewMethod(newmethod: AstMethod) { val newclazz = newmethod.containingClass val relatedClasses = (newclazz.thisAncestorsAndInterfaces + classtree.getDescendantsAndAncestors(newclazz)).distinct() //val relatedClasses = newclazz.ancestors + classtree.getDescendants(newclazz) // ancestors are known (descendants may not have been built completely) val methods = (relatedClasses).map { relatedClass -> oldprogram[relatedClass.name].getMethod(newmethod.name, newmethod.desc) //val rmethod = oldprogram[relatedClass.name].getMethod(newmethod.name, newmethod.desc) //if (rmethod != null) addMethod(rmethod.ref, "checkTreeNewMethod $newmethod") }.filterNotNull() if (SHAKING_TRACE) { for (rclass in relatedClasses) { //println(" *-- $rclass") } for (rmethod in methods) { val methodRef = rmethod.ref if (methodRef !in processed) { println(" <-- $rmethod") } else { //println(" :-- $rmethod") } } } for (rmethod in methods) { addMethod(rmethod.ref, "checkTreeNewMethod $newmethod") } } } class ClassTree(val SHAKING_TRACE: Boolean, val program: AstProgram) { val childrenList = hashMapOf<AstClass, ArrayList<AstClass>>() fun getChildren(clazz: AstClass): ArrayList<AstClass> { if (clazz.program != program) invalidOp("TreeShaking Internal Error: Invalid program [1]") return childrenList.getOrPut(clazz) { arrayListOf() } } fun getDescendants(clazz: AstClass): List<AstClass> { if (clazz.program != program) invalidOp("TreeShaking Internal Error: Invalid program [2]") return getChildren(clazz) + getChildren(clazz).flatMap { getChildren(it) } } fun getDescendantsAndAncestors(clazz: AstClass): List<AstClass> { return getDescendants(clazz).flatMap { it.thisAncestorsAndInterfaces } } fun add(clazz: AstClass) { if (clazz.program != program) invalidOp("TreeShaking Internal Error: Invalid program [3]") if (SHAKING_TRACE) println(" :: $clazz :: ${clazz.extending} :: ${clazz.implementing}") if (clazz.extending != null) getChildren(program[clazz.extending]) += clazz for (impl in clazz.implementing) getChildren(program[impl]) += clazz } fun dump() { for ((clazz, children) in childrenList) { println("* $clazz") println(" - $children") } } }
apache-2.0
d75439207bf65e5b95feb75e6c6be8e6
35.264286
168
0.731863
3.877546
false
false
false
false
outadoc/Twistoast-android
keolisprovider/src/main/kotlin/fr/outadev/android/transport/timeo/dto/ListeLignesDTO.kt
1
1317
/* * Twistoast - ListeLignesDTO.kt * Copyright (C) 2013-2016 Baptiste Candellier * * Twistoast 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. * * Twistoast 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 fr.outadev.android.transport.timeo.dto import org.simpleframework.xml.Element import org.simpleframework.xml.ElementList /** * Represents a list of lines or stops in the XML API (xml=1 root node). * * @author outadoc */ class ListeLignesDTO { @field:Element(name = "erreur") var erreur: ErreurDTO? = null @field:Element(name = "heure") var heure: String? = null @field:Element(name = "date") var date: String? = null @field:Element(name = "expire") var expire: String? = null @field:ElementList(name = "alss") var alss: List<AlsDTO> = mutableListOf() }
gpl-3.0
7f8211bb3e6c33788c48b9f504120939
36.657143
78
0.724374
3.648199
false
false
false
false
http4k/http4k
http4k-server/ktorcio/src/main/kotlin/org/http4k/server/KtorCIO.kt
1
3172
package org.http4k.server import io.ktor.http.ContentType import io.ktor.http.HttpHeaders import io.ktor.http.HttpStatusCode import io.ktor.server.application.createApplicationPlugin import io.ktor.server.application.install import io.ktor.server.cio.CIO import io.ktor.server.cio.CIOApplicationEngine import io.ktor.server.engine.embeddedServer import io.ktor.server.engine.stop import io.ktor.server.plugins.origin import io.ktor.server.request.ApplicationRequest import io.ktor.server.request.header import io.ktor.server.request.httpMethod import io.ktor.server.request.uri import io.ktor.server.response.ApplicationResponse import io.ktor.server.response.header import io.ktor.server.response.respondOutputStream import io.ktor.utils.io.jvm.javaio.toInputStream import kotlinx.coroutines.Dispatchers.Default import kotlinx.coroutines.withContext import org.http4k.core.Headers import org.http4k.core.HttpHandler import org.http4k.core.Method import org.http4k.core.Request import org.http4k.core.RequestSource import org.http4k.core.Response import org.http4k.lens.Header import org.http4k.lens.Header.CONTENT_TYPE import org.http4k.server.ServerConfig.StopMode.Immediate import java.util.concurrent.TimeUnit.SECONDS import io.ktor.http.Headers as KHeaders @Suppress("EXPERIMENTAL_API_USAGE") class KtorCIO(val port: Int = 8000, override val stopMode: ServerConfig.StopMode) : ServerConfig { constructor(port: Int = 8000) : this(port, Immediate) init { if (stopMode != Immediate) { throw ServerConfig.UnsupportedStopMode(stopMode) } } override fun toServer(http: HttpHandler): Http4kServer = object : Http4kServer { private val engine: CIOApplicationEngine = embeddedServer(CIO, port) { install(createApplicationPlugin(name = "http4k") { onCall { withContext(Default) { it.response.fromHttp4K(http(it.request.asHttp4k())) } } }) } override fun start() = apply { engine.start() } override fun stop() = apply { engine.stop(0, 2, SECONDS) } override fun port() = engine.environment.connectors[0].port } } fun ApplicationRequest.asHttp4k() = Request(Method.valueOf(httpMethod.value), uri) .headers(headers.toHttp4kHeaders()) .body(receiveChannel().toInputStream(), header("Content-Length")?.toLong()) .source(RequestSource(origin.remoteHost, scheme = origin.scheme)) // origin.remotePort does not exist for Ktor suspend fun ApplicationResponse.fromHttp4K(response: Response) { status(HttpStatusCode.fromValue(response.status.code)) response.headers .filterNot { HttpHeaders.isUnsafe(it.first) || it.first == CONTENT_TYPE.meta.name } .forEach { header(it.first, it.second ?: "") } call.respondOutputStream( CONTENT_TYPE(response)?.let { ContentType.parse(it.toHeaderValue()) } ) { response.body.stream.copyTo(this) } } private fun KHeaders.toHttp4kHeaders(): Headers = names().flatMap { name -> (getAll(name) ?: emptyList()).map { name to it } }
apache-2.0
7d3d6b8da3b848afb4694c43f20c6461
35.45977
114
0.715952
3.911221
false
false
false
false
msebire/intellij-community
plugins/github/src/org/jetbrains/plugins/github/pullrequest/avatars/CachingGithubAvatarIconsProvider.kt
2
3773
// 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.github.pullrequest.avatars import com.intellij.openapi.Disposable import com.intellij.openapi.application.ModalityState import com.intellij.openapi.application.runInEdt import com.intellij.openapi.util.LowMemoryWatcher import com.intellij.util.IconUtil import com.intellij.util.ui.JBUI import com.intellij.util.ui.JBValue import icons.GithubIcons import org.jetbrains.annotations.CalledInAwt import org.jetbrains.plugins.github.api.GithubApiRequestExecutor import org.jetbrains.plugins.github.api.data.GithubUser import org.jetbrains.plugins.github.util.CachingGithubUserAvatarLoader import org.jetbrains.plugins.github.util.GithubImageResizer import java.awt.Component import java.awt.Graphics import java.awt.Image import java.util.concurrent.CompletableFuture import javax.swing.Icon /** * @param component which will be repainted when icons are loaded */ internal class CachingGithubAvatarIconsProvider(private val avatarsLoader: CachingGithubUserAvatarLoader, private val imagesResizer: GithubImageResizer, private val requestExecutor: GithubApiRequestExecutor, private val iconSize: JBValue, private val component: Component) : Disposable { private val scaleContext = JBUI.ScaleContext.create(component) private var defaultIcon = createDefaultIcon(iconSize.get()) private val icons = mutableMapOf<GithubUser, Icon>() init { LowMemoryWatcher.register(Runnable { icons.clear() }, this) } private fun createDefaultIcon(size: Int): Icon { val standardDefaultAvatar = GithubIcons.DefaultAvatar val scale = size.toFloat() / standardDefaultAvatar.iconWidth.toFloat() return IconUtil.scale(standardDefaultAvatar, null, scale) } @CalledInAwt fun getIcon(user: GithubUser): Icon { val iconSize = iconSize.get() // so that icons are rescaled when any scale changes (be it font size or current DPI) if (scaleContext.update(JBUI.ScaleContext.create(component))) { defaultIcon = createDefaultIcon(iconSize) icons.clear() } val modality = ModalityState.stateForComponent(component) return icons.getOrPut(user) { val icon = DelegatingIcon(defaultIcon) avatarsLoader .requestAvatar(requestExecutor, user) .thenCompose<Image?> { if (it != null) imagesResizer.requestImageResize(it, iconSize, scaleContext) else CompletableFuture.completedFuture(null) } .thenAccept { if (it != null) runInEdt(modality) { icon.delegate = IconUtil.createImageIcon(it) component.repaint() } } icon } } private class DelegatingIcon(var delegate: Icon) : Icon { override fun getIconHeight() = delegate.iconHeight override fun getIconWidth() = delegate.iconWidth override fun paintIcon(c: Component?, g: Graphics?, x: Int, y: Int) = delegate.paintIcon(c, g, x, y) } override fun dispose() {} // helper to avoid passing all the services to clients class Factory(private val avatarsLoader: CachingGithubUserAvatarLoader, private val imagesResizer: GithubImageResizer, private val requestExecutor: GithubApiRequestExecutor) { fun create(iconSize: JBValue, component: Component) = CachingGithubAvatarIconsProvider(avatarsLoader, imagesResizer, requestExecutor, iconSize, component) } }
apache-2.0
34b1b3890466b718f59e7d39beb0e030
40.461538
140
0.696793
5.05087
false
false
false
false
wseemann/RoMote
app/src/main/java/wseemann/media/romote/model/Device.kt
1
2500
package wseemann.media.romote.model import com.jaku.model.Device class Device : Device() { private var customUserDeviceName: String? = null companion object { fun fromDevice(jakuDevice: Device): wseemann.media.romote.model.Device { val device = wseemann.media.romote.model.Device() device.host = jakuDevice.host device.udn = jakuDevice.udn device.serialNumber = jakuDevice.serialNumber device.deviceId = jakuDevice.deviceId device.vendorName = jakuDevice.vendorName device.modelNumber = jakuDevice.modelNumber device.modelName = jakuDevice.modelName device.wifiMac = jakuDevice.wifiMac device.ethernetMac = jakuDevice.ethernetMac device.networkType = jakuDevice.networkType device.userDeviceName = jakuDevice.userDeviceName device.softwareVersion = jakuDevice.softwareVersion device.softwareBuild = jakuDevice.softwareBuild device.secureDevice = jakuDevice.secureDevice device.language = jakuDevice.language device.country = jakuDevice.country device.locale = jakuDevice.locale device.timeZone = jakuDevice.timeZone device.timeZoneOffset = jakuDevice.timeZoneOffset device.powerMode = jakuDevice.powerMode device.supportsSuspend = jakuDevice.supportsSuspend device.supportsFindRemote = jakuDevice.supportsFindRemote device.supportsAudioGuide = jakuDevice.supportsAudioGuide device.developerEnabled = jakuDevice.developerEnabled device.keyedDeveloperId = jakuDevice.keyedDeveloperId device.searchEnabled = jakuDevice.searchEnabled device.voiceSearchEnabled = jakuDevice.voiceSearchEnabled device.notificationsEnabled = jakuDevice.notificationsEnabled device.notificationsFirstUse = jakuDevice.notificationsFirstUse device.supportsPrivateListening = jakuDevice.supportsPrivateListening device.headphonesConnected = jakuDevice.headphonesConnected device.isTv = jakuDevice.isTv device.isStick = jakuDevice.isStick return device } } fun getCustomUserDeviceName(): String? { return customUserDeviceName } fun setCustomUserDeviceName(customUserDeviceName: String?) { this.customUserDeviceName = customUserDeviceName } }
apache-2.0
022b72aa2cb7986028f87df32fd85815
42.12069
81
0.6884
5.668934
false
false
false
false
NooAn/bytheway
app/src/main/java/ru/a1024bits/bytheway/viewmodel/BaseViewModel.kt
1
1736
package ru.a1024bits.bytheway.viewmodel import android.arch.lifecycle.Lifecycle import android.arch.lifecycle.LifecycleObserver import android.arch.lifecycle.MutableLiveData import android.arch.lifecycle.ViewModel import android.content.Context import io.reactivex.Scheduler import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.disposables.CompositeDisposable import io.reactivex.schedulers.Schedulers import ru.a1024bits.bytheway.App import ru.a1024bits.bytheway.util.Constants import java.util.concurrent.TimeUnit /** * Created by Andrei_Gusenkov on 12/18/2017. */ open class BaseViewModel : ViewModel(), LifecycleObserver { val disposables = CompositeDisposable() val loadingStatus = MutableLiveData<Boolean>() val timeoutUnit = TimeUnit.SECONDS companion object { const val TIMEOUT_SECONDS = 14L } fun addObserver(lifecycle: Lifecycle) { lifecycle.addObserver(this) } fun removeObserver(lifecycle: Lifecycle) { lifecycle.removeObserver(this) } protected fun getBackgroundScheduler(): Scheduler { return Schedulers.io() } protected fun getMainThreadScheduler(): Scheduler { return AndroidSchedulers.mainThread() } fun markPromptIsShowing(nameScreenPrompt: String) { App.INSTANCE.getSharedPreferences(Constants.APP_PREFERENCES, Context.MODE_PRIVATE).edit().putBoolean(nameScreenPrompt, false).apply() } fun promptNotShowing(nameScreenPrompt: String): Boolean = App.INSTANCE.getSharedPreferences(Constants.APP_PREFERENCES, Context.MODE_PRIVATE).getBoolean(nameScreenPrompt, true) override fun onCleared() { disposables.dispose() super.onCleared() } }
mit
9bac231c9b1f9c851e58af6b1b1e876a
30.017857
141
0.754032
4.756164
false
false
false
false
akvo/akvo-flow-mobile
app/src/main/java/org/akvo/flow/presentation/form/view/FormViewPresenter.kt
1
5179
/* * Copyright (C) 2020 Stichting Akvo (Akvo Foundation) * * This file is part of Akvo Flow. * * Akvo Flow 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. * * Akvo Flow 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 Akvo Flow. If not, see <http://www.gnu.org/licenses/>. */ package org.akvo.flow.presentation.form.view import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.async import kotlinx.coroutines.cancelChildren import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.launch import org.akvo.flow.domain.interactor.forms.FormResult import org.akvo.flow.domain.interactor.forms.GetFormWithGroups import org.akvo.flow.domain.interactor.responses.LoadResponses import org.akvo.flow.domain.interactor.responses.ResponsesResult import org.akvo.flow.domain.languages.LoadLanguages import org.akvo.flow.domain.languages.SaveLanguages import org.akvo.flow.presentation.Presenter import org.akvo.flow.presentation.form.languages.LanguageMapper import org.akvo.flow.presentation.form.view.entity.ViewFormMapper import timber.log.Timber import javax.inject.Inject class FormViewPresenter @Inject constructor( private val saveLanguagesUseCase: SaveLanguages, private val languageMapper: LanguageMapper, private val loadLanguages: LoadLanguages, private val getFormUseCase: GetFormWithGroups, private val viewFormMapper: ViewFormMapper, private val loadResponses: LoadResponses ) : Presenter { var view: IFormView? = null private var job = SupervisorJob() private val uiScope = CoroutineScope(Dispatchers.Main + job) override fun destroy() { uiScope.coroutineContext.cancelChildren() } fun loadForm(formId: String, formInstanceId: Long) { val params: MutableMap<String, Any> = HashMap(2) params[GetFormWithGroups.PARAM_FORM_ID] = formId val paramsResponses: MutableMap<String, Any> = HashMap(2) paramsResponses[LoadResponses.PARAM_FORM_INSTANCE_ID] = formInstanceId view?.showLoading() uiScope.launch { try { // coroutineScope is needed, else in case of any network error, it will crash coroutineScope { val formResult = async { getFormUseCase.execute(params)} .await() val responsesResult = async { loadResponses.execute(paramsResponses)} .await() if (formResult is FormResult.Success && responsesResult is ResponsesResult.Success) { val viewForm = viewFormMapper.transform(formResult.domainForm, responsesResult.responses) view?.hideLoading() view?.displayForm(viewForm) } else if (formResult is FormResult.ParamError ) { Timber.e(formResult.message) view?.hideLoading() view?.showErrorLoadingForm() } else { //TODO: display specific error when responses could not be loaded view?.hideLoading() view?.showErrorLoadingForm() } } } catch (e: Exception) { Timber.e(e) view?.hideLoading() view?.showErrorLoadingForm() } } } //language is saved per survey and not form fun saveLanguages(selectedLanguages: Set<String>, surveyId: Long) { val params: MutableMap<String, Any> = HashMap(4) params[SaveLanguages.PARAM_SURVEY_ID] = surveyId params[SaveLanguages.PARAM_LANGUAGES_LIST] = selectedLanguages uiScope.launch { when(saveLanguagesUseCase.execute(params)) { is SaveLanguages.SaveLanguageResult.Success -> view?.onLanguagesSaved() is SaveLanguages.SaveLanguageResult.Error -> view?.onLanguagesSavedError() } } } fun loadLanguages(surveyId: Long, formId: String) { val params: MutableMap<String, Any> = HashMap(2) params[LoadLanguages.PARAM_SURVEY_ID] = surveyId params[LoadLanguages.PARAM_FORM_ID] = formId uiScope.launch { when(val result = loadLanguages.execute(params)) { is LoadLanguages.LanguageResult.Success -> view?.displayLanguages( languageMapper.transform( result.savedLanguages.toTypedArray(), result.availableLanguages ) ) is LoadLanguages.LanguageResult.Error -> view?.showLanguagesError() } } } }
gpl-3.0
3f36b92f80323ce1a8b1077f976a3af4
41.105691
113
0.660359
4.79537
false
false
false
false
ebraminio/DroidPersianCalendar
PersianCalendar/src/main/java/com/byagowi/persiancalendar/ui/calendar/times/TimeItemAdapter.kt
1
2797
package com.byagowi.persiancalendar.ui.calendar.times import android.view.ViewGroup import androidx.annotation.StringRes import androidx.recyclerview.widget.RecyclerView import com.byagowi.persiancalendar.R import com.byagowi.persiancalendar.databinding.TimeItemBinding import com.byagowi.persiancalendar.utils.toFormattedString import com.byagowi.persiancalendar.utils.layoutInflater import com.google.android.flexbox.FlexboxLayoutManager import io.github.persiancalendar.praytimes.PrayTimes class TimeItemAdapter : RecyclerView.Adapter<TimeItemAdapter.ViewHolder>() { @StringRes private val timeNames = listOf( R.string.imsak, R.string.fajr, R.string.sunrise, R.string.dhuhr, R.string.asr, R.string.sunset, R.string.maghrib, R.string.isha, R.string.midnight ) var prayTimes: PrayTimes? = null set(prayTimes) { field = prayTimes timeNames.indices.forEach(::notifyItemChanged) } var isExpanded = false set(expanded) { field = expanded timeNames.indices.forEach(::notifyItemChanged) } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = ViewHolder( TimeItemBinding.inflate(parent.context.layoutInflater, parent, false) ) override fun onBindViewHolder(holder: ViewHolder, position: Int) = holder.bind(position) override fun getItemCount(): Int = timeNames.size inner class ViewHolder(private val binding: TimeItemBinding) : RecyclerView.ViewHolder(binding.root) { private val emptyLayout = FlexboxLayoutManager.LayoutParams(0, 0) private val wrapContent = FlexboxLayoutManager.LayoutParams( FlexboxLayoutManager.LayoutParams.WRAP_CONTENT, FlexboxLayoutManager.LayoutParams.WRAP_CONTENT ) fun bind(position: Int) { val timeName = timeNames[position] binding.root.layoutParams = if (!isExpanded && timeName !in listOf( R.string.fajr, R.string.dhuhr, R.string.maghrib ) ) emptyLayout else wrapContent binding.name.setText(timeName) binding.time.text = prayTimes?.run { (when (timeName) { R.string.imsak -> imsakClock R.string.fajr -> fajrClock R.string.sunrise -> sunriseClock R.string.dhuhr -> dhuhrClock R.string.asr -> asrClock R.string.sunset -> sunsetClock R.string.maghrib -> maghribClock R.string.isha -> ishaClock R.string.midnight -> midnightClock else -> midnightClock }).toFormattedString() } ?: "" } } }
gpl-3.0
4e3cf6bd40ca55de37331142923bf4f5
37.847222
92
0.643904
4.898424
false
false
false
false
dafi/commonutils
app/src/main/java/com/ternaryop/utils/date/TimeDistance.kt
1
2854
package com.ternaryop.utils.date import java.time.LocalDate import java.time.format.DateTimeFormatter import java.time.temporal.ChronoUnit import java.time.temporal.ChronoUnit.DAYS import java.time.temporal.ChronoUnit.YEARS import java.util.Calendar /** * Created by dave on 08/06/14. * Contains methods to compute days, years */ const val APPEND_DATE_FOR_PAST_AND_PRESENT = 1 private val DATE_FORMATTER_TOMORROW = DateTimeFormatter.ofPattern("'Tomorrow at' HH:mm") private val DATE_FORMATTER_TODAY = DateTimeFormatter.ofPattern("'Today at' HH:mm") private val DATE_FORMATTER_DATE = DateTimeFormatter.ofPattern("dd/MM/yyyy") private val DATE_FORMATTER_IN_DAYS = DateTimeFormatter.ofPattern("'In %1\$d days at' HH:mm") /** * Calculate the years between the current calendar and the passed one, if null 'now' is used */ fun Calendar.yearsBetweenDates(to: Calendar? = null): Int { val now = LocalDate.of(get(Calendar.YEAR), get(Calendar.MONTH) + 1, get(Calendar.DAY_OF_MONTH)) val toLocal = to?.run { LocalDate.of(get(Calendar.YEAR), get(Calendar.MONTH) + 1, get(Calendar.DAY_OF_MONTH)) } ?: LocalDate.now() return YEARS.between(now, toLocal).toInt() } /** * Determine days difference since this timestamp to current time * if timestamp is equal to Long.MAX_VALUE then return Long.MAX_VALUE * * @return numbers of days, if negative indicates days in the future beyond passed timestamp */ fun Long.daysSinceNow(): Long { return if (this == Long.MAX_VALUE) { Long.MAX_VALUE } else { DAYS.between(millisToLocalDate(), LocalDate.now()) } } fun Long.formatPublishDaysAgo(flags: Int): String { val dayString = StringBuffer() if (this == Long.MAX_VALUE) { dayString.append("Never Published") } else { val localDateTime = millisToLocalDateTime() val days = ChronoUnit.DAYS.between(localDateTime.toLocalDate(), LocalDate.now()) if (days < 0) { if (days == -1L) { DATE_FORMATTER_TOMORROW.formatTo(localDateTime, dayString) } else { val s = DATE_FORMATTER_IN_DAYS.format(localDateTime) dayString.append(String.format(s, -days)) } } else { when (days) { 0L -> { DATE_FORMATTER_TODAY.formatTo(localDateTime, dayString) } 1L -> dayString.append("Yesterday") else -> dayString.append(String.format("%1\$d days ago", days)) } val appendDate = flags and APPEND_DATE_FOR_PAST_AND_PRESENT != 0 if (days > 1 && appendDate) { dayString.append(" (") DATE_FORMATTER_DATE.formatTo(localDateTime, dayString) dayString.append(")") } } } return dayString.toString() }
mit
cae18a27e4ea7f049130633aabdf0238
34.234568
99
0.639804
4.065527
false
false
false
false
songzhw/Hello-kotlin
AdvancedJ/src/main/kotlin/pojo/StoryResponse.kt
1
776
package pojo import org.json.JSONObject /* { "code": 100, "desp": "server connected", "data": { "id": 123, "content": "long long time ago" } } */ class StoryResponse(val json : String) { var code: Int = 0 var desp: String = "" var id : Int = 0 var story: String = "" init { val jsonObject = JSONObject(json) code = jsonObject.getInt("code") desp = jsonObject.getString("desp") val tmpData : JSONObject? = jsonObject.get("data") as JSONObject? id = tmpData?.getInt("id") ?: 0 story = tmpData?.getString("content") ?: "" } override fun toString(): String { return "StoryResponse(code=$code, desp='$desp', id=$id, story='$story')" } }
apache-2.0
8b46f0a4a0937276d452d23963b6956f
20
80
0.541237
3.730769
false
false
false
false
BasinMC/Basin
faucet/src/main/kotlin/org/basinmc/faucet/world/WorldProperties.kt
1
5221
/* * Copyright 2016 Hex <[email protected]> * and other copyright owners as documented in the project's IP log. * * Licensed under the Apache License, Version 2.0 (the "License&quot; * 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.basinmc.faucet.world import org.basinmc.faucet.math.Vector2Int import org.basinmc.faucet.math.Vector3Int /** * Represents various properties about a world. Default values are taken from * net.minecraft.world.storage.WorldInfo */ class WorldProperties(private var spawn: Vector3Int?, @Deprecated("NMS Magic Number") val dimensionId: Int, // TODO: Deprecated NMS magic number - Really necessary? private var name: String?) { // FIXME: Not fully migrated yet // Do we really need to make this mutable? Optimally worldgen parameters should be final private var seaLevel = 63 private var difficulty = Difficulty.NORMAL val timer = Timer() private var hardcore = false private var defaultGamemode = GameMode.SURVIVAL private var borderEnabled = false private var worldBorder = Border() private var rainTime = 0 fun getSeaLevel(): Int { return seaLevel } fun setSeaLevel(seaLevel: Int): WorldProperties { this.seaLevel = seaLevel return this } fun getDifficulty(): Difficulty { return difficulty } fun setDifficulty(difficulty: Difficulty): WorldProperties { this.difficulty = difficulty return this } fun getSpawn(): Vector3Int? { return spawn } fun setSpawn(spawn: Vector3Int): WorldProperties { this.spawn = spawn return this } fun getName(): String? { return name } fun setName(name: String): WorldProperties { this.name = name return this } fun isHardcore(): Boolean { return hardcore } fun setHardcore(hardcore: Boolean): WorldProperties { this.hardcore = hardcore return this } fun getDefaultGamemode(): GameMode { return defaultGamemode } fun setDefaultGamemode(defaultGamemode: GameMode): WorldProperties { this.defaultGamemode = defaultGamemode return this } fun isBorderEnabled(): Boolean { return borderEnabled } fun setBorderEnabled(borderEnabled: Boolean): WorldProperties { this.borderEnabled = borderEnabled return this } fun getWorldBorder(): Border { return worldBorder } fun setWorldBorder(worldBorder: Border): WorldProperties { this.worldBorder = worldBorder return this } fun getRainTime(): Int { return rainTime } fun setRainTime(rainTime: Int): WorldProperties { this.rainTime = rainTime return this } /** * Properties relating to a world border. Default values are taken from * net.minecraft.world.storage.WorldInfo */ class Border { private var center = Vector2Int(0, 0) private var radius = 6.0E7 private var safeZone = 5.0 private var damage = 0.2 private var warningDistance = 5 private var warningTime = 15 /** * Get the block coordinates of the center of the world border * * @return a 2 dimensional integer vector */ fun getCenter(): Vector2Int { return center } fun setCenter(center: Vector2Int): Border { this.center = center return this } /** * Get the distance which the world border extends in each direction from the center. * * @return distance, in blocks */ fun getRadius(): Double { return radius } fun setRadius(radius: Double): Border { this.radius = radius return this } fun getSafeZone(): Double { return safeZone } fun setSafeZone(safeZone: Double): Border { this.safeZone = safeZone return this } /** * Get the amount of damage dealt per block to players who cross the border */ fun getDamage(): Double { return damage } fun setDamage(damage: Double): Border { this.damage = damage return this } fun getWarningDistance(): Int { return warningDistance } fun setWarningDistance(warningDistance: Int): Border { this.warningDistance = warningDistance return this } fun getWarningTime(): Int { return warningTime } fun setWarningTime(warningTime: Int): Border { this.warningTime = warningTime return this } } class Timer { private var totalTime = 0 private var localTime = 0 fun getLocalTime(): Int { return localTime } fun setLocalTime(localTime: Int): Timer { this.localTime = localTime return this } fun getTotalTime(): Int { return totalTime } fun setTotalTime(totalTime: Int): Timer { this.totalTime = totalTime return this } } }
apache-2.0
741a882f37c36c2cee03b9c2c05e54a1
21.691304
97
0.669669
4.356427
false
false
false
false
aCoder2013/general
general-server/src/main/java/com/song/middleware/server/storage/mysql/MysqlStorageComponent.kt
1
5004
package com.song.middleware.server.storage.mysql import com.song.middleware.server.domain.ServiceDO import com.song.middleware.server.domain.ServiceStatus import com.song.middleware.server.storage.ServiceStorageComponent import com.song.middleware.server.storage.exception.StorageException import com.song.middleware.server.storage.mysql.mapper.ServiceMapper import com.song.middleware.server.util.HttpUtils import okhttp3.Request.Builder import org.slf4j.LoggerFactory import org.springframework.beans.factory.annotation.Autowired import org.springframework.stereotype.Component import java.io.IOException import java.util.concurrent.* import javax.annotation.PostConstruct /** * Created by song on 2017/8/5. */ @Component class MysqlStorageComponent @Autowired constructor(private val serviceMapper: ServiceMapper) : ServiceStorageComponent { private var executor: ExecutorService? = null private var healthCheckExecutor: ScheduledExecutorService? = null @PostConstruct fun init() { val processorNum = Runtime.getRuntime().availableProcessors() this.executor = ThreadPoolExecutor(processorNum, processorNum, 0L, TimeUnit.MILLISECONDS, LinkedBlockingQueue<Runnable>(DEFAULT_CAPACITY)) { r, executor -> executor.submit(r) throw StorageException("The storage thread pool queue is full, plz check.") } this.healthCheckExecutor = Executors.newScheduledThreadPool(processorNum) Runtime.getRuntime().addShutdownHook(Thread { executor!!.shutdown() try { if (!executor!!.awaitTermination(1, TimeUnit.MINUTES)) { val runnables = executor!!.shutdownNow() log.warn( "Storage executor was abruptly shut down. {} running tasks will be interrupted.", runnables.size) } healthCheckExecutor!!.shutdown() } catch (ignore: InterruptedException) { //we're shutting down anyway. } }) } override fun syncQuery(name: String, ip: String, port: String): ServiceDO { try { return serviceMapper.findOne(name, ip, port) } catch (e: StorageException) { throw StorageException(e) } } override fun syncQuery(name: String): List<ServiceDO> { try { return serviceMapper.findAllByName(name) } catch (e: Exception) { throw StorageException(e) } } override fun asyncQuery(name: String): Future<List<ServiceDO>> { return executor!!.submit<List<ServiceDO>> { serviceMapper.findAllByName(name) } } override fun syncRegister(serviceDO: ServiceDO) { try { val serviceInDB = serviceMapper .findOne(serviceDO.name!!, serviceDO.ip!!, serviceDO.port!!) if (serviceDO.status == ServiceStatus.DOWN.code) { serviceMapper .updateStatus(serviceInDB.id, ServiceStatus.DOWN.code) } this.healthCheckExecutor!!.scheduleAtFixedRate({ val serviceInstance = serviceMapper .findOne(serviceDO.name!!, serviceDO.ip!!, serviceDO.port!!) var checkSuccess = false try { val execute = HttpUtils.instance .newCall( Builder().url(serviceInstance.healthCheckUrl).build()) .execute() if (execute.isSuccessful) { checkSuccess = true } } catch (e: IOException) { log.error("health check failed", e) } if (!checkSuccess) { serviceMapper .updateStatus(serviceInstance.id, ServiceStatus.DOWN.code) } }, 60, serviceDO.healthCheckInterval, TimeUnit.SECONDS) log.info("Discover a new instance {}/{}:{}", serviceDO.name, serviceDO.id, serviceDO.ip) } catch (e: Exception) { throw StorageException("Save service into storage failed_" + e.message, e) } } override fun asyncRegister(serviceDO: ServiceDO): Future<*> { return executor!!.submit { syncRegister(serviceDO) } } override fun syncUnregister(name: String, ip: String, port: String) { try { val serviceDO = serviceMapper.findOne(name, ip, port) if (serviceDO != null) { serviceMapper.updateStatus(serviceDO.id, ServiceStatus.OFFLINE.code) } } catch (e: Exception) { throw StorageException(e) } } companion object { private val log = LoggerFactory.getLogger(MysqlStorageComponent.javaClass) private val DEFAULT_CAPACITY = 5000 } }
apache-2.0
a019e69537b7febfbc50bcc2f86dab09
35.794118
109
0.60032
5.22884
false
false
false
false
debop/debop4k
debop4k-core/src/main/kotlin/debop4k/core/collections/RingBuffer.kt
1
3559
/* * Copyright (c) 2016. Sunghyouk Bae <[email protected]> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package debop4k.core.collections import org.eclipse.collections.api.block.predicate.Predicate import org.eclipse.collections.impl.list.mutable.FastList import java.lang.IndexOutOfBoundsException import java.util.* /** * 제한된 크기를 가지는 Ring Buffer 입니다. * * @author debop [email protected] */ class RingBuffer<E>(val maxSize: Int) : Iterable<E> { @Suppress("UNCHECKED_CAST") val array: Array<E?> = arrayOfNulls<Any?>(maxSize) as Array<E?> // Array<Any?>(maxSize, { null }) as Array<E?> var read: Int = 0 var write: Int = 0 var _count: Int = 0 val length: Int get() = _count fun size(): Int = _count val isEmpty: Boolean get() = _count == 0 fun add(item: E): Boolean { array[write] = item write = (++write) % maxSize if (_count == maxSize) read = (++read) % maxSize else ++_count return true } fun addAll(vararg elements: E): Boolean { elements.forEach { add(it) } return true } fun addAll(c: Collection<E>): Boolean { c.forEach { add(it) } return true } operator fun get(index: Int): E { if (index >= _count) throw IndexOutOfBoundsException(index.toString()) return array[(read + index) % maxSize]!! } fun drop(n: Int): RingBuffer<E> { if (n >= maxSize) clear() read = (read + n) % maxSize return this } fun removeIf(predicate: Predicate<E>): Boolean { return removeIf { predicate.accept(it) } } fun removeIf(predicate: (E) -> Boolean): Boolean { var removeCount = 0 var j = 0 for (i in 0 until _count) { val elem = get(i) if (predicate(elem)) { removeCount++ } else { if (j < i) set(j, elem) j++ } } _count -= removeCount write = (read + _count) % maxSize return removeCount > 0 } operator fun set(index: Int, elem: E): Unit { if (index >= _count) throw IndexOutOfBoundsException(index.toString()) array[(read + index) % maxSize] = elem } fun next(): E? { if (read == write) throw NoSuchElementException() val result = array[read] read = (++read) % maxSize _count-- return result } fun clear(): Unit { read = 0 write = 0 _count = 0 } inline fun <reified E> toArray(): Array<E?> { val result = arrayOfNulls<E?>(_count) return toArray(result) } inline fun <reified E> toArray(a: Array<E?>): Array<E?> { var b = a if (a.size < length) { b = arrayOfNulls<E?>(length) } this.forEachIndexed { i, e -> b[i] = e as E } return b } fun toList(): FastList<E> = FastList.newList(this) override fun iterator(): MutableIterator<E> { return object : MutableIterator<E> { private var index = 0 override fun hasNext(): Boolean = index != _count override fun next(): E = get(index++) override fun remove() { // Nothing to do. } } } }
apache-2.0
36e50e9f6cd4e0483895b58f07df3cfa
21.812903
112
0.615276
3.67846
false
false
false
false
FHannes/intellij-community
python/src/com/jetbrains/python/pyi/PyiCustomPackageIdentifier.kt
12
1070
/* * Copyright 2000-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jetbrains.python.pyi import com.intellij.psi.PsiDirectory import com.intellij.psi.PsiFile import com.jetbrains.python.PyNames import com.jetbrains.python.psi.PyCustomPackageIdentifier /** * @author vlan */ class PyiCustomPackageIdentifier : PyCustomPackageIdentifier { override fun isPackage(directory: PsiDirectory) = directory.findFile(PyNames.INIT_DOT_PYI) != null override fun isPackageFile(file: PsiFile) = file.name == PyNames.INIT_DOT_PYI }
apache-2.0
5040f395ab4c71e64137ca044bcae1c0
34.666667
100
0.766355
4.007491
false
false
false
false
gotev/android-upload-service
examples/app/demoapp/src/main/java/net/gotev/uploadservicedemo/activities/HttpUploadActivity.kt
2
5324
package net.gotev.uploadservicedemo.activities import android.os.Bundle import android.view.Menu import android.view.MenuItem import android.widget.ArrayAdapter import android.widget.EditText import android.widget.Spinner import androidx.core.app.NavUtils import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import net.gotev.recycleradapter.AdapterItem import net.gotev.recycleradapter.RecyclerAdapter import net.gotev.uploadservicedemo.R import net.gotev.uploadservicedemo.dialogs.AddFileParameterNameDialog import net.gotev.uploadservicedemo.dialogs.AddNameValueDialog import net.gotev.uploadservicedemo.utils.UploadItemUtils import net.gotev.uploadservicedemo.views.AddItem abstract class HttpUploadActivity : FilePickerActivity() { val httpMethod: Spinner by lazy { findViewById(R.id.http_method) } val serverUrl: EditText by lazy { findViewById(R.id.server_url) } val addHeader: AddItem by lazy { findViewById(R.id.add_header) } val addParameter: AddItem by lazy { findViewById(R.id.add_parameter) } val addFile: AddItem by lazy { findViewById(R.id.add_file) } private val uploadItemsAdapter = RecyclerAdapter() private val uploadItemUtils = UploadItemUtils(uploadItemsAdapter) protected var fileParameterName: String? = null private val addHeaderDialog by lazy { AddNameValueDialog( context = this, delegate = { name, value -> uploadItemUtils.addHeader(name, value) }, asciiOnly = true, title = R.string.add_header, nameHint = R.string.header_name_hint, valueHint = R.string.header_value_hint, nameError = R.string.provide_header_name, valueError = R.string.provide_header_value ) } private val addParameterDialog by lazy { AddNameValueDialog( context = this, delegate = { name, value -> uploadItemUtils.addParameter(name, value) }, asciiOnly = false, title = R.string.add_parameter, nameHint = R.string.parameter_name_hint, valueHint = R.string.parameter_value_hint, nameError = R.string.provide_parameter_name, valueError = R.string.provide_parameter_value ) } private val addFileParameterNameDialog: AddFileParameterNameDialog by lazy { AddFileParameterNameDialog( context = this, hint = R.string.parameter_name_hint, errorMessage = R.string.provide_parameter_name, detailsMessage = R.string.next_instructions, delegate = { value -> fileParameterName = value openFilePicker() } ) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_upload) supportActionBar?.apply { setDisplayShowHomeEnabled(true) setDisplayHomeAsUpEnabled(true) } httpMethod.adapter = ArrayAdapter.createFromResource( this, R.array.http_methods, android.R.layout.simple_spinner_item ).apply { setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item) } findViewById<RecyclerView>(R.id.request_items).apply { layoutManager = LinearLayoutManager(this@HttpUploadActivity, RecyclerView.VERTICAL, false) adapter = uploadItemsAdapter } emptyItem?.let { uploadItemsAdapter.setEmptyItem(it) } addHeader.setOnClickListener { addHeaderDialog.show() } addParameter.setOnClickListener { addParameterDialog.show() } addFile.setOnClickListener { addFileParameterNameDialog.show() } } override fun onCreateOptionsMenu(menu: Menu): Boolean { menuInflater.inflate(R.menu.menu_upload, menu) return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { android.R.id.home -> { NavUtils.navigateUpFromSameTask(this) return true } R.id.settings -> return true R.id.info -> { onInfo() return true } R.id.done -> { onDone( httpMethod = httpMethod.selectedItem as String, serverUrl = serverUrl.text.toString(), uploadItemUtils = uploadItemUtils ) return true } } return super.onOptionsItemSelected(item) } override fun onPause() { super.onPause() addParameterDialog.hide() addHeaderDialog.hide() addFileParameterNameDialog.hide() } override fun onPickedFiles(pickedFiles: List<String>) { val paramName = fileParameterName if (paramName.isNullOrBlank()) return uploadItemUtils.addFile(paramName, pickedFiles.first()) } abstract val emptyItem: AdapterItem<*>? abstract fun onDone(httpMethod: String, serverUrl: String, uploadItemUtils: UploadItemUtils) abstract fun onInfo() }
apache-2.0
b3283d73adcdd8e782e0f1e9bbc4d398
32.484277
96
0.639745
5.065652
false
false
false
false
dafi/photoshelf
tumblr-ui-draft/src/main/java/com/ternaryop/photoshelf/tumblr/ui/draft/fragment/RefreshHolder.kt
1
1667
package com.ternaryop.photoshelf.tumblr.ui.draft.fragment import android.content.Context import android.view.View import android.view.animation.AnimationUtils import android.widget.TextView import androidx.swiperefreshlayout.widget.SwipeRefreshLayout import com.ternaryop.photoshelf.tumblr.ui.draft.R import com.ternaryop.widget.ProgressHighlightViewLayout import com.ternaryop.widget.WaitingResultSwipeRefreshLayout internal class RefreshHolder( val context: Context, private val progressHighlightViewLayout: ProgressHighlightViewLayout, private val swipeLayout: WaitingResultSwipeRefreshLayout, listener: SwipeRefreshLayout.OnRefreshListener ) { val isRefreshing: Boolean get() = swipeLayout.isWaitingResult val progressIndicator: TextView get() = progressHighlightViewLayout.currentView as TextView init { progressHighlightViewLayout.progressAnimation = AnimationUtils.loadAnimation(context, R.anim.fade_loop) swipeLayout.setColorScheme(R.array.progress_swipe_colors) swipeLayout.setOnRefreshListener(listener) } fun advanceProgressIndicator() = progressHighlightViewLayout.incrementProgress() fun onStarted() { progressHighlightViewLayout.visibility = View.VISIBLE progressHighlightViewLayout.startProgress() progressIndicator.text = context.resources.getString(R.string.start_import_title) swipeLayout.setRefreshingAndWaitingResult(true) } fun onCompleted() { swipeLayout.setRefreshingAndWaitingResult(false) progressHighlightViewLayout.stopProgress() progressHighlightViewLayout.visibility = View.GONE } }
mit
cbc0ba9316af64d860cad15b480b727c
36.886364
111
0.787043
5.575251
false
false
false
false
NextFaze/dev-fun
devfun/src/main/java/com/nextfaze/devfun/internal/WindowCallbacks.kt
1
11172
package com.nextfaze.devfun.internal import android.app.Application import android.os.Bundle import android.view.* import android.view.accessibility.AccessibilityEvent import androidx.annotation.RequiresApi import androidx.fragment.app.DialogFragment import androidx.fragment.app.Fragment import androidx.fragment.app.FragmentActivity import androidx.fragment.app.FragmentManager import com.nextfaze.devfun.core.ActivityTracker import com.nextfaze.devfun.core.resumedActivity import com.nextfaze.devfun.internal.android.* import com.nextfaze.devfun.internal.log.* import java.util.concurrent.CopyOnWriteArrayList /** * Function signature of a listener for [Window] key events. * * @return Flag indicating if the event should be consumed (not forwarded to the system level handler). i.e. `true` will block propagation. * All key event listeners will receive the event even if one of them returns `true`. * * @see WindowCallbacks.addKeyEventListener * @see WindowCallbacks.removeKeyEventListener */ typealias KeyEventListener = (event: KeyEvent) -> Boolean /** * Function signature of a listener for [Window] focus changes. * * @see WindowCallbacks.resumedActivityHasFocus * @see WindowCallbacks.addResumedActivityFocusChangeListener * @see WindowCallbacks.removeResumedActivityFocusChangeListener */ typealias FocusChangeListener = (focus: Boolean) -> Unit /** * Handles wrapping and posting [Window] events throughout an app's life. * * Used to tell the DevMenu overlays key events, and overlays when the current activity has focus. i.e. when they should * hide if a dialog is visible etc. * * @see KeyEventListener * @see FocusChangeListener */ @Suppress("MemberVisibilityCanBePrivate") class WindowCallbacks(private val application: Application, private val activityTracker: ActivityTracker) { private val log = logger() private val resumedActivityFocusChangeListeners = CopyOnWriteArrayList<FocusChangeListener>() private val keyEventListeners = CopyOnWriteArrayList<KeyEventListener>() private inner class Callbacks(private val window: Window) : WindowCallbackWrapper(window.callback) { override fun onWindowFocusChanged(hasFocus: Boolean) { super.onWindowFocusChanged(hasFocus) val resumedActivityWindow = activityTracker.resumedActivity?.window ?: return if (window === resumedActivityWindow) { // i.e. this callback is for the currently resumed activity resumedActivityHasFocus = hasFocus log.t { "Activity $window hasFocus: $hasFocus" } } else { log.t { "Non-activity $window hasFocus: $hasFocus" } } } override fun dispatchKeyEvent(event: KeyEvent): Boolean { var blockNormalHandlers = false keyEventListeners.forEach { blockNormalHandlers = blockNormalHandlers || it(event) } return blockNormalHandlers || super.dispatchKeyEvent(event) } } private val callbacks = application.registerActivityCallbacks( onCreated = { it, _ -> it.window.wrapCallbackIfNecessary(true) if (it is FragmentActivity) { it.supportFragmentManager.registerFragmentLifecycleCallbacks(object : FragmentManager.FragmentLifecycleCallbacks() { override fun onFragmentActivityCreated(fm: FragmentManager, f: Fragment, savedInstanceState: Bundle?) = f.wrap(true) override fun onFragmentResumed(fm: FragmentManager, f: Fragment) = f.wrap(false) @Suppress("DEPRECATION") private fun Fragment.wrap(initialWrap: Boolean) { when (this) { is DialogFragment -> dialog?.window?.wrapCallbackIfNecessary(initialWrap) is android.app.DialogFragment -> dialog?.window?.wrapCallbackIfNecessary(initialWrap) } } }, false) } }, onResumed = { it.window.wrapCallbackIfNecessary(false) } ) /** * AppCompatDelegate is created in AppCompatActivity.onCreate, grabbing an instance of the current window callback (which * unless changed already is the activity itself). * * However when applying the support action bar (Toolbar) via setSupportActionBar, the window callback is changed to * ToolbarActionBar.ToolbarCallbackWrapper wrapping the *original* (activity, not the current) callback (as that's what the delegate * grabbed during onCreate). * * Thus our callback will be clobbered as we set the callback *after* the activity is created (as the activity lifecycle callbacks * are run after Activity.onCreate and all the delegate stuff is setup) * * Ideally we'd set our callback before Activity.super.onCreate(), but that is not possible(?) without a custom activity base class * (which we can't ask people to use as that'd just be a PITA) * * Hence we must re-apply our callback, but to avoid a potential wrapping nightmare, we only do it if it's the ToolbarCallbackWrapper * * @param initialWrap Should be true for *first* call. Subsequent calls (`onResume` etc) should be false to avoid re-wapping if something else wrapped us. */ private fun Window.wrapCallbackIfNecessary(initialWrap: Boolean) { val currentCallback = callback if (currentCallback !is WindowCallbackWrapper) { if (initialWrap || currentCallback.toString().contains("ToolbarCallbackWrapper")) { Callbacks(this).also { callback = it } } else { log.w { "DevFun's Window callback wrapper was overridden by $currentCallback - some functionality may be lost." } } } } var resumedActivityHasFocus = true get() { val resumedActivity = activityTracker.resumedActivity ?: return false // if our callback has been clobbered always assume we have focus val callback = resumedActivity.window.callback if (callback !is WindowCallbackWrapper) { log.w { "Window callback was changed - assuming activity in focus (callback=$callback)" } return true } return field } private set(value) { field = value resumedActivityFocusChangeListeners.forEach { listener -> listener(value) } } internal fun dispose() { callbacks.unregister(application) } // Resumed activity focus change listeners fun addResumedActivityFocusChangeListener(listener: FocusChangeListener): FocusChangeListener { resumedActivityFocusChangeListeners += listener return listener } @JvmName("plusAssignResumedActivityFocusChangeListener") operator fun plusAssign(listener: FocusChangeListener) { addResumedActivityFocusChangeListener(listener) } fun removeResumedActivityFocusChangeListener(listener: FocusChangeListener): FocusChangeListener { resumedActivityFocusChangeListeners -= listener return listener } @JvmName("minusAssignResumedActivityFocusChangeListener") operator fun minusAssign(listener: FocusChangeListener) { removeResumedActivityFocusChangeListener(listener) } // Window key event listeners fun addKeyEventListener(listener: KeyEventListener): KeyEventListener { keyEventListeners += listener return listener } @JvmName("plusAssignKeyEventListener") operator fun plusAssign(listener: KeyEventListener) { addKeyEventListener(listener) } fun removeKeyEventListener(listener: KeyEventListener): KeyEventListener { keyEventListeners -= listener return listener } @JvmName("minusAssignKeyEventListener") operator fun minusAssign(listener: KeyEventListener) { removeKeyEventListener(listener) } } // TODO use me once https://youtrack.jetbrains.com/issue/KT-26725 is fixed (Kotlin 1.3.20) //internal open class ActivityWindowCallbackWrapper(private val callback: Window.Callback) : Window.Callback by callback private open class WindowCallbackWrapper(private val wrapped: Window.Callback) : Window.Callback { override fun dispatchKeyEvent(event: KeyEvent): Boolean = wrapped.dispatchKeyEvent(event) override fun dispatchKeyShortcutEvent(event: KeyEvent): Boolean = wrapped.dispatchKeyShortcutEvent(event) override fun dispatchTouchEvent(event: MotionEvent): Boolean = wrapped.dispatchTouchEvent(event) override fun dispatchTrackballEvent(event: MotionEvent): Boolean = wrapped.dispatchTrackballEvent(event) override fun dispatchGenericMotionEvent(event: MotionEvent): Boolean = wrapped.dispatchGenericMotionEvent(event) override fun dispatchPopulateAccessibilityEvent(event: AccessibilityEvent): Boolean = wrapped.dispatchPopulateAccessibilityEvent(event) override fun onCreatePanelView(featureId: Int): View? = wrapped.onCreatePanelView(featureId) override fun onCreatePanelMenu(featureId: Int, menu: Menu): Boolean = wrapped.onCreatePanelMenu(featureId, menu) override fun onPreparePanel(featureId: Int, view: View?, menu: Menu): Boolean = wrapped.onPreparePanel(featureId, view, menu) override fun onMenuOpened(featureId: Int, menu: Menu): Boolean = wrapped.onMenuOpened(featureId, menu) override fun onMenuItemSelected(featureId: Int, item: MenuItem): Boolean = wrapped.onMenuItemSelected(featureId, item) override fun onWindowAttributesChanged(attrs: WindowManager.LayoutParams) = wrapped.onWindowAttributesChanged(attrs) override fun onContentChanged() = wrapped.onContentChanged() override fun onWindowFocusChanged(hasFocus: Boolean) = wrapped.onWindowFocusChanged(hasFocus) override fun onAttachedToWindow() = wrapped.onAttachedToWindow() override fun onDetachedFromWindow() = wrapped.onDetachedFromWindow() override fun onPanelClosed(featureId: Int, menu: Menu) = wrapped.onPanelClosed(featureId, menu) override fun onSearchRequested(): Boolean = wrapped.onSearchRequested() override fun onWindowStartingActionMode(callback: ActionMode.Callback): ActionMode? = wrapped.onWindowStartingActionMode(callback) override fun onActionModeStarted(mode: ActionMode) = wrapped.onActionModeStarted(mode) override fun onActionModeFinished(mode: ActionMode) = wrapped.onActionModeFinished(mode) @RequiresApi(23) override fun onSearchRequested(searchEvent: SearchEvent): Boolean = wrapped.onSearchRequested(searchEvent) @RequiresApi(23) override fun onWindowStartingActionMode(callback: ActionMode.Callback, type: Int): ActionMode? = wrapped.onWindowStartingActionMode(callback, type) @RequiresApi(24) override fun onProvideKeyboardShortcuts(data: List<KeyboardShortcutGroup>, menu: Menu?, deviceId: Int) = wrapped.onProvideKeyboardShortcuts(data, menu, deviceId) @RequiresApi(26) override fun onPointerCaptureChanged(hasCapture: Boolean) = wrapped.onPointerCaptureChanged(hasCapture) }
apache-2.0
1e9c04dc068c05512e46459a3e5e1c80
46.74359
158
0.722431
5.381503
false
false
false
false
nemerosa/ontrack
ontrack-extension-casc/src/test/java/net/nemerosa/ontrack/extension/casc/context/core/admin/AccountGroupGlobalPermissionsAdminContextIT.kt
1
3056
package net.nemerosa.ontrack.extension.casc.context.core.admin import net.nemerosa.ontrack.common.getOrNull import net.nemerosa.ontrack.extension.casc.AbstractCascTestSupport import net.nemerosa.ontrack.model.security.AccountGroupInput import net.nemerosa.ontrack.model.security.PermissionInput import net.nemerosa.ontrack.model.security.PermissionTargetType import net.nemerosa.ontrack.model.security.Roles import net.nemerosa.ontrack.test.TestUtils.uid import org.junit.jupiter.api.Test import kotlin.test.assertEquals internal class AccountGroupGlobalPermissionsAdminContextIT : AbstractCascTestSupport() { @Test fun `Adding new group roles`() { val name = uid("g") asAdmin { val group = accountService.createGroup(AccountGroupInput(name, "Group $name")) casc(""" ontrack: admin: group-permissions: - group: $name role: AUTOMATION """.trimIndent()) val role = accountService.getGlobalRoleForAccountGroup(group).getOrNull() assertEquals(Roles.GLOBAL_AUTOMATION, role?.id) } } @Test fun `Updating existing group roles`() { val name = uid("g") asAdmin { val group = accountService.createGroup(AccountGroupInput(name, "Group $name")) accountService.saveGlobalPermission(PermissionTargetType.GROUP, group.id(), PermissionInput(Roles.GLOBAL_ADMINISTRATOR)) casc(""" ontrack: admin: group-permissions: - group: $name role: AUTOMATION """.trimIndent()) val role = accountService.getGlobalRoleForAccountGroup(group).getOrNull() assertEquals(Roles.GLOBAL_AUTOMATION, role?.id) } } @Test fun `Preserving existing group roles`() { val existing = uid("g") val name = uid("g") asAdmin { val existingGroup = accountService.createGroup(AccountGroupInput(existing, "Group $existing")) val group = accountService.createGroup(AccountGroupInput(name, "Group $name")) accountService.saveGlobalPermission(PermissionTargetType.GROUP, existingGroup.id(), PermissionInput(Roles.GLOBAL_ADMINISTRATOR)) casc(""" ontrack: admin: group-permissions: - group: $name role: AUTOMATION """.trimIndent()) // New role added assertEquals(Roles.GLOBAL_AUTOMATION, accountService.getGlobalRoleForAccountGroup(group).getOrNull()?.id) // Old mapping preserved assertEquals(Roles.GLOBAL_ADMINISTRATOR, accountService.getGlobalRoleForAccountGroup(existingGroup).getOrNull()?.id) } } }
mit
97c53b264da6b01b0d9931fc0058a058
38.192308
106
0.590641
5.399293
false
true
false
false
d9n/intellij-rust
src/test/kotlin/org/rustSlowTests/RsCompilerSourcesPerformance.kt
1
4372
package org.rustSlowTests import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.vfs.VfsUtilCore import com.intellij.openapi.vfs.VirtualFile import com.intellij.openapi.vfs.VirtualFileVisitor import com.intellij.psi.PsiElement import com.intellij.psi.PsiFileFactory import com.intellij.psi.impl.DebugUtil import com.intellij.psi.util.PsiTreeUtil import org.rust.lang.RsFileType import org.rust.lang.RsTestBase import java.util.* import kotlin.system.measureTimeMillis class RsCompilerSourcesPerformance : RsTestBase() { override fun getProjectDescriptor() = WithStdlibRustProjectDescriptor // Use this function to check that some code does not blow up // on some strange real-world PSI. // fun `test anything`() = forAllPsiElements { element -> // if (element is RsNamedElement) { // check(element.name != null) // } // } fun testParsingStandardLibrarySources() { val sources = rustSrcDir() parseRustFiles( sources, ignored = setOf("test", "doc", "etc", "grammar"), expectedNumberOfFiles = 500, checkForErrors = true ) } private data class FileStats( val path: String, val time: Long, val fileLength: Int ) private fun parseRustFiles(directory: VirtualFile, ignored: Collection<String>, expectedNumberOfFiles: Int, checkForErrors: Boolean) { val processed = ArrayList<FileStats>() val totalTime = measureTimeMillis { VfsUtilCore.visitChildrenRecursively(directory, object : VirtualFileVisitor<Void>() { override fun visitFileEx(file: VirtualFile): Result { if (file.isDirectory && file.name in ignored) return SKIP_CHILDREN // BACKCOMPAT: Rust 1.16.0 // There is a syntax error in this file // https://github.com/rust-lang/rust/pull/37278 if (file.path.endsWith("dataflow/graphviz.rs")) return CONTINUE if (file.fileType != RsFileType) return CONTINUE val fileContent = String(file.contentsToByteArray()) val time = measureTimeMillis { val psi = PsiFileFactory.getInstance(project).createFileFromText(file.name, file.fileType, fileContent) val psiString = DebugUtil.psiToString(psi, /* skipWhitespace = */ true) if (checkForErrors) { check("PsiErrorElement" !in psiString) { "Failed to parse ${file.path}\n\n$fileContent\n\n$psiString\n\n${file.path}" } } } val relPath = FileUtil.getRelativePath(directory.path, file.path, '/')!! processed += FileStats(relPath, time, fileContent.length) return CONTINUE } }) } check(processed.size > expectedNumberOfFiles) reportTeamCityMetric("$name totalTime", totalTime) println("\n$name " + "\nTotal: ${totalTime}ms" + "\nFileTree: ${processed.size}") val slowest = processed.sortedByDescending { it.time }.take(5) println("\nSlowest files") for ((path, time, fileLength) in slowest) { println("${"%3d".format(time)}ms ${"%3d".format(fileLength / 1024)}kb: $path") } println() } @Suppress("unused") private fun forAllPsiElements(f: (PsiElement) -> Unit) { VfsUtilCore.visitChildrenRecursively(rustSrcDir(), object : VirtualFileVisitor<Void>() { override fun visitFileEx(file: VirtualFile): Result { if (file.fileType != RsFileType) return CONTINUE val fileContent = String(file.contentsToByteArray()) val psi = PsiFileFactory.getInstance(project).createFileFromText(file.name, file.fileType, fileContent) PsiTreeUtil.processElements(psi) { f(it) true } return CONTINUE } }) } private fun rustSrcDir(): VirtualFile = projectDescriptor.stdlib!! }
mit
d0a9986384065b2febab381d18fdc6b3
37.690265
127
0.583715
5.161747
false
true
false
false
openHPI/android-app
app/src/main/java/de/xikolo/models/dao/DateDao.kt
1
5822
package de.xikolo.models.dao import androidx.lifecycle.LiveData import de.xikolo.extensions.asCopy import de.xikolo.extensions.asLiveData import de.xikolo.models.CourseDate import de.xikolo.models.dao.base.BaseDao import de.xikolo.utils.extensions.midnight import de.xikolo.utils.extensions.sevenDaysAhead import io.realm.Realm import io.realm.Sort import io.realm.kotlin.where import java.util.* class DateDao(realm: Realm) : BaseDao<CourseDate>(CourseDate::class, realm) { init { defaultSort = "date" to Sort.ASCENDING } fun allForCourse(courseId: String): LiveData<List<CourseDate>> = query() .equalTo("courseId", courseId) .sort("date", Sort.DESCENDING) .findAllAsync() .asLiveData() class Unmanaged { companion object { fun findNext(): CourseDate? = Realm.getDefaultInstance().use { realm -> realm.where<CourseDate>() .greaterThanOrEqualTo("date", Date()) .sort("date", Sort.ASCENDING) .findFirst() ?.asCopy() } fun countToday(): Long = Realm.getDefaultInstance().use { realm -> realm.where<CourseDate>() .between("date", Date(), Date().midnight) .sort("date", Sort.ASCENDING) .count() } fun countNextSevenDays(): Long = Realm.getDefaultInstance().use { realm -> realm.where<CourseDate>() .between("date", Date(), Date().sevenDaysAhead) .sort("date", Sort.ASCENDING) .count() } fun countFuture(): Long = Realm.getDefaultInstance().use { realm -> realm.where<CourseDate>() .greaterThan("date", Date()) .sort("date", Sort.ASCENDING) .count() } fun countTodayForCourse(courseId: String): Long = Realm.getDefaultInstance().use { realm -> realm.where<CourseDate>() .equalTo("courseId", courseId) .between("date", Date(), Date().midnight) .sort("date", Sort.ASCENDING) .count() } fun countNextSevenDaysForCourse(courseId: String): Long = Realm.getDefaultInstance().use { realm -> realm.where<CourseDate>() .equalTo("courseId", courseId) .between("date", Date(), Date().sevenDaysAhead) .sort("date", Sort.ASCENDING) .count() } fun countFutureForCourse(courseId: String): Long = Realm.getDefaultInstance().use { realm -> realm.where<CourseDate>() .equalTo("courseId", courseId) .greaterThan("date", Date()) .sort("date", Sort.ASCENDING) .count() } fun allToday(): List<CourseDate> = Realm.getDefaultInstance().use { realm -> realm.where<CourseDate>() .between("date", Date(), Date().midnight) .sort("date", Sort.ASCENDING) .findAll() .asCopy() } fun allNextSevenDaysWithoutToday(): List<CourseDate> = Realm.getDefaultInstance().use { realm -> realm.where<CourseDate>() .between("date", Date().midnight, Date().sevenDaysAhead) .sort("date", Sort.ASCENDING) .findAll() .asCopy() } fun allFutureWithoutNextSevenDays(): List<CourseDate> = Realm.getDefaultInstance().use { realm -> realm.where<CourseDate>() .greaterThan("date", Date().sevenDaysAhead) .sort("date", Sort.ASCENDING) .findAll() .asCopy() } fun allTodayForCourse(courseId: String): List<CourseDate> = Realm.getDefaultInstance().use { realm -> realm.where<CourseDate>() .equalTo("courseId", courseId) .between("date", Date(), Date().midnight) .sort("date", Sort.ASCENDING) .findAll() .asCopy() } fun allNextSevenDaysWithoutTodayForCourse(courseId: String): List<CourseDate> = Realm.getDefaultInstance().use { realm -> realm.where<CourseDate>() .equalTo("courseId", courseId) .between("date", Date().midnight, Date().sevenDaysAhead) .sort("date", Sort.ASCENDING) .findAll() .asCopy() } fun allFutureWithoutNextSevenDaysForCourse(courseId: String): List<CourseDate> = Realm.getDefaultInstance().use { realm -> realm.where<CourseDate>() .equalTo("courseId", courseId) .greaterThan("date", Date().sevenDaysAhead) .sort("date", Sort.ASCENDING) .findAll() .asCopy() } } } }
bsd-3-clause
8bcd24e253a4c45424453af8cdab60d7
37.813333
92
0.459808
5.833667
false
false
false
false
soywiz/korge
korge/src/commonMain/kotlin/com/soywiz/korge/view/Graphics.kt
1
7878
package com.soywiz.korge.view import com.soywiz.kds.* import com.soywiz.kds.iterators.* import com.soywiz.kmem.* import com.soywiz.korim.color.* import com.soywiz.korim.paint.* import com.soywiz.korim.vector.* import com.soywiz.korma.geom.* import com.soywiz.korma.geom.shape.* import com.soywiz.korma.geom.vector.* import kotlin.jvm.* inline fun Container.graphics(autoScaling: Boolean = false, callback: @ViewDslMarker Graphics.() -> Unit = {}): Graphics = Graphics(autoScaling).addTo(this, callback).apply { redrawIfRequired() } inline fun Container.sgraphics(callback: @ViewDslMarker Graphics.() -> Unit = {}): Graphics = Graphics(autoScaling = true).addTo(this, callback).apply { redrawIfRequired() } open class Graphics @JvmOverloads constructor( autoScaling: Boolean = false ) : BaseGraphics(autoScaling), VectorBuilder { internal val graphicsPathPool = Pool(reset = { it.clear() }) { GraphicsPath() } private var shapeVersion = 0 private val shapes = arrayListOf<Shape>() val allShapes: List<Shape> get() = shapes private val compoundShape = CompoundShape(shapes) private var fill: Paint? = null private var stroke: Paint? = null @PublishedApi internal var currentPath = graphicsPathPool.alloc() private var hitShapeVersion = -1 private var hitShape2dVersion = -1 private var hitShapeAnchorVersion = -1 private var tempVectorPaths = arrayListOf<VectorPath>() private val tempMatrix = Matrix() private var customHitShape2d: Shape2d? = null private var customHitShapes: List<VectorPath>? = null override var hitShape: VectorPath? set(value) = run { customHitShapes = value?.let { listOf(it) } } get() = hitShapes?.firstOrNull() @PublishedApi internal inline fun dirty(callback: () -> Unit): Graphics { this.dirty = true callback() return this } override var hitShapes: List<VectorPath>? set(value) { customHitShapes = value } get() { if (customHitShapes != null) return customHitShapes if (hitShapeVersion != shapeVersion) { hitShapeVersion = shapeVersion tempVectorPaths.clear() // @TODO: Try to combine polygons on KorGE 2.0 to have a single hitShape for (shape in shapes) { //when (shape) { //is StyledShape -> shape.path?.let { tempVectorPaths.add(it) } //else -> tempVectorPaths.add(shape.getPath()) //} } } //println("AAAAAAAAAAAAAAAA") return tempVectorPaths } override var hitShape2d: Shape2d set(value) { customHitShape2d = value } get() { if (customHitShape2d != null) return customHitShape2d!! if (hitShape2dVersion != shapeVersion) { hitShape2dVersion = shapeVersion customHitShape2d = hitShapes!!.toShape2d() } //println("AAAAAAAAAAAAAAAA") return customHitShape2d!! } /** * Ensure that after this function the [bitmap] property is up-to-date with all the drawings inside [block]. */ inline fun lock(block: Graphics.() -> Unit): Graphics { try { block() } finally { redrawIfRequired() } return this } fun clear() { shapes.forEach { (it as? StyledShape)?.path?.let { path -> graphicsPathPool.free(path) } } shapes.clear() currentPath.clear() } private var thickness: Double = 1.0 private var pixelHinting: Boolean = false private var scaleMode: LineScaleMode = LineScaleMode.NORMAL private var startCap: LineCap = LineCap.BUTT private var endCap: LineCap = LineCap.BUTT private var lineJoin: LineJoin = LineJoin.MITER private var miterLimit: Double = 4.0 init { hitTestUsingShapes = true } override val lastX: Double get() = currentPath.lastX override val lastY: Double get() = currentPath.lastY override val totalPoints: Int get() = currentPath.totalPoints override fun close() = currentPath.close() override fun cubicTo(cx1: Double, cy1: Double, cx2: Double, cy2: Double, ax: Double, ay: Double) { currentPath.cubicTo(cx1, cy1, cx2, cy2, ax, ay) } override fun lineTo(x: Double, y: Double) { currentPath.lineTo(x, y) } override fun moveTo(x: Double, y: Double) { currentPath.moveTo(x, y) } override fun quadTo(cx: Double, cy: Double, ax: Double, ay: Double) { currentPath.quadTo(cx, cy, ax, ay) } inline fun fill(color: RGBA, alpha: Double = 1.0, callback: @ViewDslMarker VectorBuilder.() -> Unit) = fill(toColorFill(color, alpha), callback) inline fun fill(paint: Paint, callback: @ViewDslMarker VectorBuilder.() -> Unit) { beginFill(paint) try { callback() } finally { endFill() } } inline fun stroke( paint: Paint, info: StrokeInfo, callback: @ViewDslMarker VectorBuilder.() -> Unit ) { beginStroke(paint, info) try { callback() } finally { endStroke() } } inline fun fillStroke( fill: Paint, stroke: Paint, strokeInfo: StrokeInfo, callback: @ViewDslMarker VectorBuilder.() -> Unit ) { beginFillStroke(fill, stroke, strokeInfo) try { callback() } finally { endFillStroke() } } fun beginFillStroke( fill: Paint, stroke: Paint, strokeInfo: StrokeInfo ) { this.fill = fill this.stroke = stroke this.setStrokeInfo(strokeInfo) } fun beginFill(paint: Paint) = dirty { fill = paint currentPath.clear() } private fun setStrokeInfo(info: StrokeInfo) { this.thickness = info.thickness this.pixelHinting = info.pixelHinting this.scaleMode = info.scaleMode this.startCap = info.startCap this.endCap = info.endCap this.lineJoin = info.lineJoin this.miterLimit = info.miterLimit } fun beginStroke(paint: Paint, info: StrokeInfo) = dirty { setStrokeInfo(info) stroke = paint currentPath.clear() } @PublishedApi internal fun toColorFill(color: RGBA, alpha: Double): ColorPaint = ColorPaint(RGBA(color.r, color.g, color.b, (color.a * alpha).toInt().clamp(0, 255))) fun beginFill(color: RGBA, alpha: Double) = beginFill(toColorFill(color, alpha)) fun shape(shape: Shape) { shapes += shape currentPath = graphicsPathPool.alloc() shapeVersion++ } inline fun shape(shape: VectorPath) = dirty { currentPath.write(shape) } inline fun shape(shape: VectorPath, matrix: Matrix) = dirty { currentPath.write(shape, matrix) } fun endFill() = dirty { shapes += FillShape(currentPath, null, fill ?: ColorPaint(Colors.RED), Matrix()) currentPath = graphicsPathPool.alloc() shapeVersion++ } fun endStroke() = dirty { shapes += PolylineShape(currentPath, null, stroke ?: ColorPaint(Colors.RED), Matrix(), thickness, pixelHinting, scaleMode, startCap, endCap, lineJoin, miterLimit) //shapes += PolylineShape(currentPath, null, fill ?: Context2d.Color(Colors.RED), Matrix(), thickness, pixelHinting, scaleMode, startCap, endCap, joints, miterLimit) currentPath = graphicsPathPool.alloc() shapeVersion++ } fun endFillStroke() = dirty { shapes += FillShape(currentPath, null, fill ?: ColorPaint(Colors.RED), Matrix()) shapes += PolylineShape(graphicsPathPool.alloc().also { it.write(currentPath) }, null, stroke ?: ColorPaint(Colors.RED), Matrix(), thickness, pixelHinting, scaleMode, startCap, endCap, lineJoin, miterLimit) currentPath = graphicsPathPool.alloc() shapeVersion++ } override fun drawShape(ctx: Context2d) { [email protected](ctx) } override fun getShapeBounds(bb: BoundsBuilder) { shapes.fastForEach { it.addBounds(bb) } } }
apache-2.0
2330a70c768e0f7e14b71eae7560a804
32.10084
208
0.652577
3.996956
false
false
false
false
samtstern/quickstart-android
mlkit/app/src/main/java/com/google/firebase/samples/apps/mlkit/kotlin/VisionProcessorBase.kt
1
4204
package com.google.firebase.samples.apps.mlkit.kotlin import android.graphics.Bitmap import androidx.annotation.GuardedBy import com.google.android.gms.tasks.Task import com.google.firebase.ml.vision.common.FirebaseVisionImage import com.google.firebase.ml.vision.common.FirebaseVisionImageMetadata import com.google.firebase.samples.apps.mlkit.common.BitmapUtils import com.google.firebase.samples.apps.mlkit.common.FrameMetadata import com.google.firebase.samples.apps.mlkit.common.GraphicOverlay import com.google.firebase.samples.apps.mlkit.common.VisionImageProcessor import java.nio.ByteBuffer /** * Abstract base class for ML Kit frame processors. Subclasses need to implement {@link * #onSuccess(T, FrameMetadata, GraphicOverlay)} to define what they want to with the detection * results and {@link #detectInImage(FirebaseVisionImage)} to specify the detector object. * * @param <T> The type of the detected feature. */ abstract class VisionProcessorBase<T> : VisionImageProcessor { // To keep the latest images and its metadata. @GuardedBy("this") private var latestImage: ByteBuffer? = null @GuardedBy("this") private var latestImageMetaData: FrameMetadata? = null // To keep the images and metadata in process. @GuardedBy("this") private var processingImage: ByteBuffer? = null @GuardedBy("this") private var processingMetaData: FrameMetadata? = null @Synchronized override fun process( data: ByteBuffer, frameMetadata: FrameMetadata, graphicOverlay: GraphicOverlay ) { latestImage = data latestImageMetaData = frameMetadata if (processingImage == null && processingMetaData == null) { processLatestImage(graphicOverlay) } } // Bitmap version override fun process(bitmap: Bitmap, graphicOverlay: GraphicOverlay) { detectInVisionImage( null, /* bitmap */ FirebaseVisionImage.fromBitmap(bitmap), null, graphicOverlay ) } @Synchronized private fun processLatestImage(graphicOverlay: GraphicOverlay) { processingImage = latestImage processingMetaData = latestImageMetaData latestImage = null latestImageMetaData = null if (processingImage != null && processingMetaData != null) { processImage(processingImage!!, processingMetaData!!, graphicOverlay) } } private fun processImage( data: ByteBuffer, frameMetadata: FrameMetadata, graphicOverlay: GraphicOverlay ) { val metadata = FirebaseVisionImageMetadata.Builder() .setFormat(FirebaseVisionImageMetadata.IMAGE_FORMAT_NV21) .setWidth(frameMetadata.width) .setHeight(frameMetadata.height) .setRotation(frameMetadata.rotation) .build() val bitmap = BitmapUtils.getBitmap(data, frameMetadata) detectInVisionImage( bitmap, FirebaseVisionImage.fromByteBuffer(data, metadata), frameMetadata, graphicOverlay ) } private fun detectInVisionImage( originalCameraImage: Bitmap?, image: FirebaseVisionImage, metadata: FrameMetadata?, graphicOverlay: GraphicOverlay ) { detectInImage(image) .addOnSuccessListener { results -> onSuccess( originalCameraImage, results, metadata!!, graphicOverlay ) processLatestImage(graphicOverlay) } .addOnFailureListener { e -> onFailure(e) } } override fun stop() {} protected abstract fun detectInImage(image: FirebaseVisionImage): Task<T> /** * Callback that executes with a successful detection result. * * @param originalCameraImage hold the original image from camera, used to draw the background * image. */ protected abstract fun onSuccess( originalCameraImage: Bitmap?, results: T, frameMetadata: FrameMetadata, graphicOverlay: GraphicOverlay ) protected abstract fun onFailure(e: Exception) }
apache-2.0
7f55e86580d598ee6c98bd11313fbe3d
32.365079
98
0.673168
5.424516
false
true
false
false
karollewandowski/aem-intellij-plugin
src/main/kotlin/co/nums/intellij/aem/errorreports/GitHubErrorBean.kt
1
2563
package co.nums.intellij.aem.errorreports import com.intellij.openapi.application.ApplicationNamesInfo import com.intellij.openapi.application.ex.ApplicationInfoEx import org.apache.commons.codec.digest.DigestUtils.md5Hex class GitHubErrorBean( private val errorMessage: String?, private val stackTrace: String?, private val description: String?, private val lastAction: String?, private val pluginVersion: String?, private val systemInfo: SystemInfo, private val appNamesInfo: ApplicationNamesInfo, private val appInfo: ApplicationInfoEx ) { /** * Includes last event message and exception hash (10 last characters * of MD5 hex representation of printed stack trace). */ val issueTitle = "${errorMessage()} [${errorHash()}]" private fun errorMessage() = if (!errorMessage.isNullOrBlank()) errorMessage else "Unspecified error" private fun errorHash() = if (stackTrace != null) md5Hex(stackTrace).takeLast(10) else "no-hash" val issueDetails = getCommentAsMarkdownText(includeException = true) val issueDetailsWithoutException = getCommentAsMarkdownText(includeException = false) private fun getCommentAsMarkdownText(includeException: Boolean) = description() + exception(includeException) + errorContext() private fun description() = """ |## Description |${if (!description.isNullOrBlank()) description else "*No description*"} """.trimMargin() private fun exception(includeException: Boolean) = if (!includeException) "" else """ | |## Exception |``` |${stackTrace ?: "invalid stack trace"} |``` """.trimMargin() private fun errorContext() = """ | |## Error context |``` |Last Action: $lastAction |Plugin Version: ${pluginVersion ?: "unknown"} |OS Name: ${systemInfo.osName} |Java Version: ${systemInfo.javaVersion} |Java VM Vendor: ${systemInfo.javaVmVendor} |Product Name: ${appNamesInfo.productName} |Full Product Name: ${appNamesInfo.fullProductName} |App Version Name: ${appInfo.versionName} |Is EAP: ${appInfo.isEAP} |App Build: ${appInfo.build.asString()} |App Version: ${appInfo.fullVersion} |``` """.trimMargin() }
gpl-3.0
b174dc2552469b6e9893c8dabc2b1745
36.144928
105
0.60554
5.230612
false
false
false
false
Zeyad-37/UseCases
usecases/src/main/java/com/zeyad/usecases/Extensions.kt
2
2305
package com.zeyad.usecases import android.content.Context import android.net.ConnectivityManager import android.net.NetworkInfo import android.os.Build import android.util.Log import org.json.JSONArray import org.json.JSONException import java.util.* fun withDisk(shouldPersist: Boolean): Boolean { return Config.withSQLite && shouldPersist } fun withCache(shouldCache: Boolean): Boolean { return Config.withCache && shouldCache } fun <T> convertToListOfId(jsonArray: JSONArray, idType: Class<T>): List<T> { var idList: MutableList<T> = ArrayList() if (jsonArray.length() > 0) { val length = jsonArray.length() idList = ArrayList(length) for (i in 0 until length) { try { idList.add(idType.cast(jsonArray.get(i))!!) } catch (e: JSONException) { Log.e("Utils", "convertToListOfId", e) } } } return idList } fun convertToStringListOfId(jsonArray: JSONArray?): List<Long> { var idList: MutableList<Long> = ArrayList() if (jsonArray != null && jsonArray.length() > 0) { idList = ArrayList(jsonArray.length()) val length = jsonArray.length() for (i in 0 until length) { try { idList.add(jsonArray.get(i).toString().toLong()) } catch (e: JSONException) { Log.e("Utils", "convertToListOfId", e) } } } return idList } fun isNetworkNotAvailable(context: Context): Boolean = !isNetworkAvailable(context) fun isNetworkAvailable(context: Context): Boolean { val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { val networks = connectivityManager.allNetworks for (network in networks) { if (connectivityManager.getNetworkInfo(network).state == NetworkInfo.State.CONNECTED) { return true } } } else { val info = connectivityManager.allNetworkInfo if (info != null) { for (anInfo in info) { if (anInfo.state == NetworkInfo.State.CONNECTED) { return true } } } } return false }
apache-2.0
33877b6ed21985af114b8239e5c9decd
29.746667
107
0.616486
4.424184
false
false
false
false
pennlabs/penn-mobile-android
PennMobile/src/main/java/com/pennapps/labs/pennmobile/components/floatingbottombar/parsers/ExpandableBottomBarParser.kt
1
3194
package com.pennapps.labs.pennmobile.components.floatingbottombar.parsers import android.content.Context import android.graphics.Color import android.util.AttributeSet import android.util.Xml import com.pennapps.labs.pennmobile.R import com.pennapps.labs.pennmobile.components.floatingbottombar.ExpandableBottomBarMenuItem import org.xmlpull.v1.XmlPullParser internal class ExpandableBottomBarParser(private val context: Context) { companion object { private const val NO_ID = 0 private const val NO_TEXT = "" private const val NO_COLOR = Color.TRANSPARENT private const val MENU_TAG = "menu" private const val MENU_ITEM_TAG = "item" } // We don't use namespaces private val namespace: String? = null fun inflate(menuId: Int): List<ExpandableBottomBarMenuItem> { val parser = context.resources.getLayout(menuId) parser.use { val attrs = Xml.asAttributeSet(parser) return readBottomBar(parser, attrs) } } private fun readBottomBar(parser: XmlPullParser, attrs: AttributeSet): List<ExpandableBottomBarMenuItem> { val items = mutableListOf<ExpandableBottomBarMenuItem>() var eventType = parser.eventType var tagName: String // This loop will skip to the menu start tag do { if (eventType == XmlPullParser.START_TAG) { tagName = parser.name if (tagName == MENU_TAG) { // Go to next tag eventType = parser.next() break } throw RuntimeException("Expecting menu, got $tagName") } eventType = parser.next() } while (eventType != XmlPullParser.END_DOCUMENT) var reachedEndOfMenu = false while (!reachedEndOfMenu) { tagName = parser.name if (eventType == XmlPullParser.END_TAG) { if (tagName == MENU_TAG) { reachedEndOfMenu = true } } if (eventType == XmlPullParser.START_TAG) { when (tagName) { MENU_ITEM_TAG -> items.add(readBottomBarItem(parser, attrs)) } } eventType = parser.next() } return items } private fun readBottomBarItem(parser: XmlPullParser, attrs: AttributeSet): ExpandableBottomBarMenuItem { val typedArray = context.obtainStyledAttributes(attrs, R.styleable.ExpandableBottomBarItem) val id = typedArray.getResourceId(R.styleable.ExpandableBottomBarItem_android_id, NO_ID) val iconId = typedArray.getResourceId(R.styleable.ExpandableBottomBarItem_exb_icon, NO_ID) val color = typedArray.getColor(R.styleable.ExpandableBottomBarItem_exb_color, NO_COLOR) val text = typedArray.getString(R.styleable.ExpandableBottomBarItem_android_title) ?: NO_TEXT typedArray.recycle() parser.require(XmlPullParser.START_TAG, namespace, MENU_ITEM_TAG) return ExpandableBottomBarMenuItem(id, iconId, text, color) } }
mit
972308019348d2d80bc7cf7d449fb0af
34.88764
101
0.623982
5.045814
false
false
false
false
stripe/stripe-android
payments-model/src/main/java/com/stripe/android/model/BankAccount.kt
1
4894
package com.stripe.android.model import androidx.annotation.RestrictTo import androidx.annotation.Size import com.stripe.android.core.model.StripeModel import kotlinx.parcelize.Parcelize /** * [The bank account object](https://stripe.com/docs/api/customer_bank_accounts/object) */ @Parcelize data class BankAccount @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) constructor( /** * Unique identifier for the object. * * [id](https://stripe.com/docs/api/customer_bank_accounts/object#customer_bank_account_object-id) */ override val id: String? = null, /** * The name of the person or business that owns the bank account. * * [account_holder_name](https://stripe.com/docs/api/customer_bank_accounts/object#customer_bank_account_object-account_holder_name) */ val accountHolderName: String? = null, /** * The type of entity that holds the account. This can be either individual or company. * * [account_holder_type](https://stripe.com/docs/api/customer_bank_accounts/object#customer_bank_account_object-account_holder_type) */ val accountHolderType: Type? = null, /** * Name of the bank associated with the routing number (e.g., WELLS FARGO). * * [bank_name](https://stripe.com/docs/api/customer_bank_accounts/object#customer_bank_account_object-bank_name) */ val bankName: String? = null, /** * Two-letter ISO code representing the country the bank account is located in. * * [country](https://stripe.com/docs/api/customer_bank_accounts/object#customer_bank_account_object-country) */ @param:Size(2) @field:Size(2) @get:Size(2) val countryCode: String? = null, /** * Three-letter ISO code for the currency paid out to the bank account. * * [currency](https://stripe.com/docs/api/customer_bank_accounts/object#customer_bank_account_object-currency) */ @param:Size(3) @field:Size(3) @get:Size(3) val currency: String? = null, /** * Uniquely identifies this particular bank account. You can use this attribute to check * whether two bank accounts are the same. * * [fingerprint](https://stripe.com/docs/api/customer_bank_accounts/object#customer_bank_account_object-fingerprint) */ val fingerprint: String? = null, /** * [last4](https://stripe.com/docs/api/customer_bank_accounts/object#customer_bank_account_object-last4) */ val last4: String? = null, /** * The routing transit number for the bank account. * * [routing_number](https://stripe.com/docs/api/customer_bank_accounts/object#customer_bank_account_object-routing_number) */ val routingNumber: String? = null, /** * For bank accounts, possible values are `new`, `validated`, `verified`, `verification_failed`, * or `errored`. A bank account that hasn’t had any activity or validation performed is new. * If Stripe can determine that the bank account exists, its status will be `validated`. Note * that there often isn’t enough information to know (e.g., for smaller credit unions), and * the validation is not always run. If customer bank account verification has succeeded, * the bank account status will be `verified`. If the verification failed for any reason, * such as microdeposit failure, the status will be `verification_failed`. If a transfer sent * to this bank account fails, we’ll set the status to `errored` and will not continue to send * transfers until the bank details are updated. * * For external accounts, possible values are `new` and `errored`. Validations aren’t run * against external accounts because they’re only used for payouts. This means the other * statuses don’t apply. If a transfer fails, the status is set to `errored` and transfers * are stopped until account details are updated. * * [status](https://stripe.com/docs/api/customer_bank_accounts/object#customer_bank_account_object-status) */ val status: Status? = null ) : StripeModel, StripePaymentSource { enum class Type(internal val code: String) { Company("company"), Individual("individual"); override fun toString(): String = code internal companion object { internal fun fromCode(code: String?) = values().firstOrNull { it.code == code } } } enum class Status(internal val code: String) { New("new"), Validated("validated"), Verified("verified"), VerificationFailed("verification_failed"), Errored("errored"); override fun toString(): String = code internal companion object { internal fun fromCode(code: String?): Status? { return values().firstOrNull { it.code == code } } } } }
mit
2394c88fa20b126e6b54c1b22872d2ed
36.553846
136
0.669603
4.068333
false
false
false
false
AndroidX/androidx
window/window-testing/src/main/java/androidx/window/testing/layout/DisplayFeatureTesting.kt
3
7934
/* * 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. */ @file:JvmName("DisplayFeatureTesting") package androidx.window.testing.layout import android.app.Activity import android.graphics.Rect import androidx.window.core.ExperimentalWindowApi import androidx.window.layout.FoldingFeature import androidx.window.layout.FoldingFeature.OcclusionType.Companion.FULL import androidx.window.layout.FoldingFeature.OcclusionType.Companion.NONE import androidx.window.layout.FoldingFeature.Orientation import androidx.window.layout.FoldingFeature.Orientation.Companion.HORIZONTAL import androidx.window.layout.FoldingFeature.Orientation.Companion.VERTICAL import androidx.window.layout.FoldingFeature.State import androidx.window.layout.FoldingFeature.State.Companion.HALF_OPENED import androidx.window.layout.WindowMetricsCalculator /** * A convenience method to get a test fold with default values provided. With the default values * it returns a [FoldingFeature.State.HALF_OPENED] feature that splits the screen along the * [FoldingFeature.Orientation.HORIZONTAL] axis. * * The bounds of the feature are calculated based on [orientation] and [size]. If the * feature is [VERTICAL] then the feature is centered horizontally. The top-left x-coordinate is * center - ([size] / 2) and the top-right x-coordinate is center + ([size] / 2). If the feature is * [HORIZONTAL] then the feature is centered vertically. The top-left y-coordinate is center - * ([size] / 2) and the bottom-left y-coordinate is center - ([size] / 2). The folding features * always cover the window in one dimension and that determines the other coordinates. * * @param activity that will house the [FoldingFeature]. * @param center the center of the fold complementary to the orientation. For a [HORIZONTAL] fold, * this is the y-axis and for a [VERTICAL] fold this is the x-axis. * @param size the smaller dimension of the fold. The larger dimension always covers the entire * window. * @param state [State] of the fold. The default value is [HALF_OPENED] * @param orientation [Orientation] of the fold. The default value is [HORIZONTAL] * @return [FoldingFeature] that is splitting if the width is not 0 and runs parallel to the * [Orientation] axis. */ @JvmOverloads @JvmName("createFoldingFeature") fun FoldingFeature( activity: Activity, center: Int = -1, size: Int = 0, state: State = HALF_OPENED, orientation: Orientation = HORIZONTAL ): FoldingFeature { val metricsCalculator = WindowMetricsCalculator.getOrCreate() val windowBounds = metricsCalculator.computeCurrentWindowMetrics(activity).bounds return foldingFeatureInternal( windowBounds = windowBounds, center = center, size = size, state = state, orientation = orientation ) } /** * A convenience method to get a test [FoldingFeature] with default values provided. With the * default values it returns a [FoldingFeature.State.HALF_OPENED] feature that splits the screen * along the [FoldingFeature.Orientation.HORIZONTAL] axis. * * The bounds of the feature are calculated based on [orientation] and [size]. If the * feature is [VERTICAL] then the feature is centered horizontally. The top-left x-coordinate is * center - ([size] / 2) and the top-right x-coordinate is center + ([size] / 2). If the feature is * [HORIZONTAL] then the feature is centered vertically. The top-left y-coordinate is center - * ([size] / 2) and the bottom-left y-coordinate is center - ([size] / 2). The folding features * always cover the window in one dimension and that determines the other coordinates. * * @param windowBounds that will contain the [FoldingFeature]. * @param center the center of the fold complementary to the orientation. For a [HORIZONTAL] fold, * this is the y-axis and for a [VERTICAL] fold this is the x-axis. * @param size the smaller dimension of the fold. The larger dimension always covers the entire * window. * @param state [State] of the fold. The default value is [HALF_OPENED] * @param orientation [Orientation] of the fold. The default value is [HORIZONTAL] * @return [FoldingFeature] that is splitting if the width is not 0 and runs parallel to the * [Orientation] axis. */ @JvmOverloads @JvmName("createFoldingFeature") @ExperimentalWindowApi fun FoldingFeature( windowBounds: Rect, center: Int = -1, size: Int = 0, state: State = HALF_OPENED, orientation: Orientation = HORIZONTAL ): FoldingFeature { return foldingFeatureInternal(windowBounds, center, size, state, orientation) } private fun foldingFeatureInternal( windowBounds: Rect, center: Int = -1, size: Int = 0, state: State = HALF_OPENED, orientation: Orientation = HORIZONTAL ): FoldingFeature { val shouldTreatAsHinge = size != 0 val isSeparating = shouldTreatAsHinge || state == HALF_OPENED val offset = size / 2 val actualCenter = if (center < 0) { when (orientation) { HORIZONTAL -> windowBounds.centerY() VERTICAL -> windowBounds.centerX() else -> windowBounds.centerX() } } else { center } val start = actualCenter - offset val end = actualCenter + offset val bounds = if (orientation == VERTICAL) { val windowHeight = windowBounds.height() Rect(start, 0, end, windowHeight) } else { val windowWidth = windowBounds.width() Rect(0, start, windowWidth, end) } val occlusionType = if (shouldTreatAsHinge) { FULL } else { NONE } return FakeFoldingFeature( bounds = bounds, isSeparating = isSeparating, occlusionType = occlusionType, orientation = orientation, state = state ) } private class FakeFoldingFeature( override val bounds: Rect, override val isSeparating: Boolean, override val occlusionType: FoldingFeature.OcclusionType, override val orientation: Orientation, override val state: State ) : FoldingFeature { init { require(!(bounds.width() == 0 && bounds.height() == 0)) { "Bounds must be non zero" } require(!(bounds.left != 0 && bounds.top != 0)) { "Bounding rectangle must start at the top or left window edge for folding features" } } override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as FakeFoldingFeature if (bounds != other.bounds) return false if (isSeparating != other.isSeparating) return false if (occlusionType != other.occlusionType) return false if (orientation != other.orientation) return false if (state != other.state) return false return true } override fun hashCode(): Int { var result = bounds.hashCode() result = 31 * result + isSeparating.hashCode() result = 31 * result + occlusionType.hashCode() result = 31 * result + orientation.hashCode() result = 31 * result + state.hashCode() return result } override fun toString(): String { return "${FakeFoldingFeature::class.java.simpleName} { bounds = $bounds, isSeparating = " + "$isSeparating, occlusionType = $occlusionType, orientation = $orientation, state = " + "$state" } }
apache-2.0
01d71bbda8ddaf132c7448cedf23045e
39.692308
99
0.704689
4.449804
false
false
false
false
Xenoage/Zong
utils-kotlin/src/com/xenoage/utils/math/Fraction.kt
1
5595
package com.xenoage.utils.math import com.xenoage.utils.annotations.Optimized import com.xenoage.utils.annotations.Reason import com.xenoage.utils.annotations.Reason.MemorySaving import com.xenoage.utils.math.Fraction.Companion.fr import kotlin.math.abs /** * This class represents a fraction of two integer values. * * It can for example be used to represent durations. * When possible, the fraction is cancelled automatically. */ data class Fraction( val numerator: Int, val denominator: Int ) : Comparable<Fraction> { /** True, if this fraction is 0 */ val is0: Boolean get() = numerator == 0 /** True, if this fraction is greater than 0 */ val isGreater0: Boolean get() = numerator > 0 /** * Adds the given Fraction to this one and returns the result. */ operator fun plus(fraction: Fraction): Fraction { if (fraction.numerator == 0) return this val numerator = this.numerator * fraction.denominator + this.denominator * fraction.numerator val denominator = this.denominator * fraction.denominator return fr(numerator, denominator) } /** * Subtracts the given fraction from this one and returns the result.. */ operator fun minus(fraction: Fraction): Fraction { if (fraction.numerator == 0) return this val numerator = this.numerator * fraction.denominator - this.denominator * fraction.numerator val denominator = this.denominator * fraction.denominator return fr(numerator, denominator) } /** * Inverts this fraction and returns the result. */ fun invert() = fr(-numerator, denominator) /** * Inverts this fraction and returns the result. */ operator fun unaryMinus() = invert() /** * Compares this fraction with the given one. * @return the value 0 if this fraction is * equal to the given one; -1 if this fraction is numerically less * than the given one; 1 if this fraction is numerically * greater than the given one. */ override fun compareTo(other: Fraction): Int { val compare = this - other return when { compare.numerator < 0 -> -1 compare.numerator == 0 -> 0 else -> 1 } } /** * Returns this fraction as a String in the * format "numerator/denominator", e.g. "3/4". */ override fun toString() = numerator.toString() + "/" + denominator /** * Returns this fraction as a float value (which may * have rounding errors). */ fun toFloat(): Float = 1f * numerator / denominator /** * Divides this [Fraction] by the given one. */ operator fun div(fraction: Fraction) = fr(this.numerator * fraction.denominator, this.denominator * fraction.numerator) /** * Multiplies this [Fraction] with the given one. */ operator fun times(fraction: Fraction) = fr(this.numerator * fraction.numerator, this.denominator * fraction.denominator) /** * Multiplies this [Fraction] with the given scalar value. */ operator fun times(scalar: Int) = fr(this.numerator * scalar, this.denominator) companion object { /** * Creates a new fraction with the given numerator and denominator. * For the most common fractions like 1, 1/2 or 1/4, shared instances are used. */ @Optimized(MemorySaving) fun fr(numerator: Int, denominator: Int): Fraction { //check values var num = numerator var den = denominator if (den == 0) throw IllegalArgumentException("Denominator may not be 0") if (num == 0) return _0 //if fraction is negative, always the numerator is negative val absNum = abs(num) val absDen = abs(den) if (num < 0 || den < 0) { num = if (numerator < 0 && denominator < 0) absNum else -1 * absNum den = absDen } //shorten fraction val gcd = gcd(absNum, absDen).clampMin(1) num /= gcd den /= gcd //reuse shared instances for common fractions when (den) { 1 -> when (num) { 1 -> return _1 } 2 -> when (num) { 1 -> return _1_2 } 3 -> when (num) { 1 -> return _1_3 } 4 -> when (num) { 1 -> return _1_4 3 -> return _3_4 } 8 -> when (num) { 1 -> return _1_8 3 -> return _3_8 } 16 -> when (num) { 1 -> return _1_16 3 -> return _3_16 } 32 -> when (num) { 1 -> return _1_32 3 -> return _3_32 } 64 -> when (num) { 1 -> return _1_64 3 -> return _3_64 } } return Fraction(num, den) } /** * Creates a new fraction with the given numerator. * The denominator is 1. */ fun fr(number: Int) = fr(number, 1) /** The comparator for fractions. */ val comparator = Comparator<Fraction> { obj, fraction -> obj.compareTo(fraction) } } } val _0 = Fraction(0, 1) val _1 = Fraction(1, 1) val _1_2 = Fraction(1, 2) val _1_3 = Fraction(1, 3) val _1_4 = Fraction(1, 4) val _3_4 = Fraction(3, 4) val _1_8 = Fraction(1, 8) val _3_8 = Fraction(3, 8) val _1_16 = Fraction(1, 16) val _3_16 = Fraction(3, 16) val _1_32 = Fraction(1, 32) val _3_32 = Fraction(3, 32) val _1_64 = Fraction(1, 64) val _3_64 = Fraction(3, 64) /** * Creates a new fraction from this string, which must have the format * "x", "x/y" or "z+x/y" for x and y and z being an integer. */ fun String.toFraction(): Fraction { val plus = split("\\+".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray() if (plus.size == 1) { val div = split("/".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray() if (div.size == 1) return fr(toInt()) else if (div.size == 2) return fr(div[0].toInt(), div[1].toInt()) } else if (plus.size == 2) { return fr(plus[0].toInt()) + plus[1].toFraction() } throw IllegalArgumentException("Invalid fraction: $this") }
agpl-3.0
2ae4a72b9868de6c8a0d157a139f7c3c
24.09417
95
0.643432
3.312611
false
false
false
false
Undin/intellij-rust
src/main/kotlin/org/rust/ide/annotator/fixes/AddTypeFix.kt
2
1506
/* * 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 com.intellij.codeInspection.LocalQuickFixAndIntentionActionOnPsiElement import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import org.rust.ide.presentation.renderInsertionSafe import org.rust.ide.utils.template.buildAndRunTemplate import org.rust.lang.core.psi.RsPsiFactory import org.rust.lang.core.types.ty.Ty import org.rust.openapiext.createSmartPointer /** * Adds type ascription after the given element. */ class AddTypeFix(anchor: PsiElement, ty: Ty) : LocalQuickFixAndIntentionActionOnPsiElement(anchor) { private val typeText: String = ty.renderInsertionSafe() override fun getFamilyName(): String = "Add type" override fun getText(): String = "Add type $typeText" override fun invoke( project: Project, file: PsiFile, editor: Editor?, startElement: PsiElement, endElement: PsiElement ) { val factory = RsPsiFactory(project) val parent = startElement.parent val colon = factory.createColon() val anchor = parent.addAfter(colon, startElement) val type = factory.createType(typeText) val insertedType = parent.addAfter(type, anchor) editor?.buildAndRunTemplate(parent, listOf(insertedType.createSmartPointer())) } }
mit
5cb7980cb20f30368de20ed7efe6b4d3
31.73913
100
0.737716
4.508982
false
false
false
false
MeilCli/Twitter4HK
library/src/main/kotlin/com/twitter/meil_mitu/twitter4hk/streaming/MessageType.kt
1
4067
package com.twitter.meil_mitu.twitter4hk.streaming import com.twitter.meil_mitu.twitter4hk.exception.Twitter4HKException import com.twitter.meil_mitu.twitter4hk.util.JsonUtils.getJSONObject import com.twitter.meil_mitu.twitter4hk.util.JsonUtils.getString import org.json.JSONObject object MessageType { val unknown = 0 val status = 1 val directMessage = 2 val block = 3 val unBlock = 4 val favorite = 5 val unFavorite = 6 val follow = 7 val unFollow = 8 val listCreated = 9 val listDestroyed = 10 val listUpdated = 11 val listMemberAdded = 12 val listMemberRemoved = 13 val listUserSubscribed = 14 val listUserUnSubscribed = 15 val userUpdate = 16 //https://blog.twitter.com/ja/2014/streaming-api-new-features val mute = 17 val unMute = 18 //https://twittercommunity.com/t/addition-of-new-social-event-to-streaming-api-retweet-has-been-retweeted/30911 val favoritedRetweet = 19 val retweetedRetweet = 20 //https://twittercommunity.com/t/quote-tweet-events-in-the-streaming-api/38457 val quotedTweet = 21 val friends = 22 val deleteStatus = 23 fun type(obj: JSONObject): Int { if (obj.isNull("sender") == false) { return MessageType.directMessage } else if (obj.isNull("text") == false) { return MessageType.status } else if (obj.isNull("direct_message") == false) { return MessageType.directMessage } else if (obj.isNull("friends") == false) { return MessageType.friends } else if (obj.isNull("delete") == false) { val delete = getJSONObject(obj, "delete") if (delete.isNull("status") == false) { return MessageType.deleteStatus } } else if (obj.isNull("event") == false) { try { val event = getString(obj, "event") if (event == "block") { return MessageType.block } else if (event == "unblock") { return MessageType.unBlock } else if (event == "favorite") { return MessageType.favorite } else if (event == "unfavorite") { return MessageType.unFavorite } else if (event == "follow") { return MessageType.follow } else if (event == "unfollow") { return MessageType.unFollow } else if (event == "list_created") { return MessageType.listCreated } else if (event == "list_destroyed") { return MessageType.listDestroyed } else if (event == "list_updated") { return MessageType.listUpdated } else if (event == "list_member_added") { return MessageType.listMemberAdded } else if (event == "list_member_removed") { return MessageType.listMemberRemoved } else if (event == "list_user_subscribed") { return MessageType.listUserSubscribed } else if (event == "list_user_unsubscribed") { return MessageType.listUserUnSubscribed } else if (event == "user_update") { return MessageType.userUpdate } else if (event == "mute") { return MessageType.mute } else if (event == "unmute") { return MessageType.unMute } else if (event == "favorited_retweet") { return MessageType.favoritedRetweet } else if (event == "retweeted_retweet") { return MessageType.retweetedRetweet } else if (event == "quoted_tweet") { return MessageType.quotedTweet } } catch (e: Twitter4HKException) { e.printStackTrace() } } return MessageType.unknown } }
mit
55a387a9868f35b14bd483c9341500f7
39.267327
115
0.552742
4.71263
false
false
false
false
Undin/intellij-rust
src/main/kotlin/org/rust/ide/inspections/RsTryMacroInspection.kt
3
2055
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.ide.inspections import com.intellij.codeInspection.LocalQuickFix import com.intellij.codeInspection.ProblemDescriptor import com.intellij.openapi.project.Project import org.rust.lang.core.macros.isExprOrStmtContext import org.rust.lang.core.psi.RsMacroCall import org.rust.lang.core.psi.RsPsiFactory import org.rust.lang.core.psi.RsTryExpr import org.rust.lang.core.psi.RsVisitor import org.rust.lang.core.psi.ext.isStdTryMacro import org.rust.lang.core.psi.ext.macroBody import org.rust.lang.core.psi.ext.replaceWithExpr /** * Change `try!` macro to `?` operator. */ class RsTryMacroInspection : RsLocalInspectionTool() { @Suppress("DialogTitleCapitalization") override fun getDisplayName(): String = "try! macro usage" override fun buildVisitor(holder: RsProblemsHolder, isOnTheFly: Boolean): RsVisitor = object : RsVisitor() { override fun visitMacroCall(o: RsMacroCall) { val isApplicable = o.isExprOrStmtContext && o.isStdTryMacro if (!isApplicable) return holder.registerProblem( o, "try! macro can be replaced with ? operator", object : LocalQuickFix { override fun getName() = "Change try! to ?" override fun getFamilyName() = name override fun applyFix(project: Project, descriptor: ProblemDescriptor) { val macro = descriptor.psiElement as? RsMacroCall ?: return val factory = RsPsiFactory(project) val body = macro.macroBody ?: return val expr = factory.tryCreateExpression(body) ?: return val tryExpr = factory.createExpression("()?") as RsTryExpr tryExpr.expr.replace(expr) macro.replaceWithExpr(tryExpr) } } ) } } }
mit
4a736d1ba5769404138cc1c67f3ebd8d
37.773585
112
0.633577
4.735023
false
false
false
false
androidx/androidx
room/room-paging-rxjava2/src/androidTest/kotlin/androidx/room/paging/rxjava2/LimitOffsetRxPagingSourceTest.kt
3
23319
/* * 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.room.paging.rxjava2 import android.database.Cursor import androidx.arch.core.executor.testing.CountingTaskExecutorRule import androidx.paging.LoadType import androidx.paging.PagingConfig import androidx.paging.PagingSource.LoadParams import androidx.paging.PagingSource.LoadResult import androidx.room.Dao import androidx.room.Database import androidx.room.Entity import androidx.room.Insert import androidx.room.PrimaryKey import androidx.room.Query import androidx.room.Room import androidx.room.RoomDatabase import androidx.room.RoomSQLiteQuery import androidx.room.paging.util.ThreadSafeInvalidationObserver import androidx.room.util.getColumnIndexOrThrow import androidx.sqlite.db.SimpleSQLiteQuery import androidx.test.core.app.ApplicationProvider import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.filters.MediumTest import androidx.testutils.TestExecutor import androidx.testutils.withTestTimeout import com.google.common.truth.Truth import com.google.common.truth.Truth.assertThat import io.reactivex.Single import java.util.concurrent.TimeUnit import java.util.concurrent.atomic.AtomicBoolean import kotlin.test.assertFailsWith import kotlin.test.assertFalse import kotlin.test.assertTrue import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.cancelAndJoin import kotlinx.coroutines.delay import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking import kotlinx.coroutines.rx2.await import kotlinx.coroutines.test.advanceUntilIdle import kotlinx.coroutines.test.runTest import org.junit.After import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith private const val tableName: String = "TestItem" @OptIn(ExperimentalCoroutinesApi::class) @RunWith(AndroidJUnit4::class) @MediumTest class LimitOffsetRxPagingSourceTest { @JvmField @Rule val countingTaskExecutorRule = CountingTaskExecutorRule() @After fun tearDown() { countingTaskExecutorRule.drainTasks(500, TimeUnit.MILLISECONDS) assertTrue(countingTaskExecutorRule.isIdle) } @Test fun initialLoad_empty() = setupAndRun { db -> val pagingSource = LimitOffsetRxPagingSourceImpl(db) val single = pagingSource.refresh() val result = single.await() as LoadResult.Page assertThat(result.data).isEmpty() } @Test fun initialLoad() = setupAndRun { db -> db.dao.addAllItems(ITEMS_LIST) val pagingSource = LimitOffsetRxPagingSourceImpl(db) val single = pagingSource.refresh() val result = single.await() as LoadResult.Page assertThat(result.data).containsExactlyElementsIn( ITEMS_LIST.subList(0, 15) ) } @Test fun simpleAppend() = setupAndRun { db -> db.dao.addAllItems(ITEMS_LIST) val pagingSource = LimitOffsetRxPagingSourceImpl(db) val single = pagingSource.append(key = 15) val result = single.await() as LoadResult.Page assertThat(result.data).containsExactlyElementsIn( ITEMS_LIST.subList(15, 20) ) } @Test fun simplePrepend() = setupAndRun { db -> db.dao.addAllItems(ITEMS_LIST) val pagingSource = LimitOffsetRxPagingSourceImpl(db) val single = pagingSource.prepend(key = 20) val result = single.await() as LoadResult.Page assertThat(result.data).containsExactlyElementsIn( ITEMS_LIST.subList(15, 20) ) } @Test fun initialLoad_invalidationTracker_isRegistered() = setupAndRun { db -> db.dao.addAllItems(ITEMS_LIST) val pagingSource = LimitOffsetRxPagingSourceImpl(db) val single = pagingSource.refresh() // run loadSingle to register InvalidationTracker single.await() assertTrue(pagingSource.observer.privateRegisteredState().get()) } @Test fun nonInitialLoad_invalidationTracker_isRegistered() = setupAndRun { db -> db.dao.addAllItems(ITEMS_LIST) val pagingSource = LimitOffsetRxPagingSourceImpl(db) val single = pagingSource.prepend(key = 20) // run loadSingle to register InvalidationTracker single.await() assertTrue(pagingSource.observer.privateRegisteredState().get()) } @Test fun refresh_singleImmediatelyReturn() = setupAndRun { db -> db.dao.addAllItems(ITEMS_LIST) val pagingSource = LimitOffsetRxPagingSourceImpl(db) val single = pagingSource.refresh() var observer = single.test() observer.assertNotComplete() // let room complete its tasks countingTaskExecutorRule.drainTasks(500, TimeUnit.MILLISECONDS) val result = observer.values().first() as LoadResult.Page assertThat(result.data).containsExactlyElementsIn( ITEMS_LIST.subList(0, 15) ) observer.assertComplete() observer.assertNoErrors() observer.dispose() } @Test fun append_singleImmediatelyReturn() = setupAndRun { db -> db.dao.addAllItems(ITEMS_LIST) val pagingSource = LimitOffsetRxPagingSourceImpl(db) val single = pagingSource.append(key = 10) var observer = single.test() observer.assertNotComplete() // let room complete its tasks countingTaskExecutorRule.drainTasks(500, TimeUnit.MILLISECONDS) val result = observer.values().first() as LoadResult.Page assertThat(result.data).containsExactlyElementsIn( ITEMS_LIST.subList(10, 15) ) observer.assertComplete() observer.assertNoErrors() observer.dispose() } @Test fun prepend_singleImmediatelyReturn() = setupAndRun { db -> db.dao.addAllItems(ITEMS_LIST) val pagingSource = LimitOffsetRxPagingSourceImpl(db) val single = pagingSource.prepend(key = 15) var observer = single.test() observer.assertNotComplete() // let room complete its tasks countingTaskExecutorRule.drainTasks(500, TimeUnit.MILLISECONDS) val result = observer.values().first() as LoadResult.Page assertThat(result.data).containsExactlyElementsIn( ITEMS_LIST.subList(10, 15) ) observer.assertComplete() observer.assertNoErrors() observer.dispose() } @Test fun dbUpdate_invalidatesPagingSource() = setupAndRun { db -> db.dao.addAllItems(ITEMS_LIST) val pagingSource = LimitOffsetRxPagingSourceImpl(db) val single = pagingSource.append(key = 50) // trigger load to register observer single.await() countingTaskExecutorRule.drainTasks(500, TimeUnit.MILLISECONDS) // make sure observer is registered and pagingSource is still valid at this point assertTrue(pagingSource.observer.privateRegisteredState().get()) assertFalse(pagingSource.invalid) // this should cause refreshVersionsSync to invalidate pagingSource db.dao.addItem(TestItem(113)) countingTaskExecutorRule.drainTasks(500, TimeUnit.MILLISECONDS) assertTrue(pagingSource.invalid) val single2 = pagingSource.append(key = 55) val result = single2.await() Truth.assertThat(result).isInstanceOf(LoadResult.Invalid::class.java) } @Test fun append_returnsInvalid() = setupAndRun { db -> db.dao.addAllItems(ITEMS_LIST) val pagingSource = LimitOffsetRxPagingSourceImpl(db) val single = pagingSource.append(key = 50) // this should cause load to return LoadResult.Invalid pagingSource.invalidate() assertTrue(pagingSource.invalid) // trigger load var result = single.await() // let room complete its tasks countingTaskExecutorRule.drainTasks(500, TimeUnit.MILLISECONDS) Truth.assertThat(result).isInstanceOf(LoadResult.Invalid::class.java) } @Test fun prepend_returnsInvalid() = setupAndRun { db -> db.dao.addAllItems(ITEMS_LIST) val pagingSource = LimitOffsetRxPagingSourceImpl(db) val single = pagingSource.prepend(key = 50) // this should cause load to return LoadResult.Invalid pagingSource.invalidate() assertTrue(pagingSource.invalid) // trigger load var observer = single.test() // let room complete its tasks countingTaskExecutorRule.drainTasks(500, TimeUnit.MILLISECONDS) val result = observer.values().first() Truth.assertThat(result).isInstanceOf(LoadResult.Invalid::class.java) observer.dispose() } @Test fun refresh_consecutively() = setupAndRun { db -> db.dao.addAllItems(ITEMS_LIST) val pagingSource = LimitOffsetRxPagingSourceImpl(db) val single = pagingSource.refresh() val result = single.await() as LoadResult.Page assertThat(result.data).containsExactlyElementsIn( ITEMS_LIST.subList(0, 15) ) val pagingSource2 = LimitOffsetRxPagingSourceImpl(db) val single2 = pagingSource2.refresh() val result2 = single2.await() as LoadResult.Page Truth.assertThat(result2.data).containsExactlyElementsIn( ITEMS_LIST.subList(0, 15) ) } @Test fun append_consecutively() = setupAndRun { db -> db.dao.addAllItems(ITEMS_LIST) val pagingSource = LimitOffsetRxPagingSourceImpl(db) val single = pagingSource.append(key = 15) val result = single.await() as LoadResult.Page assertThat(result.data).containsExactlyElementsIn( ITEMS_LIST.subList(15, 20) ) val single2 = pagingSource.append(key = 40) val result2 = single2.await() as LoadResult.Page Truth.assertThat(result2.data).containsExactlyElementsIn( ITEMS_LIST.subList(40, 45) ) val single3 = pagingSource.append(key = 45) // sequential append val result3 = single3.await() as LoadResult.Page Truth.assertThat(result3.data).containsExactlyElementsIn( ITEMS_LIST.subList(45, 50) ) } @Test fun prepend_consecutively() = setupAndRun { db -> db.dao.addAllItems(ITEMS_LIST) val pagingSource = LimitOffsetRxPagingSourceImpl(db) val single = pagingSource.prepend(key = 15) val result = single.await() as LoadResult.Page assertThat(result.data).containsExactlyElementsIn( ITEMS_LIST.subList(10, 15) ) val single2 = pagingSource.prepend(key = 40) val result2 = single2.await() as LoadResult.Page Truth.assertThat(result2.data).containsExactlyElementsIn( ITEMS_LIST.subList(35, 40) ) val single3 = pagingSource.prepend(key = 45) // sequential prepend val result3 = single3.await() as LoadResult.Page Truth.assertThat(result3.data).containsExactlyElementsIn( ITEMS_LIST.subList(40, 45) ) } @Test fun refreshAgain_afterDispose() = setupAndRun { db -> db.dao.addAllItems(ITEMS_LIST) val pagingSource = LimitOffsetRxPagingSourceImpl(db) var isDisposed = false val single = pagingSource.refresh() // dispose right after subscription .doOnSubscribe { disposable -> disposable.dispose() } .doOnSuccess { Truth.assertWithMessage("The single should not succeed").fail() } .doOnError { Truth.assertWithMessage("The single should not error out").fail() } .doOnDispose { isDisposed = true } assertFailsWith<AssertionError> { withTestTimeout(2) { single.await() } } assertTrue(isDisposed) assertFalse(pagingSource.invalid) // using same paging source val single2 = pagingSource.refresh() val result2 = single2.await() as LoadResult.Page Truth.assertThat(result2.data).containsExactlyElementsIn( ITEMS_LIST.subList(0, 15) ) } @Test fun appendAgain_afterDispose() = setupAndRun { db -> db.dao.addAllItems(ITEMS_LIST) val pagingSource = LimitOffsetRxPagingSourceImpl(db) var isDisposed = false val single = pagingSource.append(key = 15) // dispose right after subscription .doOnSubscribe { disposable -> disposable.dispose() } .doOnSuccess { Truth.assertWithMessage("The single should not succeed").fail() } .doOnError { Truth.assertWithMessage("The single should not error out").fail() } .doOnDispose { isDisposed = true } assertFailsWith<AssertionError> { withTestTimeout(2) { single.await() } } assertTrue(isDisposed) assertFalse(pagingSource.invalid) // try with same key same paging source val single2 = pagingSource.append(key = 15) val result2 = single2.await() as LoadResult.Page Truth.assertThat(result2.data).containsExactlyElementsIn( ITEMS_LIST.subList(15, 20) ) } @Test fun prependAgain_afterDispose() = setupAndRun { db -> db.dao.addAllItems(ITEMS_LIST) val pagingSource = LimitOffsetRxPagingSourceImpl(db) var isDisposed = false val single = pagingSource.prepend(key = 40) // dispose right after subscription .doOnSubscribe { disposable -> disposable.dispose() } .doOnSuccess { Truth.assertWithMessage("The single should not succeed").fail() } .doOnError { Truth.assertWithMessage("The single should not error out").fail() } .doOnDispose { isDisposed = true } assertFailsWith<AssertionError> { withTestTimeout(2) { single.await() } } assertTrue(isDisposed) assertFalse(pagingSource.invalid) // try with same key same paging source val single2 = pagingSource.prepend(key = 40) val result2 = single2.await() as LoadResult.Page Truth.assertThat(result2.data).containsExactlyElementsIn( ITEMS_LIST.subList(35, 40) ) } @Test fun assert_usesQueryExecutor() { val queryExecutor = TestExecutor() val testDb = Room.inMemoryDatabaseBuilder( ApplicationProvider.getApplicationContext(), LimitOffsetTestDb::class.java ).setQueryExecutor(queryExecutor) .build() testDb.dao.addAllItems(ITEMS_LIST) queryExecutor.executeAll() // add items first runTest { assertFalse(queryExecutor.executeAll()) // make sure its idle now val pagingSource = LimitOffsetRxPagingSourceImpl(testDb) val single = pagingSource.append(key = 15) var resultReceived = false // subscribe to single launch { val result = single.await() as LoadResult.Page assertThat(result.data).containsExactlyElementsIn( ITEMS_LIST.subList(15, 20) ) resultReceived = true } advanceUntilIdle() // execute Single's await() assertTrue(queryExecutor.executeAll()) advanceUntilIdle() assertTrue(resultReceived) assertFalse(queryExecutor.executeAll()) } testDb.close() } @Test fun cancelledCoroutine_disposesSingle() { val testDb = Room.inMemoryDatabaseBuilder( ApplicationProvider.getApplicationContext(), LimitOffsetTestDb::class.java ).build() testDb.dao.addAllItems(ITEMS_LIST) val pagingSource = LimitOffsetRxPagingSourceImpl(testDb) runBlocking { var isDisposed = false val single = pagingSource.refresh() .doOnSubscribe { Thread.sleep(300) } // subscribe but delay the load .doOnSuccess { Truth.assertWithMessage("The single should not succeed").fail() } .doOnError { Truth.assertWithMessage("The single should not error out").fail() } .doOnDispose { isDisposed = true } val job = launch { single.await() } job.start() delay(100) // start single.await() to subscribe but don't let it complete job.cancelAndJoin() assertTrue(job.isCancelled) assertTrue(isDisposed) } // need to drain before closing testDb or else will throw SQLiteConnectionPool exception countingTaskExecutorRule.drainTasks(500, TimeUnit.MILLISECONDS) testDb.close() } @Test fun refresh_secondaryConstructor() = setupAndRun { db -> val pagingSource = object : LimitOffsetRxPagingSource<TestItem>( db = db, supportSQLiteQuery = SimpleSQLiteQuery("SELECT * FROM $tableName ORDER BY id ASC") ) { override fun convertRows(cursor: Cursor): List<TestItem> { return convertRowsHelper(cursor) } } db.dao.addAllItems(ITEMS_LIST) val single = pagingSource.refresh() val result = single.await() as LoadResult.Page assertThat(result.data).containsExactlyElementsIn( ITEMS_LIST.subList(0, 15) ) } @Test fun append_secondaryConstructor() = setupAndRun { db -> val pagingSource = object : LimitOffsetRxPagingSource<TestItem>( db = db, supportSQLiteQuery = SimpleSQLiteQuery("SELECT * FROM $tableName ORDER BY id ASC") ) { override fun convertRows(cursor: Cursor): List<TestItem> { return convertRowsHelper(cursor) } } db.dao.addAllItems(ITEMS_LIST) val single = pagingSource.append(key = 15) val result = single.await() as LoadResult.Page assertThat(result.data).containsExactlyElementsIn( ITEMS_LIST.subList(15, 20) ) } @Test fun prepend_secondaryConstructor() = setupAndRun { db -> val pagingSource = object : LimitOffsetRxPagingSource<TestItem>( db = db, supportSQLiteQuery = SimpleSQLiteQuery("SELECT * FROM $tableName ORDER BY id ASC") ) { override fun convertRows(cursor: Cursor): List<TestItem> { return convertRowsHelper(cursor) } } db.dao.addAllItems(ITEMS_LIST) val single = pagingSource.prepend(key = 15) val result = single.await() as LoadResult.Page assertThat(result.data).containsExactlyElementsIn( ITEMS_LIST.subList(10, 15) ) } @Test fun jumping_enabled() = setupAndRun { db -> val pagingSource = LimitOffsetRxPagingSourceImpl(db) assertTrue(pagingSource.jumpingSupported) } private fun setupAndRun( test: suspend (LimitOffsetTestDb) -> Unit ) { val db = Room.inMemoryDatabaseBuilder( ApplicationProvider.getApplicationContext(), LimitOffsetTestDb::class.java ).build() runTest { test(db) } db.close() } } private fun LimitOffsetRxPagingSource<TestItem>.refresh( key: Int? = null, ): Single<LoadResult<Int, TestItem>> { return loadSingle( createLoadParam( loadType = LoadType.REFRESH, key = key, ) ) } private fun LimitOffsetRxPagingSource<TestItem>.append( key: Int? = -1, ): Single<LoadResult<Int, TestItem>> { itemCount.set(ITEMS_LIST.size) // to bypass check for initial load return loadSingle( createLoadParam( loadType = LoadType.APPEND, key = key, ) ) } private fun LimitOffsetRxPagingSource<TestItem>.prepend( key: Int? = -1, ): Single<LoadResult<Int, TestItem>> { itemCount.set(ITEMS_LIST.size) // to bypass check for initial load return loadSingle( createLoadParam( loadType = LoadType.PREPEND, key = key, ) ) } private class LimitOffsetRxPagingSourceImpl( db: RoomDatabase, query: String = "SELECT * FROM $tableName ORDER BY id ASC", ) : LimitOffsetRxPagingSource<TestItem>( db = db, sourceQuery = RoomSQLiteQuery.acquire(query, 0), tables = arrayOf(tableName) ) { override fun convertRows(cursor: Cursor): List<TestItem> = convertRowsHelper(cursor) } private fun convertRowsHelper(cursor: Cursor): List<TestItem> { val cursorIndexOfId = getColumnIndexOrThrow(cursor, "id") val data = mutableListOf<TestItem>() while (cursor.moveToNext()) { val tmpId = cursor.getInt(cursorIndexOfId) data.add(TestItem(tmpId)) } return data } private val CONFIG = PagingConfig( pageSize = 5, enablePlaceholders = true, initialLoadSize = 15, ) private val ITEMS_LIST = createItemsForDb(0, 100) private fun createItemsForDb(startId: Int, count: Int): List<TestItem> { return List(count) { TestItem( id = it + startId, ) } } private fun createLoadParam( loadType: LoadType, key: Int? = null, initialLoadSize: Int = CONFIG.initialLoadSize, pageSize: Int = CONFIG.pageSize, placeholdersEnabled: Boolean = CONFIG.enablePlaceholders ): LoadParams<Int> { return when (loadType) { LoadType.REFRESH -> { LoadParams.Refresh( key = key, loadSize = initialLoadSize, placeholdersEnabled = placeholdersEnabled ) } LoadType.APPEND -> { LoadParams.Append( key = key ?: -1, loadSize = pageSize, placeholdersEnabled = placeholdersEnabled ) } LoadType.PREPEND -> { LoadParams.Prepend( key = key ?: -1, loadSize = pageSize, placeholdersEnabled = placeholdersEnabled ) } } } @Suppress("UNCHECKED_CAST") private fun ThreadSafeInvalidationObserver.privateRegisteredState(): AtomicBoolean { return ThreadSafeInvalidationObserver::class.java .getDeclaredField("registered") .let { it.isAccessible = true it.get(this) } as AtomicBoolean } @Database(entities = [TestItem::class], version = 1, exportSchema = false) abstract class LimitOffsetTestDb : RoomDatabase() { abstract val dao: TestItemDao } @Entity(tableName = "TestItem") data class TestItem( @PrimaryKey val id: Int, val value: String = "item $id" ) @Dao interface TestItemDao { @Insert fun addAllItems(testItems: List<TestItem>) @Insert fun addItem(testItem: TestItem) @Query("SELECT COUNT(*) from $tableName") fun itemCount(): Int }
apache-2.0
a1a73a065d4ccd19177a793e1a2d9530
32.552518
96
0.65363
5.02673
false
true
false
false
jvalduvieco/blok
apps/Api/src/test/kotlin/com/blok/Post/Functional/CommentStepDefinitions.kt
1
2893
package com.blok.Post.Functional import com.blok.common.DatabaseSetup import com.blok.model.Comment import com.blok.post.Infrastructure.PostgresPostRepositoryForTesting import com.natpryce.hamkrest.assertion.assertThat import com.natpryce.hamkrest.equalTo import cucumber.api.java.Before import cucumber.api.java.en.Then import cucumber.api.java.en.When import org.apache.http.HttpStatus import org.junit.Assert.assertTrue import java.util.* class CommentStepDefinitions { private val postRepository = PostgresPostRepositoryForTesting(DatabaseSetup()) @Before fun cleanDatabase() { postRepository.cleanDatabase() } @When("^I add a comment to post ([a-f0-9-]+) by author=\"([^\"]*)\" with content=\"([^\"]*)\"$") @Throws(Throwable::class) fun iAddACommentWithContent(postId: UUID, author: String, content: String) { val payload: String = """ { "author" : "$author", "content" : "$content" } """ val response: String = post("http://localhost:4567/posts/${postId}/comments", payload) assertTrue(parseObjectCreationResponse(response) is UUID) } @Then("^the post ([a-f0-9-]+) has (\\d+) comment$") fun thePostHasComments(postId: UUID, numberOfComments: Int) { val comments: List<Comment> = get("http://localhost:4567/posts/${postId}/comments") assertThat(numberOfComments, equalTo(comments.count())) } @Then("^the post ([a-f0-9-]+) has a comment with content \"([^\"]*)\"$") fun aCommentWithContentExists(postId: UUID, content: String) { val comments: List<Comment> = get("http://localhost:4567/posts/${postId}/comments") val commentsThatMatch: List<Comment> = comments.filter { comment -> comment.content == content} assertThat(1, equalTo(commentsThatMatch.count())) } @When("^I add comments to a non existent post 404 is given$") fun iAddCommentsToANonExistingPost() { val payload: String = """ { "author" : "Peter", "content" : "and the wolf" } """ try { post("http://localhost:4567/posts/${UUID.randomUUID()}/comments", payload) } catch (e: FailedRequest) { assertThat(HttpStatus.SC_NOT_FOUND, equalTo(e.statusCode)) } } @When("^I delete one comment of post ([a-f0-9-]+)$") fun iDeleteOneCommentOf(postId: UUID) { val comments: List<Comment> = get("http://localhost:4567/posts/${postId}/comments") delete("http://localhost:4567/posts/${postId}/comments/${comments.first().id}") } @When("^I delete a non existent comment of post ([a-f0-9-]+) 404 is given$") fun iDeleteANonExistentComment(postId: UUID) { try { delete("http://localhost:4567/posts/${postId}/comments/" + UUID.randomUUID()) } catch (e: FailedRequest) { assertThat(HttpStatus.SC_NOT_FOUND, equalTo(e.statusCode)) } } }
mit
c6c93c3683e11e97758c771966510e0f
40.342857
103
0.654338
3.952186
false
false
false
false
minecraft-dev/MinecraftDev
src/main/kotlin/util/utils.kt
1
9922
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2022 minecraft-dev * * MIT License */ package com.demonwav.mcdev.util import com.google.gson.Gson import com.google.gson.reflect.TypeToken import com.intellij.lang.java.lexer.JavaLexer import com.intellij.openapi.application.AppUIExecutor import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.ModalityState import com.intellij.openapi.application.runReadAction import com.intellij.openapi.command.WriteCommandAction import com.intellij.openapi.module.Module import com.intellij.openapi.module.ModuleManager import com.intellij.openapi.progress.ProcessCanceledException import com.intellij.openapi.project.DumbService import com.intellij.openapi.project.Project import com.intellij.openapi.project.ProjectManager import com.intellij.openapi.roots.libraries.LibraryKind import com.intellij.openapi.util.Computable import com.intellij.openapi.util.Condition import com.intellij.openapi.util.Ref import com.intellij.pom.java.LanguageLevel import com.intellij.psi.PsiDocumentManager import com.intellij.psi.PsiFile import java.util.Locale import kotlin.reflect.KClass import org.jetbrains.concurrency.Promise import org.jetbrains.concurrency.runAsync inline fun <T : Any?> runWriteTask(crossinline func: () -> T): T { return invokeAndWait { ApplicationManager.getApplication().runWriteAction(Computable { func() }) } } fun runWriteTaskLater(func: () -> Unit) { invokeLater { ApplicationManager.getApplication().runWriteAction(func) } } inline fun <T : Any?> Project.runWriteTaskInSmartMode(crossinline func: () -> T): T { if (ApplicationManager.getApplication().isReadAccessAllowed) { return runWriteTask { func() } } val dumbService = DumbService.getInstance(this) val ref = Ref<T>() while (true) { dumbService.waitForSmartMode() val success = runWriteTask { if (isDisposed) { throw ProcessCanceledException() } if (dumbService.isDumb) { return@runWriteTask false } ref.set(func()) return@runWriteTask true } if (success) { break } } return ref.get() } fun <T : Any?> invokeAndWait(func: () -> T): T { val ref = Ref<T>() ApplicationManager.getApplication().invokeAndWait({ ref.set(func()) }, ModalityState.defaultModalityState()) return ref.get() } fun invokeLater(func: () -> Unit) { ApplicationManager.getApplication().invokeLater(func, ModalityState.defaultModalityState()) } fun invokeLater(expired: Condition<*>, func: () -> Unit) { ApplicationManager.getApplication().invokeLater(func, ModalityState.defaultModalityState(), expired) } fun invokeLaterAny(func: () -> Unit) { ApplicationManager.getApplication().invokeLater(func, ModalityState.any()) } fun <T> invokeEdt(block: () -> T): T { return AppUIExecutor.onUiThread().submit(block).get() } inline fun <T : Any?> PsiFile.runWriteAction(crossinline func: () -> T) = applyWriteAction { func() } inline fun <T : Any?> PsiFile.applyWriteAction(crossinline func: PsiFile.() -> T): T { val result = WriteCommandAction.writeCommandAction(this).withGlobalUndo().compute<T, Throwable> { func() } val documentManager = PsiDocumentManager.getInstance(project) val document = documentManager.getDocument(this) ?: return result documentManager.doPostponedOperationsAndUnblockDocument(document) return result } inline fun <T> runReadActionAsync(crossinline runnable: () -> T): Promise<T> { return runAsync { runReadAction(runnable) } } fun waitForAllSmart() { for (project in ProjectManager.getInstance().openProjects) { if (!project.isDisposed) { DumbService.getInstance(project).waitForSmartMode() } } } /** * Returns an untyped array for the specified [Collection]. */ fun Collection<*>.toArray(): Array<Any?> { @Suppress("PLATFORM_CLASS_MAPPED_TO_KOTLIN") return (this as java.util.Collection<*>).toArray() } inline fun <T : Collection<*>> T.ifEmpty(func: () -> Unit): T { if (isEmpty()) { func() } return this } inline fun <T : Collection<*>?> T.ifNullOrEmpty(func: () -> Unit): T { if (this == null || isEmpty()) { func() } return this } inline fun <T : Collection<*>> T.ifNotEmpty(func: (T) -> Unit): T { if (isNotEmpty()) { func(this) } return this } inline fun <T, R> Iterable<T>.mapFirstNotNull(transform: (T) -> R?): R? { forEach { element -> transform(element)?.let { return it } } return null } inline fun <T, R> Array<T>.mapFirstNotNull(transform: (T) -> R?): R? { forEach { element -> transform(element)?.let { return it } } return null } inline fun <T : Any> Iterable<T?>.forEachNotNull(func: (T) -> Unit) { forEach { it?.let(func) } } inline fun <T, reified R> Array<T>.mapToArray(transform: (T) -> R) = Array(size) { i -> transform(this[i]) } inline fun <T, reified R> List<T>.mapToArray(transform: (T) -> R) = Array(size) { i -> transform(this[i]) } inline fun <T, reified R> Collection<T>.mapToArray(transform: (T) -> R): Array<R> { val result = arrayOfNulls<R>(size) var i = 0 for (element in this) { result[i++] = transform(element) } return result.castNotNull() } fun <T> Array<T?>.castNotNull(): Array<T> { @Suppress("UNCHECKED_CAST") return this as Array<T> } // Same as Collections.rotate but for arrays fun <T> Array<T>.rotate(amount: Int) { val size = size if (size == 0) return var distance = amount % size if (distance < 0) distance += size if (distance == 0) return var cycleStart = 0 var nMoved = 0 while (nMoved != size) { var displaced = this[cycleStart] var i = cycleStart do { i += distance if (i >= size) i -= size val newDisplaced = this[i] this[i] = displaced displaced = newDisplaced nMoved++ } while (i != cycleStart) cycleStart++ } } inline fun <T> Iterable<T>.firstIndexOrNull(predicate: (T) -> Boolean): Int? { for ((index, element) in this.withIndex()) { if (predicate(element)) { return index } } return null } fun Module.findChildren(): Set<Module> { return runReadAction { val manager = ModuleManager.getInstance(project) val result = mutableSetOf<Module>() for (m in manager.modules) { if (m === this) { continue } val path = manager.getModuleGroupPath(m) ?: continue val namedModule = path.last()?.let { manager.findModuleByName(it) } ?: continue if (namedModule != this) { continue } result.add(m) } return@runReadAction result } } // Using the ugly TypeToken approach we can use any complex generic signature, including // nested generics inline fun <reified T : Any> Gson.fromJson(text: String): T = fromJson(text, object : TypeToken<T>() {}.type) fun <T : Any> Gson.fromJson(text: String, type: KClass<T>): T = fromJson(text, type.java) fun <K> Map<K, *>.containsAllKeys(vararg keys: K) = keys.all { this.containsKey(it) } /** * Splits a string into the longest prefix matching a predicate and the corresponding suffix *not* matching. * * Note: Name inspired by Scala. */ inline fun String.span(predicate: (Char) -> Boolean): Pair<String, String> { val prefix = takeWhile(predicate) return prefix to drop(prefix.length) } fun String.getSimilarity(text: String, bonus: Int = 0): Int { if (this == text) { return 1_000_000 + bonus // exact match } val lowerCaseThis = this.lowercase(Locale.ENGLISH) val lowerCaseText = text.lowercase(Locale.ENGLISH) if (lowerCaseThis == lowerCaseText) { return 100_000 + bonus // lowercase exact match } val distance = Math.min(lowerCaseThis.length, lowerCaseText.length) for (i in 0 until distance) { if (lowerCaseThis[i] != lowerCaseText[i]) { return i + bonus } } return distance + bonus } fun String.isJavaKeyword() = JavaLexer.isSoftKeyword(this, LanguageLevel.HIGHEST) fun String.toJavaIdentifier(allowDollars: Boolean = true): String { if (this.isEmpty()) { return "_" } if (this.isJavaKeyword()) { return "_$this" } if (!this[0].isJavaIdentifierStart() && this[0].isJavaIdentifierPart()) { return "_$this".toJavaIdentifier(allowDollars) } return this.asSequence() .map { if (it.isJavaIdentifierPart() && (allowDollars || it != '$')) { it } else { "_" } } .joinToString("") } fun String.toPackageName(): String { if (this.isEmpty()) { return "_" } val firstChar = this.first().let { if (it.isJavaIdentifierStart()) { "$it" } else { "" } } val packageName = firstChar + this.asSequence() .drop(1) .filter { it.isJavaIdentifierPart() || it == '.' } .joinToString("") return if (packageName.isEmpty()) { "_" } else { packageName.lowercase(Locale.ENGLISH) } } inline fun <reified T> Iterable<*>.firstOfType(): T? { return this.firstOrNull { it is T } as? T } fun libraryKind(id: String): LibraryKind = LibraryKind.findById(id) ?: LibraryKind.create(id) fun String.capitalize(): String = replaceFirstChar { if (it.isLowerCase()) { it.titlecase(Locale.ENGLISH) } else { it.toString() } } fun String.decapitalize(): String = replaceFirstChar { it.lowercase(Locale.ENGLISH) }
mit
042e0b1368ea08b784bc10de598a23b0
27.843023
112
0.634247
4.07977
false
false
false
false
andstatus/andstatus
app/src/main/kotlin/org/andstatus/app/timeline/TimelineViewPositionStorage.kt
1
5045
/* * Copyright (c) 2014-2018 yvolk (Yuri Volkov), http://yurivolkov.com * * 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.andstatus.app.timeline import android.widget.ListView import org.andstatus.app.util.MyLog /** * Determines where to save / retrieve position in the list * Information on two rows is stored for each "position" hence two keys. * Plus Query string is being stored for the search results. * 2014-11-15 We are storing [ViewItem.getDate] for the last item to retrieve, not its ID as before * @author [email protected] */ internal class TimelineViewPositionStorage<T : ViewItem<T>>(private val activity: LoadableListActivity<T>, private val params: TimelineParameters) { private val adapter: BaseTimelineAdapter<T> = activity.getListAdapter() private val listView: ListView? = activity.listView fun save() { val method = "save" + params.timeline.getId() if (isEmpty()) { MyLog.v(TAG) { "$method; skipped" } return } val itemCount = adapter.count val firstVisibleAdapterPosition = Integer.min( Integer.max(listView?.firstVisiblePosition ?: 0, 0), itemCount - 1) val pos = activity.getCurrentListPosition() val lastPosition = Integer.min((listView?.lastVisiblePosition ?: 0) + 10, itemCount - 1) val minDate = adapter.getItem(lastPosition).getDate() if (pos.itemId > 0) { saveListPosition(pos.itemId, minDate, pos.y) } else if (minDate > 0) { saveListPosition(0, minDate, 0) } if (pos.itemId <= 0 || MyLog.isVerboseEnabled()) { val msgLog = ("id:" + pos.itemId + ", y:" + pos.y + " at pos=" + firstVisibleAdapterPosition + (if (pos.position != firstVisibleAdapterPosition) " found pos=" + pos.position else "") + (if (!pos.description.isNullOrEmpty()) ", description=" + pos.description else "") + ", minDate=" + MyLog.formatDateTime(minDate) + " at pos=" + lastPosition + " of " + itemCount + ", listViews=" + (listView?.count ?: "??") + "; " + params.timeline) if (pos.itemId <= 0) { MyLog.i(TAG, "$method; failed $msgLog") } else { MyLog.v(TAG) { "$method; succeeded $msgLog" } } } } private fun isEmpty(): Boolean { return listView == null || params.isEmpty() || adapter.count == 0 } private fun saveListPosition(firstVisibleItemId: Long, minDate: Long, y: Int) { params.timeline.setVisibleItemId(firstVisibleItemId) params.timeline.setVisibleOldestDate(minDate) params.timeline.setVisibleY(y) } fun clear() { params.timeline.setVisibleItemId(0) params.timeline.setVisibleOldestDate(0) params.timeline.setVisibleY(0) MyLog.v(TAG) { "Position forgot " + params.timeline } } /** * Restore (the first visible item) position saved for this timeline * see http://stackoverflow.com/questions/3014089/maintain-save-restore-scroll-position-when-returning-to-a-listview?rq=1 */ fun restore() { val method = "restore" + params.timeline.getId() if (isEmpty()) { MyLog.v(TAG) { "$method; skipped" } return } val pos = loadListPosition(params) val restored: Boolean = listView?.let { LoadableListPosition.restore(it, adapter, pos)} ?: false if (MyLog.isVerboseEnabled()) { pos.logV(method + "; stored " + (if (restored) "succeeded" else "failed") + " " + params.timeline) activity.getCurrentListPosition().logV(method + "; actual " + if (restored) "succeeded" else "failed") } if (!restored) clear() adapter.setPositionRestored(true) } companion object { private val TAG: String = TimelineViewPositionStorage::class.simpleName!! fun loadListPosition(params: TimelineParameters): LoadableListPosition<*> { val itemId = params.timeline.getVisibleItemId() return if (itemId > 0) LoadableListPosition.saved( itemId, params.timeline.getVisibleY(), params.timeline.getVisibleOldestDate(), "saved itemId:$itemId") else LoadableListPosition.EMPTY } } }
apache-2.0
6ffe6a83233741adee6aa88bbec3b80c
42.119658
125
0.610307
4.496435
false
false
false
false
smichel17/simpletask-android
app/src/nextcloud/java/nl/mpcjanssen/simpletask/remote/FileStore.kt
1
8208
package nl.mpcjanssen.simpletask.remote import android.content.Context import android.net.ConnectivityManager import android.net.Uri import android.util.Log import com.owncloud.android.lib.common.OwnCloudClient import com.owncloud.android.lib.common.OwnCloudClientFactory import com.owncloud.android.lib.common.OwnCloudCredentialsFactory import com.owncloud.android.lib.common.operations.RemoteOperationResult import com.owncloud.android.lib.resources.files.* import nl.mpcjanssen.simpletask.TodoApplication import nl.mpcjanssen.simpletask.util.Config import nl.mpcjanssen.simpletask.util.join import nl.mpcjanssen.simpletask.util.showToastLong import java.io.File import java.io.IOException import java.util.* import kotlin.reflect.KClass private val s1 = System.currentTimeMillis().toString() /** * FileStore implementation backed by Nextcloud */ object FileStore : IFileStore { internal val NEXTCLOUD_USER = "ncUser" internal val NEXTCLOUD_PASS = "ncPass" internal val NEXTCLOUD_URL = "ncURL" var username by Config.StringOrNullPreference(NEXTCLOUD_USER) var password by Config.StringOrNullPreference(NEXTCLOUD_PASS) var serverUrl by Config.StringOrNullPreference(NEXTCLOUD_URL) var mNextcloud : OwnCloudClient? = getClient() override val isAuthenticated: Boolean get() { return username != null && mNextcloud != null } override fun logout() { username = null password = null serverUrl = null } private val TAG = "FileStore" private var mOnline: Boolean = false private val mApp = TodoApplication.app private fun getClient () : OwnCloudClient? { serverUrl?.let { url -> val ctx = TodoApplication.app.applicationContext val client = OwnCloudClientFactory.createOwnCloudClient(Uri.parse(url), ctx, true, true) client.credentials = OwnCloudCredentialsFactory.newBasicCredentials( username, password ) return client } return null } fun resetClient() { mNextcloud = getClient() } override fun getRemoteVersion(filename: String): String { val op = ReadRemoteFileOperation(filename) val res = op.execute(mNextcloud) val file = res.data[0] as RemoteFile return file.etag } override val isOnline: Boolean get() { val cm = mApp.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager val netInfo = cm.activeNetworkInfo return netInfo != null && netInfo.isConnected } override fun loadTasksFromFile(path: String): RemoteContents { // If we load a file and changes are pending, we do not want to overwrite // our local changes, instead we try to upload local Log.i(TAG, "Loading file from Nextcloud: " + path) if (!isAuthenticated) { throw IOException("Not authenticated") } val readLines = ArrayList<String>() val cacheDir = mApp.applicationContext.cacheDir val op = DownloadRemoteFileOperation(path, cacheDir.canonicalPath) op.execute(mNextcloud) val infoOp = ReadRemoteFileOperation(path) val res = infoOp.execute(mNextcloud) if (res.httpCode == 404) { throw (IOException("File not found")) } val fileInfo = res.data[0] as RemoteFile val cachePath = File(cacheDir, path).canonicalPath readLines.addAll(File(cachePath).readLines()) val currentVersionId = fileInfo.etag return RemoteContents(currentVersionId, readLines) } override fun loginActivity(): KClass<*>? { return LoginScreen::class } @Synchronized @Throws(IOException::class) override fun saveTasksToFile(path: String, lines: List<String>, eol: String): String { val contents = join(lines, eol) + eol val timestamp = timeStamp() Log.i(TAG, "Saving to file " + path) val cacheDir = mApp.applicationContext.cacheDir val tmpFile = File(cacheDir, "tmp.txt") tmpFile.writeText(contents) // if we have previously seen a file from the server, we don't upload unless it's the // one we've seen before. If we've never seen a file, we just upload unconditionally val res = UploadRemoteFileOperation(tmpFile.absolutePath, path, "text/plain", timestamp).execute(mNextcloud) val conflict = 412 if (res.httpCode == conflict) { val file = File(path) val parent = file.parent val name = file.name val nameWithoutTxt = "\\.txt$".toRegex().replace(name, "") val newName = nameWithoutTxt + "_conflict_" + UUID.randomUUID() + ".txt" val newPath = parent + "/" + newName UploadRemoteFileOperation(tmpFile.absolutePath, newPath, "text/plain", timestamp).execute(mNextcloud) showToastLong(TodoApplication.app, "CONFLICT! Uploaded as " + newName + ". Review differences manually with a text editor.") } val infoOp = ReadRemoteFileOperation(path) val infoRes = infoOp.execute(mNextcloud) val fileInfo = infoRes.data[0] as RemoteFile return fileInfo.etag } @Throws(IOException::class) override fun appendTaskToFile(path: String, lines: List<String>, eol: String) { if (!isOnline) { throw IOException("Device is offline") } val cacheDir = mApp.applicationContext.cacheDir val op = DownloadRemoteFileOperation(path, cacheDir.canonicalPath) val result = op.execute(mNextcloud) val doneContents = if (result.isSuccess) { val cachePath = File(cacheDir, path).canonicalPath File(cachePath).readLines().toMutableList() } else { ArrayList<String>() } doneContents.addAll(lines) val contents = join(doneContents, eol) + eol val tmpFile = File(cacheDir, "tmp.txt") tmpFile.writeText(contents) val timestamp = timeStamp() val writeOp = UploadRemoteFileOperation(tmpFile.absolutePath, path, "text/plain", timestamp) writeOp.execute(mNextcloud) } override fun writeFile(file: File, contents: String) { if (!isAuthenticated) { Log.e(TAG, "Not authenticated, file ${file.canonicalPath} not written.") throw IOException("Not authenticated") } val cacheDir = mApp.applicationContext.cacheDir val tmpFile = File(cacheDir, "tmp.txt") tmpFile.writeText(contents) val op = UploadRemoteFileOperation(tmpFile.absolutePath, file.canonicalPath, "text/plain", timeStamp()) val result = op.execute(mNextcloud) Log.i(TAG, "Wrote file to ${file.path}, result ${result.isSuccess}") } private fun timeStamp() = (System.currentTimeMillis() / 1000).toString() @Throws(IOException::class) override fun readFile(file: String, fileRead: (String) -> Unit) { if (!isAuthenticated) { return } val cacheDir = mApp.applicationContext.cacheDir val op = DownloadRemoteFileOperation(file, cacheDir.canonicalPath) op.execute(mNextcloud) val cachePath = File(cacheDir, file).canonicalPath val contents = File(cachePath).readText() fileRead(contents) } override fun loadFileList(path: String, txtOnly: Boolean): List<FileEntry> { val result = ArrayList<FileEntry>() val op = ReadRemoteFolderOperation(File(path).canonicalPath) val res: RemoteOperationResult = op.execute(mNextcloud) // Loop over the resulting files // Drop the first one as it is the current folder res.data.drop(1).forEach { file -> if (file is RemoteFile) { val filename = File(file.remotePath).name result.add(FileEntry(filename, isFolder = (file.mimeType == "DIR"))) } } return result } override fun getDefaultPath(): String { return "/todo.txt" } }
gpl-3.0
609734f5722fbef50fdde8efa060eff5
34.076923
111
0.649123
4.822562
false
false
false
false
EventFahrplan/EventFahrplan
app/src/main/java/nerd/tuxmobil/fahrplan/congress/favorites/StarredListAdapter.kt
1
3385
package nerd.tuxmobil.fahrplan.congress.favorites import android.content.Context import android.widget.TextView import androidx.annotation.ColorInt import androidx.core.content.ContextCompat import androidx.core.view.isVisible import info.metadude.android.eventfahrplan.commons.temporal.DateFormatter import info.metadude.android.eventfahrplan.commons.temporal.Moment import nerd.tuxmobil.fahrplan.congress.R import nerd.tuxmobil.fahrplan.congress.base.SessionsAdapter import nerd.tuxmobil.fahrplan.congress.extensions.textOrHide import nerd.tuxmobil.fahrplan.congress.models.Session class StarredListAdapter internal constructor( context: Context, list: List<Session>, numDays: Int, useDeviceTimeZone: Boolean ) : SessionsAdapter( context, R.layout.session_list_item, list, numDays, useDeviceTimeZone ) { @ColorInt private val pastSessionTextColor = ContextCompat.getColor(context, R.color.favorites_past_session_text) override fun setItemContent(position: Int, viewHolder: ViewHolder) { resetItemStyles(viewHolder) val session = getSession(position) with(viewHolder) { if (session.tookPlace) { title.setPastSessionTextColor() subtitle.setPastSessionTextColor() speakers.setPastSessionTextColor() lang.setPastSessionTextColor() day.setPastSessionTextColor() time.setPastSessionTextColor() room.setPastSessionTextColor() duration.setPastSessionTextColor() withoutVideoRecording.setImageResource(R.drawable.ic_without_video_recording_took_place) } title.textOrHide = session.title subtitle.textOrHide = session.subtitle subtitle.contentDescription = Session.getSubtitleContentDescription(subtitle.context, session.subtitle) speakers.textOrHide = session.formattedSpeakers speakers.contentDescription = Session.getSpeakersContentDescription(speakers.context, session.speakers.size, session.formattedSpeakers) lang.textOrHide = session.lang lang.contentDescription = Session.getLanguageContentDescription(lang.context, session.lang) day.isVisible = false val timeText = DateFormatter.newInstance(useDeviceTimeZone).getFormattedTime(session.dateUTC, session.timeZoneOffset) time.textOrHide = timeText time.contentDescription = Session.getStartTimeContentDescription(time.context, timeText) room.textOrHide = session.room room.contentDescription = Session.getRoomNameContentDescription(room.context, session.room) val durationText = duration.context.getString(R.string.session_list_item_duration_text, session.duration) duration.textOrHide = durationText duration.contentDescription = Session.getDurationContentDescription(duration.context, session.duration) video.isVisible = false noVideo.isVisible = false withoutVideoRecording.isVisible = session.recordingOptOut } } private val Session.tookPlace get() = endsAtDateUtc < Moment.now().toMilliseconds() private fun TextView.setPastSessionTextColor() = setTextColor(pastSessionTextColor) }
apache-2.0
d0b39ae28193f8ea6caa45ffe744c3f9
39.783133
147
0.714032
5.398724
false
false
false
false
CruGlobal/android-gto-support
gto-support-okta/src/test/kotlin/org/ccci/gto/android/common/okta/authfoundation/credential/ChangeAwareTokenStorageFlowTest.kt
1
1693
package org.ccci.gto.android.common.okta.authfoundation.credential import app.cash.turbine.test import io.mockk.Called import io.mockk.confirmVerified import io.mockk.excludeRecords import io.mockk.mockk import io.mockk.spyk import io.mockk.verify import java.util.UUID import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.test.UnconfinedTestDispatcher import kotlinx.coroutines.test.runTest import org.junit.Test @OptIn(ExperimentalCoroutinesApi::class) class ChangeAwareTokenStorageFlowTest { private val storage: ChangeAwareTokenStorage = spyk(WrappedTokenStorage(mockk(relaxUnitFun = true))) { excludeRecords { notifyChanged(any()) } } @Test fun verifyChangeFlowBehavior() = runTest(UnconfinedTestDispatcher()) { val flow = storage.changeFlow() verify { storage wasNot Called } flow.test { // we should emit an initial item awaitItem() expectNoEvents() verify(exactly = 1) { storage.addObserver(any()) } confirmVerified(storage) // emit on notify without changing observer registration storage.notifyChanged(UUID.randomUUID().toString()) awaitItem() expectNoEvents() verify(exactly = 1) { storage.addObserver(any()) } verify(exactly = 0) { storage.removeObserver(any()) } confirmVerified(storage) // cancelling the flow should remove the subscriber cancel() verify(exactly = 1) { storage.addObserver(any()) } verify(exactly = 1) { storage.removeObserver(any()) } confirmVerified(storage) } } }
mit
e0530a94b8a9040d4a026a55ae2173c4
33.55102
106
0.67218
4.907246
false
true
false
false
VKCOM/vk-android-sdk
samples/app/src/main/java/com/vk/sdk/sample/requests/VKWallPostCommand.kt
1
6518
/******************************************************************************* * The MIT License (MIT) * * Copyright (c) 2019 vk.com * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. ******************************************************************************/ package com.vk.sdk.sample.requests import android.net.Uri import com.vk.api.sdk.VKApiJSONResponseParser import com.vk.api.sdk.VKApiManager import com.vk.api.sdk.VKHttpPostCall import com.vk.api.sdk.VKMethodCall import com.vk.api.sdk.exceptions.VKApiIllegalResponseException import com.vk.api.sdk.internal.ApiCommand import com.vk.sdk.sample.models.VKFileUploadInfo import com.vk.sdk.sample.models.VKSaveInfo import com.vk.sdk.sample.models.VKServerUploadInfo import org.json.JSONException import org.json.JSONObject import java.util.concurrent.TimeUnit class VKWallPostCommand(private val message: String? = null, private val photos: List<Uri> = listOf(), private val ownerId: Int = 0, private val friendsOnly: Boolean = false, private val fromGroup: Boolean = false): ApiCommand<Int>() { override fun onExecute(manager: VKApiManager): Int { val callBuilder = VKMethodCall.Builder() .method("wall.post") .args("friends_only", if (friendsOnly) 1 else 0) .args("from_group", if (fromGroup) 1 else 0) .version(manager.config.version) message?.let { callBuilder.args("message", it) } if (ownerId != 0) { callBuilder.args("owner_id", ownerId) } if (photos.isNotEmpty()) { val uploadInfo = getServerUploadInfo(manager) val attachments = photos.map { uploadPhoto(it, uploadInfo, manager) } callBuilder.args("attachments", attachments.joinToString(",")) } return manager.execute(callBuilder.build(), ResponseApiParser()) } private fun getServerUploadInfo(manager: VKApiManager): VKServerUploadInfo { val uploadInfoCall = VKMethodCall.Builder() .method("photos.getWallUploadServer") .version(manager.config.version) .build() return manager.execute(uploadInfoCall, ServerUploadInfoParser()) } private fun uploadPhoto(uri: Uri, serverUploadInfo: VKServerUploadInfo, manager: VKApiManager): String { val fileUploadCall = VKHttpPostCall.Builder() .url(serverUploadInfo.uploadUrl) .args("photo", uri, "image.jpg") .timeout(TimeUnit.MINUTES.toMillis(5)) .retryCount(RETRY_COUNT) .build() val fileUploadInfo = manager.execute(fileUploadCall, null, FileUploadInfoParser()) val saveCall = VKMethodCall.Builder() .method("photos.saveWallPhoto") .args("server", fileUploadInfo.server) .args("photo", fileUploadInfo.photo) .args("hash", fileUploadInfo.hash) .version(manager.config.version) .build() val saveInfo = manager.execute(saveCall, SaveInfoParser()) return saveInfo.getAttachment() } companion object { const val RETRY_COUNT = 3 } private class ResponseApiParser : VKApiJSONResponseParser<Int> { override fun parse(responseJson: JSONObject): Int { try { return responseJson.getJSONObject("response").getInt("post_id") } catch (ex: JSONException) { throw VKApiIllegalResponseException(ex) } } } private class ServerUploadInfoParser : VKApiJSONResponseParser<VKServerUploadInfo> { override fun parse(responseJson: JSONObject): VKServerUploadInfo{ try { val joResponse = responseJson.getJSONObject("response") return VKServerUploadInfo( uploadUrl = joResponse.getString("upload_url"), albumId = joResponse.getInt("album_id"), userId = joResponse.getInt("user_id")) } catch (ex: JSONException) { throw VKApiIllegalResponseException(ex) } } } private class FileUploadInfoParser: VKApiJSONResponseParser<VKFileUploadInfo> { override fun parse(responseJson: JSONObject): VKFileUploadInfo{ try { val joResponse = responseJson return VKFileUploadInfo( server = joResponse.getString("server"), photo = joResponse.getString("photo"), hash = joResponse.getString("hash") ) } catch (ex: JSONException) { throw VKApiIllegalResponseException(ex) } } } private class SaveInfoParser: VKApiJSONResponseParser<VKSaveInfo> { override fun parse(responseJson: JSONObject): VKSaveInfo { try { val joResponse = responseJson.getJSONArray("response").getJSONObject(0) return VKSaveInfo( id = joResponse.getInt("id"), albumId = joResponse.getInt("album_id"), ownerId = joResponse.getInt("owner_id") ) } catch (ex: JSONException) { throw VKApiIllegalResponseException(ex) } } } }
mit
9cd48cbf88dca5eb96b88383e1a489e3
40.522293
108
0.609083
5.025443
false
false
false
false
HabitRPG/habitica-android
Habitica/src/main/java/com/habitrpg/android/habitica/ui/views/tasks/form/HabitScoringButtonsView.kt
1
3749
package com.habitrpg.android.habitica.ui.views.tasks.form import android.content.Context import android.graphics.Typeface import android.util.AttributeSet import android.view.Gravity import android.view.accessibility.AccessibilityEvent import android.widget.LinearLayout import androidx.core.content.ContextCompat import com.habitrpg.android.habitica.R import com.habitrpg.android.habitica.databinding.TaskFormHabitScoringBinding import com.habitrpg.android.habitica.extensions.asDrawable import com.habitrpg.common.habitica.extensions.layoutInflater import com.habitrpg.android.habitica.ui.views.HabiticaIconsHelper class HabitScoringButtonsView @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0 ) : LinearLayout(context, attrs, defStyleAttr) { private val binding = TaskFormHabitScoringBinding.inflate(context.layoutInflater, this) var tintColor: Int = ContextCompat.getColor(context, R.color.brand_300) var textTintColor: Int? = null override fun setEnabled(isEnabled: Boolean) { super.setEnabled(isEnabled) binding.positiveView.isEnabled = isEnabled binding.negativeView.isEnabled = isEnabled } var isPositive = true set(value) { field = value binding.positiveImageView.setImageDrawable(HabiticaIconsHelper.imageOfHabitControlPlus(tintColor, value).asDrawable(resources)) if (value) { binding.positiveTextView.setTextColor(textTintColor ?: tintColor) binding.positiveView.contentDescription = toContentDescription(R.string.positive_habit_form, R.string.on) binding.positiveTextView.typeface = Typeface.create("sans-serif-medium", Typeface.NORMAL) } else { binding.positiveTextView.setTextColor(ContextCompat.getColor(context, R.color.text_secondary)) binding.positiveView.contentDescription = toContentDescription(R.string.positive_habit_form, R.string.off) binding.positiveTextView.typeface = Typeface.create("sans-serif", Typeface.NORMAL) } } var isNegative = true set(value) { field = value binding.negativeImageView.setImageDrawable(HabiticaIconsHelper.imageOfHabitControlMinus(tintColor, value).asDrawable(resources)) if (value) { binding.negativeTextView.setTextColor(textTintColor ?: tintColor) binding.negativeView.contentDescription = toContentDescription(R.string.negative_habit_form, R.string.on) binding.negativeTextView.typeface = Typeface.create("sans-serif-medium", Typeface.NORMAL) } else { binding.negativeTextView.setTextColor(ContextCompat.getColor(context, R.color.text_secondary)) binding.negativeView.contentDescription = toContentDescription(R.string.negative_habit_form, R.string.off) binding.negativeTextView.typeface = Typeface.create("sans-serif", Typeface.NORMAL) } } private fun toContentDescription(descriptionStringId: Int, statusStringId: Int): String { return context.getString(descriptionStringId) + ", " + context.getString(statusStringId) } init { gravity = Gravity.CENTER binding.positiveView.setOnClickListener { isPositive = !isPositive sendAccessibilityEvent(AccessibilityEvent.CONTENT_CHANGE_TYPE_CONTENT_DESCRIPTION) } binding.negativeView.setOnClickListener { isNegative = !isNegative sendAccessibilityEvent(AccessibilityEvent.CONTENT_CHANGE_TYPE_CONTENT_DESCRIPTION) } isPositive = true isNegative = true } }
gpl-3.0
9adc76d099e3ca71f0053f33d1273ed6
45.283951
140
0.715124
5.012032
false
false
false
false
StepicOrg/stepic-android
app/src/main/java/org/stepik/android/domain/course_list/interactor/CourseListVisitedInteractor.kt
1
1740
package org.stepik.android.domain.course_list.interactor import io.reactivex.Flowable import io.reactivex.Single import ru.nobird.android.core.model.PagedList import org.stepik.android.domain.course.analytic.CourseViewSource import org.stepik.android.domain.course.model.SourceTypeComposition import org.stepik.android.domain.course_list.model.CourseListItem import org.stepik.android.domain.visited_courses.model.VisitedCourse import org.stepik.android.domain.visited_courses.repository.VisitedCoursesRepository import javax.inject.Inject class CourseListVisitedInteractor @Inject constructor( private val visitedCoursesRepository: VisitedCoursesRepository, private val courseListInteractor: CourseListInteractor ) { fun getVisitedCourseListItems(): Flowable<PagedList<CourseListItem.Data>> = visitedCoursesRepository .observeVisitedCourses() .flatMapSingle { visitedCourses -> getCourseListItems(visitedCourses.map(VisitedCourse::course)) } fun getCourseListItems( courseId: List<Long>, courseViewSource: CourseViewSource, sourceTypeComposition: SourceTypeComposition = SourceTypeComposition.REMOTE ): Single<PagedList<CourseListItem.Data>> = courseListInteractor.getCourseListItems(courseId, courseViewSource = courseViewSource, sourceTypeComposition = sourceTypeComposition) private fun getCourseListItems(courseIds: List<Long>): Single<PagedList<CourseListItem.Data>> = courseListInteractor .getCourseListItems( courseIds = courseIds, courseViewSource = CourseViewSource.Visited, sourceTypeComposition = SourceTypeComposition.CACHE ) }
apache-2.0
df89cbc0d4cfa16487166ae743acafd1
42.525
141
0.762644
5.631068
false
false
false
false
NerdNumber9/TachiyomiEH
app/src/main/java/exh/ui/migration/MetadataFetchDialog.kt
1
7149
package exh.ui.migration import android.app.Activity import android.content.pm.ActivityInfo import android.os.Build import android.text.Html import com.afollestad.materialdialogs.MaterialDialog import eu.kanade.tachiyomi.R import eu.kanade.tachiyomi.data.database.DatabaseHelper import eu.kanade.tachiyomi.data.preference.PreferencesHelper import eu.kanade.tachiyomi.data.preference.getOrDefault import eu.kanade.tachiyomi.source.SourceManager import exh.EXH_SOURCE_ID import exh.isLewdSource import timber.log.Timber import uy.kohesive.injekt.injectLazy import kotlin.concurrent.thread class MetadataFetchDialog { val db: DatabaseHelper by injectLazy() val sourceManager: SourceManager by injectLazy() val preferenceHelper: PreferencesHelper by injectLazy() fun show(context: Activity) { //Too lazy to actually deal with orientation changes context.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_NOSENSOR var running = true val progressDialog = MaterialDialog.Builder(context) .title("Fetching library metadata") .content("Preparing library") .progress(false, 0, true) .negativeText("Stop") .onNegative { dialog, which -> running = false dialog.dismiss() notifyMigrationStopped(context) } .cancelable(false) .canceledOnTouchOutside(false) .show() thread { val libraryMangas = db.getLibraryMangas().executeAsBlocking() .filter { isLewdSource(it.source) } .distinctBy { it.id } context.runOnUiThread { progressDialog.maxProgress = libraryMangas.size } val mangaWithMissingMetadata = libraryMangas .filterIndexed { index, libraryManga -> if(index % 100 == 0) { context.runOnUiThread { progressDialog.setContent("[Stage 1/2] Scanning for missing metadata...") progressDialog.setProgress(index + 1) } } db.getSearchMetadataForManga(libraryManga.id!!).executeAsBlocking() == null } .toList() context.runOnUiThread { progressDialog.maxProgress = mangaWithMissingMetadata.size } //Actual metadata fetch code for((i, manga) in mangaWithMissingMetadata.withIndex()) { if(!running) break context.runOnUiThread { progressDialog.setContent("[Stage 2/2] Processing: ${manga.title}") progressDialog.setProgress(i + 1) } try { val source = sourceManager.get(manga.source) source?.let { manga.copyFrom(it.fetchMangaDetails(manga).toBlocking().first()) } } catch (t: Throwable) { Timber.e(t, "Could not migrate manga!") } } context.runOnUiThread { // Ensure activity still exists before we do anything to the activity if(Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1 || !context.isDestroyed) { progressDialog.dismiss() //Enable orientation changes again context.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_NOSENSOR if (running) displayMigrationComplete(context) } } } } fun askMigration(activity: Activity, explicit: Boolean) { var extra = "" db.getLibraryMangas().asRxSingle().subscribe { if(!explicit && it.none { isLewdSource(it.source) }) { // Do not open dialog on startup if no manga // Also do not check again preferenceHelper.migrateLibraryAsked().set(true) } else { //Not logged in but have ExHentai galleries if (!preferenceHelper.enableExhentai().getOrDefault()) { it.find { it.source == EXH_SOURCE_ID }?.let { extra = "<b><font color='red'>If you use ExHentai, please log in first before fetching your library metadata!</font></b><br><br>" } } activity.runOnUiThread { MaterialDialog.Builder(activity) .title("Fetch library metadata") .content(Html.fromHtml("You need to fetch your library's metadata before tag searching in the library will function.<br><br>" + "This process may take a long time depending on your library size and will also use up a significant amount of internet bandwidth but can be stopped and started whenever you wish.<br><br>" + extra + "This process can be done later if required.")) .positiveText("Migrate") .negativeText("Later") .onPositive { _, _ -> show(activity) } .onNegative { _, _ -> adviseMigrationLater(activity) } .onAny { _, _ -> preferenceHelper.migrateLibraryAsked().set(true) } .cancelable(false) .canceledOnTouchOutside(false) .show() } } } } fun adviseMigrationLater(activity: Activity) { MaterialDialog.Builder(activity) .title("Metadata fetch canceled") .content("Library metadata fetch has been canceled.\n\n" + "You can run this operation later by going to: Settings > Advanced > Migrate library metadata") .positiveText("Ok") .cancelable(true) .canceledOnTouchOutside(true) .show() } fun notifyMigrationStopped(activity: Activity) { MaterialDialog.Builder(activity) .title("Metadata fetch stopped") .content("Library metadata fetch has been stopped.\n\n" + "You can continue this operation later by going to: Settings > Advanced > Migrate library metadata") .positiveText("Ok") .cancelable(true) .canceledOnTouchOutside(true) .show() } fun displayMigrationComplete(activity: Activity) { MaterialDialog.Builder(activity) .title("Migration complete") .content("${activity.getString(R.string.app_name)} is now ready for use!") .positiveText("Ok") .cancelable(true) .canceledOnTouchOutside(true) .show() } }
apache-2.0
f0ec62c04ff6b1926e877eb746e64d9c
41.301775
226
0.543013
5.728365
false
false
false
false
mtransitapps/parser
src/main/java/org/mtransit/parser/gtfs/data/GCalendarDate.kt
1
3217
package org.mtransit.parser.gtfs.data import org.mtransit.parser.gtfs.GAgencyTools import java.lang.Integer.max import java.lang.Integer.min // https://developers.google.com/transit/gtfs/reference#calendar_dates_fields // https://gtfs.org/reference/static/#calendar_datestxt data class GCalendarDate( val serviceIdInt: Int, val date: Int, // YYYYMMDD val exceptionType: GCalendarDatesExceptionType ) { constructor( serviceId: String, date: Int, exceptionType: GCalendarDatesExceptionType ) : this( GIDs.getInt(serviceId), date, exceptionType ) @Deprecated(message = "Not memory efficient") @Suppress("unused") val serviceId = _serviceId private val _serviceId: String get() { return GIDs.getString(serviceIdInt) } @Suppress("unused") fun getCleanServiceId(agencyTools: GAgencyTools): String { return agencyTools.cleanServiceId(_serviceId) } val uID by lazy { getNewUID(date, serviceIdInt) } @Suppress("unused") fun isServiceIdInt(serviceIdInt: Int): Boolean { return this.serviceIdInt == serviceIdInt } fun isServiceIdInts(serviceIdInts: Collection<Int?>): Boolean { return serviceIdInts.contains(serviceIdInt) } fun isBefore(date: Int): Boolean { return this.date < date } fun isBetween(startDate: Int, endDate: Int): Boolean { return date in startDate..endDate } fun isDate(date: Int): Boolean { return this.date == date } fun isAfter(date: Int): Boolean { return this.date > date } @Suppress("unused") fun toStringPlus(): String { return toString() + "+(serviceIdInt:$_serviceId)" } companion object { const val FILENAME = "calendar_dates.txt" const val SERVICE_ID = "service_id" const val DATE = "date" const val EXCEPTION_DATE = "exception_type" @JvmStatic fun getNewUID( date: Int, serviceIdInt: Int, ) = "${date}0${serviceIdInt}".toLong() @JvmStatic fun isServiceEntirelyRemoved( gCalendar: GCalendar, gCalendarDates: List<GCalendarDate>?, ) = isServiceEntirelyRemoved(gCalendar, gCalendarDates, gCalendar.startDate, gCalendar.endDate) @JvmStatic fun isServiceEntirelyRemoved( gCalendar: GCalendar, gCalendarDates: List<GCalendarDate>?, startDate: Int, endDate: Int, ): Boolean { val startDateToCheck = max(startDate, gCalendar.startDate) val endDateToCheck = min(endDate, gCalendar.endDate) val gCalendarDateServiceId = gCalendarDates?.filter { it.isServiceIdInt(gCalendar.serviceIdInt) } ?: return false // NOT entirely removed (startDateToCheck..endDateToCheck).forEach { date -> if (gCalendarDateServiceId.none { it.isDate(date) && it.exceptionType == GCalendarDatesExceptionType.SERVICE_REMOVED }) { return false // NOT entirely removed } } return true // removed } } }
apache-2.0
ca70fd6aa61ee36031c7e07be427f7ba
28.522936
150
0.623251
4.622126
false
false
false
false
yyYank/Kebab
src/main/kotlin/report/ScreenshotReporter.kt
1
1883
package kebab.report import kebab.core.Browser import kebab.support.report.ReporterSupport import org.openqa.selenium.OutputType import org.openqa.selenium.TakesScreenshot import org.openqa.selenium.WebDriverException import org.webbitserver.helpers.Base64 import java.io.File import java.nio.file.Files /** * Created by yy_yank on 2016/10/05. */ class ScreenshotReporter : ReporterSupport() { override fun writeReport(reportState: ReportState) { // note - this is not covered by tests unless using a driver that can take screenshots val screenshotDriver = determineScreenshotDriver(reportState.browser) var decoded: ByteArray? = null if (screenshotDriver != null) { try { val rawBase64 = screenshotDriver.getScreenshotAs(OutputType.BASE64) decoded = Base64.decode(rawBase64 as String) // WebDriver has a bug where sometimes the screenshot has been encoded twice if (!PngUtils.isPng(decoded)) { decoded = Base64.decode(decoded.toString()) } } catch (e: WebDriverException) { // TODO decoded = ExceptionToPngConverter(e).convert("An exception has been thrown while getting the screenshot:") } } val file = saveScreenshotPngBytes(reportState.outputDir, reportState.label, decoded) notifyListeners(reportState, listOf(file)) } fun saveScreenshotPngBytes(outputDir: File, label: String, bytes: ByteArray?): File { val file = getFile(outputDir, label, "png") Files.write(file.toPath(), bytes) return file } fun determineScreenshotDriver(browser: Browser): TakesScreenshot? = if (browser.config.driver is TakesScreenshot) { browser.config.driver as TakesScreenshot } else { null } }
apache-2.0
95aad8f239fddbcd12d1d87c34713359
32.625
122
0.66649
4.649383
false
false
false
false
theScrabi/NewPipe
app/src/main/java/org/schabi/newpipe/local/subscription/dialog/FeedGroupReorderDialog.kt
1
4561
package org.schabi.newpipe.local.subscription.dialog import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.DialogFragment import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProvider import androidx.recyclerview.widget.ItemTouchHelper import androidx.recyclerview.widget.ItemTouchHelper.SimpleCallback import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.xwray.groupie.GroupAdapter import com.xwray.groupie.TouchCallback import com.xwray.groupie.kotlinandroidextensions.GroupieViewHolder import icepick.Icepick import icepick.State import kotlinx.android.synthetic.main.dialog_feed_group_reorder.confirm_button import kotlinx.android.synthetic.main.dialog_feed_group_reorder.feed_groups_list import org.schabi.newpipe.R import org.schabi.newpipe.database.feed.model.FeedGroupEntity import org.schabi.newpipe.local.subscription.dialog.FeedGroupReorderDialogViewModel.DialogEvent.ProcessingEvent import org.schabi.newpipe.local.subscription.dialog.FeedGroupReorderDialogViewModel.DialogEvent.SuccessEvent import org.schabi.newpipe.local.subscription.item.FeedGroupReorderItem import org.schabi.newpipe.util.ThemeHelper import java.util.Collections class FeedGroupReorderDialog : DialogFragment() { private lateinit var viewModel: FeedGroupReorderDialogViewModel @State @JvmField var groupOrderedIdList = ArrayList<Long>() private val groupAdapter = GroupAdapter<GroupieViewHolder>() private val itemTouchHelper = ItemTouchHelper(getItemTouchCallback()) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) Icepick.restoreInstanceState(this, savedInstanceState) setStyle(STYLE_NO_TITLE, ThemeHelper.getMinWidthDialogTheme(requireContext())) } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { return inflater.inflate(R.layout.dialog_feed_group_reorder, container) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) viewModel = ViewModelProvider(this).get(FeedGroupReorderDialogViewModel::class.java) viewModel.groupsLiveData.observe(viewLifecycleOwner, Observer(::handleGroups)) viewModel.dialogEventLiveData.observe( viewLifecycleOwner, Observer { when (it) { ProcessingEvent -> disableInput() SuccessEvent -> dismiss() } } ) feed_groups_list.layoutManager = LinearLayoutManager(requireContext()) feed_groups_list.adapter = groupAdapter itemTouchHelper.attachToRecyclerView(feed_groups_list) confirm_button.setOnClickListener { viewModel.updateOrder(groupOrderedIdList) } } override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) Icepick.saveInstanceState(this, outState) } private fun handleGroups(list: List<FeedGroupEntity>) { val groupList: List<FeedGroupEntity> if (groupOrderedIdList.isEmpty()) { groupList = list groupOrderedIdList.addAll(groupList.map { it.uid }) } else { groupList = list.sortedBy { groupOrderedIdList.indexOf(it.uid) } } groupAdapter.update(groupList.map { FeedGroupReorderItem(it, itemTouchHelper) }) } private fun disableInput() { confirm_button?.isEnabled = false isCancelable = false } private fun getItemTouchCallback(): SimpleCallback { return object : TouchCallback() { override fun onMove( recyclerView: RecyclerView, source: RecyclerView.ViewHolder, target: RecyclerView.ViewHolder ): Boolean { val sourceIndex = source.adapterPosition val targetIndex = target.adapterPosition groupAdapter.notifyItemMoved(sourceIndex, targetIndex) Collections.swap(groupOrderedIdList, sourceIndex, targetIndex) return true } override fun isLongPressDragEnabled(): Boolean = false override fun isItemViewSwipeEnabled(): Boolean = false override fun onSwiped(viewHolder: RecyclerView.ViewHolder, swipeDir: Int) {} } } }
gpl-3.0
b6c7501952c294842a0e2309d61fddb9
37.652542
116
0.720895
5.391253
false
false
false
false
mdaniel/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/WrapWithCollectionLiteralCallFix.kt
1
3366
// 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.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.base.psi.replaced import org.jetbrains.kotlin.idea.codeinsight.api.classic.quickfixes.KotlinQuickFixAction import org.jetbrains.kotlin.idea.intentions.branchedTransformations.isNullExpression import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.endOffset import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType import org.jetbrains.kotlin.types.KotlinType import org.jetbrains.kotlin.types.Variance import org.jetbrains.kotlin.types.typeUtil.isSubtypeOf class WrapWithCollectionLiteralCallFix private constructor( element: KtExpression, private val functionName: String, private val wrapInitialElement: Boolean ) : KotlinQuickFixAction<KtExpression>(element) { override fun invoke(project: Project, editor: Editor?, file: KtFile) { val expression = element ?: return val factory = KtPsiFactory(expression) val replaced = if (wrapInitialElement) expression.replaced(factory.createExpressionByPattern("$functionName($0)", expression)) else expression.replaced(factory.createExpression("$functionName()")) editor?.caretModel?.moveToOffset(replaced.endOffset) } override fun getFamilyName(): String = KotlinBundle.message("wrap.with.collection.literal.call") override fun getText() = if (wrapInitialElement) KotlinBundle.message("wrap.element.with.0.call", functionName) else KotlinBundle.message("replace.with.0.call", functionName) companion object { fun create(expectedType: KotlinType, expressionType: KotlinType, element: KtExpression): List<WrapWithCollectionLiteralCallFix> { if (element.getStrictParentOfType<KtAnnotationEntry>() != null) return emptyList() val collectionType = with(ConvertCollectionFix) { expectedType.getCollectionType(acceptNullableTypes = true) } ?: return emptyList() val expectedArgumentType = expectedType .arguments.singleOrNull() ?.takeIf { it.projectionKind != Variance.IN_VARIANCE } ?.type ?: return emptyList() val result = mutableListOf<WrapWithCollectionLiteralCallFix>() val isNullExpression = element.isNullExpression() if ((expressionType.isSubtypeOf(expectedArgumentType) || isNullExpression) && collectionType.literalFunctionName != null) { result += WrapWithCollectionLiteralCallFix(element, collectionType.literalFunctionName, wrapInitialElement = true) } // Replace "null" with emptyList() if (isNullExpression && collectionType.emptyCollectionFunction != null) { result += WrapWithCollectionLiteralCallFix(element, collectionType.emptyCollectionFunction, wrapInitialElement = false) } return result } } }
apache-2.0
f3bba3cada01fe6ffc96f62ab0a8c70c
43.289474
158
0.699941
5.437803
false
false
false
false
mdaniel/intellij-community
java/java-features-trainer/src/com/intellij/java/ift/lesson/run/JavaRunConfigurationLesson.kt
7
1903
// 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.java.ift.lesson.run import com.intellij.execution.ExecutionBundle import com.intellij.icons.AllIcons import com.intellij.java.ift.JavaLessonsBundle import com.intellij.openapi.actionSystem.CommonDataKeys import com.intellij.openapi.actionSystem.DataProvider import com.intellij.openapi.editor.ex.EditorGutterComponentEx import training.dsl.* import training.learn.lesson.general.run.CommonRunConfigurationLesson import java.awt.Rectangle class JavaRunConfigurationLesson : CommonRunConfigurationLesson("java.run.configuration") { override val sample: LessonSample = JavaRunLessonsUtils.demoSample override val demoConfigurationName: String = JavaRunLessonsUtils.demoClassName override fun LessonContext.runTask() { task { highlightRunGutters(0) } task("RunClass") { text(JavaLessonsBundle.message("java.run.configuration.lets.run", icon(AllIcons.Actions.Execute), action(it), strong(ExecutionBundle.message("default.runner.start.action.text").dropMnemonic()))) //Wait toolwindow checkToolWindowState("Run", true) test { actions(it) } } } override val sampleFilePath: String = "src/${JavaRunLessonsUtils.demoClassName}.java" } internal fun TaskContext.highlightRunGutters(startLineIndex: Int, highlightInside: Boolean = false, usePulsation: Boolean = false) { triggerAndBorderHighlight { this.highlightInside = highlightInside this.usePulsation = usePulsation }.componentPart l@{ ui: EditorGutterComponentEx -> if (CommonDataKeys.EDITOR.getData(ui as DataProvider) != editor) return@l null val y = editor.visualLineToY(startLineIndex) return@l Rectangle(25, y, ui.width - 40, editor.lineHeight * 2) } }
apache-2.0
51836aca967cdf24c377738a98a8077d
40.369565
140
0.758276
4.563549
false
true
false
false
ingokegel/intellij-community
platform/platform-impl/src/com/intellij/openapi/client/ClientSessionImpl.kt
1
7511
// 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.client import com.intellij.codeWithMe.ClientId import com.intellij.codeWithMe.ClientId.Companion.isLocal import com.intellij.configurationStore.StateStorageManager import com.intellij.ide.plugins.ContainerDescriptor import com.intellij.ide.plugins.IdeaPluginDescriptorImpl import com.intellij.ide.plugins.PluginManagerCore import com.intellij.openapi.application.Application import com.intellij.openapi.application.impl.ApplicationImpl import com.intellij.openapi.components.ComponentConfig import com.intellij.openapi.components.PersistentStateComponent import com.intellij.openapi.components.ServiceDescriptor import com.intellij.openapi.components.impl.stores.IComponentStore import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.extensions.PluginId import com.intellij.openapi.project.Project import com.intellij.openapi.project.impl.ProjectImpl import com.intellij.serviceContainer.ComponentManagerImpl import com.intellij.serviceContainer.PrecomputedExtensionModel import com.intellij.serviceContainer.executeRegisterTaskForOldContent import com.intellij.util.messages.MessageBus import kotlinx.coroutines.* import org.jetbrains.annotations.ApiStatus import java.nio.file.Path private val LOG = logger<ClientSessionImpl>() @ApiStatus.Experimental @ApiStatus.Internal abstract class ClientSessionImpl( final override val clientId: ClientId, protected val sharedComponentManager: ClientAwareComponentManager ) : ComponentManagerImpl(null, false), ClientSession { override val isLocal = clientId.isLocal override val isLightServiceSupported = false override val isMessageBusSupported = false init { registerServiceInstance(ClientSession::class.java, this, fakeCorePluginDescriptor) } fun registerServices() { registerComponents() } fun preloadServices(syncScope: CoroutineScope) { assert(containerState.get() == ContainerState.PRE_INIT) val exceptionHandler = CoroutineExceptionHandler { _, exception -> LOG.error(exception) } this.preloadServices(modules = PluginManagerCore.getPluginSet().getEnabledModules(), activityPrefix = "client ", syncScope = syncScope + exceptionHandler, onlyIfAwait = false ) assert(containerState.compareAndSet(ContainerState.PRE_INIT, ContainerState.COMPONENT_CREATED)) } override suspend fun preloadService(service: ServiceDescriptor): Job? { return ClientId.withClientId(clientId) { super.preloadService(service) } } override fun isServiceSuitable(descriptor: ServiceDescriptor): Boolean { return descriptor.client == ServiceDescriptor.ClientKind.ALL || isLocal && descriptor.client == ServiceDescriptor.ClientKind.LOCAL || !isLocal && descriptor.client == ServiceDescriptor.ClientKind.GUEST } /** * only per-client services are supported (no components, extensions, listeners) */ override fun registerComponents(modules: List<IdeaPluginDescriptorImpl>, app: Application?, precomputedExtensionModel: PrecomputedExtensionModel?, listenerCallbacks: MutableList<in Runnable>?) { for (rootModule in modules) { registerServices(getContainerDescriptor(rootModule).services, rootModule) executeRegisterTaskForOldContent(rootModule) { module -> registerServices(getContainerDescriptor(module).services, module) } } } override fun isComponentSuitable(componentConfig: ComponentConfig): Boolean { LOG.error("components aren't supported") return false } override fun <T : Any> doGetService(serviceClass: Class<T>, createIfNeeded: Boolean): T? { return doGetService(serviceClass, createIfNeeded, true) } fun <T : Any> doGetService(serviceClass: Class<T>, createIfNeeded: Boolean, fallbackToShared: Boolean): T? { val clientService = super.doGetService(serviceClass, createIfNeeded) if (clientService != null || !fallbackToShared) return clientService if (createIfNeeded && !isLocal) { val sessionsManager = sharedComponentManager.getService(ClientSessionsManager::class.java) val localSession = sessionsManager?.getSession(ClientId.localId) as? ClientSessionImpl if (localSession?.doGetService(serviceClass, createIfNeeded = true, fallbackToShared = false) != null) { LOG.error("$serviceClass is registered only for client=\"local\", " + "please provide a guest-specific implementation, or change to client=\"all\"") return null } } ClientId.withClientId(ClientId.localId) { return if (createIfNeeded) { sharedComponentManager.getService(serviceClass) } else { sharedComponentManager.getServiceIfCreated(serviceClass) } } } override fun getApplication(): Application? { return sharedComponentManager.getApplication() } override val componentStore = ClientSessionComponentStore() override fun toString(): String { return clientId.toString() } } class ClientSessionComponentStore : IComponentStore { override val storageManager: StateStorageManager get() = throw UnsupportedOperationException() override fun setPath(path: Path) { } override fun initComponent(component: Any, serviceDescriptor: ServiceDescriptor?, pluginId: PluginId?) { if (component is PersistentStateComponent<*>) { LOG.error("Persisting is not supported for per-client services. Loading ${component::class.java.name} with default values") } } override fun unloadComponent(component: Any) { } override fun initPersistencePlainComponent(component: Any, key: String) { } override fun reloadStates(componentNames: Set<String>, messageBus: MessageBus) { } override fun reloadState(componentClass: Class<out PersistentStateComponent<*>>) { } override fun isReloadPossible(componentNames: Set<String>): Boolean { return false } override suspend fun save(forceSavingAllSettings: Boolean) { } override fun saveComponent(component: PersistentStateComponent<*>) { } override fun removeComponent(name: String) { } override fun clearCaches() { } override fun release() { } } @ApiStatus.Internal open class ClientAppSessionImpl( clientId: ClientId, application: ApplicationImpl ) : ClientSessionImpl(clientId, application), ClientAppSession { override fun getContainerDescriptor(pluginDescriptor: IdeaPluginDescriptorImpl): ContainerDescriptor { return pluginDescriptor.appContainerDescriptor } init { registerServiceInstance(ClientAppSession::class.java, this, fakeCorePluginDescriptor) } } @ApiStatus.Internal open class ClientProjectSessionImpl( clientId: ClientId, final override val project: ProjectImpl, ) : ClientSessionImpl(clientId, project), ClientProjectSession { override fun getContainerDescriptor(pluginDescriptor: IdeaPluginDescriptorImpl): ContainerDescriptor { return pluginDescriptor.projectContainerDescriptor } init { registerServiceInstance(ClientProjectSession::class.java, this, fakeCorePluginDescriptor) registerServiceInstance(Project::class.java, project, fakeCorePluginDescriptor) } override val appSession: ClientAppSession get() = ClientSessionsManager.getAppSession(clientId)!! }
apache-2.0
0e5168afd04700384b24b620daf80278
34.937799
129
0.755159
5.285714
false
false
false
false
hsson/card-balance-app
app/src/main/java/se/creotec/chscardbalance2/model/Model.kt
1
3423
// Copyright (c) 2017 Alexander Håkansson // // This software is released under the MIT License. // https://opensource.org/licenses/MIT package se.creotec.chscardbalance2.model import se.creotec.chscardbalance2.BuildConfig import se.creotec.chscardbalance2.Constants import se.creotec.chscardbalance2.service.AbstractBackendService class Model : IModel { override val quickChargeURL: String = BuildConfig.BACKEND_URL + Constants.ENDPOINT_CHARGE override var notifications: NotificationData = NotificationData() private val cardDataChangedListeners: MutableSet<OnCardDataChangedListener> = HashSet() private val menuDataChangedListeners: MutableSet<OnMenuDataChangedListener> = HashSet() private val serviceFailedListeners: MutableSet<IModel.OnServiceFailedListener> = HashSet() private val userInfoChangedListeners: MutableSet<OnUserInfoChangedListener> = HashSet() override var cardData: CardData = CardData() set(value) { field = value notifyCardDataChangedListeners() } override var menuData: MenuData = MenuData() set(value) { field = value notifyMenuDataChangedListeners() } override var cardLastTimeUpdated: Long = -1 set(value) = if (value >= 0) field = value else field = -1 override var menuLastTimeUpdated: Long = -1 set(value) = if (value >= 0) field = value else field = -1 override var preferredMenuLanguage: String = Constants.PREFS_MENU_LANGUAGE_DEFAULT set(value) { if (isOKLang(value)) field = value } override var userInfo: String = "" set(value) { if (field != value) { field = value notifyUserInfoChangedListeners() } } override fun addOnUserInfoChangedListener(listener: OnUserInfoChangedListener) { userInfoChangedListeners.add(listener) } override fun removeOnUserInfoChangedListener(listener: OnUserInfoChangedListener) { userInfoChangedListeners.remove(listener) } override fun notifyUserInfoChangedListeners() { userInfoChangedListeners.forEach { it.onUserInfoChanged(this.userInfo) } } override fun addCardDataListener(listener: OnCardDataChangedListener) { cardDataChangedListeners.add(listener) } override fun notifyCardDataChangedListeners() { for (listener in cardDataChangedListeners) { listener.cardDataChanged(this.cardData) } } override fun addMenuDataListener(listener: OnMenuDataChangedListener) { menuDataChangedListeners.add(listener) } override fun notifyMenuDataChangedListeners() { for (listener in this.menuDataChangedListeners) { listener.menuDataChanged(this.menuData) } } override fun addServiceFailedListener(listener: IModel.OnServiceFailedListener) { serviceFailedListeners.add(listener) } override fun notifyServiceFailed(service: AbstractBackendService<*>, error: String) { for (listener in serviceFailedListeners) { listener.serviceFailed(service, error) } } private fun isOKLang(language: String): Boolean { when (language) { Constants.ENDPOINT_MENU_LANG_EN -> return true Constants.ENDPOINT_MENU_LANG_SV -> return true else -> return false } } }
mit
c5ddd8fa46a1b47d905d9af9887271d4
35.021053
94
0.689071
5.047198
false
false
false
false
micolous/metrodroid
src/main/java/au/id/micolous/metrodroid/activity/MetrodroidActivity.kt
1
2656
/* * MetrodroidActivity.kt * * Copyright 2018 Google * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package au.id.micolous.metrodroid.activity import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import au.id.micolous.farebot.R import au.id.micolous.metrodroid.util.Preferences import au.id.micolous.metrodroid.util.Utils import android.content.Context abstract class MetrodroidActivity : AppCompatActivity() { private var mAppliedTheme: Int = 0 private var mAppliedLang: String = "" protected open val themeVariant: Int? get() = null override fun attachBaseContext(base: Context) { val locale = Utils.effectiveLocale() mAppliedLang = locale super.attachBaseContext(Utils.languageContext(base, locale)) } override fun onCreate(savedInstanceState: Bundle?) { val variant = themeVariant val baseTheme = chooseTheme() val theme: Int mAppliedTheme = baseTheme if (variant != null) { val a = obtainStyledAttributes( baseTheme, intArrayOf(variant)) theme = a.getResourceId(0, baseTheme) a.recycle() } else theme = baseTheme setTheme(theme) if (mAppliedLang != "") Utils.resetActivityTitle(this) super.onCreate(savedInstanceState) } protected fun setDisplayHomeAsUpEnabled(b: Boolean) { supportActionBar?.setDisplayHomeAsUpEnabled(b) } protected fun setHomeButtonEnabled(b: Boolean) { supportActionBar?.setHomeButtonEnabled(b) } override fun onResume() { super.onResume() if (chooseTheme() != mAppliedTheme || Utils.effectiveLocale() != mAppliedLang) recreate() } companion object { fun chooseTheme(): Int = when (Preferences.themePreference) { "light" -> R.style.Metrodroid_Light "farebot" -> R.style.FareBot_Theme_Common else -> R.style.Metrodroid_Dark } } }
gpl-3.0
92110f8d8bf45330f8a3836f08658aa6
30.247059
86
0.666039
4.643357
false
false
false
false
TealCube/facecore
src/main/kotlin/io/pixeloutlaw/minecraft/spigot/garbage/ReflectionUtil.kt
1
4633
/* * The MIT License * Copyright © 2015 Pixel Outlaw * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package io.pixeloutlaw.minecraft.spigot.garbage import org.bukkit.Bukkit import java.lang.reflect.Constructor import java.lang.reflect.Field import java.lang.reflect.Method /** * Reflection utilities for NMS/CraftBukkit. */ object ReflectionUtil { /** * Version string for NMS and CraftBukkit classes. */ @JvmStatic val version: String by lazy { Bukkit.getServer().javaClass.`package`.name.let { it.substring(it.lastIndexOf('.') + 1) + "." } } // cache of loaded NMS classes private val loadedNmsClasses = mutableMapOf<String, Class<*>?>() // cache of loaded CraftBukkit classes private val loadedCbClasses = mutableMapOf<String, Class<*>?>() // cache of loaded methods private val loadedMethods = mutableMapOf<Class<*>, MutableMap<String, Method?>>() // cache of loaded fields private val loadedFields = mutableMapOf<Class<*>, MutableMap<String, Field?>>() /** * Attempts to get an NMS class from the cache if in the cache, tries to put it in the cache if it's not already * there. */ @JvmStatic @Synchronized fun getNmsClass(nmsClassName: String): Class<*>? = loadedNmsClasses.getOrPut(nmsClassName) { val clazzName = "net.minecraft.server.${version}$nmsClassName" try { Class.forName(clazzName) } catch (ex: ClassNotFoundException) { null } } /** * Attempts to get a CraftBukkit class from the cache if in the cache, tries to put it in the cache if it's not * already there. */ @JvmStatic @Synchronized fun getCbClass(nmsClassName: String): Class<*>? = loadedCbClasses.getOrPut(nmsClassName) { val clazzName = "org.bukkit.craftbukkit.${version}$nmsClassName" try { Class.forName(clazzName) } catch (ex: ClassNotFoundException) { null } } /** * Attempts to find the constructor on the class that has the same types of parameters. */ @Suppress("detekt.SpreadOperator") fun getConstructor(clazz: Class<*>, vararg params: Class<*>): Constructor<*>? = try { clazz.getConstructor(*params) } catch (ex: NoSuchMethodException) { null } /** * Attempts to find the method on the class that has the same types of parameters and same name. */ @Suppress("detekt.SpreadOperator") fun getMethod(clazz: Class<*>, methodName: String, vararg params: Class<*>): Method? { val methods = loadedMethods[clazz] ?: mutableMapOf() if (methods.containsKey(methodName)) { return methods[methodName] } val method = try { clazz.getMethod(methodName, *params) } catch (ex: NoSuchMethodException) { null } methods[methodName] = method loadedMethods[clazz] = methods return method } /** * Attempts to find the field on the class that has the same name. */ @Suppress("detekt.SpreadOperator") fun getField(clazz: Class<*>, fieldName: String): Field? { val fields = loadedFields[clazz] ?: mutableMapOf() if (fields.containsKey(fieldName)) { return fields[fieldName] } val method = try { clazz.getField(fieldName) } catch (ex: NoSuchFieldException) { null } fields[fieldName] = method loadedFields[clazz] = fields return method } }
isc
29ed74140f6ee68c5327a7a81fba982a
32.810219
116
0.653713
4.745902
false
false
false
false
iPoli/iPoli-android
app/src/main/java/io/ipoli/android/challenge/QuestPickerViewState.kt
1
9245
package io.ipoli.android.challenge import android.content.res.ColorStateList import android.support.annotation.ColorRes import android.support.v4.content.ContextCompat import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.mikepenz.iconics.IconicsDrawable import com.mikepenz.iconics.typeface.IIcon import com.mikepenz.ionicons_typeface_library.Ionicons import io.ipoli.android.R import io.ipoli.android.challenge.QuestPickerViewState.StateType.* import io.ipoli.android.common.AppState import io.ipoli.android.common.BaseViewStateReducer import io.ipoli.android.common.redux.Action import io.ipoli.android.common.redux.BaseViewState import io.ipoli.android.common.view.AndroidColor import io.ipoli.android.common.view.AndroidIcon import io.ipoli.android.common.view.listItemIcon import io.ipoli.android.common.view.visible import io.ipoli.android.quest.BaseQuest import io.ipoli.android.quest.Quest import io.ipoli.android.quest.RepeatingQuest import kotlinx.android.synthetic.main.item_quest_picker.view.* import org.threeten.bp.LocalDate /** * Created by Polina Zhelyazkova <[email protected]> * on 3/7/18. */ sealed class QuestPickerAction : Action { data class Load(val challengeId: String = "") : QuestPickerAction() { override fun toMap() = mapOf("challengeId" to challengeId) } data class Loaded(val quests: List<Quest>, val repeatingQuests: List<RepeatingQuest>) : QuestPickerAction() { override fun toMap() = mapOf( "quests" to quests.joinToString(",") { it.name }, "repeatingQuests" to repeatingQuests.joinToString(",") { it.name } ) } data class Filter(val query: String) : QuestPickerAction() data class Check(val id: String, val isSelected: Boolean) : QuestPickerAction() object Save : QuestPickerAction() object Next : QuestPickerAction() } object QuestPickerReducer : BaseViewStateReducer<QuestPickerViewState>() { override val stateKey = key<QuestPickerViewState>() val MIN_FILTER_QUERY_LEN = 3 override fun reduce( state: AppState, subState: QuestPickerViewState, action: Action ) = when (action) { is QuestPickerAction.Load -> { subState.copy( challengeId = action.challengeId ) } is QuestPickerAction.Loaded -> { val quests = createPickerQuests(action.quests, action.repeatingQuests) subState.copy( type = if (quests.isEmpty()) EMPTY else DATA_CHANGED, allQuests = quests, filteredQuests = quests ) } is QuestPickerAction.Filter -> { val query = action.query.trim() when { query.isEmpty() -> subState.copy( type = if (subState.allQuests.isEmpty()) EMPTY else DATA_CHANGED, filteredQuests = subState.allQuests ) query.length < MIN_FILTER_QUERY_LEN -> subState else -> { val filteredQuests = filterQuests( query, subState.allQuests ) subState.copy( type = if (filteredQuests.isEmpty()) EMPTY else DATA_CHANGED, filteredQuests = filteredQuests ) } } } is QuestPickerAction.Check -> { subState.copy( type = ITEM_SELECTED, selectedQuests = if (action.isSelected) { subState.selectedQuests + action.id } else { subState.selectedQuests - action.id } ) } else -> subState } private fun createPickerQuests( quests: List<Quest>, repeatingQuests: List<RepeatingQuest> ) = sortQuests( quests.map { PickerQuest.OneTime(it) } + repeatingQuests.map { PickerQuest.Repeating( it ) }) private fun filterQuests( query: String, quests: List<PickerQuest> ) = sortQuests( quests.filter { it.name.toLowerCase().contains(query.toLowerCase()) } ) private fun sortQuests(result: List<PickerQuest>): List<PickerQuest> { return result.sortedWith(Comparator { q1, q2 -> val d1 = q1.date val d2 = q2.date if (d1 == null && d2 == null) { return@Comparator -1 } if (d1 == null) { return@Comparator 1 } if (d2 == null) { return@Comparator -1 } if (d2.isAfter(d1)) { return@Comparator 1 } return@Comparator if (d1.isAfter(d2)) { -1 } else 0 }) } override fun defaultState() = QuestPickerViewState( type = LOADING, challengeId = "", allQuests = listOf(), filteredQuests = listOf(), selectedQuests = setOf() ) } sealed class PickerQuest( open val baseQuest: BaseQuest, open val id: String, open val name: String, open val date: LocalDate? ) { data class OneTime(val quest: Quest) : PickerQuest(quest, quest.id, quest.name, quest.scheduledDate) data class Repeating(val repeatingQuest: RepeatingQuest) : PickerQuest( repeatingQuest, repeatingQuest.id, repeatingQuest.name, repeatingQuest.repeatPattern.startDate ) } data class QuestPickerViewState( val type: QuestPickerViewState.StateType, val challengeId: String, val allQuests: List<PickerQuest>, val filteredQuests: List<PickerQuest>, val selectedQuests: Set<String> ) : BaseViewState() { enum class StateType { LOADING, EMPTY, DATA_CHANGED, ITEM_SELECTED } } data class QuestViewModel( val id: String, val name: String, @ColorRes val color: Int, val icon: IIcon, val isRepeating: Boolean, val isSelected: Boolean ) class QuestAdapter( private var viewModels: List<QuestViewModel> = listOf(), private var checkListener: (String, Boolean) -> Unit ) : RecyclerView.Adapter<ViewHolder>() { override fun getItemCount() = viewModels.size override fun onBindViewHolder(holder: ViewHolder, position: Int) { val vm = viewModels[position] val view = holder.itemView view.questName.text = vm.name view.questIcon.backgroundTintList = ColorStateList.valueOf(ContextCompat.getColor(view.context, vm.color)) view.questIcon.setImageDrawable(IconicsDrawable(view.context).listItemIcon(vm.icon)) view.questRepeatIndicator.visible = vm.isRepeating view.questCheck.setOnCheckedChangeListener(null) view.questCheck.isChecked = vm.isSelected view.questCheck.setOnCheckedChangeListener { _, isChecked -> checkListener(vm.id, isChecked) } view.setOnClickListener { view.questCheck.isChecked = !view.questCheck.isChecked } } fun updateAll(viewModels: List<QuestViewModel>) { this.viewModels = viewModels notifyDataSetChanged() } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = ViewHolder( LayoutInflater.from(parent.context).inflate( R.layout.item_quest_picker, parent, false ) ) } class ViewHolder(view: View) : RecyclerView.ViewHolder(view) fun QuestPickerViewState.toViewModels() = filteredQuests.map { when (it) { is PickerQuest.OneTime -> { val quest = it.quest QuestViewModel( id = quest.id, name = quest.name, color = AndroidColor.valueOf(quest.color.name).color500, icon = quest.icon?.let { AndroidIcon.valueOf(it.name).icon } ?: Ionicons.Icon.ion_checkmark, isRepeating = false, isSelected = selectedQuests.contains(it.id) ) } is PickerQuest.Repeating -> { val rq = it.repeatingQuest QuestViewModel( id = rq.id, name = rq.name, color = AndroidColor.valueOf(rq.color.name).color500, icon = rq.icon?.let { AndroidIcon.valueOf(it.name).icon } ?: Ionicons.Icon.ion_checkmark, isRepeating = true, isSelected = selectedQuests.contains(it.id) ) } } }
gpl-3.0
aba448aac751f74f4ad473f53af62e98
31.216028
92
0.571011
5.032662
false
false
false
false
Turbo87/intellij-emberjs
src/test/kotlin/com/emberjs/translations/EmberIntlFoldingBuilderTest.kt
1
1478
package com.emberjs.translations import com.intellij.testFramework.fixtures.BasePlatformTestCase import com.intellij.util.indexing.FileBasedIndex import java.nio.file.Paths class EmberIntlFoldingBuilderTest : BasePlatformTestCase() { override fun getTestDataPath(): String? { val resource = ClassLoader.getSystemResource("com/emberjs/translations/fixtures") return Paths.get(resource.toURI()).toAbsolutePath().toString() } fun doTest(templateName: String, fixtureName: String = "ember-intl") { // Load fixture files into the project myFixture.copyDirectoryToProject(fixtureName, "/") // Rebuild index now that the `package.json` file is copied over FileBasedIndex.getInstance().requestRebuild(EmberIntlIndex.NAME) myFixture.testFoldingWithCollapseStatus( "$testDataPath/$fixtureName/app/templates/$templateName-expectation.hbs", "$testDataPath/$fixtureName/app/templates/$templateName.hbs") } fun testFolding() = doTest("folding-test") fun testUnknownTranslation() = doTest("missing-translation-folding-test") fun testPlaceholders() = doTest("placeholder-folding-test") fun testSubexpression() = doTest("sexpr-folding-test") fun testJson() = doTest("json", "ember-intl-json") fun testFoldingWithoutDependency() = doTest("folding-test", "no-dependencies") fun testBaseLocale() = doTest("base-locale-test", "ember-intl-with-base-locale") }
apache-2.0
b39a9e1df00e3bd9d12f637a9e92d74a
42.470588
89
0.723951
4.590062
false
true
false
false
GunoH/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createVariable/CreateLocalVariableActionFactory.kt
2
4033
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.quickfix.createFromUsage.createVariable import com.intellij.codeInsight.intention.IntentionAction import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.psi.PsiElement import com.intellij.psi.util.findParentOfType import org.jetbrains.kotlin.diagnostics.Diagnostic import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.intentions.ConvertToBlockBodyIntention import org.jetbrains.kotlin.idea.quickfix.KotlinSingleIntentionActionFactory import org.jetbrains.kotlin.idea.quickfix.createFromUsage.CreateFromUsageFixBase import org.jetbrains.kotlin.idea.quickfix.createFromUsage.callableBuilder.* import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.getAssignmentByLHS import org.jetbrains.kotlin.psi.psiUtil.getParentOfTypeAndBranch import org.jetbrains.kotlin.psi.psiUtil.getQualifiedElement import org.jetbrains.kotlin.types.Variance import java.util.* object CreateLocalVariableActionFactory : KotlinSingleIntentionActionFactory() { override fun createAction(diagnostic: Diagnostic): IntentionAction? { val refExpr = diagnostic.psiElement.findParentOfType<KtNameReferenceExpression>(strict = false) ?: return null if (refExpr.getQualifiedElement() != refExpr) return null if (refExpr.getParentOfTypeAndBranch<KtCallableReferenceExpression> { callableReference } != null) return null if (getContainer(refExpr) == null) return null return CreateLocalFromUsageAction(refExpr) } private fun getContainer(refExpr: KtNameReferenceExpression): KtElement? { var element: PsiElement = refExpr while (true) { when (val parent = element.parent) { null, is KtAnnotationEntry -> return null is KtBlockExpression -> return parent is KtDeclarationWithBody -> { if (parent.bodyExpression == element) return parent element = parent } else -> element = parent } } } class CreateLocalFromUsageAction(refExpr: KtNameReferenceExpression, val propertyName: String = refExpr.getReferencedName()) : CreateFromUsageFixBase<KtNameReferenceExpression>(refExpr) { override fun getText(): String = KotlinBundle.message("fix.create.from.usage.local.variable", propertyName) override fun invoke(project: Project, editor: Editor?, file: KtFile) { val refExpr = element ?: return val container = getContainer(refExpr) ?: return val assignment = refExpr.getAssignmentByLHS() val varExpected = assignment != null var originalElement: KtExpression = assignment ?: refExpr val actualContainer = when (container) { is KtBlockExpression -> container else -> ConvertToBlockBodyIntention.convert(container as KtDeclarationWithBody, true).bodyExpression!! } as KtBlockExpression if (actualContainer != container) { val bodyExpression = actualContainer.statements.first()!! originalElement = (bodyExpression as? KtReturnExpression)?.returnedExpression ?: bodyExpression } val typeInfo = TypeInfo( originalElement.getExpressionForTypeGuess(), if (varExpected) Variance.INVARIANT else Variance.OUT_VARIANCE ) val propertyInfo = PropertyInfo(propertyName, TypeInfo.Empty, typeInfo, varExpected, Collections.singletonList(actualContainer)) with(CallableBuilderConfiguration(listOfNotNull(propertyInfo), originalElement, file, editor).createBuilder()) { placement = CallablePlacement.NoReceiver(actualContainer) build() } } } }
apache-2.0
36f578c4d9a877e086dbbeea9f032db2
48.182927
128
0.707166
5.688293
false
false
false
false
GunoH/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/macros/KotlinBundledUsageDetector.kt
1
3413
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.macros import com.intellij.openapi.components.Service import com.intellij.openapi.components.service import com.intellij.openapi.project.Project import com.intellij.openapi.roots.OrderRootType import com.intellij.openapi.startup.StartupActivity import com.intellij.util.messages.Topic import com.intellij.workspaceModel.ide.WorkspaceModelChangeListener import com.intellij.workspaceModel.storage.VersionedStorageChange import com.intellij.workspaceModel.storage.bridgeEntities.LibraryEntity import org.jetbrains.jps.util.JpsPathUtil import org.jetbrains.kotlin.idea.base.plugin.artifacts.KotlinArtifactConstants import org.jetbrains.kotlin.idea.versions.forEachAllUsedLibraries import java.io.File import java.util.concurrent.atomic.AtomicBoolean @Service(Service.Level.PROJECT) class KotlinBundledUsageDetector(private val project: Project) { private val isKotlinBundledFound = AtomicBoolean(false) private fun detected() { if (isKotlinBundledFound.compareAndSet(/* expectedValue = */ false, /* newValue = */ true)) { project.messageBus.syncPublisher(TOPIC).kotlinBundledDetected() } } internal class ModelChangeListener(private val project: Project) : WorkspaceModelChangeListener { override fun changed(event: VersionedStorageChange) { val detectorService = project.detectorInstance if (detectorService.isKotlinBundledFound.get()) { return } val changes = event.getChanges(LibraryEntity::class.java).ifEmpty { return } val isDistUsedInLibraries = changes.asSequence() .mapNotNull { it.newEntity } .flatMap { it.roots } .any { it.url.url.isStartsWithDistPrefix } if (isDistUsedInLibraries) { detectorService.detected() } } } internal class MyStartupActivity : StartupActivity.DumbAware { override fun runActivity(project: Project) { var isUsed = false project.forEachAllUsedLibraries { library -> if (library.getUrls(OrderRootType.CLASSES).any(String::isStartsWithDistPrefix)) { isUsed = true return@forEachAllUsedLibraries false } true } if (isUsed) { project.detectorInstance.detected() } } } companion object { @JvmField @Topic.ProjectLevel val TOPIC = Topic(KotlinBundledUsageDetectorListener::class.java, Topic.BroadcastDirection.NONE) /** * @return * **false** -> **KOTLIN_BUNDLED** certainly NOT used in any JPS library.<br> * **true** -> **KOTLIN_BUNDLED** is potentially used in the project/module libraries */ @JvmStatic fun isKotlinBundledPotentiallyUsedInLibraries(project: Project): Boolean { return project.detectorInstance.isKotlinBundledFound.get() } } } private val Project.detectorInstance: KotlinBundledUsageDetector get() = service() private val String.isStartsWithDistPrefix: Boolean get() = File(JpsPathUtil.urlToPath(this)).startsWith(KotlinArtifactConstants.KOTLIN_DIST_LOCATION_PREFIX)
apache-2.0
c529ac2bf0cdb8154b5d1ddb68311104
38.686047
120
0.686786
5.02651
false
false
false
false
GunoH/intellij-community
plugins/kotlin/gradle/gradle-tooling/impl/src/org/jetbrains/kotlin/idea/gradleTooling/arguments/cachedArgsInfoImpl.kt
3
4773
// 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.gradleTooling.arguments import org.jetbrains.kotlin.idea.projectModel.CachedArgsInfo import org.jetbrains.kotlin.idea.projectModel.KotlinCachedCompilerArgument fun createCachedArgsInfo(cachedArgsInfo: CachedArgsInfo<*>, cloningCache: MutableMap<Any, Any>): CachedArgsInfo<*> = when (cachedArgsInfo) { is CachedSerializedArgsInfo -> cloningCache.getOrPut(cachedArgsInfo) { CachedSerializedArgsInfo( cachedArgsInfo.cacheOriginIdentifier, cachedArgsInfo.currentCompilerArguments.map { KotlinCachedRegularCompilerArgument(it, cloningCache) }, cachedArgsInfo.defaultCompilerArguments.map { KotlinCachedRegularCompilerArgument(it, cloningCache) }, cachedArgsInfo.dependencyClasspath.mapNotNull { KotlinCachedCompilerArgument(it, cloningCache) } ) } as CachedSerializedArgsInfo is CachedExtractedArgsInfo -> cloningCache.getOrPut(cachedArgsInfo) { CachedExtractedArgsInfo( cachedArgsInfo.cacheOriginIdentifier, CachedCompilerArgumentsBucket(cachedArgsInfo.currentCompilerArguments, cloningCache), CachedCompilerArgumentsBucket(cachedArgsInfo.defaultCompilerArguments, cloningCache), cachedArgsInfo.dependencyClasspath.mapNotNull { KotlinCachedCompilerArgument(it, cloningCache) } ) } as CachedExtractedArgsInfo else -> { error("") } } interface CachedSerializedArgsInfo : CachedArgsInfo<List<KotlinCachedRegularCompilerArgument>> { override val cacheOriginIdentifier: Long override val currentCompilerArguments: List<KotlinCachedRegularCompilerArgument> override val defaultCompilerArguments: List<KotlinCachedRegularCompilerArgument> override val dependencyClasspath: Collection<KotlinCachedCompilerArgument<*>> } fun CachedSerializedArgsInfo( cacheOriginIdentifier: Long, currentCompilerArguments: List<KotlinCachedRegularCompilerArgument>, defaultCompilerArguments: List<KotlinCachedRegularCompilerArgument>, dependencyClasspath: Collection<KotlinCachedCompilerArgument<*>> ): CachedSerializedArgsInfo = CachedSerializedArgsInfoImpl(cacheOriginIdentifier, currentCompilerArguments, defaultCompilerArguments, dependencyClasspath) fun CachedSerializedArgsInfo(cachedArgsInfo: CachedSerializedArgsInfo): CachedSerializedArgsInfo = CachedSerializedArgsInfo( cachedArgsInfo.cacheOriginIdentifier, cachedArgsInfo.currentCompilerArguments, cachedArgsInfo.defaultCompilerArguments, cachedArgsInfo.dependencyClasspath ) private data class CachedSerializedArgsInfoImpl( override val cacheOriginIdentifier: Long, override val currentCompilerArguments: List<KotlinCachedRegularCompilerArgument>, override val defaultCompilerArguments: List<KotlinCachedRegularCompilerArgument>, override val dependencyClasspath: Collection<KotlinCachedCompilerArgument<*>> ) : CachedSerializedArgsInfo interface CachedExtractedArgsInfo : CachedArgsInfo<CachedCompilerArgumentsBucket> { override val cacheOriginIdentifier: Long override val currentCompilerArguments: CachedCompilerArgumentsBucket override val defaultCompilerArguments: CachedCompilerArgumentsBucket override val dependencyClasspath: Collection<KotlinCachedCompilerArgument<*>> } fun CachedExtractedArgsInfo( cacheOriginIdentifier: Long, currentCompilerArguments: CachedCompilerArgumentsBucket, defaultCompilerArguments: CachedCompilerArgumentsBucket, dependencyClasspath: Collection<KotlinCachedCompilerArgument<*>> ): CachedExtractedArgsInfo = CachedExtractedArgsInfoImpl(cacheOriginIdentifier, currentCompilerArguments, defaultCompilerArguments, dependencyClasspath) fun CachedExtractedArgsInfo(cachedArgsInfo: CachedExtractedArgsInfo, cloningCache: MutableMap<Any, Any>): CachedExtractedArgsInfo = CachedExtractedArgsInfo( cachedArgsInfo.cacheOriginIdentifier, CachedCompilerArgumentsBucket(cachedArgsInfo.currentCompilerArguments, cloningCache), CachedCompilerArgumentsBucket(cachedArgsInfo.defaultCompilerArguments, cloningCache), cachedArgsInfo.dependencyClasspath ) private data class CachedExtractedArgsInfoImpl( override val cacheOriginIdentifier: Long, override val currentCompilerArguments: CachedCompilerArgumentsBucket, override val defaultCompilerArguments: CachedCompilerArgumentsBucket, override val dependencyClasspath: Collection<KotlinCachedCompilerArgument<*>> ) : CachedExtractedArgsInfo
apache-2.0
3b944512fce48afb4939efe8d9d2ae05
52.640449
158
0.800545
7.96828
false
false
false
false
codebutler/farebot
farebot-app/src/main/java/com/codebutler/farebot/app/feature/card/CardScreenView.kt
1
3048
/* * CardScreenView.kt * * This file is part of FareBot. * Learn more at: https://codebutler.github.io/farebot/ * * Copyright (C) 2017 Eric Butler <[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.codebutler.farebot.app.feature.card import android.content.Context import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import android.view.View import android.widget.LinearLayout import android.widget.TextView import com.codebutler.farebot.R import com.codebutler.farebot.app.core.kotlin.bindView import com.codebutler.farebot.transit.TransitInfo import com.jakewharton.rxrelay2.PublishRelay import com.wealthfront.magellan.BaseScreenView import com.xwray.groupie.GroupAdapter import io.reactivex.Observable class CardScreenView(context: Context) : BaseScreenView<CardScreen>(context) { private val clicksRelay = PublishRelay.create<TransactionViewModel>() private val balanceLayout: LinearLayout by bindView(R.id.balance_layout) private val balanceTextView: TextView by bindView(R.id.balance) private val errorTextView: TextView by bindView(R.id.error) private val recycler: RecyclerView by bindView(R.id.recycler) init { inflate(context, R.layout.screen_card, this) recycler.layoutManager = LinearLayoutManager(context) } internal fun observeItemClicks(): Observable<TransactionViewModel> = clicksRelay.hide() fun setTransitInfo(transitInfo: TransitInfo, viewModels: List<TransactionViewModel>) { val balance = transitInfo.getBalanceString(resources) if (balance.isEmpty()) { setError(resources.getString(R.string.no_information)) } else { balanceTextView.text = balance if (viewModels.isNotEmpty()) { recycler.adapter = GroupAdapter<TransactionAdapter.TransactionViewHolder>() recycler.adapter = TransactionAdapter(viewModels, clicksRelay) } else { recycler.visibility = View.GONE balanceLayout.layoutParams = LinearLayout.LayoutParams( LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT) } } } fun setError(error: String) { recycler.visibility = View.GONE balanceLayout.visibility = View.GONE errorTextView.visibility = View.VISIBLE errorTextView.text = error } }
gpl-3.0
3e64ccd8a3c239b8e794cefa89f42d48
38.076923
91
0.72769
4.562874
false
false
false
false
inorichi/mangafeed
app/src/main/java/eu/kanade/tachiyomi/data/download/DownloadNotifier.kt
2
8215
package eu.kanade.tachiyomi.data.download import android.content.Context import android.graphics.BitmapFactory import androidx.core.app.NotificationCompat import eu.kanade.tachiyomi.R import eu.kanade.tachiyomi.data.download.model.Download import eu.kanade.tachiyomi.data.notification.NotificationHandler import eu.kanade.tachiyomi.data.notification.NotificationReceiver import eu.kanade.tachiyomi.data.notification.Notifications import eu.kanade.tachiyomi.data.preference.PreferencesHelper import eu.kanade.tachiyomi.util.lang.chop import eu.kanade.tachiyomi.util.system.notificationBuilder import eu.kanade.tachiyomi.util.system.notificationManager import uy.kohesive.injekt.injectLazy import java.util.regex.Pattern /** * DownloadNotifier is used to show notifications when downloading one or multiple chapters. * * @param context context of application */ internal class DownloadNotifier(private val context: Context) { private val preferences: PreferencesHelper by injectLazy() private val progressNotificationBuilder by lazy { context.notificationBuilder(Notifications.CHANNEL_DOWNLOADER_PROGRESS) { setLargeIcon(BitmapFactory.decodeResource(context.resources, R.mipmap.ic_launcher)) setAutoCancel(false) setOnlyAlertOnce(true) } } private val completeNotificationBuilder by lazy { context.notificationBuilder(Notifications.CHANNEL_DOWNLOADER_COMPLETE) { setAutoCancel(false) } } private val errorNotificationBuilder by lazy { context.notificationBuilder(Notifications.CHANNEL_DOWNLOADER_ERROR) { setAutoCancel(false) } } /** * Status of download. Used for correct notification icon. */ private var isDownloading = false /** * Updated when error is thrown */ private var errorThrown = false /** * Updated when paused */ var paused = false /** * Shows a notification from this builder. * * @param id the id of the notification. */ private fun NotificationCompat.Builder.show(id: Int) { context.notificationManager.notify(id, build()) } /** * Dismiss the downloader's notification. Downloader error notifications use a different id, so * those can only be dismissed by the user. */ fun dismissProgress() { context.notificationManager.cancel(Notifications.ID_DOWNLOAD_CHAPTER_PROGRESS) } /** * Called when download progress changes. * * @param download download object containing download information. */ fun onProgressChange(download: Download) { with(progressNotificationBuilder) { if (!isDownloading) { setSmallIcon(android.R.drawable.stat_sys_download) clearActions() // Open download manager when clicked setContentIntent(NotificationHandler.openDownloadManagerPendingActivity(context)) isDownloading = true // Pause action addAction( R.drawable.ic_pause_24dp, context.getString(R.string.action_pause), NotificationReceiver.pauseDownloadsPendingBroadcast(context) ) } val downloadingProgressText = context.getString( R.string.chapter_downloading_progress, download.downloadedImages, download.pages!!.size ) if (preferences.hideNotificationContent()) { setContentTitle(downloadingProgressText) setContentText(null) } else { val title = download.manga.title.chop(15) val quotedTitle = Pattern.quote(title) val chapter = download.chapter.name.replaceFirst("$quotedTitle[\\s]*[-]*[\\s]*".toRegex(RegexOption.IGNORE_CASE), "") setContentTitle("$title - $chapter".chop(30)) setContentText(downloadingProgressText) } setProgress(download.pages!!.size, download.downloadedImages, false) setOngoing(true) show(Notifications.ID_DOWNLOAD_CHAPTER_PROGRESS) } } /** * Show notification when download is paused. */ fun onPaused() { with(progressNotificationBuilder) { setContentTitle(context.getString(R.string.chapter_paused)) setContentText(context.getString(R.string.download_notifier_download_paused)) setSmallIcon(R.drawable.ic_pause_24dp) setProgress(0, 0, false) setOngoing(false) clearActions() // Open download manager when clicked setContentIntent(NotificationHandler.openDownloadManagerPendingActivity(context)) // Resume action addAction( R.drawable.ic_play_arrow_24dp, context.getString(R.string.action_resume), NotificationReceiver.resumeDownloadsPendingBroadcast(context) ) // Clear action addAction( R.drawable.ic_close_24dp, context.getString(R.string.action_cancel_all), NotificationReceiver.clearDownloadsPendingBroadcast(context) ) show(Notifications.ID_DOWNLOAD_CHAPTER_PROGRESS) } // Reset initial values isDownloading = false } /** * This function shows a notification to inform download tasks are done. */ fun onComplete() { dismissProgress() if (!errorThrown) { // Create notification with(completeNotificationBuilder) { setContentTitle(context.getString(R.string.download_notifier_downloader_title)) setContentText(context.getString(R.string.download_notifier_download_finish)) setSmallIcon(android.R.drawable.stat_sys_download_done) clearActions() setAutoCancel(true) setContentIntent(NotificationHandler.openDownloadManagerPendingActivity(context)) setProgress(0, 0, false) show(Notifications.ID_DOWNLOAD_CHAPTER_COMPLETE) } } // Reset states to default errorThrown = false isDownloading = false } /** * Called when the downloader receives a warning. * * @param reason the text to show. */ fun onWarning(reason: String) { with(errorNotificationBuilder) { setContentTitle(context.getString(R.string.download_notifier_downloader_title)) setStyle(NotificationCompat.BigTextStyle().bigText(reason)) setSmallIcon(R.drawable.ic_warning_white_24dp) setAutoCancel(true) clearActions() setContentIntent(NotificationHandler.openDownloadManagerPendingActivity(context)) setProgress(0, 0, false) show(Notifications.ID_DOWNLOAD_CHAPTER_ERROR) } // Reset download information isDownloading = false } /** * Called when the downloader receives an error. It's shown as a separate notification to avoid * being overwritten. * * @param error string containing error information. * @param chapter string containing chapter title. */ fun onError(error: String? = null, chapter: String? = null, mangaTitle: String? = null) { // Create notification with(errorNotificationBuilder) { setContentTitle( mangaTitle?.plus(": $chapter") ?: context.getString(R.string.download_notifier_downloader_title) ) setContentText(error ?: context.getString(R.string.download_notifier_unknown_error)) setSmallIcon(R.drawable.ic_warning_white_24dp) clearActions() setContentIntent(NotificationHandler.openDownloadManagerPendingActivity(context)) setProgress(0, 0, false) show(Notifications.ID_DOWNLOAD_CHAPTER_ERROR) } // Reset download information errorThrown = true isDownloading = false } }
apache-2.0
3e857b11de60160910ffc012d50d2df6
34.562771
133
0.64017
5.341352
false
false
false
false