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
leandroBorgesFerreira/CoolSlidingPanel
library/src/main/java/com/ebanx/library/GestureListener.kt
1
4174
package com.ebanx.library import android.view.GestureDetector import android.view.MotionEvent import android.view.View class GestureListener internal constructor(private val animator: GestureListener.GestureAnimator, private val menuContainer: View, private val contentContainer: View, private val endOffSet: Int, val screenSize: Int, private val expandedContentHeight: Int, private val collapsedContentHeight: Int) : GestureDetector.SimpleOnGestureListener() { var isExpanded: Boolean = false var isScrolling: Boolean = false var isOnFling: Boolean = false var isAnimating: Boolean = false private val rightEdge: Float private val leftEdge: Float init { isExpanded = false rightEdge = screenSize * RIGHT_TRIGGER_MULTIPLICATOR leftEdge = screenSize * LEFT_TRIGGER_MULTIPLICATOR } override fun onDown(e: MotionEvent): Boolean { return true } override fun onScroll(e1: MotionEvent, e2: MotionEvent, distanceX: Float, distanceY: Float): Boolean { val diffY = e2.y - e1.y val diffX = e2.x - e1.x if (!isScrolling && Math.abs(diffX) > Math.abs(diffY) && Math.abs(diffX) > 30) { isScrolling = true } if (!isScrolling) { return false } if (!isExpanded && diffX > 0 && isScrolling && e1.x < leftEdge) { contentContainer.x = diffX // menuContainer.setX(diffX - contentContainer.getWidth()); val layoutParams = contentContainer.layoutParams layoutParams.height = (expandedContentHeight - 0.15 * expandedContentHeight.toDouble() * contentContainer.x.toDouble() / screenSize).toInt() contentContainer.layoutParams = layoutParams return false } else if (isExpanded && diffX < 0 && isScrolling && e1.x > rightEdge) { contentContainer.x = diffX + contentContainer.width // menuContainer.setX(diffX); val layoutParams = contentContainer.layoutParams layoutParams.height = (expandedContentHeight - 0.15 * expandedContentHeight.toDouble() * contentContainer.x.toDouble() / screenSize).toInt() contentContainer.layoutParams = layoutParams return false } return false } override fun onFling(e1: MotionEvent, e2: MotionEvent, velocityX: Float, velocityY: Float): Boolean { if (!isScrolling && (Math.abs(velocityX) < FLING_TRIGGER_VELOCITY || Math.abs(velocityX) < Math.abs(velocityY))) { return true } val diffX = e2.x - e1.x isOnFling = true if (diffX > 40 && e1.x < leftEdge) { animator.flingWidthAnimation(contentContainer.x, (screenSize - endOffSet).toFloat(), expandedContentHeight, collapsedContentHeight, contentContainer, menuContainer) return true } if (diffX < -40 && e1.x > rightEdge) { animator.flingWidthAnimation(contentContainer.x, 0f, collapsedContentHeight, expandedContentHeight, contentContainer, menuContainer) return true } return false } internal interface GestureAnimator { fun flingWidthAnimation(initialX: Float, finalX: Float, initialHeight: Int, finalHeight: Int, slideView: View, expandView: View) } companion object { private val RIGHT_TRIGGER_MULTIPLICATOR = 9f / 10f private val LEFT_TRIGGER_MULTIPLICATOR = 1 / 10f private val FLING_TRIGGER_VELOCITY = 2000f } }
apache-2.0
c81329504b2d566070855b4c5d49ffde
34.372881
152
0.555822
5.572764
false
false
false
false
JetBrains/kotlin-native
Interop/StubGenerator/src/main/kotlin/org/jetbrains/kotlin/native/interop/gen/Imports.kt
2
2244
/* * Copyright 2010-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.kotlin.native.interop.gen import org.jetbrains.kotlin.konan.library.KonanLibrary import org.jetbrains.kotlin.native.interop.indexer.* interface Imports { fun getPackage(location: Location): String? } class PackageInfo(val name: String, val library: KonanLibrary) class ImportsImpl(internal val headerIdToPackage: Map<HeaderId, PackageInfo>) : Imports { override fun getPackage(location: Location): String? { val packageInfo = headerIdToPackage[location.headerId] ?: return null accessedLibraries += packageInfo.library return packageInfo.name } private val accessedLibraries = mutableSetOf<KonanLibrary>() val requiredLibraries: Set<KonanLibrary> get() = accessedLibraries.toSet() } class HeaderInclusionPolicyImpl(private val nameGlobs: List<String>) : HeaderInclusionPolicy { override fun excludeUnused(headerName: String?): Boolean { if (nameGlobs.isEmpty()) { return false } if (headerName == null) { // Builtins; included only if no globs are specified: return true } return nameGlobs.all { !headerName.matchesToGlob(it) } } } class HeaderExclusionPolicyImpl( private val importsImpl: ImportsImpl ) : HeaderExclusionPolicy { override fun excludeAll(headerId: HeaderId): Boolean { return headerId in importsImpl.headerIdToPackage } } private fun String.matchesToGlob(glob: String): Boolean = java.nio.file.FileSystems.getDefault() .getPathMatcher("glob:$glob").matches(java.nio.file.Paths.get(this))
apache-2.0
3477d153ca14fde82091844a87689328
30.166667
94
0.707219
4.461233
false
false
false
false
jwren/intellij-community
plugins/devkit/intellij.devkit.uiDesigner/src/ConvertFormDialog.kt
1
2097
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.idea.devkit.uiDesigner import com.intellij.openapi.project.Project import com.intellij.openapi.ui.DialogWrapper import com.intellij.ui.EditorTextFieldWithBrowseButton import com.intellij.ui.layout.* import javax.swing.JComponent class ConvertFormDialog(val project: Project, var className: String) : DialogWrapper(project) { enum class FormBaseClass { None, Configurable } var boundInstanceType: String = "" var boundInstanceExpression: String = "" var generateDescriptors = false var baseClass = FormBaseClass.None init { init() title = DevKitUIDesignerBundle.message("convert.form.dialog.title") } override fun createCenterPanel(): JComponent? { return panel { row(DevKitUIDesignerBundle.message("convert.form.dialog.label.target.class.name")) { textField(::className, columns = 40).focused() } row(DevKitUIDesignerBundle.message("convert.form.dialog.label.bound.instance.type")) { EditorTextFieldWithBrowseButton(project, true)() .withBinding(EditorTextFieldWithBrowseButton::getText, EditorTextFieldWithBrowseButton::setText, ::boundInstanceType.toBinding()) } row(DevKitUIDesignerBundle.message("convert.form.dialog.label.bound.instance.expression")) { textField(::boundInstanceExpression) } titledRow(DevKitUIDesignerBundle.message("convert.form.dialog.base.class.separator")) { buttonGroup(::baseClass) { row { radioButton(DevKitUIDesignerBundle.message("convert.form.dialog.base.class.none"), FormBaseClass.None) } row { radioButton(DevKitUIDesignerBundle.message("convert.form.dialog.base.class.configurable"), FormBaseClass.Configurable) row { checkBox(DevKitUIDesignerBundle.message("convert.form.dialog.label.checkbox.generate.descriptors.for.search.everywhere"), ::generateDescriptors) } } } } } } }
apache-2.0
c796ca3bc92d09f7fc1dbcfddca9268a
40.94
158
0.718169
4.82069
false
true
false
false
GunoH/intellij-community
plugins/git4idea/src/git4idea/ui/branch/dashboard/BranchesTree.kt
2
20125
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package git4idea.ui.branch.dashboard import com.intellij.dvcs.DvcsUtil import com.intellij.dvcs.branch.GroupingKey import com.intellij.dvcs.ui.RepositoryChangesBrowserNode.Companion.getColorManager import com.intellij.dvcs.ui.RepositoryChangesBrowserNode.Companion.getRepositoryIcon import com.intellij.icons.AllIcons import com.intellij.ide.dnd.TransferableList import com.intellij.ide.dnd.aware.DnDAwareTree import com.intellij.ide.util.treeView.TreeState import com.intellij.openapi.Disposable import com.intellij.openapi.application.runInEdt import com.intellij.openapi.components.* import com.intellij.openapi.project.Project import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.TextRange import com.intellij.openapi.util.registry.Registry import com.intellij.openapi.util.text.StringUtil import com.intellij.psi.codeStyle.FixingLayoutMatcher import com.intellij.psi.codeStyle.MinusculeMatcher import com.intellij.psi.codeStyle.NameUtil import com.intellij.ui.* import com.intellij.ui.hover.TreeHoverListener import com.intellij.ui.speedSearch.SpeedSearch import com.intellij.ui.speedSearch.SpeedSearchSupply import com.intellij.util.EditSourceOnDoubleClickHandler.isToggleEvent import com.intellij.util.PlatformIcons import com.intellij.util.ThreeState import com.intellij.util.ui.UIUtil import com.intellij.util.ui.tree.TreeUtil import com.intellij.vcs.branch.BranchData import com.intellij.vcs.branch.BranchPresentation import com.intellij.vcs.branch.LinkedBranchDataImpl import com.intellij.vcs.log.util.VcsLogUtil import com.intellij.vcsUtil.VcsImplUtil import git4idea.repo.GitRepository import git4idea.repo.GitRepositoryManager import git4idea.ui.branch.GitBranchManager import git4idea.ui.branch.GitBranchPopupActions.LocalBranchActions.constructIncomingOutgoingTooltip import git4idea.ui.branch.dashboard.BranchesDashboardActions.BranchesTreeActionGroup import icons.DvcsImplIcons import org.jetbrains.annotations.NonNls import java.awt.Graphics import java.awt.GraphicsEnvironment import java.awt.datatransfer.Transferable import java.awt.event.MouseEvent import java.util.* import javax.swing.Icon import javax.swing.JComponent import javax.swing.JTree import javax.swing.TransferHandler import javax.swing.event.TreeExpansionEvent import javax.swing.event.TreeExpansionListener import javax.swing.tree.TreePath internal class BranchesTreeComponent(project: Project) : DnDAwareTree() { var doubleClickHandler: (BranchTreeNode) -> Unit = {} var searchField: SearchTextField? = null init { putClientProperty(AUTO_SELECT_ON_MOUSE_PRESSED, false) setCellRenderer(BranchTreeCellRenderer(project)) isRootVisible = false setShowsRootHandles(true) isOpaque = false isHorizontalAutoScrollingEnabled = false installDoubleClickHandler() SmartExpander.installOn(this) TreeHoverListener.DEFAULT.addTo(this) initDnD() } private inner class BranchTreeCellRenderer(project: Project) : ColoredTreeCellRenderer() { private val repositoryManager = GitRepositoryManager.getInstance(project) private val colorManager = getColorManager(project) private val branchManager = project.service<GitBranchManager>() private var incomingOutgoingIcon: NodeIcon? = null override fun customizeCellRenderer(tree: JTree, value: Any?, selected: Boolean, expanded: Boolean, leaf: Boolean, row: Int, hasFocus: Boolean) { if (value !is BranchTreeNode) return val descriptor = value.getNodeDescriptor() val branchInfo = descriptor.branchInfo val isBranchNode = descriptor.type == NodeType.BRANCH val isGroupNode = descriptor.type == NodeType.GROUP_NODE val isRepositoryNode = descriptor.type == NodeType.GROUP_REPOSITORY_NODE icon = when { isBranchNode && branchInfo != null && branchInfo.isCurrent && branchInfo.isFavorite -> DvcsImplIcons.CurrentBranchFavoriteLabel isBranchNode && branchInfo != null && branchInfo.isCurrent -> DvcsImplIcons.CurrentBranchLabel isBranchNode && branchInfo != null && branchInfo.isFavorite -> AllIcons.Nodes.Favorite isBranchNode -> AllIcons.Vcs.BranchNode isGroupNode -> PlatformIcons.FOLDER_ICON isRepositoryNode -> getRepositoryIcon(descriptor.repository!!, colorManager) else -> null } toolTipText = if (branchInfo != null && branchInfo.isLocal) BranchPresentation.getTooltip(getBranchesTooltipData(branchInfo.branchName, getSelectedRepositories(descriptor))) else null append(value.getTextRepresentation(), SimpleTextAttributes.REGULAR_ATTRIBUTES, true) val repositoryGrouping = branchManager.isGroupingEnabled(GroupingKey.GROUPING_BY_REPOSITORY) if (!repositoryGrouping && branchInfo != null && branchInfo.repositories.size < repositoryManager.repositories.size) { append(" (${DvcsUtil.getShortNames(branchInfo.repositories)})", SimpleTextAttributes.GRAYED_ATTRIBUTES) } val incomingOutgoingState = branchInfo?.incomingOutgoingState incomingOutgoingIcon = incomingOutgoingState?.icon?.let { NodeIcon(it, preferredSize.width + tree.insets.left) } tree.toolTipText = incomingOutgoingState?.run { constructIncomingOutgoingTooltip(hasIncoming(), hasOutgoing()) } } override fun calcFocusedState() = super.calcFocusedState() || searchField?.textEditor?.hasFocus() ?: false private fun getBranchesTooltipData(branchName: String, repositories: Collection<GitRepository>): List<BranchData> { return repositories.map { repo -> val trackedBranchName = repo.branches.findLocalBranch(branchName)?.findTrackedBranch(repo)?.name val presentableRootName = VcsImplUtil.getShortVcsRootName(repo.project, repo.root) LinkedBranchDataImpl(presentableRootName, branchName, trackedBranchName) } } override fun paint(g: Graphics) { super.paint(g) incomingOutgoingIcon?.let { (icon, locationX) -> icon.paintIcon(this@BranchTreeCellRenderer, g, locationX, (size.height - icon.iconHeight) / 2) } } } private data class NodeIcon(val icon: Icon, val locationX: Int) override fun hasFocus() = super.hasFocus() || searchField?.textEditor?.hasFocus() ?: false private fun installDoubleClickHandler() { object : DoubleClickListener() { override fun onDoubleClick(e: MouseEvent): Boolean { val clickPath = getClosestPathForLocation(e.x, e.y) ?: return false val selectionPath = selectionPath if (selectionPath == null || clickPath != selectionPath) return false val node = (selectionPath.lastPathComponent as? BranchTreeNode) ?: return false if (isToggleEvent(this@BranchesTreeComponent, e)) return false doubleClickHandler(node) return true } }.installOn(this) } private fun initDnD() { if (!GraphicsEnvironment.isHeadless()) { transferHandler = BRANCH_TREE_TRANSFER_HANDLER } } fun getSelectedBranches(): List<BranchInfo> { return getSelectedNodes() .mapNotNull { it.getNodeDescriptor().branchInfo } .toList() } fun getSelectedNodes(): Sequence<BranchTreeNode> { val paths = selectionPaths ?: return emptySequence() return paths.asSequence() .map(TreePath::getLastPathComponent) .mapNotNull { it as? BranchTreeNode } } fun getSelectedRemotes(): Set<RemoteInfo> { val paths = selectionPaths ?: return emptySet() return paths.asSequence() .map(TreePath::getLastPathComponent) .mapNotNull { it as? BranchTreeNode } .filter { it.getNodeDescriptor().displayName != null && it.getNodeDescriptor().type == NodeType.GROUP_NODE && (it.getNodeDescriptor().parent?.type == NodeType.REMOTE_ROOT || it.getNodeDescriptor().parent?.repository != null) } .mapNotNull { with(it.getNodeDescriptor()) { RemoteInfo(displayName!!, parent?.repository) } } .toSet() } fun getSelectedRepositories(descriptor: BranchNodeDescriptor): List<GitRepository> { var parent = descriptor.parent while (parent != null) { val repository = parent.repository if (repository != null) return listOf(repository) parent = parent.parent } return descriptor.branchInfo?.repositories ?: emptyList() } fun getSelectedRepositories(branchInfo: BranchInfo): Set<GitRepository> { val paths = selectionPaths ?: return emptySet() return paths.asSequence() .filter { val lastPathComponent = it.lastPathComponent lastPathComponent is BranchTreeNode && lastPathComponent.getNodeDescriptor().branchInfo == branchInfo } .mapNotNull { findNodeDescriptorInPath(it) { descriptor -> Objects.nonNull(descriptor.repository) } } .mapNotNull(BranchNodeDescriptor::repository) .toSet() } private fun findNodeDescriptorInPath(path: TreePath, condition: (BranchNodeDescriptor) -> Boolean): BranchNodeDescriptor? { var curPath: TreePath? = path while (curPath != null) { val node = curPath.lastPathComponent as? BranchTreeNode if (node != null && condition(node.getNodeDescriptor())) return node.getNodeDescriptor() curPath = curPath.parentPath } return null } } internal class FilteringBranchesTree( val project: Project, val component: BranchesTreeComponent, private val uiController: BranchesDashboardController, rootNode: BranchTreeNode = BranchTreeNode(BranchNodeDescriptor(NodeType.ROOT)), place: @NonNls String, disposable: Disposable ) : FilteringTree<BranchTreeNode, BranchNodeDescriptor>(component, rootNode) { private val expandedPaths = HashSet<TreePath>() private val localBranchesNode = BranchTreeNode(BranchNodeDescriptor(NodeType.LOCAL_ROOT)) private val remoteBranchesNode = BranchTreeNode(BranchNodeDescriptor(NodeType.REMOTE_ROOT)) private val headBranchesNode = BranchTreeNode(BranchNodeDescriptor(NodeType.HEAD_NODE)) private val branchFilter: (BranchInfo) -> Boolean = { branch -> !uiController.showOnlyMy || branch.isMy == ThreeState.YES } private val nodeDescriptorsModel = NodeDescriptorsModel(localBranchesNode.getNodeDescriptor(), remoteBranchesNode.getNodeDescriptor()) private var localNodeExist = false private var remoteNodeExist = false private val treeStateProvider = BranchesTreeStateProvider(this, disposable) private val treeStateHolder: BranchesTreeStateHolder get() = project.service() private val groupingConfig: MutableMap<GroupingKey, Boolean> = with(project.service<GitBranchManager>()) { hashMapOf( GroupingKey.GROUPING_BY_DIRECTORY to isGroupingEnabled(GroupingKey.GROUPING_BY_DIRECTORY), GroupingKey.GROUPING_BY_REPOSITORY to isGroupingEnabled(GroupingKey.GROUPING_BY_REPOSITORY) ) } fun toggleGrouping(key: GroupingKey, state: Boolean) { groupingConfig[key] = state refreshTree() } fun isGroupingEnabled(key: GroupingKey) = groupingConfig[key] == true init { runInEdt { PopupHandler.installPopupMenu(component, BranchesTreeActionGroup(project, this), place) setupTreeListeners() } } override fun createSpeedSearch(searchTextField: SearchTextField): SpeedSearchSupply = object : FilteringSpeedSearch(searchTextField) { private val customWordMatchers = hashSetOf<MinusculeMatcher>() override fun matchingFragments(text: String): Iterable<TextRange?>? { val allTextRanges = super.matchingFragments(text) if (customWordMatchers.isEmpty()) return allTextRanges val wordRanges = arrayListOf<TextRange>() for (wordMatcher in customWordMatchers) { wordMatcher.matchingFragments(text)?.let(wordRanges::addAll) } return when { allTextRanges != null -> allTextRanges + wordRanges wordRanges.isNotEmpty() -> wordRanges else -> null } } override fun updatePattern(string: String?) { super.updatePattern(string) onUpdatePattern(string) } override fun onUpdatePattern(text: String?) { customWordMatchers.clear() customWordMatchers.addAll(buildCustomWordMatchers(text)) } private fun buildCustomWordMatchers(text: String?): Set<MinusculeMatcher> { if (text == null) return emptySet() val wordMatchers = hashSetOf<MinusculeMatcher>() for (word in StringUtil.split(text, " ")) { wordMatchers.add( FixingLayoutMatcher("*$word", NameUtil.MatchingCaseSensitivity.NONE, "")) } return wordMatchers } } override fun installSearchField(): SearchTextField { val searchField = super.installSearchField() component.searchField = searchField return searchField } private fun setupTreeListeners() { component.addTreeExpansionListener(object : TreeExpansionListener { override fun treeExpanded(event: TreeExpansionEvent) { expandedPaths.add(event.path) treeStateHolder.setStateProvider(treeStateProvider) } override fun treeCollapsed(event: TreeExpansionEvent) { expandedPaths.remove(event.path) treeStateHolder.setStateProvider(treeStateProvider) } }) component.addTreeSelectionListener { treeStateHolder.setStateProvider(treeStateProvider) } } fun getSelectedRepositories(branchInfo: BranchInfo): List<GitRepository> { val selectedRepositories = component.getSelectedRepositories(branchInfo) return if (selectedRepositories.isNotEmpty()) selectedRepositories.toList() else branchInfo.repositories } fun getSelectedBranches() = component.getSelectedBranches() fun getSelectedBranchFilters(): List<String> { return component.getSelectedNodes() .mapNotNull { with(it.getNodeDescriptor()) { if (type == NodeType.HEAD_NODE) VcsLogUtil.HEAD else branchInfo?.branchName } } .toList() } fun getSelectedRemotes() = component.getSelectedRemotes() fun getSelectedBranchNodes() = component.getSelectedNodes().map(BranchTreeNode::getNodeDescriptor).toSet() private fun restorePreviouslyExpandedPaths() { TreeUtil.restoreExpandedPaths(component, expandedPaths.toList()) } override fun expandTreeOnSearchUpdateComplete(pattern: String?) { restorePreviouslyExpandedPaths() } override fun onSpeedSearchUpdateComplete(pattern: String?) { updateSpeedSearchBackground() } override fun useIdentityHashing(): Boolean = false private fun updateSpeedSearchBackground() { val speedSearch = searchModel.speedSearch as? SpeedSearch ?: return val textEditor = component.searchField?.textEditor ?: return if (isEmptyModel()) { textEditor.isOpaque = true speedSearch.noHits() } else { textEditor.isOpaque = false textEditor.background = UIUtil.getTextFieldBackground() } } private fun isEmptyModel() = searchModel.isLeaf(localBranchesNode) && searchModel.isLeaf(remoteBranchesNode) override fun getNodeClass() = BranchTreeNode::class.java override fun createNode(nodeDescriptor: BranchNodeDescriptor) = when (nodeDescriptor.type) { NodeType.LOCAL_ROOT -> localBranchesNode NodeType.REMOTE_ROOT -> remoteBranchesNode NodeType.HEAD_NODE -> headBranchesNode else -> BranchTreeNode(nodeDescriptor) } override fun getChildren(nodeDescriptor: BranchNodeDescriptor) = when (nodeDescriptor.type) { NodeType.ROOT -> getRootNodeDescriptors() NodeType.LOCAL_ROOT -> localBranchesNode.getNodeDescriptor().getDirectChildren() NodeType.REMOTE_ROOT -> remoteBranchesNode.getNodeDescriptor().getDirectChildren() NodeType.GROUP_NODE -> nodeDescriptor.getDirectChildren() NodeType.GROUP_REPOSITORY_NODE -> nodeDescriptor.getDirectChildren() else -> emptyList() //leaf branch node } private fun BranchNodeDescriptor.getDirectChildren() = nodeDescriptorsModel.getChildrenForParent(this) fun update(initial: Boolean) { val branchesReloaded = uiController.reloadBranches() runPreservingTreeState(initial) { searchModel.updateStructure() } if (branchesReloaded) { tree.revalidate() tree.repaint() } } private fun runPreservingTreeState(loadSaved: Boolean, runnable: () -> Unit) { if (Registry.`is`("git.branches.panel.persist.tree.state")) { val treeState = if (loadSaved) treeStateHolder.getInitialTreeState() else TreeState.createOn(tree, root) runnable() if (treeState != null) { treeState.applyTo(tree) } else { initDefaultTreeExpandState() } } else { runnable() if (loadSaved) { initDefaultTreeExpandState() } } } private fun initDefaultTreeExpandState() { // expanding lots of nodes is a slow operation (and result is not very useful) if (TreeUtil.hasManyNodes(tree, 30000)) { TreeUtil.collapseAll(tree, 1) } else { TreeUtil.expandAll(tree) } } fun refreshTree() { runPreservingTreeState(false) { tree.selectionModel.clearSelection() refreshNodeDescriptorsModel() searchModel.updateStructure() } } fun refreshNodeDescriptorsModel() { with(uiController) { nodeDescriptorsModel.clear() localNodeExist = localBranches.isNotEmpty() remoteNodeExist = remoteBranches.isNotEmpty() nodeDescriptorsModel.populateFrom((localBranches.asSequence() + remoteBranches.asSequence()).filter(branchFilter), groupingConfig) } } override fun getText(nodeDescriptor: BranchNodeDescriptor?) = nodeDescriptor?.branchInfo?.branchName ?: nodeDescriptor?.displayName private fun getRootNodeDescriptors() = mutableListOf<BranchNodeDescriptor>().apply { if (localNodeExist || remoteNodeExist) add(headBranchesNode.getNodeDescriptor()) if (localNodeExist) add(localBranchesNode.getNodeDescriptor()) if (remoteNodeExist) add(remoteBranchesNode.getNodeDescriptor()) } } private val BRANCH_TREE_TRANSFER_HANDLER = object : TransferHandler() { override fun createTransferable(tree: JComponent): Transferable? { if (tree is BranchesTreeComponent) { val branches = tree.getSelectedBranches() if (branches.isEmpty()) return null return object : TransferableList<BranchInfo>(branches.toList()) { override fun toString(branch: BranchInfo) = branch.toString() } } return null } override fun getSourceActions(c: JComponent) = COPY_OR_MOVE } @State(name = "BranchesTreeState", storages = [Storage(StoragePathMacros.PRODUCT_WORKSPACE_FILE)], reportStatistic = false) @Service(Service.Level.PROJECT) internal class BranchesTreeStateHolder : PersistentStateComponent<TreeState> { private var treeStateProvider: BranchesTreeStateProvider? = null private var _treeState: TreeState? = null fun getInitialTreeState(): TreeState? = state override fun getState(): TreeState? { return treeStateProvider?.getState() ?: _treeState } override fun loadState(state: TreeState) { _treeState = state } fun setStateProvider(provider: BranchesTreeStateProvider) { treeStateProvider = provider } } internal class BranchesTreeStateProvider(tree: FilteringBranchesTree, disposable: Disposable) { private var tree: FilteringBranchesTree? = tree private var state: TreeState? = null init { Disposer.register(disposable) { persistTreeState() this.tree = null } } fun getState(): TreeState? { persistTreeState() return state } private fun persistTreeState() { if (Registry.`is`("git.branches.panel.persist.tree.state")) { tree?.let { state = TreeState.createOn(it.tree, it.root) } } } }
apache-2.0
6ba22d6bf301acbfbc6b567fac550c4e
36.337662
140
0.726161
5.206986
false
false
false
false
GunoH/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/replaceWith/DeprecatedSymbolUsageFix.kt
1
2169
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.quickfix.replaceWith import com.intellij.codeInsight.intention.HighPriorityAction import com.intellij.codeInsight.intention.IntentionAction import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import org.jetbrains.kotlin.diagnostics.Diagnostic import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.codeInliner.UsageReplacementStrategy import org.jetbrains.kotlin.idea.core.moveCaret import org.jetbrains.kotlin.idea.codeinsight.api.classic.quickfixes.CleanupFix import org.jetbrains.kotlin.idea.quickfix.KotlinSingleIntentionActionFactory import com.intellij.openapi.application.runWriteAction import org.jetbrains.kotlin.psi.KtReferenceExpression import org.jetbrains.kotlin.resolve.calls.util.getCalleeExpressionIfAny class DeprecatedSymbolUsageFix( element: KtReferenceExpression, replaceWith: ReplaceWithData ) : DeprecatedSymbolUsageFixBase(element, replaceWith), CleanupFix, HighPriorityAction { override fun getFamilyName() = KotlinBundle.message("replace.deprecated.symbol.usage") override fun getText() = KotlinBundle.message("replace.with.0", replaceWith.pattern) override fun invoke(replacementStrategy: UsageReplacementStrategy, project: Project, editor: Editor?) { val element = element ?: return val replacer = replacementStrategy.createReplacer(element) ?: return val result = replacer() ?: return if (editor != null) { val offset = (result.getCalleeExpressionIfAny() ?: result).textOffset editor.moveCaret(offset) } } companion object : KotlinSingleIntentionActionFactory() { override fun createAction(diagnostic: Diagnostic): IntentionAction? { val (referenceExpression, replacement) = extractDataFromDiagnostic(diagnostic, false) ?: return null return DeprecatedSymbolUsageFix(referenceExpression, replacement).takeIf { it.isAvailable } } } }
apache-2.0
4d6513317950b2e5a50585d9eaa89b7f
49.44186
158
0.781466
5.12766
false
false
false
false
smmribeiro/intellij-community
plugins/gradle/gradle-dependency-updater/src/org/jetbrains/plugins/gradle/dsl/RepositoriesWithShorthandMethods.kt
9
1878
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.gradle.dsl import com.android.tools.idea.gradle.dsl.api.repositories.RepositoryModel.RepositoryType import java.net.URI enum class RepositoriesWithShorthandMethods( val methodName: String, val dslRepositoryType: RepositoryType, val repositoryId: String? = null, val urls: Set<URI> ) { JCENTER(methodName = "jcenter", dslRepositoryType = RepositoryType.MAVEN, urls = setOf(URI.create("https://jcenter.bintray.com"))), MAVEN_CENTRAL(methodName = "mavenCentral", dslRepositoryType = RepositoryType.MAVEN_CENTRAL, repositoryId = "maven_central", urls = setOf(URI.create("https://repo.maven.apache.org/maven2/"), URI.create("https://repo1.maven.org/maven2"), URI.create("https://maven-central.storage-download.googleapis.com/maven2"))), GOOGLE_MAVEN(methodName = "gmaven", dslRepositoryType = RepositoryType.GOOGLE_DEFAULT, repositoryId = "google", urls = setOf(URI.create("https://maven.google.com"))); companion object { fun findByUrlLenient(url: String): RepositoriesWithShorthandMethods? = values().find { repo -> repo.urls.any { it.isEquivalentLenientTo(url) } } fun findByRepoType(repoType: RepositoryType): RepositoriesWithShorthandMethods? = values().find { repo -> repo.dslRepositoryType == repoType } private fun URI.isEquivalentLenientTo(url: String?): Boolean { if (url == null) return false val otherUriNormalized = URI(url.trim().trimEnd('/', '?', '#')).normalize() val thisUriNormalized = URI(toASCIIString().trim().trimEnd('/', '?', '#')).normalize() return thisUriNormalized == otherUriNormalized } } }
apache-2.0
32e4ac4f07479d3f9c93a27362b4d16e
47.153846
140
0.686901
4.337182
false
false
false
false
smmribeiro/intellij-community
platform/lang-impl/src/com/intellij/ide/bookmark/ui/BookmarksViewFactory.kt
9
2096
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.ide.bookmark.ui import com.intellij.ide.actions.ToggleToolbarAction.isToolbarVisible import com.intellij.openapi.actionSystem.ex.ActionUtil import com.intellij.openapi.project.DumbAware import com.intellij.openapi.project.Project import com.intellij.openapi.ui.Splittable import com.intellij.openapi.wm.ToolWindow import com.intellij.openapi.wm.ToolWindowFactory import com.intellij.openapi.wm.ToolWindowId import com.intellij.openapi.wm.ToolWindowManager import com.intellij.openapi.wm.ex.ToolWindowEx import com.intellij.openapi.wm.ex.ToolWindowManagerListener import java.util.concurrent.atomic.AtomicBoolean internal class BookmarksViewFactory : DumbAware, ToolWindowFactory, ToolWindowManagerListener { private val orientation = AtomicBoolean(true) override fun createToolWindowContent(project: Project, window: ToolWindow) { val manager = window.contentManager val panel = BookmarksView(project, isToolbarVisible(window, project)).also { it.orientation = orientation.get() } manager.addContent(manager.factory.createContent(panel, null, false).apply { isCloseable = false }) project.messageBus.connect(manager).subscribe(ToolWindowManagerListener.TOPIC, this) window.helpId = "bookmarks.tool.window.help" window.setTitleActions(listOfNotNull(ActionUtil.getAction("Bookmarks.ToolWindow.TitleActions"))) if (window is ToolWindowEx) window.setAdditionalGearActions(ActionUtil.getActionGroup("Bookmarks.ToolWindow.GearActions")) } override fun stateChanged(manager: ToolWindowManager) { val window = manager.getToolWindow(ToolWindowId.BOOKMARKS) ?: return if (window.isDisposed) return val vertical = !window.anchor.isHorizontal if (vertical != orientation.getAndSet(vertical)) { for (content in window.contentManager.contents) { val splittable = content?.component as? Splittable splittable?.orientation = vertical } } } }
apache-2.0
4335bfe6bcfea3c5ecdcc5a4251cdc91
50.121951
158
0.794847
4.606593
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/ScopeFunctionConversionInspection.kt
1
17309
// 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.inspections import com.intellij.codeInspection.* import com.intellij.openapi.fileEditor.FileEditorManager import com.intellij.openapi.project.Project import com.intellij.psi.PsiDocumentManager import com.intellij.psi.PsiElement import com.intellij.psi.PsiElementVisitor import com.intellij.psi.SmartPsiElementPointer import org.jetbrains.kotlin.descriptors.SimpleFunctionDescriptor import org.jetbrains.kotlin.descriptors.ValueParameterDescriptor import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.core.KotlinNameSuggester import org.jetbrains.kotlin.idea.core.ShortenReferences import org.jetbrains.kotlin.idea.refactoring.getThisLabelName import org.jetbrains.kotlin.idea.refactoring.rename.KotlinVariableInplaceRenameHandler import org.jetbrains.kotlin.idea.references.resolveMainReferenceToDescriptors import org.jetbrains.kotlin.idea.util.application.isUnitTestMode import org.jetbrains.kotlin.idea.util.getReceiverTargetDescriptor import org.jetbrains.kotlin.idea.util.getResolutionScope import org.jetbrains.kotlin.idea.util.safeAnalyzeNonSourceRootCode import org.jetbrains.kotlin.incremental.components.NoLookupLocation import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.createSmartPointer import org.jetbrains.kotlin.psi.psiUtil.endOffset import org.jetbrains.kotlin.psi.psiUtil.getOrCreateParameterList import org.jetbrains.kotlin.psi.psiUtil.startOffset import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.BindingContext.FUNCTION import org.jetbrains.kotlin.resolve.calls.callUtil.getResolvedCall import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameSafe import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.resolve.scopes.LexicalScope import org.jetbrains.kotlin.resolve.scopes.receivers.ImplicitReceiver import org.jetbrains.kotlin.resolve.scopes.utils.collectDescriptorsFiltered import org.jetbrains.kotlin.resolve.scopes.utils.findVariable import org.jetbrains.kotlin.types.KotlinType private val counterpartNames = mapOf( "apply" to "also", "run" to "let", "also" to "apply", "let" to "run" ) class ScopeFunctionConversionInspection : AbstractKotlinInspection() { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean, session: LocalInspectionToolSession): PsiElementVisitor { return callExpressionVisitor { expression -> val counterpartName = getCounterpart(expression) if (counterpartName != null) { holder.registerProblem( expression.calleeExpression!!, KotlinBundle.message("call.is.replaceable.with.another.scope.function"), ProblemHighlightType.GENERIC_ERROR_OR_WARNING, if (counterpartName == "also" || counterpartName == "let") ConvertScopeFunctionToParameter(counterpartName) else ConvertScopeFunctionToReceiver(counterpartName) ) } } } } private fun getCounterpart(expression: KtCallExpression): String? { val callee = expression.calleeExpression as? KtNameReferenceExpression ?: return null val calleeName = callee.getReferencedName() val counterpartName = counterpartNames[calleeName] val lambdaExpression = expression.lambdaArguments.singleOrNull()?.getLambdaExpression() if (counterpartName != null && lambdaExpression != null) { if (lambdaExpression.valueParameters.isNotEmpty()) { return null } val bindingContext = callee.safeAnalyzeNonSourceRootCode(BodyResolveMode.PARTIAL) val resolvedCall = callee.getResolvedCall(bindingContext) ?: return null val descriptor = resolvedCall.resultingDescriptor if (descriptor.dispatchReceiverParameter == null && descriptor.extensionReceiverParameter == null) return null if (descriptor.fqNameSafe.asString() == "kotlin.$calleeName" && nameResolvesToStdlib(expression, bindingContext, counterpartName)) { return counterpartName } } return null } private fun nameResolvesToStdlib(expression: KtCallExpression, bindingContext: BindingContext, name: String): Boolean { val scope = expression.getResolutionScope(bindingContext) ?: return true val descriptors = scope.collectDescriptorsFiltered(nameFilter = { it.asString() == name }) return descriptors.isNotEmpty() && descriptors.all { it.fqNameSafe.asString() == "kotlin.$name" } } class Replacement<T : PsiElement> private constructor( private val elementPointer: SmartPsiElementPointer<T>, private val replacementFactory: KtPsiFactory.(T) -> PsiElement ) { companion object { fun <T : PsiElement> create(element: T, replacementFactory: KtPsiFactory.(T) -> PsiElement): Replacement<T> { return Replacement(element.createSmartPointer(), replacementFactory) } } fun apply(factory: KtPsiFactory) { elementPointer.element?.let { it.replace(factory.replacementFactory(it)) } } val endOffset get() = elementPointer.element!!.endOffset } class ReplacementCollection(private val project: Project) { private val replacements = mutableListOf<Replacement<out PsiElement>>() var createParameter: KtPsiFactory.() -> PsiElement? = { null } var elementToRename: PsiElement? = null fun <T : PsiElement> add(element: T, replacementFactory: KtPsiFactory.(T) -> PsiElement) { replacements.add(Replacement.create(element, replacementFactory)) } fun apply() { val factory = KtPsiFactory(project) elementToRename = factory.createParameter() // Calls need to be processed in outside-in order replacements.sortBy { it.endOffset } for (replacement in replacements) { replacement.apply(factory) } } fun isNotEmpty() = replacements.isNotEmpty() } abstract class ConvertScopeFunctionFix(private val counterpartName: String) : LocalQuickFix { override fun getFamilyName() = KotlinBundle.message("convert.scope.function.fix.family.name", counterpartName) override fun applyFix(project: Project, problemDescriptor: ProblemDescriptor) { val callee = problemDescriptor.psiElement as KtNameReferenceExpression val callExpression = callee.parent as? KtCallExpression ?: return val bindingContext = callExpression.analyze() val lambda = callExpression.lambdaArguments.firstOrNull() ?: return val functionLiteral = lambda.getLambdaExpression()?.functionLiteral ?: return val lambdaDescriptor = bindingContext[FUNCTION, functionLiteral] ?: return functionLiteral.valueParameterList?.delete() functionLiteral.arrow?.delete() val replacements = ReplacementCollection(project) analyzeLambda(bindingContext, lambda, lambdaDescriptor, replacements) callee.replace(KtPsiFactory(project).createExpression(counterpartName) as KtNameReferenceExpression) replacements.apply() postprocessLambda(lambda) if (replacements.isNotEmpty() && replacements.elementToRename != null && !isUnitTestMode()) { replacements.elementToRename!!.startInPlaceRename() } } protected abstract fun postprocessLambda(lambda: KtLambdaArgument) protected abstract fun analyzeLambda( bindingContext: BindingContext, lambda: KtLambdaArgument, lambdaDescriptor: SimpleFunctionDescriptor, replacements: ReplacementCollection ) } class ConvertScopeFunctionToParameter(counterpartName: String) : ConvertScopeFunctionFix(counterpartName) { override fun analyzeLambda( bindingContext: BindingContext, lambda: KtLambdaArgument, lambdaDescriptor: SimpleFunctionDescriptor, replacements: ReplacementCollection ) { val project = lambda.project val factory = KtPsiFactory(project) val functionLiteral = lambda.getLambdaExpression()?.functionLiteral val lambdaExtensionReceiver = lambdaDescriptor.extensionReceiverParameter val lambdaDispatchReceiver = lambdaDescriptor.dispatchReceiverParameter var parameterName = "it" val scopes = mutableSetOf<LexicalScope>() if (functionLiteral != null && needUniqueNameForParameter(lambda, scopes)) { val parameterType = lambdaExtensionReceiver?.type ?: lambdaDispatchReceiver?.type parameterName = findUniqueParameterName(parameterType, scopes) replacements.createParameter = { val lambdaParameterList = functionLiteral.getOrCreateParameterList() val parameterToAdd = createLambdaParameterList(parameterName).parameters.first() lambdaParameterList.addParameterBefore(parameterToAdd, lambdaParameterList.parameters.firstOrNull()) } } lambda.accept(object : KtTreeVisitorVoid() { override fun visitSimpleNameExpression(expression: KtSimpleNameExpression) { super.visitSimpleNameExpression(expression) if (expression is KtOperationReferenceExpression) return val resolvedCall = expression.getResolvedCall(bindingContext) ?: return val dispatchReceiverTarget = resolvedCall.dispatchReceiver?.getReceiverTargetDescriptor(bindingContext) val extensionReceiverTarget = resolvedCall.extensionReceiver?.getReceiverTargetDescriptor(bindingContext) if (dispatchReceiverTarget == lambdaDescriptor || extensionReceiverTarget == lambdaDescriptor) { val parent = expression.parent if (parent is KtCallExpression && expression == parent.calleeExpression) { if ((parent.parent as? KtQualifiedExpression)?.receiverExpression !is KtThisExpression) { replacements.add(parent) { element -> factory.createExpressionByPattern("$0.$1", parameterName, element) } } } else if (parent is KtQualifiedExpression && parent.receiverExpression is KtThisExpression) { // do nothing } else { val referencedName = expression.getReferencedName() replacements.add(expression) { createExpression("$parameterName.$referencedName") } } } } override fun visitThisExpression(expression: KtThisExpression) { val resolvedCall = expression.getResolvedCall(bindingContext) ?: return if (resolvedCall.resultingDescriptor == lambdaDispatchReceiver || resolvedCall.resultingDescriptor == lambdaExtensionReceiver ) { replacements.add(expression) { createExpression(parameterName) } } } }) } override fun postprocessLambda(lambda: KtLambdaArgument) { val filter = { element: PsiElement -> if (element is KtThisExpression && element.getLabelName() != null) ShortenReferences.FilterResult.PROCESS else ShortenReferences.FilterResult.GO_INSIDE } ShortenReferences{ ShortenReferences.Options(removeThisLabels = true) }.process(lambda, filter) } private fun needUniqueNameForParameter( lambdaArgument: KtLambdaArgument, scopes: MutableSet<LexicalScope> ): Boolean { val resolutionScope = lambdaArgument.getResolutionScope() scopes.add(resolutionScope) var needUniqueName = false if (resolutionScope.findVariable(Name.identifier("it"), NoLookupLocation.FROM_IDE) != null) { needUniqueName = true // Don't return here - we still need to gather the list of nested scopes } lambdaArgument.accept(object : KtTreeVisitorVoid() { override fun visitDeclaration(dcl: KtDeclaration) { super.visitDeclaration(dcl) checkNeedUniqueName(dcl) } override fun visitLambdaExpression(lambdaExpression: KtLambdaExpression) { super.visitLambdaExpression(lambdaExpression) lambdaExpression.bodyExpression?.statements?.firstOrNull()?.let { checkNeedUniqueName(it) } } private fun checkNeedUniqueName(dcl: KtElement) { val nestedResolutionScope = dcl.getResolutionScope() scopes.add(nestedResolutionScope) if (nestedResolutionScope.findVariable(Name.identifier("it"), NoLookupLocation.FROM_IDE) != null) { needUniqueName = true } } }) return needUniqueName } private fun findUniqueParameterName( parameterType: KotlinType?, resolutionScopes: Collection<LexicalScope> ): String { fun isNameUnique(parameterName: String): Boolean { return resolutionScopes.none { it.findVariable(Name.identifier(parameterName), NoLookupLocation.FROM_IDE) != null } } return if (parameterType != null) KotlinNameSuggester.suggestNamesByType(parameterType, ::isNameUnique).first() else { KotlinNameSuggester.suggestNameByName("p", ::isNameUnique) } } } class ConvertScopeFunctionToReceiver(counterpartName: String) : ConvertScopeFunctionFix(counterpartName) { override fun analyzeLambda( bindingContext: BindingContext, lambda: KtLambdaArgument, lambdaDescriptor: SimpleFunctionDescriptor, replacements: ReplacementCollection ) { lambda.accept(object : KtTreeVisitorVoid() { override fun visitSimpleNameExpression(expression: KtSimpleNameExpression) { super.visitSimpleNameExpression(expression) if (expression.getReferencedName() == "it") { val result = expression.resolveMainReferenceToDescriptors().singleOrNull() if (result is ValueParameterDescriptor && result.containingDeclaration == lambdaDescriptor) { replacements.add(expression) { createThisExpression() } } } else { val resolvedCall = expression.getResolvedCall(bindingContext) ?: return val dispatchReceiver = resolvedCall.dispatchReceiver if (dispatchReceiver is ImplicitReceiver) { val parent = expression.parent val thisLabelName = dispatchReceiver.declarationDescriptor.getThisLabelName() if (parent is KtCallExpression && expression == parent.calleeExpression) { replacements.add(parent) { element -> createExpressionByPattern("this@$0.$1", thisLabelName, element) } } else { val referencedName = expression.getReferencedName() replacements.add(expression) { createExpression("this@$thisLabelName.$referencedName") } } } } } override fun visitThisExpression(expression: KtThisExpression) { val resolvedCall = expression.getResolvedCall(bindingContext) ?: return val qualifierName = resolvedCall.resultingDescriptor.containingDeclaration.name replacements.add(expression) { createThisExpression(qualifierName.asString()) } } }) } override fun postprocessLambda(lambda: KtLambdaArgument) { val filter = { element: PsiElement -> if (element is KtThisExpression && element.getLabelName() != null) ShortenReferences.FilterResult.PROCESS else if (element is KtQualifiedExpression && element.receiverExpression is KtThisExpression) ShortenReferences.FilterResult.PROCESS else ShortenReferences.FilterResult.GO_INSIDE } ShortenReferences { ShortenReferences.Options(removeThis = true, removeThisLabels = true) }.process(lambda, filter) } } private fun PsiElement.startInPlaceRename() { val project = project val document = containingFile.viewProvider.document ?: return val editor = FileEditorManager.getInstance(project).selectedTextEditor ?: return if (editor.document == document) { PsiDocumentManager.getInstance(project).doPostponedOperationsAndUnblockDocument(editor.document) editor.caretModel.moveToOffset(startOffset) KotlinVariableInplaceRenameHandler().doRename(this, editor, null) } }
apache-2.0
3f3980108aad1dfbe2a226585bf38c87
46.163488
158
0.681668
6.101163
false
false
false
false
smmribeiro/intellij-community
notebooks/visualization/src/org/jetbrains/plugins/notebooks/visualization/r/inlays/components/ImageInverter.kt
7
7070
/* * 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 org.jetbrains.plugins.notebooks.visualization.r.inlays.components import com.intellij.util.ui.ImageUtil import java.awt.Color import java.awt.GraphicsConfiguration import java.awt.image.BufferedImage import java.awt.image.IndexColorModel import java.io.ByteArrayInputStream import java.io.ByteArrayOutputStream import javax.imageio.ImageIO import kotlin.math.max import kotlin.math.min class ImageInverter(foreground: Color, background: Color, private val graphicsConfiguration: GraphicsConfiguration? = null) { private val rgb = FloatArray(3) private val hsl = FloatArray(3) private val whiteHsl = FloatArray(3) private val blackHsl = FloatArray(3) init { foreground.getRGBColorComponents(rgb) convertRGBtoHSL(rgb, whiteHsl) background.getRGBColorComponents(rgb) convertRGBtoHSL(rgb, blackHsl) } /** * Check if [image] should be inverted in dark themes. * * @param brightnessThreshold images with average brightness exceeding the threshold will be recommended for inversion * * @return true if it's recommended to invert the image */ fun shouldInvert(image: BufferedImage, brightnessThreshold: Double = 0.7): Boolean { val colors = getImageSample(image) val numberOfColorsInComplexImage = 5000 val numberOfPixels = colors.size val numberOfColorsThreshold = min(numberOfPixels / 3, numberOfColorsInComplexImage) val hasAlpha = image.colorModel.hasAlpha() val averageBrightness = colors.map { getBrightness(it, hasAlpha) }.sum() / numberOfPixels val numberOfColors = colors.toSet() return (averageBrightness > brightnessThreshold && numberOfColors.size < numberOfColorsThreshold) || hasLightBackground(colors, hasAlpha, brightnessThreshold) == true } /** * Get part of image for color analysis. * * For narrow/low images all image pixels are returned. * For regular images the result is a concatenation of areas in image corners and at the central area. */ private fun getImageSample(image: BufferedImage): IntArray { if (image.height < 10 || image.width < 10) { val colors = IntArray(image.height * image.width) image.getRGB(0, 0, image.width, image.height, colors, 0, image.width) return colors } val defaultSpotSize = min(max(image.height / 10, image.width / 10), min(image.height, image.width)) val spotHeight = min(image.height, defaultSpotSize) val spotWidth = min(image.width, defaultSpotSize) val spotSize = spotHeight * spotWidth val colors = IntArray(spotSize * 5) image.getRGB(0, 0, spotWidth, spotHeight, colors, 0, spotWidth) image.getRGB(image.width - spotWidth, 0, spotWidth, spotHeight, colors, spotSize, spotWidth) image.getRGB(0, image.height - spotHeight, spotWidth, spotHeight, colors, 2 * spotSize, spotWidth) image.getRGB(image.width - spotWidth, image.height - spotHeight, spotWidth, spotHeight, colors, 3 * spotSize, spotWidth) // We operate on integers so dividing and multiplication with the same number is not trivial operation val centralSpotX = image.width / spotWidth / 2 * spotWidth val centralSpotY = image.height / spotHeight / 2 * spotHeight image.getRGB(centralSpotX, centralSpotY, spotWidth, spotHeight, colors, 4 * spotSize, spotWidth) return colors } private fun getBrightness(argb: Int, hasAlpha: Boolean): Float { val color = Color(argb, hasAlpha) val hsb = FloatArray(3) Color.RGBtoHSB(color.red, color.green, color.blue, hsb) return hsb[2] } /** * Try to guess whether the image has light background. * * The background is defined as a large fraction of pixels with the same color. */ private fun hasLightBackground(colors: IntArray, hasAlpha: Boolean, brightnessThreshold: Double): Boolean? { val dominantColorPair = colors.groupBy { it }.maxByOrNull { it.value.size } ?: return null val dominantColor = dominantColorPair.key val dominantPixels = dominantColorPair.value return dominantPixels.size.toDouble() / colors.size > 0.5 && getBrightness(dominantColor, hasAlpha) > brightnessThreshold } fun invert(color: Color): Color { val alpha = invert(color.rgb) val argb = convertHSLtoRGB(hsl, alpha) return Color(argb, true) } fun invert(image: BufferedImage): BufferedImage { val width = ImageUtil.getUserWidth(image) val height = ImageUtil.getUserHeight(image) return ImageUtil.createImage(width, height, BufferedImage.TYPE_INT_ARGB).also { outputImage -> invertInPlace(image, outputImage) } } fun invert(content: ByteArray): ByteArray { val image = ImageIO.read(ByteArrayInputStream(content)) ?: return content val outputImage = createImageWithInvertedPalette(image) invertInPlace(image, outputImage) return ByteArrayOutputStream().use { outputStream -> ImageIO.write(outputImage, "png", outputStream) outputStream.flush() outputStream.toByteArray() } } private fun invertInPlace(image: BufferedImage, outputImage: BufferedImage) { val rgbArray = image.getRGB(0, 0, image.width, image.height, null, 0, image.width) if (rgbArray.isEmpty()) return // Usually graph data contains regions with same color. Previous converted color may be reused. var prevArgb = rgbArray[0] var prevConverted = convertHSLtoRGB(hsl, invert(prevArgb)) for (i in rgbArray.indices) { val argb = rgbArray[i] if (argb != prevArgb) { prevArgb = argb prevConverted = convertHSLtoRGB(hsl, invert(argb)) } rgbArray[i] = prevConverted } outputImage.setRGB(0, 0, image.width, image.height, rgbArray, 0, image.width) } private fun createImageWithInvertedPalette(image: BufferedImage): BufferedImage { val model = image.colorModel if (model !is IndexColorModel) { return image } val palette = IntArray(model.mapSize) model.getRGBs(palette) for ((index, argb) in palette.withIndex()) { val alpha = invert(argb) palette[index] = convertHSLtoRGB(hsl, alpha) } return ImageUtil.createImage(graphicsConfiguration, image.width, image.height, BufferedImage.TYPE_BYTE_INDEXED) } // Note: returns alpha, resulting color resides in `hsl` private fun invert(argb: Int): Float { val alpha = ((argb shr 24) and 255) / 255f rgb[R] = ((argb shr 16) and 255) / 255f rgb[G] = ((argb shr 8) and 255) / 255f rgb[B] = ((argb) and 255) / 255f convertRGBtoHSL(rgb, hsl) hsl[SATURATION] = hsl[SATURATION] * (50.0f + whiteHsl[SATURATION]) / 1.5f / 100f hsl[LUMINANCE] = (100 - hsl[LUMINANCE]) * (whiteHsl[LUMINANCE] - blackHsl[LUMINANCE]) / 100f + blackHsl[LUMINANCE] return alpha } companion object { private const val SATURATION = 1 private const val LUMINANCE = 2 private const val R = 0 private const val G = 1 private const val B = 2 } }
apache-2.0
a12117b98b4035d228886067d6e43aba
37.846154
140
0.710467
4.178487
false
false
false
false
DuckDeck/AndroidDemo
app/src/main/java/stan/androiddemo/project/petal/Module/Setting/PetalSettingActivity.kt
1
9341
package stan.androiddemo.project.petal.Module.Setting import android.annotation.TargetApi import android.app.Activity import android.content.Context import android.content.Intent import android.content.res.Configuration import android.media.RingtoneManager import android.net.Uri import android.os.Build import android.os.Bundle import android.preference.* import android.support.v4.app.NavUtils import android.text.TextUtils import android.view.MenuItem import stan.androiddemo.R class PetalSettingActivity : AppCompatPreferenceActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setupActionBar() } /** * Set up the [android.app.ActionBar], if the API is available. */ private fun setupActionBar() { val actionBar = getSupportActionBar() actionBar?.setDisplayHomeAsUpEnabled(true) } override fun onMenuItemSelected(featureId: Int, item: MenuItem): Boolean { val id = item.itemId if (id == android.R.id.home) { if (!super.onMenuItemSelected(featureId, item)) { NavUtils.navigateUpFromSameTask(this) } return true } return super.onMenuItemSelected(featureId, item) } /** * {@inheritDoc} */ override fun onIsMultiPane(): Boolean { return isXLargeTablet(this) } /** * {@inheritDoc} */ @TargetApi(Build.VERSION_CODES.HONEYCOMB) override fun onBuildHeaders(target: List<PreferenceActivity.Header>) { loadHeadersFromResource(R.xml.pref_headers, target) } /** * This method stops fragment injection in malicious applications. * Make sure to deny any unknown fragments here. */ override fun isValidFragment(fragmentName: String): Boolean { return PreferenceFragment::class.java.name == fragmentName || GeneralPreferenceFragment::class.java.name == fragmentName || DataSyncPreferenceFragment::class.java.name == fragmentName || NotificationPreferenceFragment::class.java.name == fragmentName } /** * This fragment shows general preferences only. It is used when the * activity is showing a two-pane settings UI. */ @TargetApi(Build.VERSION_CODES.HONEYCOMB) class GeneralPreferenceFragment : PreferenceFragment() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) addPreferencesFromResource(R.xml.pref_general) setHasOptionsMenu(true) // Bind the summaries of EditText/List/Dialog/Ringtone preferences // to their values. When their values change, their summaries are // updated to reflect the new value, per the Android Design // guidelines. bindPreferenceSummaryToValue(findPreference("example_text")) bindPreferenceSummaryToValue(findPreference("example_list")) } override fun onOptionsItemSelected(item: MenuItem): Boolean { val id = item.itemId if (id == android.R.id.home) { startActivity(Intent(activity, PetalSettingActivity::class.java)) return true } return super.onOptionsItemSelected(item) } } /** * This fragment shows notification preferences only. It is used when the * activity is showing a two-pane settings UI. */ @TargetApi(Build.VERSION_CODES.HONEYCOMB) class NotificationPreferenceFragment : PreferenceFragment() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) addPreferencesFromResource(R.xml.pref_notification) setHasOptionsMenu(true) // Bind the summaries of EditText/List/Dialog/Ringtone preferences // to their values. When their values change, their summaries are // updated to reflect the new value, per the Android Design // guidelines. bindPreferenceSummaryToValue(findPreference("notifications_new_message_ringtone")) } override fun onOptionsItemSelected(item: MenuItem): Boolean { val id = item.itemId if (id == android.R.id.home) { startActivity(Intent(activity, PetalSettingActivity::class.java)) return true } return super.onOptionsItemSelected(item) } } /** * This fragment shows data and sync preferences only. It is used when the * activity is showing a two-pane settings UI. */ @TargetApi(Build.VERSION_CODES.HONEYCOMB) class DataSyncPreferenceFragment : PreferenceFragment() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) addPreferencesFromResource(R.xml.pref_data_sync) setHasOptionsMenu(true) // Bind the summaries of EditText/List/Dialog/Ringtone preferences // to their values. When their values change, their summaries are // updated to reflect the new value, per the Android Design // guidelines. bindPreferenceSummaryToValue(findPreference("sync_frequency")) } override fun onOptionsItemSelected(item: MenuItem): Boolean { val id = item.itemId if (id == android.R.id.home) { startActivity(Intent(activity, PetalSettingActivity::class.java)) return true } return super.onOptionsItemSelected(item) } } companion object { private val sBindPreferenceSummaryToValueListener = Preference.OnPreferenceChangeListener { preference, value -> val stringValue = value.toString() if (preference is ListPreference) { // For list preferences, look up the correct display value in // the preference's 'entries' list. val listPreference = preference val index = listPreference.findIndexOfValue(stringValue) // Set the summary to reflect the new value. preference.setSummary( if (index >= 0) listPreference.entries[index] else null) } else if (preference is RingtonePreference) { // For ringtone preferences, look up the correct display value // using RingtoneManager. if (TextUtils.isEmpty(stringValue)) { // Empty values correspond to 'silent' (no ringtone). preference.setSummary(R.string.pref_ringtone_silent) } else { val ringtone = RingtoneManager.getRingtone( preference.getContext(), Uri.parse(stringValue)) if (ringtone == null) { // Clear the summary if there was a lookup error. preference.setSummary(null) } else { // Set the summary to reflect the new ringtone display // name. val name = ringtone.getTitle(preference.getContext()) preference.setSummary(name) } } } else { // For all other preferences, set the summary to the value's // simple string representation. preference.summary = stringValue } true } /** * Helper method to determine if the device has an extra-large screen. For * example, 10" tablets are extra-large. */ private fun isXLargeTablet(context: Context): Boolean { return context.resources.configuration.screenLayout and Configuration.SCREENLAYOUT_SIZE_MASK >= Configuration.SCREENLAYOUT_SIZE_XLARGE } /** * Binds a preference's summary to its value. More specifically, when the * preference's value is changed, its summary (line of text below the * preference title) is updated to reflect the value. The summary is also * immediately updated upon calling this method. The exact display format is * dependent on the type of preference. * @see .sBindPreferenceSummaryToValueListener */ private fun bindPreferenceSummaryToValue(preference: Preference) { // Set the listener to watch for value changes. preference.onPreferenceChangeListener = sBindPreferenceSummaryToValueListener // Trigger the listener immediately with the preference's // current value. sBindPreferenceSummaryToValueListener.onPreferenceChange(preference, PreferenceManager .getDefaultSharedPreferences(preference.context) .getString(preference.key, "")) } fun launch(activity: Activity) { val intent = Intent(activity, PetalSettingActivity::class.java) // ActivityCompat.startActivity(); activity.startActivity(intent) } } }
mit
6ed7cd33bba14f007982f5b31158d78d
38.083682
146
0.616636
5.737715
false
false
false
false
Werb/PickPhotoSample
pickphotoview/src/main/java/com/werb/pickphotoview/PickPhotoPreviewActivity.kt
1
6967
package com.werb.pickphotoview import android.app.Activity import android.content.Intent import android.os.Build import android.os.Bundle import android.support.annotation.Keep import android.support.v4.view.PagerAdapter import android.support.v4.view.ViewPager import android.view.View import android.view.ViewGroup import android.view.animation.DecelerateInterpolator import com.werb.eventbus.EventBus import com.werb.eventbus.Subscriber import com.werb.pickphotoview.event.PickPreviewEvent import com.werb.pickphotoview.extensions.alphaColor import com.werb.pickphotoview.extensions.color import com.werb.pickphotoview.extensions.string import com.werb.pickphotoview.util.PickConfig import com.werb.pickphotoview.util.PickPhotoHelper import com.werb.pickphotoview.widget.PreviewImage import kotlinx.android.synthetic.main.pick_activty_preview_photo.* import kotlinx.android.synthetic.main.pick_widget_my_toolbar.* /** * Created by wanbo on 2017/1/4. */ @Keep class PickPhotoPreviewActivity : BasePickActivity() { private var path: String? = null private var dir: String? = null private val selectImages = PickPhotoHelper.selectImages private val allImages: List<String> by lazy { allImage() } private val imageViews: List<PreviewImage> by lazy { imageViews() } private var full = false override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) EventBus.register(this) setContentView(R.layout.pick_activty_preview_photo) path = intent.getStringExtra("path") dir = intent.getStringExtra("dir") initToolbar() } override fun onDestroy() { super.onDestroy() EventBus.unRegister(this) } private fun initToolbar() { GlobalData.model?.let { toolbar.setBackgroundColor(color(it.toolbarColor)) statusBar.setBackgroundColor(color(it.statusBarColor)) midTitle.setTextColor(color(it.toolbarTextColor)) cancel.setTextColor(color(it.toolbarTextColor)) if (selectImages.size > 0) { sure.setTextColor(color(it.toolbarTextColor)) } else { sure.setTextColor(alphaColor(color(it.toolbarTextColor))) } sure.text = String.format(string(R.string.pick_photo_sure), selectImages.size) sure.setOnClickListener { add() } cancel.setOnClickListener { finish() } path?.let { val index = allImages.indexOf(it) val all = allImages.size val current = index + 1 midTitle.text = "$current/$all" viewPager.adapter = ListPageAdapter() viewPager.currentItem = index viewPager.addOnPageChangeListener(object : ViewPager.OnPageChangeListener { override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) { } override fun onPageSelected(position: Int) { val i = position + 1 midTitle.text = "$i/$all" } override fun onPageScrollStateChanged(state: Int) { } }) } } } private fun imageViews(): List<PreviewImage> = arrayListOf<PreviewImage>().apply { for (index in 1..4) { add(PreviewImage(this@PickPhotoPreviewActivity)) } } private fun add() { if (selectImages.isNotEmpty()) { finishForResult() } } private fun allImage(): List<String> { val groupImage = PickPhotoHelper.groupImage return groupImage?.mGroupMap?.get(dir) ?: emptyList() } private fun full() { full = !full hideOrShowToolbar() if (full) { window.decorView.systemUiVisibility = View.INVISIBLE } else { window.decorView.systemUiVisibility = View.VISIBLE GlobalData.model?.let { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { if (it.lightStatusBar) { window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN } } } } } private fun hideOrShowToolbar() { appbar.animate() .translationY(if (!full) 0f else -appbar.height.toFloat()) .setInterpolator(DecelerateInterpolator()) .start() } @Subscriber() private fun select(event: PickPreviewEvent) { GlobalData.model?.let { if (selectImages.size > 0) { sure.setTextColor(color(it.toolbarTextColor)) } else { sure.setTextColor(alphaColor(color(it.toolbarTextColor))) } sure.text = String.format(string(R.string.pick_photo_sure), selectImages.size) } if (full) full() } //通过ViewPager实现滑动的图片 private inner class ListPageAdapter : PagerAdapter() { override fun getCount(): Int { return allImages.size } override fun isViewFromObject(view: View, any: Any): Boolean { return view === any } override fun instantiateItem(container: ViewGroup, position: Int): Any { val i = position % 4 val pic = imageViews[i] val params = ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT) val path = allImages[position] pic.setImage(path, this@PickPhotoPreviewActivity::full) container.addView(pic, params) return pic } override fun destroyItem(container: ViewGroup, position: Int, `object`: Any) { val i = position % 4 val imageView = imageViews[i] container.removeView(imageView) imageView.clear() } } companion object { fun startActivity(activity: Activity, requestCode: Int, currentPath: String, dirName: String) { val intent = Intent(activity, PickPhotoPreviewActivity::class.java) intent.putExtra("path", currentPath) intent.putExtra("dir", dirName) activity.startActivityForResult(intent, requestCode) activity.overridePendingTransition(R.anim.activity_anim_right_to_current, R.anim.activity_anim_not_change) } } override fun finish() { super.finish() overridePendingTransition(R.anim.activity_anim_not_change, R.anim.activity_anim_current_to_right) } private fun finishForResult() { val intent = Intent() intent.setClass(this@PickPhotoPreviewActivity, PickPhotoActivity::class.java) setResult(PickConfig.PREVIEW_PHOTO_DATA, intent) finish() } }
apache-2.0
01afe1b188fff62914b64315eeea8779
33.919598
139
0.622536
4.829048
false
false
false
false
sg26565/hott-transmitter-config
MdlViewer/src/main/kotlin/de/treichels/hott/mdlviewer/javafx/JavaFxCurveImageGenerator.kt
1
6459
/** * HoTT Transmitter Config Copyright (C) 2013 Oliver Treichel * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR * A PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with this program. If not, see <http:></http:>//www.gnu.org/licenses/>. */ package de.treichels.hott.mdlviewer.javafx import de.treichels.hott.model.Curve import de.treichels.hott.report.html.CurveImageGenerator import javafx.embed.swing.SwingFXUtils import javafx.scene.canvas.Canvas import javafx.scene.image.Image import javafx.scene.paint.Color import javafx.scene.shape.StrokeLineCap import javafx.scene.shape.StrokeLineJoin import javafx.scene.text.Font import org.apache.commons.math3.analysis.interpolation.SplineInterpolator import tornadofx.* import java.io.ByteArrayOutputStream import java.io.IOException import java.util.* import java.util.concurrent.CountDownLatch import javax.imageio.ImageIO /** * Generate offline PNG image using JavaFX. * * @author Oliver Treichel &lt;[email protected]&gt; */ class JavaFxCurveImageGenerator : CurveImageGenerator { private lateinit var image: Image override fun getImageSource(curve: Curve, scale: Double, description: Boolean): String { val pitchCurve = curve.point[0].position == 0 val canvas = Canvas((10 + 200 * scale), (10 + 250 * scale)) with(canvas.graphicsContext2D) { // clear background fill = Color.WHITE fillRect(0.0, 0.0, (10 + 200 * scale), (10 + 250 * scale)) // draw out limit rect stroke = Color.BLACK strokeRect(5.0, 5.0, (200 * scale), (250 * scale)) // dashed gray lines lineWidth = 1.0 lineCap = StrokeLineCap.BUTT lineJoin = StrokeLineJoin.ROUND miterLimit = 0.0 setLineDashes(5.0, 5.0) stroke = Color.GRAY // +100% and -100% horizontal lines strokeLine(5.0, (5 + 25 * scale), (5 + 200 * scale), (5 + 25 * scale)) strokeLine(5.0, (5 + 225 * scale), (5 + 200 * scale), (5 + 225 * scale)) // horizontal 0% line strokeLine(5.0, (5 + 125 * scale), (5 + 200 * scale), (5 + 125 * scale)) if (!pitchCurve) { // vertical 0% line strokeLine((5 + 100 * scale), 5.0, (5 + 100 * scale), (5 + 250 * scale)) } lineWidth = 1.0 setLineDashes(0.0) font = Font.font("Arial", 12.0) stroke = Color.BLACK val numPoints = curve.point.count { it.isEnabled } val xVals = DoubleArray(numPoints) val yVals = DoubleArray(numPoints) curve.point.filter { it.isEnabled }.forEachIndexed { i, p -> when (i) { 0 -> xVals[i] = if (pitchCurve) 0.0 else -100.0 numPoints - 1 -> xVals[i] = 100.0 else -> xVals[i] = p.position.toDouble() } yVals[i] = p.value.toDouble() // draw dot and point number if (description) { val x0: Double val y0: Double if (pitchCurve) { x0 = 5 + xVals[i] * 2.0 * scale y0 = 5 + (225 - yVals[i] * 2) * scale } else { x0 = 5 + (100 + xVals[i]) * scale y0 = 5 + (125 - yVals[i]) * scale } strokeOval(x0 - 2, y0 - 2, 4.0, 4.0) clearRect(x0 - 6, y0 - 16, 8.0, 12.0) strokeText(Integer.toString(p.number + 1), x0 - 3, y0 - 5) } } lineWidth = 2.0 if (numPoints > 2 && curve.isSmoothing) { // spline interpolate the curve points val s = SplineInterpolator() val function = s.interpolate(xVals, yVals) beginPath() if (pitchCurve) { moveTo(5.0, 5 + (225 - yVals[0] * 2) * scale) var x = 6.0 while (x < 4 + 200 * scale) { lineTo(x, 5 + (225 - function.value((x - 5) / scale / 2.0) * 2) * scale) x++ } } else { moveTo(5.0, 5 + (125 - yVals[0]) * scale) var x = 6.0 while (x < 4 + 200 * scale) { lineTo(x, 5 + (125 - function.value((x - 5) / scale - 100)) * scale) x++ } } stroke() } else { beginPath() if (pitchCurve) { moveTo(5 + xVals[0] * 2.0 * scale, 5 + (225 - yVals[0] * 2) * scale) for (i in 1 until numPoints) { lineTo(5 + xVals[i] * 2.0 * scale, 5 + (225 - yVals[i] * 2) * scale) } } else { moveTo(5 + (100 + xVals[0]) * scale, 5 + (125 - yVals[0]) * scale) for (i in 1 until numPoints) { lineTo(5 + (100 + xVals[i]) * scale, 5 + (125 - yVals[i]) * scale) } } stroke() } } val latch = CountDownLatch(1) // take snapshot on ui thread runLater { image = canvas.snapshot(null, null) latch.countDown() } // wait until snapshot completes latch.await() val renderedImage = SwingFXUtils.fromFXImage(image, null) try { ByteArrayOutputStream().use { baos -> ImageIO.write(renderedImage, "png", baos) return CurveImageGenerator.PREFIX + Base64.getEncoder().encodeToString(baos.toByteArray()) } } catch (e: IOException) { throw RuntimeException(e) } } }
lgpl-3.0
fb7ef3ce08596c7095ffafbd5fcfd395
36.12069
160
0.508128
4.260554
false
false
false
false
datawire/discovery
discovery-gateway/src/main/kotlin/io/datawire/discovery/gateway/DiscoveryGatewayVerticle.kt
1
3217
/* * Copyright 2016 Datawire. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.datawire.discovery.gateway import io.vertx.core.AbstractVerticle import io.vertx.core.http.HttpHeaders import io.vertx.core.http.HttpMethod import io.vertx.core.json.JsonObject import io.vertx.ext.auth.jwt.JWTAuth import io.vertx.ext.web.Router import io.vertx.core.logging.LoggerFactory import io.vertx.ext.web.handler.CorsHandler import io.vertx.ext.web.handler.JWTAuthHandler class DiscoveryGatewayVerticle(): AbstractVerticle() { private val log = LoggerFactory.getLogger(DiscoveryGatewayVerticle::class.java) private val jsonContentType = "application/json; charset=utf-8" override fun start() { log.info("Starting Discovery Gateway") val router = Router.router(vertx) registerHealthCheck(router) registerConnectHandler(router) val server = vertx.createHttpServer() server.requestHandler { router.accept(it) }.listen(config().getInteger("port")) // todo(plombardi): replace with {} syntax once this bug fix is released // // https://github.com/eclipse/vert.x/pull/1282 log.info("Running server on {}", config().getInteger("port")) } private fun registerHealthCheck(router: Router) { log.info("Registering health check (path: /health)") router.get("/health").handler { rc -> rc.response().setStatusCode(200).end() } } private fun registerConnectHandler(router: Router) { log.info("Registering JWT handler") val jwtAuth = JWTAuth.create(vertx, config().getJsonObject("jsonWebToken")) val jwt = JWTAuthHandler.create(jwtAuth, "/health") router.route("/v1/connect*").handler(CorsHandler .create("*") .allowedMethods(setOf(HttpMethod.OPTIONS, HttpMethod.POST)) .allowedHeaders(setOf( HttpHeaders.AUTHORIZATION, HttpHeaders.CONTENT_TYPE, HttpHeaders.CONTENT_LENGTH, HttpHeaders.ORIGIN).map { it.toString() }.toSet()) .allowCredentials(true)) router.post("/v1/connect").handler(jwt) log.info("Registering connector URL") router.post("/v1/connect").produces("application/json").handler { rc -> val response = rc.response()!! vertx.eventBus().send<String>("discovery-resolver", "DEPRECATED") { if (it.succeeded()) { val address = it.result().body() val connectOptions = JsonObject(mapOf( "url" to "ws://$address/v1/messages" )) response.setStatusCode(200).putHeader("content-type", jsonContentType).end(connectOptions.encodePrettily()) } else { response.setStatusCode(500).end() } } } } }
apache-2.0
7f94aa4c5a3527b367ce24e5ddf090bb
32.873684
117
0.69226
4.177922
false
false
false
false
hazuki0x0/YuzuBrowser
legacy/src/main/java/jp/hazuki/yuzubrowser/legacy/action/ActionList.kt
1
3281
/* * Copyright (C) 2017-2019 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.legacy.action import android.os.Parcel import android.os.Parcelable import com.squareup.moshi.JsonEncodingException import com.squareup.moshi.JsonReader import com.squareup.moshi.JsonWriter import jp.hazuki.yuzubrowser.legacy.utils.util.JsonConvertable import okio.Buffer import java.io.EOFException import java.io.IOException import java.util.* class ActionList : ArrayList<Action>, Parcelable, JsonConvertable { constructor() : super() constructor(jsonStr: String) : super() { fromJsonString(jsonStr) } constructor(source: Parcel) : super() { source.readList(this, Action::class.java.classLoader) } override fun describeContents(): Int { return 0 } override fun writeToParcel(dest: Parcel, flags: Int) { dest.writeList(this) } fun add(`object`: SingleAction): Boolean { return add(Action(`object`)) } @Throws(IOException::class) fun writeAction(writer: JsonWriter) { writer.beginArray() for (action in this) { action.writeAction(writer) } writer.endArray() } @Throws(IOException::class) fun loadAction(reader: JsonReader): Boolean { if (reader.peek() != JsonReader.Token.BEGIN_ARRAY) return false reader.beginArray() while (reader.hasNext()) { val action = Action() if (!action.loadAction(reader)) { return if (reader.peek() == JsonReader.Token.END_ARRAY) break else false } add(action) } reader.endArray() return true } override fun toJsonString(): String? { val buffer = Buffer() JsonWriter.of(buffer).use { writeAction(it) } return buffer.readUtf8() } override fun fromJsonString(str: String): Boolean { clear() try { JsonReader.of(Buffer().writeUtf8(str)).use { return loadAction(it) } } catch (e: EOFException) { return false } catch (e: JsonEncodingException) { return false } } companion object { const val serialVersionUID = 4454998466204378989L @JvmField val CREATOR: Parcelable.Creator<ActionList> = object : Parcelable.Creator<ActionList> { override fun createFromParcel(source: Parcel): ActionList { return ActionList(source) } override fun newArray(size: Int): Array<ActionList?> { return arrayOfNulls(size) } } } }
apache-2.0
2eb3f30a8fdc11ac5f0766d7c6a045dd
27.042735
95
0.617799
4.595238
false
false
false
false
AlexandrDrinov/kotlin-koans-edu
src/v_builders/_40_BuildersHowItWorks.kt
8
2040
package v_builders.builders import util.questions.Answer import util.questions.Answer.* fun todoTask40(): Nothing = TODO( """ Task 40. Look at the questions below and give your answers: change 'insertAnswerHere()' in task40's map to your choice (a, b or c). All the constants are imported via 'util.questions.Answer.*', so they can be accessed by name. """ ) fun insertAnswerHere(): Nothing = todoTask40() fun task40() = linkedMapOf<Int, Answer>( /* 1. In the Kotlin code tr { td { text("Product") } td { text("Popularity") } } 'td' is: a. special built-in syntactic construct b. function declaration c. function invocation */ 1 to insertAnswerHere(), /* 2. In the Kotlin code tr (color = "yellow") { td { text("Product") } td { text("Popularity") } } 'color' is: a. new variable declaration b. argument name c. argument value */ 2 to insertAnswerHere(), /* 3. The block { text("Product") } from the previous question is: a. block inside built-in syntax construction 'td' b. function literal (or "lambda") c. something mysterious */ 3 to insertAnswerHere(), /* 4. For the code tr (color = "yellow") { this.td { text("Product") } td { text("Popularity") } } which of the following is true: a. this code doesn't compile b. 'this' refers to an instance of an outer class c. 'this' refers to a receiver parameter TR of the function literal: tr (color = "yellow") { TR.(): Unit -> this.td { text("Product") } } */ 4 to insertAnswerHere() )
mit
18a446326eaf68a73511dcdf78c57fcb
22.181818
102
0.493137
4.604966
false
false
false
false
google/intellij-gn-plugin
src/main/java/com/google/idea/gn/psi/builtin/Template.kt
1
1237
// Copyright (c) 2020 Google LLC All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package com.google.idea.gn.psi.builtin import com.google.idea.gn.GnKeys import com.google.idea.gn.completion.CompletionIdentifier import com.google.idea.gn.psi.* import com.google.idea.gn.psi.Function import com.google.idea.gn.psi.scope.Scope class Template : Function { override fun execute(call: GnCall, targetScope: Scope): GnValue? { val name = GnPsiUtil.evaluateFirstToString(call.exprList, targetScope) ?: return null val func = TemplateFunction(name, call, targetScope) targetScope.installFunction(func) call.putUserData(GnKeys.TEMPLATE_INSTALLED_FUNCTION, func) return null } override val identifierType: CompletionIdentifier.IdentifierType get() = CompletionIdentifier.IdentifierType.FUNCTION override val isBuiltin: Boolean get() = true override val identifierName: String get() = NAME override val postInsertType: CompletionIdentifier.PostInsertType? get() = CompletionIdentifier.PostInsertType.CALL_WITH_STRING companion object { const val NAME = "template" const val TARGET_NAME = "target_name" } }
bsd-3-clause
89bb329b42c74947a51bf7c476df5f74
32.432432
89
0.759903
4.109635
false
false
false
false
oversecio/oversec_crypto
crypto/src/main/java/io/oversec/one/crypto/encoding/ExtendedPaneStringMapperOutputStream.kt
1
782
package io.oversec.one.crypto.encoding import io.oversec.one.crypto.encoding.pad.AbstractPadder import java.io.IOException import java.io.OutputStream class ExtendedPaneStringMapperOutputStream( private val mapping: Array<CharArray>, private val padder: AbstractPadder?, private val spread: Int ) : OutputStream() { private val buf = StringBuilder() private var cntInvisibleChars = 0 val encoded: String get() = buf.toString() @Throws(IOException::class) override fun write(oneByte: Int) { buf.append(mapping[oneByte and 0xFF]) cntInvisibleChars++ if (padder != null && spread > 0 && cntInvisibleChars > spread) { buf.append(padder.nextPaddingChar) cntInvisibleChars = 0 } } }
gpl-3.0
64f148700afa7efe1626de6e5053054f
26.928571
73
0.679028
4.159574
false
false
false
false
oversecio/oversec_crypto
crypto/src/main/java/io/oversec/one/crypto/Help.kt
1
3033
package io.oversec.one.crypto import android.app.Activity import android.content.Context import android.content.Intent import android.content.pm.PackageManager import android.net.Uri object Help { enum class ANCHOR { encparams_pgp, encparams_simple, encparams_sym, main_help, main_apps, main_keys, main_help_acsconfig, symkey_create_pbkdf, symkey_create_random, symkey_create_scan, symkey_details, appconfig_main, appconfig_appearance, appconfig_lab, button_hide_visible, button_hide_hidden, main_settings, button_encrypt_initial, button_encrypt_encryptionparamsremembered, input_insufficientpadding, input_corruptedencoding, bossmode_active, main_padders, settextfailed, button_compose, paste_clipboard, main_help_accessibilitysettingsnotresolvable } fun open(ctx: Context, anchor: ANCHOR?) { open(ctx, anchor?.name) } @JvmOverloads fun open(ctx: Context, anchor: String? = null) { try { var url = anchor if (url == null || !url.startsWith(getUrlIndex(ctx))) { url = getUrlIndex(ctx) + if (anchor == null) "" else "#alias_$anchor" } val i = Intent(Intent.ACTION_VIEW) i.data = Uri.parse(url) //if (!(ctx instanceof Activity)) run { i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK) } ctx.startActivity(i) } catch (e: Exception) { e.printStackTrace() } } private fun getUrlIndex(ctx: Context): String { return "http://" + ctx.getString(R.string.feature_help_host) + "/index.html" } @Throws(PackageManager.NameNotFoundException::class) fun getAnchorForPackageInfos(ctx: Context, packagename: String): String { val packageInfo = ctx.packageManager.getPackageInfo(packagename, 0) val versionNumber = packageInfo.versionCode val packageNameReplaced = packagename.replace('.', '-') return getUrlIndex(ctx) + "#package_" + packageNameReplaced + "$" + versionNumber } fun openForPackage(ctx: Context, packagename: String?) { if (packagename == null) return try { val url = getAnchorForPackageInfos(ctx, packagename) val i = Intent(Intent.ACTION_VIEW) i.data = Uri.parse(url) if (ctx !is Activity) { i.flags = Intent.FLAG_ACTIVITY_NEW_TASK } ctx.startActivity(i) } catch (e: Exception) { e.printStackTrace() } } fun getApplicationName(ctx: Context, packagename: String): CharSequence { return try { val ai = ctx.packageManager.getApplicationInfo(packagename, 0) ctx.packageManager.getApplicationLabel(ai) } catch (e: PackageManager.NameNotFoundException) { packagename } } }
gpl-3.0
3d2296526b4b1bc2f511ec20225b613d
29.029703
131
0.607649
4.345272
false
false
false
false
YouriAckx/AdventOfCode
2017/src/day17/part01.kt
1
428
package day17 fun main(args: Array<String>) { var buffer = mutableListOf(0) val steps = 376 var index = 0 for (i in 1..2017) { index = (index + steps) % i val l = buffer.toList() buffer = l.subList(0, index + 1).toMutableList() buffer.add(i) buffer.addAll(l.subList(index + 1, l.size).toMutableList()) index++ } println(buffer[buffer.indexOf(2017) + 1]) }
gpl-3.0
65b0969ed10e159b41ca860a2bed7be6
25.8125
67
0.570093
3.479675
false
false
false
false
d9n/trypp.support
src/main/code/trypp/support/time/Duration.kt
1
3471
package trypp.support.time import trypp.support.memory.Poolable import trypp.support.time.Duration.Companion.of import trypp.support.time.Duration.Companion.ofMilliseconds import trypp.support.time.Duration.Companion.ofMinutes import trypp.support.time.Duration.Companion.ofSeconds /** * An class which represents a time duration. */ data class Duration /** * Don't construct directly. Use [ofSeconds], [ofMinutes], [ofMilliseconds], or [of] * instead. */ internal constructor(private var milliseconds: Float = 0f) : Poolable { fun getMilliseconds(): Float { return milliseconds } fun setMilliseconds(milliseconds: Float): Duration { this.milliseconds = if (milliseconds > 0f) milliseconds else 0f return this } fun getSeconds(): Float { return milliseconds / 1000f } fun setSeconds(seconds: Float): Duration { setMilliseconds(seconds * 1000f) return this } fun getMinutes(): Float { return getSeconds() / 60f } fun setMinutes(minutes: Float): Duration { setSeconds(minutes * 60f) return this } fun setFrom(duration: Duration): Duration { milliseconds = duration.milliseconds return this } fun addMilliseconds(milliseconds: Float): Duration { setMilliseconds(getMilliseconds() + milliseconds) return this } fun addSeconds(secs: Float): Duration { setSeconds(getSeconds() + secs) return this } fun addMinutes(minutes: Float): Duration { setMinutes(getMinutes() + minutes) return this } fun add(duration: Duration): Duration { setMilliseconds(getMilliseconds() + duration.getMilliseconds()) return this } fun subtractMilliseconds(milliseconds: Float): Duration { setMilliseconds(getMilliseconds() - milliseconds) return this } fun subtractSeconds(secs: Float): Duration { setSeconds(getSeconds() - secs) return this } fun subtractMinutes(minutes: Float): Duration { setMinutes(getMinutes() - minutes) return this } fun subtract(duration: Duration): Duration { setMilliseconds(getMilliseconds() - duration.getMilliseconds()) return this } fun setZero(): Duration { setMilliseconds(0f) return this } val isZero: Boolean get() = milliseconds == 0f /** * Overridden from [Poolable]. Prefer using [setZero] instead for readability. */ override fun reset() { setZero() } override fun toString(): String { return "${getSeconds()}s" } companion object { fun zero(): Duration { return Duration() } fun ofSeconds(secs: Float): Duration { val duration = Duration() duration.setSeconds(secs) return duration } fun ofMinutes(minutes: Float): Duration { val duration = Duration() duration.setMinutes(minutes) return duration } fun ofMilliseconds(milliseconds: Float): Duration { val duration = Duration() duration.setMilliseconds(milliseconds) return duration } fun of(duration: Duration): Duration { val clonedDuration = Duration() clonedDuration.setFrom(duration) return clonedDuration } } }
mit
7452ae060bc62160d180f57084ec7efa
23.971223
84
0.619418
4.994245
false
false
false
false
google/private-compute-libraries
javatests/com/google/android/libraries/pcc/chronicle/codegen/processor/testdata/expectedgeneratedtypes/ExpectedKotlinGeneratedDtd.kt
1
5931
/* * Copyright 2022 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.libraries.pcc.chronicle.codegen.processor.testdata.expectedgeneratedtypes import com.google.android.libraries.pcc.chronicle.api.DeletionTrigger import com.google.android.libraries.pcc.chronicle.api.FieldType import com.google.android.libraries.pcc.chronicle.api.ManagementStrategy import com.google.android.libraries.pcc.chronicle.api.StorageMedia import com.google.android.libraries.pcc.chronicle.api.Trigger import com.google.android.libraries.pcc.chronicle.api.dataTypeDescriptor import com.google.android.libraries.pcc.chronicle.codegen.processor.testdata.annotatedtypes.ExampleKotlinOpaqueType import com.google.android.libraries.pcc.chronicle.codegen.processor.testdata.annotatedtypes.ExampleKotlinType import com.google.android.libraries.pcc.chronicle.codegen.processor.testdata.annotatedtypes.ExampleKotlinTypeReadWriter import com.google.android.libraries.pcc.chronicle.codegen.processor.testdata.annotatedtypes.ExampleKotlinTypeReader import com.google.android.libraries.pcc.chronicle.codegen.processor.testdata.annotatedtypes.ExampleKotlinTypeReaderWithDataCache import com.google.android.libraries.pcc.chronicle.codegen.processor.testdata.annotatedtypes.ExampleKotlinTypeWriter import com.google.android.libraries.pcc.chronicle.codegen.processor.testdata.annotatedtypes.ExampleKotlinTypeWriterWithDataCache import com.google.android.libraries.pcc.chronicle.codegen.processor.testdata.annotatedtypes.ExampleNestedKotlinType import com.google.android.libraries.pcc.chronicle.codegen.processor.testdata.annotatedtypes.ExampleSelfReferentialKotlinType import java.time.Duration @JvmField val EXPECTED_EXAMPLE_KOTLIN_TYPE_GENERATED_DTD = dataTypeDescriptor(ExampleKotlinType::class.qualifiedName!!, cls = ExampleKotlinType::class) { "name" to FieldType.String "amount" to FieldType.Integer "others" to FieldType.List(FieldType.String) "updateTime" to FieldType.Instant "timeSinceLastOpen" to FieldType.Duration "featuresEnabled" to FieldType.List( dataTypeDescriptor(name = "MapStringValueToBooleanValue", Map.Entry::class) { "key" to FieldType.String "value" to FieldType.Boolean } ) "nickName" to FieldType.Nullable(FieldType.String) "categoryAndScore" to FieldType.Tuple(listOf(FieldType.String, FieldType.Double)) "threeThings" to FieldType.Tuple(listOf(FieldType.String, FieldType.Double, FieldType.Boolean)) "status" to FieldType.Enum( "com.google.android.libraries.pcc.chronicle.codegen.processor.testdata." + "annotatedtypes.ExampleKotlinType.Status", listOf("ON", "OFF", "UNKNOWN") ) } @JvmField val EXPECTED_EXAMPLE_NESTED_KOTLIN_TYPE_GENERATED_DTD = dataTypeDescriptor( ExampleNestedKotlinType::class.qualifiedName!!, cls = ExampleNestedKotlinType::class ) { "name" to FieldType.String "nested" to dataTypeDescriptor(ExampleKotlinType::class.qualifiedName!!, cls = ExampleKotlinType::class) { "name" to FieldType.String "amount" to FieldType.Integer "others" to FieldType.List(FieldType.String) "updateTime" to FieldType.Instant "timeSinceLastOpen" to FieldType.Duration "featuresEnabled" to FieldType.List( dataTypeDescriptor(name = "MapStringValueToBooleanValue", Map.Entry::class) { "key" to FieldType.String "value" to FieldType.Boolean } ) "nickName" to FieldType.Nullable(FieldType.String) "categoryAndScore" to FieldType.Tuple(listOf(FieldType.String, FieldType.Double)) "threeThings" to FieldType.Tuple(listOf(FieldType.String, FieldType.Double, FieldType.Boolean)) "status" to FieldType.Enum( "com.google.android.libraries.pcc.chronicle.codegen.processor.testdata." + "annotatedtypes.ExampleKotlinType.Status", listOf("ON", "OFF", "UNKNOWN") ) } } @JvmField val EXPECTED_EXAMPLE_KOTLIN_OPAQUE_TYPE_GENERATED_DTD = dataTypeDescriptor( ExampleKotlinOpaqueType::class.qualifiedName!!, cls = ExampleKotlinOpaqueType::class ) { "name" to FieldType.String "iBinder" to FieldType.Opaque("android.os.IBinder") "activityId" to FieldType.Opaque("android.app.assist.ActivityId") } @JvmField val EXPECTED_EXAMPLE_SELF_REFERENTIAL_KOTLIN_TYPE_GENERATED_DTD = dataTypeDescriptor( ExampleSelfReferentialKotlinType::class.qualifiedName!!, cls = ExampleSelfReferentialKotlinType::class ) { "children" to FieldType.List(FieldType.Reference(ExampleSelfReferentialKotlinType::class.qualifiedName!!)) } val EXPECTED_EXAMPLE_KOTLIN_TYPE_GENERATED_CONNECTIONS = setOf( ExampleKotlinTypeReader::class.java, ExampleKotlinTypeWriter::class.java, ExampleKotlinTypeReadWriter::class.java, ExampleKotlinTypeReaderWithDataCache::class.java, ExampleKotlinTypeWriterWithDataCache::class.java, ) val EXPECTED_EXAMPLE_KOTLIN_TYPE_GENERATED_MAX_ITEMS = 1000 val EXPECTED_EXAMPLE_KOTLIN_TYPE_GENERATED_DATA_CACHE_STORE_MANAGEMENT_STRATEGY = ManagementStrategy.Stored( encrypted = false, media = StorageMedia.MEMORY, ttl = Duration.ofDays(2), deletionTriggers = setOf(DeletionTrigger(Trigger.PACKAGE_UNINSTALLED, "packageName")), )
apache-2.0
00aac18a51dfb094162c38d253b9bb94
43.261194
128
0.75822
4.456048
false
true
false
false
crunchersaspire/worshipsongs
app/src/main/java/org/worshipsongs/dialog/FavouritesDialogFragment.kt
1
2207
package org.worshipsongs.dialog import android.app.Dialog import android.os.Bundle import android.view.ContextThemeWrapper import android.widget.Toast import androidx.appcompat.app.AlertDialog import androidx.fragment.app.DialogFragment import org.worshipsongs.CommonConstants import org.worshipsongs.R import org.worshipsongs.domain.SongDragDrop import org.worshipsongs.service.FavouriteService /** * Author: Seenivasan, Madasamy * version :1.0.0 */ class FavouritesDialogFragment : DialogFragment() { private val favouriteService = FavouriteService() override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { val names = favouriteService.findNames() names.add(0, "New favourite...") val builder = AlertDialog.Builder(ContextThemeWrapper(activity, R.style.DialogTheme)) builder.setTitle(getString(R.string.addToPlayList)) builder.setItems(names.toTypedArray()) { dialog, which -> [email protected](which, names) } return builder.create() } private fun onClick(which: Int, names: List<String>) { val args = arguments val songName = args!!.getString(CommonConstants.TITLE_KEY) val localisedName = args.getString(CommonConstants.LOCALISED_TITLE_KEY) val id = args.getInt(CommonConstants.ID) if (which == 0) { val addFavouritesDialogFragment = AddFavouritesDialogFragment.newInstance(args) addFavouritesDialogFragment.show(activity!!.supportFragmentManager, AddFavouritesDialogFragment::class.java.simpleName) } else { val songDragDrop = SongDragDrop(id.toLong(), songName, false) songDragDrop.tamilTitle = localisedName favouriteService.save(names[which], songDragDrop) Toast.makeText(activity, "Song added to favourite...!", Toast.LENGTH_LONG).show() } } companion object { fun newInstance(bundle: Bundle): FavouritesDialogFragment { val favouritesDialogFragment = FavouritesDialogFragment() favouritesDialogFragment.arguments = bundle return favouritesDialogFragment } } }
apache-2.0
631a10bf09fa1bb30365e40ec39bdc84
32.953846
131
0.705029
5.050343
false
false
false
false
google-developer-training/android-basics-kotlin-inventory-app
app/src/main/java/com/example/inventory/data/ItemRoomDatabase.kt
1
1884
/* * Copyright (C) 2021 The Android Open Source Project. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.inventory.data import android.content.Context import androidx.room.Database import androidx.room.Room import androidx.room.RoomDatabase /** * Database class with a singleton INSTANCE object. */ @Database(entities = [Item::class], version = 1, exportSchema = false) abstract class ItemRoomDatabase : RoomDatabase() { abstract fun itemDao(): ItemDao companion object { @Volatile private var INSTANCE: ItemRoomDatabase? = null fun getDatabase(context: Context): ItemRoomDatabase { // if the INSTANCE is not null, then return it, // if it is, then create the database return INSTANCE ?: synchronized(this) { val instance = Room.databaseBuilder( context.applicationContext, ItemRoomDatabase::class.java, "item_database" ) // Wipes and rebuilds instead of migrating if no Migration object. // Migration is not part of this codelab. .fallbackToDestructiveMigration() .build() INSTANCE = instance // return instance instance } } } }
apache-2.0
6ce94b2583e54acdde80f3340cff0dfa
33.272727
86
0.633758
5.010638
false
false
false
false
lice-lang/lice
src/main/kotlin/org/lice/Lice.kt
1
1230
/** * Created by ice1000 on 2017/2/26. * * @author ice1000 * @since 1.0.0 */ package org.lice import org.lice.core.SymbolList import org.lice.parse.Lexer import org.lice.parse.Parser import org.lice.util.InterpretException import org.lice.util.ParseException import java.io.File import java.nio.file.* object Lice { @JvmOverloads @JvmStatic @Deprecated("Use nio instead", ReplaceWith("run(Paths.get(file.toURI()), symbolList)", "org.lice.Lice.run", "java.nio.file.Paths")) fun run(file: File, symbolList: SymbolList = SymbolList()) = run(Paths.get(file.toURI()), symbolList) @JvmOverloads @JvmStatic fun run(file: Path, symbolList: SymbolList = SymbolList()) = run(String(Files.readAllBytes(file)), symbolList) @JvmOverloads @JvmStatic fun run(code: String, symbolList: SymbolList = SymbolList()): Any? { try { return Parser.parseTokenStream(Lexer(code)).accept(symbolList).eval() } catch (e: ParseException) { e.prettyPrint(code.split("\n")) } catch (e: InterpretException) { e.prettyPrint(code.split("\n")) } return null } @JvmOverloads @JvmStatic fun runBarely(code: String, symbolList: SymbolList = SymbolList()) = Parser.parseTokenStream(Lexer(code)).accept(symbolList).eval() }
gpl-3.0
35b446f8292b4ddd9287d81200563720
26.954545
132
0.722764
3.306452
false
false
false
false
Bastien7/Lux-transport-analyzer
src/main/com/bastien7/transport/analyzer/park/service/implement/ParkStateServiceImpl.kt
1
1904
package com.bastien7.transport.analyzer.park.service.implement import com.bastien7.transport.analyzer.configuration.DataParameters import com.bastien7.transport.analyzer.park.entity.Park import com.bastien7.transport.analyzer.park.entity.ParkState import com.bastien7.transport.analyzer.park.entityTFL.ParkTFL import com.bastien7.transport.analyzer.park.repository.ParkStateRepository import com.bastien7.transport.analyzer.park.service.ParkStateService import com.bastien7.transport.analyzer.park.service.externalApi.ParkTflApi import log import org.springframework.stereotype.Component import java.time.LocalDateTime @Component class ParkStateServiceImpl(val parkTflApi: ParkTflApi, val parkStateRepository: ParkStateRepository) : ParkStateService { val log = log() //@Scheduled(cron = "0 */" + DataParameters.DUMP_FREQUENCY + " * * * *") override fun collectTflData() { val apiResponse = parkTflApi.getAllParksTfl() val parks = apiResponse.map { it.toPark() } val parkState = ParkState(parks) parkStateRepository.save(parkState) log.info("Data collected from TFL api") } override fun getAllParksTfl(): List<ParkTFL> = parkTflApi.getAllParksTfl().sortedBy { it.properties.name } override fun getAllParks(): List<Park> = parkTflApi.getAllParksTfl().map { it.toPark() }.sortedBy { it.name } override fun getAllParkStates(): List<ParkState> = parkStateRepository.findAll().sortedBy { it.date } override fun getParkState(date: LocalDateTime): ParkState? { val reference: LocalDateTime = date.withSecond(0) val result = parkStateRepository.findByDateBetween( reference.minusMinutes((DataParameters.DUMP_FREQUENCY / 2).toLong()), reference.plusMinutes((DataParameters.DUMP_FREQUENCY / 2).toLong()) ) return if (result.isEmpty()) null else result.first() } }
apache-2.0
e5efb84d81531d4f65d62e3fc6b929bb
41.333333
121
0.743172
4.157205
false
false
false
false
android/user-interface-samples
CanonicalLayouts/feed-view/app/src/main/java/com/example/viewbasedfeedlayoutsample/MainActivity.kt
1
2836
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.viewbasedfeedlayoutsample import android.os.Bundle import android.view.ViewGroup import androidx.appcompat.app.AppCompatActivity import androidx.core.view.ViewCompat import androidx.core.view.WindowCompat import androidx.core.view.WindowInsetsCompat import androidx.core.view.updateLayoutParams import androidx.navigation.NavController import androidx.navigation.fragment.NavHostFragment import androidx.navigation.ui.AppBarConfiguration import androidx.navigation.ui.navigateUp import androidx.navigation.ui.setupActionBarWithNavController import com.example.viewbasedfeedlayoutsample.databinding.ActivityMainBinding class MainActivity : AppCompatActivity() { private lateinit var appBarConfiguration: AppBarConfiguration private lateinit var binding: ActivityMainBinding private lateinit var navController: NavController override fun onCreate(savedInstanceState: Bundle?) { WindowCompat.setDecorFitsSystemWindows(window, false) super.onCreate(savedInstanceState) setupContentView() setupActionBar() } override fun onSupportNavigateUp(): Boolean { return navController.navigateUp(appBarConfiguration) || super.onSupportNavigateUp() } private fun setupContentView() { binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) ViewCompat.setOnApplyWindowInsetsListener(binding.root) { view, windowInsets -> val insets = windowInsets.getInsets(WindowInsetsCompat.Type.systemBars()) view.updateLayoutParams<ViewGroup.MarginLayoutParams> { topMargin = insets.top leftMargin = insets.left bottomMargin = insets.bottom rightMargin = insets.right } WindowInsetsCompat.CONSUMED } } private fun setupActionBar() { setSupportActionBar(binding.toolbar) navController = (supportFragmentManager.findFragmentById(R.id.body) as NavHostFragment).navController appBarConfiguration = AppBarConfiguration(navController.graph) setupActionBarWithNavController(navController, appBarConfiguration) } }
apache-2.0
a2589ed73ca06c3d00f67acb380548dd
36.315789
97
0.746474
5.638171
false
true
false
false
ssaqua/ProximityService
app/src/main/kotlin/ss/proximityservice/ProximityService.kt
1
11158
package ss.proximityservice import android.annotation.SuppressLint import android.app.KeyguardManager import android.app.Service import android.content.Context import android.content.Intent import android.graphics.PixelFormat import android.hardware.Sensor import android.hardware.SensorManager import android.net.Uri import android.os.* import android.provider.Settings import android.view.View import android.view.WindowManager import android.widget.FrameLayout import android.widget.Toast import androidx.localbroadcastmanager.content.LocalBroadcastManager import dagger.android.DaggerService import ss.proximityservice.data.AppStorage import ss.proximityservice.data.Mode import ss.proximityservice.data.ProximityDetector import ss.proximityservice.settings.NOTIFICATION_DISMISS import ss.proximityservice.settings.OPERATIONAL_MODE import ss.proximityservice.settings.SCREEN_OFF_DELAY import ss.proximityservice.testing.OpenForTesting import java.util.concurrent.atomic.AtomicInteger import javax.inject.Inject @OpenForTesting class ProximityService : DaggerService(), ProximityDetector.ProximityListener { private val sensorManager: SensorManager by lazy { applicationContext.getSystemService(Context.SENSOR_SERVICE) as SensorManager } private val windowManager by lazy { applicationContext.getSystemService(Context.WINDOW_SERVICE) as WindowManager } private val broadcastManager: LocalBroadcastManager by lazy { LocalBroadcastManager.getInstance(this) } private var proximityDetector: ProximityDetector? = null private var overlay: View? = null @SuppressLint("InlinedApi") private val overlayFlags = (View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY or View.SYSTEM_UI_FLAG_LAYOUT_STABLE or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION or View.SYSTEM_UI_FLAG_FULLSCREEN) private val proximityWakeLock: PowerManager.WakeLock? by lazy { val powerManager = getSystemService(Context.POWER_SERVICE) as PowerManager if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { if (powerManager.isWakeLockLevelSupported(PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK)) { powerManager.newWakeLock(PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK, TAG) } else { null } } else { // no WakeLock level support checking for api < 21 powerManager.newWakeLock(PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK, TAG) } } // using deprecated KeyguardLock as the suggested alternative (WindowManager.LayoutParams flags) // is not suitable for a Service with no user interface private val keyguardLock: KeyguardManager.KeyguardLock by lazy { val keyguardManager = getSystemService(Context.KEYGUARD_SERVICE) as KeyguardManager keyguardManager.newKeyguardLock(TAG) } private val keyguardDisableCount: AtomicInteger = AtomicInteger(0) private val notificationHelper: NotificationHelper by lazy { NotificationHelper(applicationContext) } private val mainHandler: Handler = Handler(Looper.getMainLooper()) private val proximityHandler: Handler = Handler(Looper.myLooper()) @Inject lateinit var appStorage: AppStorage override fun onCreate() { super.onCreate() proximityDetector = ProximityDetector(this) val sensor = sensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY) sensor?.let { sensorManager.registerListener(proximityDetector, it, SensorManager.SENSOR_DELAY_NORMAL) } } override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int { when (intent.action) { INTENT_ACTION_START -> start() INTENT_ACTION_STOP -> stop() } return Service.START_NOT_STICKY } override fun onDestroy() { if (isRunning) stop() sensorManager.unregisterListener(proximityDetector) } // binding not supported override fun onBind(intent: Intent): IBinder? = null override fun onNear() { if (isRunning) { val delay = when (appStorage.getInt(SCREEN_OFF_DELAY, 0)) { 0 -> 0L 1 -> 500L 2 -> 1000L 3 -> 1500L 4 -> 2000L 5 -> 2500L 6 -> 3000L else -> 0L } proximityHandler.postDelayed({ updateProximitySensorMode(true) }, delay) } } override fun onFar() { if (isRunning) { proximityHandler.removeCallbacksAndMessages(null) updateProximitySensorMode(false) } } private fun start() { proximityWakeLock?.let { if (it.isHeld or isRunning) { mainHandler.post { toast("Proximity Service is already active") } } else { mainHandler.post { toast("Proximity Service started") } startForeground(NOTIFICATION_ID, notificationHelper.getRunningNotification()) isRunning = true broadcastManager.sendBroadcast(Intent(INTENT_NOTIFY_ACTIVE)) } } ?: run { mainHandler.post { toast("Proximity WakeLock not supported on this device") } } } private fun stop() { mainHandler.post { toast("Proximity Service stopped") } updateProximitySensorMode(false) isRunning = false broadcastManager.sendBroadcast(Intent(INTENT_NOTIFY_INACTIVE)) stopSelf() if (!appStorage.getBoolean(NOTIFICATION_DISMISS, true)) { notificationHelper.notify(NOTIFICATION_ID, notificationHelper.getStoppedNotification()) } } private fun updateProximitySensorMode(on: Boolean) { when (appStorage.getInt(OPERATIONAL_MODE, Mode.DEFAULT.ordinal)) { Mode.DEFAULT.ordinal -> updateDefaultMode(on) Mode.AMOLED_WAKELOCK.ordinal -> updateAMOLEDMode( on, WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON ) Mode.AMOLED_NO_WAKELOCK.ordinal -> updateAMOLEDMode(on) } } private fun updateDefaultMode(on: Boolean) { overlay?.let { updateAMOLEDMode(false) updateKeyguardMode(true) } proximityWakeLock?.let { wakeLock -> synchronized(wakeLock) { if (on) { if (!wakeLock.isHeld) { wakeLock.acquire() updateKeyguardMode(false) } } else { if (wakeLock.isHeld) { wakeLock.release() updateKeyguardMode(true) } } } } } private fun updateAMOLEDMode(on: Boolean, flags: Int = 0) { proximityWakeLock?.let { wakeLock -> if (wakeLock.isHeld) { wakeLock.release() updateKeyguardMode(true) } } if (on && !checkDrawOverlaySetting()) return synchronized(this) { if (on) { if (overlay == null) { overlay = FrameLayout(this).apply { systemUiVisibility = overlayFlags setTheme(R.style.OverlayTheme) } val params = WindowManager.LayoutParams( WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT, if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) WindowManager.LayoutParams.TYPE_SYSTEM_ALERT else WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY, flags, PixelFormat.OPAQUE ) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) { params.layoutInDisplayCutoutMode = WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES } // simulate SYSTEM_UI_FLAG_IMMERSIVE_STICKY for devices below API 19 if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) { overlay?.setOnSystemUiVisibilityChangeListener { visibility -> if ((visibility and View.SYSTEM_UI_FLAG_FULLSCREEN) == 0) { proximityHandler.postDelayed({ overlay?.systemUiVisibility = overlayFlags }, 2000) } } } windowManager.addView(overlay, params) updateKeyguardMode(true) } } else { overlay?.let { it.systemUiVisibility = (View.SYSTEM_UI_FLAG_LAYOUT_STABLE or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN) windowManager.removeView(it) overlay = null } updateKeyguardMode(false) } } } private fun updateKeyguardMode(on: Boolean) { synchronized(keyguardLock) { if (on) { if (keyguardDisableCount.get() > 0) { if (keyguardDisableCount.decrementAndGet() == 0) { keyguardLock.reenableKeyguard() } } } else { if (keyguardDisableCount.getAndAdd(1) == 0) { keyguardLock.disableKeyguard() } } } } private fun checkDrawOverlaySetting(): Boolean { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) return true val canDrawOverlays = Settings.canDrawOverlays(this) if (!canDrawOverlays) { startActivity( Intent( Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:$packageName") ).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) ) mainHandler.post { toast("AMOLED mode requires the permission for drawing over other apps / appear on top to be turned on") } } return canDrawOverlays } private fun toast(text: String) { Toast.makeText(applicationContext, text, Toast.LENGTH_SHORT).show() } companion object { private const val TAG = "ProximityService:ProximitySensorWakeLock" const val INTENT_ACTION_START = "ss.proximityservice.START" const val INTENT_ACTION_STOP = "ss.proximityservice.STOP" const val INTENT_NOTIFY_ACTIVE = "ss.proximityservice.ACTIVE" const val INTENT_NOTIFY_INACTIVE = "ss.proximityservice.INACTIVE" private const val NOTIFICATION_ID = 1 var isRunning = false } }
apache-2.0
c0d568b1b1dd71a8e18b2be289c7e90b
36.193333
177
0.598584
5.300713
false
false
false
false
vanniktech/Emoji
generator/template/EmojiProviderJvm.kt
1
1030
/* * Copyright (C) 2016 - Niklas Baudy, Ruben Gees, Mario Đanić and contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.vanniktech.emoji.<%= package %> import com.vanniktech.emoji.EmojiCategory import com.vanniktech.emoji.EmojiProvider <%= imports %> class <%= name %>Provider : EmojiProvider { override val categories: Array<EmojiCategory> get() = arrayOf(<% categories.forEach(function(category) { %> <%= category.name %>(),<% }); %> ) override fun release() = Unit }
apache-2.0
ca5a1dc5e575008c6b8c53a4644a4825
33.266667
78
0.714008
4.095618
false
false
false
false
chinachen01/android-demo
app/src/main/kotlin/com/example/chenyong/android_demo/AlgorithmImpl.kt
1
1305
package com.example.chenyong.android_demo /** * Created by focus on 17/1/18. */ class AlgorithmImpl { /** * 计算两个非负整数 p 和 q 的最大公约数:若 q 是 0,则最大公约数为 p。否则,将 p 除以 q得到余数r,p和q的最大公约数即为q和 r 的最大公约数。 */ fun gcd(p: Int, q: Int): Int { if (q == 0) return p else { val r = p % q return gcd(q, r) } } /** * 编写递归代码的重要三点: * 1.递归总有一个最简单的情况--方法的第一条语句总是一个包含return的条件语句 * 2.递归调用总是去尝试解决一个规模更小的子问题,这样递归才能收敛到最简单的情况 * 在下面的代码中,第四个参数和但三个参数的差值一直在缩小 * 3.递归调用的父问题和尝试解决的子问题之间不应该有交集 * 在代码中,两个子问题各自操作的数组部分是不同的 */ fun rank(key: Int, a: IntArray, lo: Int = 0, hi: Int = a.size): Int { if (lo > hi) return -1 val mid = lo + (hi - lo) / 2 if (key < a[mid]) return rank(key, a, lo, mid - 1) else if (key > a[mid]) return rank(key, a, mid + 1, hi) else return mid } }
apache-2.0
99eb7940b664e7735ff1339219bcd7f2
26.090909
87
0.545353
2.362434
false
false
false
false
kotlintest/kotlintest
kotest-core/src/commonMain/kotlin/io/kotest/core/test/Description.kt
1
2914
package io.kotest.core.test /** * The description gives the full path to a [TestCase]. * * It contains the name of every parent, with the root at index 0. * And it includes the name of the test case it represents. * * This is useful when you want to write generic extensions and you * need to be able to filter on certain tests only. * * @param parents each parent test case * @param name the name of this test case */ @Suppress("MemberVisibilityCanBePrivate") data class Description(val parents: List<String>, val name: String) { companion object { /** * Creates a Spec level description object for the given name. */ fun spec(name: String) = Description(emptyList(), name) } fun append(name: String) = Description(this.parents + this.name, name) fun hasParent(description: Description): Boolean = parents.containsAll(description.parents + listOf(description.name)) /** * Returns the parent of this description, unless it is a spec then it will throw */ fun parent(): Description = if (isSpec()) error("Cannot call .parent() on a spec") else Description( parents.dropLast(1), parents.last() ) fun isSpec(): Boolean = parents.isEmpty() fun spec(): Description = spec(parents.first()) fun tail() = if (parents.isEmpty()) throw NoSuchElementException() else Description( parents.drop(1), name ) fun fullName(): String = (parents + listOf(name)).joinToString(" ") /** * Returns a String version of this description, which is * the parents + this name concatenated with slashes. */ fun id(): String = (parents + listOf(name)).joinToString("/") fun names(): List<String> = parents + name fun depth() = names().size /** * Returns true if this instance is the immediate parent of the supplied argument. */ fun isParentOf(description: Description): Boolean = parents + name == description.parents /** * Returns true if this instance is an ancestor (nth-parent) of the supplied argument. */ fun isAncestorOf(description: Description): Boolean { if (isParentOf(description)) return true return if (description.isSpec()) false else { val p = description.parent() isAncestorOf(p) } } /** * Returns true if this instance is on the path to the given descripton. That is, if this * instance is either an ancestor of, of the same as, the given description. */ fun isOnPath(description: Description): Boolean = this == description || this.isAncestorOf(description) fun isDescendentOf(description: Description): Boolean = description.isOnPath(this) /** * Returns true if this test is a top level test. In other words, if the * test has no parents other than the spec itself. */ fun isTopLevel(): Boolean = parents.size == 1 && parent().isSpec() }
apache-2.0
9fa27a341a48ec20a4f6d3da2b0d0925
30.673913
106
0.665408
4.381955
false
true
false
false
anton-okolelov/intellij-rust
src/main/kotlin/org/rust/ide/settings/RsAutoImportOptions.kt
2
1166
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.ide.settings import com.intellij.application.options.editor.AutoImportOptionsProvider import com.intellij.ui.IdeBorderFactory import com.intellij.ui.components.JBCheckBox import com.intellij.ui.layout.panel import org.rust.openapiext.CheckboxDelegate import javax.swing.JComponent class RsAutoImportOptions : AutoImportOptionsProvider { private val showImportPopupCheckbox: JBCheckBox = JBCheckBox("Show import popup") private var showImportPopup: Boolean by CheckboxDelegate(showImportPopupCheckbox) override fun createComponent(): JComponent = panel { row { showImportPopupCheckbox() } }.apply { border = IdeBorderFactory.createTitledBorder("Rust") } override fun isModified(): Boolean { return showImportPopup != RsCodeInsightSettings.getInstance().showImportPopup } override fun apply() { RsCodeInsightSettings.getInstance().showImportPopup = showImportPopup } override fun reset() { showImportPopup = RsCodeInsightSettings.getInstance().showImportPopup } }
mit
2b11a1249b74f0df7d363608b77d9142
32.314286
85
0.765009
5.114035
false
false
false
false
toastkidjp/Jitte
app/src/test/java/jp/toastkid/yobidashi/main/initial/FirstLaunchInitializerTest.kt
1
4394
/* * Copyright (c) 2021 toastkidjp. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompany this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html. */ package jp.toastkid.yobidashi.main.initial import android.content.Context import android.content.SharedPreferences import android.graphics.Color import android.net.Uri import androidx.core.content.ContextCompat import io.mockk.MockKAnnotations import io.mockk.Runs import io.mockk.every import io.mockk.impl.annotations.MockK import io.mockk.just import io.mockk.mockk import io.mockk.mockkConstructor import io.mockk.mockkObject import io.mockk.mockkStatic import io.mockk.spyk import io.mockk.unmockkAll import io.mockk.verify import jp.toastkid.lib.preference.PreferenceApplier import jp.toastkid.search.SearchCategory import jp.toastkid.yobidashi.browser.FaviconFolderProviderService import jp.toastkid.yobidashi.browser.bookmark.BookmarkInitializer import jp.toastkid.yobidashi.settings.background.DefaultBackgroundImagePreparation import jp.toastkid.yobidashi.settings.color.DefaultColorInsertion import org.junit.After import org.junit.Before import org.junit.Test class FirstLaunchInitializerTest { private lateinit var firstLaunchInitializer: FirstLaunchInitializer @MockK private lateinit var context: Context private lateinit var preferenceApplier: PreferenceApplier @MockK private lateinit var defaultColorInsertion: DefaultColorInsertion @MockK private lateinit var faviconFolderProviderService: FaviconFolderProviderService @MockK private lateinit var defaultBackgroundImagePreparation: DefaultBackgroundImagePreparation @MockK private lateinit var sharedPreferences: SharedPreferences @MockK private lateinit var editor: SharedPreferences.Editor @Before fun setUp() { MockKAnnotations.init(this) every { context.getSharedPreferences(any(), any()) }.returns(sharedPreferences) every { sharedPreferences.edit() }.returns(editor) every { editor.putInt(any(), any()) }.returns(editor) every { editor.apply() }.just(Runs) preferenceApplier = spyk(PreferenceApplier(context)) every { preferenceApplier.isFirstLaunch() }.returns(true) every { defaultColorInsertion.insert(any()) }.returns(mockk()) every { faviconFolderProviderService.invoke(any()) }.returns(mockk()) every { defaultBackgroundImagePreparation.invoke(any(), any()) }.returns(mockk()) every { preferenceApplier.setDefaultSearchEngine(any()) }.just(Runs) mockkStatic(ContextCompat::class) every { ContextCompat.getColor(any(), any()) }.returns(Color.CYAN) mockkStatic(Uri::class) val returnValue = mockk<Uri>() every { returnValue.host }.returns("yahoo.co.jp") every { Uri.parse(any()) }.returns(returnValue) mockkObject(SearchCategory) every { SearchCategory.getDefaultCategoryName() }.returns("yahoo") mockkConstructor(BookmarkInitializer::class) every { anyConstructed<BookmarkInitializer>().invoke(any()) }.returns(mockk()) firstLaunchInitializer = FirstLaunchInitializer( context, preferenceApplier, defaultColorInsertion, faviconFolderProviderService, defaultBackgroundImagePreparation ) } @After fun tearDown() { unmockkAll() } @Test fun testInvoke() { firstLaunchInitializer.invoke() verify(exactly = 1) { preferenceApplier.isFirstLaunch() } verify(exactly = 1) { defaultColorInsertion.insert(any()) } verify(exactly = 1) { defaultBackgroundImagePreparation.invoke(any(), any()) } verify(exactly = 1) { preferenceApplier.setDefaultSearchEngine(any()) } } @Test fun test() { every { preferenceApplier.isFirstLaunch() }.returns(false) firstLaunchInitializer.invoke() verify(exactly = 1) { preferenceApplier.isFirstLaunch() } verify(exactly = 0) { defaultColorInsertion.insert(any()) } verify(exactly = 0) { defaultBackgroundImagePreparation.invoke(any(), any()) } verify(exactly = 0) { preferenceApplier.setDefaultSearchEngine(any()) } } }
epl-1.0
4914bca34f664fc6adb8c20cefd0e502
33.880952
93
0.725762
5.021714
false
false
false
false
konachan700/Mew
software/MeWSync/app/src/main/java/com/mewhpm/mewsync/ui/recyclerview/impl/RecyclerViewDevicesImpl.kt
1
5449
package com.mewhpm.mewsync.ui.recyclerview.impl import android.content.Context import android.util.AttributeSet import androidx.core.content.ContextCompat import com.afollestad.materialdialogs.MaterialDialog import com.afollestad.materialdialogs.input.input import com.mewhpm.mewsync.R import com.mewhpm.mewsync.dao.KnownDevicesDao import com.mewhpm.mewsync.data.BleDevice import com.mewhpm.mewsync.ui.recyclerview.RecyclerViewAbstract import com.mewhpm.mewsync.ui.recyclerview.data.TextPairWithIcon import com.mikepenz.google_material_typeface_library.GoogleMaterial import org.jetbrains.anko.alert import org.jetbrains.anko.cancelButton import org.jetbrains.anko.okButton import org.jetbrains.anko.selector class RecyclerViewDevicesImpl : RecyclerViewAbstract<BleDevice> { constructor(context: Context) : super(context) constructor(context: Context, attributeSet: AttributeSet?) : super(context, attributeSet) constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) private val list = ArrayList<Pair<TextPairWithIcon, BleDevice>>() var deleteEvent : (position: Int, item: TextPairWithIcon, obj: BleDevice) -> Unit = { _, _, _ -> throw NotImplementedError("deleteEvent not set") } var setDefaultEvent : (position: Int, item: TextPairWithIcon, obj: BleDevice) -> Unit = { _, _, _ -> throw NotImplementedError("setDefaultEvent not set") } var setDescriptionEvent : (obj: BleDevice, desc: String) -> Unit = { _, _ -> throw NotImplementedError("setDescriptionEvent not set") } var deviceItemClickEvent : (dev : BleDevice) -> Unit = { throw NotImplementedError("deviceItemClickEvent not set") } override fun requestList(): ArrayList<Pair<TextPairWithIcon, BleDevice>> = list override fun onElementClick(position: Int, item: TextPairWithIcon, obj: BleDevice) { deviceItemClickEvent.invoke(obj) } override fun onElementLongClick(position: Int, item: TextPairWithIcon, obj: BleDevice) { if (KnownDevicesDao.isDeviceZero(obj.mac)) { context.alert (title = "Device Zero", message = "Do you really want setup a Device Zero as default?") { okButton { sefDefault(position, item, obj) } cancelButton { } }.show() return } val actions = listOf("Set default", "Change description", "Delete") context.selector("Actions", actions) { _, index -> when (index) { 0 -> sefDefault(position, item, obj) 1 -> { MaterialDialog([email protected]).show { input(allowEmpty = true, prefill = obj.text) { _, text -> item.text = if (text.isBlank()) obj.mac else text.toString() setDescriptionEvent.invoke(obj, text.toString()) [email protected]?.notifyDataSetChanged() } title(R.string.change_desc) positiveButton(R.string.change_description) negativeButton(R.string.back) } } 2 -> { context.alert (title = "Remove device", message = "Do you want delete the device with mac: \"${obj.mac}\" and name \"${obj.name}\"?") { okButton { remove(position, item, obj) } cancelButton { } }.show() } } } } private fun createDataTextPairWithIcon(dev : BleDevice) : TextPairWithIcon { return TextPairWithIcon( icon = if (KnownDevicesDao.isDeviceZero(dev.mac)) GoogleMaterial.Icon.gmd_sd_storage else GoogleMaterial.Icon.gmd_bluetooth, iconColor = ContextCompat.getColor(context, if (dev.default) R.color.colorBrandDefaultElement else R.color.colorBrandDark1), iconSize = 48, text = if (dev.text.isBlank()) dev.mac else dev.text, textColor = ContextCompat.getColor(context, R.color.colorBrandDark2), title = dev.name, titleColor = ContextCompat.getColor(context, R.color.colorBrandBlack) ) } fun add(dev : BleDevice) { val pair = Pair(createDataTextPairWithIcon(dev), dev) list.add(pair) this.adapter?.notifyDataSetChanged() } fun clear() { list.clear() this.adapter?.notifyDataSetChanged() } private fun sefDefault(position: Int, item: TextPairWithIcon, obj: BleDevice) { list.forEach { it.first.iconColor = ContextCompat.getColor(context, R.color.colorBrandDark1) } item.iconColor = ContextCompat.getColor(context, R.color.colorBrandDefaultElement) this.adapter?.notifyDataSetChanged() setDefaultEvent.invoke(position, item, obj) } private fun remove(position: Int, item: TextPairWithIcon, obj: BleDevice) { list.removeAt(position) this.adapter?.notifyDataSetChanged() deleteEvent(position, item, obj) } fun reload() { this.adapter?.notifyDataSetChanged() } override fun create() { super.create() this.adapter = TextPairWithIconAdapterImpl() } }
gpl-3.0
43a3fa94ad3f51b37a994a09800c72ca
43.308943
159
0.627638
4.878245
false
false
false
false
EyeBody/EyeBody
EyeBody2/app/src/main/java/com/example/android/eyebody/camera/ConfirmActivity.kt
1
4886
package com.example.android.eyebody.camera import android.content.Intent import android.net.Uri import android.os.Bundle import android.support.v7.app.AlertDialog import android.support.v7.app.AppCompatActivity import android.widget.Toast import com.example.android.eyebody.MainActivity import com.example.android.eyebody.R import kotlinx.android.synthetic.main.activity_confirm.* import java.io.File import android.widget.EditText class ConfirmActivity : AppCompatActivity() { var frontFileName: String? = null var sideFileName: String? = null var frontImageUri:String="" var sideImageUri:String="" var value:String="" var memoImageDB:memoImageDb?=null var time:String="" override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_confirm) memoImageDB =memoImageDb(baseContext,"memoImage.db",null,1) showImage() saveButtonClicked() deleteButtonClicked() memoButtonClicked() } //찍은 이미지를 화면에 뿌려주는 역할 private fun showImage() { var intent = intent frontImageUri = intent.getStringExtra("frontUri")//front 이미지 uri 받아옴 sideImageUri = intent.getStringExtra("sideUri")//side 이미지 uri frontFileName = intent.extras.getString("frontName")//front 이미지 파일명 sideFileName = intent.extras.getString("sideName")//side 이미지 파일명 time=intent.extras.getString("time") var sideImage = Uri.parse(sideImageUri) var frontImage = Uri.parse(frontImageUri) image_front.setImageURI(frontImage) image_side.setImageURI(sideImage) //이미지 두개 imageview에 맵핑함 } private fun goHomeActivity() { var intent = Intent(this, MainActivity::class.java) startActivity(intent) }//홈으로 돌아감 private fun goCameraActivity() { var intent = Intent(this, CameraActivity::class.java) startActivity(intent) }//카메라 엑티비티로 돌아감 //버튼을 두개로 할 예정 삭제. 저장 //저장버튼이 클릭되면 저장하였습니다 toast창 뜨고 홈으로 돌아감 private fun saveButtonClicked() { button_save.setOnClickListener { Toast.makeText(applicationContext, "저장되었습니다", Toast.LENGTH_SHORT).show() putValuesInDb(time,frontImageUri,sideImageUri,value) goHomeActivity() } } private fun deleteFile() { var frontFile = File(frontFileName) var sideFile = File(sideFileName) frontFile.delete() sideFile.delete() } //삭제버튼 누르면 파일삭제. 다시 찍으시겠습니까?alertDialog뜨고 거절하면 홈으로 아니면 카메라 액티비티로 돌아감 private fun deleteButtonClicked() { button_delete.setOnClickListener { val alertDilog = AlertDialog.Builder(this@ConfirmActivity).create() alertDilog.setTitle("삭제") alertDilog.setMessage("삭제 하시겠습니까?") alertDilog.setButton(AlertDialog.BUTTON_NEUTRAL, "삭제후 다시촬영", { dialogInterface, i -> deleteFile() Toast.makeText(applicationContext, "다시 촬영", Toast.LENGTH_SHORT).show() goCameraActivity() }) alertDilog.setButton(AlertDialog.BUTTON_POSITIVE, "취소", { dialogInterface, j -> })//암것도 안함 alertDilog.setButton(AlertDialog.BUTTON_NEGATIVE, "삭제후 홈으로", { dialogInterface, k -> deleteFile() Toast.makeText(applicationContext, "삭제되었습니다", Toast.LENGTH_SHORT).show() goHomeActivity() }) alertDilog.show() } } private fun memoButtonClicked(){ button_memo.setOnClickListener{ val ad = AlertDialog.Builder(this@ConfirmActivity) ad.setTitle("메모") // 제목 설정 ad.setMessage("메모를 적어주세요") // 내용 설정 // EditText 삽입하기 val et = EditText(this@ConfirmActivity) ad.setView(et) // 확인 버튼 설정 ad.setPositiveButton("저장") { dialog, which -> value = et!!.text.toString() dialog.dismiss() //닫기 } ad.setNegativeButton("닫기") { dialog, which -> dialog.dismiss() //닫기 } // 창 띄우기 ad.show() } } private fun putValuesInDb(time:String, frontImage:String, sideImage:String,memo:String){ memoImageDB!!.insert(time,frontImage,sideImage,memo) } override fun onBackPressed() { super.onBackPressed() goCameraActivity() } }
mit
4cbfa56f9354042a2ebbbd14fa685bee
33.834646
96
0.634494
3.873905
false
false
false
false
wordpress-mobile/WordPress-FluxC-Android
example/src/test/java/org/wordpress/android/fluxc/quickstart/QuickStartStoreTest.kt
2
3847
package org.wordpress.android.fluxc.quickstart import com.yarolegovich.wellsql.WellSql import org.junit.Assert.assertEquals import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner import org.robolectric.RuntimeEnvironment import org.wordpress.android.fluxc.Dispatcher import org.wordpress.android.fluxc.SingleStoreWellSqlConfigForTests import org.wordpress.android.fluxc.model.QuickStartTaskModel import org.wordpress.android.fluxc.persistence.QuickStartSqlUtils import org.wordpress.android.fluxc.store.QuickStartStore import org.wordpress.android.fluxc.store.QuickStartStore.QuickStartNewSiteTask.CHECK_STATS import org.wordpress.android.fluxc.store.QuickStartStore.QuickStartNewSiteTask.CREATE_SITE import org.wordpress.android.fluxc.store.QuickStartStore.QuickStartNewSiteTask.ENABLE_POST_SHARING import org.wordpress.android.fluxc.store.QuickStartStore.QuickStartNewSiteTask.FOLLOW_SITE import org.wordpress.android.fluxc.store.QuickStartStore.QuickStartNewSiteTask.PUBLISH_POST import org.wordpress.android.fluxc.store.QuickStartStore.QuickStartNewSiteTask.REVIEW_PAGES import org.wordpress.android.fluxc.store.QuickStartStore.QuickStartNewSiteTask.UPDATE_SITE_TITLE import org.wordpress.android.fluxc.store.QuickStartStore.QuickStartNewSiteTask.UPLOAD_SITE_ICON import org.wordpress.android.fluxc.store.QuickStartStore.QuickStartNewSiteTask.VIEW_SITE import org.wordpress.android.fluxc.store.QuickStartStore.QuickStartTaskType.CUSTOMIZE import org.wordpress.android.fluxc.store.QuickStartStore.QuickStartTaskType.GROW import org.wordpress.android.fluxc.test @RunWith(RobolectricTestRunner::class) class QuickStartStoreTest { private val testLocalSiteId: Long = 72 private lateinit var quickStartStore: QuickStartStore @Before fun setUp() { val appContext = RuntimeEnvironment.application.applicationContext val config = SingleStoreWellSqlConfigForTests( appContext, listOf(QuickStartTaskModel::class.java), "" ) WellSql.init(config) config.reset() quickStartStore = QuickStartStore(QuickStartSqlUtils(), Dispatcher()) } @Test fun orderOfDoneTasks() = test { // marking tasks as done in random order quickStartStore.setDoneTask(testLocalSiteId, VIEW_SITE, true) quickStartStore.setDoneTask(testLocalSiteId, FOLLOW_SITE, true) quickStartStore.setDoneTask(testLocalSiteId, CREATE_SITE, true) // making sure done tasks are retrieved in a correct order val completedCustomizeTasks = quickStartStore.getCompletedTasksByType(testLocalSiteId, CUSTOMIZE) assertEquals(2, completedCustomizeTasks.size) assertEquals(CREATE_SITE, completedCustomizeTasks[0]) assertEquals(VIEW_SITE, completedCustomizeTasks[1]) val completedGrowTasks = quickStartStore.getCompletedTasksByType(testLocalSiteId, GROW) assertEquals(1, completedGrowTasks.size) assertEquals(FOLLOW_SITE, completedGrowTasks[0]) // making sure undone tasks are retrieved in a correct order val uncompletedCustomizeTasks = quickStartStore.getUncompletedTasksByType(testLocalSiteId, CUSTOMIZE) assertEquals(3, uncompletedCustomizeTasks.size) assertEquals(UPDATE_SITE_TITLE, uncompletedCustomizeTasks[0]) assertEquals(UPLOAD_SITE_ICON, uncompletedCustomizeTasks[1]) assertEquals(REVIEW_PAGES, uncompletedCustomizeTasks[2]) val uncompletedGrowTasks = quickStartStore.getUncompletedTasksByType(testLocalSiteId, GROW) assertEquals(3, uncompletedGrowTasks.size) assertEquals(ENABLE_POST_SHARING, uncompletedGrowTasks[0]) assertEquals(PUBLISH_POST, uncompletedGrowTasks[1]) assertEquals(CHECK_STATS, uncompletedGrowTasks[2]) } }
gpl-2.0
6a6923f2cce691b3399ff04d979b5f96
49.618421
109
0.794645
5.143048
false
true
false
false
chrisbanes/tivi
data/src/main/java/app/tivi/data/resultentities/FollowedShowEntryWithShow.kt
1
2255
/* * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package app.tivi.data.resultentities import androidx.room.Embedded import androidx.room.Ignore import androidx.room.Relation import app.tivi.data.entities.FollowedShowEntry import app.tivi.data.entities.ShowTmdbImage import app.tivi.data.entities.TiviShow import app.tivi.data.entities.findHighestRatedBackdrop import app.tivi.data.entities.findHighestRatedPoster import app.tivi.data.views.FollowedShowsWatchStats import app.tivi.extensions.unsafeLazy import java.util.Objects class FollowedShowEntryWithShow : EntryWithShow<FollowedShowEntry> { @Embedded override lateinit var entry: FollowedShowEntry @Relation(parentColumn = "show_id", entityColumn = "id") override lateinit var relations: List<TiviShow> @Relation(parentColumn = "show_id", entityColumn = "show_id") override lateinit var images: List<ShowTmdbImage> @Suppress("PropertyName") @Relation(parentColumn = "id", entityColumn = "id") lateinit var _stats: List<FollowedShowsWatchStats> val stats: FollowedShowsWatchStats? get() = _stats.firstOrNull() @delegate:Ignore val backdrop: ShowTmdbImage? by unsafeLazy { images.findHighestRatedBackdrop() } @delegate:Ignore override val poster: ShowTmdbImage? by unsafeLazy { images.findHighestRatedPoster() } override fun equals(other: Any?): Boolean = when { other === this -> true other is FollowedShowEntryWithShow -> { entry == other.entry && relations == other.relations && stats == other.stats && images == other.images } else -> false } override fun hashCode(): Int = Objects.hash(entry, relations, stats, images) }
apache-2.0
25d939bcfdf84afc236af721e644cf3a
34.793651
114
0.736142
4.361702
false
false
false
false
JimSeker/ui
Advanced/ArchNavigationDemo_kt/app/src/main/java/edu/cs4730/archnavigationdemo_kt/Fragment_Three.kt
1
1045
package edu.cs4730.archnavigationdemo_kt import android.view.LayoutInflater import android.view.ViewGroup import android.os.Bundle import android.view.View import android.widget.TextView import androidx.fragment.app.Fragment /** * This example receives arguments via the safe_arg version. Note safe args are included in Project build.grade (not module). */ class Fragment_Three : Fragment() { override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // Inflate the layout for this fragment val myView = inflater.inflate(R.layout.fragment__three, container, false) val tv_passed = myView.findViewById<TextView>(R.id.tv_passed) tv_passed.text = Fragment_ThreeArgs.fromBundle(requireArguments()).message val tv_passed2 = myView.findViewById<TextView>(R.id.tv_passed2) val stuff = "Data 2 is " + Fragment_ThreeArgs.fromBundle(requireArguments()).number tv_passed2.text = stuff return myView } }
apache-2.0
5b74ba2965858727b483dd7b0f7e67cd
37.740741
126
0.721531
4.265306
false
false
false
false
italoag/qksms
data/src/main/java/com/moez/QKSMS/receiver/MmsSentReceiver.kt
3
3815
/* * Copyright (C) 2017 Moez Bhatti <[email protected]> * * This file is part of QKSMS. * * QKSMS 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. * * QKSMS 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 QKSMS. If not, see <http://www.gnu.org/licenses/>. */ package com.moez.QKSMS.receiver import android.app.Activity import android.content.BroadcastReceiver import android.content.ContentUris import android.content.ContentValues import android.content.Context import android.content.Intent import android.net.Uri import android.provider.Telephony import com.google.android.mms.MmsException import com.google.android.mms.util_alt.SqliteWrapper import com.klinker.android.send_message.Transaction import com.moez.QKSMS.interactor.SyncMessage import dagger.android.AndroidInjection import timber.log.Timber import java.io.File import javax.inject.Inject class MmsSentReceiver : BroadcastReceiver() { @Inject lateinit var syncMessage: SyncMessage override fun onReceive(context: Context, intent: Intent) { AndroidInjection.inject(this, context) Timber.v("MMS sending result: $resultCode") val uri = Uri.parse(intent.getStringExtra(Transaction.EXTRA_CONTENT_URI)) Timber.v(uri.toString()) when (resultCode) { Activity.RESULT_OK -> { Timber.v("MMS has finished sending, marking it as so in the database") val values = ContentValues(1) values.put(Telephony.Mms.MESSAGE_BOX, Telephony.Mms.MESSAGE_BOX_SENT) SqliteWrapper.update(context, context.contentResolver, uri, values, null, null) } else -> { Timber.v("MMS has failed to send, marking it as so in the database") try { val messageId = ContentUris.parseId(uri) val values = ContentValues(1) values.put(Telephony.Mms.MESSAGE_BOX, Telephony.Mms.MESSAGE_BOX_FAILED) SqliteWrapper.update(context, context.contentResolver, Telephony.Mms.CONTENT_URI, values, "${Telephony.Mms._ID} = ?", arrayOf(messageId.toString())) // TODO this query isn't able to find any results // Need to figure out why the message isn't appearing in the PendingMessages Uri, // so that we can properly assign the error type val errorTypeValues = ContentValues(1) errorTypeValues.put(Telephony.MmsSms.PendingMessages.ERROR_TYPE, Telephony.MmsSms.ERR_TYPE_GENERIC_PERMANENT) SqliteWrapper.update(context, context.contentResolver, Telephony.MmsSms.PendingMessages.CONTENT_URI, errorTypeValues, "${Telephony.MmsSms.PendingMessages.MSG_ID} = ?", arrayOf(messageId.toString())) } catch (e: MmsException) { e.printStackTrace() } } } val filePath = intent.getStringExtra(Transaction.EXTRA_FILE_PATH) Timber.v(filePath) File(filePath).delete() Uri.parse(intent.getStringExtra("content_uri"))?.let { uri -> val pendingResult = goAsync() syncMessage.execute(uri) { pendingResult.finish() } } } }
gpl-3.0
a9fe2f86963977c6ab7d8753598b743b
40.032258
120
0.651114
4.607488
false
false
false
false
square/moshi
moshi/src/main/java/com/squareup/moshi/JsonValueReader.kt
1
12108
/* * Copyright (C) 2017 Square, 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.squareup.moshi import com.squareup.moshi.JsonValueReader.JsonIterator import com.squareup.moshi.internal.knownNotNull import okio.Buffer import okio.BufferedSource import java.math.BigDecimal /** Sentinel object pushed on [JsonValueReader.stack] when the reader is closed. */ private val JSON_READER_CLOSED = Any() /** * This class reads a JSON document by traversing a Java object comprising maps, lists, and JSON * primitives. It does depth-first traversal keeping a stack starting with the root object. During * traversal a stack tracks the current position in the document: * * The next element to act upon is on the top of the stack. * * When the top of the stack is a [List], calling [beginArray] replaces the list with a [JsonIterator]. The first * element of the iterator is pushed on top of the iterator. * * Similarly, when the top of the stack is a [Map], calling [beginObject] replaces the map with an [JsonIterator] * of its entries. The first element of the iterator is pushed on top of the iterator. * * When the top of the stack is a [Map.Entry], calling [nextName] returns the entry's key and replaces the entry * with its value on the stack. * * When an element is consumed it is popped. If the new top of the stack has a non-exhausted iterator, the next * element of that iterator is pushed. * * If the top of the stack is an exhausted iterator, calling [endArray] or [endObject] will pop it. */ internal class JsonValueReader : JsonReader { private var stack: Array<Any?> constructor(root: Any?) { scopes[stackSize] = JsonScope.NONEMPTY_DOCUMENT stack = arrayOfNulls(32) stack[stackSize++] = root } /** Copy-constructor makes a deep copy for peeking. */ constructor(copyFrom: JsonValueReader) : super(copyFrom) { stack = copyFrom.stack.clone() for (i in 0 until stackSize) { val element = stack[i] if (element is JsonIterator) { stack[i] = element.clone() } } } override fun beginArray() { val peeked = require<List<*>>(Token.BEGIN_ARRAY) val iterator = JsonIterator(Token.END_ARRAY, peeked.toTypedArray(), 0) stack[stackSize - 1] = iterator scopes[stackSize - 1] = JsonScope.EMPTY_ARRAY pathIndices[stackSize - 1] = 0 // If the iterator isn't empty push its first value onto the stack. if (iterator.hasNext()) { push(iterator.next()) } } override fun endArray() { val peeked = require<JsonIterator>(Token.END_ARRAY) if (peeked.endToken != Token.END_ARRAY || peeked.hasNext()) { throw typeMismatch(peeked, Token.END_ARRAY) } remove() } override fun beginObject() { val peeked = require<Map<*, *>>(Token.BEGIN_OBJECT) val iterator = JsonIterator(Token.END_OBJECT, peeked.entries.toTypedArray(), 0) stack[stackSize - 1] = iterator scopes[stackSize - 1] = JsonScope.EMPTY_OBJECT // If the iterator isn't empty push its first value onto the stack. if (iterator.hasNext()) { push(iterator.next()) } } override fun endObject() { val peeked = require<JsonIterator>(Token.END_OBJECT) if (peeked.endToken != Token.END_OBJECT || peeked.hasNext()) { throw typeMismatch(peeked, Token.END_OBJECT) } pathNames[stackSize - 1] = null remove() } override fun hasNext(): Boolean { if (stackSize == 0) return false val peeked = stack[stackSize - 1] return peeked !is Iterator<*> || peeked.hasNext() } override fun peek(): Token { if (stackSize == 0) return Token.END_DOCUMENT // If the top of the stack is an iterator, take its first element and push it on the stack. return when (val peeked = stack[stackSize - 1]) { is JsonIterator -> peeked.endToken is List<*> -> Token.BEGIN_ARRAY is Map<*, *> -> Token.BEGIN_OBJECT is Map.Entry<*, *> -> Token.NAME is String -> Token.STRING is Boolean -> Token.BOOLEAN is Number -> Token.NUMBER null -> Token.NULL else -> ifNotClosed(peeked) { throw typeMismatch(peeked, "a JSON value") } } } override fun nextName(): String { val peeked = require<Map.Entry<*, *>>(Token.NAME) // Swap the Map.Entry for its value on the stack and return its key. val result = stringKey(peeked) stack[stackSize - 1] = peeked.value pathNames[stackSize - 2] = result return result } override fun selectName(options: Options): Int { val peeked = require<Map.Entry<*, *>>(Token.NAME) val name = stringKey(peeked) for (i in options.strings.indices) { // Swap the Map.Entry for its value on the stack and return its key. if (options.strings[i] == name) { stack[stackSize - 1] = peeked.value pathNames[stackSize - 2] = name return i } } return -1 } override fun skipName() { if (failOnUnknown) { // Capture the peeked value before nextName() since it will reset its value. val peeked = peek() nextName() // Move the path forward onto the offending name. throw JsonDataException("Cannot skip unexpected $peeked at $path") } val (_, value) = require<Map.Entry<*, *>>(Token.NAME) // Swap the Map.Entry for its value on the stack. stack[stackSize - 1] = value pathNames[stackSize - 2] = "null" } override fun nextString(): String { return when (val peeked = if (stackSize != 0) stack[stackSize - 1] else null) { is String -> { remove() peeked } is Number -> { remove() peeked.toString() } else -> ifNotClosed(peeked) { throw typeMismatch(peeked, Token.STRING) } } } override fun selectString(options: Options): Int { val peeked = if (stackSize != 0) stack[stackSize - 1] else null if (peeked !is String) { ifNotClosed(peeked) { -1 } } for (i in options.strings.indices) { if (options.strings[i] == peeked) { remove() return i } } return -1 } override fun nextBoolean(): Boolean { val peeked = require<Boolean>(Token.BOOLEAN) remove() return peeked } override fun <T> nextNull(): T? { requireNull() remove() return null } override fun nextDouble(): Double { val result = when (val peeked = require<Any>(Token.NUMBER)) { is Number -> peeked.toDouble() is String -> { try { peeked.toDouble() } catch (e: NumberFormatException) { throw typeMismatch(peeked, Token.NUMBER) } } else -> { throw typeMismatch(peeked, Token.NUMBER) } } if (!lenient && (result.isNaN() || result.isInfinite())) { throw JsonEncodingException("JSON forbids NaN and infinities: $result at path $path") } remove() return result } override fun nextLong(): Long { val result: Long = when (val peeked = require<Any>(Token.NUMBER)) { is Number -> peeked.toLong() is String -> try { peeked.toLong() } catch (e: NumberFormatException) { try { BigDecimal(peeked).longValueExact() } catch (e2: NumberFormatException) { throw typeMismatch(peeked, Token.NUMBER) } } else -> throw typeMismatch(peeked, Token.NUMBER) } remove() return result } override fun nextInt(): Int { val result = when (val peeked = require<Any>(Token.NUMBER)) { is Number -> peeked.toInt() is String -> try { peeked.toInt() } catch (e: NumberFormatException) { try { BigDecimal(peeked).intValueExact() } catch (e2: NumberFormatException) { throw typeMismatch(peeked, Token.NUMBER) } } else -> throw typeMismatch(peeked, Token.NUMBER) } remove() return result } override fun skipValue() { if (failOnUnknown) { throw JsonDataException("Cannot skip unexpected ${peek()} at $path") } // If this element is in an object clear out the key. if (stackSize > 1) { pathNames[stackSize - 2] = "null" } val skipped = if (stackSize != 0) stack[stackSize - 1] else null if (skipped is JsonIterator) { throw JsonDataException("Expected a value but was ${peek()} at path $path") } if (skipped is Map.Entry<*, *>) { // We're skipping a name. Promote the map entry's value. val entry = stack[stackSize - 1] as Map.Entry<*, *> stack[stackSize - 1] = entry.value } else if (stackSize > 0) { // We're skipping a value. remove() } else { throw JsonDataException("Expected a value but was ${peek()} at path $path") } } override fun nextSource(): BufferedSource { val value = readJsonValue() val result = Buffer() JsonWriter.of(result).use { jsonWriter -> jsonWriter.jsonValue(value) } return result } override fun peekJson(): JsonReader = JsonValueReader(this) override fun promoteNameToValue() { if (hasNext()) { val name = nextName() push(name) } } override fun close() { stack.fill(null, 0, stackSize) stack[0] = JSON_READER_CLOSED scopes[0] = JsonScope.CLOSED stackSize = 1 } private fun push(newTop: Any?) { if (stackSize == stack.size) { if (stackSize == 256) { throw JsonDataException("Nesting too deep at $path") } scopes = scopes.copyOf(scopes.size * 2) pathNames = pathNames.copyOf(pathNames.size * 2) pathIndices = pathIndices.copyOf(pathIndices.size * 2) stack = stack.copyOf(stack.size * 2) } stack[stackSize++] = newTop } private inline fun <reified T> require(expected: Token): T = knownNotNull(require(T::class.java, expected)) private fun requireNull() = require(Void::class.java, Token.NULL) /** * Returns the top of the stack which is required to be a `type`. Throws if this reader is * closed, or if the type isn't what was expected. */ private fun <T> require(type: Class<T>, expected: Token): T? { val peeked = if (stackSize != 0) stack[stackSize - 1] else null if (type.isInstance(peeked)) { return type.cast(peeked) } if (peeked == null && expected == Token.NULL) { return null } ifNotClosed(peeked) { throw typeMismatch(peeked, expected) } } private fun stringKey(entry: Map.Entry<*, *>): String { val name = entry.key if (name is String) return name throw typeMismatch(name, Token.NAME) } private inline fun <T> ifNotClosed(peeked: Any?, body: () -> T): T { check(peeked !== JSON_READER_CLOSED) { "JsonReader is closed" } return body() } /** * Removes a value and prepares for the next. If we're iterating a map or list this advances the * iterator. */ private fun remove() { stackSize-- stack[stackSize] = null scopes[stackSize] = 0 // If we're iterating an array or an object push its next element on to the stack. if (stackSize > 0) { pathIndices[stackSize - 1]++ val parent = stack[stackSize - 1] if (parent is Iterator<*> && parent.hasNext()) { push(parent.next()) } } } internal class JsonIterator( val endToken: Token, val array: Array<Any?>, var next: Int ) : Iterator<Any?>, Cloneable { override fun hasNext() = next < array.size override fun next() = array[next++] // No need to copy the array; it's read-only. public override fun clone() = JsonIterator(endToken, array, next) } }
apache-2.0
42e7b31973e2c3942725ffc9936f3638
29.80916
116
0.633796
4.091923
false
false
false
false
septemberboy7/MDetect
mdetect/src/main/java/me/myatminsoe/mdetect/JobExecutor.kt
1
1536
package me.myatminsoe.mdetect import java.util.concurrent.BlockingQueue import java.util.concurrent.Executor import java.util.concurrent.LinkedBlockingQueue import java.util.concurrent.ThreadFactory import java.util.concurrent.ThreadPoolExecutor import java.util.concurrent.TimeUnit class JobExecutor : Executor { private val workQueue: BlockingQueue<Runnable> private val threadPoolExecutor: ThreadPoolExecutor private val threadFactory: ThreadFactory init { this.workQueue = LinkedBlockingQueue() this.threadFactory = JobThreadFactory() this.threadPoolExecutor = ThreadPoolExecutor( INITIAL_POOL_SIZE, MAX_POOL_SIZE, KEEP_ALIVE_TIME.toLong(), KEEP_ALIVE_TIME_UNIT, this.workQueue, this.threadFactory ) } override fun execute(runnable: Runnable?) { if (runnable == null) { throw IllegalArgumentException("Runnable to execute cannot be null") } this.threadPoolExecutor.execute(runnable) } private class JobThreadFactory : ThreadFactory { private var counter = 0 override fun newThread(runnable: Runnable): Thread { return Thread(runnable, THREAD_NAME + counter++) } companion object { private val THREAD_NAME = "android_" } } companion object { private val INITIAL_POOL_SIZE = 3 private val MAX_POOL_SIZE = 5 // Sets the amount of time an idle thread waits before terminating private val KEEP_ALIVE_TIME = 10 // Sets the Time Unit to seconds private val KEEP_ALIVE_TIME_UNIT = TimeUnit.SECONDS } }
mit
d64474be074ad0605125f7aaabf6ca5d
25.947368
74
0.733073
4.612613
false
false
false
false
openhab/openhab.android
mobile/src/main/java/org/openhab/habdroid/model/ParsedState.kt
1
7041
/* * Copyright (c) 2010-2022 Contributors to the openHAB project * * See the NOTICE file(s) distributed with this work for additional * information. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 */ package org.openhab.habdroid.model import android.graphics.Color import android.location.Location import android.os.Parcelable import java.util.IllegalFormatException import java.util.Locale import java.util.regex.Pattern import kotlin.math.roundToInt import kotlinx.parcelize.Parcelize @Parcelize data class HsvState internal constructor(val hue: Float, val saturation: Float, val value: Float) : Parcelable { fun toColor(includeValue: Boolean = true): Int { return Color.HSVToColor(floatArrayOf(hue, saturation, if (includeValue) value else 100F)) } } @Parcelize data class ParsedState internal constructor( val asString: String, val asBoolean: Boolean, val asNumber: NumberState?, val asHsv: HsvState?, val asBrightness: Int?, val asLocation: Location? ) : Parcelable { override fun equals(other: Any?): Boolean { return other is ParsedState && asString == other.asString } override fun hashCode(): Int { return asString.hashCode() } companion object { internal fun parseAsBoolean(state: String): Boolean { // If state is ON for switches return True if (state == "ON") { return true } val brightness = parseAsBrightness(state) if (brightness != null) { return brightness != 0 } return try { val decimalValue = Integer.valueOf(state) decimalValue > 0 } catch (e: NumberFormatException) { false } } internal fun parseAsNumber(state: String, format: String?): NumberState? { return when (state) { "ON" -> NumberState(100F) "OFF" -> NumberState(0F) else -> { val brightness = parseAsBrightness(state) if (brightness != null) { NumberState(brightness.toFloat()) } else { val spacePos = state.indexOf(' ') val number = if (spacePos >= 0) state.substring(0, spacePos) else state val unit = if (spacePos >= 0) state.substring(spacePos + 1) else null return try { NumberState(number.toFloat(), unit, format) } catch (e: NumberFormatException) { null } } } } } internal fun parseAsHsv(state: String): HsvState? { val stateSplit = state.split(",") if (stateSplit.size == 3) { // We need exactly 3 numbers to operate this try { return HsvState(stateSplit[0].toFloat(), stateSplit[1].toFloat() / 100, stateSplit[2].toFloat() / 100) } catch (e: NumberFormatException) { // fall through } } return null } internal fun parseAsLocation(state: String): Location? { val splitState = state.split(",") // Valid states are either "latitude,longitude" or "latitude,longitude,elevation", if (splitState.size == 2 || splitState.size == 3) { try { val l = Location("openhab") l.latitude = splitState[0].toDouble() l.longitude = splitState[1].toDouble() l.time = System.currentTimeMillis() if (splitState.size == 3) { l.altitude = splitState[2].toDouble() } // Do our best to avoid parsing e.g. HSV values into location by // sanity checking the values if (Math.abs(l.latitude) <= 90 && Math.abs(l.longitude) <= 180) { return l } } catch (e: NumberFormatException) { // ignored } } return null } internal fun parseAsBrightness(state: String): Int? { val hsbMatcher = HSB_PATTERN.matcher(state) if (hsbMatcher.find()) { try { return hsbMatcher.group(3)?.toFloat()?.roundToInt() } catch (e: NumberFormatException) { // fall through } } return null } private val HSB_PATTERN = Pattern.compile("^([0-9]*\\.?[0-9]+),([0-9]*\\.?[0-9]+),([0-9]*\\.?[0-9]+)$") } @Parcelize class NumberState internal constructor( val value: Float, val unit: String? = null, val format: String? = null ) : Parcelable { override fun toString(): String { return toString(Locale.getDefault()) } /** * Like [toString][.toString], but using a specific locale for formatting. */ fun toString(locale: Locale): String { if (!format.isNullOrEmpty()) { val actualFormat = format.replace("%unit%", unit.orEmpty()) try { return String.format(locale, actualFormat, getActualValue()) } catch (e: IllegalFormatException) { // State format pattern doesn't match the actual data type // -> ignore and fall back to our own formatting } } return if (unit == null) formatValue() else "${formatValue()} $unit" } fun formatValue(): String { return getActualValue().toString() } private fun getActualValue(): Number { return if (format != null && format.contains("%d")) value.roundToInt() else value } } } fun ParsedState.NumberState?.withValue(value: Float): ParsedState.NumberState { return ParsedState.NumberState(value, this?.unit, this?.format) } /** * Parses a state string into the parsed representation. * * @param numberPattern Format to use when parsing the input as number * @return null if state string is null, parsed representation otherwise */ fun String?.toParsedState(numberPattern: String? = null): ParsedState? { if (this == null) { return null } return ParsedState(this, ParsedState.parseAsBoolean(this), ParsedState.parseAsNumber(this, numberPattern), ParsedState.parseAsHsv(this), ParsedState.parseAsBrightness(this), ParsedState.parseAsLocation(this)) }
epl-1.0
a99410673f9d1ea111643110844d6c66
34.38191
112
0.540832
4.979491
false
false
false
false
vilnius/tvarkau-vilniu
app/src/main/java/lt/vilnius/tvarkau/prefs/AppPreferencesImpl.kt
1
2538
package lt.vilnius.tvarkau.prefs import android.content.SharedPreferences import com.vinted.preferx.PreferxSerializer import com.vinted.preferx.longPreference import com.vinted.preferx.objectPreference import com.vinted.preferx.stringPreference import lt.vilnius.tvarkau.auth.ApiToken import lt.vilnius.tvarkau.data.GsonSerializer import lt.vilnius.tvarkau.entity.City import java.lang.reflect.Type class AppPreferencesImpl( private val preferences: SharedPreferences, private val gsonSerializer: GsonSerializer ) : AppPreferences { private val serializer = object : PreferxSerializer { override fun fromString(string: String, type: Type): Any { return gsonSerializer.fromJsonType(string, type) } override fun toString(value: Any): String { return gsonSerializer.toJson(value) } } override val apiToken by lazy { preferences.objectPreference( name = API_TOKEN, defaultValue = ApiToken(), serializer = serializer, clazz = ApiToken::class.java ) } override val photoInstructionsLastSeen by lazy { preferences.longPreference(LAST_DISPLAYED_PHOTO_INSTRUCTIONS, 0L) } override val reportStatusSelectedFilter by lazy { preferences.stringPreference(SELECTED_FILTER_REPORT_STATUS, "") } override val reportTypeSelectedFilter by lazy { preferences.stringPreference(SELECTED_FILTER_REPORT_TYPE, "") } override val reportStatusSelectedListFilter by lazy { preferences.stringPreference(LIST_SELECTED_FILTER_REPORT_STATUS, "") } override val reportTypeSelectedListFilter by lazy { preferences.stringPreference(LIST_SELECTED_FILTER_REPORT_TYPE, "") } override val selectedCity by lazy { preferences.objectPreference( name = SELECTED_CITY, defaultValue = City.NOT_SELECTED, serializer = serializer, clazz = City::class.java ) } companion object { const val API_TOKEN = "api_token" const val SELECTED_CITY = "selected_city" const val SELECTED_FILTER_REPORT_STATUS = "filter_report_status" const val SELECTED_FILTER_REPORT_TYPE = "filter_report_type" const val LIST_SELECTED_FILTER_REPORT_STATUS = "list_filter_report_status" const val LIST_SELECTED_FILTER_REPORT_TYPE = "list_filter_report_type" const val LAST_DISPLAYED_PHOTO_INSTRUCTIONS = "last_displayed_photo_instructions" } }
mit
3dbe348965ea36951173cd906e251d84
32.84
89
0.694247
4.548387
false
false
false
false
matkoniecz/StreetComplete
app/src/main/java/de/westnordost/streetcomplete/quests/parking_access/AddParkingAccess.kt
1
1622
package de.westnordost.streetcomplete.quests.parking_access import de.westnordost.streetcomplete.R import de.westnordost.streetcomplete.data.osm.osmquests.OsmFilterQuestType import de.westnordost.streetcomplete.data.osm.edits.update_tags.StringMapChangesBuilder import de.westnordost.streetcomplete.data.user.achievements.QuestTypeAchievement.CAR class AddParkingAccess : OsmFilterQuestType<ParkingAccess>() { // Exclude parking=street_side lacking any access tags, because most of // these are found alongside public access roads, and likely will be // access=yes by default. Leaving these in makes this quest repetitive and // leads to users adding lots of redundant access=yes tags to satisfy the // quest. parking=street_side with access=unknown seems like a valid target // though. // // Cf. #2408: Parking access might omit parking=street_side override val elementFilter = """ nodes, ways, relations with amenity = parking and ( access = unknown or (!access and parking !~ street_side|lane) ) """ override val commitMessage = "Add type of parking access" override val wikiLink = "Tag:amenity=parking" override val icon = R.drawable.ic_quest_parking_access override val questTypeAchievements = listOf(CAR) override fun getTitle(tags: Map<String, String>) = R.string.quest_parking_access_title override fun createForm() = AddParkingAccessForm() override fun applyAnswerTo(answer: ParkingAccess, changes: StringMapChangesBuilder) { changes.addOrModify("access", answer.osmValue) } }
gpl-3.0
ce1efc48ae256667c9dbacec7a9554dc
40.589744
90
0.736128
4.701449
false
false
false
false
wleroux/fracturedskies
src/main/kotlin/com/fracturedskies/render/common/components/gl/GLOrthogonal.kt
1
1262
package com.fracturedskies.render.common.components.gl import com.fracturedskies.engine.collections.* import com.fracturedskies.engine.jeact.* import com.fracturedskies.engine.math.Matrix4 import com.fracturedskies.engine.math.Matrix4.Companion.orthogonal class GLOrthogonal : Component<Unit>(Unit) { companion object { fun Node.Builder<*>.orthogonal(location: Int, near: Float = 0.03f, far: Float = 1000f, additionalProps: MultiTypeMap = MultiTypeMap()) { nodes.add(Node(GLOrthogonal::class, MultiTypeMap( LOCATION to location, NEAR to near, FAR to far ).with(additionalProps))) } val LOCATION = TypedKey<Int>("location") val NEAR = TypedKey<Float>("near") val FAR = TypedKey<Float>("far") } override fun componentWillUpdate(nextProps: MultiTypeMap, nextState: Unit) { super.componentWillUpdate(nextProps, nextState) // Reset project this.bounds = Bounds(0, 0, 0, 0) } private lateinit var projection: Matrix4 override fun glRender(bounds: Bounds) { if (bounds != this.bounds) projection = orthogonal(bounds.height.toFloat(), bounds.width.toFloat(), 0f, 0f, props[NEAR], props[FAR]) glUniform(props[LOCATION], projection) super.glRender(bounds) } }
unlicense
55d4263674fc896ca16022001d589709
32.236842
140
0.707607
3.835866
false
false
false
false
pdvrieze/ProcessManager
java-common/src/jvmMain/kotlin/net/devrieze/util/db/DBHandleMap.kt
1
10684
/* * Copyright (c) 2018. * * This file is part of ProcessManager. * * ProcessManager is free software: you can redistribute it and/or modify it under the terms of version 3 of the * GNU Lesser General Public License as published by the Free Software Foundation. * * ProcessManager 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License along with ProcessManager. If not, * see <http://www.gnu.org/licenses/>. */ package net.devrieze.util.db import io.github.pdvrieze.kotlinsql.ddl.Database import io.github.pdvrieze.kotlinsql.monadic.DBReceiver import io.github.pdvrieze.kotlinsql.monadic.actions.DBAction import io.github.pdvrieze.kotlinsql.monadic.actions.mapSeq import net.devrieze.util.* import java.sql.SQLException import java.util.* open class DBHandleMap<TMP, V : Any, TR : MonadicDBTransaction<DB>, DB : Database>( transactionFactory: DBTransactionFactory<TR, DB>, elementFactory: HMElementFactory<TMP, V, TR, DB>, handleAssigner: (V, Handle<V>) -> V? = ::HANDLE_AWARE_ASSIGNER ) : DbSet<TMP, V, TR, DB>(transactionFactory, elementFactory, handleAssigner), MutableTransactionedHandleMap<V, TR> { override val elementFactory: HMElementFactory<TMP, V, TR, DB> get() = super.elementFactory as HMElementFactory<TMP, V, TR, DB> private val pendingCreates = TreeMap<Handle<V>, TMP>() protected fun isPending(handle: Handle<V>): Boolean { return pendingCreates.containsKey(handle) } fun pendingValue(handle: Handle<V>): TMP? { return pendingCreates[handle] } fun <W : V> put(value: W): Handle<W> = withDB { dbReceiver -> put(dbReceiver, value) } fun <W : V> put(receiver: DBReceiver<DB>, value: W): DBAction<DB, Handle<W>> { return addWithKey(receiver, value).map { it ?: throw RuntimeException("Adding element $value failed") } } @Deprecated("Use monadic function") override fun <W : V> put(transaction: TR, value: W): Handle<W> = with(transaction) { put(receiver = this, value = value).evaluateNow() } fun get(handle: Handle<V>): V? = withDB { dbReceiver -> get(dbReceiver, handle) } override fun get(transaction: TR, handle: Handle<V>): V? { return with(transaction) { get(dbReceiver = transaction, handle).evaluateNow() } } fun get(dbReceiver: DBReceiver<DB>, handle: Handle<V>): DBAction<DB, V?> { dbReceiver.transaction { val tr = this if (pendingCreates.containsKey(handle)) { throw IllegalArgumentException("Pending create") // XXX This is not the best way } val factory = elementFactory return SELECT(factory.createColumns) .WHERE { factory.getHandleCondition(this, handle) AND factory.filter(this) } .flatMapEach { rowData -> sequence { yield(elementFactory.createBuilder(tr, rowData)) }.asIterable() }.then { it.singleOrNull()?.let { result -> factory.createFromBuilder(tr, FactoryAccess(), result as TMP) } ?: value(null) } } } fun castOrGet(handle: Handle<V>): V? = withDB { dbReceiver -> castOrGet(dbReceiver, handle) } override fun castOrGet(transaction: TR, handle: Handle<V>): V? { return with(transaction) { castOrGet(dbReceiver = this, handle).evaluateNow() } } fun castOrGet(dbReceiver: DBReceiver<DB>, handle: Handle<V>): DBAction<DB, V?> { val element = elementFactory.asInstance(handle) if (element != null) { return dbReceiver.value(element) } // If the element is it's own handle, don't bother looking it up. return get(dbReceiver, handle) } fun set(handle: Handle<V>, value: V): V? = withDB { dbReceiver -> set(dbReceiver, handle, value) } @Throws(SQLException::class) override fun set(transaction: TR, handle: Handle<V>, value: V): V? { return with(transaction) { get(dbReceiver = transaction, handle).then { oldValue -> set(transaction, handle, oldValue, value) }.evaluateNow() } } fun set(dbReceiver: DBReceiver<DB>, handle: Handle<V>, value: V): DBAction<DB, V?> { return get(dbReceiver, handle).then { oldValue -> set(dbReceiver, handle, oldValue, value) } } @Throws(SQLException::class) protected operator fun set( dbReceiver: DBReceiver<DB>, handle: Handle<V>, oldValue: V?, newValue: V ): DBAction<DB, V?> { if (elementFactory.isEqualForStorage(oldValue, newValue)) { return dbReceiver.value(newValue) } val newValueWithHandle = handleAssigner(newValue, handle) ?: newValue return dbReceiver.transaction { val tr = this UPDATE { elementFactory.store(this, newValueWithHandle) } .WHERE { elementFactory.filter(this) AND elementFactory.getHandleCondition(this, handle) } .then { elementFactory.postStore(tr, handle, oldValue, newValueWithHandle) .then(value(oldValue)) } } } override fun iterator(transaction: TR, readOnly: Boolean): MutableIterator<V> { return with(transaction) { super.iterator(dbReceiver = transaction).evaluateNow() } } /* override fun iterator2(transaction: TR, readOnly: Boolean): MutableAutoCloseableIterator<V> { try { return super.iterator(transaction, readOnly) } catch (e: SQLException) { throw RuntimeException(e) } } */ override fun iterable(transaction: TR): MutableIterable<V> { return with(transaction) { iterable(dbReceiver = this).evaluateNow() } } fun iterable(dbReceiver: DBReceiver<DB>): DBAction<DB, MutableIterable<V>> { return with(dbReceiver) { iterator(this).map { object : MutableIterable<V> { override fun iterator(): MutableIterator<V> = it } } } } fun containsElement(element: Any): Boolean { if (element is Handle<*>) { return containsElement(element.handleValue) } return super.contains(element) } override fun containsElement(transaction: TR, element: Any): Boolean { return with(transaction) { containsElement(dbReceiver = this, element).evaluateNow() } } fun containsElement(dbReceiver: DBReceiver<DB>, element: Any): DBAction<DB, Boolean> { if (element is Handle<*>) { return containsElement(dbReceiver, element.handleValue) } return super.contains(dbReceiver, element) } override fun contains(transaction: TR, handle: Handle<V>): Boolean { return with(transaction) { contains(dbReceiver = this, handle).evaluateNow() } } override fun contains(dbReceiver: DBReceiver<DB>, element: Any): DBAction<DB, Boolean> { @Suppress("UNCHECKED_CAST") return when (element) { is Handle<*> -> contains(dbReceiver, handle = element as Handle<V>) else -> super.contains(dbReceiver, element) } } fun contains(dbReceiver: DBReceiver<DB>, handle: Handle<V>): DBAction<DB, Boolean> { return with(dbReceiver) { SELECT(COUNT(elementFactory.createColumns[0])) .WHERE { elementFactory.getHandleCondition(this, handle) AND elementFactory.filter(this) } .mapSeq { it.single()!! > 0 } } } /* @Throws(SQLException::class) override fun contains2(transaction: TR, handle: Handle<V>): Boolean { val query = database .SELECT(database.COUNT(elementFactory.createColumns[0])) .WHERE { elementFactory.getHandleCondition(this, handle) AND elementFactory.filter(this) } try { return query.getSingleList(transaction.connection) { _, data -> data[0] as Int > 0 } } catch (e: RuntimeException) { return false } } */ fun containsAll(c: Collection<*>): Boolean = withDB { dbReceiver -> containsAll(dbReceiver, c) } override fun containsAll(transaction: TR, c: Collection<*>): Boolean { return with(transaction) { containsAll(dbReceiver = this, c).evaluateNow() } } fun containsAll(dbReceiver: DBReceiver<DB>, c: Collection<*>): DBAction<DB, Boolean> { return with(dbReceiver) { c.fold(value(true)) { i: DBAction<DB, Boolean>, elem: Any? -> when (elem) { null -> value(false) else -> i.then { acc -> when (acc) { true -> contains(dbReceiver = dbReceiver, elem) else -> value(false) } } } } } } fun remove(handle: Handle<V>): Boolean { return withTransaction { remove(dbReceiver = this, handle).commit() } } override fun remove(transaction: TR, handle: Handle<V>): Boolean { return with(transaction) { remove(dbReceiver = this, handle).evaluateNow() } } fun remove(dbReceiver: DBReceiver<DB>, handle: Handle<V>): DBAction<DB, Boolean> { return dbReceiver.transaction { elementFactory.preRemove(this, handle) .then { DELETE_FROM(elementFactory.table) .WHERE { elementFactory.getHandleCondition(this, handle) AND elementFactory.filter(this) } .map { it > 0 } } } } override fun clear(transaction: TR) { return with(transaction) { clear(dbReceiver = this).evaluateNow() } } override fun invalidateCache(handle: Handle<V>) =// No-op, there is no cache Unit override fun invalidateCache() { /* No-op, no cache */ } private inline fun <R> withDB(crossinline action: (DBReceiver<DB>) -> DBAction<DB, R>): R { return withTransaction { action(this).commit() } } private inner class FactoryAccess() : DBSetAccess<TMP> { } }
lgpl-3.0
b94c5f764f0fe28ec8f17d0cb88b63d1
33.801303
114
0.599869
4.579511
false
false
false
false
debop/debop4k
debop4k-timeperiod/src/main/kotlin/debop4k/timeperiod/timeranges/MonthTimeRange.kt
1
1722
/* * 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.timeperiod.timeranges import debop4k.core.collections.fastListOf import debop4k.core.kodatimes.today import debop4k.timeperiod.DefaultTimeCalendar import debop4k.timeperiod.ITimeCalendar import debop4k.timeperiod.utils.daysInMonth import debop4k.timeperiod.utils.relativeMonthPeriod import org.joda.time.DateTime /** * Created by debop */ open class MonthTimeRange @JvmOverloads constructor(startTime: DateTime = today(), val monthCount: Int = 1, calendar: ITimeCalendar = DefaultTimeCalendar) : CalendarTimeRange(startTime.relativeMonthPeriod(monthCount), calendar) { fun daySequence(): Sequence<DayRange> { return (0 until monthCount).flatMap { m -> val monthStart = start.plusMonths(m) val dayCountInMonth = monthStart.daysInMonth() (0 until dayCountInMonth).map { DayRange(monthStart.plusDays(it), calendar) } }.asSequence() } fun days(): List<DayRange> { return fastListOf(daySequence().iterator()) } }
apache-2.0
6e72fd95fcdcd70c67d1f405fa81d689
33.46
100
0.70151
4.315789
false
false
false
false
SimonVT/cathode
cathode/src/main/java/net/simonvt/cathode/ui/credits/CreditsFragment.kt
1
8619
/* * Copyright (C) 2016 Simon Vig Therkildsen * * 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 net.simonvt.cathode.ui.credits import android.content.Context import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.LinearLayout import android.widget.TextView import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProviders import butterknife.BindView import butterknife.OnClick import net.simonvt.cathode.R import net.simonvt.cathode.api.enumeration.Department import net.simonvt.cathode.api.enumeration.ItemType import net.simonvt.cathode.common.ui.fragment.RefreshableToolbarFragment import net.simonvt.cathode.common.util.Ids import net.simonvt.cathode.common.util.guava.Preconditions import net.simonvt.cathode.common.widget.RemoteImageView import net.simonvt.cathode.ui.CathodeViewModelFactory import net.simonvt.cathode.ui.NavigationListener import javax.inject.Inject class CreditsFragment @Inject constructor( private val viewModelFactory: CathodeViewModelFactory ) : RefreshableToolbarFragment() { private lateinit var navigationListener: NavigationListener private lateinit var itemType: ItemType private var itemId: Long = 0 private var title: String? = null lateinit var viewModel: CreditsViewModel private var credits: Credits? = null private var itemCount: Int = 0 @BindView(R.id.cast_header) @JvmField var castHeader: LinearLayout? = null @BindView(R.id.cast_items) @JvmField var castItems: LinearLayout? = null @BindView(R.id.production_header) @JvmField var productionHeader: LinearLayout? = null @BindView(R.id.production_items) @JvmField var productionItems: LinearLayout? = null @BindView(R.id.art_header) @JvmField var artHeader: LinearLayout? = null @BindView(R.id.art_items) @JvmField var artItems: LinearLayout? = null @BindView(R.id.crew_header) @JvmField var crewHeader: LinearLayout? = null @BindView(R.id.crew_items) @JvmField var crewItems: LinearLayout? = null @BindView(R.id.costume_makeup_header) @JvmField var costumeMakeupHeader: LinearLayout? = null @BindView(R.id.costume_makeup_items) @JvmField var costumeMakeupItems: LinearLayout? = null @BindView(R.id.directing_header) @JvmField var directingHeader: LinearLayout? = null @BindView(R.id.directing_items) @JvmField var directingItems: LinearLayout? = null @BindView(R.id.writing_header) @JvmField var writingHeader: LinearLayout? = null @BindView(R.id.writing_items) @JvmField var writingItems: LinearLayout? = null @BindView(R.id.sound_header) @JvmField var soundHeader: LinearLayout? = null @BindView(R.id.sound_items) @JvmField var soundItems: LinearLayout? = null @BindView(R.id.camera_header) @JvmField var cameraHeader: LinearLayout? = null @BindView(R.id.camera_items) @JvmField var cameraItems: LinearLayout? = null override fun onAttach(context: Context) { super.onAttach(context) navigationListener = requireActivity() as NavigationListener } override fun onCreate(inState: Bundle?) { super.onCreate(inState) val args = requireArguments() itemId = args.getLong(ARG_ITEM_ID) title = args.getString(ARG_TITLE) itemType = args.getSerializable(ARG_TYPE) as ItemType setTitle(title) itemCount = resources.getInteger(R.integer.creditColumns) viewModel = ViewModelProviders.of(this, viewModelFactory).get(CreditsViewModel::class.java) viewModel.setItemTypeAndId(itemType, itemId) viewModel.loading.observe(this, Observer { loading -> setRefreshing(loading) }) viewModel.credits.observe(this, Observer { credits -> updateView(credits) }) } override fun onRefresh() { viewModel.refresh() } override fun createView(inflater: LayoutInflater, container: ViewGroup?, inState: Bundle?): View { return inflater.inflate(R.layout.fragment_credits, container, false) } override fun onViewCreated(view: View, inState: Bundle?) { super.onViewCreated(view, inState) updateView(credits) } @OnClick(R.id.cast_header) fun onDisplayCastCredits() { navigationListener.onDisplayCredit(itemType, itemId, Department.CAST) } @OnClick(R.id.production_header) fun onDisplayProductionCredits() { navigationListener.onDisplayCredit(itemType, itemId, Department.PRODUCTION) } @OnClick(R.id.art_header) fun onDisplayArtCredits() { navigationListener.onDisplayCredit(itemType, itemId, Department.ART) } @OnClick(R.id.crew_header) fun onDisplayCrewCredits() { navigationListener.onDisplayCredit(itemType, itemId, Department.CREW) } @OnClick(R.id.costume_makeup_header) fun onDisplayCostumeMakeUpCredits() { navigationListener.onDisplayCredit(itemType, itemId, Department.COSTUME_AND_MAKEUP) } @OnClick(R.id.directing_header) fun onDisplayDirectingCredits() { navigationListener.onDisplayCredit(itemType, itemId, Department.DIRECTING) } @OnClick(R.id.writing_header) fun onDisplayWritingCredits() { navigationListener.onDisplayCredit(itemType, itemId, Department.WRITING) } @OnClick(R.id.sound_header) fun onDisplaySoundCredits() { navigationListener.onDisplayCredit(itemType, itemId, Department.SOUND) } @OnClick(R.id.camera_header) fun onDisplayCameraCredits() { navigationListener.onDisplayCredit(itemType, itemId, Department.CAMERA) } private fun updateView(credits: Credits?) { this.credits = credits if (credits != null && view != null) { updateItems(castHeader, castItems!!, credits.cast) updateItems(productionHeader, productionItems!!, credits.production) updateItems(artHeader, artItems!!, credits.art) updateItems(crewHeader, crewItems!!, credits.crew) updateItems(costumeMakeupHeader, costumeMakeupItems!!, credits.costumeAndMakeUp) updateItems(directingHeader, directingItems!!, credits.directing) updateItems(writingHeader, writingItems!!, credits.writing) updateItems(soundHeader, soundItems!!, credits.sound) updateItems(cameraHeader, cameraItems!!, credits.camera) } } private fun updateItems(header: View?, items: ViewGroup, credits: List<Credit>?) { items.removeAllViews() val size = credits?.size ?: 0 if (size > 0) { header!!.visibility = View.VISIBLE items.visibility = View.VISIBLE var i = 0 while (i < size && i < itemCount) { val credit = credits!![i] val view = LayoutInflater.from(requireContext()).inflate(R.layout.credit_item_credit, items, false) val headshot = view.findViewById<RemoteImageView>(R.id.headshot) val name = view.findViewById<TextView>(R.id.name) val job = view.findViewById<TextView>(R.id.job) headshot.setImage(credit.getHeadshot()) name.text = credit.getName() if (credit.getJob() != null) { job.text = credit.getJob() } else { job.text = credit.getCharacter() } view.setOnClickListener { navigationListener.onDisplayPerson(credit.getPersonId()) } items.addView(view) i++ } } else { header!!.visibility = View.GONE items.visibility = View.GONE } } companion object { private const val TAG = "net.simonvt.cathode.ui.credits.CreditsFragment" private const val ARG_TYPE = "net.simonvt.cathode.ui.credits.CreditsFragment.itemType" private const val ARG_ITEM_ID = "net.simonvt.cathode.ui.credits.CreditsFragment.itemId" private const val ARG_TITLE = "net.simonvt.cathode.ui.credits.CreditsFragment.title" @JvmStatic fun getTag(itemId: Long): String { return TAG + "/" + itemId + "/" + Ids.newId() } @JvmStatic fun getArgs(itemType: ItemType, itemId: Long, title: String?): Bundle { Preconditions.checkArgument(itemId >= 0, "itemId must be >= 0") val args = Bundle() args.putSerializable(ARG_TYPE, itemType) args.putLong(ARG_ITEM_ID, itemId) args.putString(ARG_TITLE, title) return args } } }
apache-2.0
fbac3acf3c22d7df1c9b3ad52f0439bd
30.003597
100
0.728275
4.123923
false
false
false
false
debop/debop4k
debop4k-science/src/main/kotlin/debop4k/science/netcdf/NetCdfReader.kt
1
14167
/* * 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.science.netcdf import debop4k.core.areEquals import debop4k.core.loggerOf import debop4k.core.utils.LINE_SEPARATOR import debop4k.core.utils.TAB import org.eclipse.collections.impl.list.mutable.primitive.DoubleArrayList import org.eclipse.collections.impl.list.mutable.primitive.FloatArrayList import org.eclipse.collections.impl.list.mutable.primitive.IntArrayList import org.eclipse.collections.impl.list.mutable.primitive.LongArrayList import ucar.nc2.NetcdfFile import ucar.nc2.Variable import ucar.nc2.util.CancelTask import java.io.File import java.io.IOException import java.net.URI /** * Net CDF 파일의 정보를 읽어드립니다. * Created by debop */ object NetCdfReader { private val log = loggerOf(javaClass) @JvmField val CAHCE_EXTENSIONS = arrayOf("gbx9", "ncx3", "idx") /** * 지정된 경로의 NetCDF 파일을 오픈합니다. * @param path 파일의 전체경로 * * * @return [NetcdfFile] 인스턴스 */ @JvmStatic fun open(path: String): NetcdfFile = NetcdfFile.open(path) /** * 지정된 경로의 NetCDF 파일을 오픈합니다. * * @param path 파일의 전체경로 * @return {@link NetcdfFile} 인스턴스 */ @JvmStatic fun open(path: String, bufferSize: Int = -1, cancelTask: CancelTask? = null, iospMessage: Any? = null): NetcdfFile = NetcdfFile.open(path, bufferSize, cancelTask, iospMessage) /** * 지정된 경로의 NetCDF 파일을 오픈하고, 데이터를 메모리에 모두 로드합니다. * * @param filename 파일의 전체경로 * @return {@link NetcdfFile} 인스턴스 */ @JvmStatic fun openInMemory(filename: String): NetcdfFile = NetcdfFile.openInMemory(filename) /** * 지정된 경로의 NetCDF 파일을 오픈하고, 데이터를 메모리에 모두 로드합니다. * * @param uri 파일의 전체경로 * @return {@link NetcdfFile} 인스턴스 */ @JvmStatic fun openInMemory(uri: URI): NetcdfFile = NetcdfFile.openInMemory(uri) @JvmOverloads @JvmStatic fun openInMemoery(name: String, data: ByteArray, iospClassName: String? = null): NetcdfFile { return NetcdfFile.openInMemory(name, data, iospClassName) } /** * 파일을 NetCdf 형식으로 읽을 수 있는지 여부를 판단한다. * * @param path 파일 전체 경로 * @return NetCdf 형식으로 읽을 수 있는지 여부 */ @JvmStatic fun canRead(path: String): Boolean = canRead(File(path)) /** * 파일을 NetCdf 형식으로 읽을 수 있는지 여부를 판단한다. * * @param file 파일 인스턴스 * @return NetCdf 형식으로 읽을 수 있는지 여부 */ @JvmStatic fun canRead(file: File): Boolean { return !file.isDirectory && !isNetcdfCacheFile(file) && NetcdfFile.canOpen(file.canonicalPath) } /** * 파일을 NetCdf 형식으로 읽을 수 있는지 여부를 판단한다. * * @param path 파일 전체 경로 * @return NetCdf 형식으로 읽을 수 있는지 여부 */ @JvmStatic fun isNetcdfCacheFile(path: String): Boolean = isNetcdfCacheFile(File(path)) /** * 파일을 NetCdf 형식으로 읽을 수 있는지 여부를 판단한다. * * @param file 파일 인스턴스 * @return NetCdf 형식으로 읽을 수 있는지 여부 */ @JvmStatic fun isNetcdfCacheFile(file: File): Boolean { if (file.exists() && file.isFile) { val filename = file.name.toLowerCase() return CAHCE_EXTENSIONS.find { filename.endsWith(it) } != null } else { return false } } /** * NetCDF 파일 내의 지정한 이름의 [Variable] 을 구합니다. * @param nc [NetcdfFile] 인스턴스 * @param varName 찾고자하는 [Variable]의 명칭 * @return [Variable] 인스턴스. 해당 이름의 Variable 이 없는 경우에는 null 을 반환한다. */ @JvmStatic fun getVariable(nc: NetcdfFile, varName: String): Variable? { for (v in nc.variables) { log.trace("varName={}, v={}", varName, v.fullName) if (areEquals(v.fullName, varName)) { return v } } return null } /** * NetCDF 파일 내의 지정한 접두사로 시작하는 [Variable] 중 첫번째 찾은 변수를 반환합니다. * @param nc [NetcdfFile] 인스턴스 * * * @param prefix 찾고자하는 [Variable]의 접두사 * * * @return [Variable] 인스턴스. 해당 이름의 Variable 이 없는 경우에는 null 을 반환한다. */ @JvmStatic fun getVariableStartsWith(nc: NetcdfFile, prefix: String): Variable? { for (v in nc.variables) { if (v != null && v.fullName != null && v.fullName.startsWith(prefix)) { return v } } return null } /** * NetCDF 파일 내의 지정한 접미사를 가진 [Variable] 중 첫번째 찾은 변수를 반환합니다. * * @param nc [NetcdfFile] 인스턴스 * @param surfix 찾고자하는 [Variable]의 접미사 * @return [Variable] 인스턴스. 해당 이름의 Variable 이 없는 경우에는 null 을 반환한다. */ @JvmStatic fun getVariableEndsWith(nc: NetcdfFile, surfix: String): Variable? { for (v in nc.variables) { if (v != null && v.fullName != null && v.fullName.endsWith(surfix)) { return v } } return null } /** * NetCDF 파일 내의 지정한 검색어를 가진 [Variable] 중 첫번째 찾은 변수를 반환합니다. * * @param nc [NetcdfFile] 인스턴스 * @param nameToMatch 찾고자하는 [Variable]의 이름 * @return [Variable] 인스턴스. 해당 이름의 Variable 이 없는 경우에는 null 을 반환한다. */ @JvmStatic fun getVariableContains(nc: NetcdfFile, nameToMatch: String): Variable? { for (v in nc.variables) { if (v != null && v.fullName != null && v.fullName.contains(nameToMatch)) { return v } } return null } /** * [Variable]이 가진 Data 값이 스칼라 형식인지 여부 * @param v [Variable] 인스턴스 * @return Variable이 나타내는 데이터 값이 스칼라 값인지 여부 */ @JvmStatic fun isScalar(v: Variable): Boolean = getValueSize(v) == 1 /** * [Variable]이 가진 데이터의 크기 (모든 Dimension 크기) * @param v [Variable] 인스턴스 * @return 데이터의 전체 크기 */ @JvmStatic fun getValueSize(v: Variable): Int { var size = 1 for (shape in v.shape) { size *= shape } return size } /** * [Variable] 의 값을 Integer 수형으로 읽는다. * @param v [Variable] 인스턴스 * @return [Variable]의 데이터 값을 Integer 수형으로 반환한다. 없으면 null을 반환한다. */ @JvmStatic fun readInt(v: Variable): Int = readInt(v, 0) /** * [Variable] 의 값을 Integer 수형으로 읽는다. * @param v [Variable] 인스턴스 * @param dv 데이터 값이 없거나, 읽는데 실패한 경우 반환할 기본 값 * @return [Variable]의 데이터 값을 Integer 수형으로 반환한다. */ @JvmStatic fun readInt(v: Variable, dv: Int): Int { try { return v.readScalarInt() } catch (t: Throwable) { return dv } } /** * [Variable] 의 값을 Long 수형으로 읽는다. * @param v [Variable] 인스턴스 * @return [Variable]의 데이터 값을 Long 수형으로 반환한다. 없으면 null을 반환한다. */ @JvmStatic fun readLong(v: Variable): Long = v.readScalarLong() /** * [Variable] 의 값을 Long 수형으로 읽는다. * @param v [Variable] 인스턴스 * @param dv 데이터 값이 없거나, 읽는데 실패한 경우 반환할 기본 값 * @return [Variable]의 데이터 값을 Long 수형으로 반환한다. */ @JvmStatic fun readLong(v: Variable, dv: Long): Long { try { return v.readScalarLong() } catch (t: Throwable) { return dv } } /** * [Variable] 의 값을 Float 수형으로 읽는다. * * @param v [Variable] 인스턴스 * @return [Variable]의 데이터 값을 Float 수형으로 반환한다. */ @JvmStatic fun readFloat(v: Variable): Float = v.readScalarFloat() /** * [Variable] 의 값을 Float 수형으로 읽는다. * * @param v [Variable] 인스턴스 * @param dv 데이터 값이 없거나, 읽는데 실패한 경우 반환할 기본 값 * @return [Variable]의 데이터 값을 Float 수형으로 반환한다. */ @JvmStatic fun readFloat(v: Variable, dv: Float): Float { try { return v.readScalarFloat() } catch(e: IOException) { return dv } } /** * [Variable] 의 값을 Double 수형으로 읽는다. * * @param v [Variable] 인스턴스 * @return [Variable]의 데이터 값을 Double 수형으로 반환한다. */ @JvmStatic fun readDouble(v: Variable): Double = v.readScalarDouble() /** * [Variable] 의 값을 Double 수형으로 읽는다. * * @param v [Variable] 인스턴스 * @param dv 데이터 값이 없거나, 읽는데 실패한 경우 반환할 기본 값 * @return [Variable]의 데이터 값을 Double 수형으로 반환한다. */ @JvmStatic fun readDouble(v: Variable, dv: Double): Double { try { return v.readScalarDouble() } catch(e: IOException) { return dv } } /** * [Variable] 의 값을 Integer 수형의 1차원 배열로 읽습니다. * * @param v [Variable] 인스턴스 * @return [Variable]의 데이터 값을 Integer 수형의 1차원 배열로 반환한다. */ @JvmStatic fun readIntArray(v: Variable): IntArrayList { val length = getValueSize(v) val elements = IntArrayList(length) val iter = v.read().indexIterator while (iter.hasNext()) { elements.add(iter.intNext) } return elements } /** * [Variable] 의 값을 Long 수형의 1차원 배열로 읽습니다. * * @param v [Variable] 인스턴스 * @return [Variable]의 데이터 값을 Long 수형의 1차원 배열로 반환한다. */ @JvmStatic fun readLongArray(v: Variable): LongArrayList { val length = getValueSize(v) val elements = LongArrayList(length) val iter = v.read().indexIterator while (iter.hasNext()) { elements.add(iter.longNext) } return elements } /** * [Variable] 의 값을 Float 수형의 1차원 배열로 읽습니다. * * @param v [Variable] 인스턴스 * @return [Variable]의 데이터 값을 Float 수형의 1차원 배열로 반환한다. */ @JvmStatic fun readFloatArray(v: Variable): FloatArrayList { val length = getValueSize(v) val elements = FloatArrayList(length) val iter = v.read().indexIterator while (iter.hasNext()) { elements.add(iter.floatNext) } return elements } /** * [Variable] 의 값을 Double 수형의 1차원 배열로 읽습니다. * @param v [Variable] 인스턴스 * * * @return [Variable]의 데이터 값을 Double 수형의 1차원 배열로 반환한다. * * * @see NetCdfReader.read1DJavaArray */ @JvmStatic fun readDoubleArray(v: Variable): DoubleArrayList { val length = getValueSize(v) val elements = DoubleArrayList(length) val iter = v.read().indexIterator while (iter.hasNext()) { elements.add(iter.doubleNext) } return elements } /** * Variable의 Dimension 을 판단하여 값을 읽어들여 N 차원의 Java 배열로 반환합니다. * * // 3차원 데이터인 경우 * double[][][] matrix = (double[][][])NetCdfReader.readNDJavaArray(v); * * @param v [Variable] 인스턴스 * @return N 차원의 Java 배열 */ @JvmStatic fun readNDJavaArray(v: Variable): Any { return v.read().copyToNDJavaArray() } /** * Variable 의 값들을 모두 읽어, 원하는 요소 수형의 1차원 배열로 반환합니다. * * double[] elements = (double[])NetCdfReader.read1DJavaArray(v, double.class); * @param v [Variable] 인스턴스 * @param elementType Java 배열의 수형 (ex. double.class, int.class) * @return Java 1차원 배열 */ @JvmStatic fun read1DJavaArray(v: Variable, elementType: Class<*>): Any { return v.read().get1DJavaArray(elementType) } /** * [NetcdfFile] 의 내부 속성 정보를 로그애 씁니다. * @param nc [NetcdfFile] 인스턴스 */ @JvmStatic fun displayNetcdfFile(nc: NetcdfFile) { for (v in nc.variables) { log.debug("variable name={}, dimensions={}, dataType={}", v.fullName, v.dimensions, v.dataType) for (dim in v.dimensions) { log.debug("dimension = {}, length={}", dim.fullName, dim.length) } } } /** * [NetcdfFile] 의 내부 속성 정보를 문자열로 반환합니다. * @param nc [NetcdfFile] 인스턴스 * @return NetCDF 파일의 정보 */ @JvmStatic fun getInformation(nc: NetcdfFile): String { val builder = StringBuilder() for (v in nc.variables) { builder.append("Variable") .append(" name=").append(v.fullName) .append(", dimensions=").append(v.dimensions) .append(", dataType=").append(v.dataType) .append(LINE_SEPARATOR) for (dim in v.dimensions) { builder.append(TAB) .append("dimension name=").append(dim.fullName) .append(", length=").append(dim.length) .append(LINE_SEPARATOR) } } return builder.toString() } }
apache-2.0
3735c5971343db1a56b9f7e8724a96a0
25.636569
106
0.62607
3.483614
false
false
false
false
Geobert/radis
app/src/main/kotlin/fr/geobert/radis/ui/StatisticActivity.kt
1
16290
package fr.geobert.radis.ui import android.graphics.Color import android.os.Build import android.os.Bundle import android.support.v4.content.ContextCompat import android.support.v4.util.SimpleArrayMap import android.util.Log import android.view.View import android.widget.RelativeLayout import android.widget.TextView import com.github.mikephil.charting.charts.* import com.github.mikephil.charting.components.XAxis import com.github.mikephil.charting.data.* import com.github.mikephil.charting.formatter.DefaultValueFormatter import com.github.mikephil.charting.utils.ColorTemplate import fr.geobert.radis.BaseActivity import fr.geobert.radis.R import fr.geobert.radis.data.Operation import fr.geobert.radis.data.Statistic import fr.geobert.radis.db.OperationTable import fr.geobert.radis.tools.* import hirondelle.date4j.DateTime import kotlinx.android.synthetic.main.statistic_activity.* import java.text.DateFormatSymbols import java.util.* class StatisticActivity : BaseActivity() { companion object { val STAT = "statistic" } val accountNameLbl: TextView by lazy { findViewById(R.id.chart_account_name) as TextView } val filterLbl: TextView by lazy { findViewById(R.id.filter_lbl) as TextView } val timeScaleLbl: TextView by lazy { findViewById(R.id.time_scale_lbl) as TextView } //val chart_cont: RelativeLayout by lazy { findViewById(R.id.chart_cont) as RelativeLayout } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val extras = intent.extras val stat = extras.getParcelable<Statistic>(STAT) setContentView(R.layout.statistic_activity) title = stat.name setIconOnClick(View.OnClickListener { onBackPressed() }) mToolbar.menu.clear() setIcon(R.drawable.ok_48) accountNameLbl.text = stat.accountName filterLbl.text = getString(stat.getFilterStr()) val (start, end) = stat.createTimeRange() timeScaleLbl.text = "${start.formatDateLong()} ${getString(R.string.rarr)} ${end.formatDateLong()}" val p = RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT) try { val chart = createChartView(stat) chart_cont.addView(chart, p) chart.invalidate() } catch(e: InputMismatchException) { val lbl = TextView(this) lbl.text = getString(R.string.no_statistic_data) chart_cont.addView(lbl, p) } } // generate chart data private fun getColorsArray(id: Int): List<Int> = resources.getStringArray(id)?.map({ Color.parseColor(it) }) as List<Int> private val pos_colors: List<Int> by lazy(LazyThreadSafetyMode.NONE) { getColorsArray(R.array.positive_colors) } private val neg_colors: List<Int> by lazy(LazyThreadSafetyMode.NONE) { getColorsArray(R.array.negative_colors) } /** * get the ops list according to the time range, split by sum sign and group each by partFunc * @param stat the stat to analyse * @return a map with the group key and List(Operation) */ private fun partOps(stat: Statistic): Pair<Map<String, List<Operation>>, Map<String, List<Operation>>> { val (startDate, endDate) = stat.createTimeRange() val ops = OperationTable.getOpsBetweenDate(this, startDate, endDate, stat.accountId).map({ Operation(it) }) val (pos, neg) = ops.partition { it.mSum > 0 } return Pair(pos.groupBy { partFunc(stat)(it) }, neg.groupBy { partFunc(stat)(it) }) } /** * get the partitioning function according to filterType * @param stat the stat to analyse * @return the partitioning function */ private fun partFunc(stat: Statistic): (Operation) -> String = when (stat.filterType) { Statistic.THIRD_PARTY -> { o: Operation -> o.mThirdParty } Statistic.TAGS -> { o: Operation -> o.mTag } Statistic.MODE -> { o: Operation -> o.mMode } else -> { // Statistic.NO_FILTER o: Operation -> val g = GregorianCalendar() g.timeInMillis = o.getDate() when (stat.timePeriodType) { Statistic.PERIOD_DAYS, Statistic.PERIOD_ABSOLUTE -> g.time.formatDate() Statistic.PERIOD_MONTHES -> if (Build.VERSION.SDK_INT >= 9) { g.getDisplayName(Calendar.MONTH, Calendar.SHORT, Locale.getDefault()) ?: "" } else { DateFormatSymbols().shortMonths?.get(g[Calendar.MONTH]) ?: "" } Statistic.PERIOD_YEARS -> g[Calendar.YEAR].toString() else -> { "" } } } } // group sums that represents less than 10% of the total in a "misc" category private fun cleanMap(m: Map<String, Long>, total: Long): Map<String, Long> { val limit = Math.abs(total * 0.01) val result: MutableMap<String, Long> = hashMapOf() val miscKey = getString(R.string.misc_chart_cat) m.forEach { Log.d("StatisticListFragment", "key: ${it.key} / value: ${it.value} / limit: $limit / total: $total / m.size: ${m.size}") if (Math.abs(it.value) < limit) { val p = result[miscKey] if (p != null) { result.put(miscKey, p + it.value) } else { result.put(miscKey, it.value) } } else { result.put(it.key, it.value) } } return result } private fun sumPerFilter(stat: Statistic): Pair<Map<String, Long>, Map<String, Long>> { // partition the list according to filterType fun sumMapOfList(m: Map<String, List<Operation>>) = m.mapValues { it.value.fold(0L) { s: Long, o: Operation -> s + o.mSum } } fun sumMap(m: Map<String, Long>) = m.values.fold(0L) { s: Long, l: Long -> s + l } val (pos, neg) = partOps(stat) val sumP = sumMapOfList(pos) val sumN = sumMapOfList(neg) val total = sumMap(sumP) + Math.abs(sumMap(sumN)) return Pair(cleanMap(sumP, total), cleanMap(sumN, total)) } // private fun initNumFormat(stat: Statistic): NumberFormat { // val cursor = AccountTable.fetchAccount(this, stat.accountId) // cursor.moveToFirst() // val account = Account(cursor) // val numFormat = NumberFormat.getCurrencyInstance() // numFormat.currency = Currency.getInstance(account.currency) // numFormat.minimumFractionDigits = 2 // return numFormat // } // for pie chart private fun createPieData(stat: Statistic): PieData { val yValues = ArrayList<Entry>() val xValues = ArrayList<String>() // fill the data val (pos, neg) = sumPerFilter(stat) var i: Int = 0 val cols = ArrayList<Int>() fun construct(m: Map<String, Long>, colors: List<Int>) { m.forEach { val k = if (it.key.length > 0) it.key else getString(when (stat.filterType) { 1 -> R.string.no_tag 2 -> R.string.no_mode else -> throw IllegalArgumentException("No values for filter only happens for tag and mode") }).format(getString(if (it.value > 0) R.string.pos_values else R.string.neg_values)) xValues.add(k) yValues.add(Entry(Math.abs(it.value) / 100.0f, i++)) cols.add(colors[(yValues.size - 1) % colors.size]) } } construct(pos, pos_colors) construct(neg, neg_colors) val set = PieDataSet(yValues, "") for (c in ColorTemplate.COLORFUL_COLORS) cols.add(c) set.colors = cols val d = PieData(xValues, set) d.setValueFormatter(DefaultValueFormatter(2)) return d } // for lines chart private fun createLineData(stat: Statistic): LineData { val (pos, neg) = partOps(stat) val data = LineData() fun createDataSet(yVals: ArrayList<Entry>, name: String, color: Int): LineDataSet { val dataSet = LineDataSet(yVals, name) dataSet.setDrawValues(false) dataSet.color = color dataSet.setDrawCircleHole(false) dataSet.setCircleColor(color) dataSet.circleSize = 3.0f return dataSet } return when (stat.filterType) { Statistic.NO_FILTER -> { fun construct(m: Map<String, List<Operation>>, colors: List<Int>, name: String) { var i = 0 val yVals = ArrayList<Entry>() m.toSortedMap().forEach { val v = Math.abs(it.value.fold(0L) { i: Long, op: Operation -> i + op.mSum }) + 0.0f yVals.add(Entry(v / 100.0f, i)) i += 1 data.addXValue(it.key) } val dataSet = createDataSet(yVals, name, colors[0]) data.addDataSet(dataSet) } construct(pos, pos_colors, getString(R.string.positive_values)) construct(neg, neg_colors, getString(R.string.negative_values)) data } else -> { fun findMinMax(): Pair<DateTime?, DateTime?> { val posList = pos.flatMap { e -> e.value } val negList = neg.flatMap { e -> e.value } val posMin: DateTime? = posList.minBy { it.mDate }?.mDate val negMin: DateTime? = negList.minBy { it.mDate }?.mDate val posMax: DateTime? = posList.maxBy { it.mDate }?.mDate val negMax: DateTime? = negList.maxBy { it.mDate }?.mDate return Pair(if ((posMin?.compareTo(negMin) ?: 0) < 0) posMin else negMin, if ((posMax?.compareTo(negMax) ?: 0) > 0) posMax else negMax) } fun addPeriodicity(stat: Statistic, date: DateTime): DateTime { return when (stat.timeScaleType) { Statistic.PERIOD_DAYS -> { date.plusDays(1) } Statistic.PERIOD_MONTHES -> { date.plusMonth(1) } Statistic.PERIOD_YEARS -> { date.plusYear(1) } else -> { throw IllegalArgumentException("Time scale should be day, month or year only") } } } val (minDate, maxDate) = findMinMax() if (minDate != null && maxDate != null) { var min: DateTime = minDate while (min.compareTo(maxDate) < 0) { data.addXValue(min.formatDateLong()) min = addPeriodicity(stat, min) } } else { throw InputMismatchException("No data to display") } fun construct(m: Map<String, List<Operation>>, colors: List<Int>) { var i = 0 m.forEach { if (it.key.length > 0) { val yVals = ArrayList<Entry>() it.value.toSortedSet().forEach { val v = Math.abs(it.mSum / 100.0f) val idx = data.xVals.indexOf(it.mDate.formatDateLong()) yVals.add(Entry(v, idx)) } val s = createDataSet(yVals, it.key, colors[i % colors.count()]) i += 1 data.addDataSet(s) } } } construct(pos, pos_colors) construct(neg, neg_colors) data } } } // private fun filterName(stat: Statistic): String { // val stId = when (stat.filterType) { // Statistic.THIRD_PARTY -> R.string.third_parties // Statistic.TAGS -> R.string.tags // Statistic.MODE -> R.string.modes // else -> R.string.time // } // return getString(stId) // } // for bar chart private fun createBarData(stat: Statistic): BarData { val xValues = ArrayList<String>() var (tmpPos, tmpNeg) = sumPerFilter(stat) val pos: MutableMap<String, Long> = hashMapOf() pos.putAll(tmpPos) val neg: MutableMap<String, Long> = hashMapOf() neg.putAll(tmpNeg) pos.forEach { if (!neg.contains(it.key)) neg.put(it.key, 0L) } neg.forEach { if (!pos.contains(it.key)) pos.put(it.key, 0L) } var xLabels: SimpleArrayMap<String, Int> = SimpleArrayMap() fun construct(m: Map<String, Long>, isPos: Boolean): BarDataSet { val yValues = ArrayList<BarEntry>() val colors = ArrayList<Int>() m.forEach { val lbl = if (it.key.length == 0) getString(R.string.no_lbl) else it.key val v: Float = Math.abs(it.value / 100.0f) val existingSeries: Int? = xLabels[lbl] if (existingSeries == null) { val idx = yValues.count() xLabels.put(lbl, idx) xValues.add(lbl) yValues.add(BarEntry(v, idx)) } else { yValues.add(BarEntry(v, existingSeries)) } colors.add(if (isPos) pos_colors[0] else neg_colors[0]) } val set = BarDataSet(yValues, "") set.colors = colors return set } val sets = listOf(construct(pos, isPos = true), construct(neg, isPos = false)) return BarData(xValues, sets) } fun createChartView(stat: Statistic): Chart<out ChartData<out DataSet<out Entry>>> { fun lineAndBarConfig(c: BarLineChartBase<out BarLineScatterCandleBubbleData<out BarLineScatterCandleBubbleDataSet<out Entry>>>) { c.setPinchZoom(true) c.isDragEnabled = true c.isScaleXEnabled = true c.setTouchEnabled(true) c.setDescription("") c.legend.textColor = Color.WHITE c.setGridBackgroundColor(Color.TRANSPARENT) c.axisLeft.textColor = Color.WHITE c.axisRight.isEnabled = false c.xAxis.position = XAxis.XAxisPosition.BOTTOM c.xAxis.textColor = Color.WHITE } val chart = when (stat.chartType) { Statistic.CHART_PIE -> { val c = PieChart(this) c.data = createPieData(stat) c.setHoleColor(ContextCompat.getColor(this, R.color.normal_bg)) c.legend.textColor = Color.WHITE c } Statistic.CHART_BAR -> { val c = BarChart(this) c.data = createBarData(stat) lineAndBarConfig(c) c.legend.isEnabled = false c } Statistic.CHART_LINE -> { val c = LineChart(this) c.data = createLineData(stat) lineAndBarConfig(c) c.legend.isWordWrapEnabled = true c } else -> { throw IllegalArgumentException("Unknown chart type") } } chart.setBackgroundColor(Color.TRANSPARENT) return chart } }
gpl-2.0
7890581c7e31fbd4f8cfaece83bce173
39.827068
137
0.534561
4.418226
false
false
false
false
faceofcat/Tesla-Powered-Thingies
src/main/kotlin/net/ndrei/teslapoweredthingies/machines/cropcloner/GenericCropClonerPlant.kt
1
1136
package net.ndrei.teslapoweredthingies.machines.cropcloner import net.minecraft.block.properties.PropertyInteger import net.minecraft.block.state.IBlockState import net.minecraft.item.ItemStack import net.minecraft.util.NonNullList import net.minecraft.util.math.BlockPos import net.minecraft.world.World import java.util.* /** * Created by CF on 2017-07-15. */ abstract class GenericCropClonerPlant: ICropClonerPlant { override fun getAgeProperty(thing: IBlockState): PropertyInteger? { return thing.propertyKeys .filterIsInstance<PropertyInteger>() .firstOrNull { it.name === "age" } } override fun getDrops(world: World, pos: BlockPos, state: IBlockState): List<ItemStack> { val stacks = NonNullList.create<ItemStack>() state.block.getDrops(stacks, world, pos, state, 0) return stacks.toList() } override fun grow(thing: IBlockState, ageProperty: PropertyInteger, rand: Random): IBlockState { if (rand.nextInt(3) == 1) { return thing.withProperty(ageProperty, thing.getValue(ageProperty) + 1) } return thing } }
mit
bd3726bbcecd49e2902caa850be0efa2
33.454545
100
0.708627
4.176471
false
false
false
false
faceofcat/Tesla-Powered-Thingies
src/main/kotlin/net/ndrei/teslapoweredthingies/machines/cropfarm/ImmersiveHempPlant.kt
1
1435
package net.ndrei.teslapoweredthingies.machines.cropfarm import com.google.common.collect.Lists import net.minecraft.block.state.IBlockState import net.minecraft.item.ItemStack import net.minecraft.util.math.BlockPos import net.minecraft.world.World class ImmersiveHempPlant(private val world: World, private val pos: BlockPos) : IPlantWrapper { override fun canBeHarvested(): Boolean { val state = this.world.getBlockState(this.pos.up()) return (state.block.registryName?.toString() == REGISTRY_NAME) && (state.block.getMetaFromState(state) == 5) } override fun harvest(fortune: Int): List<ItemStack> { val loot = Lists.newArrayList<ItemStack>() if (this.canBeHarvested()) { val state = this.world.getBlockState(pos.up()) loot.addAll(state.block.getDrops(this.world, this.pos.up(), state, fortune)) this.world.setBlockToAir(pos.up()) } return loot } override fun canBlockNeighbours() = false override fun blocksNeighbour(pos: BlockPos) = false override fun canUseFertilizer() = true override fun useFertilizer(fertilizer: ItemStack) = VanillaGenericPlant.useFertilizer(this.world, this.pos, fertilizer) companion object { const val REGISTRY_NAME = "immersiveengineering:hemp" fun isMatch(state: IBlockState) = state.block.registryName?.toString() == REGISTRY_NAME } }
mit
a99cf373e18907461b4ec5f631c518ce
36.789474
116
0.698955
4.053672
false
false
false
false
FHannes/intellij-community
plugins/stats-collector/src/com/intellij/stats/completion/SenderComponent.kt
11
6694
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.stats.completion import com.google.common.net.HttpHeaders import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.components.ApplicationComponent import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.util.Disposer import com.intellij.stats.completion.experiment.WebServiceStatusProvider import com.intellij.util.Alarm import com.intellij.util.Time import org.apache.commons.codec.binary.Base64OutputStream import org.apache.http.HttpResponse import org.apache.http.client.fluent.Form import org.apache.http.client.fluent.Request import org.apache.http.entity.ContentType import org.apache.http.message.BasicHeader import org.apache.http.util.EntityUtils import java.io.ByteArrayOutputStream import java.io.File import java.io.IOException import java.util.zip.GZIPOutputStream import javax.swing.SwingUtilities fun assertNotEDT() { val isInTestMode = ApplicationManager.getApplication().isUnitTestMode assert(!SwingUtilities.isEventDispatchThread() || isInTestMode) } class SenderComponent(val sender: StatisticSender, val statusHelper: WebServiceStatusProvider) : ApplicationComponent { private val LOG = logger<SenderComponent>() private val disposable = Disposer.newDisposable() private val alarm = Alarm(Alarm.ThreadToUse.POOLED_THREAD, disposable) private val sendInterval = 5 * Time.MINUTE private fun send() { if (ApplicationManager.getApplication().isUnitTestMode) return try { ApplicationManager.getApplication().executeOnPooledThread { statusHelper.updateStatus() if (statusHelper.isServerOk()) { val dataServerUrl = statusHelper.getDataServerUrl() sender.sendStatsData(dataServerUrl) } } } catch (e: Exception) { LOG.error(e.message) } finally { alarm.addRequest({ send() }, sendInterval) } } override fun disposeComponent() { Disposer.dispose(disposable) } override fun initComponent() { ApplicationManager.getApplication().executeOnPooledThread { send() } } } class StatisticSender(val requestService: RequestService, val filePathProvider: FilePathProvider) { fun sendStatsData(url: String) { assertNotEDT() filePathProvider.cleanupOldFiles() val filesToSend = filePathProvider.getDataFiles() filesToSend.forEach { if (it.length() > 0) { val isSentSuccessfully = sendContent(url, it) if (isSentSuccessfully) { it.delete() } else { return } } } } private fun sendContent(url: String, file: File): Boolean { val data = requestService.postZipped(url, file) if (data != null && data.code >= 200 && data.code < 300) { return true } return false } } abstract class RequestService { abstract fun post(url: String, params: Map<String, String>): ResponseData? abstract fun post(url: String, file: File): ResponseData? abstract fun postZipped(url: String, file: File): ResponseData? abstract fun get(url: String): ResponseData? } class SimpleRequestService: RequestService() { private val LOG = logger<SimpleRequestService>() override fun post(url: String, params: Map<String, String>): ResponseData? { val form = Form.form() params.forEach { form.add(it.key, it.value) } try { val response = Request.Post(url).bodyForm(form.build()).execute() val httpResponse = response.returnResponse() return ResponseData(httpResponse.status()) } catch (e: IOException) { LOG.debug(e) return null } } override fun postZipped(url: String, file: File): ResponseData? { try { val zippedArray = getZippedContent(file) val request = Request.Post(url).bodyByteArray(zippedArray).apply { addHeader(BasicHeader(HttpHeaders.CONTENT_ENCODING, "gzip")) } val response = request.execute().returnResponse() return ResponseData(response.status(), response.text()) } catch (e: IOException) { LOG.debug(e) return null } } private fun getZippedContent(file: File): ByteArray { val fileText = file.readText() return GzipBase64Compressor.compress(fileText) } override fun post(url: String, file: File): ResponseData? { try { val response = Request.Post(url).bodyFile(file, ContentType.TEXT_HTML).execute() val httpResponse = response.returnResponse() val text = EntityUtils.toString(httpResponse.entity) return ResponseData(httpResponse.statusLine.statusCode, text) } catch (e: IOException) { LOG.debug(e) return null } } override fun get(url: String): ResponseData? { try { var data: ResponseData? = null Request.Get(url).execute().handleResponse { val text = EntityUtils.toString(it.entity) data = ResponseData(it.statusLine.statusCode, text) } return data } catch (e: IOException) { LOG.debug(e) return null } } } data class ResponseData(val code: Int, val text: String = "") { fun isOK() = code in 200..299 } object GzipBase64Compressor { fun compress(text: String): ByteArray { val outputStream = ByteArrayOutputStream() val base64Stream = GZIPOutputStream(Base64OutputStream(outputStream)) base64Stream.write(text.toByteArray()) base64Stream.close() return outputStream.toByteArray() } } fun HttpResponse.text(): String = EntityUtils.toString(entity) fun HttpResponse.status(): Int = statusLine.statusCode
apache-2.0
fed7213cede65fd9b078c78aadd249a6
32.984772
119
0.650284
4.674581
false
false
false
false
Chimerapps/moshi-generator
moshi-generator/src/main/kotlin/com/chimerapps/moshigenerator/AdapterGenerator.kt
1
17271
/* * Copyright 2017 - Chimerapps BVBA * * 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.chimerapps.moshigenerator import com.squareup.javapoet.ClassName import com.squareup.javapoet.CodeBlock import com.squareup.javapoet.FieldSpec import com.squareup.javapoet.JavaFile import com.squareup.javapoet.MethodSpec import com.squareup.javapoet.ParameterSpec import com.squareup.javapoet.ParameterizedTypeName import com.squareup.javapoet.TypeName import com.squareup.javapoet.TypeSpec import com.squareup.javapoet.WildcardTypeName import com.squareup.moshi.Json import com.squareup.moshi.JsonAdapter import com.squareup.moshi.JsonReader import com.squareup.moshi.JsonWriter import com.squareup.moshi.Moshi import java.io.IOException import java.lang.reflect.Type import java.util.logging.Level import java.util.logging.Logger import javax.annotation.processing.Filer import javax.lang.model.element.Modifier import javax.lang.model.element.VariableElement import javax.lang.model.util.Elements /** * @author Nicola Verbeeck * * Date 23/05/2017. */ @SuppressWarnings("WeakerAccess") class AdapterGenerator(private val clazz: MoshiAnnotatedClass, private val filer: Filer, private val elementUtils: Elements, private val logger: SimpleLogger) { private val logging = clazz.debugLogs() @Throws(AnnotationError::class, IOException::class) fun generate() { val from = createFromJson() val to = createToJson() val constructor = createConstructor() val adapterClassBuilder = TypeSpec.classBuilder(clazz.element.simpleName.toString() + "Adapter") adapterClassBuilder.superclass(ParameterizedTypeName.get(ClassName.get(BaseGeneratedAdapter::class.java), ClassName.get(clazz.element))) adapterClassBuilder.addModifiers(Modifier.PUBLIC) adapterClassBuilder.addOriginatingElement(clazz.element) adapterClassBuilder.addJavadoc("Generated using moshi-generator") if (logging) { adapterClassBuilder.addField( FieldSpec.builder(Logger::class.java, "LOGGER", Modifier.FINAL, Modifier.PRIVATE, Modifier.STATIC) .initializer("\$T.getLogger(\$S)", ClassName.get(Logger::class.java), "${clazz.packageName}.${clazz.element.simpleName}Adapter").build()) } adapterClassBuilder.addField(FieldSpec.builder(Moshi::class.java, "moshi", Modifier.PRIVATE).build()) adapterClassBuilder.addMethod(constructor) adapterClassBuilder.addMethod(from) adapterClassBuilder.addMethod(to) adapterClassBuilder.addMethod(generateSetMoshiMethod()) if (clazz.generatesFactory()) { MoshiFactoryGenerator(clazz.element.simpleName.toString() + "AdapterFactory", clazz.packageName, listOf(ClassName.bestGuess("${clazz.packageName}.${clazz.element.simpleName}")), filer, elementUtils) .generate() } JavaFile.builder(clazz.packageName, adapterClassBuilder.build()) .indent("\t") .build().writeTo(filer) } private fun createToJson(): MethodSpec { return MethodSpec.methodBuilder("toJson") .addAnnotation(Override::class.java) .addModifiers(Modifier.PUBLIC) .addException(IOException::class.java) .returns(TypeName.VOID) .addParameter(ParameterSpec.builder(JsonWriter::class.java, "writer", Modifier.FINAL).build()) .addParameter(ParameterSpec.builder(ClassName.get(clazz.element), "value", Modifier.FINAL).build()) .addCode(createWriterBlock()) .build() } private fun createFromJson(): MethodSpec { return MethodSpec.methodBuilder("fromJson") .addAnnotation(Override::class.java) .addModifiers(Modifier.PUBLIC) .addException(IOException::class.java) .returns(ClassName.get(clazz.element)) .addParameter(ParameterSpec.builder(JsonReader::class.java, "reader", Modifier.FINAL).build()) .addCode(createReaderBlock()) .build() } private fun createConstructor(): MethodSpec { val builder = MethodSpec.constructorBuilder() .addModifiers(Modifier.PUBLIC) .addParameter(JsonAdapter.Factory::class.java, "factory", Modifier.FINAL) .addParameter(Type::class.java, "type", Modifier.FINAL) .addStatement("super(factory,type)") if (logging) { builder.addStatement("LOGGER.log(\$T.FINE, \"Constructing \$N\")", ClassName.get(Level::class.java), "${clazz.element.simpleName}Adapter") } return builder.build() } private fun createReaderBlock(): CodeBlock { val builder = CodeBlock.builder() if (logging) { builder.addStatement("LOGGER.log(\$T.FINE, \"Reading json\")", ClassName.get(Level::class.java)) } builder.beginControlFlow("if (reader.peek() == \$T.Token.NULL)", ClassName.get(JsonReader::class.java)) builder.addStatement("return reader.nextNull()") builder.endControlFlow() val fields = clazz.fields for (variableElement in fields) { builder.addStatement("\$T __\$N = null", TypeName.get(variableElement.asType()).box(), variableElement.simpleName.toString()) } builder.addStatement("reader.beginObject()") builder.beginControlFlow("while (reader.hasNext())") builder.addStatement("final \$T _name = reader.nextName()", ClassName.get(String::class.java)) if (logging) { builder.addStatement("LOGGER.log(\$T.FINE, \"\tGot name: {0}\", _name)", ClassName.get(Level::class.java)) } builder.beginControlFlow("switch (_name)") for (variableElement in fields) { builder.add("case \$S: ", getJsonFieldName(variableElement)) generateReader(builder, variableElement) builder.addStatement("break") } builder.addStatement("default: reader.skipValue()") builder.endControlFlow() builder.endControlFlow() builder.addStatement("reader.endObject()") generateNullChecks(builder, fields) builder.add("return new \$T(", ClassName.get(clazz.element)) fields.forEachIndexed { index, variableElement -> if (index != 0) { builder.add(", ") } builder.add("__\$N", variableElement.simpleName.toString()) } builder.addStatement(")") return builder.build() } private fun createWriterBlock(): CodeBlock { val builder = CodeBlock.builder() if (clazz.generatesWriter()) { val writesNulls = clazz.writerSerializesNulls() builder.beginControlFlow("if (value == null)") .addStatement("writer.nullValue()") .addStatement("return") .endControlFlow() builder.addStatement("writer.beginObject()") val fields = clazz.writerFields for (variableElement in fields) { if (writesNulls || !isNullable(variableElement)) { builder.addStatement("writer.name(\$S)", getJsonFieldName(variableElement)) generateWriter(builder, variableElement, accessorOverride = null) } else { builder.beginControlFlow("") builder.addStatement("final \$T __nullCheck = value.${valueAccessor(variableElement)}", TypeName.get(variableElement.asType())) builder.beginControlFlow("if (__nullCheck != null)") builder.addStatement("writer.name(\$S)", getJsonFieldName(variableElement)) generateWriter(builder, variableElement, "__nullCheck") builder.endControlFlow() builder.endControlFlow() } } builder.addStatement("writer.endObject()") } else { builder.addStatement("moshi.nextAdapter(factory, type, EMPTY_ANNOTATIONS).toJson(writer, value)") } return builder.build() } private fun generateNullChecks(builder: CodeBlock.Builder, fields: List<VariableElement>) { for (field in fields) { if (!isNullable(field)) { //No annotation -> required builder.beginControlFlow("if (__\$N == null)", field.simpleName.toString()) builder.addStatement("throw new \$T(\$S)", ClassName.get(IOException::class.java), getJsonFieldName(field) + " is non-optional but was not found in the json") builder.endControlFlow() } } } private fun generateReader(builder: CodeBlock.Builder, variableElement: VariableElement) { val typeName = TypeName.get(variableElement.asType()) if (typeName.isPrimitive || typeName.isBoxedPrimitive) { generatePrimitiveReader(builder, typeName, variableElement) } else if (typeName == ClassName.get(String::class.java)) { if (isNullable(variableElement)) builder.addStatement("__\$N = (reader.peek() == \$T.Token.NULL) ? reader.<\$T>nextNull() : reader.nextString()", variableElement.simpleName.toString(), ClassName.get(JsonReader::class.java), typeName.box()) else builder.addStatement("__\$N = reader.nextString()", variableElement.simpleName.toString()) } else { generateDelegatedReader(builder, typeName, variableElement) } } private fun generateWriter(builder: CodeBlock.Builder, variableElement: VariableElement, accessorOverride: String?) { val typeName = TypeName.get(variableElement.asType()) if (typeName.isPrimitive || typeName.isBoxedPrimitive || typeName == ClassName.get(String::class.java)) { generatePrimitiveWriter(builder, variableElement, accessorOverride) } else { generateDelegatedWriter(builder, typeName, variableElement, accessorOverride) } } private fun generatePrimitiveReader(builder: CodeBlock.Builder, typeName: TypeName, variableElement: VariableElement) { val primitive = typeName.unbox() var method: String? = null if (primitive == TypeName.BOOLEAN) { method = "nextBoolean" } else if (primitive == TypeName.BYTE) { throw AnnotationError("Byte not supported") } else if (primitive == TypeName.SHORT) { builder.addStatement("__\$N = (short)reader.nextInt()", variableElement.simpleName.toString()) } else if (primitive == TypeName.INT) { method = "nextInt" } else if (primitive == TypeName.LONG) { method = "nextLong" } else if (primitive == TypeName.CHAR) { throw AnnotationError("Char not supported") } else if (primitive == TypeName.FLOAT) { builder.addStatement("__\$N = (float)reader.nextDouble()", variableElement.simpleName.toString()) } else if (primitive == TypeName.DOUBLE) { method = "nextDouble" } if (method != null) { if (isNullable(variableElement)) builder.addStatement("__\$N = (reader.peek() == \$T.Token.NULL) ? reader.<\$T>nextNull() : \$T.valueOf(reader.\$N())", variableElement.simpleName.toString(), ClassName.get(JsonReader::class.java), typeName.box(), typeName.box(), method) else builder.addStatement("__\$N = reader.\$N()", variableElement.simpleName.toString(), method) } } private fun generatePrimitiveWriter(builder: CodeBlock.Builder, variableElement: VariableElement, accessorOverride: String?) { if (accessorOverride != null) builder.addStatement("writer.value($accessorOverride)") else builder.addStatement("writer.value(value.${valueAccessor(variableElement)})") } private fun generateDelegatedReader(builder: CodeBlock.Builder, typeName: TypeName, variableElement: VariableElement) { val subBuilder = CodeBlock.builder() subBuilder.beginControlFlow("") subBuilder.addStatement("final \$T _adapter = moshi.adapter(" + makeType(typeName) + ")", ParameterizedTypeName.get(ClassName.get(JsonAdapter::class.java), typeName)) if (logging) { subBuilder.addStatement("LOGGER.log(\$T.FINE, \"\tGot delegate adapter: {0}\", _adapter)", ClassName.get(Level::class.java)) } subBuilder.addStatement("__\$N = _adapter.fromJson(reader)", variableElement.simpleName.toString()) if (logging) { subBuilder.addStatement("LOGGER.log(\$T.FINE, \"\tGot model data: {0}\", __\$N)", ClassName.get(Level::class.java), variableElement.simpleName.toString()) } subBuilder.endControlFlow() builder.add(subBuilder.build()) } private fun generateDelegatedWriter(builder: CodeBlock.Builder, typeName: TypeName, variableElement: VariableElement, accessorOverride: String?) { val subBuilder = CodeBlock.builder() subBuilder.beginControlFlow("") subBuilder.addStatement("final \$T _adapter = moshi.adapter(" + makeType(typeName) + ")", ParameterizedTypeName.get(ClassName.get(JsonAdapter::class.java), typeName)) if (logging) { subBuilder.addStatement("LOGGER.log(\$T.FINE, \"\tGot delegate adapter: {0}\", _adapter)", ClassName.get(Level::class.java)) } if (accessorOverride != null) subBuilder.addStatement("_adapter.toJson(writer, $accessorOverride)") else subBuilder.addStatement("_adapter.toJson(writer, value.${valueAccessor(variableElement)})") subBuilder.endControlFlow() builder.add(subBuilder.build()) } private fun makeType(typeName: TypeName): String { if (typeName is ParameterizedTypeName) { val parameterizedTypeName = typeName val builder = StringBuilder("com.squareup.moshi.Types.newParameterizedType(") builder.append(parameterizedTypeName.rawType.toString()) builder.append(".class, ") parameterizedTypeName.typeArguments.forEachIndexed { index, typeArgument -> if (index != 0) { builder.append(", ") } builder.append(makeType(typeArgument)) } builder.append(')') return builder.toString() } else if (typeName is WildcardTypeName) { return makeType(typeName.upperBounds[0]) } else { return typeName.toString() + ".class" } } private fun isNullable(field: VariableElement): Boolean { field.annotationMirrors.forEach { when (it.annotationType.toString()) { INTELLIJ_NULLABLE -> return true ANDROID_NULLABLE -> return true } } return false } private fun getJsonFieldName(variableElement: VariableElement): String { return variableElement.getAnnotation(Json::class.java)?.name ?: variableElement.getAnnotation(JsonName::class.java)?.name ?: return variableElement.simpleName.toString() } private fun valueAccessor(variableElement: VariableElement): String { val name = variableElement.simpleName.toString() if (clazz.hasVisibleField(name)) { return name } val type = TypeName.get(variableElement.asType()) if (type == TypeName.BOOLEAN || (type.isBoxedPrimitive && type.unbox() == TypeName.BOOLEAN)) { val getterName = if (name.startsWith("is")) name else "is${name.capitalize()}" if (clazz.hasGetter(getterName, variableElement.asType())) { return "$getterName()" } } return "get${name.capitalize()}()" } private fun generateSetMoshiMethod(): MethodSpec { return MethodSpec.methodBuilder("setMoshi") .addModifiers(Modifier.PUBLIC, Modifier.FINAL) .addParameter(TypeName.get(Moshi::class.java), "moshi", Modifier.FINAL) .addStatement("this.moshi = moshi") .build() } companion object { private val INTELLIJ_NULLABLE = "org.jetbrains.annotations.Nullable" private val ANDROID_NULLABLE = "android.support.annotation.Nullable" } }
apache-2.0
1ba3600ac6946cddd03b70ddb3994ff2
44.690476
252
0.631174
5.066295
false
false
false
false
GeoffreyMetais/vlc-android
application/vlc-android/src/org/videolan/vlc/util/DialogDelegates.kt
1
2936
package org.videolan.vlc.util import androidx.fragment.app.DialogFragment import androidx.fragment.app.Fragment import androidx.fragment.app.FragmentActivity import androidx.lifecycle.LifecycleOwner import androidx.lifecycle.Observer import org.videolan.libvlc.Dialog import org.videolan.vlc.gui.dialogs.VlcLoginDialog import org.videolan.vlc.gui.dialogs.VlcProgressDialog import org.videolan.vlc.gui.dialogs.VlcQuestionDialog import videolan.org.commontools.LiveEvent private const val TAG = "DialogDelegate" interface IDialogHandler interface IDialogDelegate { fun observeDialogs(lco: LifecycleOwner, manager: IDialogManager) } interface IDialogManager { fun fireDialog(dialog: Dialog) fun dialogCanceled(dialog: Dialog?) } class DialogDelegate : IDialogDelegate { override fun observeDialogs(lco: LifecycleOwner, manager: IDialogManager) { dialogEvt.observe(lco, Observer { when(it) { is Show -> manager.fireDialog(it.dialog) is Cancel -> manager.dialogCanceled(it.dialog) } }) } companion object DialogsListener : Dialog.Callbacks { private val dialogEvt: LiveEvent<DialogEvt> = LiveEvent() var dialogCounter = 0 override fun onProgressUpdate(dialog: Dialog.ProgressDialog) { val vlcProgressDialog = dialog.context as? VlcProgressDialog ?: return if (vlcProgressDialog.isVisible) vlcProgressDialog.updateProgress() } override fun onDisplay(dialog: Dialog.ErrorMessage) { dialogEvt.value = Cancel(dialog) } override fun onDisplay(dialog: Dialog.LoginDialog) { dialogEvt.value = Show(dialog) } override fun onDisplay(dialog: Dialog.QuestionDialog) { dialogEvt.value = Show(dialog) } override fun onDisplay(dialog: Dialog.ProgressDialog) { dialogEvt.value = Show(dialog) } override fun onCanceled(dialog: Dialog?) { (dialog?.context as? DialogFragment)?.dismiss() dialogEvt.value = Cancel(dialog) } } } fun Fragment.showVlcDialog(dialog: Dialog) { activity?.showVlcDialog(dialog) } @Suppress("INACCESSIBLE_TYPE") fun FragmentActivity.showVlcDialog(dialog: Dialog) { val dialogFragment = when (dialog) { is Dialog.LoginDialog -> VlcLoginDialog().apply { vlcDialog = dialog } is Dialog.QuestionDialog -> VlcQuestionDialog().apply { vlcDialog = dialog } is Dialog.ProgressDialog -> VlcProgressDialog().apply { vlcDialog = dialog } else -> null } ?: return val fm = supportFragmentManager dialogFragment.show(fm, "vlc_dialog_${++DialogDelegate.dialogCounter}") } private sealed class DialogEvt private class Show(val dialog: Dialog) : DialogEvt() private class Cancel(val dialog: Dialog?) : DialogEvt()
gpl-2.0
9a3191227e1e772e9c19dad4d5ba2df1
30.244681
82
0.682561
4.64557
false
false
false
false
tomhenne/Jerusalem
src/main/java/de/esymetric/jerusalem/routing/algorithms/TomsAStarStarRouting.kt
1
6702
package de.esymetric.jerusalem.routing.algorithms import de.esymetric.jerusalem.ownDataRepresentation.Node import de.esymetric.jerusalem.ownDataRepresentation.fileSystem.PartitionedNodeListFile import de.esymetric.jerusalem.ownDataRepresentation.fileSystem.PartitionedTransitionListFile import de.esymetric.jerusalem.ownDataRepresentation.fileSystem.PartitionedWayCostFile import de.esymetric.jerusalem.ownDataRepresentation.geoData.GPSMath.calculateDistance import de.esymetric.jerusalem.ownDataRepresentation.geoData.Position import de.esymetric.jerusalem.ownDataRepresentation.geoData.importExport.KML import de.esymetric.jerusalem.routing.Router import de.esymetric.jerusalem.routing.RoutingAlgorithm import de.esymetric.jerusalem.routing.RoutingHeuristics import de.esymetric.jerusalem.routing.RoutingType import de.esymetric.jerusalem.utils.Utils import java.util.* class TomsAStarStarRouting : RoutingAlgorithm { private var openList: SortedSet<Node> = TreeSet() private var openListMap = HashMap<Long, Node>() private var closedList = HashSet<Long>() lateinit var nlf: PartitionedNodeListFile lateinit var wlf: PartitionedTransitionListFile lateinit var wcf: PartitionedWayCostFile lateinit var type: RoutingType lateinit var target: Node lateinit var heuristics: RoutingHeuristics override fun getRoute( start: Node, target: Node, type: RoutingType, nlf: PartitionedNodeListFile, wlf: PartitionedTransitionListFile, wcf: PartitionedWayCostFile, heuristics: RoutingHeuristics, targetNodeMasterNodes: List<Node>, maxExecutionTimeSec: Int, useOptimizedPath: Boolean ): List<Node>? { this.nlf = nlf this.wlf = wlf this.wcf = wcf this.type = type this.target = target this.heuristics = heuristics val maxTime = Date().time + maxExecutionTimeSec.toLong() * 1000L // clear openList.clear() openListMap.clear() closedList.clear() start.totalCost = calculateDistance( start.lat, start.lng, target.lat, target.lng ) * heuristics.estimateRemainingCost(type) / 1000.0 start.realCostSoFar = 0.0 openList.add(start) openListMap[start.uID] = start var node: Node var bestNode: Node? = null var count = 0 while (openList.size > 0) { node = openList.first() openList.remove(node) openListMap.remove(node.uID) if (bestNode == null || bestNode.remainingCost() > node.remainingCost()) bestNode = node if (node == target) { if (Router.debugMode) println( "final number of open nodes was " + openList.size + " - closed list size was " + closedList.size + " - final cost is " + Utils.formatTimeStopWatch((node.totalCost.toInt() * 1000).toLong()) ) return getFullPath(node) } if (SAVE_STATE_AS_KML) saveStateAsKml(getFullPath(node), ++count) // for debugging expand(node, targetNodeMasterNodes) closedList.add(node.uID) if (closedList.size > MAX_NODES_IN_CLOSED_LIST) break if (closedList.size and 0xfff == 0 && Date().time > maxTime ) break if (Router.debugMode && closedList.size and 0xffff == 0) println( "closed list now contains " + closedList.size + " entries" ) } if (Router.debugMode) println( "no route - open list is empty - final number of open nodes was " + openList.size + " - closed list size was " + closedList.size ) bestNode ?: return null return getFullPath(bestNode) } private fun getFullPath(sourceNode: Node): List<Node> { var node: Node = sourceNode val foundPath: MutableList<Node> = LinkedList() while (true) { foundPath.add(node) node = if (node.predecessor == null) break else { node.predecessor!! } } foundPath.reverse() return foundPath } fun expand(currentNode: Node, targetNodeMasterNodes: List<Node?>) { // falls es sich um eine mit dem Ziel verbunde Kreuzungsnode handelt, // den Original-Pfad verfolgen und nicht den optimierten Pfad, welcher // die targetNode �berspringen w�rde for (t in currentNode.listTransitions(nlf, wlf, wcf)) { var transition = t if (targetNodeMasterNodes.contains(t.targetNode) && targetNodeMasterNodes.contains(currentNode) ) { transition = wlf.getTransition(currentNode, t.id, nlf, wcf) ?: t } var successor = transition.targetNode if (closedList.contains(successor!!.uID)) continue // clone successor object - this is required because successor // contains search path specific information and can be in open list // multiple times successor = successor.clone() as Node var cost = currentNode.realCostSoFar val transitionCost = transition.getCost(type) if (transitionCost == RoutingHeuristics.BLOCKED_WAY_COST) continue cost += transitionCost successor.realCostSoFar = cost cost += successor.getRemainingCost(target, type, heuristics) successor.totalCost = cost if (openListMap.containsKey(successor.uID) && cost > openListMap[successor.uID]!!.totalCost ) continue successor.predecessor = currentNode openList.remove(successor) openList.add(successor) openListMap[successor.uID] = successor } } /** * Enable this method to document the process of route creation. */ fun saveStateAsKml(route: List<Node?>?, count: Int) { val kml = KML() val trackPts = Vector<Position>() for (n in route!!) { val p = Position() p.latitude = n!!.lat p.longitude = n.lng trackPts.add(p) } kml.trackPositions = trackPts kml.save("current_$count.kml") } companion object { const val MAX_NODES_IN_CLOSED_LIST = 1000000 const val SAVE_STATE_AS_KML = false } }
apache-2.0
77ed4f2f80cb186f0a4ba331c68967b1
39.875
111
0.607196
4.774056
false
false
false
false
ivw/tinyscript
compiler-core/src/test/kotlin/tinyscript/compiler/core/FunctionExpressionSpec.kt
1
1426
package tinyscript.compiler.core import org.jetbrains.spek.api.Spek import org.jetbrains.spek.api.dsl.describe import org.jetbrains.spek.api.dsl.it object FunctionExpressionSpec : Spek({ describe("function expression") { it("can be used with and without parameters") { assertAnalysis(""" multiplyByTwo = [n: Int] -> n * 2 double = multiplyByTwo[n = 1] sayHi = -> println[m = "Hi"] sayHi[] """) } it("has to be called with the right arguments") { assertAnalysisFails(""" multiplyByTwo = [n: Int] -> n * 2 foo = multiplyByTwo[] """) } it("must be analysed even when not called") { assertAnalysisFails(""" foo = -> abc """) assertAnalysisFails(""" foo = -> (-> abc) """) } it("can be used with an explicit type") { assertAnalysis(""" multiplyByTwo: [n: Int] -> Int = [n: Int] -> n * 2 """) assertAnalysis(""" multiplyByTwo: [n: Int, foo: String] -> ? = [n: Int] -> n * 2 """) assertAnalysisFails(""" multiplyByTwo: [] -> Int = [n: Int] -> n * 2 """) assertAnalysisFails(""" multiplyByTwo: [n: Int] -> String = [n: Int] -> n * 2 """) } it("can use forward references until it is called") { assertAnalysis(""" sayHi = -> println[m = hiMessage] hiMessage = "Hi" sayHi[] """) assertAnalysisFails(""" sayHi = -> println[m = hiMessage] sayHi[] hiMessage = "Hi" """) } } })
mit
614367b2890925ead06e9df93588ecfc
21.28125
65
0.572931
3.331776
false
false
false
false
BOINC/boinc
android/BOINC/app/src/main/java/edu/berkeley/boinc/adapter/ClientLogRecyclerViewAdapter.kt
3
2631
/* * This file is part of BOINC. * http://boinc.berkeley.edu * Copyright (C) 2020 University of California * * BOINC is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation, * either version 3 of the License, or (at your option) any later version. * * BOINC 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with BOINC. If not, see <http://www.gnu.org/licenses/>. */ package edu.berkeley.boinc.adapter import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import edu.berkeley.boinc.databinding.EventLogClientListItemLayoutBinding import edu.berkeley.boinc.rpc.Message import edu.berkeley.boinc.utils.secondsToLocalDateTime import java.time.format.DateTimeFormatter import java.time.format.FormatStyle class ClientLogRecyclerViewAdapter(private val messages: List<Message>) : RecyclerView.Adapter<ClientLogRecyclerViewAdapter.ViewHolder>() { private val dateTimeFormatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM) override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val binding = EventLogClientListItemLayoutBinding.inflate(LayoutInflater.from(parent.context)) return ViewHolder(binding) } override fun getItemCount() = messages.size override fun onBindViewHolder(holder: ViewHolder, position: Int) { holder.date.text = getDateTimeString(position) holder.message.text = getMessage(position) val project = getProject(position) if (project.isEmpty()) { holder.project.visibility = View.GONE } else { holder.project.visibility = View.VISIBLE holder.project.text = project } } fun getDateTimeString(position: Int): String = dateTimeFormatter.format(messages[position].timestamp.secondsToLocalDateTime()) fun getMessage(position: Int) = messages[position].body fun getProject(position: Int) = messages[position].project class ViewHolder(binding: EventLogClientListItemLayoutBinding) : RecyclerView.ViewHolder(binding.root) { val date = binding.msgsDate val project = binding.msgsProject val message = binding.msgsMessage } }
lgpl-3.0
c0cd3a037d07bef212654c5f977a1484
38.863636
130
0.748005
4.706619
false
false
false
false
soywiz/korge
korge-dragonbones/src/commonMain/kotlin/com/dragonbones/model/SkinData.kt
1
2981
/** * The MIT License (MIT) * * Copyright (c) 2012-2018 DragonBones team and other 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. */ package com.dragonbones.model import com.dragonbones.core.* import com.soywiz.kds.* import com.soywiz.kds.iterators.* /** * - The skin data, typically a armature data instance contains at least one skinData. * @version DragonBones 3.0 * @language en_US */ /** * - 皮肤数据,通常一个骨架数据至少包含一个皮肤数据。 * @version DragonBones 3.0 * @language zh_CN */ class SkinData(pool: SingleObjectPool<SkinData>) : BaseObject(pool) { /** * - The skin name. * @version DragonBones 3.0 * @language en_US */ /** * - 皮肤名称。 * @version DragonBones 3.0 * @language zh_CN */ var name: String = "" /** * @private */ val displays: FastStringMap<FastArrayList<DisplayData?>> = FastStringMap() /** * @private */ var parent: ArmatureData? = null override fun _onClear() { this.displays.fastValueForEach { slotDisplays -> slotDisplays.fastForEach { display -> display?.returnToPool() } } this.displays.clear() this.name = "" //this.parent = null // } /** * @internal */ fun addDisplay(slotName: String, value: DisplayData?) { if (!(slotName in this.displays)) { this.displays[slotName] = FastArrayList() } if (value != null) { value.parent = this } val slotDisplays = this.displays[slotName] // TODO clear prev slotDisplays?.add(value) } /** * @private */ fun getDisplay(slotName: String, displayName: String): DisplayData? { getDisplays(slotName)?.fastForEach { display -> if (display != null && display.name == displayName) { return display } } return null } /** * @private */ fun getDisplays(slotName: String?): FastArrayList<DisplayData?>? = this.displays.getNull(slotName) override fun toString(): String = "[class dragonBones.SkinData]" }
apache-2.0
466521dca08f23137a99c2b66dfea46d
26.317757
99
0.694492
3.742638
false
false
false
false
donald-w/Anki-Android
AnkiDroid/src/main/java/com/ichi2/anki/reviewer/EaseButton.kt
1
4091
/* * Copyright (c) 2021 David Allison <[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.ichi2.anki.reviewer import android.view.MotionEvent import android.view.View import android.view.ViewGroup import android.widget.LinearLayout import android.widget.TextView import androidx.annotation.StringRes import com.ichi2.anki.AbstractFlashcardViewer /** * The UI of an ease button * * Currently contains a some business logic: * * [nextTime] is used by the API * * [canPerformClick] is used to determine if the answer is being shown and the button isn't blocked */ class EaseButton(private val ease: Int, private val layout: LinearLayout, private val easeTextView: TextView, private val easeTimeView: TextView) { var height: Int get() = layout.layoutParams.height set(value) { layout.layoutParams.height = value } @get:JvmName("canPerformClick") val canPerformClick get() = layout.isEnabled && layout.visibility == View.VISIBLE var nextTime: String get() = easeTimeView.text.toString() set(value) { easeTimeView.text = value } fun hideNextReviewTime() { easeTimeView.visibility = View.GONE } fun setButtonScale(scale: Int) { val params = layout.layoutParams params.height = params.height * scale / 100 } fun setVisibility(visibility: Int) { layout.visibility = visibility } fun setColor(color: Int) { layout.setBackgroundResource(color) } fun setListeners(easeHandler: AbstractFlashcardViewer.SelectEaseHandler) { layout.setOnClickListener { view: View? -> easeHandler.onClick(view) } layout.setOnTouchListener { view: View?, event: MotionEvent? -> easeHandler.onTouch(view, event) } } fun detachFromParent() { if (layout.parent != null) { (layout.parent as ViewGroup).removeView(layout) } } fun addTo(toAddTo: LinearLayout) { toAddTo.addView(layout) } fun hide() { layout.visibility = View.GONE easeTimeView.text = "" } /** Perform a click if the button is visible */ fun performSafeClick() { if (!canPerformClick) return layout.performClick() } /** * Makes the button clickable if it is the provided ease, otherwise enabled. * * @param currentEase The current ease of the card */ fun unblockBasedOnEase(currentEase: Int) { if (this.ease == currentEase) { layout.isClickable = true } else { layout.isEnabled = true } } /** * Makes the button not clickable if it is the provided ease, otherwise disable it. * * @param currentEase The current ease of the card */ fun blockBasedOnEase(currentEase: Int) { if (this.ease == currentEase) { layout.isClickable = false } else { layout.isEnabled = false } } fun performClickWithVisualFeedback() { layout.requestFocus() layout.performClick() } fun requestFocus() { } fun setup(backgroundColor: Int, textColor: Int, @StringRes easeStringRes: Int) { layout.visibility = View.VISIBLE layout.setBackgroundResource(backgroundColor) easeTextView.setText(easeStringRes) easeTextView.setTextColor(textColor) easeTimeView.setTextColor(textColor) } }
gpl-3.0
923e39b6dfa372cb398a76bb9e3ab556
29.080882
147
0.659741
4.451578
false
false
false
false
mctoyama/PixelClient
src/main/kotlin/org/pixelndice/table/pixelclient/connection/lobby/client/StateRunning22TextMessage.kt
1
1047
package org.pixelndice.table.pixelclient.connection.lobby.client import org.apache.logging.log4j.LogManager import org.pixelndice.table.pixelclient.ApplicationBus import org.pixelndice.table.pixelclient.ds.Account import org.pixelndice.table.pixelprotocol.Protobuf private val logger = LogManager.getLogger(StateRunning22TextMessage::class.java) class StateRunning22TextMessage : State { override fun process(ctx: Context) { val packet = ctx.channel.packet if( packet != null ){ if( packet.payloadCase == Protobuf.Packet.PayloadCase.TEXTMESSAGE){ val textMessage = packet.textMessage val accountFrom = Account.fromProtobuf(textMessage.from) val accountTo = Account.fromProtobuf(textMessage.to) ApplicationBus.post(ApplicationBus.ReceiveTextMessage(accountFrom,textMessage.toAll, accountFrom, textMessage.text)) }else{ logger.error("Expecting TextMessage, instead received $packet") } } } }
bsd-2-clause
34cf429a44eae99baabf47b269ac68e9
33.9
132
0.704871
4.737557
false
false
false
false
joffrey-bion/mc-mining-optimizer
src/main/kotlin/org/hildan/minecraft/mining/optimizer/blocks/Sample.kt
1
4985
package org.hildan.minecraft.mining.optimizer.blocks import org.hildan.minecraft.mining.optimizer.geometry.BlockIndex import org.hildan.minecraft.mining.optimizer.geometry.Dimensions import org.hildan.minecraft.mining.optimizer.geometry.Wrapping import org.hildan.minecraft.mining.optimizer.ore.BlockType import java.util.* /** * An arbitrary group of blocks. It can have any dimension, thus it is different from a minecraft chunk, which is * 16x256x16. */ data class Sample( /** The dimensions of this sample. */ val dimensions: Dimensions, /** The blocks of this sample. */ private var blocks: MutableList<BlockType>, ) { /** The number of dug blocks currently in this sample. */ var dugBlocks = mutableSetOf<BlockIndex>() private set /** The number of dug blocks currently in this sample. */ val dugBlocksCount: Int get() = dugBlocks.size /** The number of ore blocks currently in this sample. */ var oreBlocksCount = 0 private set /** * Creates a new pure sample of the given [dimensions] containing only blocks of the given [initialBlockType]. */ constructor(dimensions: Dimensions, initialBlockType: BlockType) : this( dimensions = dimensions, blocks = MutableList(dimensions.nbPositions) { initialBlockType }, ) { oreBlocksCount = if (initialBlockType.isOre) blocks.size else 0 dugBlocks = if (initialBlockType == BlockType.AIR) blocks.indices.toMutableSet() else mutableSetOf() } /** * Creates a copy of the given [source] Sample. */ constructor(source: Sample) : this(source.dimensions, ArrayList(source.blocks)) { this.oreBlocksCount = source.oreBlocksCount this.dugBlocks = HashSet(source.dugBlocksCount) } /** * Fills this [Sample] with the given [blockType]. */ fun fill(blockType: BlockType) { blocks.fill(blockType) oreBlocksCount = if (blockType.isOre) blocks.size else 0 dugBlocks = if (blockType == BlockType.AIR) blocks.indices.toMutableSet() else mutableSetOf() } /** * Resets this [Sample] to the same state as the given [sample]. */ fun resetTo(sample: Sample) { blocks = ArrayList(sample.blocks) oreBlocksCount = sample.oreBlocksCount dugBlocks = HashSet(sample.dugBlocks) } /** * Gets the 6 blocks that are adjacent to this block, with [Wrapping.WRAP_XZ] wrapping. If this block is on the * floor or ceiling of this sample, less than 6 blocks are returned because part of them is cut off. */ private val BlockIndex.neighbours get() = with(dimensions) { neighbours } /** * Returns whether the given [x], [y], [z] coordinates belong to this sample. */ fun contains(x: Int, y: Int, z: Int): Boolean = dimensions.contains(x, y, z) /** * Gets the type of the block located at the given [x], [y], [z] coordinates. */ fun getBlockType(x: Int, y: Int, z: Int): BlockType = getBlockType(getIndex(x, y, z)) /** * Sets the type of the block located at the given [x], [y], [z] coordinates. */ fun setBlockType(x: Int, y: Int, z: Int, type: BlockType) = setBlockType(getIndex(x, y, z), type) private fun getIndex(x: Int, y: Int, z: Int) = dimensions.getIndex(x, y, z) /** * Gets the type of the block located at the given [index]. */ private fun getBlockType(index: BlockIndex): BlockType = blocks[index] /** * Sets the type of the block located at the given [index]. */ private fun setBlockType(index: BlockIndex, type: BlockType) { val formerType = blocks[index] blocks[index] = type if (!formerType.isOre && type.isOre) { oreBlocksCount++ } else if (formerType.isOre && !type.isOre) { oreBlocksCount-- } if (formerType != BlockType.AIR && type == BlockType.AIR) { dugBlocks.add(index) } else if (formerType == BlockType.AIR && type != BlockType.AIR) { dugBlocks.remove(index) } } /** * Digs the block at the specified [index]. */ fun digBlock(index: BlockIndex) { setBlockType(index, BlockType.AIR) } /** * Digs the block at the specified [x], [y], [z] coordinates. */ fun digBlock(x: Int, y: Int, z: Int) = digBlock(getIndex(x, y, z)) fun digVisibleOresRecursively() { val explored = HashSet(dugBlocks) val toExplore = explored.flatMapTo(ArrayDeque()) { it.neighbours.asIterable() } while (toExplore.isNotEmpty()) { val blockIndex = toExplore.poll() explored.add(blockIndex) if (blocks[blockIndex].isOre) { digBlock(blockIndex) blockIndex.neighbours.filterNotTo(toExplore) { explored.contains(it) } } } } override fun toString(): String = "Size: $dimensions Dug: $dugBlocksCount" }
mit
80e3d31e4dfde71e2bbba5eb3c70ef6c
34.35461
115
0.635105
4.16806
false
false
false
false
pyamsoft/padlock
padlock/src/main/java/com/pyamsoft/padlock/list/info/LockInfoItem.kt
1
2962
/* * Copyright 2019 Peter Kenji Yamanaka * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.pyamsoft.padlock.list.info import android.view.View import androidx.recyclerview.widget.RecyclerView import com.pyamsoft.padlock.Injector import com.pyamsoft.padlock.PadLockComponent import com.pyamsoft.padlock.R import com.pyamsoft.padlock.list.info.LockInfoItem.ViewHolder import com.pyamsoft.padlock.model.LockState import com.pyamsoft.padlock.model.list.ActivityEntry import com.pyamsoft.padlock.model.list.ActivityEntry.Item import com.pyamsoft.pydroid.core.bus.EventBus import com.pyamsoft.pydroid.core.bus.Publisher import timber.log.Timber import javax.inject.Inject class LockInfoItem internal constructor( entry: ActivityEntry.Item, private val system: Boolean ) : LockInfoBaseItem<Item, LockInfoItem, ViewHolder>(entry) { override fun getType(): Int = R.id.adapter_lock_info override fun getLayoutRes(): Int = R.layout.adapter_item_lockinfo override fun bindView( holder: ViewHolder, payloads: List<Any> ) { super.bindView(holder, payloads) holder.bind(model, system) } override fun unbindView(holder: ViewHolder) { super.unbindView(holder) holder.unbind() } override fun filterAgainst(query: String): Boolean { val name = model.name.toLowerCase() .trim { it <= ' ' } Timber.d("Filter predicate: '%s' against %s", query, name) return name.contains(query) } override fun getViewHolder(view: View): ViewHolder = ViewHolder(view) class ViewHolder internal constructor(itemView: View) : RecyclerView.ViewHolder(itemView) { @field:Inject internal lateinit var publisher: EventBus<LockInfoEvent> @field:Inject internal lateinit var view: LockInfoItemView init { Injector.obtain<PadLockComponent>(itemView.context.applicationContext) .plusLockInfoItemComponent() .itemView(itemView) .build() .inject(this) } private fun processModifyDatabaseEntry( model: ActivityEntry.Item, system: Boolean, newLockState: LockState ) { publisher.publish(LockInfoEvent.from(model, newLockState, null, system)) } fun bind( model: ActivityEntry.Item, system: Boolean ) { view.bind(model, system) view.onSwitchChanged { processModifyDatabaseEntry(model, system, it) } } fun unbind() { view.unbind() } } }
apache-2.0
8651fe2ebc2880efaa44290c1eac923a
28.039216
93
0.720122
4.148459
false
false
false
false
exponent/exponent
android/versioned-abis/expoview-abi44_0_0/src/main/java/abi44_0_0/expo/modules/filesystem/FileSystemModule.kt
2
48755
package abi44_0_0.expo.modules.filesystem import android.annotation.SuppressLint import android.app.Activity import android.content.Context import android.content.Intent import android.net.Uri import android.os.AsyncTask import android.os.Build import android.os.Bundle import android.os.Environment import android.os.StatFs import android.provider.DocumentsContract import android.util.Base64 import android.util.Log import androidx.core.content.FileProvider import androidx.documentfile.provider.DocumentFile import abi44_0_0.expo.modules.core.ExportedModule import abi44_0_0.expo.modules.core.ModuleRegistry import abi44_0_0.expo.modules.core.ModuleRegistryDelegate import abi44_0_0.expo.modules.core.Promise import abi44_0_0.expo.modules.core.interfaces.ActivityEventListener import abi44_0_0.expo.modules.core.interfaces.ActivityProvider import abi44_0_0.expo.modules.core.interfaces.ExpoMethod import abi44_0_0.expo.modules.core.interfaces.services.EventEmitter import abi44_0_0.expo.modules.core.interfaces.services.UIManager import abi44_0_0.expo.modules.interfaces.filesystem.FilePermissionModuleInterface import abi44_0_0.expo.modules.interfaces.filesystem.Permission import java.io.BufferedInputStream import java.io.ByteArrayOutputStream import java.io.File import java.io.FileInputStream import java.io.FileNotFoundException import java.io.FileOutputStream import java.io.IOException import java.io.InputStream import java.io.OutputStream import java.io.OutputStreamWriter import java.lang.ClassCastException import java.lang.Exception import java.lang.IllegalArgumentException import java.lang.NullPointerException import java.math.BigInteger import java.net.CookieHandler import java.net.URLConnection import java.util.* import java.util.concurrent.TimeUnit import kotlin.math.pow import okhttp3.Call import okhttp3.Callback import okhttp3.Headers import okhttp3.JavaNetCookieJar import okhttp3.MediaType import okhttp3.MultipartBody import okhttp3.OkHttpClient import okhttp3.Request import okhttp3.RequestBody import okhttp3.Response import okhttp3.ResponseBody import okio.Buffer import okio.BufferedSource import okio.ForwardingSource import okio.Okio import okio.Source import org.apache.commons.codec.binary.Hex import org.apache.commons.codec.digest.DigestUtils import org.apache.commons.io.FileUtils import org.apache.commons.io.IOUtils private const val NAME = "ExponentFileSystem" private val TAG = FileSystemModule::class.java.simpleName private const val EXDownloadProgressEventName = "expo-file-system.downloadProgress" private const val EXUploadProgressEventName = "expo-file-system.uploadProgress" private const val MIN_EVENT_DT_MS: Long = 100 private const val HEADER_KEY = "headers" private const val DIR_PERMISSIONS_REQUEST_CODE = 5394 // The class needs to be 'open', because it's inherited in expoview open class FileSystemModule( context: Context, private val moduleRegistryDelegate: ModuleRegistryDelegate = ModuleRegistryDelegate() ) : ExportedModule(context), ActivityEventListener { init { try { ensureDirExists(getContext().filesDir) ensureDirExists(getContext().cacheDir) } catch (e: IOException) { e.printStackTrace() } } private inline fun <reified T> moduleRegistry() = moduleRegistryDelegate.getFromModuleRegistry<T>() private val uIManager: UIManager by moduleRegistry() private var client: OkHttpClient? = null private var dirPermissionsRequest: Promise? = null private val taskHandlers: MutableMap<String, TaskHandler> = HashMap() override fun onCreate(moduleRegistry: ModuleRegistry) { moduleRegistryDelegate.onCreate(moduleRegistry) } override fun getName() = NAME override fun getConstants(): Map<String, Any?> { return mapOf( "documentDirectory" to Uri.fromFile(context.filesDir).toString() + "/", "cacheDirectory" to Uri.fromFile(context.cacheDir).toString() + "/", "bundleDirectory" to "asset:///", ) } @Throws(IOException::class) private fun Uri.checkIfFileExists() { val file = this.toFile() if (!file.exists()) { throw IOException("Directory for '${file.path}' doesn't exist.") } } @Throws(IOException::class) private fun Uri.checkIfFileDirExists() { val file = this.toFile() val dir = file.parentFile if (dir == null || !dir.exists()) { throw IOException("Directory for '${file.path}' doesn't exist. Please make sure directory '${file.parent}' exists before calling downloadAsync.") } } private fun permissionsForPath(path: String?): EnumSet<Permission>? { val filePermissionModule: FilePermissionModuleInterface by moduleRegistry() return filePermissionModule.getPathPermissions(context, path) } private fun permissionsForUri(uri: Uri) = when { uri.isSAFUri -> permissionsForSAFUri(uri) uri.scheme == "content" -> EnumSet.of(Permission.READ) uri.scheme == "asset" -> EnumSet.of(Permission.READ) uri.scheme == "file" -> permissionsForPath(uri.path) uri.scheme == null -> EnumSet.of(Permission.READ) else -> EnumSet.noneOf(Permission::class.java) } private fun permissionsForSAFUri(uri: Uri): EnumSet<Permission> { val documentFile = getNearestSAFFile(uri) return EnumSet.noneOf(Permission::class.java).apply { if (documentFile != null) { if (documentFile.canRead()) { add(Permission.READ) } if (documentFile.canWrite()) { add(Permission.WRITE) } } } } // For now we only need to ensure one permission at a time, this allows easier error message strings, // we can generalize this when needed later @Throws(IOException::class) private fun ensurePermission(uri: Uri, permission: Permission, errorMsg: String) { if (permissionsForUri(uri)?.contains(permission) != true) { throw IOException(errorMsg) } } @Throws(IOException::class) private fun ensurePermission(uri: Uri, permission: Permission) { if (permission == Permission.READ) { ensurePermission(uri, permission, "Location '$uri' isn't readable.") } if (permission == Permission.WRITE) { ensurePermission(uri, permission, "Location '$uri' isn't writable.") } ensurePermission(uri, permission, "Location '$uri' doesn't have permission '${permission.name}'.") } @Throws(IOException::class) private fun openAssetInputStream(uri: Uri): InputStream { // AssetManager expects no leading slash. val asset = requireNotNull(uri.path).substring(1) return context.assets.open(asset) } @Throws(IOException::class) private fun openResourceInputStream(resourceName: String?): InputStream { var resourceId = context.resources.getIdentifier(resourceName, "raw", context.packageName) if (resourceId == 0) { // this resource doesn't exist in the raw folder, so try drawable resourceId = context.resources.getIdentifier(resourceName, "drawable", context.packageName) if (resourceId == 0) { throw FileNotFoundException("No resource found with the name '$resourceName'") } } return context.resources.openRawResource(resourceId) } @ExpoMethod fun getInfoAsync(_uriStr: String, options: Map<String?, Any?>, promise: Promise) { var uriStr = _uriStr try { val uri = Uri.parse(uriStr) var absoluteUri = uri if (uri.scheme == "file") { uriStr = parseFileUri(uriStr) absoluteUri = Uri.parse(uriStr) } ensurePermission(absoluteUri, Permission.READ) if (uri.scheme == "file") { val file = absoluteUri.toFile() if (file.exists()) { promise.resolve( Bundle().apply { putBoolean("exists", true) putBoolean("isDirectory", file.isDirectory) putString("uri", Uri.fromFile(file).toString()) putDouble("size", getFileSize(file).toDouble()) putDouble("modificationTime", 0.001 * file.lastModified()) options["md5"].takeIf { it == true }?.let { putString("md5", md5(file)) } } ) } else { promise.resolve( Bundle().apply { putBoolean("exists", false) putBoolean("isDirectory", false) } ) } } else if (uri.scheme == "content" || uri.scheme == "asset" || uri.scheme == null) { try { val inputStream: InputStream = when (uri.scheme) { "content" -> context.contentResolver.openInputStream(uri) "asset" -> openAssetInputStream(uri) else -> openResourceInputStream(uriStr) } ?: throw FileNotFoundException() promise.resolve( Bundle().apply { putBoolean("exists", true) putBoolean("isDirectory", false) putString("uri", uri.toString()) // NOTE: `.available()` is supposedly not a reliable source of size info, but it's been // more reliable than querying `OpenableColumns.SIZE` in practice in tests ¯\_(ツ)_/¯ putDouble("size", inputStream.available().toDouble()) if (options.containsKey("md5") && options["md5"] == true) { val md5bytes = DigestUtils.md5(inputStream) putString("md5", String(Hex.encodeHex(md5bytes))) } } ) } catch (e: FileNotFoundException) { promise.resolve( Bundle().apply { putBoolean("exists", false) putBoolean("isDirectory", false) } ) } } else { throw IOException("Unsupported scheme for location '$uri'.") } } catch (e: Exception) { e.message?.let { Log.e(TAG, it) } promise.reject(e) } } @ExpoMethod fun readAsStringAsync(uriStr: String?, options: Map<String?, Any?>, promise: Promise) { try { val uri = Uri.parse(uriStr) ensurePermission(uri, Permission.READ) // TODO:Bacon: Add more encoding types to match iOS val encoding = getEncodingFromOptions(options) var contents: String? if (encoding.equals("base64", ignoreCase = true)) { getInputStream(uri).use { inputStream -> contents = if (options.containsKey("length") && options.containsKey("position")) { val length = (options["length"] as Number).toInt() val position = (options["position"] as Number).toInt() val buffer = ByteArray(length) inputStream.skip(position.toLong()) val bytesRead = inputStream.read(buffer, 0, length) Base64.encodeToString(buffer, 0, bytesRead, Base64.NO_WRAP) } else { val inputData = getInputStreamBytes(inputStream) Base64.encodeToString(inputData, Base64.NO_WRAP) } } } else { contents = when { uri.scheme == "file" -> IOUtils.toString(FileInputStream(uri.toFile())) uri.scheme == "asset" -> IOUtils.toString(openAssetInputStream(uri)) uri.scheme == null -> IOUtils.toString(openResourceInputStream(uriStr)) uri.isSAFUri -> IOUtils.toString(context.contentResolver.openInputStream(uri)) else -> throw IOException("Unsupported scheme for location '$uri'.") } } promise.resolve(contents) } catch (e: Exception) { e.message?.let { Log.e(TAG, it) } promise.reject(e) } } @ExpoMethod fun writeAsStringAsync(uriStr: String?, string: String?, options: Map<String?, Any?>, promise: Promise) { try { val uri = Uri.parse(uriStr) ensurePermission(uri, Permission.WRITE) val encoding = getEncodingFromOptions(options) getOutputStream(uri).use { out -> if (encoding == "base64") { val bytes = Base64.decode(string, Base64.DEFAULT) out.write(bytes) } else { OutputStreamWriter(out).use { writer -> writer.write(string) } } } promise.resolve(null) } catch (e: Exception) { e.message?.let { Log.e(TAG, it) } promise.reject(e) } } @ExpoMethod fun deleteAsync(uriStr: String?, options: Map<String?, Any?>, promise: Promise) { try { val uri = Uri.parse(uriStr) val appendedUri = Uri.withAppendedPath(uri, "..") ensurePermission(appendedUri, Permission.WRITE, "Location '$uri' isn't deletable.") if (uri.scheme == "file") { val file = uri.toFile() if (file.exists()) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { FileUtils.forceDelete(file) } else { // to be removed once Android SDK 25 support is dropped forceDelete(file) } promise.resolve(null) } else { if (options.containsKey("idempotent") && options["idempotent"] as Boolean) { promise.resolve(null) } else { promise.reject( "ERR_FILESYSTEM_CANNOT_FIND_FILE", "File '$uri' could not be deleted because it could not be found" ) } } } else if (uri.isSAFUri) { val file = getNearestSAFFile(uri) if (file != null && file.exists()) { file.delete() promise.resolve(null) } else { if (options.containsKey("idempotent") && options["idempotent"] as Boolean) { promise.resolve(null) } else { promise.reject( "ERR_FILESYSTEM_CANNOT_FIND_FILE", "File '$uri' could not be deleted because it could not be found" ) } } } else { throw IOException("Unsupported scheme for location '$uri'.") } } catch (e: Exception) { e.message?.let { Log.e(TAG, it) } promise.reject(e) } } @ExpoMethod fun moveAsync(options: Map<String?, Any?>, promise: Promise) { try { if (!options.containsKey("from")) { promise.reject("ERR_FILESYSTEM_MISSING_PARAMETER", "`FileSystem.moveAsync` needs a `from` path.") return } val fromUri = Uri.parse(options["from"] as String?) ensurePermission(Uri.withAppendedPath(fromUri, ".."), Permission.WRITE, "Location '$fromUri' isn't movable.") if (!options.containsKey("to")) { promise.reject("ERR_FILESYSTEM_MISSING_PARAMETER", "`FileSystem.moveAsync` needs a `to` path.") return } val toUri = Uri.parse(options["to"] as String?) ensurePermission(toUri, Permission.WRITE) if (fromUri.scheme == "file") { val from = fromUri.toFile() val to = toUri.toFile() if (from.renameTo(to)) { promise.resolve(null) } else { promise.reject( "ERR_FILESYSTEM_CANNOT_MOVE_FILE", "File '$fromUri' could not be moved to '$toUri'" ) } } else if (fromUri.isSAFUri) { val documentFile = getNearestSAFFile(fromUri) if (documentFile == null || !documentFile.exists()) { promise.reject("ERR_FILESYSTEM_CANNOT_MOVE_FILE", "File '$fromUri' could not be moved to '$toUri'") return } val output = File(toUri.path) transformFilesFromSAF(documentFile, output, false) promise.resolve(null) } else { throw IOException("Unsupported scheme for location '$fromUri'.") } } catch (e: Exception) { e.message?.let { Log.e(TAG, it) } promise.reject(e) } } @ExpoMethod fun copyAsync(options: Map<String?, Any?>, promise: Promise) { try { if (!options.containsKey("from")) { promise.reject("ERR_FILESYSTEM_MISSING_PARAMETER", "`FileSystem.moveAsync` needs a `from` path.") return } val fromUri = Uri.parse(options["from"] as String?) ensurePermission(fromUri, Permission.READ) if (!options.containsKey("to")) { promise.reject("ERR_FILESYSTEM_MISSING_PARAMETER", "`FileSystem.moveAsync` needs a `to` path.") return } val toUri = Uri.parse(options["to"] as String?) ensurePermission(toUri, Permission.WRITE) when { fromUri.scheme == "file" -> { val from = fromUri.toFile() val to = toUri.toFile() if (from.isDirectory) { FileUtils.copyDirectory(from, to) } else { FileUtils.copyFile(from, to) } promise.resolve(null) } fromUri.isSAFUri -> { val documentFile = getNearestSAFFile(fromUri) if (documentFile == null || !documentFile.exists()) { promise.reject("ERR_FILESYSTEM_CANNOT_FIND_FILE", "File '$fromUri' could not be copied because it could not be found") return } val output = File(toUri.path) transformFilesFromSAF(documentFile, output, true) promise.resolve(null) } fromUri.scheme == "content" -> { val inputStream = context.contentResolver.openInputStream(fromUri) val out: OutputStream = FileOutputStream(toUri.toFile()) IOUtils.copy(inputStream, out) promise.resolve(null) } fromUri.scheme == "asset" -> { val inputStream = openAssetInputStream(fromUri) val out: OutputStream = FileOutputStream(toUri.toFile()) IOUtils.copy(inputStream, out) promise.resolve(null) } fromUri.scheme == null -> { // this is probably an asset embedded by the packager in resources val inputStream = openResourceInputStream(options["from"] as String?) val out: OutputStream = FileOutputStream(toUri.toFile()) IOUtils.copy(inputStream, out) promise.resolve(null) } else -> { throw IOException("Unsupported scheme for location '$fromUri'.") } } } catch (e: Exception) { e.message?.let { Log.e(TAG, it) } promise.reject(e) } } @Throws(IOException::class) private fun transformFilesFromSAF(documentFile: DocumentFile, outputDir: File, copy: Boolean) { if (!documentFile.exists()) { return } if (!outputDir.exists() && !outputDir.mkdirs()) { throw IOException("Couldn't create folder in output dir.") } if (documentFile.isDirectory) { for (file in documentFile.listFiles()) { documentFile.name?.let { transformFilesFromSAF(file, File(outputDir, it), copy) } } if (!copy) { documentFile.delete() } return } documentFile.name?.let { val newFile = File(outputDir.path, it) context.contentResolver.openInputStream(documentFile.uri).use { `in` -> FileOutputStream(newFile).use { out -> IOUtils.copy(`in`, out) } } if (!copy) { documentFile.delete() } } } @ExpoMethod fun makeDirectoryAsync(uriStr: String?, options: Map<String?, Any?>, promise: Promise) { try { val uri = Uri.parse(uriStr) ensurePermission(uri, Permission.WRITE) if (uri.scheme == "file") { val file = uri.toFile() val previouslyCreated = file.isDirectory val setIntermediates = options.containsKey("intermediates") && options["intermediates"] as Boolean val success = if (setIntermediates) file.mkdirs() else file.mkdir() if (success || setIntermediates && previouslyCreated) { promise.resolve(null) } else { promise.reject( "ERR_FILESYSTEM_CANNOT_CREATE_DIRECTORY", "Directory '$uri' could not be created or already exists." ) } } else { throw IOException("Unsupported scheme for location '$uri'.") } } catch (e: Exception) { e.message?.let { Log.e(TAG, it) } promise.reject(e) } } @ExpoMethod fun readDirectoryAsync(uriStr: String?, options: Map<String?, Any?>?, promise: Promise) { try { val uri = Uri.parse(uriStr) ensurePermission(uri, Permission.READ) if (uri.scheme == "file") { val file = uri.toFile() val children = file.listFiles() if (children != null) { val result = children.map { it.name } promise.resolve(result) } else { promise.reject( "ERR_FILESYSTEM_CANNOT_READ_DIRECTORY", "Directory '$uri' could not be read." ) } } else if (uri.isSAFUri) { promise.reject( "ERR_FILESYSTEM_UNSUPPORTED_SCHEME", "Can't read Storage Access Framework directory, use StorageAccessFramework.readDirectoryAsync() instead." ) } else { throw IOException("Unsupported scheme for location '$uri'.") } } catch (e: Exception) { e.message?.let { Log.e(TAG, it) } promise.reject(e) } } @ExpoMethod fun getTotalDiskCapacityAsync(promise: Promise) { try { val root = StatFs(Environment.getDataDirectory().absolutePath) val blockCount = root.blockCountLong val blockSize = root.blockSizeLong val capacity = BigInteger.valueOf(blockCount).multiply(BigInteger.valueOf(blockSize)) // cast down to avoid overflow val capacityDouble = Math.min(capacity.toDouble(), 2.0.pow(53.0) - 1) promise.resolve(capacityDouble) } catch (e: Exception) { e.message?.let { Log.e(TAG, it) } promise.reject("ERR_FILESYSTEM_CANNOT_DETERMINE_DISK_CAPACITY", "Unable to access total disk capacity", e) } } @ExpoMethod fun getFreeDiskStorageAsync(promise: Promise) { try { val external = StatFs(Environment.getDataDirectory().absolutePath) val availableBlocks = external.availableBlocksLong val blockSize = external.blockSizeLong val storage = BigInteger.valueOf(availableBlocks).multiply(BigInteger.valueOf(blockSize)) // cast down to avoid overflow val storageDouble = Math.min(storage.toDouble(), 2.0.pow(53.0) - 1) promise.resolve(storageDouble) } catch (e: Exception) { e.message?.let { Log.e(TAG, it) } promise.reject("ERR_FILESYSTEM_CANNOT_DETERMINE_DISK_CAPACITY", "Unable to determine free disk storage capacity", e) } } @ExpoMethod fun getContentUriAsync(uri: String, promise: Promise) { try { val fileUri = Uri.parse(uri) ensurePermission(fileUri, Permission.WRITE) ensurePermission(fileUri, Permission.READ) fileUri.checkIfFileDirExists() if (fileUri.scheme == "file") { val file = fileUri.toFile() promise.resolve(contentUriFromFile(file).toString()) } else { promise.reject("ERR_FILESYSTEM_CANNOT_READ_DIRECTORY", "No readable files with the uri '$uri'. Please use other uri.") } } catch (e: Exception) { e.message?.let { Log.e(TAG, it) } promise.reject(e) } } private fun contentUriFromFile(file: File): Uri { val activityProvider: ActivityProvider by moduleRegistry() val application = activityProvider.currentActivity.application return FileProvider.getUriForFile(application, "${application.packageName}.FileSystemFileProvider", file) } @ExpoMethod fun readSAFDirectoryAsync(uriStr: String?, options: Map<String?, Any?>?, promise: Promise) { try { val uri = Uri.parse(uriStr) ensurePermission(uri, Permission.READ) if (uri.isSAFUri) { val file = DocumentFile.fromTreeUri(context, uri) if (file == null || !file.exists() || !file.isDirectory) { promise.reject( "ERR_FILESYSTEM_CANNOT_READ_DIRECTORY", "Uri '$uri' doesn't exist or isn't a directory." ) return } val children = file.listFiles() val result = children.map { it.uri.toString() } promise.resolve(result) } else { throw IOException("The URI '$uri' is not a Storage Access Framework URI. Try using FileSystem.readDirectoryAsync instead.") } } catch (e: Exception) { e.message?.let { Log.e(TAG, it) } promise.reject(e) } } @ExpoMethod fun makeSAFDirectoryAsync(uriStr: String?, dirName: String?, promise: Promise) { try { val uri = Uri.parse(uriStr) ensurePermission(uri, Permission.WRITE) if (!uri.isSAFUri) { throw IOException("The URI '$uri' is not a Storage Access Framework URI. Try using FileSystem.makeDirectoryAsync instead.") } val dir = getNearestSAFFile(uri) if (dir != null) { if (!dir.isDirectory) { promise.reject("ERR_FILESYSTEM_CANNOT_CREATE_DIRECTORY", "Provided uri '$uri' is not pointing to a directory.") return } } val newDir = dirName?.let { dir?.createDirectory(it) } if (newDir == null) { promise.reject("ERR_FILESYSTEM_CANNOT_CREATE_DIRECTORY", "Unknown error.") return } promise.resolve(newDir.uri.toString()) } catch (e: Exception) { promise.reject(e) } } @ExpoMethod fun createSAFFileAsync(uriStr: String?, fileName: String?, mimeType: String?, promise: Promise) { try { val uri = Uri.parse(uriStr) ensurePermission(uri, Permission.WRITE) if (uri.isSAFUri) { val dir = getNearestSAFFile(uri) if (dir == null || !dir.isDirectory) { promise.reject("ERR_FILESYSTEM_CANNOT_CREATE_FILE", "Provided uri '$uri' is not pointing to a directory.") return } if (mimeType == null || fileName == null) { promise.reject("ERR_FILESYSTEM_CANNOT_CREATE_FILE", "Parameters fileName and mimeType can not be null.") return } val newFile = dir.createFile(mimeType, fileName) if (newFile == null) { promise.reject("ERR_FILESYSTEM_CANNOT_CREATE_FILE", "Unknown error.") return } promise.resolve(newFile.uri.toString()) } else { throw IOException("The URI '$uri' is not a Storage Access Framework URI.") } } catch (e: Exception) { promise.reject(e) } } @ExpoMethod fun requestDirectoryPermissionsAsync(initialFileUrl: String?, promise: Promise) { if (dirPermissionsRequest != null) { promise.reject("ERR_FILESYSTEM_CANNOT_ASK_FOR_PERMISSIONS", "You have an unfinished permission request.") return } try { val intent = Intent(Intent.ACTION_OPEN_DOCUMENT_TREE) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { initialFileUrl ?.let { Uri.parse(it) } ?.let { intent.putExtra(DocumentsContract.EXTRA_INITIAL_URI, it) } } val activityProvider: ActivityProvider by moduleRegistry() val activity = activityProvider.currentActivity if (activity == null) { promise.reject("ERR_FILESYSTEM_CANNOT_ASK_FOR_PERMISSIONS", "Can't find activity.") return } uIManager.registerActivityEventListener(this) dirPermissionsRequest = promise activity.startActivityForResult(intent, DIR_PERMISSIONS_REQUEST_CODE) } catch (e: Exception) { e.message?.let { Log.e(TAG, it) } promise.reject("ERR_FILESYSTEM_CANNOT_ASK_FOR_PERMISSIONS", "Can't ask for permissions.", e) } } private fun createUploadRequest(url: String, fileUriString: String, options: Map<String, Any>, promise: Promise, decorator: RequestBodyDecorator): Request? { try { val fileUri = Uri.parse(fileUriString) ensurePermission(fileUri, Permission.READ) fileUri.checkIfFileExists() if (!options.containsKey("httpMethod")) { promise.reject("ERR_FILESYSTEM_MISSING_HTTP_METHOD", "Missing HTTP method.", null) return null } val method = options["httpMethod"] as String? if (!options.containsKey("uploadType")) { promise.reject("ERR_FILESYSTEM_MISSING_UPLOAD_TYPE", "Missing upload type.", null) return null } val requestBuilder = Request.Builder().url(url) if (options.containsKey(HEADER_KEY)) { val headers = options[HEADER_KEY] as Map<String, Any>? headers?.forEach { (key, value) -> requestBuilder.addHeader(key, value.toString()) } } val body = createRequestBody(options, decorator, fileUri.toFile()) return requestBuilder.method(method, body).build() } catch (e: Exception) { e.message?.let { Log.e(TAG, it) } promise.reject(e) } return null } private fun createRequestBody(options: Map<String, Any>, decorator: RequestBodyDecorator, file: File): RequestBody? { val uploadType = UploadType.fromInt((options["uploadType"] as Double).toInt()) return when { uploadType === UploadType.BINARY_CONTENT -> { decorator.decorate(RequestBody.create(null, file)) } uploadType === UploadType.MULTIPART -> { val bodyBuilder = MultipartBody.Builder().setType(MultipartBody.FORM) options["parameters"]?.let { (it as Map<String, Any>) .forEach { (key, value) -> bodyBuilder.addFormDataPart(key, value.toString()) } } val mimeType: String = options["mimeType"]?.let { it as String } ?: URLConnection.guessContentTypeFromName(file.name) val fieldName = options["fieldName"]?.let { it as String } ?: file.name bodyBuilder.addFormDataPart(fieldName, file.name, decorator.decorate(RequestBody.create(MediaType.parse(mimeType), file))) bodyBuilder.build() } else -> { throw IllegalArgumentException("ERR_FILESYSTEM_INVALID_UPLOAD_TYPE. " + String.format("Invalid upload type: %s.", options["uploadType"])) } } } @ExpoMethod fun uploadAsync(url: String, fileUriString: String, options: Map<String, Any>, promise: Promise) { val request = createUploadRequest( url, fileUriString, options, promise, RequestBodyDecorator { requestBody -> requestBody } ) ?: return okHttpClient?.let { it.newCall(request).enqueue(object : Callback { override fun onFailure(call: Call, e: IOException) { Log.e(TAG, e.message.toString()) promise.reject(e) } override fun onResponse(call: Call, response: Response) { val result = Bundle().apply { putString("body", response.body()?.string()) putInt("status", response.code()) putBundle("headers", translateHeaders(response.headers())) } response.close() promise.resolve(result) } }) } ?: run { promise.reject(NullPointerException("okHttpClient is null")) } } @ExpoMethod fun uploadTaskStartAsync(url: String, fileUriString: String, uuid: String, options: Map<String, Any>, promise: Promise) { val progressListener: CountingRequestListener = object : CountingRequestListener { private var mLastUpdate: Long = -1 override fun onProgress(bytesWritten: Long, contentLength: Long) { val eventEmitter: EventEmitter by moduleRegistry() val uploadProgress = Bundle() val uploadProgressData = Bundle() val currentTime = System.currentTimeMillis() // Throttle events. Sending too many events will block the JS event loop. // Make sure to send the last event when we're at 100%. if (currentTime > mLastUpdate + MIN_EVENT_DT_MS || bytesWritten == contentLength) { mLastUpdate = currentTime uploadProgressData.putDouble("totalByteSent", bytesWritten.toDouble()) uploadProgressData.putDouble("totalBytesExpectedToSend", contentLength.toDouble()) uploadProgress.putString("uuid", uuid) uploadProgress.putBundle("data", uploadProgressData) eventEmitter.emit(EXUploadProgressEventName, uploadProgress) } } } val request = createUploadRequest( url, fileUriString, options, promise, object : RequestBodyDecorator { override fun decorate(requestBody: RequestBody): RequestBody { return CountingRequestBody(requestBody, progressListener) } } ) ?: return val call = okHttpClient!!.newCall(request) taskHandlers[uuid] = TaskHandler(call) call.enqueue(object : Callback { override fun onFailure(call: Call, e: IOException) { if (call.isCanceled) { promise.resolve(null) return } Log.e(TAG, e.message.toString()) promise.reject(e) } override fun onResponse(call: Call, response: Response) { val result = Bundle() val body = response.body() result.apply { putString("body", body?.string()) putInt("status", response.code()) putBundle("headers", translateHeaders(response.headers())) } response.close() promise.resolve(result) } }) } @ExpoMethod fun downloadAsync(url: String, uriStr: String?, options: Map<String?, Any?>?, promise: Promise) { try { val uri = Uri.parse(uriStr) ensurePermission(uri, Permission.WRITE) uri.checkIfFileDirExists() when { url.contains(":").not() -> { val context = context val resources = context.resources val packageName = context.packageName val resourceId = resources.getIdentifier(url, "raw", packageName) val bufferedSource = Okio.buffer(Okio.source(context.resources.openRawResource(resourceId))) val file = uri.toFile() file.delete() val sink = Okio.buffer(Okio.sink(file)) sink.writeAll(bufferedSource) sink.close() val result = Bundle() result.putString("uri", Uri.fromFile(file).toString()) options?.get("md5").takeIf { it == true }?.let { result.putString("md5", md5(file)) } promise.resolve(result) } "file" == uri.scheme -> { val requestBuilder = Request.Builder().url(url) if (options != null && options.containsKey(HEADER_KEY)) { try { val headers = options[HEADER_KEY] as Map<String, Any>? headers?.forEach { (key, value) -> requestBuilder.addHeader(key, value.toString()) } } catch (exception: ClassCastException) { promise.reject("ERR_FILESYSTEM_INVALID_HEADERS", "Invalid headers dictionary. Keys and values should be strings.", exception) return } } okHttpClient?.newCall(requestBuilder.build())?.enqueue(object : Callback { override fun onFailure(call: Call, e: IOException) { Log.e(TAG, e.message.toString()) promise.reject(e) } @Throws(IOException::class) override fun onResponse(call: Call, response: Response) { val file = uri.toFile() file.delete() val sink = Okio.buffer(Okio.sink(file)) sink.writeAll(response.body()!!.source()) sink.close() val result = Bundle().apply { putString("uri", Uri.fromFile(file).toString()) putInt("status", response.code()) putBundle("headers", translateHeaders(response.headers())) if (options?.get("md5") == true) { putString("md5", md5(file)) } } response.close() promise.resolve(result) } }) ?: run { promise.reject(NullPointerException("okHttpClient is null")) } } else -> throw IOException("Unsupported scheme for location '$uri'.") } } catch (e: Exception) { e.message?.let { Log.e(TAG, it) } promise.reject(e) } } @ExpoMethod fun networkTaskCancelAsync(uuid: String, promise: Promise) { val taskHandler = taskHandlers[uuid] taskHandler?.call?.cancel() promise.resolve(null) } @ExpoMethod fun downloadResumableStartAsync(url: String, fileUriStr: String, uuid: String, options: Map<String?, Any?>, resumeData: String?, promise: Promise) { try { val fileUri = Uri.parse(fileUriStr) fileUri.checkIfFileDirExists() if (fileUri.scheme != "file") { throw IOException("Unsupported scheme for location '$fileUri'.") } val progressListener: ProgressListener = object : ProgressListener { var mLastUpdate: Long = -1 override fun update(bytesRead: Long, contentLength: Long, done: Boolean) { val eventEmitter by moduleRegistry<EventEmitter>() if (eventEmitter != null) { val downloadProgress = Bundle() val downloadProgressData = Bundle() val totalBytesWritten = bytesRead + (resumeData?.toLong() ?: 0) val totalBytesExpectedToWrite = contentLength + (resumeData?.toLong() ?: 0) val currentTime = System.currentTimeMillis() // Throttle events. Sending too many events will block the JS event loop. // Make sure to send the last event when we're at 100%. if (currentTime > mLastUpdate + MIN_EVENT_DT_MS || totalBytesWritten == totalBytesExpectedToWrite) { mLastUpdate = currentTime downloadProgressData.putDouble("totalBytesWritten", totalBytesWritten.toDouble()) downloadProgressData.putDouble("totalBytesExpectedToWrite", totalBytesExpectedToWrite.toDouble()) downloadProgress.putString("uuid", uuid) downloadProgress.putBundle("data", downloadProgressData) eventEmitter.emit(EXDownloadProgressEventName, downloadProgress) } } } } val client = okHttpClient?.newBuilder() ?.addNetworkInterceptor { chain -> val originalResponse = chain.proceed(chain.request()) originalResponse.newBuilder() .body(ProgressResponseBody(originalResponse.body(), progressListener)) .build() } ?.build() if (client == null) { promise.reject(NullPointerException("okHttpClient is null")) return } val requestBuilder = Request.Builder() resumeData.let { requestBuilder.addHeader("Range", "bytes=$it-") } if (options.containsKey(HEADER_KEY)) { val headers = options[HEADER_KEY] as Map<String, Any>? headers?.forEach { (key, value) -> requestBuilder.addHeader(key, value.toString()) } } DownloadResumableTask().apply { val request = requestBuilder.url(url).build() val call = client.newCall(request) taskHandlers[uuid] = DownloadTaskHandler(fileUri, call) val params = DownloadResumableTaskParams( options, call, fileUri.toFile(), resumeData != null, promise ) execute(params) } } catch (e: Exception) { e.message?.let { Log.e(TAG, it) } promise.reject(e) } } @ExpoMethod fun downloadResumablePauseAsync(uuid: String, promise: Promise) { val taskHandler = taskHandlers[uuid] if (taskHandler == null) { val e: Exception = IOException("No download object available") e.message?.let { Log.e(TAG, it) } promise.reject(e) return } if (taskHandler !is DownloadTaskHandler) { promise.reject("ERR_FILESYSTEM_CANNOT_FIND_TASK", "Cannot find task.") return } taskHandler.call.cancel() taskHandlers.remove(uuid) try { val file = taskHandler.fileUri.toFile() val result = Bundle().apply { putString("resumeData", file.length().toString()) } promise.resolve(result) } catch (e: Exception) { e.message?.let { Log.e(TAG, it) } promise.reject(e) } } @SuppressLint("WrongConstant") override fun onActivityResult(activity: Activity, requestCode: Int, resultCode: Int, data: Intent?) { if (requestCode == DIR_PERMISSIONS_REQUEST_CODE && dirPermissionsRequest != null) { val result = Bundle() if (resultCode == Activity.RESULT_OK && data != null) { val treeUri = data.data val takeFlags = ( data.flags and (Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION) ) treeUri?.let { activity.contentResolver.takePersistableUriPermission(it, takeFlags) } result.putBoolean("granted", true) result.putString("directoryUri", treeUri.toString()) } else { result.putBoolean("granted", false) } dirPermissionsRequest?.resolve(result) uIManager.unregisterActivityEventListener(this) dirPermissionsRequest = null } } override fun onNewIntent(intent: Intent) = Unit private class DownloadResumableTaskParams internal constructor(var options: Map<String?, Any?>?, var call: Call, var file: File, var isResume: Boolean, var promise: Promise) private inner class DownloadResumableTask : AsyncTask<DownloadResumableTaskParams?, Void?, Void?>() { override fun doInBackground(vararg params: DownloadResumableTaskParams?): Void? { val call = params[0]?.call val promise = params[0]?.promise val file = params[0]?.file val isResume = params[0]?.isResume val options = params[0]?.options return try { val response = call!!.execute() val responseBody = response.body() val input = BufferedInputStream(responseBody!!.byteStream()) val output = FileOutputStream(file, isResume == true) val data = ByteArray(1024) var count = 0 while (input.read(data).also { count = it } != -1) { output.write(data, 0, count) } val result = Bundle().apply { putString("uri", Uri.fromFile(file).toString()) putInt("status", response.code()) putBundle("headers", translateHeaders(response.headers())) options?.get("md5").takeIf { it == true }?.let { putString("md5", file?.let { md5(it) }) } } response.close() promise?.resolve(result) null } catch (e: Exception) { if (call?.isCanceled == true) { promise?.resolve(null) return null } e.message?.let { Log.e(TAG, it) } promise?.reject(e) null } } } private open class TaskHandler(val call: Call) private class DownloadTaskHandler(val fileUri: Uri, call: Call) : TaskHandler(call) // https://github.com/square/okhttp/blob/master/samples/guide/src/main/java/okhttp3/recipes/Progress.java private class ProgressResponseBody internal constructor(private val responseBody: ResponseBody?, private val progressListener: ProgressListener) : ResponseBody() { private var bufferedSource: BufferedSource? = null override fun contentType(): MediaType? = responseBody?.contentType() override fun contentLength(): Long = responseBody?.contentLength() ?: -1 override fun source(): BufferedSource = bufferedSource ?: Okio.buffer(source(responseBody!!.source())) private fun source(source: Source): Source { return object : ForwardingSource(source) { var totalBytesRead = 0L @Throws(IOException::class) override fun read(sink: Buffer, byteCount: Long): Long { val bytesRead = super.read(sink, byteCount) // read() returns the number of bytes read, or -1 if this source is exhausted. totalBytesRead += if (bytesRead != -1L) bytesRead else 0 progressListener.update( totalBytesRead, responseBody?.contentLength() ?: -1, bytesRead == -1L ) return bytesRead } } } } internal fun interface ProgressListener { fun update(bytesRead: Long, contentLength: Long, done: Boolean) } @get:Synchronized private val okHttpClient: OkHttpClient? get() { if (client == null) { val builder = OkHttpClient.Builder() .connectTimeout(60, TimeUnit.SECONDS) .readTimeout(60, TimeUnit.SECONDS) .writeTimeout(60, TimeUnit.SECONDS) val cookieHandler: CookieHandler by moduleRegistry() builder.cookieJar(JavaNetCookieJar(cookieHandler)) client = builder.build() } return client } @Throws(IOException::class) private fun md5(file: File): String { val inputStream: InputStream = FileInputStream(file) return inputStream.use { val md5bytes = DigestUtils.md5(it) String(Hex.encodeHex(md5bytes)) } } @Throws(IOException::class) private fun ensureDirExists(dir: File) { if (!(dir.isDirectory || dir.mkdirs())) { throw IOException("Couldn't create directory '$dir'") } } /** * Concatenated copy of [email protected]#FileUtils#forceDelete * Newer version of commons-io uses File#toPath() under the hood that unsupported below Android SDK 26 * See docs for reference https://commons.apache.org/proper/commons-io/javadocs/api-1.4/index.html */ @Throws(IOException::class) private fun forceDelete(file: File) { if (file.isDirectory) { val files = file.listFiles() ?: throw IOException("Failed to list contents of $file") var exception: IOException? = null for (f in files) { try { forceDelete(f) } catch (ioe: IOException) { exception = ioe } } if (null != exception) { throw exception } if (!file.delete()) { throw IOException("Unable to delete directory $file.") } } else if (!file.delete()) { throw IOException("Unable to delete file: $file") } } private fun getFileSize(file: File): Long { if (!file.isDirectory) { return file.length() } val content = file.listFiles() ?: return 0 val size = content.map { getFileSize(it) }.reduceOrNull { total, itemSize -> total + itemSize } ?: 0 return size } private fun getEncodingFromOptions(options: Map<String?, Any?>): String { return if (options.containsKey("encoding") && options["encoding"] is String) { (options["encoding"] as String).toLowerCase(Locale.ROOT) } else { "utf8" } } @Throws(IOException::class) private fun getInputStream(uri: Uri) = when { uri.scheme == "file" -> FileInputStream(uri.toFile()) uri.scheme == "asset" -> openAssetInputStream(uri) uri.isSAFUri -> context.contentResolver.openInputStream(uri)!! else -> throw IOException("Unsupported scheme for location '$uri'.") } @Throws(IOException::class) private fun getOutputStream(uri: Uri) = when { uri.scheme == "file" -> FileOutputStream(uri.toFile()) uri.isSAFUri -> context.contentResolver.openOutputStream(uri)!! else -> throw IOException("Unsupported scheme for location '$uri'.") } private fun getNearestSAFFile(uri: Uri): DocumentFile? { val file = DocumentFile.fromSingleUri(context, uri) return if (file != null && file.isFile) { file } else DocumentFile.fromTreeUri(context, uri) } /** * Checks if the provided URI is compatible with the Storage Access Framework. * For more information check out https://developer.android.com/guide/topics/providers/document-provider. * * @param uri * @return whatever the provided URI is SAF URI */ // extension functions of Uri class private fun Uri.toFile() = File(this.path) private val Uri.isSAFUri: Boolean get() = scheme == "content" && host?.startsWith("com.android.externalstorage") ?: false private fun parseFileUri(uriStr: String) = uriStr.substring(uriStr.indexOf(':') + 3) @Throws(IOException::class) private fun getInputStreamBytes(inputStream: InputStream): ByteArray { val bytesResult: ByteArray val byteBuffer = ByteArrayOutputStream() val bufferSize = 1024 val buffer = ByteArray(bufferSize) try { var len: Int while (inputStream.read(buffer).also { len = it } != -1) { byteBuffer.write(buffer, 0, len) } bytesResult = byteBuffer.toByteArray() } finally { try { byteBuffer.close() } catch (ignored: IOException) { } } return bytesResult } // Copied out of React Native's `NetworkingModule.java` private fun translateHeaders(headers: Headers): Bundle { val responseHeaders = Bundle() for (i in 0 until headers.size()) { val headerName = headers.name(i) // multiple values for the same header if (responseHeaders[headerName] != null) { responseHeaders.putString( headerName, responseHeaders.getString(headerName) + ", " + headers.value(i) ) } else { responseHeaders.putString(headerName, headers.value(i)) } } return responseHeaders } }
bsd-3-clause
0eb4d531aee40fcb2f3715c737629ecd
35.904618
175
0.632602
4.475032
false
false
false
false
Undin/intellij-rust
src/main/kotlin/org/rust/cargo/project/settings/impl/SerializationUtils.kt
3
3258
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ @file:JvmName("SerializationUtils") @file:Suppress("unused") package org.rust.cargo.project.settings.impl import com.intellij.util.addOptionTag import com.intellij.util.xmlb.Constants import org.jdom.Element import org.rust.cargo.project.settings.RustProjectSettingsService.MacroExpansionEngine // Bump this number if Rust project settings changes const val XML_FORMAT_VERSION: Int = 2 const val VERSION: String = "version" const val TOOLCHAIN_HOME_DIRECTORY: String = "toolchainHomeDirectory" const val AUTO_UPDATE_ENABLED: String = "autoUpdateEnabled" const val EXPLICIT_PATH_TO_STDLIB: String = "explicitPathToStdlib" const val EXTERNAL_LINTER: String = "externalLinter" const val RUN_EXTERNAL_LINTER_ON_THE_FLY: String = "runExternalLinterOnTheFly" const val EXTERNAL_LINTER_ARGUMENTS: String = "externalLinterArguments" const val COMPILE_ALL_TARGETS: String = "compileAllTargets" const val USE_OFFLINE: String = "useOffline" const val MACRO_EXPANSION_ENGINE: String = "macroExpansionEngine" const val DOCTEST_INJECTION_ENABLED: String = "doctestInjectionEnabled" const val USE_RUSTFMT: String = "useRustfmt" const val RUN_RUSTFMT_ON_SAVE: String = "runRustfmtOnSave" const val USE_SKIP_CHILDREN: String = "useSkipChildren" // Legacy properties needed for migration const val USE_CARGO_CHECK_ANNOTATOR: String = "useCargoCheckAnnotator" const val CARGO_CHECK_ARGUMENTS: String = "cargoCheckArguments" const val EXPAND_MACROS: String = "expandMacros" fun Element.updateToCurrentVersion() { updateToVersionIfNeeded(2) { renameOption(USE_CARGO_CHECK_ANNOTATOR, RUN_EXTERNAL_LINTER_ON_THE_FLY) renameOption(CARGO_CHECK_ARGUMENTS, EXTERNAL_LINTER_ARGUMENTS) if (getOptionValueAsBoolean(EXPAND_MACROS) == false) { setOptionValue(MACRO_EXPANSION_ENGINE, MacroExpansionEngine.DISABLED) } } check(version == XML_FORMAT_VERSION) } private fun Element.updateToVersionIfNeeded(newVersion: Int, update: Element.() -> Unit) { if (version != newVersion - 1) return update() setOptionValue(VERSION, newVersion) } private val Element.version: Int get() = getOptionValueAsInt(VERSION) ?: 1 private fun Element.getOptionWithName(name: String): Element? = children.find { it.getAttribute(Constants.NAME)?.value == name } private fun Element.getOptionValue(name: String): String? = getOptionWithName(name)?.getAttributeValue(Constants.VALUE) private fun Element.getOptionValueAsBoolean(name: String): Boolean? = getOptionValue(name)?.let { when (it) { "true" -> true "false" -> false else -> null } } private fun Element.getOptionValueAsInt(name: String): Int? = getOptionValue(name)?.let { Integer.valueOf(it) } private fun Element.setOptionValue(name: String, value: Any) { val option = getOptionWithName(name) if (option != null) { option.setAttribute(Constants.VALUE, value.toString()) } else { addOptionTag(name, value.toString()) } } private fun Element.renameOption(oldName: String, newName: String) { getOptionWithName(oldName)?.setAttribute(Constants.NAME, newName) }
mit
fb93ff356e29b1c0dfa111d3b4fb574f
36.448276
90
0.741559
3.94431
false
false
false
false
McGars/basekitk
basekitk/src/main/kotlin/com/mcgars/basekitk/tools/custom/StatusBarFrameLayout.kt
1
1609
package com.mcgars.basekitk.tools.custom import android.content.Context import android.graphics.Canvas import android.graphics.Paint import android.os.Build import android.util.AttributeSet import android.view.WindowInsets import com.bluelinelabs.conductor.ChangeHandlerFrameLayout import com.mcgars.basekitk.R import com.mcgars.basekitk.tools.colorAttr import com.mcgars.basekitk.tools.forEach import com.mcgars.basekitk.tools.getStatusBarHeight /** * In some case fitsystem not work correctly, this draw behind * status bar rect with colorAccent */ class StatusBarFrameLayout @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0 ) : ChangeHandlerFrameLayout(context, attrs, defStyleAttr) { private var statusBarHeight = 0f private var paint = Paint().apply { strokeWidth = 0f } init { // make us to use onDraw method setWillNotDraw(false) statusBarHeight = context.getStatusBarHeight().toFloat() // background color of status bar rect paint.color = context.colorAttr(R.attr.colorPrimaryDark) } override fun onDraw(canvas: Canvas) { super.onDraw(canvas) if (width > 0) { canvas.drawRect(0f, 0f, width.toFloat(), statusBarHeight, paint) } } override fun onApplyWindowInsets(insets: WindowInsets): WindowInsets { forEach { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT_WATCH) { it.dispatchApplyWindowInsets(insets) } } return insets } }
apache-2.0
463eca2e3a2124968b4fb6f8097bd123
27.245614
76
0.691112
4.636888
false
false
false
false
taigua/exercism
kotlin/linked-list/src/main/kotlin/Deque.kt
1
1207
/** * Created by Corwin on 2017/2/1. */ private data class Node<T>(val v: T, var previous: Node<T>? = null, var next: Node<T>? = null) class Deque<T> { private var head: Node<T>? = null private var tail: Node<T>? = null fun push(v: T) { val node = Node(v, previous = tail, next = null) tail?.next = node tail = node if (head == null) head = tail } fun pop() : T { if (tail == null) { throw IllegalAccessException("Empty deque.") } val value = tail?.v val p = tail?.previous p?.next = null tail?.previous = null if (head == tail) head = null tail = p return value!! } fun unshift(v: T) { val node = Node(v, previous = null, next = head) head?.previous = node head = node if (tail == null) tail = head } fun shift() : T { if (head == null) { throw IllegalAccessException("Empty deque.") } val value = head?.v val n = head?.next n?.previous = null head?.next = null if (tail == head) tail = null head = n return value!! } }
mit
80f386f60646bb0076f94834cc6a44e4
20.553571
94
0.487987
3.771875
false
false
false
false
eyesniper2/skRayFall
src/main/java/net/rayfall/eyesniper2/skrayfall/effectlibsupport/EffEffectLibAnimatedBallEffect.kt
1
3421
package net.rayfall.eyesniper2.skrayfall.effectlibsupport import ch.njol.skript.Skript import ch.njol.skript.doc.Description import ch.njol.skript.doc.Name import ch.njol.skript.lang.Effect import ch.njol.skript.lang.Expression import ch.njol.skript.lang.SkriptParser import ch.njol.skript.util.VisualEffect import ch.njol.util.Kleenean import de.slikey.effectlib.effect.AnimatedBallEffect import de.slikey.effectlib.util.DynamicLocation import net.rayfall.eyesniper2.skrayfall.Core import org.bukkit.Location import org.bukkit.entity.Entity import org.bukkit.event.Event @Name("Animated Ball Effect") @Description("Creates an EffectLib animated ball effect.") class EffEffectLibAnimatedBallEffect : Effect() { // (spawn|create|apply) (a|the|an) animated ball (effect|formation) (at|on|for|to) // %entity/location% with id %string% [with particle %visualeffects%][ off set by %number%, // %number%(,| and) %number%] private var targetExpression: Expression<*>? = null private var idExpression: Expression<String>? = null private var visualEffectExpression: Expression<VisualEffect>? = null private var xOffsetExpression: Expression<Number>? = null private var yOffsetExpression: Expression<Number>? = null private var zOffsetExpression: Expression<Number>? = null @Suppress("UNCHECKED_CAST") override fun init(exp: Array<Expression<*>?>, arg1: Int, arg2: Kleenean, arg3: SkriptParser.ParseResult): Boolean { targetExpression = exp[0] idExpression = exp[1] as Expression<String> visualEffectExpression = exp[2] as? Expression<VisualEffect> xOffsetExpression = exp[3] as Expression<Number> yOffsetExpression = exp[4] as Expression<Number> zOffsetExpression = exp[5] as Expression<Number> return true } override fun toString(arg0: Event?, arg1: Boolean): String { return "" } override fun execute(evt: Event) { val target = targetExpression?.getSingle(evt) val id = idExpression?.getSingle(evt) val baseEffect = AnimatedBallEffect(Core.effectManager) if (id == null) { Skript.warning("Id was null for EffectLib Animated Ball") return } when (target) { is Entity -> { baseEffect.setDynamicOrigin(DynamicLocation(target as Entity?)) } is Location -> { baseEffect.setDynamicOrigin(DynamicLocation(target as Location?)) } else -> { assert(false) } } val particle = EffectLibUtils.getParticleFromVisualEffect(visualEffectExpression?.getSingle(evt)) if (particle != null) { baseEffect.particle = particle } val xOffset = xOffsetExpression?.getSingle(evt) val yOffset = yOffsetExpression?.getSingle(evt) val zOffset = zOffsetExpression?.getSingle(evt) if (xOffset != null && yOffset != null && zOffset != null) { baseEffect.xOffset = xOffset.toFloat() baseEffect.yOffset = yOffset.toFloat() baseEffect.zOffset = zOffset.toFloat() } baseEffect.infinite() baseEffect.start() val setEffectSuccess = Core.rayfallEffectManager.setEffect(baseEffect, id.replace("\"", "")) if (!setEffectSuccess) { baseEffect.cancel() } } }
gpl-3.0
5053aa0db76e304c7284b827e671eefa
35.021053
119
0.663549
4.281602
false
false
false
false
androidx/androidx
work/work-multiprocess/src/androidTest/java/androidx/work/multiprocess/ParcelableWorkContinuationImplTest.kt
3
8736
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.work.multiprocess import android.content.Context import android.os.Build import androidx.arch.core.executor.ArchTaskExecutor import androidx.arch.core.executor.TaskExecutor import androidx.test.core.app.ApplicationProvider import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.filters.MediumTest import androidx.work.Configuration import androidx.work.ExistingWorkPolicy import androidx.work.OneTimeWorkRequest import androidx.work.WorkRequest import androidx.work.impl.Scheduler import androidx.work.impl.WorkContinuationImpl import androidx.work.impl.WorkManagerImpl import androidx.work.impl.utils.SerialExecutorImpl import androidx.work.impl.utils.SynchronousExecutor import androidx.work.impl.utils.taskexecutor.SerialExecutor import androidx.work.multiprocess.parcelable.ParcelConverters.marshall import androidx.work.multiprocess.parcelable.ParcelConverters.unmarshall import androidx.work.multiprocess.parcelable.ParcelableWorkContinuationImpl import org.junit.Assert.assertEquals import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.mockito.Mockito.`when` import org.mockito.Mockito.mock import org.mockito.Mockito.spy import java.util.concurrent.Executor @RunWith(AndroidJUnit4::class) public class ParcelableWorkContinuationImplTest { private lateinit var context: Context private lateinit var workManager: WorkManagerImpl @Before public fun setUp() { if (Build.VERSION.SDK_INT <= 27) { // Exclude <= API 27, from tests because it causes a SIGSEGV. return } context = ApplicationProvider.getApplicationContext<Context>() val taskExecutor = object : TaskExecutor() { override fun executeOnDiskIO(runnable: Runnable) { runnable.run() } override fun isMainThread(): Boolean { return true } override fun postToMainThread(runnable: Runnable) { runnable.run() } } ArchTaskExecutor.getInstance().setDelegate(taskExecutor) val scheduler = mock(Scheduler::class.java) val configuration = Configuration.Builder() .setExecutor(SynchronousExecutor()) .build() workManager = spy( WorkManagerImpl( context, configuration, object : androidx.work.impl.utils.taskexecutor.TaskExecutor { val executor = Executor { it.run() } val serialExecutor = SerialExecutorImpl(executor) override fun getMainThreadExecutor(): Executor { return serialExecutor } override fun getSerialTaskExecutor(): SerialExecutor { return serialExecutor } } ) ) `when`<List<Scheduler>>(workManager.schedulers).thenReturn(listOf(scheduler)) WorkManagerImpl.setDelegate(workManager) } @Test @MediumTest public fun basicContinuationTest() { if (Build.VERSION.SDK_INT <= 27) { // Exclude <= API 27, from tests because it causes a SIGSEGV. return } val first = OneTimeWorkRequest.Builder(TestWorker::class.java).build() val second = OneTimeWorkRequest.Builder(TestWorker::class.java).build() val continuation = workManager.beginWith(listOf(first)).then(second) val parcelable = ParcelableWorkContinuationImpl(continuation as WorkContinuationImpl) assertOn(parcelable) } @Test @MediumTest public fun continuationTests2() { if (Build.VERSION.SDK_INT <= 27) { // Exclude <= API 27, from tests because it causes a SIGSEGV. return } val first = OneTimeWorkRequest.Builder(TestWorker::class.java).build() val second = OneTimeWorkRequest.Builder(TestWorker::class.java).build() val third = OneTimeWorkRequest.Builder(TestWorker::class.java).build() val continuation = workManager.beginWith(listOf(first, second)).then(third) val parcelable = ParcelableWorkContinuationImpl(continuation as WorkContinuationImpl) assertOn(parcelable) } @Test @MediumTest public fun continuationTest3() { if (Build.VERSION.SDK_INT <= 27) { // Exclude <= API 27, from tests because it causes a SIGSEGV. return } val first = OneTimeWorkRequest.Builder(TestWorker::class.java).build() val second = OneTimeWorkRequest.Builder(TestWorker::class.java).build() val continuation = workManager.beginUniqueWork( "test", ExistingWorkPolicy.REPLACE, listOf(first) ).then(second) val parcelable = ParcelableWorkContinuationImpl(continuation as WorkContinuationImpl) assertOn(parcelable) } @Test @MediumTest public fun continuationTest4() { if (Build.VERSION.SDK_INT <= 27) { // Exclude <= API 27, from tests because it causes a SIGSEGV. return } val first = OneTimeWorkRequest.Builder(TestWorker::class.java).build() val second = OneTimeWorkRequest.Builder(TestWorker::class.java).build() val continuation = workManager.beginUniqueWork( "test", ExistingWorkPolicy.REPLACE, listOf(first) ).then(second) val parcelable = ParcelableWorkContinuationImpl(continuation as WorkContinuationImpl) val continuation2 = parcelable.info.toWorkContinuationImpl(workManager) equal( ParcelableWorkContinuationImpl(continuation).info, ParcelableWorkContinuationImpl(continuation2).info ) } @Test @MediumTest public fun combineContinuationTests() { if (Build.VERSION.SDK_INT <= 27) { // Exclude <= API 27, from tests because it causes a SIGSEGV. return } val first = OneTimeWorkRequest.Builder(TestWorker::class.java).build() val second = OneTimeWorkRequest.Builder(TestWorker::class.java).build() val third = OneTimeWorkRequest.Builder(TestWorker::class.java).build() val continuation1 = workManager.beginWith(listOf(first, second)).then(third) val fourth = OneTimeWorkRequest.Builder(TestWorker::class.java).build() val fifth = OneTimeWorkRequest.Builder(TestWorker::class.java).build() val sixth = OneTimeWorkRequest.Builder(TestWorker::class.java).build() val continuation2 = workManager.beginWith(listOf(fourth, fifth)).then(sixth) val continuation = WorkContinuationImpl.combine(listOf(continuation1, continuation2)) val parcelable = ParcelableWorkContinuationImpl(continuation as WorkContinuationImpl) assertOn(parcelable) } // Utilities private fun assertOn(parcelable: ParcelableWorkContinuationImpl) { val parcelable2 = unmarshall(marshall(parcelable), ParcelableWorkContinuationImpl.CREATOR) equal(parcelable.info, parcelable2.info) } private fun equal( first: ParcelableWorkContinuationImpl.WorkContinuationImplInfo, second: ParcelableWorkContinuationImpl.WorkContinuationImplInfo ) { assertEquals(first.name, second.name) assertEquals(first.existingWorkPolicy, second.existingWorkPolicy) assertRequests(first.work, second.work) assertEquals(first.parentInfos?.size, first.parentInfos?.size) first.parentInfos?.forEachIndexed { i, info -> equal(info, second.parentInfos!![i]) } } private fun assertRequest(first: WorkRequest, second: WorkRequest) { assertEquals(first.id, second.id) assertEquals(first.workSpec, second.workSpec) assertEquals(first.tags, second.tags) } private fun assertRequests(listOne: List<WorkRequest>, listTwo: List<WorkRequest>) { listOne.forEachIndexed { i, workRequest -> assertRequest(workRequest, listTwo[i]) } } }
apache-2.0
cad2c992e59e8f801a5fec2e562cdc12
37.654867
98
0.680746
5.132785
false
true
false
false
androidx/androidx
bluetooth/integration-tests/testapp/src/main/java/androidx/bluetooth/integration/testapp/ui/framework/FwkFragment.kt
3
5312
/* * 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.bluetooth.integration.testapp.ui.framework import android.annotation.SuppressLint import android.bluetooth.BluetoothManager import android.bluetooth.le.AdvertiseCallback import android.bluetooth.le.AdvertiseData import android.bluetooth.le.AdvertiseSettings import android.bluetooth.le.ScanCallback import android.bluetooth.le.ScanResult import android.bluetooth.le.ScanSettings import android.content.Context import android.os.Bundle import android.os.ParcelUuid import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Toast import androidx.bluetooth.integration.testapp.R import androidx.bluetooth.integration.testapp.databinding.FragmentFwkBinding import androidx.fragment.app.Fragment import androidx.navigation.fragment.findNavController class FwkFragment : Fragment() { companion object { const val TAG = "FwkFragment" val ServiceUUID: ParcelUuid = ParcelUuid.fromString("0000b81d-0000-1000-8000-00805f9b34fb") } private val scanCallback = object : ScanCallback() { override fun onScanResult(callbackType: Int, result: ScanResult?) { Log.d(TAG, "onScanResult() called with: callbackType = $callbackType, result = $result") } override fun onBatchScanResults(results: MutableList<ScanResult>?) { Log.d(TAG, "onBatchScanResults() called with: results = $results") } override fun onScanFailed(errorCode: Int) { Log.d(TAG, "onScanFailed() called with: errorCode = $errorCode") } } private val advertiseCallback = object : AdvertiseCallback() { override fun onStartFailure(errorCode: Int) { Log.d(TAG, "onStartFailure() called with: errorCode = $errorCode") } override fun onStartSuccess(settingsInEffect: AdvertiseSettings?) { Log.d(TAG, "onStartSuccess() called") } } private var _binding: FragmentFwkBinding? = null // This property is only valid between onCreateView and onDestroyView. private val binding get() = _binding!! override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { _binding = FragmentFwkBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) binding.buttonNext.setOnClickListener { findNavController().navigate(R.id.action_FwkFragment_to_BtxFragment) } binding.buttonScan.setOnClickListener { scan() } binding.switchAdvertise.setOnClickListener { if (binding.switchAdvertise.isChecked) startAdvertise() } } override fun onDestroyView() { super.onDestroyView() _binding = null } // Permissions are handled by MainActivity requestBluetoothPermissions @SuppressLint("MissingPermission") private fun scan() { Log.d(TAG, "scan() called") val bluetoothManager = context?.getSystemService(Context.BLUETOOTH_SERVICE) as? BluetoothManager val bluetoothAdapter = bluetoothManager?.adapter val bleScanner = bluetoothAdapter?.bluetoothLeScanner val scanSettings = ScanSettings.Builder() .setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY) .build() bleScanner?.startScan(null, scanSettings, scanCallback) Toast.makeText(context, getString(R.string.scan_start_message), Toast.LENGTH_LONG) .show() } // Permissions are handled by MainActivity requestBluetoothPermissions @SuppressLint("MissingPermission") private fun startAdvertise() { Log.d(TAG, "startAdvertise() called") val bluetoothManager = context?.getSystemService(Context.BLUETOOTH_SERVICE) as? BluetoothManager val bluetoothAdapter = bluetoothManager?.adapter val bleAdvertiser = bluetoothAdapter?.bluetoothLeAdvertiser val advertiseSettings = AdvertiseSettings.Builder() .setAdvertiseMode(AdvertiseSettings.ADVERTISE_MODE_LOW_LATENCY) .setTimeout(0) .build() val advertiseData = AdvertiseData.Builder() .addServiceUuid(ServiceUUID) .setIncludeDeviceName(true) .build() bleAdvertiser?.startAdvertising(advertiseSettings, advertiseData, advertiseCallback) Toast.makeText(context, getString(R.string.advertise_start_message), Toast.LENGTH_LONG) .show() } }
apache-2.0
650f75c8bc76dea1522a7021a43e161c
33.270968
100
0.701242
4.833485
false
false
false
false
TUWien/DocScan
app/src/main/java/at/ac/tuwien/caa/docscan/db/model/MetaData.kt
1
2586
package at.ac.tuwien.caa.docscan.db.model import android.os.Parcelable import androidx.annotation.Keep import androidx.room.ColumnInfo import kotlinx.parcelize.Parcelize @Parcelize @Keep data class MetaData( /** * Represents the related upload id, this is usually available when a document is created * from a QR-code, which can be then used for uploads so that a document is associated to * specific document in the backend already. */ @ColumnInfo(name = KEY_RELATED_UPLOAD_ID) var relatedUploadId: Int? = null, /** * Transkribus author related tag */ @ColumnInfo(name = KEY_AUTHOR) var author: String?, /** * Transkribus authority related tag */ @ColumnInfo(name = KEY_AUTHORITY) var authority: String?, /** * Transkribus authority related tag */ @ColumnInfo(name = KEY_HIERARCHY) var hierarchy: String?, /** * Transkribus genre related tag */ @ColumnInfo(name = KEY_GENRE) var genre: String?, /** * Transkribus language related tag */ @ColumnInfo(name = KEY_LANGUAGE) var language: String?, /** * Transkribus isProjectReadme2020 related tag */ @ColumnInfo(name = KEY_IS_PROJECT_README_2020) var isProjectReadme2020: Boolean, /** * Transkribus allowImagePublication related tag */ @ColumnInfo(name = KEY_ALLOW_IMAGE_PUBLICATION) var allowImagePublication: Boolean, /** * Transkribus signature related tag */ @ColumnInfo(name = KEY_SIGNATURE) var signature: String?, /** * Transkribus url related tag */ @ColumnInfo(name = KEY_URL) var url: String?, /** * Transkribus writer related tag */ @ColumnInfo(name = KEY_WRITER) var writer: String?, /** * Transkribus description tag (only set from the QR-code) */ @ColumnInfo(name = KEY_DESCRIPTION) var description: String? ) : Parcelable { companion object { const val KEY_RELATED_UPLOAD_ID = "related_upload_id" const val KEY_AUTHOR = "author" const val KEY_WRITER = "writer" const val KEY_DESCRIPTION = "description" const val KEY_GENRE = "genre" const val KEY_SIGNATURE = "signature" const val KEY_AUTHORITY = "authority" const val KEY_HIERARCHY = "hierarchy" const val KEY_URL = "url" const val KEY_LANGUAGE = "language" const val KEY_IS_PROJECT_README_2020 = "is_project_readme_2020" const val KEY_ALLOW_IMAGE_PUBLICATION = "allow_image_publication" } }
lgpl-3.0
60458f96193d317be29ab8aa4d6dce92
28.05618
93
0.640758
4.267327
false
false
false
false
kenrube/Fantlab-client
app/src/main/kotlin/ru/fantlab/android/ui/adapter/viewholder/ResponseViewHolder.kt
2
3356
package ru.fantlab.android.ui.adapter.viewholder import android.view.View import android.view.ViewGroup import kotlinx.android.synthetic.main.response_row_item.view.* import ru.fantlab.android.R import ru.fantlab.android.data.dao.model.Response import ru.fantlab.android.helper.FantlabHelper import ru.fantlab.android.helper.InputHelper import ru.fantlab.android.helper.getTimeAgo import ru.fantlab.android.helper.parseFullDate import ru.fantlab.android.provider.scheme.LinkParserHelper import ru.fantlab.android.provider.storage.WorkTypesProvider import ru.fantlab.android.ui.modules.work.CyclePagerActivity import ru.fantlab.android.ui.modules.work.WorkPagerActivity import ru.fantlab.android.ui.widgets.recyclerview.BaseRecyclerAdapter import ru.fantlab.android.ui.widgets.recyclerview.BaseViewHolder class ResponseViewHolder(itemView: View, adapter: BaseRecyclerAdapter<Response, ResponseViewHolder>) : BaseViewHolder<Response>(itemView, adapter) { override fun bind(response: Response) { itemView.avatarLayout.setUrl("https://${LinkParserHelper.HOST_DATA}/images/users/${response.userId}") itemView.responseUser.text = response.userName.capitalize() itemView.userInfo.setOnClickListener { listener?.onOpenContextMenu(response) } itemView.date.text = response.dateIso.parseFullDate(true).getTimeAgo() itemView.authors.text = if (!InputHelper.isEmpty(response.workAuthor)) response.workAuthor else response.workAuthorOrig itemView.workName.text = if (response.workName.isNotEmpty()) response.workName else response.workNameOrig itemView.coverLayout.setUrl("https:${response.workImage}", WorkTypesProvider.getCoverByTypeId(response.workTypeId)) itemView.coverLayout.setOnClickListener { if (response.workTypeId == FantlabHelper.WorkType.WORK_TYPE_CYCLE.id) CyclePagerActivity.startActivity(itemView.context, response.workId, response.workName, 0) else WorkPagerActivity.startActivity(itemView.context, response.workId, response.workName, 0) } itemView.responseText.text = response.text .replace("(\r\n)+".toRegex(), "\n") .replace("\\[spoiler].*|\\[\\/spoiler]".toRegex(), "") .replace("\\[.*]".toRegex(), "") .replace(":\\w+:".toRegex(), "") if (response.mark == null) { itemView.rating.visibility = View.GONE } else { itemView.rating.text = response.mark.toString() itemView.rating.visibility = View.VISIBLE } response.voteCount.let { when { it < 0 -> { itemView.votes.setDrawables(R.drawable.ic_thumb_down) itemView.votes.text = response.voteCount.toString() itemView.votes.visibility = View.VISIBLE } it > 0 -> { itemView.votes.setDrawables(R.drawable.ic_thumb_up) itemView.votes.text = response.voteCount.toString() itemView.votes.visibility = View.VISIBLE } else -> itemView.votes.visibility = View.GONE } } } interface OnOpenContextMenu { fun onOpenContextMenu(userItem: Response) } companion object { private var listener: OnOpenContextMenu? = null fun newInstance( viewGroup: ViewGroup, adapter: BaseRecyclerAdapter<Response, ResponseViewHolder> ): ResponseViewHolder { return ResponseViewHolder(getView(viewGroup, R.layout.response_row_item), adapter) } fun setOnContextMenuListener(listener: ResponseViewHolder.OnOpenContextMenu) { this.listener = listener } } }
gpl-3.0
51080690a4dafaeba0ed349bac5fa1e6
35.096774
121
0.763111
3.86191
false
false
false
false
Gnar-Team/Gnar-bot
src/main/kotlin/xyz/gnarbot/gnar/commands/settings/PrefixCommand.kt
1
2385
package xyz.gnarbot.gnar.commands.settings import net.dv8tion.jda.api.Permission import xyz.gnarbot.gnar.commands.BotInfo import xyz.gnarbot.gnar.commands.Category import xyz.gnarbot.gnar.commands.Command import xyz.gnarbot.gnar.commands.Context import xyz.gnarbot.gnar.commands.template.CommandTemplate import xyz.gnarbot.gnar.commands.template.annotations.Description @Command( aliases = ["prefix"], usage = "(set|reset) [string]", description = "Set the bot prefix for the server." ) @BotInfo( id = 56, category = Category.SETTINGS, permissions = [Permission.MANAGE_SERVER] ) class PrefixCommand : CommandTemplate() { private val mention = Regex("<@!?(\\d+)>|<#(\\d+)>|<@&(\\d+)>") @Description("Set the prefix.") fun set(context: Context, prefix: String) { if (prefix matches mention) { context.send().error("The prefix can't be set to a mention.").queue() return } if (context.data.command.prefix == prefix) { context.send().error("The prefix is already set to `$prefix`.").queue() return } if (prefix == "__" || prefix == "~~" || prefix == "**" || prefix == "`" || prefix == "```" || prefix == "*" || prefix == "_") { context.send().error("To prevent markdown formatting issues, `$prefix` is not an allowable prefix.").queue() return } context.data.command.prefix = prefix context.data.save() context.send().info("The prefix has been set to `${context.data.command.prefix}`.").queue() } @Description("Reset to the default prefix.") fun reset(context: Context) { if (context.data.command.prefix == null) { context.send().error("The prefix is already set to the default.").queue() return } context.data.command.prefix = null context.data.save() context.send().info("The prefix has been reset to `${context.bot.configuration.prefix}`.").queue() } override fun onWalkFail(context: Context, args: Array<String>, depth: Int) { onWalkFail(context, args, depth, null, buildString { append("Default prefix will still be valid.\n") val prefix = context.data.command.prefix append("Current prefix: `").append(prefix).append('`') }) } }
mit
24f3b4460daea802ce79f11b7d0790bf
34.61194
135
0.607966
4.184211
false
false
false
false
elect86/jAssimp
src/main/kotlin/assimp/BaseImporter.kt
1
6671
package assimp import assimp.format.ProgressHandler import glm_.plus import glm_.shl /** * Created by elect on 13/11/2016. */ /** utility to do char4 to uint32 in a portable manner */ fun AI_MAKE_MAGIC(string: String) = (string[0] shl 24) + (string[1] shl 16) + (string[2] shl 8) + string[3] abstract class BaseImporter { /** The error description of the last error that occurred. An empty string if there was no error. */ var errorText = "" private set /** Currently set progress handler. */ var progress: ProgressHandler? = null /** Returns whether the class can handle the format of the given file. *. * The implementation should be as quick as possible. A check for the file extension is enough. If no suitable * loader is found with this strategy, canRead() is called again, the 'checkSig' parameter set to true this time. * Now the implementation is expected to perform a full check of the file structure, possibly searching the first * bytes of the file for magic identifiers or keywords. * * @param file Path and file name of the file to be examined. * @param checkSig Set to true if this method is called a second time. This time, the implementation may take more * time to examine the contents of the file to be loaded for magic bytes, keywords, etc to be able to load files * with unknown/not existent file extensions. * @return true if the class can read this file, false if not. */ abstract fun canRead(file: String, ioSystem: IOSystem, checkSig: Boolean): Boolean /** Imports the given file and returns the imported data. * If the import succeeds, ownership of the data is transferred to the caller. If the import fails, null is * returned. The function takes care that any partially constructed data is destroyed beforehand. * * @param imp Importer object hosting this loader. * @param file Path of the file to be imported. * @return The imported data or null if failed. If it failed a human-readable error description can be retrieved * by accessing errorText * * @note This function is not intended to be overridden. Implement internReadFile() to do the import. If an * exception is thrown somewhere in internReadFile(), this function will catch it and transform it into a suitable * response to the caller. */ fun readFile(imp: Importer, ioHandler: IOSystem = ASSIMP.defaultIOSystem, filePath: String): AiScene? { progress = imp.progressHandler assert(progress != null) // Gather configuration properties for this run setupProperties(imp) // create a scene object to hold the data val sc = AiScene() // dispatch importing try { internReadFile(filePath, ioHandler, sc) } catch (err: Exception) { // extract error description logger.error(err) {} errorText = err.localizedMessage return null } // return what we gathered from the import. return sc } /** Called prior to ReadFile(). * The function is a request to the importer to update its configuration basing on the Importer's configuration * property list. * @param imp Importer instance */ open fun setupProperties(imp: Importer) = Unit /** Called by Importer::GetImporterInfo to get a description of some loader features. Importers must provide this * information. */ abstract val info: AiImporterDesc /** Called by Importer::GetExtensionList for each loaded importer. * Take the extension list contained in the structure returned by info and insert all file extensions into the * given set. * @param extension set to collect file extensions in*/ val extensionList get() = info.fileExtensions /** Imports the given file into the given scene structure. The function is expected to throw an ImportErrorException * if there is an error. If it terminates normally, the data in AiScene is expected to be correct. Override this * function to implement the actual importing. * <br> * The output scene must meet the following requirements:<br> * <ul> * <li>At least a root node must be there, even if its only purpose is to reference one mesh.</li> * <li>AiMesh.primitiveTypes may be 0. The types of primitives in the mesh are determined automatically in this * case.</li> * <li>the vertex data is stored in a pseudo-indexed "verbose" format. * In fact this means that every vertex that is referenced by a face is unique. Or the other way round: a vertex * index may not occur twice in a single AiMesh.</li> * <li>AiAnimation.duration may be -1. Assimp determines the length of the animation automatically in this case as * the length of the longest animation channel.</li> * <li>AiMesh.bitangents may be null if tangents and normals are given. In this case bitangents are computed as the * cross product between normal and tangent.</li> * <li>There needn't be a material. If none is there a default material is generated. However, it is recommended * practice for loaders to generate a default material for yourself that matches the default material setting for * the file format better than Assimp's generic default material. Note that default materials *should* be named * AI_DEFAULT_MATERIAL_NAME if they're just color-shaded or AI_DEFAULT_TEXTURED_MATERIAL_NAME if they define a * (dummy) texture. </li> * </ul> * If the AI_SCENE_FLAGS_INCOMPLETE-Flag is <b>not</b> set:<ul> * <li> at least one mesh must be there</li> * <li> there may be no meshes with 0 vertices or faces</li> * </ul> * This won't be checked (except by the validation step): Assimp will crash if one of the conditions is not met! * * @param file Path of the file to be imported. * @param scene The scene object to hold the imported data. Null is not a valid parameter. * */ open fun internReadFile(file: String, ioSystem: IOSystem, scene: AiScene) = Unit companion object { /** Extract file extension from a string * @param file Input file * @return extension without trailing dot, all lowercase */ fun getExtension (file: String): String { val pos = file.indexOfLast { it == '.' } // no file extension at all if( pos == -1) return "" return file.substring(pos+1).toLowerCase() // thanks to Andy Maloney for the hint } } }
mit
0f40a97f85d509fb63fd37233875a2b7
47.70073
120
0.677859
4.474178
false
false
false
false
andrewoma/kwery
core/src/main/kotlin/com/github/andrewoma/kwery/core/dialect/HsqlDialect.kt
1
2172
/* * Copyright (c) 2015 Andrew O'Malley * * 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.github.andrewoma.kwery.core.dialect import java.sql.* open class HsqlDialect : Dialect { override fun bind(value: Any, limit: Int): String = when (value) { is String -> escapeSingleQuotedString(value.truncate(limit)) is Timestamp -> timestampFormat.get().format(value) is Date -> "'$value'" is Time -> "'$value'" is java.sql.Array -> bindArray(value, limit, "array[", "]") is Blob -> standardBlob(value, limit) is ByteArray -> standardByteArray(value, limit) is Clob -> escapeSingleQuotedString(standardClob(value, limit)) else -> value.toString() } override val supportsArrayBasedIn = true override fun arrayBasedIn(name: String) = "in(unnest(:$name))" override val supportsAllocateIds = true override fun allocateIds(count: Int, sequence: String, columnName: String) = "select next value for $sequence as $columnName from unnest(sequence_array(1, $count, 1))" override val supportsFetchingGeneratedKeysByName = true }
mit
f8c8223d09082942f736d6e0cf3dfb2f
41.607843
102
0.716851
4.40568
false
false
false
false
UCSoftworks/LeafDb
leafdb-core/src/main/java/com/ucsoftworks/leafdb/DbUtils.kt
1
1468
package com.ucsoftworks.leafdb import com.ucsoftworks.leafdb.wrapper.ILeafDbCursor import java.util.* /** * Created by Pasenchuk Victor on 19/08/2017 */ internal fun appendEscapedSQLString(sb: StringBuilder, sqlString: String) { sb.append('\'') if (sqlString.indexOf('\'') != -1) { val length = sqlString.length for (i in 0..length - 1) { val c = sqlString[i] if (c == '\'') { sb.append('\'') } sb.append(c) } } else sb.append(sqlString) sb.append('\'') } /** * SQL-escape a string. */ internal fun sqlEscapeString(value: String): String { val escaper = StringBuilder() appendEscapedSQLString(escaper, value) return escaper.toString() } internal val Any?.sqlValue: String get() = when (this) { null -> "NULL" is Number -> this.toString() is Date -> this.time.toString() else -> sqlEscapeString(this.toString()) } internal fun ILeafDbCursor?.collectIndexedStrings(position: Int = 1): List<Pair<Long, String>> { val strings = mutableListOf<Pair<Long, String>>() try { if (this != null && !this.isClosed && !this.empty) do { strings.add(Pair(this.getLong(1), this.getString(position))) } while (this.moveToNext()) } finally { if (this != null && !this.isClosed) { this.close() } } return strings }
lgpl-3.0
f7fdf5b60576417a82211c9b15329dfe
23.483333
96
0.56812
3.893899
false
false
false
false
Heiner1/AndroidAPS
core/src/main/java/info/nightscout/androidaps/plugins/general/overview/notifications/NotificationUserMessage.kt
1
355
package info.nightscout.androidaps.plugins.general.overview.notifications class NotificationUserMessage (text :String): Notification() { init { var hash = text.hashCode() if (hash < USER_MESSAGE) hash += USER_MESSAGE id = hash date = System.currentTimeMillis() this.text = text level = URGENT } }
agpl-3.0
3a1eb9d3d0acb4e60009d78834193115
26.384615
73
0.639437
4.4375
false
false
false
false
Unpublished/AmazeFileManager
app/src/main/java/com/amaze/filemanager/filesystem/compressed/extractcontents/helpers/RarExtractor.kt
2
8919
/* * Copyright (C) 2014-2021 Arpit Khurana <[email protected]>, Vishal Nehra <[email protected]>, * Emmanuel Messulam<[email protected]>, Raymond Lai <airwave209gt at gmail.com> and Contributors. * * This file is part of Amaze File Manager. * * Amaze File Manager 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.amaze.filemanager.filesystem.compressed.extractcontents.helpers import android.content.Context import com.amaze.filemanager.asynchronous.management.ServiceWatcherUtil import com.amaze.filemanager.file_operations.filesystem.compressed.ArchivePasswordCache import com.amaze.filemanager.file_operations.utils.UpdatePosition import com.amaze.filemanager.filesystem.FileUtil import com.amaze.filemanager.filesystem.MakeDirectoryOperation import com.amaze.filemanager.filesystem.compressed.CompressedHelper import com.amaze.filemanager.filesystem.compressed.extractcontents.Extractor import com.amaze.filemanager.filesystem.compressed.isPasswordProtectedCompat import com.amaze.filemanager.filesystem.files.GenericCopyUtil import com.github.junrar.Archive import com.github.junrar.exception.CorruptHeaderException import com.github.junrar.exception.RarException import com.github.junrar.exception.UnsupportedRarV5Exception import com.github.junrar.rarfile.FileHeader import org.apache.commons.compress.PasswordRequiredException import java.io.BufferedInputStream import java.io.BufferedOutputStream import java.io.File import java.io.IOException import java.util.zip.CRC32 import java.util.zip.CheckedOutputStream class RarExtractor( context: Context, filePath: String, outputPath: String, listener: OnUpdate, updatePosition: UpdatePosition ) : Extractor(context, filePath, outputPath, listener, updatePosition) { @Throws(IOException::class) override fun extractWithFilter(filter: Filter) { try { var totalBytes: Long = 0 val rarFile: Archive = runCatching { ArchivePasswordCache.getInstance()[filePath]?.let { Archive(File(filePath), it).also { archive -> archive.password = it } } ?: Archive(File(filePath)) }.onFailure { if (UnsupportedRarV5Exception::class.java.isAssignableFrom(it::class.java)) { throw it } else { throw PasswordRequiredException(filePath) } }.getOrNull()!! if (rarFile.isPasswordProtectedCompat() || rarFile.isEncrypted) { if (ArchivePasswordCache.getInstance().containsKey(filePath)) { runCatching { tryExtractSmallestFileInArchive(context, rarFile) }.onFailure { throw PasswordRequiredException(filePath) }.onSuccess { File(it).delete() } } else { throw PasswordRequiredException(filePath) } } val fileHeaders: List<FileHeader> // iterating archive elements to find file names that are to be extracted rarFile.fileHeaders.partition { header -> CompressedHelper.isEntryPathValid(header.fileName) }.apply { fileHeaders = first totalBytes = first.sumOf { it.fullUnpackSize } invalidArchiveEntries = second.map { it.fileName } } if (fileHeaders.isNotEmpty()) { listener.onStart(totalBytes, fileHeaders[0].fileName) fileHeaders.forEach { entry -> if (!listener.isCancelled) { listener.onUpdate(entry.fileName) extractEntry(context, rarFile, entry, outputPath) } } listener.onFinish() } else { throw EmptyArchiveNotice() } } catch (e: RarException) { throw IOException(e) } } @Throws(IOException::class) private fun extractEntry( context: Context, rarFile: Archive, entry: FileHeader, outputDir: String ) { var _entry = entry val entrySpawnsVolumes = entry.isSplitAfter val name = fixEntryName(entry.fileName).replace( "\\\\".toRegex(), CompressedHelper.SEPARATOR ) val outputFile = File(outputDir, name) if (!outputFile.canonicalPath.startsWith(outputDir)) { throw IOException("Incorrect RAR FileHeader path!") } if (entry.isDirectory) { MakeDirectoryOperation.mkdir(outputFile, context) outputFile.setLastModified(entry.mTime.time) return } if (!outputFile.parentFile.exists()) { MakeDirectoryOperation.mkdir(outputFile.parentFile, context) outputFile.parentFile.setLastModified(entry.mTime.time) } /* junrar doesn't throw exceptions if wrong archive password is supplied, until extracted file CRC is compared against the one stored in archive. So we can only rely on verifying CRC during extracting */ val inputStream = BufferedInputStream(rarFile.getInputStream(entry)) val outputStream = CheckedOutputStream( BufferedOutputStream(FileUtil.getOutputStream(outputFile, context)), CRC32() ) try { var len: Int val buf = ByteArray(GenericCopyUtil.DEFAULT_BUFFER_SIZE) while (inputStream.read(buf).also { len = it } != -1) { if (!listener.isCancelled) { outputStream.write(buf, 0, len) ServiceWatcherUtil.position += len.toLong() } else break } /* In multi-volume archives, FileHeader may have changed as the other parts of the archive is processed. Need to lookup the FileHeader in the volume the archive currently resides on again, as the correct CRC of the extract file will be there instead. */ if (entrySpawnsVolumes) { _entry = rarFile.fileHeaders.find { it.fileName.equals(entry.fileName) }!! } /* junrar does not provide convenient way to verify archive password is correct, we can only rely on post-extract file checksum matching to see if the file is extracted correctly = correct password. RAR header stores checksum in signed 2's complement (as hex though). Some bitwise ops needed to compare with CheckOutputStream used above, which always produces checksum in unsigned long */ if (_entry.fileCRC.toLong() and 0xffffffffL != outputStream.checksum.value) { throw IOException("Checksum verification failed for entry $name") } } finally { outputStream.close() inputStream.close() outputFile.setLastModified(entry.mTime.time) } } private fun tryExtractSmallestFileInArchive(context: Context, archive: Archive): String { archive.fileHeaders ?: throw IOException(CorruptHeaderException()) with( archive.fileHeaders.filter { !it.isDirectory } ) { if (isEmpty()) { throw IOException(CorruptHeaderException()) } else { associateBy({ it.fileName }, { it.fullUnpackSize }) .minByOrNull { it.value }!!.run { val header = archive.fileHeaders.find { it.fileName.equals(this.key) }!! val filename = fixEntryName(header.fileName).replace( "\\\\".toRegex(), CompressedHelper.SEPARATOR ) extractEntry(context, archive, header, context.externalCacheDir!!.absolutePath) return "${context.externalCacheDir!!.absolutePath}/$filename" } } } } }
gpl-3.0
26e2e5801cee6a747f35b9e2fe55aa0f
41.471429
107
0.612737
5.356757
false
false
false
false
k9mail/k-9
app/ui/legacy/src/main/java/com/fsck/k9/ui/settings/account/AccountSettingsDataStore.kt
2
13674
package com.fsck.k9.ui.settings.account import androidx.preference.PreferenceDataStore import com.fsck.k9.Account import com.fsck.k9.Account.SpecialFolderSelection import com.fsck.k9.NotificationLight import com.fsck.k9.NotificationVibration import com.fsck.k9.Preferences import com.fsck.k9.job.K9JobManager import com.fsck.k9.notification.NotificationChannelManager import com.fsck.k9.notification.NotificationController import java.util.concurrent.ExecutorService class AccountSettingsDataStore( private val preferences: Preferences, private val executorService: ExecutorService, private val account: Account, private val jobManager: K9JobManager, private val notificationChannelManager: NotificationChannelManager, private val notificationController: NotificationController ) : PreferenceDataStore() { private var notificationSettingsChanged = false override fun getBoolean(key: String, defValue: Boolean): Boolean { return when (key) { "mark_message_as_read_on_view" -> account.isMarkMessageAsReadOnView "mark_message_as_read_on_delete" -> account.isMarkMessageAsReadOnDelete "account_sync_remote_deletetions" -> account.isSyncRemoteDeletions "always_show_cc_bcc" -> account.isAlwaysShowCcBcc "message_read_receipt" -> account.isMessageReadReceipt "default_quoted_text_shown" -> account.isDefaultQuotedTextShown "reply_after_quote" -> account.isReplyAfterQuote "strip_signature" -> account.isStripSignature "account_notify" -> account.isNotifyNewMail "account_notify_self" -> account.isNotifySelfNewMail "account_notify_contacts_mail_only" -> account.isNotifyContactsMailOnly "account_notify_sync" -> account.isNotifySync "openpgp_hide_sign_only" -> account.isOpenPgpHideSignOnly "openpgp_encrypt_subject" -> account.isOpenPgpEncryptSubject "openpgp_encrypt_all_drafts" -> account.isOpenPgpEncryptAllDrafts "autocrypt_prefer_encrypt" -> account.autocryptPreferEncryptMutual "upload_sent_messages" -> account.isUploadSentMessages "ignore_chat_messages" -> account.isIgnoreChatMessages else -> defValue } } override fun putBoolean(key: String, value: Boolean) { when (key) { "mark_message_as_read_on_view" -> account.isMarkMessageAsReadOnView = value "mark_message_as_read_on_delete" -> account.isMarkMessageAsReadOnDelete = value "account_sync_remote_deletetions" -> account.isSyncRemoteDeletions = value "always_show_cc_bcc" -> account.isAlwaysShowCcBcc = value "message_read_receipt" -> account.isMessageReadReceipt = value "default_quoted_text_shown" -> account.isDefaultQuotedTextShown = value "reply_after_quote" -> account.isReplyAfterQuote = value "strip_signature" -> account.isStripSignature = value "account_notify" -> account.isNotifyNewMail = value "account_notify_self" -> account.isNotifySelfNewMail = value "account_notify_contacts_mail_only" -> account.isNotifyContactsMailOnly = value "account_notify_sync" -> account.isNotifySync = value "openpgp_hide_sign_only" -> account.isOpenPgpHideSignOnly = value "openpgp_encrypt_subject" -> account.isOpenPgpEncryptSubject = value "openpgp_encrypt_all_drafts" -> account.isOpenPgpEncryptAllDrafts = value "autocrypt_prefer_encrypt" -> account.autocryptPreferEncryptMutual = value "upload_sent_messages" -> account.isUploadSentMessages = value "ignore_chat_messages" -> account.isIgnoreChatMessages = value else -> return } saveSettingsInBackground() } override fun getInt(key: String?, defValue: Int): Int { return when (key) { "chip_color" -> account.chipColor else -> defValue } } override fun putInt(key: String?, value: Int) { when (key) { "chip_color" -> setAccountColor(value) else -> return } saveSettingsInBackground() } override fun getLong(key: String?, defValue: Long): Long { return when (key) { "openpgp_key" -> account.openPgpKey else -> defValue } } override fun putLong(key: String?, value: Long) { when (key) { "openpgp_key" -> account.openPgpKey = value else -> return } saveSettingsInBackground() } override fun getString(key: String, defValue: String?): String? { return when (key) { "account_description" -> account.name "show_pictures_enum" -> account.showPictures.name "account_display_count" -> account.displayCount.toString() "account_message_age" -> account.maximumPolledMessageAge.toString() "account_autodownload_size" -> account.maximumAutoDownloadMessageSize.toString() "account_check_frequency" -> account.automaticCheckIntervalMinutes.toString() "folder_sync_mode" -> account.folderSyncMode.name "folder_push_mode" -> account.folderPushMode.name "delete_policy" -> account.deletePolicy.name "expunge_policy" -> account.expungePolicy.name "max_push_folders" -> account.maxPushFolders.toString() "idle_refresh_period" -> account.idleRefreshMinutes.toString() "message_format" -> account.messageFormat.name "quote_style" -> account.quoteStyle.name "account_quote_prefix" -> account.quotePrefix "account_setup_auto_expand_folder" -> { loadSpecialFolder(account.autoExpandFolderId, SpecialFolderSelection.MANUAL) } "folder_display_mode" -> account.folderDisplayMode.name "folder_target_mode" -> account.folderTargetMode.name "searchable_folders" -> account.searchableFolders.name "archive_folder" -> loadSpecialFolder(account.archiveFolderId, account.archiveFolderSelection) "drafts_folder" -> loadSpecialFolder(account.draftsFolderId, account.draftsFolderSelection) "sent_folder" -> loadSpecialFolder(account.sentFolderId, account.sentFolderSelection) "spam_folder" -> loadSpecialFolder(account.spamFolderId, account.spamFolderSelection) "trash_folder" -> loadSpecialFolder(account.trashFolderId, account.trashFolderSelection) "folder_notify_new_mail_mode" -> account.folderNotifyNewMailMode.name "account_combined_vibration" -> getCombinedVibrationValue() "account_remote_search_num_results" -> account.remoteSearchNumResults.toString() "account_ringtone" -> account.notificationSettings.ringtone "notification_light" -> account.notificationSettings.light.name else -> defValue } } override fun putString(key: String, value: String?) { if (value == null) return when (key) { "account_description" -> account.name = value "show_pictures_enum" -> account.showPictures = Account.ShowPictures.valueOf(value) "account_display_count" -> account.displayCount = value.toInt() "account_message_age" -> account.maximumPolledMessageAge = value.toInt() "account_autodownload_size" -> account.maximumAutoDownloadMessageSize = value.toInt() "account_check_frequency" -> { if (account.updateAutomaticCheckIntervalMinutes(value.toInt())) { reschedulePoll() } } "folder_sync_mode" -> { if (account.updateFolderSyncMode(Account.FolderMode.valueOf(value))) { reschedulePoll() } } "folder_push_mode" -> account.folderPushMode = Account.FolderMode.valueOf(value) "delete_policy" -> account.deletePolicy = Account.DeletePolicy.valueOf(value) "expunge_policy" -> account.expungePolicy = Account.Expunge.valueOf(value) "max_push_folders" -> account.maxPushFolders = value.toInt() "idle_refresh_period" -> account.idleRefreshMinutes = value.toInt() "message_format" -> account.messageFormat = Account.MessageFormat.valueOf(value) "quote_style" -> account.quoteStyle = Account.QuoteStyle.valueOf(value) "account_quote_prefix" -> account.quotePrefix = value "account_setup_auto_expand_folder" -> account.autoExpandFolderId = extractFolderId(value) "folder_display_mode" -> account.folderDisplayMode = Account.FolderMode.valueOf(value) "folder_target_mode" -> account.folderTargetMode = Account.FolderMode.valueOf(value) "searchable_folders" -> account.searchableFolders = Account.Searchable.valueOf(value) "archive_folder" -> saveSpecialFolderSelection(value, account::setArchiveFolderId) "drafts_folder" -> saveSpecialFolderSelection(value, account::setDraftsFolderId) "sent_folder" -> saveSpecialFolderSelection(value, account::setSentFolderId) "spam_folder" -> saveSpecialFolderSelection(value, account::setSpamFolderId) "trash_folder" -> saveSpecialFolderSelection(value, account::setTrashFolderId) "folder_notify_new_mail_mode" -> account.folderNotifyNewMailMode = Account.FolderMode.valueOf(value) "account_combined_vibration" -> setCombinedVibrationValue(value) "account_remote_search_num_results" -> account.remoteSearchNumResults = value.toInt() "account_ringtone" -> setNotificationSound(value) "notification_light" -> setNotificationLight(value) else -> return } saveSettingsInBackground() } private fun setAccountColor(color: Int) { if (color != account.chipColor) { account.chipColor = color if (account.notificationSettings.light == NotificationLight.AccountColor) { notificationSettingsChanged = true } } } private fun setNotificationSound(value: String) { account.notificationSettings.let { notificationSettings -> if (!notificationSettings.isRingEnabled || notificationSettings.ringtone != value) { account.updateNotificationSettings { it.copy(isRingEnabled = true, ringtone = value) } notificationSettingsChanged = true } } } private fun setNotificationLight(value: String) { val light = NotificationLight.valueOf(value) if (light != account.notificationSettings.light) { account.updateNotificationSettings { it.copy(light = light) } notificationSettingsChanged = true } } fun saveSettingsInBackground() { executorService.execute { if (notificationSettingsChanged) { notificationChannelManager.recreateMessagesNotificationChannel(account) notificationController.restoreNewMailNotifications(listOf(account)) } notificationSettingsChanged = false saveSettings() } } private fun saveSettings() { preferences.saveAccount(account) } private fun reschedulePoll() { jobManager.scheduleMailSync(account) } private fun extractFolderId(preferenceValue: String): Long? { val folderValue = preferenceValue.substringAfter(FolderListPreference.FOLDER_VALUE_DELIMITER) return if (folderValue == FolderListPreference.NO_FOLDER_VALUE) null else folderValue.toLongOrNull() } private fun saveSpecialFolderSelection( preferenceValue: String, specialFolderSetter: (Long?, SpecialFolderSelection) -> Unit ) { val specialFolder = extractFolderId(preferenceValue) val specialFolderSelection = if (preferenceValue.startsWith(FolderListPreference.AUTOMATIC_PREFIX)) { SpecialFolderSelection.AUTOMATIC } else { SpecialFolderSelection.MANUAL } specialFolderSetter(specialFolder, specialFolderSelection) } private fun loadSpecialFolder(specialFolderId: Long?, specialFolderSelection: SpecialFolderSelection): String { val prefix = when (specialFolderSelection) { SpecialFolderSelection.AUTOMATIC -> FolderListPreference.AUTOMATIC_PREFIX SpecialFolderSelection.MANUAL -> FolderListPreference.MANUAL_PREFIX } return prefix + (specialFolderId?.toString() ?: FolderListPreference.NO_FOLDER_VALUE) } private fun getCombinedVibrationValue(): String { return with(account.notificationSettings.vibration) { VibrationPreference.encode( isVibrationEnabled = isEnabled, vibratePattern = pattern, vibrationTimes = repeatCount ) } } private fun setCombinedVibrationValue(value: String) { val (isVibrationEnabled, vibrationPattern, vibrationTimes) = VibrationPreference.decode(value) account.updateNotificationSettings { notificationSettings -> notificationSettings.copy( vibration = NotificationVibration( isEnabled = isVibrationEnabled, pattern = vibrationPattern, repeatCount = vibrationTimes, ) ) } notificationSettingsChanged = true } }
apache-2.0
ea01a7d6912165ae01910eaab1d1d5eb
46.314879
115
0.658549
4.959739
false
false
false
false
JetBrains/ideavim
vim-engine/src/main/kotlin/com/maddyhome/idea/vim/vimscript/model/expressions/SublistExpression.kt
1
2334
/* * Copyright 2003-2022 The IdeaVim authors * * Use of this source code is governed by an MIT-style * license that can be found in the LICENSE.txt file or at * https://opensource.org/licenses/MIT. */ package com.maddyhome.idea.vim.vimscript.model.expressions import com.maddyhome.idea.vim.api.ExecutionContext import com.maddyhome.idea.vim.api.VimEditor import com.maddyhome.idea.vim.ex.ExException import com.maddyhome.idea.vim.vimscript.model.VimLContext import com.maddyhome.idea.vim.vimscript.model.datatypes.VimDataType import com.maddyhome.idea.vim.vimscript.model.datatypes.VimDictionary import com.maddyhome.idea.vim.vimscript.model.datatypes.VimList import com.maddyhome.idea.vim.vimscript.model.datatypes.VimString data class SublistExpression(val from: Expression?, val to: Expression?, val expression: Expression) : Expression() { override fun evaluate(editor: VimEditor, context: ExecutionContext, vimContext: VimLContext): VimDataType { val expressionValue = expression.evaluate(editor, context, vimContext) val arraySize = when (expressionValue) { is VimDictionary -> throw ExException("E719: Cannot slice a Dictionary") is VimList -> expressionValue.values.size else -> expressionValue.asString().length } var fromInt = Integer.parseInt(from?.evaluate(editor, context, vimContext)?.asString() ?: "0") if (fromInt < 0) { fromInt += arraySize } var toInt = Integer.parseInt(to?.evaluate(editor, context, vimContext)?.asString() ?: (arraySize - 1).toString()) if (toInt < 0) { toInt += arraySize } return if (expressionValue is VimList) { if (fromInt > arraySize) { VimList(mutableListOf()) } else if (fromInt == toInt) { expressionValue.values[fromInt] } else if (fromInt <= toInt) { VimList(expressionValue.values.subList(fromInt, toInt + 1)) } else { VimList(mutableListOf()) } } else { if (fromInt > arraySize) { VimString("") } else if (fromInt <= toInt) { if (toInt > expressionValue.asString().length - 1) { VimString(expressionValue.asString().substring(fromInt)) } else { VimString(expressionValue.asString().substring(fromInt, toInt + 1)) } } else { VimString("") } } } }
mit
30aea9b23fd52bd76e8701cf84421c02
37.262295
117
0.687232
4.298343
false
false
false
false
wordpress-mobile/WordPress-Android
WordPress/src/test/java/org/wordpress/android/ui/mediapicker/loader/MediaLoaderTest.kt
1
8245
package org.wordpress.android.ui.mediapicker.loader import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.delay import kotlinx.coroutines.flow.collect import kotlinx.coroutines.launch import org.assertj.core.api.Assertions.assertThat import org.junit.Before import org.junit.Test import org.mockito.Mock import org.mockito.kotlin.any import org.mockito.kotlin.isNull import org.mockito.kotlin.whenever import org.wordpress.android.BaseUnitTest import org.wordpress.android.test import org.wordpress.android.ui.mediapicker.MediaItem import org.wordpress.android.ui.mediapicker.MediaItem.Identifier import org.wordpress.android.ui.mediapicker.MediaType.IMAGE import org.wordpress.android.ui.mediapicker.MediaType.VIDEO import org.wordpress.android.ui.mediapicker.loader.MediaLoader.DomainModel import org.wordpress.android.ui.mediapicker.loader.MediaLoader.LoadAction import org.wordpress.android.ui.mediapicker.loader.MediaSource.MediaLoadingResult import org.wordpress.android.ui.utils.UiString.UiStringText class MediaLoaderTest : BaseUnitTest() { @Mock lateinit var mediaSource: MediaSource @Mock lateinit var identifier1: Identifier @Mock lateinit var identifier2: Identifier private lateinit var mediaLoader: MediaLoader private lateinit var firstMediaItem: MediaItem private lateinit var secondMediaItem: MediaItem @Before fun setUp() { mediaLoader = MediaLoader(mediaSource) firstMediaItem = MediaItem(identifier1, "url://first_item", "first item", IMAGE, "image/jpeg", 1) secondMediaItem = MediaItem(identifier2, "url://second_item", "second item", VIDEO, "video/mpeg", 2) } @Test fun `loads media items on start`() = withMediaLoader { resultModel, performAction -> val mediaItems = listOf(firstMediaItem) whenever( mediaSource.load( forced = false, loadMore = false ) ).thenReturn(MediaLoadingResult.Success(mediaItems, hasMore = false)) performAction(LoadAction.Start(), true) resultModel.assertModel(mediaItems) } @Test fun `shows an error when loading fails`() = withMediaLoader { resultModel, performAction -> val errorMessage = "error" whenever(mediaSource.load(forced = false, loadMore = false)).thenReturn( MediaLoadingResult.Failure( UiStringText(errorMessage) ) ) performAction(LoadAction.Start(), true) resultModel.assertModel(errorMessage = errorMessage) } @Test fun `loads next page`() = withMediaLoader { resultModel, performAction -> val firstPage = MediaLoadingResult.Success(listOf(firstMediaItem), hasMore = true) val secondPage = MediaLoadingResult.Success(listOf(firstMediaItem, secondMediaItem)) whenever(mediaSource.load(forced = false, loadMore = false)).thenReturn(firstPage) whenever(mediaSource.load(forced = false, loadMore = true)).thenReturn(secondPage) performAction(LoadAction.Start(), true) resultModel.assertModel(listOf(firstMediaItem), hasMore = true) performAction(LoadAction.NextPage, true) resultModel.assertModel(listOf(firstMediaItem, secondMediaItem), hasMore = false) } @Test fun `shows an error when loading next page fails`() = withMediaLoader { resultModel, performAction -> val firstPage = MediaLoadingResult.Success(listOf(firstMediaItem), hasMore = true) val message = "error" val secondPage = MediaLoadingResult.Failure(UiStringText(message), data = listOf(firstMediaItem)) whenever(mediaSource.load(forced = false, loadMore = false)).thenReturn(firstPage) whenever(mediaSource.load(forced = false, loadMore = true)).thenReturn(secondPage) performAction(LoadAction.Start(), true) resultModel.assertModel(listOf(firstMediaItem), hasMore = true) performAction(LoadAction.NextPage, true) resultModel.assertModel(listOf(firstMediaItem), errorMessage = message, hasMore = true) } @Test fun `refresh overrides data`() = withMediaLoader { resultModel, performAction -> val firstResult = MediaLoadingResult.Success(listOf(firstMediaItem)) val secondResult = MediaLoadingResult.Success(listOf(secondMediaItem)) whenever(mediaSource.load(any(), any(), isNull())).thenReturn(firstResult, secondResult) performAction(LoadAction.Start(), true) resultModel.assertModel(listOf(firstMediaItem)) performAction(LoadAction.Refresh(true), true) resultModel.assertModel(listOf(secondMediaItem)) } @Test fun `filters out media item`() = withMediaLoader { resultModel, performAction -> val mediaItems = listOf(firstMediaItem, secondMediaItem) val filter = "second" whenever(mediaSource.load(forced = false, loadMore = false)).thenReturn(MediaLoadingResult.Success(mediaItems)) whenever( mediaSource.load( forced = false, loadMore = false, filter = filter ) ).thenReturn(MediaLoadingResult.Success(listOf(secondMediaItem))) performAction(LoadAction.Start(), true) performAction(LoadAction.Filter(filter), true) resultModel.assertModel(listOf(secondMediaItem)) performAction(LoadAction.ClearFilter, true) resultModel.assertModel(mediaItems) } @Test fun `clears filter`() = withMediaLoader { resultModel, performAction -> val mediaItems = listOf(firstMediaItem, secondMediaItem) val filter = "second" whenever( mediaSource.load( forced = false, loadMore = false, filter = filter ) ).thenReturn(MediaLoadingResult.Success(listOf(secondMediaItem))) whenever( mediaSource.load( forced = false, loadMore = false ) ).thenReturn(MediaLoadingResult.Success(mediaItems)) performAction(LoadAction.Start(), true) performAction(LoadAction.Filter(filter), true) performAction(LoadAction.ClearFilter, true) resultModel.assertModel(mediaItems) } private fun List<DomainModel>.assertModel( mediaItems: List<MediaItem> = listOf(), errorMessage: String? = null, hasMore: Boolean = false ) { this.last().apply { assertThat(this.domainItems).isEqualTo(mediaItems) if (errorMessage != null) { assertThat(this.emptyState?.title).isEqualTo(UiStringText(errorMessage)) assertThat(this.emptyState?.isError).isTrue() } else { assertThat(this.emptyState?.title).isNull() } assertThat(this.hasMore).isEqualTo(hasMore) } } private fun withMediaLoader( assertFunction: suspend ( domainModels: List<DomainModel>, performAction: suspend ( action: LoadAction, awaitResult: Boolean ) -> Unit ) -> Unit ) = test { val loadActions: Channel<LoadAction> = Channel() val domainModels: MutableList<DomainModel> = mutableListOf() val job = launch { mediaLoader.loadMedia(loadActions).collect { domainModels.add(it) } } assertFunction(domainModels) { action, awaitResult -> val currentCount = domainModels.size loadActions.send(action) if (awaitResult) { domainModels.awaitResult(currentCount + 1) } } job.cancel() } private suspend fun List<DomainModel>.awaitResult(count: Int) { val limit = 10 var counter = 0 while (counter < limit && this.size < count) { counter++ delay(1) } } }
gpl-2.0
adc57963e0109d19f92b880a7ce7ffd4
36.648402
119
0.642207
5.364346
false
true
false
false
wordpress-mobile/WordPress-Android
WordPress/src/main/java/org/wordpress/android/ui/LayoutBehaviors.kt
1
3590
package org.wordpress.android.ui import android.content.Context import android.util.AttributeSet import android.view.View import android.view.View.MeasureSpec import android.view.animation.AccelerateInterpolator import androidx.coordinatorlayout.widget.CoordinatorLayout import androidx.core.view.marginBottom import com.google.android.material.floatingactionbutton.FloatingActionButton import com.google.android.material.snackbar.Snackbar.SnackbarLayout import org.wordpress.android.ui.WPTooltipView.TooltipPosition.ABOVE /** * This class will let WPTooltipViewBehavior anchor above FloatingActionButton with transition animation. */ class WPTooltipViewBehavior : CoordinatorLayout.Behavior<WPTooltipView> { constructor() : super() constructor(context: Context, attr: AttributeSet) : super(context, attr) override fun layoutDependsOn(parent: CoordinatorLayout, child: WPTooltipView, dependency: View): Boolean { return dependency is FloatingActionButton } override fun onDependentViewChanged(parent: CoordinatorLayout, child: WPTooltipView, dependency: View): Boolean { if (child.position != ABOVE) { // Remove this condition if you want to support different TooltipPosition throw IllegalArgumentException("This behavior only supports TooltipPosition.ABOVE") } if (dependency.measuredWidth == 0 || child.measuredWidth == 0) { dependency.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED) child.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED) } child.x = dependency.x - child.measuredWidth + dependency.measuredWidth child.y = dependency.y - child.measuredHeight return true } override fun onDependentViewRemoved(parent: CoordinatorLayout, child: WPTooltipView, dependency: View) { super.onDependentViewRemoved(parent, child, dependency) child.visibility = View.GONE } } /** * This class will let FloatingActionButton anchor above SnackBar with transition animation. */ class FloatingActionButtonBehavior : CoordinatorLayout.Behavior<FloatingActionButton> { constructor() : super() constructor(context: Context, attrs: AttributeSet) : super(context, attrs) override fun layoutDependsOn(parent: CoordinatorLayout, child: FloatingActionButton, dependency: View): Boolean { return dependency is SnackbarLayout } override fun onDependentViewChanged( parent: CoordinatorLayout, child: FloatingActionButton, dependency: View ): Boolean { if (dependency.visibility == View.VISIBLE) { moveChildUp(child, dependency.height + dependency.marginBottom) return true } return false } override fun onDependentViewRemoved(parent: CoordinatorLayout, child: FloatingActionButton, dependency: View) { moveChildToInitialPosition(child) } private fun moveChildUp(child: View, translation: Int) { child.animate() .translationY((-translation).toFloat()) .setInterpolator(AccelerateInterpolator()) .setDuration(child.resources.getInteger(android.R.integer.config_shortAnimTime).toLong()) .start() } private fun moveChildToInitialPosition(child: View) { child.animate() .translationY(0f) .setInterpolator(AccelerateInterpolator()) .setDuration(child.resources.getInteger(android.R.integer.config_shortAnimTime).toLong()) .start() } }
gpl-2.0
bccfe65d3d391b1b78bcd327ad78176c
38.021739
117
0.717549
5.334324
false
false
false
false
ingokegel/intellij-community
plugins/git4idea/src/git4idea/light/LightGitStatusBarWidget.kt
5
2912
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package git4idea.light import com.intellij.ide.lightEdit.LightEdit import com.intellij.ide.lightEdit.LightEditCompatible import com.intellij.ide.lightEdit.LightEditService import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.project.Project import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.text.HtmlBuilder import com.intellij.openapi.wm.StatusBar import com.intellij.openapi.wm.StatusBarWidget import com.intellij.openapi.wm.StatusBarWidgetFactory import com.intellij.util.Consumer import git4idea.i18n.GitBundle import java.awt.Component import java.awt.event.MouseEvent private const val ID = "light.edit.git" private val LOG = Logger.getInstance("#git4idea.light.LightGitStatusBarWidget") private class LightGitStatusBarWidget(private val lightGitTracker: LightGitTracker) : StatusBarWidget, StatusBarWidget.TextPresentation { private var statusBar: StatusBar? = null init { lightGitTracker.addUpdateListener(object : LightGitTrackerListener { override fun update() { statusBar?.updateWidget(ID()) } }, this) } override fun ID(): String = ID override fun install(statusBar: StatusBar) { this.statusBar = statusBar } override fun getPresentation(): StatusBarWidget.WidgetPresentation = this override fun getText(): String { return lightGitTracker.currentLocation?.let { GitBundle.message("git.light.status.bar.text", it) } ?: "" } override fun getTooltipText(): String { val locationText = lightGitTracker.currentLocation?.let { GitBundle.message("git.light.status.bar.tooltip", it) } ?: "" if (locationText.isBlank()) return locationText val selectedFile = LightEditService.getInstance().selectedFile if (selectedFile != null) { val statusText = lightGitTracker.getFileStatus(selectedFile).getPresentation() if (statusText.isNotBlank()) return HtmlBuilder().append(locationText).br().append(statusText).toString() } return locationText } override fun getAlignment(): Float = Component.LEFT_ALIGNMENT override fun getClickConsumer(): Consumer<MouseEvent>? = null override fun dispose() = Unit } class LightGitStatusBarWidgetFactory : StatusBarWidgetFactory, LightEditCompatible { override fun getId(): String = ID override fun getDisplayName(): String = GitBundle.message("git.light.status.bar.display.name") override fun isAvailable(project: Project): Boolean = LightEdit.owns(project) override fun createWidget(project: Project): StatusBarWidget { LOG.assertTrue(LightEdit.owns(project)) return LightGitStatusBarWidget(LightGitTracker.getInstance()) } override fun disposeWidget(widget: StatusBarWidget) = Disposer.dispose(widget) override fun canBeEnabledOn(statusBar: StatusBar): Boolean = true }
apache-2.0
ef07893b5806d3b8d89eca67cf8d7003
35.873418
137
0.773352
4.666667
false
false
false
false
SimpleMobileTools/Simple-Music-Player
app/src/main/kotlin/com/simplemobiletools/musicplayer/models/QueueItem.kt
1
434
package com.simplemobiletools.musicplayer.models import androidx.room.ColumnInfo import androidx.room.Entity @Entity(tableName = "queue_items", primaryKeys = ["track_id"]) data class QueueItem( @ColumnInfo(name = "track_id") var trackId: Long, @ColumnInfo(name = "track_order") var trackOrder: Int, @ColumnInfo(name = "is_current") var isCurrent: Boolean, @ColumnInfo(name = "last_position") var lastPosition: Int )
gpl-3.0
783b91202b1e829e58ef71a8d719e068
35.166667
62
0.732719
3.741379
false
false
false
false
mdaniel/intellij-community
platform/build-scripts/groovy/org/jetbrains/intellij/build/impl/WindowsDistributionBuilder.kt
1
18602
// 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.intellij.build.impl import com.intellij.diagnostic.telemetry.createTask import com.intellij.diagnostic.telemetry.useWithScope import com.intellij.openapi.util.JDOMUtil import com.intellij.openapi.util.SystemInfoRt import com.intellij.openapi.util.io.NioFiles import com.intellij.openapi.util.text.StringUtilRt import io.opentelemetry.api.common.AttributeKey import io.opentelemetry.api.trace.Span import org.jdom.Element import org.jetbrains.intellij.build.* import org.jetbrains.intellij.build.TraceManager.spanBuilder import org.jetbrains.intellij.build.impl.productInfo.* import org.jetbrains.intellij.build.impl.support.RepairUtilityBuilder import org.jetbrains.intellij.build.io.copyFileToDir import org.jetbrains.intellij.build.io.runProcess import org.jetbrains.intellij.build.io.substituteTemplatePlaceholders import org.jetbrains.intellij.build.io.transformFile import java.nio.file.Files import java.nio.file.Path import java.nio.file.StandardCopyOption import java.util.concurrent.ForkJoinTask import java.util.function.BiPredicate internal class WindowsDistributionBuilder( override val context: BuildContext, private val customizer: WindowsDistributionCustomizer, private val ideaProperties: Path?, private val patchedApplicationInfo: String, ) : OsSpecificDistributionBuilder { private val icoFile: Path? init { val icoPath = (if (context.applicationInfo.isEAP) customizer.icoPathForEAP else null) ?: customizer.icoPath icoFile = icoPath?.let { Path.of(icoPath) } } override val targetOs: OsFamily get() = OsFamily.WINDOWS override fun copyFilesForOsDistribution(targetPath: Path, arch: JvmArchitecture) { val distBinDir = targetPath.resolve("bin") Files.createDirectories(distBinDir) val binWin = FileSet(context.paths.communityHomeDir.communityRoot.resolve("bin/win")).includeAll() if (!context.includeBreakGenLibraries()) { @Suppress("SpellCheckingInspection") binWin.exclude("breakgen*") } binWin.copyToDir(distBinDir) val pty4jNativeDir = unpackPty4jNative(context, targetPath, "win") generateBuildTxt(context, targetPath) copyDistFiles(context, targetPath) Files.writeString(distBinDir.resolve(ideaProperties!!.fileName), StringUtilRt.convertLineSeparators(Files.readString(ideaProperties), "\r\n")) if (icoFile != null) { Files.copy(icoFile, distBinDir.resolve("${context.productProperties.baseFileName}.ico"), StandardCopyOption.REPLACE_EXISTING) } if (customizer.includeBatchLaunchers) { generateScripts(distBinDir) } generateVMOptions(distBinDir) buildWinLauncher(targetPath) customizer.copyAdditionalFiles(context, targetPath.toString()) context.executeStep(spanBuilder = spanBuilder("sign windows"), stepId = BuildOptions.WIN_SIGN_STEP) { val nativeFiles = ArrayList<Path>() for (nativeRoot in listOf(distBinDir, pty4jNativeDir)) { Files.find(nativeRoot, Integer.MAX_VALUE, BiPredicate { file, attributes -> if (attributes.isRegularFile) { val path = file.toString() path.endsWith(".exe") || path.endsWith(".dll") } else { false } }).use { stream -> stream.forEach(nativeFiles::add) } } Span.current().setAttribute(AttributeKey.stringArrayKey("files"), nativeFiles.map(Path::toString)) customizer.getBinariesToSign(context).mapTo(nativeFiles) { targetPath.resolve(it) } if (nativeFiles.isNotEmpty()) { context.signFiles(nativeFiles, BuildOptions.WIN_SIGN_OPTIONS) } } } override fun buildArtifacts(osAndArchSpecificDistPath: Path, arch: JvmArchitecture) { copyFilesForOsDistribution(osAndArchSpecificDistPath, arch) val jreDir = context.bundledRuntime.extract(BundledRuntimeImpl.getProductPrefix(context), OsFamily.WINDOWS, arch) @Suppress("SpellCheckingInspection") val vcRtDll = jreDir.resolve("jbr/bin/msvcp140.dll") check(Files.exists(vcRtDll)) { "VS C++ Runtime DLL (${vcRtDll.fileName}) not found in ${vcRtDll.parent}.\n" + "If JBR uses a newer version, please correct the path in this code and update Windows Launcher build configuration.\n" + "If DLL was relocated to another place, please correct the path in this code." } copyFileToDir(vcRtDll, osAndArchSpecificDistPath.resolve("bin")) val zipWithJbrPathTask = if (customizer.buildZipArchiveWithBundledJre) { createBuildWinZipTask(listOf(jreDir), customizer.zipArchiveWithBundledJreSuffix, osAndArchSpecificDistPath, customizer, context).fork() } else { null } val zipWithoutJbrPathTask = if (customizer.buildZipArchiveWithoutBundledJre) { createBuildWinZipTask(emptyList(), customizer.zipArchiveWithoutBundledJreSuffix, osAndArchSpecificDistPath, customizer, context).fork() } else { null } var exePath: Path? = null context.executeStep("build Windows Exe Installer", BuildOptions.WINDOWS_EXE_INSTALLER_STEP) { val productJsonDir = context.paths.tempDir.resolve("win.dist.product-info.json.exe") validateProductJson(jsonText = generateProductJson(targetDir = productJsonDir, isJreIncluded = true, context = context), relativePathToProductJson = "", installationDirectories = listOf(context.paths.distAllDir, osAndArchSpecificDistPath, jreDir), installationArchives = emptyList(), context = context) exePath = buildNsisInstaller(winDistPath = osAndArchSpecificDistPath, additionalDirectoryToInclude = productJsonDir, suffix = "", customizer = customizer, jreDir = jreDir, context = context) } val zipWithJbrPath = zipWithJbrPathTask?.join() zipWithoutJbrPathTask?.join() val exePath1 = exePath if (zipWithJbrPath != null && exePath1 != null) { checkThatExeInstallerAndZipWithJbrAreTheSame(zipWithJbrPath, exePath1) return } } private fun checkThatExeInstallerAndZipWithJbrAreTheSame(zipPath: Path, exePath: Path) { if (context.options.isInDevelopmentMode) { Span.current().addEvent("comparing .zip and .exe skipped in development mode") return } if (!SystemInfoRt.isLinux) { Span.current().addEvent("comparing .zip and .exe is not supported on ${SystemInfoRt.OS_NAME}") return } Span.current().addEvent("compare ${zipPath.fileName} vs. ${exePath.fileName}") val tempZip = Files.createTempDirectory(context.paths.tempDir, "zip-") val tempExe = Files.createTempDirectory(context.paths.tempDir, "exe-") try { runProcess(args = listOf("7z", "x", "-bd", exePath.toString()), workingDir = tempExe, logger = context.messages) runProcess(args = listOf("unzip", "-q", zipPath.toString()), workingDir = tempZip, logger = context.messages) @Suppress("SpellCheckingInspection") NioFiles.deleteRecursively(tempExe.resolve("\$PLUGINSDIR")) runProcess(listOf("diff", "-q", "-r", tempZip.toString(), tempExe.toString()), null, context.messages) RepairUtilityBuilder.generateManifest(context, tempExe, exePath.fileName.toString()) } finally { NioFiles.deleteRecursively(tempZip) NioFiles.deleteRecursively(tempExe) } } private fun generateScripts(distBinDir: Path) { val fullName = context.applicationInfo.productName val baseName = context.productProperties.baseFileName val scriptName = "${baseName}.bat" val vmOptionsFileName = "${baseName}64.exe" val classPathJars = context.bootClassPathJarNames var classPath = "SET \"CLASS_PATH=%IDE_HOME%\\lib\\${classPathJars[0]}\"" for (i in 1 until classPathJars.size) { classPath += "\nSET \"CLASS_PATH=%CLASS_PATH%;%IDE_HOME%\\lib\\${classPathJars[i]}\"" } var additionalJvmArguments = context.getAdditionalJvmArguments(OsFamily.WINDOWS) if (!context.xBootClassPathJarNames.isEmpty()) { additionalJvmArguments = additionalJvmArguments.toMutableList() val bootCp = context.xBootClassPathJarNames.joinToString(separator = ";") { "%IDE_HOME%\\lib\\${it}" } additionalJvmArguments.add("\"-Xbootclasspath/a:$bootCp\"") } val winScripts = context.paths.communityHomeDir.communityRoot.resolve("platform/build-scripts/resources/win/scripts") val actualScriptNames = Files.newDirectoryStream(winScripts).use { dirStream -> dirStream.map { it.fileName.toString() }.sorted() } @Suppress("SpellCheckingInspection") val expectedScriptNames = listOf("executable-template.bat", "format.bat", "inspect.bat", "ltedit.bat") check(actualScriptNames == expectedScriptNames) { "Expected script names '${expectedScriptNames.joinToString(separator = " ")}', " + "but got '${actualScriptNames.joinToString(separator = " ")}' " + "in $winScripts. Please review ${WindowsDistributionBuilder::class.java.name} and update accordingly" } substituteTemplatePlaceholders( inputFile = winScripts.resolve("executable-template.bat"), outputFile = distBinDir.resolve(scriptName), placeholder = "@@", values = listOf( Pair("product_full", fullName), Pair("product_uc", context.productProperties.getEnvironmentVariableBaseName(context.applicationInfo)), Pair("product_vendor", context.applicationInfo.shortCompanyName), Pair("vm_options", vmOptionsFileName), Pair("system_selector", context.systemSelector), Pair("ide_jvm_args", additionalJvmArguments.joinToString(separator = " ")), Pair("class_path", classPath), Pair("base_name", baseName), Pair("main_class_name", context.productProperties.mainClassName), ) ) val inspectScript = context.productProperties.inspectCommandName @Suppress("SpellCheckingInspection") for (fileName in listOf("format.bat", "inspect.bat", "ltedit.bat")) { val sourceFile = winScripts.resolve(fileName) val targetFile = distBinDir.resolve(fileName) substituteTemplatePlaceholders( inputFile = sourceFile, outputFile = targetFile, placeholder = "@@", values = listOf( Pair("product_full", fullName), Pair("script_name", scriptName), ) ) } if (inspectScript != "inspect") { val targetPath = distBinDir.resolve("${inspectScript}.bat") Files.move(distBinDir.resolve("inspect.bat"), targetPath) context.patchInspectScript(targetPath) } FileSet(distBinDir) .include("*.bat") .enumerate() .forEach { file -> transformFile(file) { target -> @Suppress("BlockingMethodInNonBlockingContext") Files.writeString(target, toDosLineEndings(Files.readString(file))) } } } private fun generateVMOptions(distBinDir: Path) { val productProperties = context.productProperties val fileName = "${productProperties.baseFileName}64.exe.vmoptions" val vmOptions = VmOptionsGenerator.computeVmOptions(context.applicationInfo.isEAP, productProperties) VmOptionsGenerator.writeVmOptions(distBinDir.resolve(fileName), vmOptions, "\r\n") } private fun buildWinLauncher(winDistPath: Path) { spanBuilder("build Windows executable").useWithScope { val executableBaseName = "${context.productProperties.baseFileName}64" val launcherPropertiesPath = context.paths.tempDir.resolve("launcher.properties") val upperCaseProductName = context.applicationInfo.upperCaseProductName @Suppress("SpellCheckingInspection") val vmOptions = context.getAdditionalJvmArguments(OsFamily.WINDOWS) + listOf("-Dide.native.launcher=true") val productName = context.applicationInfo.shortProductName val classPath = context.bootClassPathJarNames.joinToString(separator = ";") val bootClassPath = context.xBootClassPathJarNames.joinToString(separator = ";") val envVarBaseName = context.productProperties.getEnvironmentVariableBaseName(context.applicationInfo) val icoFilesDirectory = context.paths.tempDir.resolve("win-launcher-ico") val appInfoForLauncher = generateApplicationInfoForLauncher(patchedApplicationInfo, icoFilesDirectory) @Suppress("SpellCheckingInspection") Files.writeString(launcherPropertiesPath, """ IDS_JDK_ONLY=${context.productProperties.toolsJarRequired} IDS_JDK_ENV_VAR=${envVarBaseName}_JDK IDS_APP_TITLE=${productName} Launcher IDS_VM_OPTIONS_PATH=%APPDATA%\\\\${context.applicationInfo.shortCompanyName}\\\\${context.systemSelector} IDS_VM_OPTION_ERRORFILE=-XX:ErrorFile=%USERPROFILE%\\\\java_error_in_${executableBaseName}_%p.log IDS_VM_OPTION_HEAPDUMPPATH=-XX:HeapDumpPath=%USERPROFILE%\\\\java_error_in_${executableBaseName}.hprof IDC_WINLAUNCHER=${upperCaseProductName}_LAUNCHER IDS_PROPS_ENV_VAR=${envVarBaseName}_PROPERTIES IDS_VM_OPTIONS_ENV_VAR=${envVarBaseName}_VM_OPTIONS IDS_ERROR_LAUNCHING_APP=Error launching $productName IDS_VM_OPTIONS=${vmOptions.joinToString(separator = " ")} IDS_CLASSPATH_LIBS=${classPath} IDS_BOOTCLASSPATH_LIBS=${bootClassPath} IDS_INSTANCE_ACTIVATION=${context.productProperties.fastInstanceActivation} IDS_MAIN_CLASS=${context.productProperties.mainClassName.replace('.', '/')} """.trimIndent().trim()) val communityHome = context.paths.communityHome val inputPath = "${communityHome}/platform/build-scripts/resources/win/launcher/WinLauncher.exe" val outputPath = winDistPath.resolve("bin/${executableBaseName}.exe") val classpath = ArrayList<String>() val generatorClasspath = context.getModuleRuntimeClasspath(module = context.findRequiredModule("intellij.tools.launcherGenerator"), forTests = false) classpath.addAll(generatorClasspath) sequenceOf(context.findApplicationInfoModule(), context.findRequiredModule("intellij.platform.icons")) .flatMap { it.sourceRoots } .forEach { root -> classpath.add(root.file.absolutePath) } for (p in context.productProperties.brandingResourcePaths) { classpath.add(p.toString()) } classpath.add(icoFilesDirectory.toString()) runJava( context = context, mainClass = "com.pme.launcher.LauncherGeneratorMain", args = listOf( inputPath, appInfoForLauncher.toString(), "$communityHome/native/WinLauncher/resource.h", launcherPropertiesPath.toString(), outputPath.toString(), ), jvmArgs = listOf("-Djava.awt.headless=true"), classPath = classpath ) } } /** * Generates ApplicationInfo.xml file for launcher generator which contains link to proper *.ico file. * todo pass path to ico file to LauncherGeneratorMain directly (probably after IDEA-196705 is fixed). */ private fun generateApplicationInfoForLauncher(appInfo: String, icoFilesDirectory: Path): Path { val patchedFile = context.paths.tempDir.resolve("win-launcher-application-info.xml") if (icoFile == null) { Files.writeString(patchedFile, appInfo) return patchedFile } Files.createDirectories(icoFilesDirectory) Files.copy(icoFile, icoFilesDirectory.resolve(icoFile.fileName), StandardCopyOption.REPLACE_EXISTING) val root = JDOMUtil.load(appInfo) // do not use getChild - maybe null due to namespace val iconElement = root.content.firstOrNull { it is Element && it.name == "icon" } ?: throw RuntimeException("`icon` element not found in $appInfo:\n${appInfo}") (iconElement as Element).setAttribute("ico", icoFile.fileName.toString()) JDOMUtil.write(root, patchedFile) return patchedFile } } private fun createBuildWinZipTask(jreDirectoryPaths: List<Path>, @Suppress("SameParameterValue") zipNameSuffix: String, winDistPath: Path, customizer: WindowsDistributionCustomizer, context: BuildContext): ForkJoinTask<Path> { val baseName = context.productProperties.getBaseArtifactName(context.applicationInfo, context.buildNumber) val targetFile = context.paths.artifactDir.resolve("${baseName}${zipNameSuffix}.zip") return createTask(spanBuilder("build Windows ${zipNameSuffix}.zip distribution") .setAttribute("targetFile", targetFile.toString())) { val productJsonDir = context.paths.tempDir.resolve("win.dist.product-info.json.zip$zipNameSuffix") generateProductJson(productJsonDir, !jreDirectoryPaths.isEmpty(), context) val zipPrefix = customizer.getRootDirectoryName(context.applicationInfo, context.buildNumber) val dirs = listOf(context.paths.distAllDir, winDistPath, productJsonDir) + jreDirectoryPaths zipWithPrefixes(context = context, targetFile = targetFile, map = dirs.associateWithTo(LinkedHashMap(dirs.size)) { zipPrefix }, compress = true) checkInArchive(archiveFile = targetFile, pathInArchive = zipPrefix, context = context) context.notifyArtifactWasBuilt(targetFile) targetFile } } private fun generateProductJson(targetDir: Path, isJreIncluded: Boolean, context: BuildContext): String { val launcherPath = "bin/${context.productProperties.baseFileName}64.exe" val vmOptionsPath = "bin/${context.productProperties.baseFileName}64.exe.vmoptions" val javaExecutablePath = if (isJreIncluded) "jbr/bin/java.exe" else null val file = targetDir.resolve(PRODUCT_INFO_FILE_NAME) Files.createDirectories(targetDir) val json = generateMultiPlatformProductJson( "bin", context.builtinModule, listOf( ProductInfoLaunchData( os = OsFamily.WINDOWS.osName, launcherPath = launcherPath, javaExecutablePath = javaExecutablePath, vmOptionsFilePath = vmOptionsPath, startupWmClass = null, ) ), context) Files.writeString(file, json) return json } private fun toDosLineEndings(x: String): String { return x.replace("\r", "").replace("\n", "\r\n") }
apache-2.0
0c8c3efa2d29c608a0f2c530b4ad2767
44.150485
141
0.702935
4.960533
false
false
false
false
DanielGrech/anko
dsl/src/org/jetbrains/android/anko/Main.kt
3
3120
/* * Copyright 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.android.anko import org.jetbrains.android.anko.config.DefaultAnkoConfiguration import org.jetbrains.android.anko.utils.AndroidVersionDirectoryFilter import org.jetbrains.android.anko.utils.JarFileFilter import java.io.File fun main(args: Array<String>) { if (args.isNotEmpty()) { args.forEach { taskName -> println(":: $taskName") when (taskName) { "gen", "generate" -> gen() "clean" -> clean() "versions" -> versions() else -> { println("Invalid task $taskName") return } } } println("Done.") } else gen() } private fun clean() { deleteDirectory(File("workdir/gen/")) } private fun versions() { for (version in getVersions()) { val jars = getJars(version) println("${version.getName()}") jars?.forEach { println(" ${it.name}") } } } private fun deleteDirectory(f: File) { if (!f.exists()) return if (f.isDirectory()) { f.listFiles()?.forEach { deleteDirectory(it) } } if (!f.delete()) { throw RuntimeException("Failed to delete ${f.getAbsolutePath()}") } } private fun getVersions(): Array<File> { val original = File("workdir/original/") if (!original.exists() || !original.isDirectory()) { throw RuntimeException("\"workdir/original\" directory does not exist.") } return original.listFiles(AndroidVersionDirectoryFilter()) ?: arrayOf<File>() } private fun getJars(version: File) = version.listFiles(JarFileFilter()) private fun gen() { for (version in getVersions()) { val jars = getJars(version)?.map { it.getAbsolutePath() } ?: listOf<String>() val intVersion = parseVersion(version.getName()) if (intVersion != null && jars.isNotEmpty()) { println("Processing version ${version.getName()}, jars: ${jars.joinToString()}") val outputDirectory = "workdir/gen/${version.getName()}/" val fileOutputDirectory = File("$outputDirectory/src/main/kotlin/") if (!fileOutputDirectory.exists()) { fileOutputDirectory.mkdirs() } DSLGenerator(intVersion, version.getName(), jars, DefaultAnkoConfiguration(outputDirectory)).run() } } } private fun parseVersion(name: String): Int? { val prob = name.filter { it.isDigit() } return if (prob.isNotEmpty()) prob.toInt() else null }
apache-2.0
24e14216cb764902573640db140131f7
31.510417
110
0.626923
4.425532
false
false
false
false
mdaniel/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/TrailingCommaInspection.kt
1
11560
// 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.inspections import com.intellij.application.options.CodeStyle import com.intellij.codeInsight.intention.FileModifier import com.intellij.codeInspection.* import com.intellij.codeInspection.ui.SingleCheckboxOptionsPanel import com.intellij.codeInspection.util.InspectionMessage import com.intellij.codeInspection.util.IntentionFamilyName import com.intellij.openapi.project.Project import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiElement import com.intellij.psi.PsiElementVisitor import com.intellij.psi.PsiFile import com.intellij.psi.codeStyle.CodeStyleManager import com.intellij.psi.codeStyle.CodeStyleSettingsManager import com.intellij.psi.util.PsiTreeUtil import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.codeinsight.api.classic.inspections.AbstractKotlinInspection import org.jetbrains.kotlin.idea.formatter.TrailingCommaVisitor import org.jetbrains.kotlin.idea.formatter.kotlinCustomSettings import org.jetbrains.kotlin.idea.formatter.trailingComma.TrailingCommaContext import org.jetbrains.kotlin.idea.formatter.trailingComma.TrailingCommaHelper import org.jetbrains.kotlin.idea.formatter.trailingComma.TrailingCommaState import org.jetbrains.kotlin.idea.formatter.trailingComma.addTrailingCommaIsAllowedFor import org.jetbrains.kotlin.idea.formatter.trailingCommaAllowedInModule import org.jetbrains.kotlin.idea.util.application.isUnitTestMode import org.jetbrains.kotlin.idea.util.application.withPsiAttachment import org.jetbrains.kotlin.idea.util.isComma import org.jetbrains.kotlin.idea.util.isLineBreak import org.jetbrains.kotlin.idea.util.leafIgnoringWhitespaceAndComments import org.jetbrains.kotlin.psi.KtElement import org.jetbrains.kotlin.psi.psiUtil.* import org.jetbrains.kotlin.utils.KotlinExceptionWithAttachments import javax.swing.JComponent import kotlin.properties.Delegates class TrailingCommaInspection( @JvmField var addCommaWarning: Boolean = false ) : AbstractKotlinInspection() { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor = object : TrailingCommaVisitor() { override val recursively: Boolean = false private var useTrailingComma by Delegates.notNull<Boolean>() override fun process(trailingCommaContext: TrailingCommaContext) { val element = trailingCommaContext.ktElement val kotlinCustomSettings = element.containingKtFile.kotlinCustomSettings useTrailingComma = kotlinCustomSettings.addTrailingCommaIsAllowedFor(element) when (trailingCommaContext.state) { TrailingCommaState.MISSING, TrailingCommaState.EXISTS -> { checkCommaPosition(element) checkLineBreaks(element) } else -> Unit } checkTrailingComma(trailingCommaContext) } private fun checkLineBreaks(commaOwner: KtElement) { val first = TrailingCommaHelper.elementBeforeFirstElement(commaOwner) if (first?.nextLeaf(true)?.isLineBreak() == false) { first.nextSibling?.let { registerProblemForLineBreak(commaOwner, it, ProblemHighlightType.INFORMATION) } } val last = TrailingCommaHelper.elementAfterLastElement(commaOwner) if (last?.prevLeaf(true)?.isLineBreak() == false) { registerProblemForLineBreak( commaOwner, last, if (addCommaWarning) ProblemHighlightType.GENERIC_ERROR_OR_WARNING else ProblemHighlightType.INFORMATION, ) } } private fun checkCommaPosition(commaOwner: KtElement) { for (invalidComma in TrailingCommaHelper.findInvalidCommas(commaOwner)) { reportProblem( invalidComma, KotlinBundle.message("inspection.trailing.comma.comma.loses.the.advantages.in.this.position"), KotlinBundle.message("inspection.trailing.comma.fix.comma.position") ) } } private fun checkTrailingComma(trailingCommaContext: TrailingCommaContext) { val commaOwner = trailingCommaContext.ktElement val trailingCommaOrLastElement = TrailingCommaHelper.trailingCommaOrLastElement(commaOwner) ?: return when (trailingCommaContext.state) { TrailingCommaState.MISSING -> { if (!trailingCommaAllowedInModule(commaOwner)) return reportProblem( trailingCommaOrLastElement, KotlinBundle.message("inspection.trailing.comma.missing.trailing.comma"), KotlinBundle.message("inspection.trailing.comma.add.trailing.comma"), if (addCommaWarning) ProblemHighlightType.GENERIC_ERROR_OR_WARNING else ProblemHighlightType.INFORMATION, ) } TrailingCommaState.REDUNDANT -> { reportProblem( trailingCommaOrLastElement, KotlinBundle.message("inspection.trailing.comma.useless.trailing.comma"), KotlinBundle.message("inspection.trailing.comma.remove.trailing.comma"), ProblemHighlightType.LIKE_UNUSED_SYMBOL, checkTrailingCommaSettings = false, ) } else -> Unit } } private fun reportProblem( commaOrElement: PsiElement, @InspectionMessage message: String, @IntentionFamilyName fixMessage: String, highlightType: ProblemHighlightType = ProblemHighlightType.GENERIC_ERROR_OR_WARNING, checkTrailingCommaSettings: Boolean = true, ) { val commaOwner = commaOrElement.parent as KtElement // case for KtFunctionLiteral, where PsiWhiteSpace after KtTypeParameterList isn't included in this list val problemOwner = commonParent(commaOwner, commaOrElement) val highlightTypeWithAppliedCondition = highlightType.applyCondition(!checkTrailingCommaSettings || useTrailingComma) // INFORMATION shouldn't be reported in batch mode if (isOnTheFly || highlightTypeWithAppliedCondition != ProblemHighlightType.INFORMATION) { holder.registerProblem( problemOwner, message, highlightTypeWithAppliedCondition, commaOrElement.textRangeOfCommaOrSymbolAfter.shiftLeft(problemOwner.startOffset), createQuickFix(fixMessage, commaOwner), ) } } private fun registerProblemForLineBreak( commaOwner: KtElement, elementForTextRange: PsiElement, highlightType: ProblemHighlightType, ) { val problemElement = commonParent(commaOwner, elementForTextRange) val highlightTypeWithAppliedCondition = highlightType.applyCondition(useTrailingComma) // INFORMATION shouldn't be reported in batch mode if (isOnTheFly || highlightTypeWithAppliedCondition != ProblemHighlightType.INFORMATION) { holder.registerProblem( problemElement, KotlinBundle.message("inspection.trailing.comma.missing.line.break"), highlightTypeWithAppliedCondition, TextRange.from(elementForTextRange.startOffset, 1).shiftLeft(problemElement.startOffset), createQuickFix(KotlinBundle.message("inspection.trailing.comma.add.line.break"), commaOwner), ) } } private fun commonParent(commaOwner: PsiElement, elementForTextRange: PsiElement): PsiElement = PsiTreeUtil.findCommonParent(commaOwner, elementForTextRange) ?: throw KotlinExceptionWithAttachments("Common parent not found") .withPsiAttachment("commaOwner", commaOwner) .withAttachment("commaOwnerRange", commaOwner.textRange) .withPsiAttachment("elementForTextRange", elementForTextRange) .withAttachment("elementForTextRangeRange", elementForTextRange.textRange) .withPsiAttachment("parent", commaOwner.parent) .withAttachment("parentRange", commaOwner.parent.textRange) private fun ProblemHighlightType.applyCondition(condition: Boolean): ProblemHighlightType = when { isUnitTestMode() -> ProblemHighlightType.GENERIC_ERROR_OR_WARNING condition -> this else -> ProblemHighlightType.INFORMATION } private fun createQuickFix( @IntentionFamilyName fixMessage: String, commaOwner: KtElement, ): LocalQuickFix = ReformatTrailingCommaFix(commaOwner, fixMessage) private val PsiElement.textRangeOfCommaOrSymbolAfter: TextRange get() { val textRange = textRange if (isComma) return textRange return nextLeaf()?.leafIgnoringWhitespaceAndComments(false)?.endOffset?.takeIf { it > 0 }?.let { TextRange.create(it - 1, it).intersection(textRange) } ?: TextRange.create(textRange.endOffset - 1, textRange.endOffset) } } override fun createOptionsPanel(): JComponent = SingleCheckboxOptionsPanel( KotlinBundle.message("inspection.trailing.comma.report.also.a.missing.comma"), this, "addCommaWarning", ) class ReformatTrailingCommaFix(commaOwner: KtElement, @IntentionFamilyName private val fixMessage: String) : LocalQuickFix { val commaOwnerPointer = commaOwner.createSmartPointer() override fun getFamilyName(): String = fixMessage override fun applyFix(project: Project, problemDescriptor: ProblemDescriptor) { val element = commaOwnerPointer.element ?: return val range = createFormatterTextRange(element) val settings = CodeStyleSettingsManager.getInstance(project).cloneSettings(CodeStyle.getSettings(element.containingKtFile)) settings.kotlinCustomSettings.ALLOW_TRAILING_COMMA = true settings.kotlinCustomSettings.ALLOW_TRAILING_COMMA_ON_CALL_SITE = true CodeStyle.doWithTemporarySettings(project, settings, Runnable { CodeStyleManager.getInstance(project).reformatRange(element, range.startOffset, range.endOffset) }) } private fun createFormatterTextRange(commaOwner: KtElement): TextRange { val startElement = TrailingCommaHelper.elementBeforeFirstElement(commaOwner) ?: commaOwner val endElement = TrailingCommaHelper.elementAfterLastElement(commaOwner) ?: commaOwner return TextRange.create(startElement.startOffset, endElement.endOffset) } override fun getFileModifierForPreview(target: PsiFile): FileModifier? { val element = commaOwnerPointer.element ?: return null return ReformatTrailingCommaFix(PsiTreeUtil.findSameElementInCopy(element, target), fixMessage) } } }
apache-2.0
7b22f6600a560cc8e966cc86ae4e91f2
50.838565
158
0.682699
6.262189
false
false
false
false
hermantai/samples
android/jetpack/PlayDataBinding/app/src/main/java/com/gmail/htaihm/playdatabinding/HeroActivity.kt
1
1629
package com.gmail.htaihm.playdatabinding import android.content.Context import android.content.Intent import android.databinding.DataBindingUtil import android.databinding.ObservableInt import android.support.v7.app.AppCompatActivity import android.os.Bundle import com.gmail.htaihm.playdatabinding.databinding.ActivityHeroBinding class HeroActivity : AppCompatActivity() { companion object { const val ARG_HERO_ID = "hero_id" fun createIntent(context: Context, heroId: String) : Intent { // HeroActivity.javaClass is actually a static method, which gets the class of "this" object, which is // HeroActivity.companion in this class, which is wrong. val intent = Intent(context, HeroActivity::class.java) intent.putExtra(ARG_HERO_ID, heroId) return intent } } private lateinit var heroVO: HeroVO override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val binding: ActivityHeroBinding = DataBindingUtil.setContentView(this, R.layout.activity_hero) val bundle = requireNotNull(intent.extras) val heroId = bundle.getString(ARG_HERO_ID, "") val repository = HeroesRepository.getInstance(applicationContext) repository.getHero(heroId)?.let { hero -> heroVO = HeroVO(hero.id, hero.name, ObservableInt(hero.matches), hero.abilities) binding.heroVO = heroVO binding.increaseMatches.setOnClickListener { heroVO.matches.set(heroVO.matches.get() + 1) } } } }
apache-2.0
862be5d6b4218e76f3ff21d841754358
35.2
114
0.685083
4.537604
false
false
false
false
hermantai/samples
kotlin/Mastering-Kotlin-master/Chapter04/src/Object.kt
1
680
object SimpleSingleton interface SomeInterface { fun doSomething(foo: String) {} } val someInterface = object : SomeInterface { override fun doSomething(foo: String) { super.doSomething(foo) } } class SomeClass private constructor() { private val id = "id" companion object Factory : SomeInterface { const val someVal = "val" fun foo() {} fun createSomeClass() = SomeClass() override fun doSomething(foo: String) { super.doSomething(foo) } } } fun main(args: Array<String>) { SomeClass.foo() val transient = object { val prop = "foo" } println(transient.prop) }
apache-2.0
a8888525c31ea8fde9ab170ef2467be3
16.921053
47
0.610294
4.25
false
false
false
false
android/play-billing-samples
ClassyTaxiAppKotlin/app/src/main/java/com/example/subscriptions/ui/TvMainFragment.kt
1
19357
/* * Copyright 2019 Google LLC. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.subscriptions.ui import android.content.Intent import android.graphics.Bitmap import android.os.Bundle import android.util.DisplayMetrics import android.util.Log import android.view.Gravity import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.FrameLayout import android.widget.ProgressBar import androidx.core.content.ContextCompat import androidx.fragment.app.Fragment import androidx.leanback.app.BackgroundManager import androidx.leanback.app.DetailsSupportFragment import androidx.leanback.widget.Action import androidx.leanback.widget.ArrayObjectAdapter import androidx.leanback.widget.ClassPresenterSelector import androidx.leanback.widget.DetailsOverviewRow import androidx.leanback.widget.FullWidthDetailsOverviewRowPresenter import androidx.leanback.widget.SparseArrayObjectAdapter import androidx.lifecycle.Lifecycle import androidx.lifecycle.ViewModelProviders import androidx.lifecycle.lifecycleScope import androidx.lifecycle.repeatOnLifecycle import com.bumptech.glide.Glide import com.bumptech.glide.request.RequestOptions import com.bumptech.glide.request.target.SimpleTarget import com.bumptech.glide.request.transition.Transition import com.example.subscriptions.R import com.example.subscriptions.billing.isAccountHold import com.example.subscriptions.billing.isBasicContent import com.example.subscriptions.billing.isGracePeriod import com.example.subscriptions.billing.isPremiumContent import com.example.subscriptions.billing.isSubscriptionRestore import com.example.subscriptions.billing.isTransferRequired import com.example.subscriptions.data.SubscriptionContent import com.example.subscriptions.data.SubscriptionStatus import com.example.subscriptions.presenter.SubscriptionDetailsPresenter import com.example.subscriptions.utils.basicTextForSubscription import com.example.subscriptions.utils.premiumTextForSubscription import kotlinx.coroutines.flow.collect import kotlinx.coroutines.launch /** * TvMainFragment implements DetailsSupportFragment to provide an Android TV optimized experience to the user. * The class creates a Presenter and adds a DetailsOverviewRow Leanback widget used to display metadata from * a SubscriptionContent object. * * * This Activity subscribes to StateFlow updates observed by its parent Activity in order to update the content * available. */ class TvMainFragment : DetailsSupportFragment() { companion object { private const val ACTION_SUBSCRIBE_BASIC = 1 private const val ACTION_SUBSCRIBE_PREMIUM = 2 private const val ACTION_MANAGE_SUBSCRIPTIONS = 3 private const val ACTION_SIGN_IN_OUT = 4 private const val TAG = "TvMainFragment" } private lateinit var metrics: DisplayMetrics private lateinit var presenterSelector: ClassPresenterSelector private lateinit var objectAdapter: ArrayObjectAdapter private lateinit var subscriptionContent: SubscriptionContent private lateinit var backgroundManager: BackgroundManager private lateinit var detailsOverviewRow: DetailsOverviewRow private lateinit var authenticationViewModel: FirebaseUserViewModel private lateinit var subscriptionsStatusViewModel: SubscriptionStatusViewModel private lateinit var billingViewModel: BillingViewModel private var basicSubscription: SubscriptionStatus? = null private var premiumSubscription: SubscriptionStatus? = null private lateinit var spinnerFragment: SpinnerFragment /** * Lifecycle call onCreate() */ override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) prepareBackgroundManager() } /** * Lifecycle call onActivityCreated() */ override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) // Creates default SubscriptionContent object createSubscriptionContent() authenticationViewModel = ViewModelProviders.of(requireActivity()).get(FirebaseUserViewModel::class.java) subscriptionsStatusViewModel = ViewModelProviders.of(requireActivity()).get(SubscriptionStatusViewModel::class.java) billingViewModel = ViewModelProviders.of(requireActivity()).get(BillingViewModel::class.java) spinnerFragment = SpinnerFragment() // Update the UI whenever a user signs in / out authenticationViewModel.firebaseUser.observe(requireActivity(), { Log.d(TAG, "firebaseUser onChange()") refreshUI() }) // Show or hide a Spinner based on loading state lifecycleScope.launch { viewLifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED) { subscriptionsStatusViewModel.loading.collect { isLoading -> if (isLoading) { parentFragmentManager.beginTransaction() .replace(R.id.main_frame, spinnerFragment) .commit() Log.i(TAG, "loading spinner shown") } else { parentFragmentManager.beginTransaction() .remove(spinnerFragment) .commit() Log.i(TAG, "loading spinner hidden") } } } } // Updates subscription image for Basic plan lifecycleScope.launch { viewLifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED) { subscriptionsStatusViewModel.basicContent.collect { content -> Log.d(TAG, "basicContent onChange()") content?.url?.let { // If a premium subscription exists, don't update image with basic plan if (premiumSubscription == null) { updateSubscriptionImage(it) } } } } } // Updates subscription image for Premium plan lifecycleScope.launch { viewLifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED) { subscriptionsStatusViewModel.premiumContent.collect { content -> content?.url?.let { updateSubscriptionImage(it) } } } } // Updates subscription details based on list of available subscriptions lifecycleScope.launch { viewLifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED) { subscriptionsStatusViewModel.subscriptions.collect { Log.d(TAG, "subscriptions onChange()") updateSubscriptionDetails(it) } } } } /** * Lifecycle call onResume() */ override fun onResume() { super.onResume() updateBackground() } /** * Lifecycle call onPause() */ override fun onPause() { backgroundManager.release() super.onPause() } /** * Creates a SubscriptionContent object used for populating information about a Subscription. */ private fun createSubscriptionContent() { subscriptionContent = SubscriptionContent.Builder() .title(getString(R.string.app_name)) .subtitle(getString(R.string.paywall_message)) .build() } /** * Prepares BackgroundManager class used for updating the backdrop image. */ private fun prepareBackgroundManager() { backgroundManager = BackgroundManager.getInstance(requireActivity()) backgroundManager.attach(requireActivity().window) metrics = DisplayMetrics() requireActivity().windowManager.defaultDisplay.getMetrics(metrics) } /** * Updates the background image used as backdrop. */ private fun updateBackground() { val options = RequestOptions() .fitCenter() .dontAnimate() Glide.with(this) .asBitmap() .load(R.drawable.tv_background_img) .apply(options) .into(object : SimpleTarget<Bitmap>(metrics.widthPixels, metrics.heightPixels) { /** * The method that will be called when the resource load has finished. * * @param resource the loaded resource. */ override fun onResourceReady(resource: Bitmap, transition: Transition<in Bitmap>?) { backgroundManager.setBitmap(resource) } }) } /** * Updates Subscription details based on the provided list of subscriptions retrieved from the server */ private fun updateSubscriptionDetails(subscriptionStatuses: List<SubscriptionStatus>?) { // Clear out any previously cached subscriptions basicSubscription = null premiumSubscription = null // Create new SubscriptionContent builder and populate with metadata from SubscriptionStatus list val subscriptionContentBuilder = SubscriptionContent.Builder() subscriptionContentBuilder.title(getString(R.string.app_name)) if (subscriptionStatuses != null && subscriptionStatuses.isNotEmpty()) { Log.d(TAG, "We have subscriptions!") // Iterate through the list of subscriptions to build our SubscriptionContent object for (subscription in subscriptionStatuses) { // Basic Plan if (subscription.isBasicContent) { Log.d(TAG, "basic subscription found") // Update our builder object subscriptionContentBuilder.subtitle(getString(R.string.basic_auto_message)) subscriptionContentBuilder.description(getString(R.string.basic_content_text)) // Cache the subscription in a global member variable basicSubscription = subscription } // Premium Plan if (isPremiumContent(subscription)) { Log.d(TAG, "premium subscription found") // Update our builder object subscriptionContentBuilder.subtitle(getString(R.string.premium_auto_message)) subscriptionContentBuilder.description(getString(R.string.premium_content_text)) // Cache the subscription in a global member variable premiumSubscription = subscription } // Subscription restore if (isSubscriptionRestore(subscription)) { Log.d(TAG, "subscription restore") val expiryDate = getHumanReadableDate(subscription.activeUntilMillisec) val subtitleText = getString(R.string.restore_message_with_date, expiryDate) subscriptionContentBuilder.subtitle(subtitleText) subscriptionContentBuilder.description(null) } // Account in grace period if (isGracePeriod(subscription)) { Log.d(TAG, "account in grace period") subscriptionContentBuilder.subtitle(getString(R.string.grace_period_message)) subscriptionContentBuilder.description(null) } // Account transfer if (isTransferRequired(subscription)) { Log.d(TAG, "account transfer required") subscriptionContentBuilder.subtitle(getString(R.string.transfer_message)) subscriptionContentBuilder.description(null) } // Account on hold if (isAccountHold(subscription)) { Log.d(TAG, "account on hold") subscriptionContentBuilder.subtitle(getString(R.string.account_hold_message)) subscriptionContentBuilder.description(null) } } } else { // Default message to display when there are no subscriptions available subscriptionContentBuilder.subtitle(getString(R.string.paywall_message)) } // Refresh the UI refreshUI() detailsOverviewRow.item = subscriptionContentBuilder.build() } /** * Updates DetailOverviewRow's image using the provided URL. */ private fun updateSubscriptionImage(url: String) { val options = RequestOptions() .fitCenter() .dontAnimate() Glide.with(requireActivity()) .asBitmap() .load(url) .apply(options) .into(object : SimpleTarget<Bitmap>() { /** * The method that will be called when the resource load has finished. * * @param resource the loaded resource. */ override fun onResourceReady(resource: Bitmap, transition: Transition<in Bitmap>?) { detailsOverviewRow.setImageBitmap(requireActivity(), resource) } }) } /** * Creates a ClassPresenterSelector, adds a styled FullWidthDetailsOverviewRowPresenter with * an OnActionClickedListener to handle click events for the available Actions. */ private fun setupAdapter() { // Set detail background and style. val detailsPresenter = FullWidthDetailsOverviewRowPresenter(SubscriptionDetailsPresenter()) detailsPresenter.backgroundColor = ContextCompat.getColor(requireActivity(), R.color.primaryColor) detailsPresenter.initialState = FullWidthDetailsOverviewRowPresenter.STATE_SMALL detailsPresenter.alignmentMode = FullWidthDetailsOverviewRowPresenter.ALIGN_MODE_MIDDLE // Set OnActionClickListener to handle Action click events detailsPresenter.setOnActionClickedListener { action -> if (action.id == ACTION_SUBSCRIBE_BASIC.toLong()) { // TODO(232165789): update with new method calls // Subscribe to basic plan // billingViewModel.buyBasic() } else if (action.id == ACTION_SUBSCRIBE_PREMIUM.toLong()) { // If a basic subscription exists, handle as an upgrade to premium // else, handle as a new subscription to premium // if (basicSubscription != null) { // billingViewModel.buyUpgrade() // } else { // billingViewModel.buyPremium() // } } else if (action.id == ACTION_MANAGE_SUBSCRIPTIONS.toLong()) { // Launch Activity to manage subscriptions startActivity(Intent(requireActivity(), TvManageSubscriptionsActivity::class.java)) } else if (action.id == ACTION_SIGN_IN_OUT.toLong()) { // Handle sign-in / sign-out event based on current state if (authenticationViewModel.isSignedIn()) { (requireActivity() as TvMainActivity).triggerSignOut() } else { (requireActivity() as TvMainActivity).triggerSignIn() } } } // Create ClassPresenter, add the DetailsPresenter and bind to its adapter presenterSelector = ClassPresenterSelector() presenterSelector.addClassPresenter(DetailsOverviewRow::class.java, detailsPresenter) objectAdapter = ArrayObjectAdapter(presenterSelector) adapter = objectAdapter } /** * Creates a DetailsOverviewRow and adds Action buttons to the layout */ private fun setupDetailsOverviewRow() { // Create DetailsOverviewRow widget detailsOverviewRow = DetailsOverviewRow(subscriptionContent) // Create Action Adapter val actionAdapter = SparseArrayObjectAdapter() // Add Basic Plan Action button actionAdapter.set( ACTION_SUBSCRIBE_BASIC, Action( ACTION_SUBSCRIBE_BASIC.toLong(), if (basicSubscription != null) basicTextForSubscription(resources, basicSubscription!!) else resources.getString(R.string.subscription_option_basic_message) ) ) // Add Premium Plan Action button actionAdapter.set( ACTION_SUBSCRIBE_PREMIUM, Action( ACTION_SUBSCRIBE_PREMIUM.toLong(), if (premiumSubscription != null) premiumTextForSubscription(resources, premiumSubscription!!) else resources.getString(R.string.subscription_option_premium_message) ) ) // Add Manage Subscriptions Action button actionAdapter.set( ACTION_MANAGE_SUBSCRIPTIONS, Action( ACTION_MANAGE_SUBSCRIPTIONS.toLong(), resources.getString(R.string.manage_subscription_label) ) ) // Add Sign in / out Action button actionAdapter.set( ACTION_SIGN_IN_OUT, Action( ACTION_SIGN_IN_OUT.toLong(), if (authenticationViewModel.isSignedIn()) getString(R.string.sign_out) else getString(R.string.sign_in) ) ) // Set Action Adapter and add DetailsOverviewRow to Presenter class detailsOverviewRow.actionsAdapter = actionAdapter objectAdapter.add(detailsOverviewRow) } /** * Refreshes the UI */ private fun refreshUI() { setupAdapter() setupDetailsOverviewRow() } /** * Custom Fragment used for displaying a Spinner during long running tasks (e.g. network requests) */ class SpinnerFragment : Fragment() { override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { val progressBar = ProgressBar(container?.context) if (container is FrameLayout) { val res = resources val width = res.getDimensionPixelSize(R.dimen.spinner_width) val height = res.getDimensionPixelSize(R.dimen.spinner_height) val layoutParams = FrameLayout.LayoutParams(width, height, Gravity.CENTER) progressBar.layoutParams = layoutParams } return progressBar } } }
apache-2.0
2d4ba4fa06c0604117a20d01dc6c5a98
37.559761
111
0.635687
5.941375
false
false
false
false
iPoli/iPoli-android
app/src/main/java/io/ipoli/android/planday/scenes/PlanDayTodayViewController.kt
1
19526
package io.ipoli.android.planday.scenes import android.content.res.ColorStateList import android.graphics.drawable.GradientDrawable import android.os.Bundle import android.support.annotation.ColorRes import android.support.v4.widget.TextViewCompat import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.RecyclerView import android.support.v7.widget.helper.ItemTouchHelper import android.text.SpannableString import android.text.style.StrikethroughSpan import android.view.* import android.widget.TextView import com.mikepenz.google_material_typeface_library.GoogleMaterial import com.mikepenz.iconics.IconicsDrawable import com.mikepenz.iconics.typeface.IIcon import com.mikepenz.ionicons_typeface_library.Ionicons import io.ipoli.android.Constants import io.ipoli.android.R import io.ipoli.android.common.ViewUtils import io.ipoli.android.common.redux.android.BaseViewController import io.ipoli.android.common.text.QuestStartTimeFormatter import io.ipoli.android.common.view.* import io.ipoli.android.common.view.recyclerview.BaseRecyclerViewAdapter import io.ipoli.android.common.view.recyclerview.RecyclerViewViewModel import io.ipoli.android.common.view.recyclerview.SimpleSwipeCallback import io.ipoli.android.common.view.recyclerview.SimpleViewHolder import io.ipoli.android.pet.AndroidPetAvatar import io.ipoli.android.pet.PetState import io.ipoli.android.planday.PlanDayAction import io.ipoli.android.planday.PlanDayReducer import io.ipoli.android.planday.PlanDayViewState import io.ipoli.android.planday.PlanDayViewState.StateType.* import io.ipoli.android.quest.schedule.addquest.AddQuestAnimationHelper import kotlinx.android.synthetic.main.controller_plan_day_today.view.* import kotlinx.android.synthetic.main.item_plan_today_quest.view.* import kotlinx.android.synthetic.main.item_plan_today_suggestion.view.* import kotlinx.android.synthetic.main.view_empty_list.view.* import kotlinx.android.synthetic.main.view_loader.view.* import org.threeten.bp.LocalDate class PlanDayTodayViewController(args: Bundle? = null) : BaseViewController<PlanDayAction, PlanDayViewState>(args) { override val stateKey = PlanDayReducer.stateKey private lateinit var addQuestAnimationHelper: AddQuestAnimationHelper override var helpConfig: HelpConfig? = HelpConfig( R.string.help_dialog_plan_day_today_title, R.string.help_dialog_plan_day_today_message ) override fun onCreateView( inflater: LayoutInflater, container: ViewGroup, savedViewState: Bundle? ): View { setHasOptionsMenu(true) val view = container.inflate(R.layout.controller_plan_day_today) setToolbar(view.toolbar) val collapsingToolbar = view.collapsingToolbarContainer collapsingToolbar.isTitleEnabled = false view.toolbar.title = stringRes(R.string.plan_my_day) view.todayQuests.layoutManager = LinearLayoutManager( container.context, LinearLayoutManager.VERTICAL, false ) view.todayQuests.adapter = QuestAdapter() view.suggestionQuests.layoutManager = LinearLayoutManager( container.context, LinearLayoutManager.VERTICAL, false ) view.suggestionQuests.adapter = SuggestionAdapter() initSwipe(view) initAddQuest(view) initEmptyView(view) view.descriptionIcon.setImageDrawable( IconicsDrawable(activity!!) .icon(GoogleMaterial.Icon.gmd_info_outline) .color(attrData(R.attr.colorAccent)) .sizeDp(24) ) view.importFromBucketList.onDebounceClick { navigate().toBucketListPicker { qs -> dispatch(PlanDayAction.MoveBucketListQuestsToToday(qs)) } } return view } private fun initSwipe(view: View) { val swipeHandler = object : SimpleSwipeCallback( R.drawable.ic_event_white_24dp, R.color.md_blue_500, R.drawable.ic_delete_white_24dp, R.color.md_red_500 ) { override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) { val questId = questId(viewHolder) if (direction == ItemTouchHelper.END) { navigate() .toReschedule( includeToday = false, listener = { date, time, duration -> dispatch( PlanDayAction.RescheduleQuest( questId, date, time, duration ) ) }, cancelListener = { view.todayQuests.adapter.notifyItemChanged(viewHolder.adapterPosition) } ) } else { dispatch(PlanDayAction.RemoveQuest(questId)) PetMessagePopup( stringRes(R.string.remove_quest_undo_message), { dispatch(PlanDayAction.UndoRemoveQuest(questId)) }, stringRes(R.string.undo) ).show(view.context) } } private fun questId(holder: RecyclerView.ViewHolder): String { val adapter = view.todayQuests.adapter as QuestAdapter val item = adapter.getItemAt(holder.adapterPosition) return item.id } override fun getSwipeDirs( recyclerView: RecyclerView?, viewHolder: RecyclerView.ViewHolder? ) = ItemTouchHelper.START or ItemTouchHelper.END } val itemTouchHelper = ItemTouchHelper(swipeHandler) itemTouchHelper.attachToRecyclerView(view.todayQuests) } private fun initAddQuest(view: View) { addQuestAnimationHelper = AddQuestAnimationHelper( controller = this, addContainer = view.addContainer, fab = view.addQuest, background = view.addContainerBackground ) view.addContainerBackground.onDebounceClick { addContainerRouter(view).popCurrentController() ViewUtils.hideKeyboard(view) addQuestAnimationHelper.closeAddContainer() } view.addQuest.onDebounceClick { addQuestAnimationHelper.openAddContainer(LocalDate.now()) } } private fun addContainerRouter(view: View) = getChildRouter(view.addContainer, "add-quest") private fun initEmptyView(view: View) { view.emptyAnimation.gone() view.emptyTitle.setText(R.string.empty_plan_today_list_title) view.emptyText.setText(R.string.empty_plan_today_list_text) } override fun onAttach(view: View) { super.onAttach(view) exitFullScreen() } override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { super.onCreateOptionsMenu(menu, inflater) inflater.inflate(R.menu.plan_day_today_menu, menu) } override fun onOptionsItemSelected(item: MenuItem): Boolean { if (item.itemId == android.R.id.home) { dispatch(PlanDayAction.Back) return true } if (item.itemId == R.id.actionDone) { dispatch(PlanDayAction.StartDay) return true } return super.onOptionsItemSelected(item) } override fun onCreateLoadAction() = PlanDayAction.LoadToday override fun render(state: PlanDayViewState, view: View) { when (state.type) { TODAY_DATA_LOADED -> { view.loader.gone() (view.todayQuests.adapter as QuestAdapter).updateAll(state.todayViewModels) if (state.todayQuests!!.isEmpty()) { view.dailyQuestsTitle.gone() view.timelineIndicator.gone() view.emptyContainer.visible() view.emptyAnimation.playAnimation() } else { view.dailyQuestsTitle.visible() view.timelineIndicator.visible() view.emptyContainer.gone() view.emptyAnimation.pauseAnimation() } (view.suggestionQuests.adapter as SuggestionAdapter).updateAll(state.suggestionViewModels) if (state.suggestedQuests!!.isEmpty()) { view.suggestionQuestsContainer.gone() } else { view.suggestionQuestsContainer.visible() } renderPet(view, state) } DAILY_CHALLENGE_QUESTS_CHANGED -> { (view.todayQuests.adapter as QuestAdapter).updateAll(state.todayViewModels) renderPet(view, state) } MAX_DAILY_CHALLENGE_QUESTS_REACHED -> showShortToast( stringRes( R.string.max_daily_challenge_selected_message, Constants.DAILY_CHALLENGE_QUEST_COUNT ) ) DAY_STARTED -> { dispatch(PlanDayAction.Done) navigateFromRoot().setHome() } NOT_ENOUGH_DAILY_CHALLENGE_QUESTS -> showShortToast( stringRes( R.string.not_enough_daily_challenge_quests_message, Constants.DAILY_CHALLENGE_QUEST_COUNT - state.dailyChallengeQuestIds!!.size ) ) else -> { } } } private fun renderTag(tagNameView: TextView, tag: TagViewModel) { tagNameView.visible() tagNameView.text = tag.name TextViewCompat.setTextAppearance( tagNameView, R.style.TextAppearance_AppCompat_Caption ) val indicator = tagNameView.compoundDrawablesRelative[0] as GradientDrawable indicator.mutate() val size = ViewUtils.dpToPx(8f, tagNameView.context).toInt() indicator.setSize(size, size) indicator.setColor(colorRes(tag.color)) tagNameView.setCompoundDrawablesRelativeWithIntrinsicBounds( indicator, null, null, null ) } private fun renderPet(view: View, state: PlanDayViewState) { view.dailyChallengePet.setImageResource(state.petAvatarImage) view.dailyChallengePetState.setImageResource(state.petAvatarStateImage) view.dailyChallengePet.visible() view.dailyChallengePetState.visible() view.selectedQuestsCount.text = state.selectedCount } data class TagViewModel(val name: String, @ColorRes val color: Int) data class QuestItem( override val id: String, val name: String, val startTime: String, @ColorRes val color: Int, val tags: List<TagViewModel>, val icon: IIcon, val isRepeating: Boolean, val isFromChallenge: Boolean, val isForDailyChallenge: Boolean, val isSelectableForDailyChallenge: Boolean, val isCompleted: Boolean ) : RecyclerViewViewModel data class SuggestionItem( override val id: String, val name: String, val startTime: String, val startTimeIcon: IIcon, @ColorRes val color: Int, val tags: List<TagViewModel>, val icon: IIcon, val isRepeating: Boolean, val isFromChallenge: Boolean ) : RecyclerViewViewModel inner class QuestAdapter : BaseRecyclerViewAdapter<QuestItem>(R.layout.item_plan_today_quest) { override fun onBindViewModel(vm: QuestItem, view: View, holder: SimpleViewHolder) { if (vm.isCompleted) { val span = SpannableString(vm.name) span.setSpan(StrikethroughSpan(), 0, vm.name.length, 0) view.questName.text = span } else { view.questName.text = vm.name } view.questIcon.backgroundTintList = ColorStateList.valueOf(colorRes(vm.color)) view.questIcon.setImageDrawable(smallListItemIcon(vm.icon)) view.questStartTime.text = vm.startTime view.questStartTime.setCompoundDrawablesRelativeWithIntrinsicBounds( IconicsDrawable(view.context) .icon(GoogleMaterial.Icon.gmd_timer) .sizeDp(16) .colorRes(colorTextSecondaryResource) .respectFontBounds(true), null, null, null ) if (vm.tags.isNotEmpty()) { renderTag(view.questTagName, vm.tags.first()) } else { view.questTagName.gone() } view.questRepeatIndicator.visibility = if (vm.isRepeating) View.VISIBLE else View.GONE view.questChallengeIndicator.visibility = if (vm.isFromChallenge) View.VISIBLE else View.GONE if (vm.isForDailyChallenge && !vm.isSelectableForDailyChallenge) { view.questStar.visible() view.questStar.setImageResource(R.drawable.ic_star_grey_24dp) view.questStar.setOnClickListener(null) } else if (vm.isForDailyChallenge) { view.questStar.visible() view.questStar.setImageResource(R.drawable.ic_star_accent_24dp) view.questStar.onDebounceClick { dispatch(PlanDayAction.RemoveDailyChallengeQuest(vm.id)) } } else if (vm.isSelectableForDailyChallenge) { view.questStar.visible() view.questStar.setImageResource(R.drawable.ic_star_border_text_secondary_24dp) view.questStar.onDebounceClick { dispatch(PlanDayAction.AddDailyChallengeQuest(vm.id)) } } else { view.questStar.gone() } } } inner class SuggestionAdapter : BaseRecyclerViewAdapter<SuggestionItem>(R.layout.item_plan_today_suggestion) { override fun onBindViewModel(vm: SuggestionItem, view: View, holder: SimpleViewHolder) { view.suggestionName.text = vm.name view.suggestionIcon.backgroundTintList = ColorStateList.valueOf(colorRes(vm.color)) view.suggestionIcon.setImageDrawable(smallListItemIcon(vm.icon)) view.suggestionStartTime.text = vm.startTime view.suggestionStartTime.setCompoundDrawablesRelativeWithIntrinsicBounds( IconicsDrawable(view.context) .icon(vm.startTimeIcon) .sizeDp(16) .colorRes(colorTextSecondaryResource) .respectFontBounds(true), null, null, null ) if (vm.tags.isNotEmpty()) { renderTag(view.suggestionTagName, vm.tags.first()) } else { view.suggestionTagName.gone() } view.suggestionRepeatIndicator.visibility = if (vm.isRepeating) View.VISIBLE else View.GONE view.suggestionChallengeIndicator.visibility = if (vm.isFromChallenge) View.VISIBLE else View.GONE view.suggestionAccept.onDebounceClick { dispatch(PlanDayAction.AcceptSuggestion(vm.id)) showShortToast(R.string.suggestion_accepted) } } } private val PlanDayViewState.suggestionViewModels: List<SuggestionItem> get() = suggestedQuests!!.map { SuggestionItem( id = it.id, name = it.name, tags = it.tags.map { t -> TagViewModel( t.name, t.color.androidColor.color500 ) }, startTime = QuestStartTimeFormatter.formatWithDuration( it, activity!!, shouldUse24HourFormat ), startTimeIcon = if (it.isScheduled) GoogleMaterial.Icon.gmd_access_time else GoogleMaterial.Icon.gmd_timer, color = it.color.androidColor.color500, icon = it.icon?.androidIcon?.icon ?: Ionicons.Icon.ion_checkmark, isRepeating = it.isFromRepeatingQuest, isFromChallenge = it.isFromChallenge ) } private val PlanDayViewState.todayViewModels: List<QuestItem> get() = todayQuests!!.map { QuestItem( id = it.id, name = it.name, tags = it.tags.map { t -> TagViewModel( t.name, t.color.androidColor.color500 ) }, startTime = QuestStartTimeFormatter.formatWithDuration( it, activity!!, shouldUse24HourFormat ), color = it.color.androidColor.color500, icon = it.icon?.androidIcon?.icon ?: Ionicons.Icon.ion_checkmark, isRepeating = it.isFromRepeatingQuest, isFromChallenge = it.isFromChallenge, isForDailyChallenge = dailyChallengeQuestIds!!.contains(it.id), isSelectableForDailyChallenge = !isDailyChallengeCompleted, isCompleted = it.isCompleted ) } private val PlanDayViewState.petAvatarImage: Int get() = AndroidPetAvatar.valueOf(petAvatar!!.name).image private val PlanDayViewState.petAvatarStateImage: Int get() { val stateImage = AndroidPetAvatar.valueOf(petAvatar!!.name).stateImage return when (dailyChallengeQuestIds!!.size) { 3 -> stateImage[PetState.AWESOME]!! 2 -> stateImage[PetState.HAPPY]!! 1 -> stateImage[PetState.GOOD]!! 0 -> stateImage[PetState.SAD]!! else -> throw IllegalStateException("Unexpected daily challenge quests count ${dailyChallengeQuestIds.size}") } } private val PlanDayViewState.selectedCount: String get() { val count = dailyChallengeQuestIds!!.size return if (count == Constants.DAILY_CHALLENGE_QUEST_COUNT) { stringRes(R.string.daily_challenge_active) } else { stringRes( R.string.selected_daily_challenge_count, count, Constants.DAILY_CHALLENGE_QUEST_COUNT ) } } }
gpl-3.0
09164a1ec24193305512e5643d17dc38
36.990272
125
0.579689
5.463346
false
false
false
false
spinnaker/orca
orca-queue/src/test/kotlin/com/netflix/spinnaker/orca/q/MessageCompatibilityTest.kt
4
2591
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License") * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.spinnaker.orca.q import com.fasterxml.jackson.module.kotlin.convertValue import com.netflix.spinnaker.orca.api.pipeline.SyntheticStageOwner.STAGE_AFTER import com.netflix.spinnaker.orca.api.pipeline.SyntheticStageOwner.STAGE_BEFORE import com.netflix.spinnaker.orca.jackson.OrcaObjectMapper import com.netflix.spinnaker.q.Message import java.util.UUID import org.assertj.core.api.Assertions.assertThat import org.jetbrains.spek.api.Spek import org.jetbrains.spek.api.dsl.describe import org.jetbrains.spek.api.dsl.given import org.jetbrains.spek.api.dsl.it import org.jetbrains.spek.api.dsl.on internal object MessageCompatibilityTest : Spek({ describe("deserializing ContinueParentStage") { val mapper = OrcaObjectMapper.newInstance().apply { registerSubtypes(ContinueParentStage::class.java) } val json = mapOf( "kind" to "continueParentStage", "executionType" to "PIPELINE", "executionId" to UUID.randomUUID().toString(), "application" to "covfefe", "stageId" to UUID.randomUUID().toString() ) given("an older message with no syntheticStageOwner") { on("deserializing the JSON") { val message = mapper.convertValue<Message>(json) it("doesn't blow up") { assertThat(message).isInstanceOf(ContinueParentStage::class.java) } it("defaults the missing field") { assertThat((message as ContinueParentStage).phase).isEqualTo(STAGE_BEFORE) } } } given("a newer message with a syntheticStageOwner") { val newJson = json + mapOf("phase" to "STAGE_AFTER") on("deserializing the JSON") { val message = mapper.convertValue<Message>(newJson) it("doesn't blow up") { assertThat(message).isInstanceOf(ContinueParentStage::class.java) } it("deserializes the new field") { assertThat((message as ContinueParentStage).phase).isEqualTo(STAGE_AFTER) } } } } })
apache-2.0
42cfd2cd8f5e20f52ecb56e7ca6fe4f0
32.649351
84
0.709765
4.311148
false
false
false
false
marius-m/wt4
app/src/main/java/lt/markmerkk/widgets/tickets/TicketFilterSettingsPresenter.kt
1
3202
package lt.markmerkk.widgets.tickets import lt.markmerkk.SchedulerProvider import lt.markmerkk.TicketStorage import lt.markmerkk.TimeProvider import lt.markmerkk.UserSettings import lt.markmerkk.entities.TicketStatus import lt.markmerkk.tickets.TicketApi import lt.markmerkk.tickets.TicketStatusesLoader import org.slf4j.LoggerFactory import rx.Subscription class TicketFilterSettingsPresenter( private val view: TicketFilterSettingsContract.View, private val ticketApi: TicketApi, private val timeProvider: TimeProvider, private val ticketStorage: TicketStorage, private val userSettings: UserSettings, private val schedulerProvider: SchedulerProvider ) : TicketFilterSettingsContract.Presenter { private var subsUpdate: Subscription? = null private lateinit var ticketStatusesLoader: TicketStatusesLoader override fun onAttach() { ticketStatusesLoader = TicketStatusesLoader( listener = view, ticketApi = ticketApi, timeProvider = timeProvider, ioScheduler = schedulerProvider.io(), uiScheduler = schedulerProvider.ui() ) ticketStatusesLoader.onAttach() } override fun onDetach() { ticketStatusesLoader.onDetach() } override fun loadTicketStatuses() { ticketStatusesLoader.fetchTicketStatuses() } override fun saveTicketStatuses( ticketStatusViewModels: List<TicketStatusViewModel>, useOnlyCurrentUser: Boolean, filterIncludeAssignee: Boolean, filterIncludeReporter: Boolean, filterIncludeIsWatching: Boolean ) { val newTicketStatuses = ticketStatusViewModels .map { TicketStatus(it.nameProperty.get(), it.enableProperty.get()) } val enabledTicketStatusNames = newTicketStatuses .filter { it.enabled } .map { it.name } subsUpdate = ticketStorage .updateTicketStatuses(newTicketStatuses) .subscribeOn(schedulerProvider.io()) .doOnSuccess { userSettings.issueJql = TicketJQLGenerator .generateJQL(enabledStatuses = enabledTicketStatusNames, onlyCurrentUser = useOnlyCurrentUser) userSettings.onlyCurrentUserIssues = useOnlyCurrentUser userSettings.ticketFilterIncludeAssignee = filterIncludeAssignee userSettings.ticketFilterIncludeReporter = filterIncludeReporter userSettings.ticketFilterIncludeIsWatching = filterIncludeIsWatching } .observeOn(schedulerProvider.ui()) .doOnSubscribe { view.showProgress() } .doAfterTerminate { view.hideProgress() } .subscribe({ view.cleanUpAndExit() }, { view.cleanUpAndExit() logger.warn("Error saving ticket filter settings", it) }) } companion object { private val logger = LoggerFactory.getLogger(TicketFilterSettingsPresenter::class.java)!! } }
apache-2.0
511ab00b402341340cb5174825108a27
38.54321
122
0.653029
6.075901
false
false
false
false
linkedin/LiTr
litr/src/main/java/com/linkedin/android/litr/io/WavMediaTarget.kt
1
5788
/* * Copyright 2019 LinkedIn Corporation * All Rights Reserved. * * Licensed under the BSD 2-Clause License (the "License"). See License in the project root for * license information. */ // header implementation by Kevin Mark is taken from https://gist.github.com/kmark/d8b1b01fb0d2febf5770 and modified package com.linkedin.android.litr.io import android.media.MediaCodec import android.media.MediaFormat import java.io.File import java.io.FileOutputStream import java.io.IOException import java.io.OutputStream import java.io.RandomAccessFile import java.nio.ByteBuffer import java.nio.ByteOrder import kotlin.IllegalStateException private const val BYTES_PER_SAMPLE = 2 private const val MAX_SIZE = 4294967295 /** * Implementation of [MediaTarget] that writes a single audio track to WAV file. * Accepts only one track in "audio-raw" format that has channel count and sample rate data. * Track rata must be in 16 bit little endian PCM format, e.g. coming from a direct ByteBuffer. */ class WavMediaTarget( private val targetPath: String ) : MediaTarget { private val tracks = mutableListOf<MediaFormat>() private val outputStream: OutputStream private var size: Long = 0 init { outputStream = FileOutputStream(File(targetPath)) } override fun addTrack(mediaFormat: MediaFormat, targetTrack: Int): Int { return if (tracks.size == 0 && mediaFormat.containsKey(MediaFormat.KEY_MIME) && mediaFormat.getString(MediaFormat.KEY_MIME) == "audio/raw" && mediaFormat.containsKey(MediaFormat.KEY_CHANNEL_COUNT) && mediaFormat.containsKey(MediaFormat.KEY_SAMPLE_RATE)) { tracks.add(mediaFormat) writeWavHeader( mediaFormat.getInteger(MediaFormat.KEY_CHANNEL_COUNT), mediaFormat.getInteger(MediaFormat.KEY_SAMPLE_RATE), BYTES_PER_SAMPLE ) 0 } else { -1 } } override fun writeSampleData(targetTrack: Int, buffer: ByteBuffer, info: MediaCodec.BufferInfo) { size += info.size if (size >= MAX_SIZE) { release() throw IllegalStateException("WAV file size cannot exceed $MAX_SIZE bytes") } outputStream.write(buffer.array(), info.offset, info.size) } override fun release() { outputStream.close() updateWavHeader() } override fun getOutputFilePath(): String { return targetPath } // modified version of https://gist.github.com/kmark/d8b1b01fb0d2febf5770#file-audiorecordactivity-java-L288 /** * Writes the proper 44-byte RIFF/WAVE header to/for the given stream * Two size fields are left empty/null since we do not yet know the final stream size * * @param channelCount number of channels * @param sampleRate sample rate in hertz * @param bytesPerSample number of bytes per audio channel sample */ private fun writeWavHeader(channelCount: Int, sampleRate: Int, bytesPerSample: Int) { // Convert the multi-byte integers to raw bytes in little endian format as required by the spec val littleBytes = ByteBuffer .allocate(14) .order(ByteOrder.LITTLE_ENDIAN) .putShort(channelCount.toShort()) .putInt(sampleRate) .putInt(sampleRate * channelCount * bytesPerSample) .putShort((channelCount * bytesPerSample).toShort()) .putShort((bytesPerSample * 8).toShort()) .array() // Not necessarily the best, but it's very easy to visualize this way outputStream.write(byteArrayOf( // RIFF header 'R'.toByte(), 'I'.toByte(), 'F'.toByte(), 'F'.toByte(), // ChunkID 0, 0, 0, 0, // ChunkSize (must be updated later) 'W'.toByte(), 'A'.toByte(), 'V'.toByte(), 'E'.toByte(), // Format // fmt subchunk 'f'.toByte(), 'm'.toByte(), 't'.toByte(), ' '.toByte(), // Subchunk1ID 16, 0, 0, 0, // Subchunk1 Size 1, 0, // AudioFormat littleBytes[0], littleBytes[1], // NumChannels littleBytes[2], littleBytes[3], littleBytes[4], littleBytes[5], // SampleRate littleBytes[6], littleBytes[7], littleBytes[8], littleBytes[9], // ByteRate littleBytes[10], littleBytes[11], // BlockAlign littleBytes[12], littleBytes[13], // BitsPerSample // data subchunk 'd'.toByte(), 'a'.toByte(), 't'.toByte(), 'a'.toByte(), // Subchunk2 ID 0, 0, 0, 0)) } // modified version of https://gist.github.com/kmark/d8b1b01fb0d2febf5770#file-audiorecordactivity-java-L331 /** * Updates the given wav file's header to include the final chunk sizes */ private fun updateWavHeader() { val targetFile = File(targetPath) val sizes = ByteBuffer .allocate(8) .order(ByteOrder.LITTLE_ENDIAN) .putInt((targetFile.length() - 8).toInt()) // ChunkSize .putInt((targetFile.length() - 44).toInt()) // Subchunk2Size .array() var accessWave: RandomAccessFile? = null try { accessWave = RandomAccessFile(targetFile, "rw") // ChunkSize accessWave.seek(4) accessWave.write(sizes, 0, 4) // Subchunk2Size accessWave.seek(40) accessWave.write(sizes, 4, 4) } catch (ex: IOException) { throw ex } finally { if (accessWave != null) { try { accessWave.close() } catch (ex: IOException) { // fail silently } } } } }
bsd-2-clause
ad9a6fe6f276475fec4fab37131e8be1
37.078947
116
0.613856
4.361718
false
false
false
false
RayBa82/DVBViewerController
dvbViewerController/src/main/java/org/dvbviewer/controller/activitiy/base/GroupDrawerActivity.kt
1
3853
package org.dvbviewer.controller.activitiy.base import android.database.Cursor import android.os.Bundle import android.view.View import android.widget.AdapterView import android.widget.AdapterView.OnItemClickListener import androidx.loader.app.LoaderManager import androidx.loader.content.CursorLoader import androidx.loader.content.Loader import org.dvbviewer.controller.activitiy.DrawerActivity import org.dvbviewer.controller.data.ProviderConsts import org.dvbviewer.controller.data.entities.ChannelGroup import org.dvbviewer.controller.data.entities.DVBViewerPreferences import org.dvbviewer.controller.ui.fragments.ChannelEpg import org.dvbviewer.controller.ui.fragments.ChannelPager import org.dvbviewer.controller.ui.fragments.EpgPager import java.util.* abstract class GroupDrawerActivity : DrawerActivity(), OnItemClickListener, LoaderManager.LoaderCallbacks<Cursor>, ChannelEpg.EpgDateInfo, ChannelPager.OnGroupChangedListener { protected lateinit var prefs: DVBViewerPreferences protected var mEpgPager: EpgPager? = null protected var groupIndex = 0 protected var showFavs: Boolean = false override var epgDate: Long = 0 /* * (non-Javadoc) * * @see * org.dvbviewer.controller.ui.base.BaseSinglePaneActivity#onCreate(android * .os.Bundle) */ override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setDisplayHomeAsUpEnabled(true) prefs = DVBViewerPreferences(this) showFavs = prefs.prefs.getBoolean(DVBViewerPreferences.KEY_CHANNELS_USE_FAVS, false) epgDate = if (savedInstanceState != null && savedInstanceState.containsKey(ChannelEpg.KEY_EPG_DAY)) savedInstanceState.getLong(ChannelEpg.KEY_EPG_DAY) else Date().time if (savedInstanceState != null) { groupIndex = savedInstanceState.getInt(ChannelPager.KEY_GROUP_INDEX, 0) } else { groupIndex = intent.getIntExtra(ChannelPager.KEY_GROUP_INDEX, 0) } supportLoaderManager.initLoader(0, savedInstanceState, this) } override fun onCreateLoader(id: Int, args: Bundle?): Loader<Cursor> { showFavs = prefs.getBoolean(DVBViewerPreferences.KEY_CHANNELS_USE_FAVS, false) val selection = if (showFavs) ProviderConsts.GroupTbl.TYPE + " = " + ChannelGroup.TYPE_FAV else ProviderConsts.GroupTbl.TYPE + " = " + ChannelGroup.TYPE_CHAN val orderBy = ProviderConsts.GroupTbl._ID return CursorLoader(this, ProviderConsts.GroupTbl.CONTENT_URI, null, selection, null, orderBy) } override fun onLoadFinished(loader: Loader<Cursor>, data: Cursor) { mDrawerAdapter.changeCursor(data) mDrawerList.setItemChecked(groupIndex, true) } override fun onLoaderReset(loader: Loader<Cursor>) { } override fun onItemClick(parent: AdapterView<*>, view: View, position: Int, id: Long) { groupIndex = position mDrawerLayout.closeDrawers() } /* (non-Javadoc) * @see com.actionbarsherlock.app.SherlockFragmentActivity#onSaveInstanceState(android.os.Bundle) */ override fun onSaveInstanceState(outState: Bundle) { outState.putLong(ChannelEpg.KEY_EPG_DAY, epgDate) outState.putInt(ChannelPager.KEY_GROUP_INDEX, groupIndex) super.onSaveInstanceState(outState) } override fun groupChanged(groupId: Long, groupIndex: Int, channelIndex: Int) { this.groupIndex = groupIndex for (i in 0 until mDrawerList.adapter.count) { mDrawerList.setItemChecked(i, false) } mDrawerList.setItemChecked(groupIndex, true) if (mEpgPager != null) { mEpgPager!!.refresh(groupId, channelIndex) } } companion object { val CHANNEL_PAGER_TAG = ChannelPager::class.java.simpleName val EPG_PAGER_TAG = EpgPager::class.java.simpleName } }
apache-2.0
854c6303c41c6de1cd6a6eb1053d01da
37.919192
176
0.731897
4.433832
false
false
false
false
inorichi/mangafeed
app/src/main/java/eu/kanade/tachiyomi/data/updater/AppUpdateService.kt
2
6009
package eu.kanade.tachiyomi.data.updater import android.app.PendingIntent import android.app.Service import android.content.Context import android.content.Intent import android.os.IBinder import android.os.PowerManager import androidx.core.content.ContextCompat import eu.kanade.tachiyomi.BuildConfig import eu.kanade.tachiyomi.R import eu.kanade.tachiyomi.data.notification.Notifications import eu.kanade.tachiyomi.network.GET import eu.kanade.tachiyomi.network.NetworkHelper import eu.kanade.tachiyomi.network.ProgressListener import eu.kanade.tachiyomi.network.await import eu.kanade.tachiyomi.network.newCallWithProgress import eu.kanade.tachiyomi.util.lang.launchIO import eu.kanade.tachiyomi.util.storage.getUriCompat import eu.kanade.tachiyomi.util.storage.saveTo import eu.kanade.tachiyomi.util.system.acquireWakeLock import eu.kanade.tachiyomi.util.system.isServiceRunning import eu.kanade.tachiyomi.util.system.logcat import logcat.LogPriority import uy.kohesive.injekt.injectLazy import java.io.File class AppUpdateService : Service() { private val network: NetworkHelper by injectLazy() /** * Wake lock that will be held until the service is destroyed. */ private lateinit var wakeLock: PowerManager.WakeLock private lateinit var notifier: AppUpdateNotifier override fun onCreate() { super.onCreate() notifier = AppUpdateNotifier(this) wakeLock = acquireWakeLock(javaClass.name) startForeground(Notifications.ID_APP_UPDATER, notifier.onDownloadStarted().build()) } /** * This method needs to be implemented, but it's not used/needed. */ override fun onBind(intent: Intent): IBinder? = null override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { if (intent == null) return START_NOT_STICKY val url = intent.getStringExtra(EXTRA_DOWNLOAD_URL) ?: return START_NOT_STICKY val title = intent.getStringExtra(EXTRA_DOWNLOAD_TITLE) ?: getString(R.string.app_name) launchIO { downloadApk(title, url) } stopSelf(startId) return START_NOT_STICKY } override fun stopService(name: Intent?): Boolean { destroyJob() return super.stopService(name) } override fun onDestroy() { destroyJob() super.onDestroy() } private fun destroyJob() { if (wakeLock.isHeld) { wakeLock.release() } } /** * Called to start downloading apk of new update * * @param url url location of file */ private suspend fun downloadApk(title: String, url: String) { // Show notification download starting. notifier.onDownloadStarted(title) val progressListener = object : ProgressListener { // Progress of the download var savedProgress = 0 // Keep track of the last notification sent to avoid posting too many. var lastTick = 0L override fun update(bytesRead: Long, contentLength: Long, done: Boolean) { val progress = (100 * (bytesRead.toFloat() / contentLength)).toInt() val currentTime = System.currentTimeMillis() if (progress > savedProgress && currentTime - 200 > lastTick) { savedProgress = progress lastTick = currentTime notifier.onProgressChange(progress) } } } try { // Download the new update. val response = network.client.newCallWithProgress(GET(url), progressListener).await() // File where the apk will be saved. val apkFile = File(externalCacheDir, "update.apk") if (response.isSuccessful) { response.body!!.source().saveTo(apkFile) } else { response.close() throw Exception("Unsuccessful response") } notifier.onDownloadFinished(apkFile.getUriCompat(this)) } catch (error: Exception) { logcat(LogPriority.ERROR, error) notifier.onDownloadError(url) } } companion object { internal const val EXTRA_DOWNLOAD_URL = "${BuildConfig.APPLICATION_ID}.UpdaterService.DOWNLOAD_URL" internal const val EXTRA_DOWNLOAD_TITLE = "${BuildConfig.APPLICATION_ID}.UpdaterService.DOWNLOAD_TITLE" /** * Returns the status of the service. * * @param context the application context. * @return true if the service is running, false otherwise. */ private fun isRunning(context: Context): Boolean = context.isServiceRunning(AppUpdateService::class.java) /** * Downloads a new update and let the user install the new version from a notification. * * @param context the application context. * @param url the url to the new update. */ fun start(context: Context, url: String, title: String = context.getString(R.string.app_name)) { if (!isRunning(context)) { val intent = Intent(context, AppUpdateService::class.java).apply { putExtra(EXTRA_DOWNLOAD_TITLE, title) putExtra(EXTRA_DOWNLOAD_URL, url) } ContextCompat.startForegroundService(context, intent) } } /** * Returns [PendingIntent] that starts a service which downloads the apk specified in url. * * @param url the url to the new update. * @return [PendingIntent] */ internal fun downloadApkPendingService(context: Context, url: String): PendingIntent { val intent = Intent(context, AppUpdateService::class.java).apply { putExtra(EXTRA_DOWNLOAD_URL, url) } return PendingIntent.getService(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT) } } }
apache-2.0
65c8cacea3e367eff48f43ea594221c1
33.734104
111
0.640706
4.933498
false
false
false
false
jovr/imgui
glfw/src/main/kotlin/imgui/impl/glfw/ImplGlfw.kt
1
12569
package imgui.impl.glfw import glm_.b import glm_.c import glm_.f import glm_.vec2.Vec2 import glm_.vec2.Vec2d import glm_.vec2.Vec2i import imgui.* import imgui.ImGui.io import imgui.ImGui.mouseCursor import imgui.Key import imgui.api.g import imgui.impl.* import imgui.windowsIme.imeListener import kool.cap import kool.lim import org.lwjgl.glfw.GLFW.* import org.lwjgl.system.MemoryUtil.NULL import org.lwjgl.system.Platform import uno.glfw.* import uno.glfw.GlfwWindow.CursorMode import java.nio.ByteBuffer import java.nio.FloatBuffer import kotlin.collections.set // GLFW callbacks // - When calling Init with 'install_callbacks=true': GLFW callbacks will be installed for you. They will call user's previously installed callbacks, if any. // - When calling Init with 'install_callbacks=false': GLFW callbacks won't be installed. You will need to call those function yourself from your own GLFW callbacks. class ImplGlfw @JvmOverloads constructor( /** Main window */ val window: GlfwWindow, installCallbacks: Boolean = true, /** for vr environment */ val vrTexSize: Vec2i? = null, clientApi: GlfwClientApi = GlfwClientApi.OpenGL) { /** for passing inputs in vr */ var vrCursorPos: Vec2? = null init { with(io) { // Setup backend capabilities flags backendFlags = backendFlags or BackendFlag.HasMouseCursors // We can honor GetMouseCursor() values (optional) backendFlags = backendFlags or BackendFlag.HasSetMousePos // We can honor io.WantSetMousePos requests (optional, rarely used) backendPlatformName = "imgui_impl_glfw" // Keyboard mapping. Dear ImGui will use those indices to peek into the io.KeysDown[] array. keyMap[Key.Tab] = GLFW_KEY_TAB keyMap[Key.LeftArrow] = GLFW_KEY_LEFT keyMap[Key.RightArrow] = GLFW_KEY_RIGHT keyMap[Key.UpArrow] = GLFW_KEY_UP keyMap[Key.DownArrow] = GLFW_KEY_DOWN keyMap[Key.PageUp] = GLFW_KEY_PAGE_UP keyMap[Key.PageDown] = GLFW_KEY_PAGE_DOWN keyMap[Key.Home] = GLFW_KEY_HOME keyMap[Key.End] = GLFW_KEY_END keyMap[Key.Insert] = GLFW_KEY_INSERT keyMap[Key.Delete] = GLFW_KEY_DELETE keyMap[Key.Backspace] = GLFW_KEY_BACKSPACE keyMap[Key.Space] = GLFW_KEY_SPACE keyMap[Key.Enter] = GLFW_KEY_ENTER keyMap[Key.Escape] = GLFW_KEY_ESCAPE keyMap[Key.KeyPadEnter] = GLFW_KEY_KP_ENTER keyMap[Key.A] = GLFW_KEY_A keyMap[Key.C] = GLFW_KEY_C keyMap[Key.V] = GLFW_KEY_V keyMap[Key.X] = GLFW_KEY_X keyMap[Key.Y] = GLFW_KEY_Y keyMap[Key.Z] = GLFW_KEY_Z backendRendererName = null backendPlatformName = null backendLanguageUserData = null backendRendererUserData = null backendPlatformUserData = null setClipboardTextFn = { _, text -> glfwSetClipboardString(clipboardUserData as Long, text) } getClipboardTextFn = { glfwGetClipboardString(clipboardUserData as Long) } clipboardUserData = window.handle.value if (Platform.get() == Platform.WINDOWS) imeWindowHandle = window.hwnd } // Create mouse cursors // (By design, on X11 cursors are user configurable and some cursors may be missing. When a cursor doesn't exist, // GLFW will emit an error which will often be printed by the app, so we temporarily disable error reporting. // Missing cursors will return NULL and our _UpdateMouseCursor() function will use the Arrow cursor instead.) val prevErrorCallback = glfwSetErrorCallback(null) mouseCursors[MouseCursor.Arrow.i] = glfwCreateStandardCursor(GLFW_ARROW_CURSOR) mouseCursors[MouseCursor.TextInput.i] = glfwCreateStandardCursor(GLFW_IBEAM_CURSOR) mouseCursors[MouseCursor.ResizeAll.i] = glfwCreateStandardCursor(GLFW_ARROW_CURSOR) // FIXME: GLFW doesn't have this. [JVM] TODO // mouseCursors[MouseCursor.ResizeAll.i] = glfwCreateStandardCursor(GLFW_RESIZE_ALL_CURSOR) mouseCursors[MouseCursor.ResizeNS.i] = glfwCreateStandardCursor(GLFW_VRESIZE_CURSOR) mouseCursors[MouseCursor.ResizeEW.i] = glfwCreateStandardCursor(GLFW_HRESIZE_CURSOR) mouseCursors[MouseCursor.ResizeNESW.i] = glfwCreateStandardCursor(GLFW_ARROW_CURSOR) // FIXME: GLFW doesn't have this. mouseCursors[MouseCursor.ResizeNWSE.i] = glfwCreateStandardCursor(GLFW_ARROW_CURSOR) // FIXME: GLFW doesn't have this. // mouseCursors[MouseCursor.ResizeNESW.i] = glfwCreateStandardCursor(GLFW_RESIZE_NESW_CURSOR) // mouseCursors[MouseCursor.ResizeNWSE.i] = glfwCreateStandardCursor(GLFW_RESIZE_NWSE_CURSOR) mouseCursors[MouseCursor.Hand.i] = glfwCreateStandardCursor(GLFW_HAND_CURSOR) mouseCursors[MouseCursor.NotAllowed.i] = glfwCreateStandardCursor(GLFW_ARROW_CURSOR) // mouseCursors[MouseCursor.NotAllowed.i] = glfwCreateStandardCursor(GLFW_NOT_ALLOWED_CURSOR) glfwSetErrorCallback(prevErrorCallback) // [JVM] Chain GLFW callbacks: our callbacks will be installed in parallel with any other already existing if (installCallbacks) { // native callbacks will be added at the GlfwWindow creation via default parameter window.mouseButtonCBs["imgui"] = mouseButtonCallback window.scrollCBs["imgui"] = scrollCallback window.keyCBs["imgui"] = keyCallback window.charCBs["imgui"] = charCallback imeListener.install(window) } imgui.impl.clientApi = clientApi } fun shutdown() { mouseCursors.forEach(::glfwDestroyCursor) mouseCursors.fill(NULL) clientApi = GlfwClientApi.Unknown } private fun updateMousePosAndButtons() { // Update buttons repeat(io.mouseDown.size) { /* If a mouse press event came, always pass it as "mouse held this frame", so we don't miss click-release events that are shorter than 1 frame. */ io.mouseDown[it] = mouseJustPressed[it] || glfwGetMouseButton(window.handle.value, it) != 0 mouseJustPressed[it] = false } // Update mouse position val mousePosBackup = Vec2d(io.mousePos) io.mousePos put -Float.MAX_VALUE if (window.isFocused) if (io.wantSetMousePos) window.cursorPos = mousePosBackup else io.mousePos put (vrCursorPos ?: window.cursorPos) else vrCursorPos?.let(io.mousePos::put) // window is usually unfocused in vr } private fun updateMouseCursor() { if (io.configFlags has ConfigFlag.NoMouseCursorChange || window.cursorMode == CursorMode.disabled) return val imguiCursor = mouseCursor if (imguiCursor == MouseCursor.None || io.mouseDrawCursor) // Hide OS mouse cursor if imgui is drawing it or if it wants no cursor window.cursorMode = CursorMode.hidden else { // Show OS mouse cursor // FIXME-PLATFORM: Unfocused windows seems to fail changing the mouse cursor with GLFW 3.2, but 3.3 works here. window.cursor = GlfwCursor(mouseCursors[imguiCursor.i].takeIf { it != NULL } ?: mouseCursors[MouseCursor.Arrow.i]) window.cursorMode = CursorMode.normal } } fun updateGamepads() { io.navInputs.fill(0f) if (io.configFlags has ConfigFlag.NavEnableGamepad) { // Update gamepad inputs val buttons = Joystick._1.buttons ?: ByteBuffer.allocate(0) val buttonsCount = buttons.lim val axes = Joystick._1.axes ?: FloatBuffer.allocate(0) val axesCount = axes.lim fun mapButton(nav: NavInput, button: Int) { if (buttonsCount > button && buttons[button] == GLFW_PRESS.b) io.navInputs[nav] = 1f } fun mapAnalog(nav: NavInput, axis: Int, v0: Float, v1: Float) { var v = if (axesCount > axis) axes[axis] else v0 v = (v - v0) / (v1 - v0) if (v > 1f) v = 1f if (io.navInputs[nav] < v) io.navInputs[nav] = v } mapButton(NavInput.Activate, 0) // Cross / A mapButton(NavInput.Cancel, 1) // Circle / B mapButton(NavInput.Menu, 2) // Square / X mapButton(NavInput.Input, 3) // Triangle / Y mapButton(NavInput.DpadLeft, 13) // D-Pad Left mapButton(NavInput.DpadRight, 11) // D-Pad Right mapButton(NavInput.DpadUp, 10) // D-Pad Up mapButton(NavInput.DpadDown, 12) // D-Pad Down mapButton(NavInput.FocusPrev, 4) // L1 / LB mapButton(NavInput.FocusNext, 5) // R1 / RB mapButton(NavInput.TweakSlow, 4) // L1 / LB mapButton(NavInput.TweakFast, 5) // R1 / RB mapAnalog(NavInput.LStickLeft, 0, -0.3f, -0.9f) mapAnalog(NavInput.LStickRight, 0, +0.3f, +0.9f) mapAnalog(NavInput.LStickUp, 1, +0.3f, +0.9f) mapAnalog(NavInput.LStickDown, 1, -0.3f, -0.9f) io.backendFlags = when { axesCount > 0 && buttonsCount > 0 -> io.backendFlags or BackendFlag.HasGamepad else -> io.backendFlags wo BackendFlag.HasGamepad } } } fun newFrame() { assert(io.fonts.isBuilt) { "Font atlas not built! It is generally built by the renderer backend. Missing call to renderer _NewFrame() function? e.g. ImGui_ImplOpenGL3_NewFrame()." } // Setup display size (every frame to accommodate for window resizing) val size = window.size val displaySize = window.framebufferSize io.displaySize put (vrTexSize ?: window.size) if (size allGreaterThan 0) io.displayFramebufferScale put (displaySize / size) // Setup time step val currentTime = glfw.time io.deltaTime = if (time > 0) (currentTime - time).f else 1f / 60f time = currentTime updateMousePosAndButtons() updateMouseCursor() // Update game controllers (if enabled and available) updateGamepads() } companion object { lateinit var instance: ImplGlfw fun init(window: GlfwWindow, installCallbacks: Boolean = true, vrTexSize: Vec2i? = null) { instance = ImplGlfw(window, installCallbacks, vrTexSize) } fun newFrame() = instance.newFrame() fun shutdown() = instance.shutdown() val mouseButtonCallback: MouseButtonCB = { button: Int, action: Int, _: Int -> if (action == GLFW_PRESS && button in 0..2) mouseJustPressed[button] = true } val scrollCallback: ScrollCB = { offset: Vec2d -> io.mouseWheelH += offset.x.f io.mouseWheel += offset.y.f } val keyCallback: KeyCB = { key: Int, _: Int, action: Int, _: Int -> with(io) { if (key in keysDown.indices) if (action == GLFW_PRESS) keysDown[key] = true else if (action == GLFW_RELEASE) keysDown[key] = false // Modifiers are not reliable across systems keyCtrl = keysDown[GLFW_KEY_LEFT_CONTROL] || keysDown[GLFW_KEY_RIGHT_CONTROL] keyShift = keysDown[GLFW_KEY_LEFT_SHIFT] || keysDown[GLFW_KEY_RIGHT_SHIFT] keyAlt = keysDown[GLFW_KEY_LEFT_ALT] || keysDown[GLFW_KEY_RIGHT_ALT] keySuper = when(Platform.get()) { Platform.WINDOWS -> false else -> keysDown[GLFW_KEY_LEFT_SUPER] || keysDown[GLFW_KEY_RIGHT_SUPER] } } } val charCallback: CharCB = { c: Int -> if (!imeInProgress) io.addInputCharacter(c.c) } fun initForOpengl(window: GlfwWindow, installCallbacks: Boolean = true, vrTexSize: Vec2i? = null): ImplGlfw = ImplGlfw(window, installCallbacks, vrTexSize, GlfwClientApi.OpenGL) fun initForVulkan(window: GlfwWindow, installCallbacks: Boolean = true, vrTexSize: Vec2i? = null): ImplGlfw = ImplGlfw(window, installCallbacks, vrTexSize, GlfwClientApi.Vulkan) } }
mit
cb2f8f6315249f7c93dca6cc3ada0c95
43.105263
189
0.623836
4.334138
false
false
false
false
KDE/kdeconnect-android
src/org/kde/kdeconnect/Plugins/RunCommandPlugin/RunCommandControlsProviderService.kt
1
8969
/* * SPDX-FileCopyrightText: 2021 Maxim Leshchenko <[email protected]> * * SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL */ package org.kde.kdeconnect.Plugins.RunCommandPlugin import android.app.PendingIntent import android.content.Intent import android.content.SharedPreferences import android.graphics.drawable.Icon import android.service.controls.Control import android.service.controls.ControlsProviderService import android.service.controls.actions.CommandAction import android.service.controls.actions.ControlAction import android.service.controls.templates.StatelessTemplate import android.util.Log import androidx.annotation.RequiresApi import androidx.preference.PreferenceManager import io.reactivex.Flowable import io.reactivex.processors.ReplayProcessor import org.json.JSONArray import org.json.JSONException import org.kde.kdeconnect.BackgroundService import org.kde.kdeconnect.Device import org.kde.kdeconnect.UserInterface.MainActivity import org.kde.kdeconnect_tp.R import org.reactivestreams.FlowAdapters import java.util.* import java.util.concurrent.Flow import java.util.function.Consumer private class CommandEntryWithDevice(name: String, cmd: String, key: String, val device: Device) : CommandEntry(name, cmd, key) @RequiresApi(30) class RunCommandControlsProviderService : ControlsProviderService() { private lateinit var updatePublisher: ReplayProcessor<Control> private lateinit var sharedPreferences: SharedPreferences override fun createPublisherForAllAvailable(): Flow.Publisher<Control> { return FlowAdapters.toFlowPublisher(Flowable.fromIterable(getAllCommandsList().map { commandEntry -> Control.StatelessBuilder(commandEntry.device.deviceId + "-" + commandEntry.key, getIntent(commandEntry.device)) .setTitle(commandEntry.name) .setSubtitle(commandEntry.command) .setStructure(commandEntry.device.name) .setCustomIcon(Icon.createWithResource(this, R.drawable.run_command_plugin_icon_24dp)) .build() })) } override fun createPublisherFor(controlIds: MutableList<String>): Flow.Publisher<Control> { updatePublisher = ReplayProcessor.create() for (controlId in controlIds) { val commandEntry = getCommandByControlId(controlId) if (commandEntry != null && commandEntry.device.isReachable) { updatePublisher.onNext(Control.StatefulBuilder(controlId, getIntent(commandEntry.device)) .setTitle(commandEntry.name) .setSubtitle(commandEntry.command) .setStructure(commandEntry.device.name) .setStatus(Control.STATUS_OK) .setStatusText(getString(R.string.tap_to_execute)) .setControlTemplate(StatelessTemplate(commandEntry.key)) .setCustomIcon(Icon.createWithResource(this, R.drawable.run_command_plugin_icon_24dp)) .build()) } else if (commandEntry != null && commandEntry.device.isPaired && !commandEntry.device.isReachable) { updatePublisher.onNext(Control.StatefulBuilder(controlId, getIntent(commandEntry.device)) .setTitle(commandEntry.name) .setSubtitle(commandEntry.command) .setStructure(commandEntry.device.name) .setStatus(Control.STATUS_DISABLED) .setControlTemplate(StatelessTemplate(commandEntry.key)) .setCustomIcon(Icon.createWithResource(this, R.drawable.run_command_plugin_icon_24dp)) .build()) } else { updatePublisher.onNext(Control.StatefulBuilder(controlId, getIntent(commandEntry?.device)) .setStatus(Control.STATUS_NOT_FOUND) .build()) } } return FlowAdapters.toFlowPublisher(updatePublisher) } override fun performControlAction(controlId: String, action: ControlAction, consumer: Consumer<Int>) { if (!this::updatePublisher.isInitialized) { updatePublisher = ReplayProcessor.create() } if (action is CommandAction) { val commandEntry = getCommandByControlId(controlId) if (commandEntry != null) { val plugin = BackgroundService.getInstance().getDevice(controlId.split("-")[0]).getPlugin(RunCommandPlugin::class.java) if (plugin != null) { BackgroundService.RunCommand(this) { plugin.runCommand(commandEntry.key) } consumer.accept(ControlAction.RESPONSE_OK) } else { consumer.accept(ControlAction.RESPONSE_FAIL) } updatePublisher.onNext(Control.StatefulBuilder(controlId, getIntent(commandEntry.device)) .setTitle(commandEntry.name) .setSubtitle(commandEntry.command) .setStructure(commandEntry.device.name) .setStatus(Control.STATUS_OK) .setStatusText(getString(R.string.tap_to_execute)) .setControlTemplate(StatelessTemplate(commandEntry.key)) .setCustomIcon(Icon.createWithResource(this, R.drawable.run_command_plugin_icon_24dp)) .build()) } } } private fun getSavedCommandsList(device: Device): List<CommandEntryWithDevice> { if (!this::sharedPreferences.isInitialized) { sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this) } val commandList = mutableListOf<CommandEntryWithDevice>() return try { val jsonArray = JSONArray(sharedPreferences.getString(RunCommandPlugin.KEY_COMMANDS_PREFERENCE + device.deviceId, "[]")) for (index in 0 until jsonArray.length()) { val jsonObject = jsonArray.getJSONObject(index) commandList.add(CommandEntryWithDevice(jsonObject.getString("name"), jsonObject.getString("command"), jsonObject.getString("key"), device)) } commandList } catch (error: JSONException) { Log.e("RunCommand", "Error parsing JSON", error) listOf() } } private fun getAllCommandsList(): List<CommandEntryWithDevice> { val commandList = mutableListOf<CommandEntryWithDevice>() val service = BackgroundService.getInstance() ?: return commandList for (device in service.devices.values) { if (!device.isReachable) { commandList.addAll(getSavedCommandsList(device)) continue } else if (!device.isPaired) { continue } val plugin = device.getPlugin(RunCommandPlugin::class.java) if (plugin != null) { for (jsonObject in plugin.commandList) { try { commandList.add(CommandEntryWithDevice(jsonObject.getString("name"), jsonObject.getString("command"), jsonObject.getString("key"), device)) } catch (error: JSONException) { Log.e("RunCommand", "Error parsing JSON", error) } } } } return commandList } private fun getCommandByControlId(controlId: String): CommandEntryWithDevice? { val controlIdParts = controlId.split("-") val service = BackgroundService.getInstance(); if (service == null) return null val device = service.getDevice(controlIdParts[0]) if (device == null || !device.isPaired) return null val commandList = if (device.isReachable) { device.getPlugin(RunCommandPlugin::class.java)?.commandList?.map { jsonObject -> CommandEntryWithDevice(jsonObject.getString("name"), jsonObject.getString("command"), jsonObject.getString("key"), device) } } else { getSavedCommandsList(device) } return commandList?.find { command -> try { command.key == controlIdParts[1] } catch (error: JSONException) { Log.e("RunCommand", "Error parsing JSON", error) false } } } private fun getIntent(device: Device?): PendingIntent { val intent = Intent(Intent.ACTION_MAIN).setClass(this, MainActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) intent.putExtra(MainActivity.EXTRA_DEVICE_ID, device?.deviceId) return PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE) } }
gpl-2.0
ce87ced0eb9f352927101e584addd3fb
43.405941
163
0.635745
5.238902
false
false
false
false
meik99/CoffeeList
app/src/main/java/rynkbit/tk/coffeelist/ui/admin/invoice/ManageInvoicesFragment.kt
1
1974
package rynkbit.tk.coffeelist.ui.admin.invoice import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.observe import androidx.recyclerview.widget.LinearLayoutManager import kotlinx.android.synthetic.main.manage_invoices_fragment.* import rynkbit.tk.coffeelist.R import rynkbit.tk.coffeelist.contract.entity.Invoice import rynkbit.tk.coffeelist.db.facade.InvoiceFacade class ManageInvoicesFragment : Fragment() { private lateinit var viewModel: ManageInvoicesViewModel private lateinit var invoiceAdapter: ManageInvoicesAdapter override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { return inflater.inflate(R.layout.manage_invoices_fragment, container, false) } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) viewModel = ViewModelProvider(this).get(ManageInvoicesViewModel::class.java) invoiceAdapter = ManageInvoicesAdapter() invoiceAdapter.onInvoiceStateChange = updateInvoice() listInvoices.adapter = invoiceAdapter listInvoices.layoutManager = LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false) updateInvoices() } private fun updateInvoice(): ((Invoice) -> Unit) = {invoice -> InvoiceFacade() .changeState(invoice) .observe(this) { } } private fun updateInvoices() { val liveData = InvoiceFacade() .findAll() liveData .observe(this, Observer { liveData.removeObservers(this) invoiceAdapter.updateInvoices(it) }) } }
mit
4fa582b0e677e6d48fa98e3160c33bce
33.631579
84
0.699595
5.378747
false
false
false
false
AshishKayastha/Movie-Guide
app/src/main/kotlin/com/ashish/movieguide/ui/common/adapter/RecyclerViewAdapter.kt
1
3352
package com.ashish.movieguide.ui.common.adapter import android.support.v7.widget.RecyclerView import android.util.SparseArray import android.view.ViewGroup import com.ashish.movieguide.ui.base.recyclerview.BaseContentHolder import com.ashish.movieguide.ui.common.adapter.ViewType.Companion.CONTENT_VIEW import com.ashish.movieguide.ui.common.adapter.ViewType.Companion.LOADING_VIEW import com.bumptech.glide.Glide import java.util.ArrayList /** * Created by Ashish on Dec 30. */ class RecyclerViewAdapter<in I : ViewType>( layoutId: Int, adapterType: Int, onItemClickListener: OnItemClickListener? ) : RecyclerView.Adapter<RecyclerView.ViewHolder>(), RemoveListener { private val loadingItem = object : ViewType { override fun getViewType() = LOADING_VIEW } private var itemList: ArrayList<ViewType> = ArrayList() private var delegateAdapters = SparseArray<ViewTypeDelegateAdapter>() private val contentAdapter = AdapterFactory.getAdapter(layoutId, adapterType, onItemClickListener) init { delegateAdapters.put(LOADING_VIEW, LoadingDelegateAdapter()) delegateAdapters.put(CONTENT_VIEW, contentAdapter) } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = delegateAdapters.get(viewType).onCreateViewHolder(parent) override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) { delegateAdapters.get(getItemViewType(position)).onBindViewHolder(holder, itemList[position]) } override fun getItemViewType(position: Int) = itemList[position].getViewType() override fun onViewRecycled(holder: RecyclerView.ViewHolder?) { super.onViewRecycled(holder) if (holder is BaseContentHolder<*>) Glide.clear(holder.posterImage) } override fun getItemCount() = itemList.size @Suppress("UNCHECKED_CAST") fun <I> getItem(position: Int) = itemList[position] as I fun showItemList(newItemList: List<I>?) { newItemList?.let { val oldPosition = itemCount itemList = ArrayList(it) notifyItemRangeInserted(oldPosition, it.size) } } fun addLoadingItem() { itemList.add(loadingItem) notifyItemInserted(itemCount - 1) } fun addNewItemList(newItemList: List<I>?) { val loadingItemPosition = removeLoadingItem() newItemList?.let { itemList.addAll(it) notifyItemRangeChanged(loadingItemPosition, itemCount) } } fun removeLoadingItem(): Int { val loadingItemPosition = itemCount - 1 itemList.removeAt(loadingItemPosition) notifyItemRemoved(loadingItemPosition) notifyItemRangeChanged(loadingItemPosition, itemCount) return loadingItemPosition } fun replaceItem(position: Int, item: I) { itemList[position] = item notifyItemChanged(position) } fun removeItem(position: Int) { itemList.removeAt(position) notifyItemRemoved(position) notifyItemRangeChanged(position, itemCount) } fun clearAll() { val oldSize = itemCount if (oldSize > 0) { itemList.clear() notifyItemRangeRemoved(0, oldSize) } } override fun removeListener() = (contentAdapter as RemoveListener).removeListener() }
apache-2.0
dcce76b4e3d1594901b9aa3d54fa29d6
31.872549
102
0.699582
5.048193
false
false
false
false
dahlstrom-g/intellij-community
platform/lang-impl/src/com/intellij/util/indexing/diagnostic/ProjectIndexingHistoryFusReporterListener.kt
2
8173
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.util.indexing.diagnostic import com.intellij.internal.statistic.eventLog.EventLogGroup import com.intellij.internal.statistic.eventLog.events.EventFields import com.intellij.internal.statistic.eventLog.events.ObjectEventData import com.intellij.internal.statistic.eventLog.events.ObjectListEventField import com.intellij.internal.statistic.service.fus.collectors.CounterUsagesCollector import com.intellij.internal.statistic.utils.StatisticsUtil import com.intellij.openapi.fileTypes.FileType import com.intellij.openapi.fileTypes.FileTypeManager import com.intellij.openapi.project.Project import com.intellij.util.indexing.diagnostic.dto.toMillis import java.util.* import java.util.concurrent.TimeUnit import kotlin.collections.HashMap import kotlin.math.roundToLong class ProjectIndexingHistoryFusReporterListener : ProjectIndexingHistoryListener { override fun onStartedIndexing(projectIndexingHistory: ProjectIndexingHistory) { ProjectIndexingHistoryFusReporter.reportIndexingStarted( projectIndexingHistory.project, projectIndexingHistory.indexingSessionId ) } override fun onFinishedIndexing(projectIndexingHistory: ProjectIndexingHistory) { val scanningTime = projectIndexingHistory.times.scanFilesDuration.toMillis() val numberOfFileProviders = projectIndexingHistory.scanningStatistics.size val numberOfScannedFiles = projectIndexingHistory.scanningStatistics.sumOf { it.numberOfScannedFiles } val numberOfFilesIndexedByExtensionsDuringScan = projectIndexingHistory.scanningStatistics.sumOf { it.numberOfFilesFullyIndexedByInfrastructureExtensions } val numberOfFilesIndexedByExtensionsWithLoadingContent = projectIndexingHistory.providerStatistics.sumOf { it.totalNumberOfFilesFullyIndexedByExtensions } val numberOfFilesIndexedWithLoadingContent = projectIndexingHistory.providerStatistics.sumOf { it.totalNumberOfIndexedFiles } val totalContentLoadingTime = projectIndexingHistory.totalStatsPerFileType.values.sumOf { it.totalContentLoadingTimeInAllThreads } val totalContentData = projectIndexingHistory.totalStatsPerFileType.values.sumOf { it.totalBytes } val averageContentLoadingSpeed = calculateReadSpeed(totalContentData, totalContentLoadingTime) val contentLoadingSpeedByFileType = HashMap<FileType, Long>() projectIndexingHistory.totalStatsPerFileType.forEach { (fileType, stats) -> if (stats.totalContentLoadingTimeInAllThreads != 0L && stats.totalBytes != 0L) { contentLoadingSpeedByFileType[FileTypeManager.getInstance().getStdFileType(fileType)] = calculateReadSpeed(stats.totalBytes, stats.totalContentLoadingTimeInAllThreads) } } ProjectIndexingHistoryFusReporter.reportIndexingFinished( projectIndexingHistory.project, projectIndexingHistory.indexingSessionId, projectIndexingHistory.times.scanningType, projectIndexingHistory.times.totalUpdatingTime.toMillis(), projectIndexingHistory.times.indexingDuration.toMillis(), scanningTime, numberOfFileProviders, numberOfScannedFiles, numberOfFilesIndexedByExtensionsDuringScan, numberOfFilesIndexedByExtensionsWithLoadingContent, numberOfFilesIndexedWithLoadingContent, averageContentLoadingSpeed, contentLoadingSpeedByFileType ) } /** * @return speed as bytes per second * */ private fun calculateReadSpeed(bytes: BytesNumber, loadingTime: TimeNano): Long { if (bytes == 0L || loadingTime == 0L) return 0L val nanoSecondInOneSecond = TimeUnit.SECONDS.toNanos(1) return if (bytes * nanoSecondInOneSecond > 0) // avoid hitting overflow; possible if loaded more then 9 223 372 037 bytes // as `loadingTime` in nanoseconds tend to be much bigger value then `bytes` prefer to divide as second step (bytes * nanoSecondInOneSecond) / loadingTime else // do not use by default to avoid unnecessary conversions ((bytes.toDouble() / loadingTime) * nanoSecondInOneSecond).roundToLong() } } object ProjectIndexingHistoryFusReporter : CounterUsagesCollector() { private val GROUP = EventLogGroup("indexing.statistics", 6) override fun getGroup() = GROUP private val indexingSessionId = EventFields.Long("indexing_session_id") private val isFullRescanning = EventFields.Boolean("is_full") private val scanningType = EventFields.Enum<ScanningType>("type") { type -> type.name.lowercase(Locale.ENGLISH) } private val totalTime = EventFields.Long("total_time") private val indexingTime = EventFields.Long("indexing_time") private val scanningTime = EventFields.Long("scanning_time") private val numberOfFileProviders = EventFields.Int("number_of_file_providers") private val numberOfScannedFiles = EventFields.Int("number_of_scanned_files") private val numberOfFilesIndexedByExtensionsDuringScan = EventFields.Int("number_of_files_indexed_by_extensions_during_scan") private val numberOfFilesIndexedByExtensionsWithLoadingContent = EventFields.Int("number_of_files_indexed_by_extensions_with_loading_content") private val numberOfFilesIndexedWithLoadingContent = EventFields.Int("number_of_files_indexed_with_loading_content") private val averageContentLoadingSpeed = EventFields.Long("average_content_loading_speed_bps") private val contentLoadingSpeedForFileType = EventFields.Long("average_content_loading_speed_for_file_type_bps") private val contentLoadingSpeedByFileType = ObjectListEventField("average_content_loading_speeds_by_file_type", EventFields.FileType, contentLoadingSpeedForFileType) private val indexingStarted = GROUP.registerVarargEvent( "started", indexingSessionId ) private val indexingFinished = GROUP.registerVarargEvent( "finished", indexingSessionId, isFullRescanning, scanningType, totalTime, indexingTime, scanningTime, numberOfFileProviders, numberOfScannedFiles, numberOfFilesIndexedByExtensionsDuringScan, numberOfFilesIndexedByExtensionsWithLoadingContent, numberOfFilesIndexedWithLoadingContent, averageContentLoadingSpeed, contentLoadingSpeedByFileType ) fun reportIndexingStarted(project: Project, indexingSessionId: Long) { indexingStarted.log( project, this.indexingSessionId.with(indexingSessionId) ) } fun reportIndexingFinished( project: Project, indexingSessionId: Long, scanningType: ScanningType, totalTime: Long, indexingTime: Long, scanningTime: Long, numberOfFileProviders: Int, numberOfScannedFiles: Int, numberOfFilesIndexedByExtensionsDuringScan: Int, numberOfFilesIndexedByExtensionsWithLoadingContent: Int, numberOfFilesIndexedWithLoadingContent: Int, averageContentLoadingSpeed: Long, contentLoadingSpeedByFileType: Map<FileType, Long> ) { indexingFinished.log( project, this.indexingSessionId.with(indexingSessionId), this.isFullRescanning.with(scanningType.isFull), this.scanningType.with(scanningType), this.totalTime.with(totalTime), this.indexingTime.with(indexingTime), this.scanningTime.with(scanningTime), this.numberOfFileProviders.with(numberOfFileProviders), this.numberOfScannedFiles.with(StatisticsUtil.roundToHighestDigit(numberOfScannedFiles)), this.numberOfFilesIndexedByExtensionsDuringScan.with(StatisticsUtil.roundToHighestDigit(numberOfFilesIndexedByExtensionsDuringScan)), this.numberOfFilesIndexedByExtensionsWithLoadingContent.with( StatisticsUtil.roundToHighestDigit(numberOfFilesIndexedByExtensionsWithLoadingContent)), this.numberOfFilesIndexedWithLoadingContent.with(StatisticsUtil.roundToHighestDigit(numberOfFilesIndexedWithLoadingContent)), this.averageContentLoadingSpeed.with(averageContentLoadingSpeed), this.contentLoadingSpeedByFileType.with(contentLoadingSpeedByFileType.map { entry -> ObjectEventData(EventFields.FileType.with(entry.key), contentLoadingSpeedForFileType.with(entry.value)) }) ) } }
apache-2.0
5de4f9dd6a67880a9bb58a1cc49545c9
45.708571
139
0.799217
5.755634
false
false
false
false