repo_name
stringlengths
7
79
path
stringlengths
8
206
copies
stringclasses
36 values
size
stringlengths
2
6
content
stringlengths
55
523k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
7.18
99.5
line_max
int64
16
979
alpha_frac
float64
0.3
0.87
ratio
float64
2.01
8.07
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
ohmae/DmsExplorer
mobile/src/main/java/net/mm2d/dmsexplorer/domain/tabs/OpenUriUtils.kt
1
3086
/* * Copyright (c) 2018 大前良介 (OHMAE Ryosuke) * * This software is released under the MIT License. * http://opensource.org/licenses/MIT */ package net.mm2d.dmsexplorer.domain.tabs import android.content.Context import android.content.Intent import android.content.pm.PackageManager import android.net.Uri import android.os.Build /** * @author [大前良介 (OHMAE Ryosuke)](mailto:[email protected]) */ object OpenUriUtils { private var defaultBrowserPackage: String? = null private var browserPackages: Set<String>? = null internal fun getBrowserPackages( context: Context, update: Boolean = false ): Set<String> { if (!update) { browserPackages?.let { return it } } return getBrowserPackagesInner(context).also { browserPackages = it } } private fun getBrowserPackagesInner(context: Context): Set<String> { val pm = context.packageManager val flags = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) PackageManager.MATCH_ALL else 0 val activities = pm.queryIntentActivities(makeBrowserTestIntent(), flags) if (activities.isEmpty()) { return emptySet() } return activities.map { it.activityInfo.packageName }.toSet() } internal fun getDefaultBrowserPackage( context: Context, update: Boolean = false ): String? { if (!update) { defaultBrowserPackage?.let { return it } } return getDefaultBrowserPackageInner(context).also { defaultBrowserPackage = it } } private fun getDefaultBrowserPackageInner(context: Context): String? { val pm = context.packageManager val browserInfo = pm.resolveActivity(makeBrowserTestIntent(), 0) if (browserInfo?.activityInfo == null) { return null } val packageName = browserInfo.activityInfo.packageName return if (getBrowserPackages(context).contains(packageName)) { packageName } else null } private fun makeBrowseIntent(uri: String): Intent { val intent = Intent(Intent.ACTION_VIEW, Uri.parse(uri)) intent.addCategory(Intent.CATEGORY_BROWSABLE) return intent } private fun makeBrowserTestIntent(): Intent = makeBrowseIntent("http://www.example.com/") fun hasDefaultAppOtherThanBrowser( context: Context, uri: String ): Boolean { val pm = context.packageManager val intent = makeBrowseIntent(uri) val defaultApp = pm.resolveActivity(intent, 0) if (defaultApp?.activityInfo == null) { return false } val packageName = defaultApp.activityInfo.packageName if (getBrowserPackages(context).contains(packageName)) { return false } return pm.queryIntentActivities(intent, 0) .find { it.activityInfo != null && packageName == it.activityInfo.packageName } != null } }
mit
763fef81e9c745de46337ab6bbc342e1
30.010101
99
0.629642
4.708589
false
false
false
false
anlun/haskell-idea-plugin
plugin/src/org/jetbrains/haskell/debugger/HaskellProgramRunner.kt
1
5792
package org.jetbrains.haskell.debugger import com.intellij.debugger.impl.GenericDebuggerRunnerSettings import com.intellij.execution.runners.GenericProgramRunner import com.intellij.openapi.project.Project import com.intellij.execution.configurations.RunProfileState import com.intellij.execution.ui.RunContentDescriptor import com.intellij.execution.runners.ExecutionEnvironment import com.intellij.execution.configurations.RunProfile import org.jetbrains.haskell.run.haskell.HaskellCommandLineState import com.intellij.xdebugger.XDebuggerManager import com.intellij.xdebugger.XDebugProcessStarter import com.intellij.xdebugger.XDebugSession import com.intellij.xdebugger.XDebugProcess import com.intellij.execution.executors.DefaultDebugExecutor import org.jetbrains.haskell.run.haskell.CabalRunConfiguration import com.intellij.notification.Notification import com.intellij.notification.Notifications import com.intellij.notification.NotificationType import com.intellij.execution.ExecutionManager import org.jetbrains.haskell.debugger.config.HaskellDebugSettings import java.io.File import com.intellij.notification.NotificationListener import javax.swing.event.HyperlinkEvent import com.intellij.openapi.options.ShowSettingsUtil import org.jetbrains.haskell.debugger.prochandlers.HaskellDebugProcessHandler import com.intellij.xdebugger.impl.XDebugSessionImpl /** * Class for starting debug session. * * @author Habibullin Marat */ public class HaskellProgramRunner() : GenericProgramRunner<GenericDebuggerRunnerSettings>() { companion object { public val HS_PROGRAM_RUNNER_ID: String = "HaskellProgramRunner" private val ERROR_TITLE = "Debug execution error" private fun GENERAL_ERROR_MSG(projName: String) = "Internal error occured while executing debug process for ${projName}" private val GENERAL_DEBUGGING_TITLE = "Can't start debugger" private val MULTI_DEBUGGING_MSG = "Haskell plugin supports only single debugging mode and one debugging " + "process is already in progress" private val WRONG_REMOTE_DEBUGGER_PATH_MSG = "Correct path to remote debugger was not set. See <a href=\"#\">Settings | Haskell Debugger</a>" } /** * Getter for this runner ID */ override fun getRunnerId(): String = HS_PROGRAM_RUNNER_ID /** * Checks if this runner can be used with specified executor and RunProfile */ override fun canRun(executorId: String, profile: RunProfile): Boolean = (DefaultDebugExecutor.EXECUTOR_ID.equals(executorId) || DebugConsoleExecutor.EXECUTOR_ID.equals(executorId)) && profile is CabalRunConfiguration /** * This method is executed when debug session is started (when you press "Debug" button) */ override fun doExecute(project: Project, state: RunProfileState, contentToReuse: RunContentDescriptor?, environment: ExecutionEnvironment): RunContentDescriptor? { val hyperlinkHandler = object : NotificationListener.Adapter() { override fun hyperlinkActivated(notification: Notification, e: HyperlinkEvent) { notification.expire() if (!project.isDisposed()) { ShowSettingsUtil.getInstance()?.showSettingsDialog(project, "Haskell Debugger") } } } val debuggerManager = XDebuggerManager.getInstance(project) if (debuggerManager == null) { Notifications.Bus.notify(Notification("", ERROR_TITLE, GENERAL_ERROR_MSG(project.getName()), NotificationType.ERROR)) return null } try { if (debuggerManager.getDebugSessions().size() != 0) { Notifications.Bus.notify(Notification("", GENERAL_DEBUGGING_TITLE, MULTI_DEBUGGING_MSG, NotificationType.WARNING)) focusDebugToolWindow(debuggerManager, project) return null } val settingsState = HaskellDebugSettings.getInstance().getState() if (settingsState.debuggerType == HaskellDebugSettings.Companion.DebuggerType.REMOTE) { if (settingsState.remoteDebuggerPath == null || !File(settingsState.remoteDebuggerPath!!).exists()) { Notifications.Bus.notify(Notification("", GENERAL_DEBUGGING_TITLE, WRONG_REMOTE_DEBUGGER_PATH_MSG, NotificationType.WARNING, hyperlinkHandler)) return null } } val executionResult = (state as HaskellCommandLineState).executeDebug(project, environment.getExecutor(), this) val processHandler = executionResult.getProcessHandler()!! as HaskellDebugProcessHandler val session = debuggerManager.startSession(environment, object : XDebugProcessStarter() { override fun start(session: XDebugSession): XDebugProcess = HaskellDebugProcess(session, executionResult.getExecutionConsole()!!, processHandler, DefaultDebugExecutor.EXECUTOR_ID.equals(environment.getExecutor().getId())) }) return session.getRunContentDescriptor() } catch (e: Exception) { val msg = GENERAL_ERROR_MSG(project.getName()) Notifications.Bus.notify(Notification("", "Debug execution error", msg, NotificationType.ERROR)) } return null } private fun focusDebugToolWindow(debuggerManager: XDebuggerManager, project: Project) { val theOnlySession = debuggerManager.getDebugSessions().get(0) val descriptor = theOnlySession.getRunContentDescriptor() ExecutionManager.getInstance(project)!!.getContentManager().getToolWindowByDescriptor(descriptor)!!.show {} } }
apache-2.0
11381503cb32d7779f3e55494f0e5dbe
51.189189
163
0.711671
5.343173
false
false
false
false
Etik-Tak/backend
src/main/kotlin/dk/etiktak/backend/controller/rest/CompanyRestController.kt
1
5716
// Copyright (c) 2017, Daniel Andersen ([email protected]) // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // 3. The name of the author may not be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND // ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. /** * Rest controller responsible for handling company lifecycle. */ package dk.etiktak.backend.controller.rest import dk.etiktak.backend.controller.rest.json.add import dk.etiktak.backend.model.company.Company import dk.etiktak.backend.model.contribution.TrustVote import dk.etiktak.backend.model.user.Client import dk.etiktak.backend.security.CurrentlyLoggedClient import dk.etiktak.backend.service.client.ClientService import dk.etiktak.backend.service.company.CompanyService import org.springframework.beans.factory.annotation.Autowired import org.springframework.util.StringUtils import org.springframework.web.bind.annotation.* import java.util.* @RestController @RequestMapping("/service/company") class CompanyRestController @Autowired constructor( private val companyService: CompanyService, private val clientService: ClientService) : BaseRestController() { @RequestMapping(value = "/", method = arrayOf(RequestMethod.GET)) fun getCompany( @CurrentlyLoggedClient loggedClient: Client?, @RequestParam(required = false) uuid: String?, @RequestParam(required = false) name: String?): HashMap<String, Any> { // Check parameters if (StringUtils.isEmpty(uuid) && StringUtils.isEmpty(name)) { return illegalInvocationMap("Either 'companyUuid' or 'companyName' must be provided") } var company: Company? = null // Find company by UUID uuid?.let { company = companyService.getCompanyByUuid(uuid) ?: return notFoundMap("Company") } // Find company by name name?.let { company = companyService.getCompanyByName(name) ?: return notFoundMap("Company") } company?.let { return okMap().add(company!!, loggedClient, companyService = companyService) } ?: return notFoundMap("Company") } @RequestMapping(value = "/search/", method = arrayOf(RequestMethod.GET)) fun findCompanies( @RequestParam searchString: String, @RequestParam(required = false) pageIndex: Int?, @RequestParam(required = false) pageSize: Int?): HashMap<String, Any> { val companySearchList = companyService.getCompanySearchList(searchString, pageIndex ?: 0, pageSize ?: 10) return okMap().add(companySearchList, companyService) } @RequestMapping(value = "/create/", method = arrayOf(RequestMethod.POST)) fun createCompany( @CurrentlyLoggedClient loggedClient: Client, @RequestParam name: String): HashMap<String, Any> { val client = clientService.getByUuid(loggedClient.uuid) ?: return notFoundMap("Client") val company = companyService.createCompany(client, name) return okMap().add(company, client, companyService) } @RequestMapping(value = "/edit/", method = arrayOf(RequestMethod.POST)) fun editCompany( @CurrentlyLoggedClient loggedClient: Client, @RequestParam companyUuid: String, @RequestParam(required = false) name: String?): HashMap<String, Any> { var client = clientService.getByUuid(loggedClient.uuid) ?: return notFoundMap("Client") var company = companyService.getCompanyByUuid(companyUuid) ?: return notFoundMap("Company") name?.let { companyService.editCompanyName(client, company, name, modifyValues = {modifiedClient, modifiedCompany -> client = modifiedClient; company = modifiedCompany}) } return okMap().add(company, client, companyService) } @RequestMapping(value = "/trust/name/", method = arrayOf(RequestMethod.POST)) fun trustVoteCompanyName( @CurrentlyLoggedClient loggedClient: Client, @RequestParam companyUuid: String, @RequestParam vote: TrustVote.TrustVoteType): HashMap<String, Any> { val client = clientService.getByUuid(loggedClient.uuid) ?: return notFoundMap("Client") val company = companyService.getCompanyByUuid(companyUuid) ?: return notFoundMap("Company") companyService.trustVoteCompanyName(client, company, vote) return okMap() } }
bsd-3-clause
b6fc6881da22026f8f32afb0dc18afaf
42.969231
169
0.714311
4.779264
false
false
false
false
saki4510t/libcommon
common/src/main/java/com/serenegiant/widget/MultiDispatchTouchRelativeLayout.kt
1
3651
package com.serenegiant.widget /* * libcommon * utility/helper classes for myself * * Copyright (c) 2014-2022 saki [email protected] * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import android.content.Context import android.graphics.Rect import android.util.AttributeSet import android.util.Log import android.util.SparseBooleanArray import android.view.MotionEvent import android.view.ViewGroup import android.widget.RelativeLayout /** * 通常はViewヒエラルキーの上から順にenableでfocusableなViewの * dispatchTouchEventを呼び出して最初にtrueを返した子Viewのみが * イベント処理を行なえるのに対して、重なり合った複数のViewの下側も * 含めてタッチした位置に存在するViewに対してdispatchTouchEventの * 呼び出し処理を行うViewGroup * (同じタッチイベントで複数の子Viewへタッチイベント生成&操作できる) */ open class MultiDispatchTouchRelativeLayout @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) : RelativeLayout(context, attrs, defStyleAttr) { private val mDispatched = SparseBooleanArray() private val mWorkRect = Rect() override fun dispatchTouchEvent(ev: MotionEvent): Boolean { return if (onFilterTouchEventForSecurity(ev)) { var result = false val children = childCount for (i in 0 until children) { val v = getChildAt(i) val id = v.hashCode() v.getHitRect(mWorkRect) if (v.isEnabled && isFocusable && mWorkRect.contains(ev.x.toInt(), ev.y.toInt()) && mDispatched[id, true]) { // 子Viewが有効&子ViewのhitRect内をタッチ&子Viewがイベントをハンドリングしているとき // 子Viewのローカル座標系への変換してから子ViewのdispatchTouchEventを呼び出す val offsetX: Float = scrollX - v.left.toFloat() val offsetY: Float = scrollY - v.top.toFloat() ev.offsetLocation(offsetX, offsetY) val dispatched = v.dispatchTouchEvent(ev) mDispatched.put(id, dispatched) result = result or dispatched // オフセットを元に戻す ev.offsetLocation(-offsetX, -offsetY) } } val action = ev.actionMasked if ((!result || (action == MotionEvent.ACTION_UP) || (action == MotionEvent.ACTION_CANCEL)) && ev.pointerCount == 1) { mDispatched.clear() } // if (!result) { // // 子Viewがどれもイベントをハンドリングしなかったときは上位に任せる // // もしかすると子ViewのdispatchTouchEventが2回呼び出されるかも // result = super.dispatchTouchEvent(ev) // } if (DEBUG) Log.v(TAG, "dispatchTouchEvent:result=$result") result } else { mDispatched.clear() super.dispatchTouchEvent(ev) } } companion object { private const val DEBUG = false // set false on production private val TAG = MultiDispatchTouchRelativeLayout::class.java.simpleName } init { // 子クラスへフォーカスを与えないようにする descendantFocusability = ViewGroup.FOCUS_BLOCK_DESCENDANTS isFocusable = true } }
apache-2.0
2871232b5b10bdb9edc374d3fffa3f92
29.764706
83
0.731591
3.207566
false
false
false
false
rhdunn/xquery-intellij-plugin
src/plugin-marklogic/main/uk/co/reecedunn/intellij/plugin/marklogic/rewriter/lang/ModelTypeRegexLanguageInjection.kt
1
2276
/* * Copyright (C) 2020-2021 Reece H. Dunn * * 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 uk.co.reecedunn.intellij.plugin.marklogic.rewriter.lang import com.intellij.lang.injection.MultiHostInjector import com.intellij.lang.injection.MultiHostRegistrar import com.intellij.psi.PsiElement import com.intellij.psi.PsiLanguageInjectionHost import com.intellij.psi.xml.XmlAttribute import com.intellij.psi.xml.XmlAttributeValue import com.intellij.psi.xml.XmlTag import org.intellij.lang.regexp.RegExpLanguage import uk.co.reecedunn.intellij.plugin.core.psi.contextOfType import uk.co.reecedunn.intellij.plugin.marklogic.rewriter.endpoints.Rewriter class ModelTypeRegexLanguageInjection : MultiHostInjector { override fun elementsToInjectIn(): MutableList<out Class<out PsiElement>> = ELEMENTS_TO_INJECT_IN override fun getLanguagesToInject(registrar: MultiHostRegistrar, context: PsiElement) { val attribute = context.contextOfType<XmlAttributeValue>(false)?.parent as? XmlAttribute ?: return if (attribute.localName != "matches" || !isModelTypeRegex(attribute.parent)) return val host = context as PsiLanguageInjectionHost val range = host.textRange registrar.startInjecting(RegExpLanguage.INSTANCE) registrar.addPlace(null, null, host, range.shiftLeft(range.startOffset)) registrar.doneInjecting() } private fun isModelTypeRegex(tag: XmlTag): Boolean { return tag.namespace == Rewriter.NAMESPACE && MODEL_TYPE_LOCAL_NAMES.contains(tag.localName) } companion object { private val MODEL_TYPE_LOCAL_NAMES = setOf("match-header", "match-path", "match-string") private val ELEMENTS_TO_INJECT_IN = mutableListOf(XmlAttributeValue::class.java) } }
apache-2.0
a58cd07007dd67c371654f28ad89158b
41.943396
106
0.761863
4.286252
false
false
false
false
rhdunn/xquery-intellij-plugin
src/lang-xquery/main/uk/co/reecedunn/intellij/plugin/xquery/psi/impl/xquery/XQueryFunctionDeclPsiImpl.kt
1
8053
/* * Copyright (C) 2016-2021 Reece H. Dunn * * 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 uk.co.reecedunn.intellij.plugin.xquery.psi.impl.xquery import com.intellij.lang.ASTNode import com.intellij.navigation.ItemPresentation import com.intellij.navigation.NavigationItem import com.intellij.openapi.util.Key import com.intellij.psi.PsiElement import com.intellij.psi.tree.TokenSet import com.intellij.psi.util.elementType import uk.co.reecedunn.intellij.plugin.core.navigation.ItemPresentationEx import uk.co.reecedunn.intellij.plugin.core.sequences.children import uk.co.reecedunn.intellij.plugin.core.sequences.reverse import uk.co.reecedunn.intellij.plugin.xdm.functions.op.qname_presentation import uk.co.reecedunn.intellij.plugin.xdm.types.XdmSequenceType import uk.co.reecedunn.intellij.plugin.xdm.types.XsQNameValue import uk.co.reecedunn.intellij.plugin.xpath.ast.xpath.XPathParam import uk.co.reecedunn.intellij.plugin.xpath.lexer.XPathTokenType import uk.co.reecedunn.intellij.plugin.xpath.parser.XPathElementType import uk.co.reecedunn.intellij.plugin.xpath.psi.blockOpen import uk.co.reecedunn.intellij.plugin.xpath.psi.isEmptyEnclosedExpr import uk.co.reecedunn.intellij.plugin.xpath.resources.XPathIcons import uk.co.reecedunn.intellij.plugin.xpm.lang.validation.XpmSyntaxValidationElement import uk.co.reecedunn.intellij.plugin.xpm.optree.annotation.XpmVariadic import uk.co.reecedunn.intellij.plugin.xpm.optree.expression.XpmExpression import uk.co.reecedunn.intellij.plugin.xpm.optree.expression.impl.XpmEmptyExpression import uk.co.reecedunn.intellij.plugin.xpm.optree.function.XpmFunctionDecorator import uk.co.reecedunn.intellij.plugin.xpm.optree.variable.XpmParameter import uk.co.reecedunn.intellij.plugin.xquery.ast.plugin.PluginCompatibilityAnnotation import uk.co.reecedunn.intellij.plugin.xquery.ast.xquery.XQueryFunctionDecl import java.util.* import javax.swing.Icon class XQueryFunctionDeclPsiImpl(node: ASTNode) : XQueryAnnotatedDeclPsiImpl(node), XQueryFunctionDecl, ItemPresentationEx, XpmSyntaxValidationElement { companion object { private val PARAMETERS = Key.create<List<XpmParameter>>("PARAMETERS") private val VARIADIC_TYPE = Key.create<XpmVariadic>("VARIADIC_TYPE") private val PRESENTABLE_TEXT = Key.create<Optional<String>>("PRESENTABLE_TEXT") private val STRUCTURE_PRESENTABLE_TEXT = Key.create<Optional<String>>("STRUCTURE_PRESENTABLE_TEXT") private val PARAM_LIST_PRESENTABLE_TEXT = Key.create<String>("PARAM_LIST_PRESENTABLE_TEXT") private val FUNCTION_REF_PRESENTABLE_TEXT = Key.create<String>("FUNCTION_REF_PRESENTABLE_TEXT") private val PARAM_OR_VARIADIC = TokenSet.create( XPathElementType.PARAM, XPathTokenType.ELLIPSIS ) } // region ASTDelegatePsiElement override fun subtreeChanged() { super.subtreeChanged() clearUserData(PARAMETERS) clearUserData(VARIADIC_TYPE) clearUserData(PRESENTABLE_TEXT) clearUserData(STRUCTURE_PRESENTABLE_TEXT) clearUserData(PARAM_LIST_PRESENTABLE_TEXT) clearUserData(FUNCTION_REF_PRESENTABLE_TEXT) } // endregion // region XdmFunctionDeclaration (Data Model) override val functionName: XsQNameValue? get() = children().filter { it is XsQNameValue && it !is PluginCompatibilityAnnotation }.firstOrNull() as? XsQNameValue? override val parameters: List<XpmParameter> get() = computeUserDataIfAbsent(PARAMETERS) { children().filterIsInstance<XPathParam>().toList() } override val returnType: XdmSequenceType? get() = children().filterIsInstance<XdmSequenceType>().firstOrNull() override val functionBody: XpmExpression? get() = when (blockOpen) { null -> null // external function declaration else -> children().filterIsInstance<XpmExpression>().firstOrNull() ?: XpmEmptyExpression } // endregion // region XdmFunctionDeclaration (Variadic Type and Arity) private val variadicParameter: PsiElement? get() = reverse(children()).firstOrNull { e -> PARAM_OR_VARIADIC.contains(e.elementType) } override val variadicType: XpmVariadic get() = computeUserDataIfAbsent(VARIADIC_TYPE) { val variadicParameter = variadicParameter when (variadicParameter.elementType) { XPathTokenType.ELLIPSIS -> XpmVariadic.Ellipsis else -> XpmVariadic.No } } override val declaredArity: Int get() = parameters.size private val defaultArgumentCount: Int get() = when (variadicType) { XpmVariadic.Ellipsis -> 1 else -> 0 } override val requiredArity: Int get() = declaredArity - defaultArgumentCount // endregion // region XdmFunctionDeclaration (Presentation) override val paramListPresentableText: String get() = computeUserDataIfAbsent(PARAM_LIST_PRESENTABLE_TEXT) { val params = parameters.mapNotNull { param -> (param as NavigationItem).presentation?.presentableText }.joinToString() if (variadicType === XpmVariadic.Ellipsis) "($params ...)" else "($params)" } override val functionRefPresentableText: String? get() = computeUserDataIfAbsent(FUNCTION_REF_PRESENTABLE_TEXT) { functionName?.let { "${qname_presentation(it)}#$declaredArity" } ?: "" } // endregion // region NavigationItem override fun getPresentation(): ItemPresentation = this // endregion // region ItemPresentation override fun getIcon(unused: Boolean): Icon = XpmFunctionDecorator.getIcon(this) ?: XPathIcons.Nodes.FunctionDecl override fun getLocationString(): String? = null // e.g. the documentation tool window title. override fun getPresentableText(): String? = computeUserDataIfAbsent(PRESENTABLE_TEXT) { val name = functionName name?.localName ?: return@computeUserDataIfAbsent Optional.empty() Optional.ofNullable(qname_presentation(name)) }.orElse(null) // endregion // region ItemPresentationEx private val structurePresentableText: String? get() = computeUserDataIfAbsent(STRUCTURE_PRESENTABLE_TEXT) { val name = functionName name?.localName ?: return@computeUserDataIfAbsent Optional.empty() val returnType = returnType if (returnType == null) Optional.of("${qname_presentation(name)}$paramListPresentableText") else Optional.of("${qname_presentation(name)}$paramListPresentableText as ${returnType.typeName}") }.orElse(null) override fun getPresentableText(type: ItemPresentationEx.Type): String? = when (type) { ItemPresentationEx.Type.StructureView -> structurePresentableText ItemPresentationEx.Type.NavBarPopup -> structurePresentableText else -> presentableText } // endregion // region SortableTreeElement override fun getAlphaSortKey(): String = functionRefPresentableText ?: "" // endregion // region XpmSyntaxValidationElement override val conformanceElement: PsiElement get() { val blockOpen = blockOpen return when (blockOpen?.isEmptyEnclosedExpr) { true -> blockOpen else -> variadicParameter ?: firstChild } } // endregion }
apache-2.0
4a0a3ed0c13befb550f9ec13bd4804bc
39.064677
117
0.712405
4.739847
false
false
false
false
rhdunn/xquery-intellij-plugin
src/lang-xslt/test/uk/co/reecedunn/intellij/plugin/xslt/tests/lang/highlighter/XPathColorSettingsPageTest.kt
1
6891
/* * Copyright (C) 2016-2020 Reece H. Dunn * * 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 uk.co.reecedunn.intellij.plugin.xslt.tests.lang.highlighter import com.intellij.openapi.editor.colors.TextAttributesKey import com.intellij.openapi.util.text.StringUtil import org.hamcrest.CoreMatchers.`is` import org.junit.jupiter.api.DisplayName import org.junit.jupiter.api.Test import uk.co.reecedunn.intellij.plugin.core.tests.assertion.assertThat import uk.co.reecedunn.intellij.plugin.xpath.lang.highlighter.XPathSyntaxHighlighterColors import uk.co.reecedunn.intellij.plugin.xslt.lang.highlighter.XPathColorSettingsPage import uk.co.reecedunn.intellij.plugin.xslt.lang.highlighter.XsltSyntaxHighlighterColors @DisplayName("IntelliJ - Custom Language Support - Syntax Highlighting - XPath Color Settings Page") class XPathColorSettingsPageTest { private val settings = XPathColorSettingsPage() @Suppress("RegExpAnonymousGroup") private fun getTextAttributeKeysForTokens(text: String): List<TextAttributesKey> { var withoutHighlightElements = text settings.additionalHighlightingTagToDescriptorMap.forEach { (name, _) -> withoutHighlightElements = "<$name>([^<]*)</$name>".toRegex().replace(withoutHighlightElements) { it.groups[1]!!.value } } val highlighter = settings.highlighter val lexer = highlighter.highlightingLexer lexer.start(withoutHighlightElements) val keys = ArrayList<TextAttributesKey>() while (lexer.tokenType != null) { for (key in highlighter.getTokenHighlights(lexer.tokenType)) { if (!keys.contains(key)) { keys.add(key) } } lexer.advance() } return keys } @Suppress("RegExpAnonymousGroup") private fun getTextAttributeKeysForAdditionalDescriptors(text: String): List<Pair<String, TextAttributesKey>> { return settings.additionalHighlightingTagToDescriptorMap.asSequence().flatMap { (name, attributesKey) -> val matches = "<$name>([^<]*)</$name>".toRegex().findAll(text) assertThat("additional highlight '$name' XML annotation is present", matches.any(), `is`(true)) matches.map { match -> match.groups[1]?.value!! to attributesKey } }.toList() } @Test @DisplayName("demo text contains valid separators") fun testDemoTextSeparators() { StringUtil.assertValidSeparators(settings.demoText) } @Test @DisplayName("demo text contains all syntax-based text attribute keys") fun syntaxHighlightingTextAttributeKeys() { val keys = getTextAttributeKeysForTokens(settings.demoText) assertThat(keys.contains(XPathSyntaxHighlighterColors.ATTRIBUTE), `is`(true)) assertThat(keys.contains(XPathSyntaxHighlighterColors.BAD_CHARACTER), `is`(true)) assertThat(keys.contains(XPathSyntaxHighlighterColors.COMMENT), `is`(true)) assertThat(keys.contains(XPathSyntaxHighlighterColors.ESCAPED_CHARACTER), `is`(true)) assertThat(keys.contains(XPathSyntaxHighlighterColors.IDENTIFIER), `is`(true)) assertThat(keys.contains(XPathSyntaxHighlighterColors.KEYWORD), `is`(true)) assertThat(keys.contains(XPathSyntaxHighlighterColors.NUMBER), `is`(true)) assertThat(keys.contains(XPathSyntaxHighlighterColors.STRING), `is`(true)) assertThat(keys.size, `is`(8)) // No other matching highlight colours } @Test @DisplayName("demo text contains all semantic-based text attribute keys") fun semanticHighlightingTextAttributeKeys() { val keys = getTextAttributeKeysForAdditionalDescriptors(settings.demoText) assertThat(keys.size, `is`(18)) assertThat(keys[0], `is`("value" to XPathSyntaxHighlighterColors.ATTRIBUTE)) assertThat(keys[1], `is`("two" to XPathSyntaxHighlighterColors.ATTRIBUTE)) assertThat(keys[2], `is`("lorem" to XPathSyntaxHighlighterColors.ELEMENT)) assertThat(keys[3], `is`("ipsum" to XPathSyntaxHighlighterColors.ELEMENT)) assertThat(keys[4], `is`("one" to XPathSyntaxHighlighterColors.ELEMENT)) assertThat(keys[5], `is`("position" to XPathSyntaxHighlighterColors.FUNCTION_CALL)) assertThat(keys[6], `is`("true" to XPathSyntaxHighlighterColors.FUNCTION_CALL)) assertThat(keys[7], `is`("key-name" to XPathSyntaxHighlighterColors.MAP_KEY)) assertThat(keys[8], `is`("fn" to XPathSyntaxHighlighterColors.NS_PREFIX)) assertThat(keys[9], `is`("fn" to XPathSyntaxHighlighterColors.NS_PREFIX)) assertThat(keys[10], `is`("xs" to XPathSyntaxHighlighterColors.NS_PREFIX)) assertThat(keys[11], `is`("three" to XPathSyntaxHighlighterColors.NS_PREFIX)) assertThat(keys[12], `is`("a" to XPathSyntaxHighlighterColors.PARAMETER)) assertThat(keys[13], `is`("a" to XPathSyntaxHighlighterColors.PARAMETER)) assertThat(keys[14], `is`("ext" to XPathSyntaxHighlighterColors.PRAGMA)) assertThat(keys[15], `is`("test" to XPathSyntaxHighlighterColors.PROCESSING_INSTRUCTION)) assertThat(keys[16], `is`("integer" to XPathSyntaxHighlighterColors.TYPE)) assertThat(keys[17], `is`("items" to XPathSyntaxHighlighterColors.VARIABLE)) } @Test @DisplayName("demo text contains all keys from the attribute descriptors") fun allDescriptorsPresentInDemoText() { val tokens = getTextAttributeKeysForTokens(settings.demoText) val additional = getTextAttributeKeysForAdditionalDescriptors(settings.demoText).map { (_, key) -> key } val keys = tokens.union(additional).toMutableSet() keys.add(XsltSyntaxHighlighterColors.ATTRIBUTE_VALUE) // Not tokenized by XPath. keys.add(XsltSyntaxHighlighterColors.ESCAPED_CHARACTER) // Not tokenized by XPath. keys.add(XsltSyntaxHighlighterColors.XSLT_DIRECTIVE) // Not tokenized by XPath. val descriptorKeys = settings.attributeDescriptors.map { it.key } keys.forEach { key -> assertThat("$key from demo text in attributeDescriptors", descriptorKeys.contains(key), `is`(true)) } descriptorKeys.forEach { key -> assertThat("$key from attributeDescriptors in keys from demo text", keys.contains(key), `is`(true)) } } }
apache-2.0
26b82932b09c09c4be3708c62bca9e2c
49.669118
115
0.708315
4.563576
false
true
false
false
BrandonWilliamsCS/DulyNoted-Android
DulyNoted/app/src/test/java/com/brandonwilliamscs/dulynoted/test/model/DulyNotedStateTests.kt
1
1001
package com.brandonwilliamscs.dulynoted.test.model import com.brandonwilliamscs.dulynoted.model.DulyNotedState import com.brandonwilliamscs.dulynoted.model.music.PitchClass import org.junit.Assert import org.junit.Test /** * Created by Brandon on 9/19/2017. */ class DulyNotedStateTests { val initialState = DulyNotedState(PitchClass.C, null) @Test @Throws(Exception::class) fun canUpdateGuess() { val pitchClassD = PitchClass.C.increasePitch(1) val nextState = initialState.updateGuess(pitchClassD) Assert.assertNotNull(nextState.currentGuess) Assert.assertEquals(pitchClassD, nextState.currentGuess!!.value) Assert.assertFalse(nextState.currentGuess!!.isCorrect) } @Test @Throws(Exception::class) fun canChangeSlide() { val pitchClassD = PitchClass.C.increasePitch(1) val nextState = initialState.nextSlide(pitchClassD) Assert.assertEquals(pitchClassD, nextState.currentPromptPitchClass) } }
apache-2.0
f17628bf6b28bb135aaabdbab4625162
30.28125
75
0.737263
3.763158
false
true
false
false
InsertKoinIO/koin
core/koin-core/src/commonMain/kotlin/org/koin/core/instance/SingleInstanceFactory.kt
1
1722
/* * Copyright 2017-2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.koin.core.instance import org.koin.core.definition.BeanDefinition import org.koin.core.scope.Scope import org.koin.mp.KoinPlatformTools /** * Single instance holder * @author Arnaud Giuliani */ class SingleInstanceFactory<T>(beanDefinition: BeanDefinition<T>) : InstanceFactory<T>(beanDefinition) { private var value: T? = null private fun getValue() : T = value ?: error("Single instance created couldn't return value") override fun isCreated(context: InstanceContext?): Boolean = (value != null) override fun drop(scope: Scope?) { beanDefinition.callbacks.onClose?.invoke(value) value = null } override fun dropAll(){ drop() } override fun create(context: InstanceContext): T { return if (value == null) { super.create(context) } else getValue() } override fun get(context: InstanceContext): T { KoinPlatformTools.synchronized(this) { if (!isCreated(context)) { value = create(context) } } return getValue() } }
apache-2.0
5d7ebb69405b59de9ad62812acc5599b
28.706897
96
0.674216
4.348485
false
false
false
false
jiaminglu/kotlin-native
backend.native/tests/external/codegen/box/reflection/properties/declaredVsInheritedProperties.kt
1
2013
// TODO: muted automatically, investigate should it be ran for JS or not // IGNORE_BACKEND: JS, NATIVE // WITH_REFLECT // FILE: J.java public class J { public String publicMemberJ; private String privateMemberJ; public static String publicStaticJ; private static String privateStaticJ; } // FILE: K.kt import kotlin.reflect.* import kotlin.test.assertEquals open class K : J() { public val publicMemberK: String = "" private val privateMemberK: String = "" public val Any.publicMemberExtensionK: String get() = "" private val Any.privateMemberExtensionK: String get() = "" } class L : K() fun Collection<KProperty<*>>.names(): Set<String> = this.map { it.name }.toSet() fun check(c: Collection<KProperty<*>>, names: Set<String>) { assertEquals(names, c.names()) } fun box(): String { val j = J::class check(j.staticProperties, setOf("publicStaticJ", "privateStaticJ")) check(j.declaredMemberProperties, setOf("publicMemberJ", "privateMemberJ")) check(j.declaredMemberExtensionProperties, emptySet()) check(j.memberProperties, j.declaredMemberProperties.names()) check(j.memberExtensionProperties, emptySet()) val k = K::class check(k.staticProperties, emptySet()) check(k.declaredMemberProperties, setOf("publicMemberK", "privateMemberK")) check(k.declaredMemberExtensionProperties, setOf("publicMemberExtensionK", "privateMemberExtensionK")) check(k.memberProperties, setOf("publicMemberJ") + k.declaredMemberProperties.names()) check(k.memberExtensionProperties, k.declaredMemberExtensionProperties.names()) val l = L::class check(l.staticProperties, emptySet()) check(l.declaredMemberProperties, emptySet()) check(l.declaredMemberExtensionProperties, emptySet()) check(l.memberProperties, setOf("publicMemberJ", "publicMemberK")) check(l.memberExtensionProperties, setOf("publicMemberExtensionK")) return "OK" }
apache-2.0
5b78ec9cdccec2e1e14f2b18671ea066
27.757143
90
0.701937
4.414474
false
false
false
false
Commit451/GitLabAndroid
app/src/main/java/com/commit451/gitlab/model/api/Tag.kt
2
689
package com.commit451.gitlab.model.api import com.squareup.moshi.Json /** * A tag in Git */ data class Tag( @Json(name = "name") var name: String? = null, @Json(name = "message") var message: String? = null, @Json(name = "commit") var commit: Commit? = null, @Json(name = "release") var release: Release? = null ) { data class Commit( @Json(name = "id") var id: String? = null, @Json(name = "message") var message: String? = null ) data class Release( @Json(name = "tag_name") var tagName: String? = null, @Json(name = "description") var description: String? = null ) }
apache-2.0
bdaf20610a2429898c7b863655493b26
19.878788
39
0.554427
3.445
false
false
false
false
hitoshura25/Media-Player-Omega-Android
search_presentation/src/main/java/com/vmenon/mpo/search/presentation/viewmodel/ShowDetailsViewModel.kt
1
3176
package com.vmenon.mpo.search.presentation.viewmodel import androidx.lifecycle.* import com.vmenon.mpo.common.domain.ContentEvent import com.vmenon.mpo.search.domain.ShowSearchResultDetailsModel import com.vmenon.mpo.search.domain.ShowSearchResultEpisodeModel import com.vmenon.mpo.search.domain.ShowSearchResultModel import com.vmenon.mpo.search.presentation.mvi.ShowDetailsViewEffect import com.vmenon.mpo.search.presentation.mvi.ShowDetailsViewEvent import com.vmenon.mpo.search.presentation.mvi.ShowDetailsViewState import com.vmenon.mpo.search.usecases.SearchInteractors import kotlinx.coroutines.launch import java.lang.Exception import javax.inject.Inject class ShowDetailsViewModel : ViewModel() { @Inject lateinit var searchInteractors: SearchInteractors private val initialState = ShowDetailsViewState(loading = true) private val states = MutableLiveData<ContentEvent<ShowDetailsViewState>>(ContentEvent(initialState)) private val effects = MutableLiveData<ContentEvent<ShowDetailsViewEffect>>() private var currentState: ShowDetailsViewState get() = states.value?.anyContent() ?: initialState set(value) { states.postValue(ContentEvent(value)) } fun states(): LiveData<ContentEvent<ShowDetailsViewState>> = states fun effects(): LiveData<ContentEvent<ShowDetailsViewEffect>> = effects fun send(event: ShowDetailsViewEvent) { viewModelScope.launch { when (event) { is ShowDetailsViewEvent.LoadShowDetailsEvent -> getShowDetails( event.showSearchResultId ) is ShowDetailsViewEvent.SubscribeToShowEvent -> subscribeToShow(event.showDetails) is ShowDetailsViewEvent.QueueDownloadEvent -> queueDownload( event.show, event.episode ) } } } private suspend fun getShowDetails(showSearchResultId: Long) { currentState = try { val details = searchInteractors.getShowDetails(showSearchResultId) currentState.copy( showDetails = details, loading = false, error = false ) } catch (e: Exception) { currentState.copy( loading = false, error = true ) } } private suspend fun subscribeToShow(showDetails: ShowSearchResultDetailsModel) { effects.postValue( ContentEvent( ShowDetailsViewEffect.ShowSubscribedViewEffect( searchInteractors.subscribeToShow(showDetails) ) ) ) currentState = currentState.copy(showDetails = showDetails.copy(subscribed = true)) } private suspend fun queueDownload( show: ShowSearchResultModel, episode: ShowSearchResultEpisodeModel ) { effects.postValue( ContentEvent( ShowDetailsViewEffect.DownloadQueuedViewEffect( searchInteractors.queueDownloadForShow(show, episode) ) ) ) } }
apache-2.0
c6442b75d74e279b28eef213632de81c
34.3
98
0.657746
5.284526
false
false
false
false
CarlosEsco/tachiyomi
app/src/main/java/eu/kanade/tachiyomi/util/storage/EpubFile.kt
1
6782
package eu.kanade.tachiyomi.util.storage import eu.kanade.tachiyomi.source.model.SChapter import eu.kanade.tachiyomi.source.model.SManga import org.jsoup.Jsoup import org.jsoup.nodes.Document import java.io.Closeable import java.io.File import java.io.InputStream import java.text.ParseException import java.text.SimpleDateFormat import java.util.Locale import java.util.zip.ZipEntry import java.util.zip.ZipFile /** * Wrapper over ZipFile to load files in epub format. */ class EpubFile(file: File) : Closeable { /** * Zip file of this epub. */ private val zip = ZipFile(file) /** * Path separator used by this epub. */ private val pathSeparator = getPathSeparator() /** * Closes the underlying zip file. */ override fun close() { zip.close() } /** * Returns an input stream for reading the contents of the specified zip file entry. */ fun getInputStream(entry: ZipEntry): InputStream { return zip.getInputStream(entry) } /** * Returns the zip file entry for the specified name, or null if not found. */ fun getEntry(name: String): ZipEntry? { return zip.getEntry(name) } /** * Fills manga metadata using this epub file's metadata. */ fun fillMangaMetadata(manga: SManga) { val ref = getPackageHref() val doc = getPackageDocument(ref) val creator = doc.getElementsByTag("dc:creator").first() val description = doc.getElementsByTag("dc:description").first() manga.author = creator?.text() manga.description = description?.text() } /** * Fills chapter metadata using this epub file's metadata. */ fun fillChapterMetadata(chapter: SChapter) { val ref = getPackageHref() val doc = getPackageDocument(ref) val title = doc.getElementsByTag("dc:title").first() val publisher = doc.getElementsByTag("dc:publisher").first() val creator = doc.getElementsByTag("dc:creator").first() var date = doc.getElementsByTag("dc:date").first() if (date == null) { date = doc.select("meta[property=dcterms:modified]").first() } if (title != null) { chapter.name = title.text() } if (publisher != null) { chapter.scanlator = publisher.text() } else if (creator != null) { chapter.scanlator = creator.text() } if (date != null) { val dateFormat = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ", Locale.getDefault()) try { val parsedDate = dateFormat.parse(date.text()) if (parsedDate != null) { chapter.date_upload = parsedDate.time } } catch (e: ParseException) { // Empty } } } /** * Returns the path of all the images found in the epub file. */ fun getImagesFromPages(): List<String> { val ref = getPackageHref() val doc = getPackageDocument(ref) val pages = getPagesFromDocument(doc) return getImagesFromPages(pages, ref) } /** * Returns the path to the package document. */ private fun getPackageHref(): String { val meta = zip.getEntry(resolveZipPath("META-INF", "container.xml")) if (meta != null) { val metaDoc = zip.getInputStream(meta).use { Jsoup.parse(it, null, "") } val path = metaDoc.getElementsByTag("rootfile").first()?.attr("full-path") if (path != null) { return path } } return resolveZipPath("OEBPS", "content.opf") } /** * Returns the package document where all the files are listed. */ private fun getPackageDocument(ref: String): Document { val entry = zip.getEntry(ref) return zip.getInputStream(entry).use { Jsoup.parse(it, null, "") } } /** * Returns all the pages from the epub. */ private fun getPagesFromDocument(document: Document): List<String> { val pages = document.select("manifest > item") .filter { node -> "application/xhtml+xml" == node.attr("media-type") } .associateBy { it.attr("id") } val spine = document.select("spine > itemref").map { it.attr("idref") } return spine.mapNotNull { pages[it] }.map { it.attr("href") } } /** * Returns all the images contained in every page from the epub. */ private fun getImagesFromPages(pages: List<String>, packageHref: String): List<String> { val result = mutableListOf<String>() val basePath = getParentDirectory(packageHref) pages.forEach { page -> val entryPath = resolveZipPath(basePath, page) val entry = zip.getEntry(entryPath) val document = zip.getInputStream(entry).use { Jsoup.parse(it, null, "") } val imageBasePath = getParentDirectory(entryPath) document.allElements.forEach { if (it.tagName() == "img") { result.add(resolveZipPath(imageBasePath, it.attr("src"))) } else if (it.tagName() == "image") { result.add(resolveZipPath(imageBasePath, it.attr("xlink:href"))) } } } return result } /** * Returns the path separator used by the epub file. */ private fun getPathSeparator(): String { val meta = zip.getEntry("META-INF\\container.xml") return if (meta != null) { "\\" } else { "/" } } /** * Resolves a zip path from base and relative components and a path separator. */ private fun resolveZipPath(basePath: String, relativePath: String): String { if (relativePath.startsWith(pathSeparator)) { // Path is absolute, so return as-is. return relativePath } var fixedBasePath = basePath.replace(pathSeparator, File.separator) if (!fixedBasePath.startsWith(File.separator)) { fixedBasePath = "${File.separator}$fixedBasePath" } val fixedRelativePath = relativePath.replace(pathSeparator, File.separator) val resolvedPath = File(fixedBasePath, fixedRelativePath).canonicalPath return resolvedPath.replace(File.separator, pathSeparator).substring(1) } /** * Gets the parent directory of a path. */ private fun getParentDirectory(path: String): String { val separatorIndex = path.lastIndexOf(pathSeparator) return if (separatorIndex >= 0) { path.substring(0, separatorIndex) } else { "" } } }
apache-2.0
7c404e2cbd7cf39875550a4996e4f543
30.544186
92
0.591713
4.458909
false
false
false
false
Heiner1/AndroidAPS
app/src/main/java/info/nightscout/androidaps/plugins/constraints/phoneChecker/PhoneCheckerPlugin.kt
1
1570
package info.nightscout.androidaps.plugins.constraints.phoneChecker import android.content.Context import android.os.Build import com.scottyab.rootbeer.RootBeer import dagger.android.HasAndroidInjector import info.nightscout.androidaps.R import info.nightscout.androidaps.interfaces.Constraints import info.nightscout.androidaps.interfaces.PluginBase import info.nightscout.androidaps.interfaces.PluginDescription import info.nightscout.androidaps.interfaces.PluginType import info.nightscout.shared.logging.AAPSLogger import info.nightscout.androidaps.interfaces.ResourceHelper import javax.inject.Inject import javax.inject.Singleton @Singleton class PhoneCheckerPlugin @Inject constructor( injector: HasAndroidInjector, aapsLogger: AAPSLogger, rh: ResourceHelper, private val context: Context ) : PluginBase(PluginDescription() .mainType(PluginType.CONSTRAINTS) .neverVisible(true) .alwaysEnabled(true) .showInList(false) .pluginName(R.string.phonechecker), aapsLogger, rh, injector ), Constraints { var phoneRooted: Boolean = false var devMode: Boolean = false val phoneModel: String = Build.MODEL val manufacturer: String = Build.MANUFACTURER private fun isDevModeEnabled(): Boolean { return android.provider.Settings.Secure.getInt(context.contentResolver, android.provider.Settings.Global.DEVELOPMENT_SETTINGS_ENABLED, 0) != 0 } override fun onStart() { super.onStart() phoneRooted = RootBeer(context).isRooted devMode = isDevModeEnabled() } }
agpl-3.0
1223b2c89e545f66910f9d0bd5c58afd
32.425532
82
0.775159
4.537572
false
false
false
false
esqr/WykopMobilny
app/src/main/kotlin/io/github/feelfreelinux/wykopmobilny/utils/rx/SubscriptionHelper.kt
1
2242
package io.github.feelfreelinux.wykopmobilny.utils.rx import io.github.feelfreelinux.wykopmobilny.api.UserTokenRefresher import io.reactivex.Flowable import io.reactivex.Observable import io.reactivex.Scheduler import io.reactivex.Single import io.reactivex.disposables.Disposable import io.reactivex.functions.Action import io.reactivex.functions.Function import org.reactivestreams.Publisher import java.util.concurrent.TimeUnit interface SubscriptionHelperApi { fun <T> subscribe(single : Single<T>, success : (T) -> Unit, exception: (Throwable) -> Unit, subscriber: Any) fun dispose(subscriber: Any) fun getSubscriberCompositeDisposable(subscriber: Any): MutableList<Disposable> } open class SubscriptionHelper(internal val observeScheduler: Scheduler, internal val subscribeScheduler: Scheduler, val userTokenRefresher: UserTokenRefresher) : SubscriptionHelperApi { private val subscriptions = HashMap<String, MutableList<Disposable>>() override fun <T> subscribe(single : Single<T>, success : (T) -> Unit, exception: (Throwable) -> Unit, subscriber: Any) { val disposable = getSubscriberCompositeDisposable(subscriber) disposable.add( single .retryWhen(userTokenRefresher) .observeOn(observeScheduler) .subscribeOn(subscribeScheduler) .subscribe(success, exception) ) } override fun getSubscriberCompositeDisposable(subscriber: Any): MutableList<Disposable> { var objectSubscriptions = subscriptions[subscriber.uniqueTag] if (objectSubscriptions == null) { objectSubscriptions = mutableListOf() subscriptions.put(subscriber.uniqueTag, objectSubscriptions) } return objectSubscriptions } override fun dispose(subscriber: Any) { val disposable = subscriptions[subscriber.uniqueTag] disposable?.let { for (subscription in disposable) { subscription.dispose() } } subscriptions.remove(uniqueTag) } private val Any.uniqueTag : String get() = toString() }
mit
c01ec4449c94dfd17729f6141a35e42a
35.770492
124
0.677966
5.238318
false
false
false
false
hurricup/intellij-community
plugins/settings-repository/testSrc/GitTest.kt
1
11782
/* * Copyright 2000-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.settingsRepository.test import com.intellij.configurationStore.ApplicationStoreImpl import com.intellij.configurationStore.write import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.vcs.merge.MergeSession import com.intellij.testFramework.file import com.intellij.util.PathUtilRt import com.intellij.util.writeChild import org.assertj.core.api.Assertions.assertThat import org.jetbrains.jgit.dirCache.deletePath import org.jetbrains.jgit.dirCache.writePath import org.jetbrains.settingsRepository.CannotResolveConflictInTestMode import org.jetbrains.settingsRepository.SyncType import org.jetbrains.settingsRepository.conflictResolver import org.jetbrains.settingsRepository.copyLocalConfig import org.jetbrains.settingsRepository.git.commit import org.jetbrains.settingsRepository.git.computeIndexDiff import org.junit.Test import java.nio.charset.StandardCharsets import java.util.* // kotlin bug, cannot be val (.NoSuchMethodError: org.jetbrains.settingsRepository.SettingsRepositoryPackage.getMARKER_ACCEPT_MY()[B) internal object AM { val MARKER_ACCEPT_MY: ByteArray = "__accept my__".toByteArray() val MARKER_ACCEPT_THEIRS: ByteArray = "__accept theirs__".toByteArray() } internal class GitTest : GitTestCase() { init { conflictResolver = { files, mergeProvider -> val mergeSession = mergeProvider.createMergeSession(files) for (file in files) { val mergeData = mergeProvider.loadRevisions(file) if (Arrays.equals(mergeData.CURRENT, AM.MARKER_ACCEPT_MY) || Arrays.equals(mergeData.LAST, AM.MARKER_ACCEPT_THEIRS)) { mergeSession.conflictResolvedForFile(file, MergeSession.Resolution.AcceptedYours) } else if (Arrays.equals(mergeData.CURRENT, AM.MARKER_ACCEPT_THEIRS) || Arrays.equals(mergeData.LAST, AM.MARKER_ACCEPT_MY)) { mergeSession.conflictResolvedForFile(file, MergeSession.Resolution.AcceptedTheirs) } else if (Arrays.equals(mergeData.LAST, AM.MARKER_ACCEPT_MY)) { file.setBinaryContent(mergeData.LAST) mergeProvider.conflictResolvedForFile(file) } else { throw CannotResolveConflictInTestMode() } } } } @Test fun add() { provider.write(SAMPLE_FILE_NAME, SAMPLE_FILE_CONTENT) val diff = repository.computeIndexDiff() assertThat(diff.diff()).isTrue() assertThat(diff.added).containsOnly(SAMPLE_FILE_NAME) assertThat(diff.changed).isEmpty() assertThat(diff.removed).isEmpty() assertThat(diff.modified).isEmpty() assertThat(diff.untracked).isEmpty() assertThat(diff.untrackedFolders).isEmpty() } @Test fun addSeveral() { val addedFile = "foo.xml" val addedFile2 = "bar.xml" provider.write(addedFile, "foo") provider.write(addedFile2, "bar") val diff = repository.computeIndexDiff() assertThat(diff.diff()).isTrue() assertThat(diff.added).containsOnly(addedFile, addedFile2) assertThat(diff.changed).isEmpty() assertThat(diff.removed).isEmpty() assertThat(diff.modified).isEmpty() assertThat(diff.untracked).isEmpty() assertThat(diff.untrackedFolders).isEmpty() } @Test fun delete() { fun delete(directory: Boolean) { val dir = "dir" val fullFileSpec = "$dir/file.xml" provider.write(fullFileSpec, SAMPLE_FILE_CONTENT) provider.delete(if (directory) dir else fullFileSpec) val diff = repository.computeIndexDiff() assertThat(diff.diff()).isFalse() assertThat(diff.added).isEmpty() assertThat(diff.changed).isEmpty() assertThat(diff.removed).isEmpty() assertThat(diff.modified).isEmpty() assertThat(diff.untracked).isEmpty() assertThat(diff.untrackedFolders).isEmpty() } delete(false) delete(true) } @Test fun `set upstream`() { val url = "https://github.com/user/repo.git" repositoryManager.setUpstream(url) assertThat(repositoryManager.getUpstream()).isEqualTo(url) } @Test fun pullToRepositoryWithoutCommits() { doPullToRepositoryWithoutCommits(null) } @Test fun pullToRepositoryWithoutCommitsAndCustomRemoteBranchName() { doPullToRepositoryWithoutCommits("customRemoteBranchName") } private fun doPullToRepositoryWithoutCommits(remoteBranchName: String?) { createLocalAndRemoteRepositories(remoteBranchName) repositoryManager.pull() compareFiles(repository.workTreePath, remoteRepository.workTreePath) } @Test fun pullToRepositoryWithCommits() { doPullToRepositoryWithCommits(null) } @Test fun pullToRepositoryWithCommitsAndCustomRemoteBranchName() { doPullToRepositoryWithCommits("customRemoteBranchName") } private fun doPullToRepositoryWithCommits(remoteBranchName: String?) { createLocalAndRemoteRepositories(remoteBranchName) val file = addAndCommit("local.xml") repositoryManager.commit() repositoryManager.pull() assertThat(repository.workTree.resolve(file.name)).hasBinaryContent(file.data) compareFiles(repository.workTreePath, remoteRepository.workTreePath, PathUtilRt.getFileName(file.name)) } // never was merged. we reset using "merge with strategy "theirs", so, we must test - what's happen if it is not first merge? - see next test @Test fun resetToTheirsIfFirstMerge() { createLocalAndRemoteRepositories(initialCommit = true) sync(SyncType.OVERWRITE_LOCAL) fs .file(SAMPLE_FILE_NAME, SAMPLE_FILE_CONTENT) .compare() } @Test fun `overwrite local - second merge is null`() { createLocalAndRemoteRepositories(initialCommit = true) sync(SyncType.MERGE) restoreRemoteAfterPush() fun testRemote() { fs .file("local.xml", """<file path="local.xml" />""") .file(SAMPLE_FILE_NAME, SAMPLE_FILE_CONTENT) .compare() } testRemote() addAndCommit("_mac/local2.xml") sync(SyncType.OVERWRITE_LOCAL) fs.compare() // test: merge and push to remote after such reset sync(SyncType.MERGE) restoreRemoteAfterPush() testRemote() } @Test fun `merge - resolve conflicts to my`() { createLocalAndRemoteRepositories() val data = AM.MARKER_ACCEPT_MY provider.write(SAMPLE_FILE_NAME, data) sync(SyncType.MERGE) restoreRemoteAfterPush() fs.file(SAMPLE_FILE_NAME, data.toString(StandardCharsets.UTF_8)).compare() } @Test fun `merge - theirs file deleted, my modified, accept theirs`() { createLocalAndRemoteRepositories() sync(SyncType.MERGE) val data = AM.MARKER_ACCEPT_THEIRS provider.write(SAMPLE_FILE_NAME, data) repositoryManager.commit() remoteRepository.deletePath(SAMPLE_FILE_NAME) remoteRepository.commit("delete $SAMPLE_FILE_NAME") sync(SyncType.MERGE) fs.compare() } @Test fun `merge - my file deleted, theirs modified, accept my`() { createLocalAndRemoteRepositories() sync(SyncType.MERGE) provider.delete(SAMPLE_FILE_NAME) repositoryManager.commit() remoteRepository.writePath(SAMPLE_FILE_NAME, AM.MARKER_ACCEPT_THEIRS) remoteRepository.commit("") sync(SyncType.MERGE) restoreRemoteAfterPush() fs.compare() } @Test fun `commit if unmerged`() { createLocalAndRemoteRepositories() val data = "<foo />" provider.write(SAMPLE_FILE_NAME, data) try { sync(SyncType.MERGE) } catch (e: CannotResolveConflictInTestMode) { } // repository in unmerged state conflictResolver = {files, mergeProvider -> assertThat(files).hasSize(1) assertThat(files.first().path).isEqualTo(SAMPLE_FILE_NAME) val mergeSession = mergeProvider.createMergeSession(files) mergeSession.conflictResolvedForFile(files.first(), MergeSession.Resolution.AcceptedTheirs) } sync(SyncType.MERGE) fs.file(SAMPLE_FILE_NAME, SAMPLE_FILE_CONTENT).compare() } // remote is uninitialized (empty - initial commit is not done) @Test fun `merge with uninitialized upstream`() { doSyncWithUninitializedUpstream(SyncType.MERGE) } @Test fun `overwrite remote - uninitialized upstream`() { doSyncWithUninitializedUpstream(SyncType.OVERWRITE_REMOTE) } @Test fun `overwrite local - uninitialized upstream`() { doSyncWithUninitializedUpstream(SyncType.OVERWRITE_LOCAL) } @Test fun gitignore() { createLocalAndRemoteRepositories() provider.write(".gitignore", "*.html") sync(SyncType.MERGE) val filePaths = listOf("bar.html", "i/am/a/long/path/to/file/foo.html") for (path in filePaths) { provider.write(path, path) } val diff = repository.computeIndexDiff() assertThat(diff.diff()).isFalse() assertThat(diff.added).isEmpty() assertThat(diff.changed).isEmpty() assertThat(diff.removed).isEmpty() assertThat(diff.modified).isEmpty() assertThat(diff.untracked).isEmpty() assertThat(diff.untrackedFolders).isEmpty() for (path in filePaths) { assertThat(provider.read(path)).isNull() } } @Test fun `initial copy to repository - no local files`() { createRemoteRepository(initialCommit = false) // check error during findRemoteRefUpdatesFor (no master ref) testInitialCopy(false) } @Test fun `initial copy to repository - some local files`() { createRemoteRepository(initialCommit = false) // check error during findRemoteRefUpdatesFor (no master ref) testInitialCopy(true) } @Test fun `initial copy to repository - remote files removed`() { createRemoteRepository(initialCommit = true) // check error during findRemoteRefUpdatesFor (no master ref) testInitialCopy(true, SyncType.OVERWRITE_REMOTE) } private fun testInitialCopy(addLocalFiles: Boolean, syncType: SyncType = SyncType.MERGE) { repositoryManager.createRepositoryIfNeed() repositoryManager.setUpstream(remoteRepository.workTree.absolutePath) val store = ApplicationStoreImpl(ApplicationManager.getApplication()!!) val localConfigPath = tempDirManager.newPath("local_config", refreshVfs = true) val lafData = """<application> <component name="UISettings"> <option name="HIDE_TOOL_STRIPES" value="false" /> </component> </application>""" if (addLocalFiles) { localConfigPath.writeChild("options/ui.lnf.xml", lafData) } store.setPath(localConfigPath.toString()) store.storageManager.streamProvider = provider icsManager.sync(syncType, GitTestCase.projectRule.project, { copyLocalConfig(store.storageManager) }) if (addLocalFiles) { assertThat(localConfigPath).isDirectory() fs .file("ui.lnf.xml", lafData) restoreRemoteAfterPush() } else { assertThat(localConfigPath).doesNotExist() } fs.compare() } private fun doSyncWithUninitializedUpstream(syncType: SyncType) { createRemoteRepository(initialCommit = false) repositoryManager.setUpstream(remoteRepository.workTree.absolutePath) val path = "local.xml" val data = "<application />" provider.write(path, data) sync(syncType) if (syncType != SyncType.OVERWRITE_LOCAL) { fs.file(path, data) } restoreRemoteAfterPush() fs.compare() } }
apache-2.0
2ac2eaaf95cd5aa05b8949a319de72c5
30.932249
143
0.722034
4.524578
false
true
false
false
Maccimo/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/kotlinRefactoringUtil.kt
2
46438
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.refactoring import com.intellij.codeInsight.daemon.impl.quickfix.CreateFromUsageUtils import com.intellij.codeInsight.unwrap.RangeSplitter import com.intellij.codeInsight.unwrap.UnwrapHandler import com.intellij.ide.IdeBundle import com.intellij.ide.util.PsiElementListCellRenderer import com.intellij.lang.injection.InjectedLanguageManager import com.intellij.lang.java.JavaLanguage import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.TransactionGuard import com.intellij.openapi.command.CommandEvent import com.intellij.openapi.command.CommandListener import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.colors.EditorColors import com.intellij.openapi.editor.colors.EditorColorsManager import com.intellij.openapi.editor.markup.HighlighterTargetArea import com.intellij.openapi.editor.markup.RangeHighlighter import com.intellij.openapi.editor.markup.TextAttributes import com.intellij.openapi.options.ConfigurationException import com.intellij.openapi.project.Project import com.intellij.openapi.ui.DialogWrapper import com.intellij.openapi.ui.Messages import com.intellij.openapi.ui.popup.JBPopup import com.intellij.openapi.ui.popup.JBPopupFactory import com.intellij.openapi.ui.popup.JBPopupListener import com.intellij.openapi.ui.popup.LightweightWindowEvent import com.intellij.openapi.util.NlsContexts import com.intellij.openapi.util.Pass import com.intellij.openapi.util.TextRange import com.intellij.openapi.util.text.StringUtil import com.intellij.openapi.vfs.VirtualFile import com.intellij.psi.* import com.intellij.psi.impl.file.PsiPackageBase import com.intellij.psi.impl.light.LightElement import com.intellij.psi.presentation.java.SymbolPresentationUtil import com.intellij.psi.util.PsiTreeUtil import com.intellij.refactoring.BaseRefactoringProcessor.ConflictsInTestsException import com.intellij.refactoring.changeSignature.ChangeSignatureUtil import com.intellij.refactoring.listeners.RefactoringEventData import com.intellij.refactoring.listeners.RefactoringEventListener import com.intellij.refactoring.ui.ConflictsDialog import com.intellij.refactoring.util.ConflictsUtil import com.intellij.refactoring.util.RefactoringUIUtil import com.intellij.usageView.UsageViewTypeLocation import com.intellij.util.VisibilityUtil import com.intellij.util.containers.MultiMap import org.jetbrains.annotations.Nls import org.jetbrains.kotlin.asJava.LightClassUtil import org.jetbrains.kotlin.asJava.elements.KtLightMethod import org.jetbrains.kotlin.asJava.getAccessorLightMethods import org.jetbrains.kotlin.asJava.isSyntheticValuesOrValueOfMethod import org.jetbrains.kotlin.asJava.namedUnwrappedElement import org.jetbrains.kotlin.asJava.toLightClass import org.jetbrains.kotlin.descriptors.* import org.jetbrains.kotlin.descriptors.impl.AnonymousFunctionDescriptor import org.jetbrains.kotlin.descriptors.impl.LocalVariableDescriptor import org.jetbrains.kotlin.diagnostics.Errors import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.KotlinFileType import org.jetbrains.kotlin.idea.KotlinLanguage import org.jetbrains.kotlin.idea.base.projectStructure.RootKindFilter import org.jetbrains.kotlin.idea.base.projectStructure.languageVersionSettings import org.jetbrains.kotlin.idea.base.projectStructure.matches import org.jetbrains.kotlin.idea.base.psi.dropCurlyBracketsIfPossible import org.jetbrains.kotlin.idea.caches.resolve.analyzeAsReplacement import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny import org.jetbrains.kotlin.idea.caches.resolve.unsafeResolveToDescriptor import org.jetbrains.kotlin.idea.caches.resolve.util.getJavaMemberDescriptor import org.jetbrains.kotlin.idea.codeInsight.DescriptorToSourceUtilsIde import org.jetbrains.kotlin.idea.core.* import org.jetbrains.kotlin.idea.core.util.showYesNoCancelDialog import org.jetbrains.kotlin.idea.refactoring.changeSignature.KotlinChangeInfo import org.jetbrains.kotlin.idea.refactoring.changeSignature.KotlinValVar import org.jetbrains.kotlin.idea.refactoring.changeSignature.toValVar import org.jetbrains.kotlin.idea.refactoring.memberInfo.KtPsiClassWrapper import org.jetbrains.kotlin.idea.refactoring.rename.canonicalRender import org.jetbrains.kotlin.idea.roots.isOutsideKotlinAwareSourceRoot import org.jetbrains.kotlin.idea.util.IdeDescriptorRenderers import org.jetbrains.kotlin.idea.util.ProgressIndicatorUtils.underModalProgress import org.jetbrains.kotlin.idea.util.actualsForExpected import org.jetbrains.kotlin.idea.util.application.invokeLater import org.jetbrains.kotlin.idea.util.application.isUnitTestMode import org.jetbrains.kotlin.idea.util.liftToExpected import org.jetbrains.kotlin.idea.util.string.collapseSpaces import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.name.FqNameUnsafe import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.* import org.jetbrains.kotlin.renderer.DescriptorRenderer import org.jetbrains.kotlin.resolve.* import org.jetbrains.kotlin.resolve.calls.util.getCallWithAssert import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.resolve.scopes.receivers.ImplicitReceiver import org.jetbrains.kotlin.resolve.source.getPsi import org.jetbrains.kotlin.types.typeUtil.unCapture import java.lang.annotation.Retention import java.util.* import javax.swing.Icon import kotlin.math.min import org.jetbrains.kotlin.idea.core.util.getLineCount as newGetLineCount import org.jetbrains.kotlin.idea.core.util.toPsiDirectory as newToPsiDirectory import org.jetbrains.kotlin.idea.core.util.toPsiFile as newToPsiFile const val CHECK_SUPER_METHODS_YES_NO_DIALOG = "CHECK_SUPER_METHODS_YES_NO_DIALOG" @JvmOverloads fun getOrCreateKotlinFile( fileName: String, targetDir: PsiDirectory, packageName: String? = targetDir.getFqNameWithImplicitPrefix()?.asString() ): KtFile = (targetDir.findFile(fileName) ?: createKotlinFile(fileName, targetDir, packageName)) as KtFile fun createKotlinFile( fileName: String, targetDir: PsiDirectory, packageName: String? = targetDir.getFqNameWithImplicitPrefix()?.asString() ): KtFile { targetDir.checkCreateFile(fileName) val packageFqName = packageName?.let(::FqName) ?: FqName.ROOT val file = PsiFileFactory.getInstance(targetDir.project).createFileFromText( fileName, KotlinFileType.INSTANCE, if (!packageFqName.isRoot) "package ${packageFqName.quoteSegmentsIfNeeded()} \n\n" else "" ) return targetDir.add(file) as KtFile } fun PsiElement.getUsageContext(): PsiElement { return when (this) { is KtElement -> PsiTreeUtil.getParentOfType( this, KtPropertyAccessor::class.java, KtProperty::class.java, KtNamedFunction::class.java, KtConstructor::class.java, KtClassOrObject::class.java ) ?: containingFile else -> ConflictsUtil.getContainer(this) } } fun PsiElement.isInKotlinAwareSourceRoot(): Boolean = !isOutsideKotlinAwareSourceRoot(containingFile) fun KtFile.createTempCopy(text: String? = null): KtFile { val tmpFile = KtPsiFactory(this).createAnalyzableFile(name, text ?: this.text ?: "", this) tmpFile.originalFile = this return tmpFile } fun PsiElement.getAllExtractionContainers(strict: Boolean = true): List<KtElement> { val containers = ArrayList<KtElement>() var objectOrNonInnerNestedClassFound = false val parents = if (strict) parents else parentsWithSelf for (element in parents) { val isValidContainer = when (element) { is KtFile -> true is KtClassBody -> !objectOrNonInnerNestedClassFound || element.parent is KtObjectDeclaration is KtBlockExpression -> !objectOrNonInnerNestedClassFound else -> false } if (!isValidContainer) continue containers.add(element as KtElement) if (!objectOrNonInnerNestedClassFound) { val bodyParent = (element as? KtClassBody)?.parent objectOrNonInnerNestedClassFound = (bodyParent is KtObjectDeclaration && !bodyParent.isObjectLiteral()) || (bodyParent is KtClass && !bodyParent.isInner()) } } return containers } fun PsiElement.getExtractionContainers(strict: Boolean = true, includeAll: Boolean = false): List<KtElement> { fun getEnclosingDeclaration(element: PsiElement, strict: Boolean): PsiElement? { return (if (strict) element.parents else element.parentsWithSelf) .filter { (it is KtDeclarationWithBody && it !is KtFunctionLiteral && !(it is KtNamedFunction && it.name == null)) || it is KtAnonymousInitializer || it is KtClassBody || it is KtFile } .firstOrNull() } if (includeAll) return getAllExtractionContainers(strict) val enclosingDeclaration = getEnclosingDeclaration(this, strict)?.let { if (it is KtDeclarationWithBody || it is KtAnonymousInitializer) getEnclosingDeclaration(it, true) else it } return when (enclosingDeclaration) { is KtFile -> Collections.singletonList(enclosingDeclaration) is KtClassBody -> getAllExtractionContainers(strict).filterIsInstance<KtClassBody>() else -> { val targetContainer = when (enclosingDeclaration) { is KtDeclarationWithBody -> enclosingDeclaration.bodyExpression is KtAnonymousInitializer -> enclosingDeclaration.body else -> null } if (targetContainer is KtBlockExpression) Collections.singletonList(targetContainer) else Collections.emptyList() } } } fun Project.checkConflictsInteractively( conflicts: MultiMap<PsiElement, String>, onShowConflicts: () -> Unit = {}, onAccept: () -> Unit ) { if (!conflicts.isEmpty) { if (isUnitTestMode()) throw ConflictsInTestsException(conflicts.values()) val dialog = ConflictsDialog(this, conflicts) { onAccept() } dialog.show() if (!dialog.isOK) { if (dialog.isShowConflicts) { onShowConflicts() } return } } onAccept() } fun reportDeclarationConflict( conflicts: MultiMap<PsiElement, String>, declaration: PsiElement, message: (renderedDeclaration: String) -> String ) { conflicts.putValue(declaration, message(RefactoringUIUtil.getDescription(declaration, true).capitalize())) } fun <T : PsiElement> getPsiElementPopup( editor: Editor, elements: List<T>, renderer: PsiElementListCellRenderer<T>, title: String?, highlightSelection: Boolean, processor: (T) -> Boolean ): JBPopup = with(JBPopupFactory.getInstance().createPopupChooserBuilder(elements)) { val highlighter = if (highlightSelection) SelectionAwareScopeHighlighter(editor) else null setRenderer(renderer) setItemSelectedCallback { element: T? -> highlighter?.dropHighlight() element?.let { highlighter?.highlight(element) } } title?.let { setTitle(it) } renderer.installSpeedSearch(this, true) setItemChosenCallback { it?.let(processor) } addListener(object : JBPopupListener { override fun onClosed(event: LightweightWindowEvent) { highlighter?.dropHighlight() } }) createPopup() } class SelectionAwareScopeHighlighter(val editor: Editor) { private val highlighters = ArrayList<RangeHighlighter>() private fun addHighlighter(r: TextRange, attr: TextAttributes) { highlighters.add( editor.markupModel.addRangeHighlighter( r.startOffset, r.endOffset, UnwrapHandler.HIGHLIGHTER_LEVEL, attr, HighlighterTargetArea.EXACT_RANGE ) ) } fun highlight(wholeAffected: PsiElement) { dropHighlight() val affectedRange = wholeAffected.textRange ?: return val attributes = EditorColorsManager.getInstance().globalScheme.getAttributes(EditorColors.SEARCH_RESULT_ATTRIBUTES)!! val selectedRange = with(editor.selectionModel) { TextRange(selectionStart, selectionEnd) } val textLength = editor.document.textLength for (r in RangeSplitter.split(affectedRange, Collections.singletonList(selectedRange))) { if (r.endOffset <= textLength) addHighlighter(r, attributes) } } fun dropHighlight() { highlighters.forEach { it.dispose() } highlighters.clear() } } @Deprecated( "Use org.jetbrains.kotlin.idea.core.util.getLineStartOffset() instead", ReplaceWith("this.getLineStartOffset(line)", "org.jetbrains.kotlin.idea.core.util.getLineStartOffset"), DeprecationLevel.ERROR ) fun PsiFile.getLineStartOffset(line: Int): Int? { val doc = viewProvider.document ?: PsiDocumentManager.getInstance(project).getDocument(this) if (doc != null && line >= 0 && line < doc.lineCount) { val startOffset = doc.getLineStartOffset(line) val element = findElementAt(startOffset) ?: return startOffset if (element is PsiWhiteSpace || element is PsiComment) { return PsiTreeUtil.skipSiblingsForward(element, PsiWhiteSpace::class.java, PsiComment::class.java)?.startOffset ?: startOffset } return startOffset } return null } @Deprecated( "Use org.jetbrains.kotlin.idea.core.util.getLineEndOffset() instead", ReplaceWith("this.getLineEndOffset(line)", "org.jetbrains.kotlin.idea.core.util.getLineEndOffset"), DeprecationLevel.ERROR ) fun PsiFile.getLineEndOffset(line: Int): Int? { val document = viewProvider.document ?: PsiDocumentManager.getInstance(project).getDocument(this) return document?.getLineEndOffset(line) } fun PsiElement.getLineNumber(start: Boolean = true): Int { val document = containingFile.viewProvider.document ?: PsiDocumentManager.getInstance(project).getDocument(containingFile) val index = if (start) this.startOffset else this.endOffset if (index > (document?.textLength ?: 0)) return 0 return document?.getLineNumber(index) ?: 0 } class SeparateFileWrapper(manager: PsiManager) : LightElement(manager, KotlinLanguage.INSTANCE) { override fun toString() = "" } fun <T> chooseContainerElement( containers: List<T>, editor: Editor, title: String, highlightSelection: Boolean, toPsi: (T) -> PsiElement, onSelect: (T) -> Unit ) { val psiElements = containers.map(toPsi) choosePsiContainerElement( elements = psiElements, editor = editor, title = title, highlightSelection = highlightSelection, psi2Container = { containers[psiElements.indexOf(it)] }, onSelect = onSelect ) } fun <T : PsiElement> chooseContainerElement( elements: List<T>, editor: Editor, title: String, highlightSelection: Boolean, onSelect: (T) -> Unit ): Unit = choosePsiContainerElement( elements = elements, editor = editor, title = title, highlightSelection = highlightSelection, psi2Container = { it }, onSelect = onSelect, ) private fun psiElementRenderer() = object : PsiElementListCellRenderer<PsiElement>() { private fun PsiElement.renderName(): String = when { this is KtPropertyAccessor -> property.renderName() + if (isGetter) ".get" else ".set" this is KtObjectDeclaration && isCompanion() -> { val name = getStrictParentOfType<KtClassOrObject>()?.renderName() ?: "<anonymous>" "Companion object of $name" } else -> (this as? PsiNamedElement)?.name ?: "<anonymous>" } private fun PsiElement.renderDeclaration(): String? { if (this is KtFunctionLiteral || isFunctionalExpression()) return renderText() val descriptor = when (this) { is KtFile -> name is KtElement -> analyze()[BindingContext.DECLARATION_TO_DESCRIPTOR, this] is PsiMember -> getJavaMemberDescriptor() else -> null } ?: return null val name = renderName() val params = (descriptor as? FunctionDescriptor)?.valueParameters?.joinToString( ", ", "(", ")" ) { DescriptorRenderer.SHORT_NAMES_IN_TYPES.renderType(it.type) } ?: "" return "$name$params" } private fun PsiElement.renderText(): String = when (this) { is SeparateFileWrapper -> KotlinBundle.message("refactoring.extract.to.separate.file.text") is PsiPackageBase -> qualifiedName else -> { val text = text ?: "<invalid text>" StringUtil.shortenTextWithEllipsis(text.collapseSpaces(), 53, 0) } } private fun PsiElement.getRepresentativeElement(): PsiElement = when (this) { is KtBlockExpression -> (parent as? KtDeclarationWithBody) ?: this is KtClassBody -> parent as KtClassOrObject else -> this } override fun getElementText(element: PsiElement): String { val representativeElement = element.getRepresentativeElement() return representativeElement.renderDeclaration() ?: representativeElement.renderText() } override fun getContainerText(element: PsiElement, name: String?): String? = null override fun getIcon(element: PsiElement): Icon? = super.getIcon(element.getRepresentativeElement()) } private fun <T, E : PsiElement> choosePsiContainerElement( elements: List<E>, editor: Editor, title: String, highlightSelection: Boolean, psi2Container: (E) -> T, onSelect: (T) -> Unit, ) { val popup = getPsiElementPopup( editor, elements, psiElementRenderer(), title, highlightSelection, ) { psiElement -> @Suppress("UNCHECKED_CAST") onSelect(psi2Container(psiElement as E)) true } invokeLater { popup.showInBestPositionFor(editor) } } fun <T> chooseContainerElementIfNecessary( containers: List<T>, editor: Editor, title: String, highlightSelection: Boolean, toPsi: (T) -> PsiElement, onSelect: (T) -> Unit ): Unit = chooseContainerElementIfNecessaryImpl(containers, editor, title, highlightSelection, toPsi, onSelect) fun <T : PsiElement> chooseContainerElementIfNecessary( containers: List<T>, editor: Editor, title: String, highlightSelection: Boolean, onSelect: (T) -> Unit ): Unit = chooseContainerElementIfNecessaryImpl(containers, editor, title, highlightSelection, null, onSelect) private fun <T> chooseContainerElementIfNecessaryImpl( containers: List<T>, editor: Editor, title: String, highlightSelection: Boolean, toPsi: ((T) -> PsiElement)?, onSelect: (T) -> Unit ) { when { containers.isEmpty() -> return containers.size == 1 || isUnitTestMode() -> onSelect(containers.first()) toPsi != null -> chooseContainerElement(containers, editor, title, highlightSelection, toPsi, onSelect) else -> { @Suppress("UNCHECKED_CAST") chooseContainerElement(containers as List<PsiElement>, editor, title, highlightSelection, onSelect as (PsiElement) -> Unit) } } } fun PsiElement.isTrueJavaMethod(): Boolean = this is PsiMethod && this !is KtLightMethod fun PsiElement.canRefactor(): Boolean { return when { !isValid -> false this is PsiPackage -> directories.any { it.canRefactor() } this is KtElement || this is PsiMember && language == JavaLanguage.INSTANCE || this is PsiDirectory -> RootKindFilter.projectSources.copy(includeScriptsOutsideSourceRoots = true).matches(this) else -> false } } private fun copyModifierListItems(from: PsiModifierList, to: PsiModifierList, withPsiModifiers: Boolean = true) { if (withPsiModifiers) { for (modifier in PsiModifier.MODIFIERS) { if (from.hasExplicitModifier(modifier)) { to.setModifierProperty(modifier, true) } } } for (annotation in from.annotations) { val annotationName = annotation.qualifiedName ?: continue if (Retention::class.java.name != annotationName) { to.addAnnotation(annotationName) } } } private fun <T> copyTypeParameters( from: T, to: T, inserter: (T, PsiTypeParameterList) -> Unit ) where T : PsiTypeParameterListOwner, T : PsiNameIdentifierOwner { val factory = PsiElementFactory.getInstance((from as PsiElement).project) val templateTypeParams = from.typeParameterList?.typeParameters ?: PsiTypeParameter.EMPTY_ARRAY if (templateTypeParams.isNotEmpty()) { inserter(to, factory.createTypeParameterList()) val targetTypeParamList = to.typeParameterList val newTypeParams = templateTypeParams.map { factory.createTypeParameter(it.name!!, it.extendsList.referencedTypes) } ChangeSignatureUtil.synchronizeList( targetTypeParamList, newTypeParams, { it!!.typeParameters.toList() }, BooleanArray(newTypeParams.size) ) } } fun createJavaMethod(function: KtFunction, targetClass: PsiClass): PsiMethod { val template = LightClassUtil.getLightClassMethod(function) ?: throw AssertionError("Can't generate light method: ${function.getElementTextWithContext()}") return createJavaMethod(template, targetClass) } fun createJavaMethod(template: PsiMethod, targetClass: PsiClass): PsiMethod { val factory = PsiElementFactory.getInstance(template.project) val methodToAdd = if (template.isConstructor) { factory.createConstructor(template.name) } else { factory.createMethod(template.name, template.returnType) } val method = targetClass.add(methodToAdd) as PsiMethod copyModifierListItems(template.modifierList, method.modifierList) if (targetClass.isInterface) { method.modifierList.setModifierProperty(PsiModifier.FINAL, false) } copyTypeParameters(template, method) { psiMethod, typeParameterList -> psiMethod.addAfter(typeParameterList, psiMethod.modifierList) } val targetParamList = method.parameterList val newParams = template.parameterList.parameters.map { val param = factory.createParameter(it.name, it.type) copyModifierListItems(it.modifierList!!, param.modifierList!!) param } ChangeSignatureUtil.synchronizeList( targetParamList, newParams, { it.parameters.toList() }, BooleanArray(newParams.size) ) if (template.modifierList.hasModifierProperty(PsiModifier.ABSTRACT) || targetClass.isInterface) { method.body!!.delete() } else if (!template.isConstructor) { CreateFromUsageUtils.setupMethodBody(method) } return method } fun createJavaField(property: KtNamedDeclaration, targetClass: PsiClass): PsiField { val accessorLightMethods = property.getAccessorLightMethods() val template = accessorLightMethods.getter ?: throw AssertionError("Can't generate light method: ${property.getElementTextWithContext()}") val factory = PsiElementFactory.getInstance(template.project) val field = targetClass.add(factory.createField(property.name!!, template.returnType!!)) as PsiField with(field.modifierList!!) { val templateModifiers = template.modifierList setModifierProperty(VisibilityUtil.getVisibilityModifier(templateModifiers), true) if ((property as KtValVarKeywordOwner).valOrVarKeyword.toValVar() != KotlinValVar.Var || targetClass.isInterface) { setModifierProperty(PsiModifier.FINAL, true) } copyModifierListItems(templateModifiers, this, false) } return field } fun createJavaClass(klass: KtClass, targetClass: PsiClass?, forcePlainClass: Boolean = false): PsiClass { val kind = if (forcePlainClass) ClassKind.CLASS else (klass.unsafeResolveToDescriptor() as ClassDescriptor).kind val factory = PsiElementFactory.getInstance(klass.project) val className = klass.name!! val javaClassToAdd = when (kind) { ClassKind.CLASS -> factory.createClass(className) ClassKind.INTERFACE -> factory.createInterface(className) ClassKind.ANNOTATION_CLASS -> factory.createAnnotationType(className) ClassKind.ENUM_CLASS -> factory.createEnum(className) else -> throw AssertionError("Unexpected class kind: ${klass.getElementTextWithContext()}") } val javaClass = (targetClass?.add(javaClassToAdd) ?: javaClassToAdd) as PsiClass val template = klass.toLightClass() ?: throw AssertionError("Can't generate light class: ${klass.getElementTextWithContext()}") copyModifierListItems(template.modifierList!!, javaClass.modifierList!!) if (template.isInterface) { javaClass.modifierList!!.setModifierProperty(PsiModifier.ABSTRACT, false) } copyTypeParameters(template, javaClass) { clazz, typeParameterList -> clazz.addAfter(typeParameterList, clazz.nameIdentifier) } // Turning interface to class if (!javaClass.isInterface && template.isInterface) { val implementsList = factory.createReferenceListWithRole( template.extendsList?.referenceElements ?: PsiJavaCodeReferenceElement.EMPTY_ARRAY, PsiReferenceList.Role.IMPLEMENTS_LIST ) implementsList?.let { javaClass.implementsList?.replace(it) } } else { val extendsList = factory.createReferenceListWithRole( template.extendsList?.referenceElements ?: PsiJavaCodeReferenceElement.EMPTY_ARRAY, PsiReferenceList.Role.EXTENDS_LIST ) extendsList?.let { javaClass.extendsList?.replace(it) } val implementsList = factory.createReferenceListWithRole( template.implementsList?.referenceElements ?: PsiJavaCodeReferenceElement.EMPTY_ARRAY, PsiReferenceList.Role.IMPLEMENTS_LIST ) implementsList?.let { javaClass.implementsList?.replace(it) } } for (method in template.methods) { if (isSyntheticValuesOrValueOfMethod(method)) continue val hasParams = method.parameterList.parametersCount > 0 val needSuperCall = !template.isEnum && (template.superClass?.constructors ?: PsiMethod.EMPTY_ARRAY).all { it.parameterList.parametersCount > 0 } if (method.isConstructor && !(hasParams || needSuperCall)) continue with(createJavaMethod(method, javaClass)) { if (isConstructor && needSuperCall) { body!!.add(factory.createStatementFromText("super();", this)) } } } return javaClass } internal fun broadcastRefactoringExit(project: Project, refactoringId: String) { project.messageBus.syncPublisher(KotlinRefactoringEventListener.EVENT_TOPIC).onRefactoringExit(refactoringId) } // IMPORTANT: Target refactoring must support KotlinRefactoringEventListener internal abstract class CompositeRefactoringRunner( val project: Project, val refactoringId: String ) { protected abstract fun runRefactoring() protected open fun onRefactoringDone() {} protected open fun onExit() {} fun run() { val connection = project.messageBus.connect() connection.subscribe( RefactoringEventListener.REFACTORING_EVENT_TOPIC, object : RefactoringEventListener { override fun undoRefactoring(refactoringId: String) { } override fun refactoringStarted(refactoringId: String, beforeData: RefactoringEventData?) { } override fun conflictsDetected(refactoringId: String, conflictsData: RefactoringEventData) { } override fun refactoringDone(refactoringId: String, afterData: RefactoringEventData?) { if (refactoringId == [email protected]) { onRefactoringDone() } } } ) connection.subscribe( KotlinRefactoringEventListener.EVENT_TOPIC, object : KotlinRefactoringEventListener { override fun onRefactoringExit(refactoringId: String) { if (refactoringId == [email protected]) { try { onExit() } finally { connection.disconnect() } } } } ) runRefactoring() } } @Throws(ConfigurationException::class) fun KtElement?.validateElement(@NlsContexts.DialogMessage errorMessage: String) { if (this == null) throw ConfigurationException(errorMessage) try { AnalyzingUtils.checkForSyntacticErrors(this) } catch (e: Exception) { throw ConfigurationException(errorMessage) } } fun invokeOnceOnCommandFinish(action: () -> Unit) { val simpleConnect = ApplicationManager.getApplication().messageBus.simpleConnect() simpleConnect.subscribe(CommandListener.TOPIC, object : CommandListener { override fun beforeCommandFinished(event: CommandEvent) { action() simpleConnect.disconnect() } }) } fun FqNameUnsafe.hasIdentifiersOnly(): Boolean = pathSegments().all { it.asString().quoteIfNeeded().isIdentifier() } fun FqName.hasIdentifiersOnly(): Boolean = pathSegments().all { it.asString().quoteIfNeeded().isIdentifier() } fun PsiNamedElement.isInterfaceClass(): Boolean = when (this) { is KtClass -> isInterface() is PsiClass -> isInterface is KtPsiClassWrapper -> psiClass.isInterface else -> false } fun KtNamedDeclaration.isAbstract(): Boolean = when { hasModifier(KtTokens.ABSTRACT_KEYWORD) -> true containingClassOrObject?.isInterfaceClass() != true -> false this is KtProperty -> initializer == null && delegate == null && accessors.isEmpty() this is KtNamedFunction -> !hasBody() else -> false } fun KtNamedDeclaration.isConstructorDeclaredProperty() = this is KtParameter && ownerFunction is KtPrimaryConstructor && hasValOrVar() fun <ListType : KtElement> replaceListPsiAndKeepDelimiters( changeInfo: KotlinChangeInfo, originalList: ListType, newList: ListType, @Suppress("UNCHECKED_CAST") listReplacer: ListType.(ListType) -> ListType = { replace(it) as ListType }, itemsFun: ListType.() -> List<KtElement> ): ListType { originalList.children.takeWhile { it is PsiErrorElement }.forEach { it.delete() } val oldParameters = originalList.itemsFun().toMutableList() val newParameters = newList.itemsFun() val oldCount = oldParameters.size val newCount = newParameters.size val commonCount = min(oldCount, newCount) val originalIndexes = changeInfo.newParameters.map { it.originalIndex } val keepComments = originalList.allChildren.any { it is PsiComment } && oldCount > commonCount && originalIndexes == originalIndexes.sorted() if (!keepComments) { for (i in 0 until commonCount) { oldParameters[i] = oldParameters[i].replace(newParameters[i]) as KtElement } } if (commonCount == 0 && !keepComments) return originalList.listReplacer(newList) if (oldCount > commonCount) { if (keepComments) { ((0 until oldParameters.size) - originalIndexes).forEach { index -> val oldParameter = oldParameters[index] val nextComma = oldParameter.getNextSiblingIgnoringWhitespaceAndComments()?.takeIf { it.node.elementType == KtTokens.COMMA } if (nextComma != null) { nextComma.delete() } else { oldParameter.getPrevSiblingIgnoringWhitespaceAndComments()?.takeIf { it.node.elementType == KtTokens.COMMA }?.delete() } oldParameter.delete() } } else { originalList.deleteChildRange(oldParameters[commonCount - 1].nextSibling, oldParameters.last()) } } else if (newCount > commonCount) { val lastOriginalParameter = oldParameters.last() val psiBeforeLastParameter = lastOriginalParameter.prevSibling val withMultiline = (psiBeforeLastParameter is PsiWhiteSpace || psiBeforeLastParameter is PsiComment) && psiBeforeLastParameter.textContains('\n') val extraSpace = if (withMultiline) KtPsiFactory(originalList).createNewLine() else null originalList.addRangeAfter(newParameters[commonCount - 1].nextSibling, newParameters.last(), lastOriginalParameter) if (extraSpace != null) { val addedItems = originalList.itemsFun().subList(commonCount, newCount) for (addedItem in addedItems) { val elementBefore = addedItem.prevSibling if ((elementBefore !is PsiWhiteSpace && elementBefore !is PsiComment) || !elementBefore.textContains('\n')) { addedItem.parent.addBefore(extraSpace, addedItem) } } } } return originalList } fun <T> Pass(body: (T) -> Unit) = object : Pass<T>() { override fun pass(t: T) = body(t) } fun KtExpression.removeTemplateEntryBracesIfPossible(): KtExpression { val parent = parent as? KtBlockStringTemplateEntry ?: return this return parent.dropCurlyBracketsIfPossible().expression!! } fun dropOverrideKeywordIfNecessary(element: KtNamedDeclaration) { val callableDescriptor = element.resolveToDescriptorIfAny() as? CallableDescriptor ?: return if (callableDescriptor.overriddenDescriptors.isEmpty()) { element.removeModifier(KtTokens.OVERRIDE_KEYWORD) } } fun dropOperatorKeywordIfNecessary(element: KtNamedDeclaration) { val callableDescriptor = element.resolveToDescriptorIfAny() as? CallableDescriptor ?: return val diagnosticHolder = BindingTraceContext() OperatorModifierChecker.check(element, callableDescriptor, diagnosticHolder, element.languageVersionSettings) if (diagnosticHolder.bindingContext.diagnostics.any { it.factory == Errors.INAPPLICABLE_OPERATOR_MODIFIER }) { element.removeModifier(KtTokens.OPERATOR_KEYWORD) } } fun getQualifiedTypeArgumentList(initializer: KtExpression): KtTypeArgumentList? { val call = initializer.resolveToCall() ?: return null val typeArgumentMap = call.typeArguments val typeArguments = call.candidateDescriptor.typeParameters.mapNotNull { typeArgumentMap[it] } val renderedList = typeArguments.joinToString(prefix = "<", postfix = ">") { IdeDescriptorRenderers.SOURCE_CODE_NOT_NULL_TYPE_APPROXIMATION.renderType(it.unCapture()) } return KtPsiFactory(initializer).createTypeArguments(renderedList) } fun addTypeArgumentsIfNeeded(expression: KtExpression, typeArgumentList: KtTypeArgumentList) { val context = expression.analyze(BodyResolveMode.PARTIAL_WITH_DIAGNOSTICS) val call = expression.getCallWithAssert(context) val callElement = call.callElement as? KtCallExpression ?: return if (call.typeArgumentList != null) return val callee = call.calleeExpression ?: return if (context.diagnostics.forElement(callee).all { it.factory != Errors.TYPE_INFERENCE_NO_INFORMATION_FOR_PARAMETER && it.factory != Errors.NEW_INFERENCE_NO_INFORMATION_FOR_PARAMETER } ) { return } callElement.addAfter(typeArgumentList, callElement.calleeExpression) ShortenReferences.DEFAULT.process(callElement.typeArgumentList!!) } internal fun DeclarationDescriptor.getThisLabelName(): String { if (!name.isSpecial) return name.asString() if (this is AnonymousFunctionDescriptor) { val function = source.getPsi() as? KtFunction val argument = function?.parent as? KtValueArgument ?: (function?.parent as? KtLambdaExpression)?.parent as? KtValueArgument val callElement = argument?.getStrictParentOfType<KtCallElement>() val callee = callElement?.calleeExpression as? KtSimpleNameExpression if (callee != null) return callee.text } return "" } internal fun DeclarationDescriptor.explicateAsTextForReceiver(): String { val labelName = getThisLabelName() return if (labelName.isEmpty()) "this" else "this@$labelName" } internal fun ImplicitReceiver.explicateAsText(): String { return declarationDescriptor.explicateAsTextForReceiver() } val PsiFile.isInjectedFragment: Boolean get() = InjectedLanguageManager.getInstance(project).isInjectedFragment(this) val PsiElement.isInsideInjectedFragment: Boolean get() = containingFile.isInjectedFragment fun checkSuperMethods( declaration: KtDeclaration, ignore: Collection<PsiElement>?, @Nls actionString: String ): List<PsiElement> { if (!declaration.hasModifier(KtTokens.OVERRIDE_KEYWORD)) return listOf(declaration) val (declarationDescriptor, overriddenElementsToDescriptor) = getSuperDescriptors(declaration, ignore) if (overriddenElementsToDescriptor.isEmpty()) return listOf(declaration) fun getClassDescriptions(overriddenElementsToDescriptor: Map<PsiElement, CallableDescriptor>): List<String> { return overriddenElementsToDescriptor.entries.map { entry -> val (element, descriptor) = entry val description = when (element) { is KtNamedFunction, is KtProperty, is KtParameter -> formatClassDescriptor(descriptor.containingDeclaration) is PsiMethod -> { val psiClass = element.containingClass ?: error("Invalid element: ${element.getText()}") formatPsiClass(psiClass, markAsJava = true, inCode = false) } else -> error("Unexpected element: ${element.getElementTextWithContext()}") } " $description\n" } } fun askUserForMethodsToSearch( declarationDescriptor: CallableDescriptor, overriddenElementsToDescriptor: Map<PsiElement, CallableDescriptor> ): List<PsiElement> { val superClassDescriptions = getClassDescriptions(overriddenElementsToDescriptor) val message = KotlinBundle.message( "override.declaration.x.overrides.y.in.class.list", DescriptorRenderer.COMPACT_WITH_SHORT_TYPES.render(declarationDescriptor), "\n${superClassDescriptions.joinToString(separator = "")}", actionString ) val exitCode = showYesNoCancelDialog( CHECK_SUPER_METHODS_YES_NO_DIALOG, declaration.project, message, IdeBundle.message("title.warning"), Messages.getQuestionIcon(), Messages.YES ) return when (exitCode) { Messages.YES -> overriddenElementsToDescriptor.keys.toList() Messages.NO -> listOf(declaration) else -> emptyList() } } return askUserForMethodsToSearch(declarationDescriptor, overriddenElementsToDescriptor) } private fun getSuperDescriptors(declaration: KtDeclaration, ignore: Collection<PsiElement>?) = underModalProgress( declaration.project, KotlinBundle.message("find.usages.progress.text.declaration.superMethods") ) { val declarationDescriptor = declaration.unsafeResolveToDescriptor() as CallableDescriptor if (declarationDescriptor is LocalVariableDescriptor) return@underModalProgress (declarationDescriptor to emptyMap<PsiElement, CallableDescriptor>()) val overriddenElementsToDescriptor = HashMap<PsiElement, CallableDescriptor>() for (overriddenDescriptor in DescriptorUtils.getAllOverriddenDescriptors( declarationDescriptor )) { val overriddenDeclaration = DescriptorToSourceUtilsIde.getAnyDeclaration( declaration.project, overriddenDescriptor ) ?: continue if (overriddenDeclaration is KtNamedFunction || overriddenDeclaration is KtProperty || overriddenDeclaration is PsiMethod || overriddenDeclaration is KtParameter) { overriddenElementsToDescriptor[overriddenDeclaration] = overriddenDescriptor } } if (ignore != null) { overriddenElementsToDescriptor.keys.removeAll(ignore) } (declarationDescriptor to overriddenElementsToDescriptor) } fun getSuperMethods(declaration: KtDeclaration, ignore: Collection<PsiElement>?): List<PsiElement> { if (!declaration.hasModifier(KtTokens.OVERRIDE_KEYWORD)) return listOf(declaration) val (_, overriddenElementsToDescriptor) = getSuperDescriptors(declaration, ignore) return if (overriddenElementsToDescriptor.isEmpty()) listOf(declaration) else overriddenElementsToDescriptor.keys.toList() } fun checkSuperMethodsWithPopup( declaration: KtNamedDeclaration, deepestSuperMethods: List<PsiElement>, editor: Editor, action: (List<PsiElement>) -> Unit ) { if (deepestSuperMethods.isEmpty()) return action(listOf(declaration)) val superMethod = deepestSuperMethods.first() val (superClass, isAbstract) = when (superMethod) { is PsiMember -> superMethod.containingClass to superMethod.hasModifierProperty(PsiModifier.ABSTRACT) is KtNamedDeclaration -> superMethod.containingClassOrObject to superMethod.isAbstract() else -> null } ?: return action(listOf(declaration)) if (superClass == null) return action(listOf(declaration)) if (isUnitTestMode()) return action(deepestSuperMethods) val kindIndex = when (declaration) { is KtNamedFunction -> 1 // "function" is KtProperty, is KtParameter -> 2 // "property" else -> return } val unwrappedSupers = deepestSuperMethods.mapNotNull { it.namedUnwrappedElement } val hasJavaMethods = unwrappedSupers.any { it is PsiMethod } val hasKtMembers = unwrappedSupers.any { it is KtNamedDeclaration } val superKindIndex = when { hasJavaMethods && hasKtMembers -> 3 // "member" hasJavaMethods -> 4 // "method" else -> kindIndex } val renameBase = KotlinBundle.message("rename.base.0", superKindIndex + (if (deepestSuperMethods.size > 1) 10 else 0)) val renameCurrent = KotlinBundle.message("rename.only.current.0", kindIndex) val title = KotlinBundle.message( "rename.declaration.title.0.implements.1.2.of.3", declaration.name ?: "", if (isAbstract) 1 else 2, ElementDescriptionUtil.getElementDescription(superMethod, UsageViewTypeLocation.INSTANCE), SymbolPresentationUtil.getSymbolPresentableText(superClass) ) JBPopupFactory.getInstance() .createPopupChooserBuilder(listOf(renameBase, renameCurrent)) .setTitle(title) .setMovable(false) .setResizable(false) .setRequestFocus(true) .setItemChosenCallback { value: String? -> if (value == null) return@setItemChosenCallback val chosenElements = if (value == renameBase) deepestSuperMethods + declaration else listOf(declaration) action(chosenElements) } .createPopup() .showInBestPositionFor(editor) } fun KtNamedDeclaration.isCompanionMemberOf(klass: KtClassOrObject): Boolean { val containingObject = containingClassOrObject as? KtObjectDeclaration ?: return false return containingObject.isCompanion() && containingObject.containingClassOrObject == klass } internal fun KtDeclaration.withExpectedActuals(): List<KtDeclaration> { val expect = liftToExpected() ?: return listOf(this) val actuals = expect.actualsForExpected() return listOf(expect) + actuals } internal fun KtDeclaration.resolveToExpectedDescriptorIfPossible(): DeclarationDescriptor { val descriptor = unsafeResolveToDescriptor() return descriptor.liftToExpected() ?: descriptor } fun DialogWrapper.showWithTransaction() { TransactionGuard.submitTransaction(disposable, Runnable { show() }) } fun PsiMethod.checkDeclarationConflict(name: String, conflicts: MultiMap<PsiElement, String>, callables: Collection<PsiElement>) { containingClass ?.findMethodsByName(name, true) // as is necessary here: see KT-10386 ?.firstOrNull { it.parameterList.parametersCount == 0 && !callables.contains(it.namedUnwrappedElement as PsiElement?) } ?.let { reportDeclarationConflict(conflicts, it) { s -> "$s already exists" } } } fun <T : KtExpression> T.replaceWithCopyWithResolveCheck( resolveStrategy: (T, BindingContext) -> DeclarationDescriptor?, context: BindingContext = analyze(), preHook: T.() -> Unit = {}, postHook: T.() -> T? = { this } ): T? { val originDescriptor = resolveStrategy(this, context) ?: return null @Suppress("UNCHECKED_CAST") val elementCopy = copy() as T elementCopy.preHook() val newContext = elementCopy.analyzeAsReplacement(this, context) val newDescriptor = resolveStrategy(elementCopy, newContext) ?: return null return if (originDescriptor.canonicalRender() == newDescriptor.canonicalRender()) elementCopy.postHook() else null } @Deprecated( "Use org.jetbrains.kotlin.idea.core.util.getLineCount() instead", ReplaceWith("this.getLineCount()", "org.jetbrains.kotlin.idea.core.util.getLineCount"), DeprecationLevel.ERROR ) fun PsiElement.getLineCount(): Int { return newGetLineCount() } @Deprecated( "Use org.jetbrains.kotlin.idea.core.util.toPsiDirectory() instead", ReplaceWith("this.toPsiDirectory(project)", "org.jetbrains.kotlin.idea.core.util.toPsiDirectory"), DeprecationLevel.ERROR ) fun VirtualFile.toPsiDirectory(project: Project): PsiDirectory? { return newToPsiDirectory(project) } @Deprecated( "Use org.jetbrains.kotlin.idea.core.util.toPsiFile() instead", ReplaceWith("this.toPsiFile(project)", "org.jetbrains.kotlin.idea.core.util.toPsiFile"), DeprecationLevel.ERROR ) fun VirtualFile.toPsiFile(project: Project): PsiFile? { return newToPsiFile(project) }
apache-2.0
ca9da4aeccb7b41dab300201653f7dd1
39.593531
172
0.712498
5.041033
false
false
false
false
Maccimo/intellij-community
platform/build-scripts/groovy/org/jetbrains/intellij/build/impl/productInfo/ProductInfoGenerator.kt
2
2849
// 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.productInfo import kotlinx.serialization.ExperimentalSerializationApi import kotlinx.serialization.Serializable import kotlinx.serialization.json.Json import kotlinx.serialization.serializer import org.jetbrains.intellij.build.BuildContext import org.jetbrains.intellij.build.BuiltinModulesFileData internal const val PRODUCT_INFO_FILE_NAME = "product-info.json" @OptIn(ExperimentalSerializationApi::class) internal val jsonEncoder by lazy { Json { prettyPrint = true prettyPrintIndent = " " encodeDefaults = false explicitNulls = false } } /** * Generates product-info.json file containing meta-information about product installation. */ internal fun generateMultiPlatformProductJson(relativePathToBin: String, builtinModules: BuiltinModulesFileData?, launch: List<ProductInfoLaunchData>, context: BuildContext): String { val appInfo = context.applicationInfo val json = ProductInfoData( name = appInfo.productName, version = appInfo.fullVersion, versionSuffix = appInfo.versionSuffix!!, buildNumber = context.buildNumber, productCode = appInfo.productCode, dataDirectoryName = context.systemSelector, svgIconPath = if (appInfo.svgRelativePath == null) null else "$relativePathToBin/${context.productProperties.baseFileName}.svg", launch = launch, customProperties = context.productProperties.generateCustomPropertiesForProductInfo(), bundledPlugins = builtinModules?.bundledPlugins ?: emptyList(), fileExtensions = builtinModules?.fileExtensions ?: emptyList(), modules = builtinModules?.modules ?: emptyList(), ) return jsonEncoder.encodeToString(serializer(), json) } /** * Describes format of JSON file containing meta-information about a product installation. Must be consistent with 'product-info.schema.json' file. */ @Serializable data class ProductInfoData( val name: String, val version: String, val versionSuffix: String, val buildNumber: String, val productCode: String, val dataDirectoryName: String, val svgIconPath: String?, val launch: List<ProductInfoLaunchData> = emptyList(), val customProperties: List<CustomProperty> = emptyList(), val bundledPlugins: List<String>, val modules: List<String>, val fileExtensions: List<String>, ) @Serializable data class ProductInfoLaunchData( val os: String, val launcherPath: String, val javaExecutablePath: String?, val vmOptionsFilePath: String, val startupWmClass: String? = null, ) @Serializable data class CustomProperty( val key: String, val value: String, )
apache-2.0
d48d1ff0cf30a875df5e20ed3d2e963e
34.185185
147
0.737101
4.895189
false
false
false
false
pyamsoft/pydroid
ui/src/main/java/com/pyamsoft/pydroid/ui/app/PYDroidActivity.kt
1
6621
/* * Copyright 2022 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.pydroid.ui.app import android.os.Bundle import androidx.annotation.CallSuper import androidx.appcompat.app.AppCompatActivity import androidx.lifecycle.lifecycleScope import com.pyamsoft.pydroid.core.Logger import com.pyamsoft.pydroid.core.requireNotNull import com.pyamsoft.pydroid.inject.Injector import com.pyamsoft.pydroid.ui.PYDroidComponent import com.pyamsoft.pydroid.ui.internal.app.AppComponent import com.pyamsoft.pydroid.ui.internal.app.AppInternalViewModeler import com.pyamsoft.pydroid.ui.internal.billing.BillingDelegate import com.pyamsoft.pydroid.ui.internal.changelog.ChangeLogProvider import com.pyamsoft.pydroid.ui.internal.datapolicy.DataPolicyDelegate import com.pyamsoft.pydroid.ui.internal.rating.RatingDelegate import com.pyamsoft.pydroid.ui.internal.version.VersionCheckDelegate import com.pyamsoft.pydroid.util.doOnCreate /** * The base Activity class for PYDroid. * * You are required to extend this class so that other ui bits work. */ public abstract class PYDroidActivity : AppCompatActivity(), ChangeLogProvider { /** Injector component for Dialog and Fragment injection */ private var injector: AppComponent? = null /** DataPolicy Delegate */ internal var dataPolicy: DataPolicyDelegate? = null /** Billing Delegate */ internal var billing: BillingDelegate? = null /** Rating Delegate */ internal var rating: RatingDelegate? = null /** Version Check Delegate */ internal var versionCheck: VersionCheckDelegate? = null /** Presenter */ internal var presenter: AppInternalViewModeler? = null /** Disable the billing component */ protected open val disableBilling: Boolean = false /** Disable the rating component */ protected open val disableRating: Boolean = false /** Disable the version check component */ protected open val disableVersionCheck: Boolean = false /** Disable the data policy component */ protected open val disableDataPolicy: Boolean = false init { connectBilling() connectRating() connectVersionCheck() connectDataPolicy() } private fun showDataPolicyDisclosure() { if (disableDataPolicy) { Logger.w("Application has disabled the Data Policy component") return } // Attempt to show the data policy if we are not disabled dataPolicy.requireNotNull().showDataPolicyDisclosure() } /** Attempts to connect to in-app billing */ private fun connectBilling() { if (disableBilling) { Logger.w("Application has disabled the billing component") return } this.doOnCreate { Logger.d("Attempt Connect Billing") billing.requireNotNull().connect() } } /** Attempts to connect to in-app rating */ private fun connectRating() { if (disableRating) { Logger.w("Application has disabled the Rating component") return } this.doOnCreate { Logger.d("Attempt Connect Rating") rating.requireNotNull().bindEvents() } } /** Attempts to connect to in-app data policy dialog */ private fun connectDataPolicy() { if (disableDataPolicy) { Logger.w("Application has disabled the Data Policy component") return } this.doOnCreate { Logger.d("Attempt Connect Data Policy") dataPolicy.requireNotNull().bindEvents() } } /** Attempts to connect to in-app updates */ private fun connectVersionCheck() { if (disableVersionCheck) { Logger.w("Application has disabled the VersionCheck component") return } this.doOnCreate { Logger.d("Attempt Connect Version Check") versionCheck.requireNotNull().bindEvents() } } /** * Rating Attempt to call in-app rating dialog. Does not always result in showing the Dialog, that * is up to Google */ public fun loadInAppRating() { if (disableRating) { Logger.w("Application has disabled the Rating component") return } rating.requireNotNull().loadInAppRating() } /** Confirm the potential version upgrade */ public fun confirmUpgrade() { if (disableVersionCheck) { Logger.w("Application has disabled the VersionCheck component") return } versionCheck.requireNotNull().handleConfirmUpgrade() } /** Check for in-app updates */ public fun checkUpdates() { if (disableVersionCheck) { Logger.w("Application has disabled the VersionCheck component") return } versionCheck.requireNotNull().checkUpdates() } /** On activity create */ @CallSuper override fun onCreate(savedInstanceState: Bundle?) { // Must inject before super.onCreate or else getSystemService will be called and NPE injector = Injector.obtainFromApplication<PYDroidComponent>(this) .plusApp() .create( activity = this, disableDataPolicy = disableDataPolicy, ) .also { it.inject(this) } super.onCreate(savedInstanceState) } /** Check for updates onStart if possible */ @CallSuper override fun onStart() { super.onStart() checkUpdates() } /** On Resume show changelog if possible */ @CallSuper override fun onPostResume() { super.onPostResume() // DialogFragments cannot be shown safely until at least onPostResume presenter .requireNotNull() .handleShowCorrectDialog( scope = lifecycleScope, onShowDataPolicy = { showDataPolicyDisclosure() }, ) } /** Get system service */ @CallSuper override fun getSystemService(name: String): Any? = when (name) { // Must be defined before super.onCreate() is called or this will be null AppComponent::class.java.name -> injector.requireNotNull() else -> super.getSystemService(name) } /** On activity destroy */ @CallSuper override fun onDestroy() { super.onDestroy() billing = null rating = null versionCheck = null dataPolicy = null injector = null presenter = null } }
apache-2.0
fe24256f950a2eb9657e0f4ce6827336
27.416309
100
0.699441
4.646316
false
false
false
false
JetBrains/ideavim
vim-engine/src/main/kotlin/com/maddyhome/idea/vim/common/DigraphResult.kt
1
1602
/* * 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.common import javax.swing.KeyStroke class DigraphResult { val result: Int val stroke: KeyStroke? var promptCharacter = 0.toChar() private set private constructor(result: Int) { this.result = result stroke = null } private constructor(result: Int, promptCharacter: Char) { this.result = result this.promptCharacter = promptCharacter stroke = null } private constructor(stroke: KeyStroke?) { result = RES_DONE this.stroke = stroke } companion object { const val RES_HANDLED = 0 const val RES_UNHANDLED = 1 const val RES_DONE = 3 const val RES_BAD = 4 @JvmField val HANDLED_DIGRAPH = DigraphResult(RES_HANDLED, '?') @JvmField val HANDLED_LITERAL = DigraphResult(RES_HANDLED, '^') @JvmField val UNHANDLED = DigraphResult(RES_UNHANDLED) @JvmField val BAD = DigraphResult(RES_BAD) @JvmStatic fun done(stroke: KeyStroke?): DigraphResult { // for some reason vim does not let to insert char 10 as a digraph, it inserts 10 instead return if (stroke == null || stroke.keyCode != 10) { DigraphResult(stroke) } else { DigraphResult(KeyStroke.getKeyStroke(0.toChar())) } } @JvmStatic fun handled(promptCharacter: Char): DigraphResult { return DigraphResult(RES_HANDLED, promptCharacter) } } }
mit
32f04587221a04a76fdf648a25815a1e
22.910448
95
0.669788
3.965347
false
false
false
false
TomsUsername/Phoenix
src/main/kotlin/phoenix/bot/pogo/nRnMK9r/util/map/Fort.kt
1
1589
/** * Pokemon Go Bot Copyright (C) 2016 PokemonGoBot-authors (see authors.md for more information) * This program comes with ABSOLUTELY NO WARRANTY; * This is free software, and you are welcome to redistribute it under certain conditions. * * For more information, refer to the LICENSE file in this repositories root directory */ package phoenix.bot.pogo.nRnMK9r.util.map import com.google.common.geometry.S2LatLng import phoenix.bot.pogo.api.cache.Fort import phoenix.bot.pogo.api.cache.Pokestop import phoenix.bot.pogo.api.request.FortSearch import rx.Observable fun Pokestop.canLoot(ignoreDistance: Boolean = false, lootTimeouts: Map<String, Long>): Boolean { val canLoot = lootTimeouts.getOrElse(id, { cooldownCompleteTimestampMs }) < poGoApi.currentTimeMillis() return (ignoreDistance || inRange(poGoApi.fortSettings.interactionRangeMeters)) && canLoot } fun Pokestop.inRange(maxDistance: Double): Boolean { return distance < maxDistance } fun Pokestop.inRangeForLuredPokemon(): Boolean { return distance < poGoApi.mapSettings.encounterRangeMeters } fun Pokestop.loot(): Observable<FortSearch> { val loot: FortSearch = FortSearch().withFortId(fortData.id).withFortLatitude(fortData.latitude).withFortLongitude(fortData.longitude) return poGoApi.queueRequest(loot) } val Fort.distance: Double get() { val playerLocation = S2LatLng.fromDegrees(poGoApi.latitude, poGoApi.longitude) val fortLocation = S2LatLng.fromDegrees(fortData.latitude, fortData.longitude) return playerLocation.getEarthDistance(fortLocation) }
gpl-3.0
fc408333e921aebe9032194dfbf59a59
38.725
137
0.77533
3.847458
false
false
false
false
Applandeo/Material-Calendar-View
library/src/main/java/com/applandeo/materialcalendarview/adapters/CalendarDayAdapter.kt
1
4603
package com.applandeo.materialcalendarview.adapters import android.annotation.SuppressLint import android.content.Context import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ArrayAdapter import android.widget.ImageView import android.widget.TextView import com.applandeo.materialcalendarview.CalendarView import com.applandeo.materialcalendarview.exceptions.InvalidCustomLayoutException import com.applandeo.materialcalendarview.utils.* import kotlinx.android.synthetic.main.calendar_view_day.view.* import java.util.* private const val INVISIBLE_IMAGE_ALPHA = 0.12f /** * This class is responsible for loading a one day cell. * * * Created by Applandeo team */ class CalendarDayAdapter( context: Context, private val calendarPageAdapter: CalendarPageAdapter, private val calendarProperties: CalendarProperties, dates: MutableList<Date>, pageMonth: Int ) : ArrayAdapter<Date>(context, calendarProperties.itemLayoutResource, dates) { private val pageMonth = if (pageMonth < 0) 11 else pageMonth @SuppressLint("ViewHolder") override fun getView(position: Int, view: View?, parent: ViewGroup): View { val dayView = view ?: LayoutInflater.from(context).inflate(calendarProperties.itemLayoutResource, parent, false) val day = GregorianCalendar().apply { time = getItem(position) } dayView.dayIcon?.loadIcon(day) val dayLabel = dayView.dayLabel ?: throw InvalidCustomLayoutException setLabelColors(dayLabel, day) dayLabel.typeface = calendarProperties.typeface dayLabel.text = day[Calendar.DAY_OF_MONTH].toString() return dayView } private fun setLabelColors(dayLabel: TextView, day: Calendar) { when { // Setting not current month day color !day.isCurrentMonthDay() && !calendarProperties.selectionBetweenMonthsEnabled -> dayLabel.setDayColors(calendarProperties.anotherMonthsDaysLabelsColor) // Setting view for all SelectedDays day.isSelectedDay() -> { calendarPageAdapter.selectedDays .firstOrNull { selectedDay -> selectedDay.calendar == day } ?.let { selectedDay -> selectedDay.view = dayLabel } setSelectedDayColors(dayLabel, day, calendarProperties) } // Setting not current month day color only if selection between months is enabled for range picker !day.isCurrentMonthDay() && calendarProperties.selectionBetweenMonthsEnabled -> { if (SelectedDay(day) !in calendarPageAdapter.selectedDays) { dayLabel.setDayColors(calendarProperties.anotherMonthsDaysLabelsColor) } } // Setting disabled days color !day.isActiveDay() -> dayLabel.setDayColors(calendarProperties.disabledDaysLabelsColor) // Setting custom label color for event day day.isEventDayWithLabelColor() -> setCurrentMonthDayColors(day, dayLabel, calendarProperties) // Setting current month day color else -> setCurrentMonthDayColors(day, dayLabel, calendarProperties) } } private fun Calendar.isSelectedDay() = calendarProperties.calendarType != CalendarView.CLASSIC && SelectedDay(this) in calendarPageAdapter.selectedDays && if (!calendarProperties.selectionBetweenMonthsEnabled) this[Calendar.MONTH] == pageMonth else true private fun Calendar.isEventDayWithLabelColor() = this.isEventDayWithLabelColor(calendarProperties) private fun Calendar.isCurrentMonthDay() = this[Calendar.MONTH] == pageMonth && !(calendarProperties.minimumDate != null && this.before(calendarProperties.minimumDate) || calendarProperties.maximumDate != null && this.after(calendarProperties.maximumDate)) private fun Calendar.isActiveDay() = this !in calendarProperties.disabledDays private fun ImageView.loadIcon(day: Calendar) { if (!calendarProperties.eventsEnabled) { visibility = View.GONE return } calendarProperties.eventDays.firstOrNull { it.calendar == day }?.let { eventDay -> loadImage(eventDay.imageDrawable) // If a day doesn't belong to current month then image is transparent if (!day.isCurrentMonthDay() || !day.isActiveDay()) { alpha = INVISIBLE_IMAGE_ALPHA } } } }
apache-2.0
b76f56b6a061aed76629dbf7dd7a52f6
39.743363
113
0.686509
4.970842
false
false
false
false
mdaniel/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/RemoveExplicitLambdaParameterTypesIntention.kt
1
1531
// 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.intentions import com.intellij.openapi.editor.Editor import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingIntention import org.jetbrains.kotlin.psi.KtLambdaExpression import org.jetbrains.kotlin.psi.KtPsiFactory import org.jetbrains.kotlin.psi.psiUtil.endOffset class RemoveExplicitLambdaParameterTypesIntention : SelfTargetingIntention<KtLambdaExpression>( KtLambdaExpression::class.java, KotlinBundle.lazyMessage("remove.explicit.lambda.parameter.types.may.break.code") ) { override fun isApplicableTo(element: KtLambdaExpression, caretOffset: Int): Boolean { if (element.valueParameters.none { it.typeReference != null }) return false val arrow = element.functionLiteral.arrow ?: return false return caretOffset <= arrow.endOffset } override fun applyTo(element: KtLambdaExpression, editor: Editor?) { val oldParameterList = element.functionLiteral.valueParameterList!! val parameterString = oldParameterList.parameters.asSequence().map { it.destructuringDeclaration?.text ?: it.name }.joinToString(", ") val newParameterList = KtPsiFactory(element).createLambdaParameterList(parameterString) oldParameterList.replace(newParameterList) } }
apache-2.0
2ce7ee054afab0beaf4d406c5f507d9e
46.84375
158
0.774004
4.954693
false
false
false
false
micolous/metrodroid
src/commonMain/kotlin/au/id/micolous/metrodroid/serializers/XmlUtils.kt
1
1522
/* * XmlUtils.kt * * Copyright 2018-2019 Google * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package au.id.micolous.metrodroid.serializers import kotlinx.serialization.toUtf8Bytes object XmlUtils { private val CARDS_HEADER = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><cards>\n".toUtf8Bytes() private val CARDS_FOOTER = "</cards>\n".toUtf8Bytes() private val CARDS_SEPARATOR = byteArrayOf(10) // \n fun concatCardsFromString(cards: Iterator<String>): String { val os = StringBuilder() os.append(CARDS_HEADER) while (cards.hasNext()) { val s = cards.next() os.append(cutXmlDef(s)) os.append(CARDS_SEPARATOR) } os.append(CARDS_FOOTER) return os.toString() } fun cutXmlDef(data: String): String { return if (!data.startsWith("<?")) data else data.substring(data.indexOf("?>") + 2) } }
gpl-3.0
c6c6e90b160db8381eee732adf8dd8e9
31.382979
98
0.671485
3.92268
false
false
false
false
anitaa1990/DeviceInfo-Sample
deviceinfo/src/main/java/com/an/deviceinfo/permission/PermissionUtils.kt
1
1151
package com.an.deviceinfo.permission import android.content.Context import android.content.Intent import android.content.pm.PackageManager import android.net.Uri import android.os.Build import android.provider.Settings import android.support.v4.content.ContextCompat class PermissionUtils(private val context: Context) { @Synchronized fun isPermissionGranted(permission: String): Boolean { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) return context.checkCallingOrSelfPermission(permission) == PackageManager.PERMISSION_GRANTED val hasPermission = ContextCompat.checkSelfPermission(context, permission) return hasPermission == PackageManager.PERMISSION_GRANTED } fun openAppSettings() { val i = Intent() i.action = Settings.ACTION_APPLICATION_DETAILS_SETTINGS i.addCategory(Intent.CATEGORY_DEFAULT) i.data = Uri.parse("package:" + context.packageName) i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) i.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY) i.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS) context.startActivity(i) } }
apache-2.0
dade2a58fd1d308f4b5b0c24be7ff15c
35
104
0.737619
4.409962
false
false
false
false
GunoH/intellij-community
python/python-features-trainer/src/com/jetbrains/python/ift/lesson/refactorings/PythonRenameLesson.kt
3
6317
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.jetbrains.python.ift.lesson.refactorings import com.intellij.ide.DataManager import com.intellij.ide.actions.exclusion.ExclusionHandler import com.intellij.refactoring.RefactoringBundle import com.intellij.refactoring.ui.NameSuggestionsField import com.intellij.ui.tree.TreeVisitor import com.intellij.usageView.UsageViewBundle import com.intellij.util.ui.tree.TreeUtil import com.jetbrains.python.ift.PythonLessonsBundle import org.assertj.swing.fixture.JTreeFixture import training.dsl.* import training.learn.LessonsBundle import training.learn.course.KLesson import training.util.isToStringContains import javax.swing.JButton import javax.swing.JTree import javax.swing.tree.TreePath class PythonRenameLesson : KLesson("Rename", LessonsBundle.message("rename.lesson.name")) { override val testScriptProperties = TaskTestContext.TestScriptProperties(10) private val template = """ class Championship: def __init__(self): self.<name> = 0 def matches_count(self): return self.<name> * (self.<name> - 1) / 2 def add_new_team(self): self.<name> += 1 def team_matches(champ): champ.<name>() - 1 class Company: def __init__(self, t): self.teams = t def company_members(company): map(lambda team : team.name, company.teams) def teams(): return 16 c = Championship() c.<caret><name> = teams() print(c.<name>) """.trimIndent() + '\n' private val sample = parseLessonSample(template.replace("<name>", "teams")) override val lessonContent: LessonContext.() -> Unit = { prepareSample(sample) val dynamicWord = UsageViewBundle.message("usage.view.results.node.dynamic") var replace: String? = null var dynamicItem: String? = null task("RenameElement") { text(PythonLessonsBundle.message("python.rename.press.rename", action(it), code("teams"), code("teams_number"))) triggerUI().component { ui: NameSuggestionsField -> ui.addDataChangedListener { replace = ui.enteredName } true } triggerAndBorderHighlight().treeItem { _: JTree, path: TreePath -> val pathStr = path.getPathComponent(1).toString() if (path.pathCount == 2 && pathStr.contains(dynamicWord)) { dynamicItem = pathStr true } else false } test { actions(it) dialog { type("teams_number") button("Refactor").click() } } } task { // Increase deterministic: collapse nodes before { (previous.ui as? JTree)?.let { tree -> TreeUtil.collapseAll(tree, 1) } } val dynamicReferencesString = "[$dynamicWord]" text(PythonLessonsBundle.message("python.rename.expand.dynamic.references", code("teams"), strong(dynamicReferencesString))) triggerAndBorderHighlight().treeItem { _: JTree, path: TreePath -> path.pathCount == 6 && path.getPathComponent(5).isToStringContains("company_members") } showWarningIfFindToolbarClosed() test { //TODO: Fix tree access val jTree = previous.ui as? JTree ?: return@test val di = dynamicItem ?: return@test ideFrame { val jTreeFixture = JTreeFixture(robot, jTree) jTreeFixture.replaceSeparator("@@@") jTreeFixture.expandPath(di) // WARNING: several exception will be here because of UsageNode#toString inside info output during this operation } } } task { text(PythonLessonsBundle.message("python.rename.exclude.item", code("company_members"), action("EditorDelete"))) stateCheck { val tree = previous.ui as? JTree ?: return@stateCheck false val last = pathToExclude(tree) ?: return@stateCheck false val dataContext = DataManager.getInstance().getDataContext(tree) val exclusionProcessor: ExclusionHandler<*> = ExclusionHandler.EXCLUSION_HANDLER.getData(dataContext) ?: return@stateCheck false val leafToBeExcluded = last.lastPathComponent @Suppress("UNCHECKED_CAST") fun <T : Any?> castHack(processor: ExclusionHandler<T>): Boolean { return processor.isNodeExclusionAvailable(leafToBeExcluded as T) && processor.isNodeExcluded(leafToBeExcluded as T) } castHack(exclusionProcessor) } showWarningIfFindToolbarClosed() test { ideFrame { type("come") invokeActionViaShortcut("DELETE") } } } val confirmRefactoringButton = RefactoringBundle.message("usageView.doAction").dropMnemonic() task { triggerAndBorderHighlight().component { button: JButton -> button.text.isToStringContains(confirmRefactoringButton) } } task { val result = replace?.let { template.replace("<name>", it).replace("<caret>", "") } text(PythonLessonsBundle.message("python.rename.finish.refactoring", strong(confirmRefactoringButton))) stateCheck { editor.document.text == result } showWarningIfFindToolbarClosed() test(waitEditorToBeReady = false) { ideFrame { button(confirmRefactoringButton).click() } } } } private fun pathToExclude(tree: JTree): TreePath? { return TreeUtil.promiseVisit(tree, TreeVisitor { path -> if (path.pathCount == 7 && path.getPathComponent(6).isToStringContains("lambda")) TreeVisitor.Action.INTERRUPT else TreeVisitor.Action.CONTINUE }).blockingGet(200) } private fun TaskContext.showWarningIfFindToolbarClosed() { showWarning(PythonLessonsBundle.message("python.rename.find.window.closed.warning", action("ActivateFindToolWindow")), restoreTaskWhenResolved = true) { previous.ui?.isShowing != true } } override val helpLinks: Map<String, String> get() = mapOf( Pair(LessonsBundle.message("rename.help.link"), LessonUtil.getHelpLink("rename-refactorings.html")), ) }
apache-2.0
3e76ae8b4620da89574ad07e7106b791
34.290503
140
0.65205
4.7177
false
true
false
false
GunoH/intellij-community
plugins/kotlin/project-wizard/core/src/org/jetbrains/kotlin/tools/projectWizard/mpp/mpp.kt
1
12256
// 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.tools.projectWizard.mpp import org.jetbrains.annotations.NonNls import org.jetbrains.kotlin.tools.projectWizard.core.* import org.jetbrains.kotlin.tools.projectWizard.moduleConfigurators.SimpleTargetConfigurator import org.jetbrains.kotlin.tools.projectWizard.moduleConfigurators.inContextOfModuleConfigurator import org.jetbrains.kotlin.tools.projectWizard.plugins.kotlin.ModuleSubType import org.jetbrains.kotlin.tools.projectWizard.plugins.projectPath import org.jetbrains.kotlin.tools.projectWizard.plugins.templates.TemplatesPlugin import org.jetbrains.kotlin.tools.projectWizard.settings.JavaPackage import org.jetbrains.kotlin.tools.projectWizard.settings.buildsystem.Module import org.jetbrains.kotlin.tools.projectWizard.settings.buildsystem.SourcesetType import org.jetbrains.kotlin.tools.projectWizard.templates.FileDescriptor import org.jetbrains.kotlin.tools.projectWizard.templates.FileTemplate import org.jetbrains.kotlin.tools.projectWizard.templates.FileTextDescriptor import java.nio.file.Path import java.util.* @DslMarker annotation class ExpectFileDSL data class MppFile( @NonNls val filename: String, @NonNls val javaPackage: JavaPackage? = null, val declarations: List<MppDeclaration> ) { val fileNameWithPackage get() = javaPackage?.let { "${it.asCodePackage()}." }.orEmpty() + filename fun printForModuleSubType(moduleSubType: ModuleSubType): String = buildString { javaPackage?.let { appendLine("package ${it.asCodePackage()}"); appendLine() } if (moduleSubType == ModuleSubType.common) { declarations.joinTo(this, separator = "\n\n") { it.printExpect() } } else { printImports(declarations.flatMap { it.importsFor(moduleSubType) }) declarations.joinTo(this, separator = "\n\n") { it.printActualFor(moduleSubType) } } }.trim() private fun StringBuilder.printImports(imports: List<String>) { if (imports.isEmpty()) return imports.distinct().joinTo(this, separator = "\n", prefix = "\n", postfix = "\n\n") { import -> "import $import" } } @ExpectFileDSL class Builder(private val filename: String, val javaPackage: JavaPackage? = null) { private val declarations = mutableListOf<MppDeclaration>() fun function(signature: String, init: MppFunction.Builder.() -> Unit = {}) { declarations += MppFunction.Builder(signature).apply(init).build() } fun `class`(name: String, init: MppClass.Builder.() -> Unit = {}) { declarations += MppClass.Builder(name).apply(init).build() } fun build() = MppFile(filename, javaPackage, declarations) } } @ExpectFileDSL class MppSources(val mppFiles: List<MppFile>, private val simpleFiles: List<SimpleFiles>) { fun getFilesFor(moduleSubType: ModuleSubType): List<SimpleFile> = simpleFiles.filter { moduleSubType in it.moduleSubTypes }.flatMap { it.files } class Builder(val javaPackage: JavaPackage?) { private val mppFiles = mutableListOf<MppFile>() private val simpleFiles = mutableListOf<SimpleFiles>() fun mppFile(filename: String, init: MppFile.Builder.() -> Unit) { mppFiles += MppFile.Builder(filename, javaPackage).apply(init).build() } fun filesFor(vararg moduleSubTypes: ModuleSubType, init: SimpleFiles.Builder.() -> Unit) { simpleFiles += SimpleFiles.Builder(moduleSubTypes.toList(), javaPackage).apply(init).build() } fun build() = MppSources(mppFiles, simpleFiles) } } data class SimpleFiles(val moduleSubTypes: List<ModuleSubType>, val files: List<SimpleFile>) { class Builder(private val moduleSubTypes: List<ModuleSubType>, private val filesPackage: JavaPackage?) { private val files = mutableListOf<SimpleFile>() fun file(fileDescriptor: FileDescriptor, filename: String, type: SourcesetType, init: SimpleFile.Builder.() -> Unit = {}) { files += SimpleFile.Builder(fileDescriptor, filename, type).apply(init).apply { javaPackage = filesPackage }.build() } fun build() = SimpleFiles(moduleSubTypes, files) } } data class SimpleFile(val fileDescriptor: FileDescriptor, val javaPackage: JavaPackage?, val filename: String, val type: SourcesetType) { val uniqueIdentifier get() = "${type}/${javaPackage}/${filename}" class Builder(private val fileDescriptor: FileDescriptor, private val filename: String, private val type: SourcesetType) { var javaPackage: JavaPackage? = null fun build() = SimpleFile(fileDescriptor, javaPackage, filename, type) } } fun mppSources(javaPackage: JavaPackage? = null, init: MppSources.Builder.() -> Unit): MppSources = MppSources.Builder(javaPackage).apply(init).build() sealed class MppDeclaration { @Suppress("SpellCheckingInspection") abstract val actuals: Actuals abstract fun printExpect(): String abstract fun printActualFor(moduleSubType: ModuleSubType): String fun importsFor(moduleSubType: ModuleSubType): List<String> = actuals.getBodyFor(moduleSubType).imports @ExpectFileDSL abstract class Builder { private var defaultActualDeclarationBody = DefaultActualDeclarationBody(text = "", imports = emptyList()) @Suppress("SpellCheckingInspection") private val actuals = mutableMapOf<ModuleSubType, ActualDeclarationBody>() fun default(defaultText: String, init: DefaultActualDeclarationBody.Builder.() -> Unit = {}) { defaultActualDeclarationBody = DefaultActualDeclarationBody.Builder(defaultText).also(init).build() } fun actualFor(vararg moduleSubTypes: ModuleSubType, actualBody: String, init: ActualDeclarationBody.Builder.() -> Unit = {}) { moduleSubTypes.forEach { moduleSubType -> actuals[moduleSubType] = ActualDeclarationBody.Builder(actualBody).apply(init).build() } } protected fun buildActuals() = Actuals(defaultActualDeclarationBody, actuals) } } data class MppFunction( val signature: String, @Suppress("SpellCheckingInspection") override val actuals: Actuals, ) : MppDeclaration() { override fun printExpect(): String = "expect fun $signature" override fun printActualFor(moduleSubType: ModuleSubType): String { val body = actuals.getBodyFor(moduleSubType) return buildString { appendLine("actual fun $signature {") appendLine(body.text.indented(4)) append("}") } } @ExpectFileDSL class Builder(private val signature: String) : MppDeclaration.Builder() { fun build(): MppFunction = MppFunction( signature, buildActuals(), ) } } data class MppClass( val name: String, val expectBody: String?, @Suppress("SpellCheckingInspection") override val actuals: Actuals, ) : MppDeclaration() { override fun printExpect(): String = buildString { append("expect class $name()") expectBody?.let { body -> appendLine(" {") appendLine(body.indented(4)) append("}") } } override fun printActualFor(moduleSubType: ModuleSubType): String { val body = actuals.getBodyFor(moduleSubType) return buildString { appendLine("actual class $name actual constructor() {") appendLine(body.text.indented(4)) append("}") } } @ExpectFileDSL class Builder(private val name: String) : MppDeclaration.Builder() { var expectBody: String? = null fun build(): MppClass = MppClass( name, expectBody, buildActuals(), ) } } private fun String.indented(indentValue: Int): String { val indent = " ".repeat(indentValue) return split('\n').joinToString(separator = "\n") { line -> indent + line.trim() } } @Suppress("SpellCheckingInspection") data class Actuals( val defaultActualDeclarationBody: DefaultActualDeclarationBody, val actuals: Map<ModuleSubType, ActualDeclarationBody>, ) { fun getBodyFor(moduleSubType: ModuleSubType): DeclarationBody = actuals[moduleSubType] ?: defaultActualDeclarationBody } sealed class DeclarationBody { abstract val text: String abstract val imports: List<String> abstract class Builder { protected val imports = mutableListOf<String>() fun import(import: String) { imports += import } } } data class ActualDeclarationBody(override val text: String, override val imports: List<String>) : DeclarationBody() { class Builder(private val text: String) : DeclarationBody.Builder() { fun build() = ActualDeclarationBody(text, imports) } } data class DefaultActualDeclarationBody(override val text: String, override val imports: List<String>) : DeclarationBody() { class Builder(private val text: String) : DeclarationBody.Builder() { fun build() = DefaultActualDeclarationBody(text, imports) } } fun Writer.applyMppStructure( mppSources: List<MppSources>, module: Module, modulePath: Path, ): TaskResult<Unit> = compute { createMppFiles(mppSources, module, modulePath).ensure() createSimpleFiles(mppSources, module, modulePath).ensure() } fun Writer.applyMppStructure( mppSources: MppSources, module: Module, modulePath: Path, ): TaskResult<Unit> = applyMppStructure(listOf(mppSources), module, modulePath) private fun Writer.createMppFiles( mppSources: List<MppSources>, module: Module, modulePath: Path ): TaskResult<Unit> = inContextOfModuleConfigurator(module) { val mppFiles = mppSources.flatMap { it.mppFiles } .distinctBy { it.fileNameWithPackage } // todo merge files with the same name here mppFiles.mapSequenceIgnore { file -> module.subModules.mapSequenceIgnore mapTargets@{ target -> val moduleSubType = //TODO handle for non-simple target configurator target.configurator.safeAs<SimpleTargetConfigurator>()?.moduleSubType ?: return@mapTargets UNIT_SUCCESS val path = pathForFileInTarget(modulePath, module, file.javaPackage, file.filename, target, SourcesetType.main) val fileTemplate = FileTemplate( FileTextDescriptor(file.printForModuleSubType(moduleSubType), path), projectPath, ) TemplatesPlugin.fileTemplatesToRender.addValues(fileTemplate) } } } private fun Writer.createSimpleFiles( mppSources: List<MppSources>, module: Module, modulePath: Path ): TaskResult<Unit> = inContextOfModuleConfigurator(module) { val mppFiles = mppSources val filesWithPaths = module.subModules.flatMap { target -> val moduleSubType = //TODO handle for non-simple target configurator target.configurator.safeAs<SimpleTargetConfigurator>()?.moduleSubType ?: return@flatMap emptyList() mppFiles .flatMap { it.getFilesFor(moduleSubType) } .distinctBy { it.uniqueIdentifier } .map { file -> val path = projectPath / pathForFileInTarget(modulePath, module, file.javaPackage, file.filename, target, file.type) file to path } }.distinctBy { (_, path) -> path } filesWithPaths.mapSequenceIgnore { (file, path) -> val fileTemplate = FileTemplate(file.fileDescriptor, path, mapOf("package" to file.javaPackage?.asCodePackage())) TemplatesPlugin.fileTemplatesToRender.addValues(fileTemplate) } } private fun pathForFileInTarget( mppModulePath: Path, mppModule: Module, javaPackage: JavaPackage?, filename: String, target: Module, sourcesetType: SourcesetType, ) = mppModulePath / Defaults.SRC_DIR / "${target.name}${sourcesetType.name.capitalize(Locale.US)}" / mppModule.configurator.kotlinDirectoryName / javaPackage?.asPath() / filename
apache-2.0
0321edee8f95f216c4bef3454107a39a
37.062112
158
0.68905
4.672512
false
false
false
false
mvmike/min-cal-widget
app/src/test/kotlin/cat/mvmike/minimalcalendarwidget/domain/DayTest.kt
1
5886
// Copyright (c) 2016, Miquel Martí <[email protected]> // See LICENSE for licensing information package cat.mvmike.minimalcalendarwidget.domain import cat.mvmike.minimalcalendarwidget.BaseTest import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.params.ParameterizedTest import org.junit.jupiter.params.provider.MethodSource import java.time.DayOfWeek import java.time.LocalDate import java.util.stream.Stream internal class DayTest : BaseTest() { @ParameterizedTest @MethodSource("getLocalDatesWithExpectations") fun getDayOfWeek(dayProperties: DayTestProperties) { val day = Day( dayLocalDate = dayProperties.localDate ) val result = day.getDayOfWeek() assertThat(result).isEqualTo(dayProperties.expectedDayOfWeek) } @ParameterizedTest @MethodSource("getLocalDatesWithExpectations") fun getDayOfMonthString(dayProperties: DayTestProperties) { val day = Day( dayLocalDate = dayProperties.localDate ) val result = day.getDayOfMonthString() assertThat(result).isEqualTo(dayProperties.expectedDayOfMonthString) } @ParameterizedTest @MethodSource("getLocalDatesWithExpectations") fun isInMonth(dayProperties: DayTestProperties) { val day = Day( dayLocalDate = dayProperties.localDate ) val result = day.isInMonth(systemLocalDate) assertThat(result).isEqualTo(dayProperties.expectedIsInMonth) } @ParameterizedTest @MethodSource("getLocalDatesWithExpectations") fun isToday(dayProperties: DayTestProperties) { val day = Day( dayLocalDate = dayProperties.localDate ) val result = day.isToday(systemLocalDate) assertThat(result).isEqualTo(dayProperties.expectedIsToday) } @Suppress("UnusedPrivateMember", "LongMethod") private fun getLocalDatesWithExpectations(): Stream<DayTestProperties> = Stream.of( DayTestProperties( localDate = LocalDate.of(2018, 1, 1), expectedDayOfMonthString = " 1", expectedDayOfWeek = DayOfWeek.MONDAY, expectedIsInMonth = false, expectedIsToday = false ), DayTestProperties( localDate = LocalDate.of(2017, 12, 2), expectedDayOfMonthString = " 2", expectedDayOfWeek = DayOfWeek.SATURDAY, expectedIsInMonth = false, expectedIsToday = false ), DayTestProperties( localDate = LocalDate.of(2018, 12, 4), expectedDayOfMonthString = " 4", expectedDayOfWeek = DayOfWeek.TUESDAY, expectedIsInMonth = true, expectedIsToday = true ), DayTestProperties( localDate = LocalDate.of(2012, 7, 5), expectedDayOfMonthString = " 5", expectedDayOfWeek = DayOfWeek.THURSDAY, expectedIsInMonth = false, expectedIsToday = false ), DayTestProperties( localDate = LocalDate.of(2018, 5, 5), expectedDayOfMonthString = " 5", expectedDayOfWeek = DayOfWeek.SATURDAY, expectedIsInMonth = false, expectedIsToday = false ), DayTestProperties( localDate = LocalDate.of(2020, 12, 9), expectedDayOfMonthString = " 9", expectedDayOfWeek = DayOfWeek.WEDNESDAY, expectedIsInMonth = false, expectedIsToday = false ), DayTestProperties( localDate = LocalDate.of(2021, 11, 11), expectedDayOfMonthString = "11", expectedDayOfWeek = DayOfWeek.THURSDAY, expectedIsInMonth = false, expectedIsToday = false ), DayTestProperties( localDate = LocalDate.of(2030, 2, 12), expectedDayOfMonthString = "12", expectedDayOfWeek = DayOfWeek.TUESDAY, expectedIsInMonth = false, expectedIsToday = false ), DayTestProperties( localDate = LocalDate.of(2015, 3, 15), expectedDayOfMonthString = "15", expectedDayOfWeek = DayOfWeek.SUNDAY, expectedIsInMonth = false, expectedIsToday = false ), DayTestProperties( localDate = LocalDate.of(2016, 6, 21), expectedDayOfMonthString = "21", expectedDayOfWeek = DayOfWeek.TUESDAY, expectedIsInMonth = false, expectedIsToday = false ), DayTestProperties( localDate = LocalDate.of(1994, 4, 23), expectedDayOfMonthString = "23", expectedDayOfWeek = DayOfWeek.SATURDAY, expectedIsInMonth = false, expectedIsToday = false ), DayTestProperties( localDate = LocalDate.of(2000, 8, 27), expectedDayOfMonthString = "27", expectedDayOfWeek = DayOfWeek.SUNDAY, expectedIsInMonth = false, expectedIsToday = false ), DayTestProperties( localDate = LocalDate.of(2018, 12, 28), expectedDayOfMonthString = "28", expectedDayOfWeek = DayOfWeek.FRIDAY, expectedIsInMonth = true, expectedIsToday = false ), DayTestProperties( localDate = LocalDate.of(2019, 12, 31), expectedDayOfMonthString = "31", expectedDayOfWeek = DayOfWeek.TUESDAY, expectedIsInMonth = false, expectedIsToday = false ) ) internal data class DayTestProperties( val localDate: LocalDate, val expectedDayOfMonthString: String, val expectedDayOfWeek: DayOfWeek, val expectedIsInMonth: Boolean, val expectedIsToday: Boolean ) }
bsd-3-clause
c0c658566eec8061b43f63fbaf3d19cb
33.215116
87
0.617502
5.104076
false
true
false
false
andrsim66/Timetable-Kotlin
app/src/main/java/com/sevenander/timetable/settings/SettingsActivity.kt
1
1737
package com.sevenander.timetable.settings import android.app.Activity import android.app.AlertDialog import android.content.Context import android.content.DialogInterface import android.os.Bundle import android.support.v7.app.AppCompatActivity import com.sevenander.timetable.R class SettingsActivity : AppCompatActivity(), SettingsView { private lateinit var presenter: SettingsPresenter override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_settings) init() } override fun showDaySettings(items: Array<String?>, checkedItems: BooleanArray) { val builder = AlertDialog.Builder(this@SettingsActivity) builder.setMultiChoiceItems(items, checkedItems, selectionChanged(checkedItems)) builder.setNegativeButton(android.R.string.cancel, null) builder.setPositiveButton(android.R.string.ok, positiveClick(checkedItems)) builder.create().show() } override fun context(): Context { return this@SettingsActivity } private fun init() { presenter = SettingsPresenter(this@SettingsActivity) presenter.loadSettings() } private fun selectionChanged(checkedItems: BooleanArray): DialogInterface.OnMultiChoiceClickListener = DialogInterface.OnMultiChoiceClickListener({ dialog, which, isChecked -> checkedItems[which] = isChecked }) private fun positiveClick(checkedItems: BooleanArray): DialogInterface.OnClickListener = DialogInterface.OnClickListener({ _, _ -> presenter.saveDays(checkedItems) setResult(Activity.RESULT_OK) }) }
mit
74d9969efc10d3dd851b927d521d0e74
31.773585
92
0.712147
5.295732
false
false
false
false
marius-m/wt4
app/src/main/java/lt/markmerkk/Styles.kt
1
7046
package lt.markmerkk import com.jfoenix.controls.JFXButton import javafx.scene.control.OverrunStyle import javafx.scene.paint.Color import javafx.scene.text.Font import tornadofx.* class Styles: Stylesheet() { private val fontEmoji = Styles::class.java.getResourceAsStream("/fonts/OpenSansEmoji.ttf") .use { Font.loadFont(it, 24.0) } companion object { val jfxButtonType by cssproperty<JFXButton.ButtonType>("-jfx-button-type") { it.name } val dialogHeader by cssclass() val dialogH1TextColorful by cssclass() val dialogH9TextColorful by cssclass() val dialogHeaderContainerColorful by cssclass() val sidePanelHeader by cssclass() val sidePanelContainer by cssclass() val dialogContainer by cssclass() val dialogContainerColorContent by cssclass() val dialogContainerActionsButtons by cssclass() val dialogContainerColorActionsButtons by cssclass() val dialogButtonAction by cssclass() val buttonMenu by cssclass() val buttonMenuMini by cssclass() val inputTextField by cssclass() val labelMini by cssclass() val labelRegular by cssclass() val popUpLabel by cssclass() val emojiText by cssclass() val textMini by cssclass() val dialogAlertContainer by cssclass() val dialogAlertContainerBig by cssclass() val dialogAlertContentContainer by cssclass() val dialogAlertTextH1 by cssclass() val dialogAlertTextRegular by cssclass() val cLightest = c("#E8EAF6") val cLight = c("#7986CB") val cPrimary = c("#5C6BC0") val cDark = c("#303F9F") val cDarkest = c("#1A237E") val cActivateLightest = c("#FFD180") val cActivateLight = c("#FFAB40") val cActivatePrimary = c("#FF9800") val cActivateDark = c("#FF9100") val cActivateDarkest = c("#FF6D00") val cTextHeaderColorful = Color.WHITE val cTextMini = c("#FF6D00") val cActiveRed = c("#E91E63") val cActiveOrange = Color.ORANGE val cBackgroundPrimary = c("#5C6BC0") } init { sidePanelContainer { padding = box( top = 10.px, left = 20.px, right = 20.px, bottom = 10.px ) } dialogContainer { minWidth = 400.px padding = box( top = 10.px, left = 20.px, right = 20.px, bottom = 10.px ) } dialogContainerColorContent { backgroundColor += Color.WHITE padding = box( top = 10.px, left = 20.px, right = 20.px, bottom = 10.px ) } dialogContainerActionsButtons { padding = box( top = 10.px, left = 0.px, right = 0.px, bottom = 0.px ) } dialogContainerColorActionsButtons { backgroundColor += Color.WHITE padding = box( top = 10.px, left = 20.px, right = 20.px, bottom = 10.px ) } dialogHeader { fontSize = 24.pt fontFamily = "Verdana" padding = box( top = 0.px, left = 0.px, right = 0.px, bottom = 20.px ) } dialogH1TextColorful { textFill = cTextHeaderColorful fontSize = 24.pt fontFamily = "Verdana" } dialogH9TextColorful { textFill = cTextHeaderColorful fontSize = 8.pt fontFamily = "Verdana" } dialogHeaderContainerColorful { backgroundColor += cActiveRed minHeight = 82.px maxHeight = 82.px } sidePanelHeader { fontSize = 16.pt fontFamily = "Verdana" padding = box( top = 0.px, left = 0.px, right = 0.px, bottom = 20.px ) } buttonMenu { val dimen = 46.px prefWidth = dimen prefHeight = dimen minWidth = dimen minHeight = dimen maxWidth = dimen maxHeight = dimen backgroundRadius.add(box(50.px)) backgroundColor.add(cActiveRed) textFill = Color.WHITE ellipsisString = "..." textOverrun = OverrunStyle.WORD_ELLIPSIS } buttonMenuMini { val dimen = 20.px prefWidth = dimen prefHeight = dimen minWidth = dimen minHeight = dimen maxWidth = dimen maxHeight = dimen backgroundRadius.add(box(50.px)) backgroundColor.add(cActiveOrange) textFill = Color.WHITE ellipsisString = "..." textOverrun = OverrunStyle.WORD_ELLIPSIS } inputTextField { } labelMini { textFill = Color.GRAY fontSize = 8.pt } labelRegular { textFill = Color.GRAY fontSize = 10.pt } popUpLabel { fontSize = 10.pt } emojiText { font = fontEmoji fontFamily = "OpenSansEmoji" } dialogButtonAction { jfxButtonType.value = JFXButton.ButtonType.RAISED backgroundColor.add(Color.WHITE) backgroundRadius.add(box(4.px)) } textMini { textFill = Color.GRAY fontSize = 8.pt } dialogAlertContainer { minWidth = 320.px prefWidth = 320.px minHeight = 160.px prefHeight = 160.px padding = box( top = 10.px, left = 20.px, right = 20.px, bottom = 10.px ) } dialogAlertContainerBig { minWidth = 420.px prefWidth = 420.px minHeight = 280.px prefHeight = 280.px padding = box( top = 10.px, left = 20.px, right = 20.px, bottom = 10.px ) } dialogAlertContentContainer { padding = box( top = 10.px, left = 0.px, right = 0.px, bottom = 10.px ) } dialogAlertTextH1 { fontSize = 24.pt fontFamily = "Verdana" } dialogAlertTextRegular { fontSize = 10.pt fontFamily = "Verdana" wrapText = true } } }
apache-2.0
8901c052f031a722dd77f6cf137fecb0
28.609244
94
0.486375
4.944561
false
false
false
false
cfieber/orca
orca-queue/src/test/kotlin/com/netflix/spinnaker/orca/q/handler/StartWaitingExecutionsHandlerTest.kt
1
5718
/* * 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.handler import com.netflix.spinnaker.orca.fixture.pipeline import com.netflix.spinnaker.orca.pipeline.persistence.ExecutionRepository import com.netflix.spinnaker.orca.q.CancelExecution import com.netflix.spinnaker.orca.q.StartExecution import com.netflix.spinnaker.orca.q.StartWaitingExecutions import com.netflix.spinnaker.orca.q.pending.PendingExecutionService import com.netflix.spinnaker.q.Message import com.netflix.spinnaker.q.Queue import com.nhaarman.mockito_kotlin.* import org.jetbrains.spek.api.dsl.* import org.jetbrains.spek.api.lifecycle.CachingMode.GROUP import org.jetbrains.spek.subject.SubjectSpek import java.time.Instant.now import java.util.* import kotlin.math.absoluteValue object StartWaitingExecutionsHandlerTest : SubjectSpek<StartWaitingExecutionsHandler>({ val queue = mock<Queue>() val repository = mock<ExecutionRepository>() val pipelineQueue = mock<PendingExecutionService>() fun resetMocks() { reset(queue, repository) } subject(GROUP) { StartWaitingExecutionsHandler(queue, repository, pipelineQueue) } val configId = UUID.randomUUID().toString() describe("starting waiting pipelines") { given("there are no pipelines waiting") { beforeGroup { whenever(pipelineQueue.depth(configId)) doReturn 0 } afterGroup(::resetMocks) on("receiving the message") { subject.handle(StartWaitingExecutions(configId)) } it("does nothing") { verifyZeroInteractions(queue) } } given("there is a single pipeline waiting") { val waitingPipeline = pipeline { pipelineConfigId = configId } given("the queue should not be purged") { beforeGroup { whenever(pipelineQueue.depth(configId)) doReturn 1 whenever(pipelineQueue.popOldest(configId)) doReturn StartExecution(waitingPipeline) } afterGroup(::resetMocks) on("receiving the message") { subject.handle(StartWaitingExecutions(configId)) } it("starts the waiting pipeline") { verify(queue).push(StartExecution(waitingPipeline)) } } given("the queue should be purged") { beforeGroup { whenever(pipelineQueue.depth(configId)) doReturn 1 whenever(pipelineQueue.popNewest(configId)) doReturn StartExecution(waitingPipeline) } afterGroup(::resetMocks) on("receiving the message") { subject.handle(StartWaitingExecutions(configId, purgeQueue = true)) } it("starts the waiting pipeline") { verify(queue).push(StartExecution(waitingPipeline)) } it("does not cancel anything") { verify(queue, never()).push(isA<CancelExecution>()) } } } given("multiple waiting pipelines") { val waitingPipelines = Random().let { rnd -> (1..5).map { pipeline { pipelineConfigId = configId buildTime = now().minusSeconds(rnd.nextInt().toLong().absoluteValue).toEpochMilli() } } } val oldest = waitingPipelines.minBy { it.buildTime!! }!! val newest = waitingPipelines.maxBy { it.buildTime!! }!! given("the queue should not be purged") { beforeGroup { whenever(pipelineQueue.depth(configId)) doReturn waitingPipelines.size whenever(pipelineQueue.popOldest(configId)) doReturn StartExecution(oldest) whenever(pipelineQueue.popNewest(configId)) doReturn StartExecution(newest) } afterGroup(::resetMocks) on("receiving the message") { subject.handle(StartWaitingExecutions(configId)) } it("starts the oldest waiting pipeline") { verify(queue).push(StartExecution(oldest)) } it("does nothing else") { verifyNoMoreInteractions(queue) } } given("the queue should be purged") { beforeGroup { whenever(pipelineQueue.depth(configId)) doReturn waitingPipelines.size whenever(pipelineQueue.popOldest(configId)) doReturn StartExecution(oldest) whenever(pipelineQueue.popNewest(configId)) doReturn StartExecution(newest) argumentCaptor<(Message) -> Unit>().apply { whenever(pipelineQueue.purge(eq(configId), capture())).then { (waitingPipelines - newest).forEach { firstValue.invoke(StartExecution(it)) } } } } afterGroup(::resetMocks) on("receiving the message") { subject.handle(StartWaitingExecutions(configId, purgeQueue = true)) } it("starts the newest waiting pipeline") { verify(queue).push(StartExecution(newest)) } it("cancels all the other waiting pipelines") { verify(queue, times(waitingPipelines.size - 1)).push(isA<CancelExecution>()) } it("does not cancel the one it's trying to start") { verify(queue, never()).push(CancelExecution(newest)) } } } } })
apache-2.0
3e366b235600aada712db2f40106bec5
30.766667
95
0.661945
4.757072
false
true
false
false
infotech-group/android-drawable-dsl
src/main/kotlin/group/infotech/drawable/dsl/shapes.kt
1
3381
package group.infotech.drawable.dsl import android.annotation.TargetApi import android.graphics.drawable.GradientDrawable inline fun shapeDrawable(fill: GradientDrawable.() -> Unit): GradientDrawable = GradientDrawable().also { it.gradientType = GradientDrawable.LINEAR_GRADIENT it.fill() } enum class Shape { RECTANGLE, OVAL, LINE, RING, } typealias ShapeInt = Int fun toInt(s: Shape): ShapeInt = when (s) { Shape.RECTANGLE -> GradientDrawable.RECTANGLE Shape.OVAL -> GradientDrawable.OVAL Shape.LINE -> GradientDrawable.LINE Shape.RING -> GradientDrawable.RING } fun fromInt(s: ShapeInt): Shape? = when (s) { GradientDrawable.RECTANGLE -> Shape.RECTANGLE GradientDrawable.OVAL -> Shape.OVAL GradientDrawable.LINE -> Shape.LINE GradientDrawable.RING -> Shape.RING else -> null } var GradientDrawable.shapeEnum: Shape set(value) { shape = toInt(value) } @TargetApi(24) get() = fromInt(shape) ?: error("Illegal shape int $shape") fun rectangleShape( radius: FloatPx = Float.NaN, color: ColorInt, size: Px? = null ): GradientDrawable = shapeDrawable { shapeEnum = Shape.RECTANGLE // DO NOT CHANGE // RADIUS AND COLOR ORDER IS IMPORTANT FOR RIPPLES! if (radius != Float.NaN) { cornerRadius = radius } solidColor = color size?.let { this.size = it } } fun circleShape(color: ColorInt, size: Px? = null): GradientDrawable = shapeDrawable { shape = GradientDrawable.OVAL solidColor = color size?.let { this.size = it } } var GradientDrawable.solidColor: ColorInt set(value) = setColor(value) @Deprecated(message = NO_GETTER, level = DeprecationLevel.HIDDEN) get() = error(NO_GETTER) var GradientDrawable.size: Px set(value) = setSize(value, value) get() = intrinsicWidth class Stroke { var width: Px = -1 var color: ColorInt = -1 var dashWidth: FloatPx = 0F var dashGap: FloatPx = 0F } inline fun GradientDrawable.stroke(fill: Stroke.() -> Unit): Stroke = Stroke().also { it.fill() setStroke(it.width, it.color, it.dashWidth, it.dashGap) } class Size { var width: Px = -1 var height: Px = -1 } inline fun GradientDrawable.size(fill: Size.() -> Unit): Size = Size().also { fill(it) setSize(it.width, it.height) } class Corners { var radius: FloatPx = 0F var topLeft: FloatPx = Float.NaN var topRight: FloatPx = Float.NaN var bottomLeft: FloatPx = Float.NaN var bottomRight: FloatPx = Float.NaN internal fun FloatPx.orRadius(): FloatPx = takeIf { it >= 0 } ?: radius } fun Corners.render(): FloatArray = floatArrayOf( topLeft.orRadius(), topLeft.orRadius(), topRight.orRadius(), topRight.orRadius(), bottomRight.orRadius(), bottomRight.orRadius(), bottomLeft.orRadius(), bottomLeft.orRadius() ) inline fun GradientDrawable.corners(fill: Corners.() -> Unit): Corners = Corners().also { it.fill() cornerRadii = it.render() }
apache-2.0
883a2bbd2c44c9326c816aefaded6490
20.954545
94
0.596273
4.083333
false
false
false
false
ClearVolume/scenery
src/main/kotlin/graphics/scenery/backends/vulkan/SwingSwapchain.kt
1
5522
package graphics.scenery.backends.vulkan import graphics.scenery.Hub import graphics.scenery.backends.RenderConfigReader import graphics.scenery.backends.SceneryWindow import graphics.scenery.utils.SceneryJPanel import graphics.scenery.utils.SceneryPanel import org.lwjgl.system.MemoryUtil.memFree import org.lwjgl.vulkan.KHRSwapchain import org.lwjgl.vulkan.VkQueue import org.lwjgl.vulkan.awt.AWTVKCanvas import org.lwjgl.vulkan.awt.VKData import java.awt.BorderLayout import java.awt.Color import java.awt.event.ComponentEvent import java.awt.event.ComponentListener import javax.swing.JFrame import javax.swing.SwingUtilities /** * GLFW-based default Vulkan Swapchain and window, residing on [device], associated with [queue]. * Needs to be given [commandPools] to allocate command buffers from. [useSRGB] determines whether * the sRGB colorspace will be used, [vsync] determines whether vertical sync will be forced (swapping * rendered images in sync with the screen's frequency). [undecorated] determines whether the created * window will have the window system's default chrome or not. * * @author Ulrik Günther <[email protected]> */ open class SwingSwapchain(override val device: VulkanDevice, override val queue: VkQueue, override val commandPools: VulkanRenderer.CommandPools, override val renderConfig: RenderConfigReader.RenderConfig, override val useSRGB: Boolean = true, override val vsync: Boolean = true, override val undecorated: Boolean = false) : VulkanSwapchain(device, queue, commandPools, renderConfig, useSRGB, vsync, undecorated) { private val WINDOW_RESIZE_TIMEOUT: Long = 500_000_000 protected var sceneryPanel: SceneryPanel? = null /** * Creates a window for this swapchain, and initialiases [win] as [SceneryWindow.GLFWWindow]. * Needs to be handed a [VulkanRenderer.SwapchainRecreator]. * Returns the initialised [SceneryWindow]. */ override fun createWindow(win: SceneryWindow, swapchainRecreator: VulkanRenderer.SwapchainRecreator): SceneryWindow { val data = VKData() data.instance = device.instance logger.debug("Vulkan Instance=${data.instance}") val p = sceneryPanel as? SceneryJPanel ?: throw IllegalArgumentException("Must have SwingWindow") val canvas = object : AWTVKCanvas(data) { private val serialVersionUID = 1L var initialized: Boolean = false private set override fun initVK() { logger.debug("Surface for canvas set to $surface") [email protected] = surface this.background = Color.BLACK initialized = true } override fun paintVK() {} } p.component = canvas p.layout = BorderLayout() p.add(canvas, BorderLayout.CENTER) val frame = SwingUtilities.getAncestorOfClass(JFrame::class.java, p) as JFrame frame.isVisible = true while(!canvas.initialized) { Thread.sleep(100) } window = SceneryWindow.SwingWindow(p) window.width = win.width window.height = win.height // the listener should only be initialized here, otherwise [window] // might be uninitialized. p.addComponentListener(object : ComponentListener { override fun componentResized(e: ComponentEvent) { if(lastResize > 0L && lastResize + WINDOW_RESIZE_TIMEOUT > System.nanoTime()) { return } if(e.component.width <= 0 || e.component.height <= 0) { return } window.width = e.component.width window.height = e.component.height logger.debug("Resizing panel to ${window.width}x${window.height}") swapchainRecreator.mustRecreate = true lastResize = System.nanoTime() } override fun componentMoved(e: ComponentEvent) {} override fun componentHidden(e: ComponentEvent) {} override fun componentShown(e: ComponentEvent) {} }) return window } /** * Changes the current window to fullscreen. */ override fun toggleFullscreen(hub: Hub, swapchainRecreator: VulkanRenderer.SwapchainRecreator) { // TODO: Add } /** * Embeds the swapchain into a [SceneryPanel]. */ override fun embedIn(panel: SceneryPanel?) { if(panel == null) { return } sceneryPanel = panel } /** * Returns the number of fully presented frames. */ override fun presentedFrames(): Long { return presentedFrames } /** * Closes the swapchain, deallocating all of its resources. */ override fun close() { logger.debug("Closing swapchain $this") KHRSwapchain.vkDestroySwapchainKHR(device.vulkanDevice, handle, null) (sceneryPanel as? SceneryJPanel)?.remove(0) presentInfo.free() memFree(swapchainImage) memFree(swapchainPointer) } companion object: SwapchainParameters { override var headless = false override var usageCondition = { p: SceneryPanel? -> System.getProperty("scenery.Renderer.UseAWT", "false")?.toBoolean() ?: false || p is SceneryJPanel } } }
lgpl-3.0
bc29b52d99193aabba8e0f4bf2ccb1b9
35.322368
160
0.644448
4.920677
false
false
false
false
stanfy/helium
codegen/objc/objc-entities/src/main/kotlin/com/stanfy/helium/handler/codegen/objectivec/entity/filetree/ObjCImportPart.kt
1
922
package com.stanfy.helium.handler.codegen.objectivec.entity.filetree; /** * Created by ptaykalo on 9/10/14. * Source part that represents import line */ class ObjCImportPart(val filename:String, val isFrameworkImport:Boolean) : ObjCSourcePart { constructor(filename: String):this(filename,false) override fun asString(): String { if (isFrameworkImport) { return "#import <$filename.h>"; } else { return "#import \"$filename.h\""; } } override fun equals(other: Any?): Boolean{ if (this === other) return true if (other?.javaClass != javaClass) return false other as ObjCImportPart if (filename != other.filename) return false if (isFrameworkImport != other.isFrameworkImport) return false return true } override fun hashCode(): Int{ var result = filename.hashCode() result += 31 * result + isFrameworkImport.hashCode() return result } }
apache-2.0
0822665c3f49925274149f259cd5df38
24.611111
91
0.684382
4.026201
false
false
false
false
Kerooker/rpg-npc-generator
app/src/test/java/me/kerooker/rpgnpcgenerator/viewmodel/admob/AdmobViewmodelTest.kt
1
10879
package me.kerooker.rpgnpcgenerator.viewmodel.admob import io.kotest.IsolationMode.InstancePerTest import io.kotest.android.InstantLivedataListener import io.kotest.matchers.longs.shouldBeInRange import io.kotest.shouldBe import io.kotest.specs.BehaviorSpec import io.mockk.Runs import io.mockk.every import io.mockk.just import io.mockk.mockk import io.mockk.mockkObject import io.mockk.slot import me.kerooker.rpgnpcgenerator.repository.model.persistence.admob.AdmobRepository import java.util.Date class AdmobViewmodelTest : BehaviorSpec() { private val admobRepository = mockk<AdmobRepository>() private val target by lazy { AdmobViewModel(admobRepository) } init { mockkObject(MyBuildConfig) Given("The app ID contains PRO (Should show ads test)") { And("App is in debug mode") { every { MyBuildConfig.APPLICATION_ID } returns "me.kerooker.rpgcharactergeneratorpro.debug" When("stopAdsUntil is before now") { every { admobRepository.stopAdsUntil } returns Date().time - 1L Then("Ads should not be shown") { target.shouldShowAd.value shouldBe false } } When("stopAdsUntil is after now") { every { admobRepository.stopAdsUntil } returns Date().time + 5_000L Then("Ads should not be shown") { target.shouldShowAd.value shouldBe false } } } And("App is not in debug mode") { every { MyBuildConfig.APPLICATION_ID } returns "me.kerooker.rpgcharactergeneratorpro" When("stopAdsUntil is before now") { every { admobRepository.stopAdsUntil } returns Date().time - 1L Then("Ads should not be shown") { target.shouldShowAd.value shouldBe false } } When("stopAdsUntil is after now") { every { admobRepository.stopAdsUntil } returns Date().time + 5_000L Then("Ads should not be shown") { target.shouldShowAd.value shouldBe false } } } } Given("The app ID doesn't contain PRO (Should show ads test)") { And("App is in debug mode") { every { MyBuildConfig.APPLICATION_ID } returns "me.kerooker.rpgcharactergenerator.debug" When("stopAdsUntil is before now") { every { admobRepository.stopAdsUntil } returns Date().time - 1L Then("Ads should be shown") { target.shouldShowAd.value shouldBe true } Then("Ad banner ID should be debug banner") { target.bannerAdId shouldBe "ca-app-pub-3940256099942544/6300978111" } Then("Rewarded ad ID should be debug rewarded ad") { target.rewardedAdId shouldBe "ca-app-pub-3940256099942544/5224354917" } } When("stopAdsUntil is after now") { every { admobRepository.stopAdsUntil } returns Date().time + 5_000L Then("Ads should not be shown") { target.shouldShowAd.value shouldBe false } } } And("App is not in debug mode") { every { MyBuildConfig.APPLICATION_ID } returns "me.kerooker.rpgcharactergenerator" When("stopAdsUntil is before now") { every { admobRepository.stopAdsUntil } returns Date().time - 1L Then("Ads should be shown") { target.shouldShowAd.value shouldBe true } Then("Ad banner ID should be production banner") { target.bannerAdId shouldBe "ca-app-pub-3225017918525788/2974185880" } Then("Rewarded ad ID should be production id") { target.rewardedAdId shouldBe "ca-app-pub-3225017918525788/7230261136" } } When("stopAdsUntil is after now") { every { admobRepository.stopAdsUntil } returns Date().time + 5_000L Then("Ads should not be shown") { target.shouldShowAd.value shouldBe false } } } } Given("The app ID contains PRO (Should suggest removal test)") { every { MyBuildConfig.APPLICATION_ID } returns "me.kerooker.rpgcharactergeneratorpro" And("stopAdsUntil is before now") { every { admobRepository.stopAdsUntil } returns Date().time - 1L And("stopSuggestingRemovalUntil is before now") { every { admobRepository.stopSuggestingRemovalUntil } returns Date().time - 1L Then("Should not suggest removing ads") { target.shouldSuggestRemovingAds() shouldBe false } } And("stopSuggestingRemovalUntil is after now") { every { admobRepository.stopSuggestingRemovalUntil } returns Date().time + 5_000L Then("Should not suggest removing ads") { target.shouldSuggestRemovingAds() shouldBe false } } } And("stopAdsUntil is after now") { every { admobRepository.stopAdsUntil } returns Date().time + 5_000L And("stopSuggestingRemovalUntil is before now") { every { admobRepository.stopSuggestingRemovalUntil } returns Date().time - 1L Then("Should not suggest removing ads") { target.shouldSuggestRemovingAds() shouldBe false } } And("stopSuggestingRemovalUntil is after now") { every { admobRepository.stopSuggestingRemovalUntil } returns Date().time + 5_000L Then("Should not suggest removing ads") { target.shouldSuggestRemovingAds() shouldBe false } } } } Given("The app ID doesn't contain PRO (Should suggest removal test)") { every { MyBuildConfig.APPLICATION_ID } returns "me.kerooker.rpgcharactergenerator" And("stopAdsUntil is before now") { every { admobRepository.stopAdsUntil } returns Date().time - 1L And("stopSuggestingRemovalUntil is before now") { every { admobRepository.stopSuggestingRemovalUntil } returns Date().time - 1L Then("Should suggest removing ads") { target.shouldSuggestRemovingAds() shouldBe true } } And("stopSuggestingRemovalUntil is after now") { every { admobRepository.stopSuggestingRemovalUntil } returns Date().time + 5_000L Then("Should not suggest removing ads") { target.shouldSuggestRemovingAds() shouldBe false } } } And("stopAdsUntil is after now") { every { admobRepository.stopAdsUntil } returns Date().time + 5_000L And("stopSuggestingRemovalUntil is before now") { every { admobRepository.stopSuggestingRemovalUntil } returns Date().time - 1L Then("Should not suggest removing ads") { target.shouldSuggestRemovingAds() shouldBe false } } And("stopSuggestingRemovalUntil is after now") { every { admobRepository.stopSuggestingRemovalUntil } returns Date().time + 5_000L Then("Should not suggest removing ads") { target.shouldSuggestRemovingAds() shouldBe false } } } } Given("The ad removal were suggested") { val setValue = slot<Long>() every { admobRepository setProperty "stopSuggestingRemovalUntil" value capture(setValue) } just Runs target.suggestedRemovingAds() Then("The value should be set to ten minutes from now") { val now = Date().time setValue.captured shouldBeInRange (now + (60 * 9 * 1000)..now + (60 * 11 * 1000)) } } Given("The rewarded ad was watched") { val stopAdsUntil = slot<Long>() val stopSuggestingRemovalUntil = slot<Long>() val now = Date().time every { admobRepository setProperty "stopAdsUntil" value capture(stopAdsUntil) } just Runs every { admobRepository setProperty "stopSuggestingRemovalUntil" value capture(stopSuggestingRemovalUntil) } just Runs every { admobRepository.stopAdsUntil }.returnsMany(now - 1_000, now + 10_000L) target.watchedRewardedAd() Then("There should be no ads for a day") { stopAdsUntil.captured shouldBeInRange (now + (24 * 59 * 60 * 1000)..now + (24 * 61 * 60 * 1000)) } Then("There should be no suggestion to remove ads for a day") { stopSuggestingRemovalUntil.captured shouldBeInRange (now + (24 * 59 * 60 * 1000)..now + (24 * 61 * 60 * 1000)) } Then("The should show ads value should be update to false") { target.shouldShowAd.value!! shouldBe false } } } override fun listeners() = listOf(InstantLivedataListener()) override fun isolationMode() = InstancePerTest }
apache-2.0
6d8cb105df50c3fa5a6437b3d343af41
41.496094
130
0.504918
5.458605
false
false
false
false
dhis2/dhis2-android-sdk
core/src/main/java/org/hisp/dhis/android/core/tracker/exporter/TrackerAPIQuery.kt
1
2283
/* * Copyright (c) 2004-2022, University of Oslo * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of the HISP project nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.hisp.dhis.android.core.tracker.exporter import org.hisp.dhis.android.core.arch.call.queries.internal.BaseQueryKt import org.hisp.dhis.android.core.enrollment.EnrollmentStatus import org.hisp.dhis.android.core.trackedentity.internal.TrackerQueryCommonParams internal data class TrackerAPIQuery( val commonParams: TrackerQueryCommonParams, val orgUnit: String? = null, val uids: Collection<String> = emptyList(), val programStatus: EnrollmentStatus? = null, val lastUpdatedStr: String? = null, override val page: Int = 1, override val pageSize: Int = DEFAULT_PAGE_SIZE, override val paging: Boolean = true ) : BaseQueryKt( page, pageSize, paging )
bsd-3-clause
6087065fbc71ab08a3a0f63ce16ebc13
47.574468
83
0.764345
4.365201
false
false
false
false
dbrant/apps-android-wikipedia
app/src/main/java/org/wikipedia/database/DatabaseTable.kt
1
3947
package org.wikipedia.database import android.content.ContentProviderClient import android.content.ContentValues import android.content.Context import android.database.Cursor import android.database.sqlite.SQLiteDatabase import android.net.Uri import org.wikipedia.database.column.Column import org.wikipedia.util.log.L import kotlin.math.max abstract class DatabaseTable<T>(private val tableName: String, val baseContentURI: Uri) { protected abstract val dBVersionIntroducedAt: Int private val dBVersionDroppedAt: Int get() = 0 abstract fun fromCursor(cursor: Cursor): T protected abstract fun toContentValues(obj: T): ContentValues? open fun getColumnsAdded(version: Int): Array<Column<*>> { return emptyArray() } fun acquireClient(context: Context): ContentProviderClient? { return context.contentResolver.acquireContentProviderClient(baseContentURI) } /** * Get the db query string to be passed to the content provider where selecting for a null * value (including, notably, the main namespace) may be necessary. * @param obj The object on which the formatting of the string depends. * @return A SQL WHERE clause formatted for the content provider. */ protected open fun getPrimaryKeySelection(obj: T, selectionArgs: Array<String>): String { var primaryKeySelection = "" val args = getUnfilteredPrimaryKeySelectionArgs(obj) for (i in args.indices) { primaryKeySelection += selectionArgs[i] + if (args[i] == null) " IS NULL" else " = ?" if (i < args.size - 1) { primaryKeySelection += " AND " } } return primaryKeySelection } /** * Get the selection arguments to be bound to the db query string. * @param obj The object from which selection args are derived. * @return The array of selection arguments with null values removed. (Null arguments are * replaced with "IS NULL" in getPrimaryKeySelection(T obj, String[] selectionKeys).) */ fun getPrimaryKeySelectionArgs(obj: T): Array<String> { return getUnfilteredPrimaryKeySelectionArgs(obj).filterNotNull().toTypedArray() } /** * Override to provide full list of selection arguments, including those which may have null * values, for use in constructing the SQL query string. * @param obj Object from which selection args are to be derived. * @return Array of selection arguments (including null values). */ protected abstract fun getUnfilteredPrimaryKeySelectionArgs(obj: T): Array<String?> fun upgradeSchema(db: SQLiteDatabase, fromVersion: Int, toVersion: Int) { if (fromVersion < dBVersionIntroducedAt) { createTables(db) onUpgradeSchema(db, fromVersion, dBVersionIntroducedAt) } for (ver in max(dBVersionIntroducedAt, fromVersion) + 1..toVersion) { L.i("ver=$ver") if (ver == dBVersionDroppedAt) { dropTable(db) break } for (column in getColumnsAdded(ver)) { val alterTableString = "ALTER TABLE $tableName ADD COLUMN $column" L.i(alterTableString) db.execSQL(alterTableString) } onUpgradeSchema(db, ver - 1, ver) } } protected open fun onUpgradeSchema(db: SQLiteDatabase, fromVersion: Int, toVersion: Int) {} protected fun createTables(db: SQLiteDatabase) { L.i("Creating table=$tableName") val cols = getColumnsAdded(dBVersionIntroducedAt) db.execSQL("CREATE TABLE IF NOT EXISTS " + tableName + " ( " + cols.joinToString(", ") + " )") } private fun dropTable(db: SQLiteDatabase) { db.execSQL("DROP TABLE IF EXISTS $tableName") L.i("Dropped table=$tableName") } companion object { const val INITIAL_DB_VERSION = 1 } }
apache-2.0
05c6aea5e0bc05c89c66c4d20b093282
37.320388
102
0.665062
4.542002
false
false
false
false
sallySalem/KotlinMvpEspresso
app/src/main/java/com/example/kotlinmvpespresso/ui/repositoriesList/RepositoriesListPresenter.kt
1
2579
package com.example.kotlinmvpespresso.ui.repositoriesList import android.os.Bundle import com.example.kotlinmvpespresso.data.model.RepositoryModel import com.example.kotlinmvpespresso.ui.base.BasePresenter import com.example.kotlinmvpespresso.useCase.RepositoryUseCase import com.example.kotlinmvpespresso.utils.Constants import retrofit2.Call import retrofit2.Callback import java.util.ArrayList import javax.inject.Inject /** * Created by sally on 7/7/17. */ class RepositoriesListPresenter @Inject constructor(val repositoryUseCase: RepositoryUseCase): BasePresenter<RepositoriesListView>(){ // var repositoryUseCase: RepositoryUseCase? = null var repositoriesList = ArrayList<RepositoryModel>() lateinit var gitHubAccountName: String override fun initialize(extras: Bundle?) { super.initialize(extras) if (extras != null) { gitHubAccountName = extras.getString(Constants.KEY_GIT_HUB_ACCOUNT_MODEL) } view?.initView(repositoriesList) getRepositoriesList() } fun onRepositoryListRefresh() { getRepositoriesList() } fun onItemClick(position: Int) { view?.navigateToRepositoryDetails(repositoriesList[position]) } private fun getRepositoriesList() { //Call backend to get repositories list repositoryUseCase.getRepositoriesList(gitHubAccountName, repositoriesListCallback) } private val repositoriesListCallback = object : Callback<ArrayList<RepositoryModel>> { override fun onResponse(call: Call<ArrayList<RepositoryModel>>, response: retrofit2.Response<ArrayList<RepositoryModel>>) { view?.hideSwipeRefreshLayout() if (response.isSuccessful) { //handle successful case with response val responseResult = response.body() if (responseResult != null && responseResult.size > 0) { repositoriesList.removeAll(repositoriesList) repositoriesList.addAll(responseResult) view?.loadRepositoriesList() } else { //handle successful case with empty response view?.hideRepositoriesList() } } else { view?.hideRepositoriesList() } } override fun onFailure(call: Call<ArrayList<RepositoryModel>>, t: Throwable) { //handle failure view?.hideSwipeRefreshLayout() view?.hideRepositoriesList() view?.showErrorMessage() } } }
mit
70de7cebec2db16feee8351cffb529b0
34.833333
133
0.670027
5.199597
false
false
false
false
guilhermesan/MvvmSimpleExempleAndroid
app/src/main/java/com/mvvm/exemple/mvvmexemple/MainViewModel.kt
1
522
package com.mvvm.exemple.mvvmexemple import android.arch.lifecycle.MutableLiveData import android.arch.lifecycle.ViewModel import android.os.Handler /** * Created by guilhermes on 9/27/17. */ class MainViewModel : ViewModel() { val sumLiveData = MutableLiveData<Double>() val counterLiveData = MutableLiveData<Int>() var counting = 1 fun sum(v1:Double,v2:Double){ sumLiveData.value = (v1 + v2) } fun add(){ counting++ counterLiveData.value = counting; } }
apache-2.0
f9b95ec7d82377805ecca60de2e00888
15.34375
48
0.670498
3.810219
false
false
false
false
cdietze/klay
klay-jvm/src/main/kotlin/klay/jvm/JvmBuffers.kt
1
4355
package klay.jvm import klay.core.buffers.* import java.nio.ByteOrder abstract class JvmBuffer : Buffer { abstract val nioBuffer: java.nio.Buffer override fun rewind(): Unit { nioBuffer.rewind() } override fun limit(): Int = nioBuffer.limit() override fun limit(length: Int) { nioBuffer.limit(length) } override fun position(): Int = nioBuffer.position() override fun position(i: Int) { nioBuffer.position(i) } override fun capacity(): Int = nioBuffer.capacity() } class JvmBuffers : klay.core.GL20.Buffers() { override fun createByteBuffer(size: Int): ByteBuffer { return JvmByteBuffer(java.nio.ByteBuffer.allocateDirect(size).order(ByteOrder.nativeOrder())) } override fun arrayCopy(src: IntArray, srcPos: Int, dest: IntArray, destPos: Int, length: Int) { System.arraycopy(src, srcPos, dest, destPos, length) } override fun arrayCopy(src: FloatArray, srcPos: Int, dest: FloatArray, destPos: Int, length: Int) { System.arraycopy(src, srcPos, dest, destPos, length) } } class JvmByteBuffer(override val nioBuffer: java.nio.ByteBuffer) : JvmBuffer(), ByteBuffer { override fun get(): Byte = nioBuffer.get() override fun get(dst: ByteArray, offset: Int, length: Int) { nioBuffer.get(dst, offset, length) } override fun put(src: ByteArray, offset: Int, length: Int) { nioBuffer.put(src, offset, length) } override fun asShortBuffer(): ShortBuffer = JvmShortBuffer(nioBuffer.asShortBuffer()) override fun asIntBuffer(): IntBuffer = JvmIntBuffer(nioBuffer.asIntBuffer()) override fun asFloatBuffer(): FloatBuffer = JvmFloatBuffer(nioBuffer.asFloatBuffer()) override fun asDoubleBuffer(): DoubleBuffer = JvmDoubleBuffer(nioBuffer.asDoubleBuffer()) } class JvmIntBuffer(private val intBuffer: java.nio.IntBuffer) : JvmBuffer(), IntBuffer { override val nioBuffer: java.nio.IntBuffer = intBuffer override fun get(): Int = intBuffer.get() override fun get(i: Int): Int = intBuffer.get(i) override fun get(dst: IntArray, offset: Int, length: Int) { intBuffer.get(dst, offset, length) } override fun put(n: Int): IntBuffer { intBuffer.put(n) return this } override fun put(src: IntArray, offset: Int, length: Int): IntBuffer { intBuffer.put(src, offset, length) return this } } class JvmShortBuffer(private val shortBuffer: java.nio.ShortBuffer) : JvmBuffer(), ShortBuffer { override val nioBuffer: java.nio.ShortBuffer = shortBuffer override fun get(): Short = shortBuffer.get() override fun get(i: Int): Short = shortBuffer.get(i) override fun get(dst: ShortArray, offset: Int, length: Int) { shortBuffer.get(dst, offset, length) } override fun put(n: Short): ShortBuffer { shortBuffer.put(n) return this } override fun put(src: ShortArray, offset: Int, length: Int): ShortBuffer { shortBuffer.put(src, offset, length) return this } } class JvmFloatBuffer(private val floatBuffer: java.nio.FloatBuffer) : JvmBuffer(), FloatBuffer { override val nioBuffer: java.nio.FloatBuffer = floatBuffer override fun get(): Float = floatBuffer.get() override fun get(i: Int): Float = floatBuffer.get(i) override fun get(dst: FloatArray, offset: Int, length: Int) { floatBuffer.get(dst, offset, length) } override fun put(n: Float): FloatBuffer { floatBuffer.put(n) return this } override fun put(src: FloatArray, offset: Int, length: Int): FloatBuffer { floatBuffer.put(src, offset, length) return this } } class JvmDoubleBuffer(private val doubleBuffer: java.nio.DoubleBuffer) : JvmBuffer(), DoubleBuffer { override val nioBuffer: java.nio.DoubleBuffer = doubleBuffer override fun get(): Double = doubleBuffer.get() override fun get(i: Int): Double = doubleBuffer.get(i) override fun get(dst: DoubleArray, offset: Int, length: Int) { doubleBuffer.get(dst, offset, length) } override fun put(n: Double): DoubleBuffer { doubleBuffer.put(n) return this } override fun put(src: DoubleArray, offset: Int, length: Int): DoubleBuffer { doubleBuffer.put(src, offset, length) return this } }
apache-2.0
580947b50cac784cffed6074b1ae180d
32
103
0.674168
4.116257
false
false
false
false
ngthtung2805/dalatlaptop
app/src/main/java/com/tungnui/dalatlaptop/views/TouchImageView.kt
1
7162
package com.tungnui.dalatlaptop.views import android.content.Context import android.graphics.Matrix import android.graphics.PointF import android.graphics.drawable.Drawable import android.util.AttributeSet import android.view.MotionEvent import android.view.ScaleGestureDetector import android.view.View import android.widget.ImageView import timber.log.Timber class TouchImageView : ImageView { var mode = NONE var last = PointF() var start = PointF() var minScale = 1f var maxScale = 3f lateinit var m: FloatArray internal var viewWidth: Int = 0 internal var viewHeight: Int = 0 internal var saveScale = 1f protected var origWidth: Float = 0.toFloat() protected var origHeight: Float = 0.toFloat() internal var oldMeasuredWidth: Int = 0 internal var oldMeasuredHeight: Int = 0 lateinit var mScaleDetector: ScaleGestureDetector constructor(context: Context) : super(context) { sharedConstructing(context) } constructor(context: Context, attrs: AttributeSet) : super(context, attrs) { sharedConstructing(context) } private fun sharedConstructing(context: Context) { super.setClickable(true) mScaleDetector = ScaleGestureDetector(context, ScaleListener()) m = FloatArray(9) imageMatrix = matrix scaleType = ImageView.ScaleType.MATRIX setOnTouchListener { v, event -> mScaleDetector.onTouchEvent(event) val curr = PointF(event.x, event.y) when (event.action) { MotionEvent.ACTION_DOWN -> { last.set(curr) start.set(last) mode = DRAG } MotionEvent.ACTION_MOVE -> if (mode == DRAG) { val deltaX = curr.x - last.x val deltaY = curr.y - last.y val fixTransX = getFixDragTrans(deltaX, viewWidth.toFloat(), origWidth * saveScale) val fixTransY = getFixDragTrans(deltaY, viewHeight.toFloat(), origHeight * saveScale) matrix.postTranslate(fixTransX, fixTransY) fixTrans() last.set(curr.x, curr.y) } MotionEvent.ACTION_UP -> { mode = NONE val xDiff = Math.abs(curr.x - start.x).toInt() val yDiff = Math.abs(curr.y - start.y).toInt() if (xDiff < CLICK && yDiff < CLICK) performClick() } MotionEvent.ACTION_POINTER_UP -> mode = NONE } imageMatrix = matrix invalidate() true // indicate event was handled } } fun setMaxZoom(x: Float) { maxScale = x } private inner class ScaleListener : ScaleGestureDetector.SimpleOnScaleGestureListener() { override fun onScaleBegin(detector: ScaleGestureDetector): Boolean { mode = ZOOM Timber.d("onScaleBegin mode = ZOOM") return true } override fun onScale(detector: ScaleGestureDetector): Boolean { var mScaleFactor = detector.scaleFactor val origScale = saveScale saveScale *= mScaleFactor if (saveScale > maxScale) { saveScale = maxScale mScaleFactor = maxScale / origScale } else if (saveScale < minScale) { saveScale = minScale mScaleFactor = minScale / origScale } if (origWidth * saveScale <= viewWidth || origHeight * saveScale <= viewHeight) matrix.postScale(mScaleFactor, mScaleFactor, (viewWidth / 2).toFloat(), (viewHeight / 2).toFloat()) else matrix.postScale(mScaleFactor, mScaleFactor, detector.focusX, detector.focusY) fixTrans() Timber.d("onScale SimpleOnScaleGestureListener") return true } } internal fun fixTrans() { matrix.getValues(m) val transX = m[Matrix.MTRANS_X] val transY = m[Matrix.MTRANS_Y] val fixTransX = getFixTrans(transX, viewWidth.toFloat(), origWidth * saveScale) val fixTransY = getFixTrans(transY, viewHeight.toFloat(), origHeight * saveScale) if (fixTransX != 0f || fixTransY != 0f) matrix.postTranslate(fixTransX, fixTransY) } internal fun getFixTrans(trans: Float, viewSize: Float, contentSize: Float): Float { val minTrans: Float val maxTrans: Float if (contentSize <= viewSize) { minTrans = 0f maxTrans = viewSize - contentSize } else { minTrans = viewSize - contentSize maxTrans = 0f } if (trans < minTrans) return -trans + minTrans return if (trans > maxTrans) -trans + maxTrans else 0f } internal fun getFixDragTrans(delta: Float, viewSize: Float, contentSize: Float): Float { return if (contentSize <= viewSize) { 0f } else delta } override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { super.onMeasure(widthMeasureSpec, heightMeasureSpec) viewWidth = View.MeasureSpec.getSize(widthMeasureSpec) viewHeight = View.MeasureSpec.getSize(heightMeasureSpec) // // Rescales image on rotation // if (oldMeasuredHeight == viewWidth && oldMeasuredHeight == viewHeight || viewWidth == 0 || viewHeight == 0) return oldMeasuredHeight = viewHeight oldMeasuredWidth = viewWidth if (saveScale == 1f) { // Fit to screen. val scale: Float val drawable = drawable if (drawable == null || drawable.intrinsicWidth == 0 || drawable.intrinsicHeight == 0) return val bmWidth = drawable.intrinsicWidth val bmHeight = drawable.intrinsicHeight // Timber.d("bmSize: bmWidth: " + bmWidth + " bmHeight : " + bmHeight); val scaleX = viewWidth.toFloat() / bmWidth.toFloat() val scaleY = viewHeight.toFloat() / bmHeight.toFloat() scale = Math.min(scaleX, scaleY) matrix.setScale(scale, scale) // Center the image var redundantYSpace = viewHeight.toFloat() - scale * bmHeight.toFloat() var redundantXSpace = viewWidth.toFloat() - scale * bmWidth.toFloat() redundantYSpace /= 2.toFloat() redundantXSpace /= 2.toFloat() matrix.postTranslate(redundantXSpace, redundantYSpace) origWidth = viewWidth - 2 * redundantXSpace origHeight = viewHeight - 2 * redundantYSpace imageMatrix = matrix } fixTrans() } companion object { internal val NONE = 0 internal val DRAG = 1 internal val ZOOM = 2 internal val CLICK = 3 } }
mit
9e5ae9618792eab9ebbabef5345613a6
32.783019
94
0.575538
4.888737
false
false
false
false
paplorinc/intellij-community
platform/testGuiFramework/src/com/intellij/testGuiFramework/fixtures/NavigationBarFixture.kt
8
1739
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.testGuiFramework.fixtures import com.intellij.ide.ui.UISettings import org.fest.swing.core.Robot import org.fest.swing.fixture.ContainerFixture import javax.swing.JPanel class NavigationBarFixture(robot: Robot, panel: JPanel, private val myIdeFrame: IdeFrameFixture) : ComponentFixture<NavigationBarFixture, JPanel>(NavigationBarFixture::class.java, robot, panel), ContainerFixture<JPanel> { private val VIEW_NAV_BAR_ACTION = "ViewNavigationBar" fun show() { if (!isShowing()) myIdeFrame.invokeMainMenu(VIEW_NAV_BAR_ACTION) } fun hide() { if (isShowing()) myIdeFrame.invokeMainMenu(VIEW_NAV_BAR_ACTION) } fun isShowing(): Boolean = UISettings.instance.showNavigationBar companion object { fun createNavigationBarFixture(robot: Robot, ideFrame: IdeFrameFixture): NavigationBarFixture { val navBarPanel = robot.finder() .find(ideFrame.target()) { component -> component is JPanel && isNavBar(component) } as JPanel return NavigationBarFixture(robot, navBarPanel, ideFrame) } fun isNavBar(navBarPanel: JPanel): Boolean = navBarPanel.name == "navbar" } }
apache-2.0
643552c90bff9df187ff8885db4386d0
35.25
124
0.749281
4.272727
false
false
false
false
reactor/reactor-extensions
reactor-extra/src/main/kotlin/reactor/retry/RepeatExtensions.kt
1
5070
package reactor.retry import reactor.core.publisher.Flux import reactor.core.publisher.Mono import java.time.Duration import java.util.function.Consumer /** * Extension to add a [Flux.repeat] variant to [Flux] that uses an exponential backoff, * as enabled by reactor-extra's [Repeat] builder. * * @param times the maximum number of retry attempts * @param first the initial delay in retrying * @param max the optional upper limit the delay can reach after subsequent backoffs * @param jitter optional flag to activate random jitter in the backoffs * @param doOnRepeat optional [Consumer]-like lambda that will receive a [RepeatContext] * each time an attempt is made. * * @author Simon Baslé * @since 3.1.1 */ @Deprecated("To be removed in 3.3.0.RELEASE, replaced by module reactor-kotlin-extensions", ReplaceWith("repeatExponentialBackoff(times, first, max, jitter, doOnRepeat)", "reactor.kotlin.extra.retry.repeatExponentialBackoff")) fun <T> Flux<T>.repeatExponentialBackoff(times: Long, first: Duration, max: Duration? = null, jitter: Boolean = false, doOnRepeat: ((RepeatContext<T>) -> Unit)? = null): Flux<T> { val repeat = Repeat.times<T>(times) .exponentialBackoff(first, max) .jitter(if (jitter) Jitter.random() else Jitter.noJitter()) return if (doOnRepeat == null) repeat.apply(this) else repeat.doOnRepeat(doOnRepeat).apply(this) } /** * Extension to add a [Flux.repeat] variant to [Flux] that uses a randomized backoff, * as enabled by reactor-extra's [Repeat] builder. * * @param times the maximum number of retry attempts * @param first the initial delay in retrying * @param max the optional upper limit the delay can reach after subsequent backoffs * @param doOnRepeat optional [Consumer]-like lambda that will receive a [RepeatContext] * each time an attempt is made. * * @author Simon Baslé * @since 3.1.1 */ @Deprecated("To be removed in 3.3.0.RELEASE, replaced by module reactor-kotlin-extensions", ReplaceWith("repeatRandomBackoff(times, first, max, doOnRepeat)", "reactor.kotlin.extra.retry.repeatRandomBackoff")) fun <T> Flux<T>.repeatRandomBackoff(times: Long, first: Duration, max: Duration? = null, doOnRepeat: ((RepeatContext<T>) -> Unit)? = null): Flux<T> { val repeat = Repeat.times<T>(times) .randomBackoff(first, max) return if (doOnRepeat == null) repeat.apply(this) else repeat.doOnRepeat(doOnRepeat).apply(this) } /** * Extension to add a [Mono.repeat] variant to [Mono] that uses an exponential backoff, * as enabled by reactor-extra's [Repeat] builder. * * @param times the maximum number of retry attempts * @param first the initial delay in retrying * @param max the optional upper limit the delay can reach after subsequent backoffs * @param jitter optional flag to activate random jitter in the backoffs * @param doOnRepeat optional [Consumer]-like lambda that will receive a [RepeatContext] * each time an attempt is made. * * @author Simon Baslé * @since 3.1.1 */ @Deprecated("To be removed in 3.3.0.RELEASE, replaced by module reactor-kotlin-extensions", ReplaceWith("repeatExponentialBackoff(times, first, max, jitter, doOnRepeat)", "reactor.kotlin.extra.retry.repeatExponentialBackoff")) fun <T> Mono<T>.repeatExponentialBackoff(times: Long, first: Duration, max: Duration? = null, jitter: Boolean = false, doOnRepeat: ((RepeatContext<T>) -> Unit)? = null): Flux<T> { val repeat = Repeat.times<T>(times) .exponentialBackoff(first, max) .jitter(if (jitter) Jitter.random() else Jitter.noJitter()) return if (doOnRepeat == null) repeat.apply(this) else repeat.doOnRepeat(doOnRepeat).apply(this) } /** * Extension to add a [Mono.repeat] variant to [Mono] that uses a randomized backoff, * as enabled by reactor-extra's [Repeat] builder. * * @param times the maximum number of retry attempts * @param first the initial delay in retrying * @param max the optional upper limit the delay can reach after subsequent backoffs * @param doOnRepeat optional [Consumer]-like lambda that will receive a [RepeatContext] * each time an attempt is made. * * @author Simon Baslé * @since 3.1.1 */ @Deprecated("To be removed in 3.3.0.RELEASE, replaced by module reactor-kotlin-extensions", ReplaceWith("repeatRandomBackoff(times, first, max, doOnRepeat)", "reactor.kotlin.extra.retry.repeatRandomBackoff")) fun <T> Mono<T>.repeatRandomBackoff(times: Long, first: Duration, max: Duration? = null, doOnRepeat: ((RepeatContext<T>) -> Unit)? = null): Flux<T> { val repeat = Repeat.times<T>(times) .randomBackoff(first, max) return if (doOnRepeat == null) repeat.apply(this) else repeat.doOnRepeat(doOnRepeat).apply(this) }
apache-2.0
aa277c7354789d035875272e53a8b39e
42.307692
142
0.679629
3.905937
false
false
false
false
google/intellij-community
plugins/kotlin/base/project-structure/src/org/jetbrains/kotlin/idea/base/projectStructure/moduleInfo/LibraryInfo.kt
3
5387
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.base.projectStructure.moduleInfo import com.intellij.openapi.module.Module import com.intellij.openapi.project.Project import com.intellij.openapi.roots.OrderRootType import com.intellij.openapi.roots.impl.libraries.LibraryEx import com.intellij.openapi.roots.libraries.Library import com.intellij.openapi.util.ModificationTracker import com.intellij.openapi.vfs.VirtualFile import com.intellij.psi.search.GlobalSearchScope import com.intellij.serviceContainer.AlreadyDisposedException import com.intellij.util.PathUtil import org.jetbrains.kotlin.analyzer.* import org.jetbrains.kotlin.idea.base.projectStructure.* import org.jetbrains.kotlin.idea.base.projectStructure.compositeAnalysis.findAnalyzerServices import org.jetbrains.kotlin.idea.base.projectStructure.libraryToSourceAnalysis.ResolutionAnchorCacheService import org.jetbrains.kotlin.idea.base.projectStructure.libraryToSourceAnalysis.useLibraryToSourceAnalysis import org.jetbrains.kotlin.idea.base.projectStructure.scope.PoweredLibraryScopeBase import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.platform.* import org.jetbrains.kotlin.resolve.PlatformDependentAnalyzerServices abstract class LibraryInfo( override val project: Project, val library: Library ) : IdeaModuleInfo, LibraryModuleInfo, BinaryModuleInfo, TrackableModuleInfo { private val libraryWrapper = LibraryWrapper(library as LibraryEx) override val moduleOrigin: ModuleOrigin get() = ModuleOrigin.LIBRARY override val name: Name = Name.special("<library ${library.name}>") override val displayedName: String get() = KotlinBaseProjectStructureBundle.message("library.0", library.name.toString()) override val contentScope: GlobalSearchScope get() = LibraryWithoutSourceScope(project, library) override fun dependencies(): List<IdeaModuleInfo> { val dependencies = LibraryDependenciesCache.getInstance(project).getLibraryDependencies(this) return LinkedHashSet<IdeaModuleInfo>(dependencies.libraries.size + dependencies.sdk.size + 1).apply { add(this@LibraryInfo) addAll(dependencies.sdk) addAll(dependencies.libraries) }.toList() } abstract override val platform: TargetPlatform // must override override val analyzerServices: PlatformDependentAnalyzerServices get() = platform.findAnalyzerServices(project) private val _sourcesModuleInfo: SourceForBinaryModuleInfo by lazy { LibrarySourceInfo(project, library, this) } override val sourcesModuleInfo: SourceForBinaryModuleInfo get() = _sourcesModuleInfo override fun getLibraryRoots(): Collection<String> = library.getFiles(OrderRootType.CLASSES).mapNotNull(PathUtil::getLocalPath) override fun createModificationTracker(): ModificationTracker = if (!project.useLibraryToSourceAnalysis) { ModificationTracker.NEVER_CHANGED } else { ResolutionAnchorAwareLibraryModificationTracker(this) } internal val isDisposed get() = if (library is LibraryEx) library.isDisposed else false override fun checkValidity() { if (isDisposed) { throw AlreadyDisposedException("Library '${name}' is already disposed") } } override fun toString() = "${this::class.simpleName}(libraryName=${library.name}${if (!isDisposed) ", libraryRoots=${getLibraryRoots()}" else " -disposed-"})" override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is LibraryInfo) return false return libraryWrapper == other.libraryWrapper } override fun hashCode() = libraryWrapper.hashCode() } private class ResolutionAnchorAwareLibraryModificationTracker(libraryInfo: LibraryInfo) : ModificationTracker { private val dependencyModules: List<Module> = if (!libraryInfo.isDisposed) { ResolutionAnchorCacheService.getInstance(libraryInfo.project) .getDependencyResolutionAnchors(libraryInfo) .map { it.module } } else { emptyList() } override fun getModificationCount(): Long { if (dependencyModules.isEmpty()) { return ModificationTracker.NEVER_CHANGED.modificationCount } val project = dependencyModules.first().project val modificationTrackerProvider = KotlinModificationTrackerProvider.getInstance(project) return dependencyModules .maxOfOrNull(modificationTrackerProvider::getModuleSelfModificationCount) ?: ModificationTracker.NEVER_CHANGED.modificationCount } } @Suppress("EqualsOrHashCode") // DelegatingGlobalSearchScope requires to provide calcHashCode() private class LibraryWithoutSourceScope( project: Project, private val library: Library ) : PoweredLibraryScopeBase(project, library.getFiles(OrderRootType.CLASSES), arrayOf()) { override fun getFileRoot(file: VirtualFile): VirtualFile? = myIndex.getClassRootForFile(file) override fun equals(other: Any?) = other is LibraryWithoutSourceScope && library == other.library override fun calcHashCode(): Int = library.hashCode() override fun toString() = "LibraryWithoutSourceScope($library)" }
apache-2.0
d480619d4289af65927e94a2de0d9d9e
41.09375
140
0.754223
5.174832
false
false
false
false
JetBrains/intellij-community
python/src/com/jetbrains/python/console/PydevConsoleRunnerFactory.kt
1
13493
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.jetbrains.python.console import com.intellij.execution.target.TargetEnvironment import com.intellij.execution.target.value.* import com.intellij.openapi.module.Module import com.intellij.openapi.project.Project import com.intellij.openapi.projectRoots.Sdk import com.intellij.openapi.roots.ModuleRootManager import com.intellij.openapi.roots.ProjectRootManager import com.intellij.openapi.util.registry.Registry import com.intellij.openapi.vfs.LocalFileSystem import com.intellij.util.PathMapper import com.jetbrains.python.console.PyConsoleOptions.PyConsoleSettings import com.jetbrains.python.remote.PyRemotePathMapper import com.jetbrains.python.run.* import com.jetbrains.python.run.PythonInterpreterTargetEnvironmentFactory.Companion.findPythonTargetInterpreter import com.jetbrains.python.sdk.PythonEnvUtil import org.jetbrains.annotations.ApiStatus import java.nio.file.Path import java.util.function.Function open class PydevConsoleRunnerFactory : PythonConsoleRunnerFactory() { @ApiStatus.Experimental protected sealed class ConsoleParameters(val project: Project, val sdk: Sdk?, @ApiStatus.ScheduledForRemoval @Deprecated("Use `ConstantConsoleParameters.workingDir`") open val workingDir: String?, val envs: Map<String, String>, val consoleType: PyConsoleType, val settingsProvider: PyConsoleSettings) @ApiStatus.Experimental protected class ConstantConsoleParameters(project: Project, sdk: Sdk?, @Suppress("OVERRIDE_DEPRECATION") override val workingDir: String?, envs: Map<String, String>, consoleType: PyConsoleType, settingsProvider: PyConsoleSettings, val setupFragment: Array<String>) : ConsoleParameters(project, sdk, workingDir, envs, consoleType, settingsProvider) @ApiStatus.Experimental protected class TargetedConsoleParameters private constructor(project: Project, sdk: Sdk?, workingDir: String?, val workingDirFunction: TargetEnvironmentFunction<String>?, envs: Map<String, String>, consoleType: PyConsoleType, settingsProvider: PyConsoleSettings, val setupScript: TargetEnvironmentFunction<String>) : ConsoleParameters(project, sdk, workingDir, envs, consoleType, settingsProvider) { constructor(project: Project, sdk: Sdk?, workingDirFunction: TargetEnvironmentFunction<String>?, envs: Map<String, String>, consoleType: PyConsoleType, settingsProvider: PyConsoleSettings, setupScript: TargetEnvironmentFunction<String>) : this(project, sdk, null, workingDirFunction, envs, consoleType, settingsProvider, setupScript) @Deprecated("Use another constructor") @ApiStatus.ScheduledForRemoval constructor(project: Project, sdk: Sdk?, workingDir: String?, envs: Map<String, String>, consoleType: PyConsoleType, settingsProvider: PyConsoleSettings, setupScript: TargetEnvironmentFunction<String>) : this(project, sdk, workingDir, workingDir?.let { constant(it) }, envs, consoleType, settingsProvider, setupScript) } protected open fun createConsoleParameters(project: Project, contextModule: Module?): ConsoleParameters { val sdkAndModule = findPythonSdkAndModule(project, contextModule) val module = sdkAndModule.second val sdk = sdkAndModule.first val settingsProvider = PyConsoleOptions.getInstance(project).pythonConsoleSettings val pathMapper = getPathMapper(project, sdk, settingsProvider) val envs = settingsProvider.envs.toMutableMap() putIPythonEnvFlag(project, envs) if (Registry.`is`("python.use.targets.api")) { val workingDirFunction = getWorkingDirFunction(project, module, pathMapper, settingsProvider) val setupScriptFunction = createSetupScriptFunction(project, module, workingDirFunction, pathMapper, settingsProvider) return TargetedConsoleParameters(project, sdk, workingDirFunction, envs, PyConsoleType.PYTHON, settingsProvider, setupScriptFunction) } else { val workingDir = getWorkingDir(project, module, pathMapper, settingsProvider) val setupFragment = createSetupFragment(module, workingDir, pathMapper, settingsProvider) return ConstantConsoleParameters(project, sdk, workingDir, envs, PyConsoleType.PYTHON, settingsProvider, setupFragment) } } override fun createConsoleRunner(project: Project, contextModule: Module?): PydevConsoleRunner { val module = PyConsoleCustomizer.EP_NAME.extensionList.firstNotNullOfOrNull { it.guessConsoleModule(project, contextModule) } return when (val consoleParameters = createConsoleParameters(project, module)) { is ConstantConsoleParameters -> PydevConsoleRunnerImpl(project, consoleParameters.sdk, consoleParameters.consoleType, consoleParameters.workingDir, consoleParameters.envs, consoleParameters.settingsProvider, *consoleParameters.setupFragment) is TargetedConsoleParameters -> PydevConsoleRunnerImpl(project, consoleParameters.sdk, consoleParameters.consoleType, consoleParameters.consoleType.title, consoleParameters.workingDirFunction, consoleParameters.envs, consoleParameters.settingsProvider, consoleParameters.setupScript) } } override fun createConsoleRunnerWithFile(project: Project, config: PythonRunConfiguration): PydevConsoleRunner { val consoleParameters = createConsoleParameters(project, config.module) val sdk = if (config.sdk != null) config.sdk else consoleParameters.sdk val consoleEnvs = mutableMapOf<String, String>() consoleEnvs.putAll(consoleParameters.envs) consoleEnvs.putAll(config.envs) return when (consoleParameters) { is ConstantConsoleParameters -> PydevConsoleWithFileRunnerImpl(project, sdk, consoleParameters.consoleType, config.name, config.workingDirectory ?: consoleParameters.workingDir, consoleEnvs, consoleParameters.settingsProvider, config, *consoleParameters.setupFragment) is TargetedConsoleParameters -> PydevConsoleWithFileRunnerImpl(project, sdk, consoleParameters.consoleType, config.name, config.workingDirectory?.let { targetPath(Path.of(it)) } ?: consoleParameters.workingDirFunction, consoleEnvs, consoleParameters.settingsProvider, config, consoleParameters.setupScript) } } companion object { fun putIPythonEnvFlag(project: Project, envs: MutableMap<String, String>) { putIPythonEnvFlag(project, PlainEnvironmentController(envs)) } @JvmStatic fun putIPythonEnvFlag(project: Project, environmentController: EnvironmentController) { val ipythonEnabled = if (PyConsoleOptions.getInstance(project).isIpythonEnabled) "True" else "False" environmentController.putFixedValue(PythonEnvUtil.IPYTHONENABLE, ipythonEnabled) } fun getWorkingDir(project: Project, module: Module?, pathMapper: PathMapper?, settingsProvider: PyConsoleSettings): String? { var workingDir = getWorkingDirFromSettings(project, module, settingsProvider) if (pathMapper != null && workingDir != null) { workingDir = pathMapper.convertToRemote(workingDir) } return workingDir } private fun getWorkingDirFunction(project: Project, module: Module?, pathMapper: PathMapper?, settingsProvider: PyConsoleSettings): TargetEnvironmentFunction<String>? { val workingDir = getWorkingDirFromSettings(project, module, settingsProvider) if (pathMapper != null && workingDir != null && pathMapper.canReplaceLocal(workingDir)) { return constant(pathMapper.convertToRemote(workingDir)) } return if (workingDir.isNullOrEmpty()) null else targetPath(Path.of(workingDir)) } private fun getWorkingDirFromSettings(project: Project, module: Module?, settingsProvider: PyConsoleSettings): String? { val workingDirectoryInSettings = settingsProvider.workingDirectory if (!workingDirectoryInSettings.isNullOrEmpty()) { return workingDirectoryInSettings } if (module != null && ModuleRootManager.getInstance(module).contentRoots.isNotEmpty()) { return ModuleRootManager.getInstance(module).contentRoots[0].path } val projectRoots = ProjectRootManager.getInstance(project).contentRoots for (root in projectRoots) { if (root.fileSystem is LocalFileSystem) { // we can't start Python Console in remote folder without additional connection configurations return root.path } } return System.getProperty("user.home") } fun createSetupFragment(module: Module?, workingDir: String?, pathMapper: PathMapper?, settingsProvider: PyConsoleSettings): Array<String> { var customStartScript = settingsProvider.customStartScript if (customStartScript.isNotBlank()) { customStartScript = "\n" + customStartScript } var pythonPath = PythonCommandLineState.collectPythonPath(module, settingsProvider.shouldAddContentRoots(), settingsProvider.shouldAddSourceRoots()) if (pathMapper != null) { pythonPath = pathMapper.convertToRemote(pythonPath) } val selfPathAppend = constructPyPathAndWorkingDirCommand(pythonPath, workingDir, customStartScript) return arrayOf(selfPathAppend) } private fun makeStartWithEmptyLine(line: String): String { if (line.startsWith("\n") || line.isBlank()) return line return "\n" + line } private fun createSetupScriptFunction(project: Project, module: Module?, workingDir: TargetEnvironmentFunction<String>?, pathMapper: PyRemotePathMapper?, settingsProvider: PyConsoleSettings): TargetEnvironmentFunction<String> { val customStartScript = makeStartWithEmptyLine(settingsProvider.customStartScript) val pythonPathFuns = collectPythonPath(project, module, settingsProvider.mySdkHome, pathMapper, settingsProvider.shouldAddContentRoots(), settingsProvider.shouldAddSourceRoots(), false).toMutableSet() return constructPyPathAndWorkingDirCommand(pythonPathFuns, workingDir, customStartScript) } fun createSetupScriptWithHelpersAndProjectRoot(project: Project, projectRoot: String, sdk: Sdk, settingsProvider: PyConsoleSettings): TargetEnvironmentFunction<String> { val paths = ArrayList<Function<TargetEnvironment, String>>() paths.add(getTargetEnvironmentValueForLocalPath(Path.of(projectRoot))) val targetEnvironmentRequest = findPythonTargetInterpreter(sdk, project) val helpersTargetPath = targetEnvironmentRequest.preparePyCharmHelpers() for (helper in listOf("pycharm", "pydev")) { paths.add(helpersTargetPath.getRelativeTargetPath(helper)) } val pathStr = paths.joinToStringFunction(separator = ", ", transform = String::toStringLiteral) val projectRootStr = getTargetEnvironmentValueForLocalPath(Path.of(projectRoot)).toStringLiteral() val replaces = listOf(PydevConsoleRunnerImpl.WORKING_DIR_AND_PYTHON_PATHS to pathStr, PydevConsoleRunnerImpl.PROJECT_ROOT to projectRootStr) return ReplaceSubstringsFunction(makeStartWithEmptyLine(settingsProvider.customStartScript), replaces) } } }
apache-2.0
42a44ac3ac5faead53fcdb0ccb16db1f
60.899083
173
0.640851
5.946673
false
true
false
false
JetBrains/intellij-community
java/java-impl/src/com/intellij/lang/java/actions/PropertyRenderer.kt
1
5408
// 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.lang.java.actions import com.intellij.codeInsight.CodeInsightUtil.positionCursor import com.intellij.codeInsight.CodeInsightUtilCore.forcePsiPostprocessAndRestoreElement import com.intellij.codeInsight.ExpectedTypeInfo import com.intellij.codeInsight.daemon.impl.quickfix.CreateFromUsageUtils.ParameterNameExpression import com.intellij.codeInsight.daemon.impl.quickfix.GuessTypeParameters import com.intellij.codeInsight.template.TemplateBuilderImpl import com.intellij.codeInsight.template.TemplateManager import com.intellij.codeInsight.template.impl.VariableNode import com.intellij.lang.java.beans.PropertyKind import com.intellij.lang.java.request.CreateMethodFromJavaUsageRequest import com.intellij.lang.jvm.JvmModifier import com.intellij.lang.jvm.actions.CreateMethodRequest import com.intellij.openapi.editor.Document import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.psi.* import com.intellij.psi.codeStyle.JavaCodeStyleManager import com.intellij.psi.codeStyle.VariableKind internal abstract class PropertyRenderer( private val project: Project, private val target: PsiClass, private val request: CreateMethodRequest, nameKind: Pair<String, PropertyKind> ) { private val factory = JavaPsiFacade.getInstance(project).elementFactory private val codeStyleManager = JavaCodeStyleManager.getInstance(project)!! private val javaUsage = request as? CreateMethodFromJavaUsageRequest private val isStatic = JvmModifier.STATIC in request.modifiers private val propertyName = nameKind.first protected val propertyKind = nameKind.second private val suggestedFieldName = run { val kind = if (isStatic) VariableKind.STATIC_FIELD else VariableKind.FIELD codeStyleManager.propertyNameToVariableName(propertyName, kind) } fun generatePrototypeField(): PsiField { val prototypeType = if (propertyKind == PropertyKind.BOOLEAN_GETTER || isBooleanSetter()) PsiType.BOOLEAN else PsiType.VOID return factory.createField(suggestedFieldName, prototypeType).setStatic(isStatic) } private fun isBooleanSetter(): Boolean { if (propertyKind == PropertyKind.SETTER) { val expectedType = request.expectedParameters.single().expectedTypes.singleOrNull() return expectedType != null && PsiType.BOOLEAN == JvmPsiConversionHelper.getInstance(project).convertType(expectedType.theType) } return false } private val expectedTypes: List<ExpectedTypeInfo> = when (propertyKind) { PropertyKind.GETTER -> extractExpectedTypes(project, request.returnType).orObject(target) PropertyKind.BOOLEAN_GETTER -> listOf(PsiType.BOOLEAN.toExpectedType()) PropertyKind.SETTER -> extractExpectedTypes(project, request.expectedParameters.single().expectedTypes).orObject(target) } private lateinit var targetDocument: Document private lateinit var targetEditor: Editor private fun navigate(): Boolean { val targetFile = target.containingFile ?: return false targetDocument = targetFile.viewProvider.document ?: return false targetEditor = positionCursor(project, targetFile, target) ?: return false return true } fun doRender() { if (!navigate()) return val builder = TemplateBuilderImpl(target) builder.setGreedyToRight(true) val typeExpression = fillTemplate(builder) ?: return val template = builder.buildInlineTemplate().apply { isToShortenLongNames = true } val listener = InsertMissingFieldTemplateListener(project, target, typeExpression, isStatic) TemplateManager.getInstance(project).startTemplate(targetEditor, template, listener) } protected abstract fun fillTemplate(builder: TemplateBuilderImpl): RangeExpression? protected fun insertAccessor(prototype: PsiMethod): PsiMethod? { val method = target.add(prototype) as PsiMethod return forcePsiPostprocessAndRestoreElement(method) } private fun TemplateBuilderImpl.createTemplateContext(): TemplateContext { val substitutor = request.targetSubstitutor.toPsiSubstitutor(project) val guesser = GuessTypeParameters(project, factory, this, substitutor) return TemplateContext(project, factory, target, this, guesser, javaUsage?.context) } protected fun TemplateBuilderImpl.setupInput(input: AccessorTemplateData): RangeExpression { val templateTypeElement = createTemplateContext().setupTypeElement(input.typeElement, expectedTypes) val typeExpression = RangeExpression(targetDocument, templateTypeElement.textRange) val fieldExpression = FieldExpression(project, target, suggestedFieldName) { typeExpression.text } replaceElement(input.fieldRef, FIELD_VARIABLE, fieldExpression, true) input.endElement?.let(::setEndVariableAfter) return typeExpression } protected fun TemplateBuilderImpl.setupSetterParameter(data: SetterTemplateData) { val suggestedNameInfo = codeStyleManager.suggestVariableName(VariableKind.PARAMETER, propertyName, null, null) val setterParameterExpression = ParameterNameExpression(suggestedNameInfo.names) replaceElement(data.parameterName, SETTER_PARAM_NAME, setterParameterExpression, true) replaceElement(data.parameterRef, VariableNode(SETTER_PARAM_NAME, null), false) // copy setter parameter name to mirror } }
apache-2.0
9a120caf48ccbefa0592ded54d2d9d09
46.858407
133
0.8027
5.049486
false
false
false
false
ursjoss/sipamato
common/common-wicket/src/test/kotlin/ch/difty/scipamato/common/web/WicketBaseTest.kt
1
1411
package ch.difty.scipamato.common.web import org.apache.wicket.markup.head.filter.JavaScriptFilteredIntoFooterHeaderResponse import org.apache.wicket.protocol.http.WebApplication import org.apache.wicket.util.tester.WicketTester import org.junit.jupiter.api.BeforeEach import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.test.context.SpringBootTest import org.springframework.context.ApplicationContext import org.springframework.test.util.ReflectionTestUtils internal const val USERNAME = "testuser" internal const val PASSWORD = "secretpw" @SpringBootTest(classes = [TestApplication::class]) abstract class WicketBaseTest { protected lateinit var tester: WicketTester @Autowired private lateinit var wicketApplication: WebApplication @Autowired private lateinit var applicationContextMock: ApplicationContext @BeforeEach internal fun setUp() { wicketApplication.headerResponseDecorators.add { r -> JavaScriptFilteredIntoFooterHeaderResponse(r, AbstractPage.FOOTER_CONTAINER) } ReflectionTestUtils.setField(wicketApplication, "applicationContext", applicationContextMock) tester = WicketTester(wicketApplication) val locale = java.util.Locale("en_US") tester.session.locale = locale setUpHook() } /** * override if needed */ protected open fun setUpHook() {} }
gpl-3.0
f1fc48fb70cc57cfa526f18e5b35a230
33.414634
140
0.779589
4.734899
false
true
false
false
lomza/screenlookcount
app/src/main/java/com/totemsoft/screenlookcount/background/LookCounterService.kt
1
3151
package com.totemsoft.screenlookcount.background import android.app.NotificationChannel import android.app.NotificationManager import android.app.PendingIntent import android.app.Service import android.content.Intent import android.content.IntentFilter import android.os.Build import android.os.IBinder import android.support.v4.app.NotificationCompat import com.totemsoft.screenlookcount.ActivityMain import com.totemsoft.screenlookcount.R /** * Service which starts a receiver for catching SCREEN_ON, SCREEN_OFF, and USER_PRESENT events. * * @author Antonina */ class LookCounterService : Service() { private val SERVICE_ID = 1 private lateinit var screenLookReceiver: ScreenLookReceiver override fun onBind(intent: Intent?): IBinder? { return null } override fun onCreate() { super.onCreate() registerScreenLookReceiver() } override fun onDestroy() { unregisterReceiver(screenLookReceiver) super.onDestroy() } override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { startForegroundServiceWithNotification() return super.onStartCommand(intent, flags, startId) } private fun registerScreenLookReceiver() { val filter = IntentFilter(Intent.ACTION_SCREEN_ON) with(filter) { addAction(Intent.ACTION_SCREEN_OFF) addAction(Intent.ACTION_USER_PRESENT) } screenLookReceiver = ScreenLookReceiver() registerReceiver(screenLookReceiver, filter) } private fun startForegroundServiceWithNotification() { val intent = Intent(this, ActivityMain::class.java) val pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT) val builder: NotificationCompat.Builder if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { val channelName = getString(R.string.notification_channel_screen_looks) val importance = NotificationManager.IMPORTANCE_LOW val channelId = "LOOK_COUNTS_CHANNEL_ID" val channel = NotificationChannel(channelId, channelName, importance) channel.setShowBadge(false) builder = NotificationCompat.Builder(this, channelId) val notificatioManager = getSystemService(NotificationManager::class.java) notificatioManager.createNotificationChannel(channel) } else { builder = NotificationCompat.Builder(this) } val icon = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) R.mipmap.ic_notification else R.mipmap.ic_launcher with(builder) { setContentTitle(getString(R.string.app_name)) setContentText(getString(R.string.notification_service_description)) setWhen(System.currentTimeMillis()) setSmallIcon(icon) setContentIntent(pendingIntent) priority = NotificationCompat.PRIORITY_DEFAULT setVisibility(NotificationCompat.VISIBILITY_SECRET) } val notification = builder.build() startForeground(SERVICE_ID, notification) } }
gpl-3.0
779960d78607a9ede616db6c18a45fbb
33.25
121
0.698826
4.832822
false
false
false
false
JetBrains/teamcity-dnx-plugin
plugin-dotnet-agent/src/main/kotlin/jetbrains/buildServer/rx/Observables.kt
1
9416
package jetbrains.buildServer.rx import java.util.concurrent.atomic.AtomicBoolean import java.util.concurrent.atomic.AtomicInteger import java.util.concurrent.atomic.AtomicLong import java.util.concurrent.atomic.AtomicReference inline fun <T> observable(crossinline subscriber: Observer<T>.() -> Disposable): Observable<T> = object : Observable<T> { override fun subscribe(observer: Observer<T>): Disposable = subscriber(observer) } fun <T> observableOf(vararg values: T): Observable<T> = if (values.isEmpty()) emptyObservable() else values.asSequence().toObservable() fun <T> emptyObservable(): Observable<T> = observable { onComplete() emptyDisposable() } inline fun <T> Observable<T>.subscribe(crossinline onNext: (T) -> Unit): Disposable = subscribe(observer(onNext)) inline fun <T> Observable<T>.subscribe(crossinline onNext: (T) -> Unit, crossinline onError: (Exception) -> Unit, crossinline onComplete: () -> Unit): Disposable = subscribe(observer(onNext, onError, onComplete)) inline fun <T, R> Observable<T>.map(crossinline map: (T) -> R): Observable<R> = observable { subscribe( { onNext(map(it)) }, { onError(it) }, { onComplete() }) } inline fun <T, reified R: T> Observable<T>.ofType(): Observable<R> = observable { subscribe( { if (it is R) onNext(it) }, { onError(it) }, { onComplete() }) } inline fun <T, R> Observable<T>.reduce(initialValue: R, crossinline operation: (acc: R, T) -> R): Observable<R> = observable { var accumulator: R = initialValue val lockObject = Object() subscribe( { synchronized(lockObject) { accumulator = operation(accumulator, it) } }, { onError(it) }, { synchronized(lockObject) { onNext(accumulator) } onComplete() }) } inline fun <T> Observable<T>.filter(crossinline filter: (T) -> Boolean): Observable<T> = observable { subscribe( { if (filter(it)) onNext(it) }, { onError(it) }, { onComplete() }) } inline fun <T> Observable<T>.until(crossinline completionCondition: (T) -> Boolean): Observable<T> = observable { val isCompleted = AtomicBoolean(false) subscribe( { if (isCompleted.compareAndSet(false, completionCondition(it))) { onNext(it) if (isCompleted.get()) { onComplete() } } }, { if (!isCompleted.get()) onError(it) }, { if (!isCompleted.get()) onComplete() }) } fun <T> Observable<T>.take(range: LongRange): Observable<T> = observable { val position = AtomicLong(0) map { Pair(it, position.getAndIncrement()) } .until { it.second >= range.endInclusive } .filter { range.contains(it.second) } .map { it.first } .subscribe(this) } fun <T> Observable<T>.distinct(): Observable<T> = observable { val set = hashSetOf<T>() filter { synchronized(set) { set.add(it) } }.subscribe(this) } fun <T> Observable<T>.take(range: IntRange): Observable<T> = take(LongRange(range.start.toLong(), range.endInclusive.toLong())) fun <T> Observable<T>.first(): Observable<T> = take(LongRange(0, 0)) fun <T> Observable<T>.last(): Observable<T> = observable { val lastValue: AtomicReference<T> = AtomicReference() subscribe( { lastValue.set(it) }, { onError(it) }, { lastValue.get()?.let { onNext(it) } onComplete() }) } fun <T> Observable<T>.count(): Observable<Long> = reduce(0L) { total, _ -> total + 1L } fun <T> Sequence<T>.toObservable(): Observable<T> = observable { forEach { onNext(it) } onComplete() emptyDisposable() } @Throws(InterruptedException::class) fun <T> Observable<T>.toSequence(timeout: Long): Sequence<T> = object : Sequence<T>, Disposable { private val subscriptions = mutableListOf<Disposable>() override fun dispose() = synchronized(subscriptions) { subscriptions.forEach { it.dispose() } } override fun iterator(): Iterator<T> { val lockObject = Object() val values = mutableListOf<T>() var isFinished = false val subscription = subscribe( { synchronized(lockObject) { values.add(it) lockObject.notify() } }, { synchronized(lockObject) { isFinished = true lockObject.notifyAll() } }, { synchronized(lockObject) { isFinished = true lockObject.notifyAll() } }) synchronized(subscriptions) { subscriptions.add(subscription) } return object : Iterator<T> { override fun hasNext(): Boolean { synchronized(lockObject) { when (timeout) { 0L -> while (isEmpty()) { lockObject.wait(0) } else -> if (isEmpty()) { lockObject.wait(timeout) } } return values.size > 0 } } override fun next(): T { var nextItem: T? synchronized(lockObject) { nextItem = values[0] values.removeAt(0) } return nextItem!! } private fun isEmpty() = values.size == 0 && !isFinished } } } fun <T> Observable<T>.share(): Observable<T> { val refCounter = AtomicInteger(0) val subject = subjectOf<T>() var subscription = emptyDisposable() return observable { val curSubscription = subject.subscribe(this) if (refCounter.incrementAndGet() == 1) { synchronized(subject) { subscription = subscribe(subject) } } disposableOf { curSubscription.dispose() if (refCounter.decrementAndGet() == 0) { synchronized(subject) { try { subscription.dispose() } finally { subscription = emptyDisposable() } } } } } } inline fun <T> Observable<T>.track(crossinline onSubscribe: (Boolean) -> Unit, crossinline onUnsubscribe: (Boolean) -> Unit = {}): Observable<T> = observable { val subscription: Disposable try { onSubscribe(false) subscription = subscribe(this) } finally { onSubscribe(true) } disposableOf { try { onUnsubscribe(false) subscription.dispose() } finally { onUnsubscribe(true) } } } fun <T> Observable<T>.materialize(): Observable<Notification<T>> = observable { subscribe( { onNext(NotificationNext(it)) }, { onNext(NotificationError(it)) onComplete() }, { onNext(NotificationCompleted.completed()) onComplete() }) } fun <T> Observable<Notification<T>>.dematerialize(): Observable<T> = observable { subscribe { when (it) { is NotificationNext<T> -> onNext(it.value) is NotificationError -> onError(it.error) is NotificationCompleted -> onComplete() } } }
apache-2.0
fd07e1862eeea3a5345658a49869afcb
33.494505
212
0.441589
5.548615
false
false
false
false
AndroidX/androidx
camera/integration-tests/diagnosetestapp/src/test/java/androidx/camera/integration/diagnose/DiagnosisTest.kt
3
6435
/* * 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.camera.integration.diagnose import android.content.Context import android.graphics.BitmapFactory import android.graphics.Color import android.os.Build import androidx.camera.testing.fakes.FakeLifecycleOwner import androidx.camera.view.LifecycleCameraController import androidx.test.core.app.ApplicationProvider import java.io.BufferedReader import java.io.File import java.io.InputStreamReader import java.util.zip.ZipFile import kotlinx.coroutines.runBlocking import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import com.google.common.truth.Truth.assertThat import org.robolectric.RobolectricTestRunner import org.robolectric.annotation.Config @RunWith(RobolectricTestRunner::class) @Config(minSdk = Build.VERSION_CODES.M, maxSdk = 32) class DiagnosisTest { private val context = ApplicationProvider.getApplicationContext<Context>() private lateinit var cameraController: LifecycleCameraController private var taskList = mutableListOf<DiagnosisTask>() @Before fun setUp() { cameraController = LifecycleCameraController(context) cameraController.bindToLifecycle(FakeLifecycleOwner()) taskList.add(FakeTextSavingTask()) taskList.add(FakeTextAndImageSavingTask()) } @Test fun diagnoseAndIsAggregated_returnsOneTextFileOneJEPG() { // Act: running aggregated diagnose on taskList val file: File? runBlocking { file = Diagnosis().diagnose(context, taskList, cameraController, true) } // Assert: file exits with correct contents if (file != null) { val zipFile = ZipFile(file) val zipEntries = zipFile.entries().toList() var correctTextFileCount = 0 var correctImageFileCount = 0 // Confirm 2 zip entries assertThat(zipEntries.size).isEqualTo(2) // Checking correct filename and content for each entry zipEntries.forEach { val inputStream = zipFile.getInputStream(it) if (it.name.endsWith(".txt")) { val br = BufferedReader(InputStreamReader(inputStream)) val textRead = readText(br) assertThat(it.name).isEqualTo(AGGREGATED_TEXT_FILENAME) assertThat(textRead).isEqualTo(FAKE_TEXT_SAVING_TASK_STRING + FAKE_TEXT_AND_IMAGE_SAVING_TASK_STRING) correctTextFileCount ++ } else if (it.name.endsWith(".jpeg")) { assertThat(it.name).isEqualTo(FAKE_IMAGE_NAME) val bitmap = BitmapFactory.decodeStream(inputStream) assertBitmapColorAndSize(bitmap, Color.BLUE, 5, 5) correctImageFileCount++ } inputStream.close() } // Check for one text file and one image file assertThat(correctTextFileCount).isEqualTo(1) assertThat(correctImageFileCount).isEqualTo(1) } } @Test fun diagnoseAndIsNotAggregated_returnsTwoTextFileOneJPEG() { // Act: running non-aggregated diagnose on taskList val file: File? runBlocking { file = Diagnosis().diagnose(context, taskList, cameraController, false) } // Assert: file exits with correct contents if (file != null) { val zipFile = ZipFile(file) val zipEntries = zipFile.entries().toList() var correctImageFileCount = 0 var correctTextFileCount = 0 // Confirm there are 3 zip entries assertThat(zipEntries.size).isEqualTo(3) // Checking correct filename and content zipEntries.forEach { val inputStream = zipFile.getInputStream(it) if (it.name.endsWith(".txt")) { val br = BufferedReader(InputStreamReader(inputStream)) val textRead = readText(br) // check it contains 2 correct file name // check which file it is if (it.name.equals(FAKE_TEXT_SAVING_TASK_TXT_NAME)) { assertThat(textRead).isEqualTo(FAKE_TEXT_SAVING_TASK_STRING) correctTextFileCount++ } else if (it.name.equals(FAKE_TEXT_AND_IMAGE_SAVING_TASK_TXT_NAME)) { assertThat(textRead).isEqualTo(FAKE_TEXT_AND_IMAGE_SAVING_TASK_STRING) correctTextFileCount++ } } else if (it.name.endsWith(".jpeg")) { // todo : assert image is correct bitmap assertThat(it.name).isEqualTo(FAKE_IMAGE_NAME) val bitmap = BitmapFactory.decodeStream(inputStream) assertBitmapColorAndSize(bitmap, Color.BLUE, 5, 5) correctImageFileCount++ } inputStream.close() } // Check for 2 text file and 1 image file assertThat(correctTextFileCount).isEqualTo(2) assertThat(correctImageFileCount).isEqualTo(1) } } companion object { // Strings for filenames private const val AGGREGATED_TEXT_FILENAME = "text_report.txt" private const val FAKE_TEXT_SAVING_TASK_TXT_NAME = "FakeTextSavingTask.txt" private const val FAKE_TEXT_AND_IMAGE_SAVING_TASK_TXT_NAME = "FakeTextAndImageSavingTask.txt" private const val FAKE_IMAGE_NAME = "FakeImage.jpeg" // Strings for text appended in each task private const val FAKE_TEXT_SAVING_TASK_STRING = "This is a fake test 1.Line 2." private const val FAKE_TEXT_AND_IMAGE_SAVING_TASK_STRING = "This is fake task 2." } }
apache-2.0
ad3d62c4db7f95d779ac1214779d9f91
39.734177
94
0.635276
4.763138
false
true
false
false
firebase/firebase-android-sdk
buildSrc/src/main/java/com/google/firebase/gradle/plugins/SdkUtil.kt
1
1723
// Copyright 2019 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.firebase.gradle.plugins import com.android.build.gradle.LibraryExtension import java.io.File import java.io.FileInputStream import java.io.IOException import java.util.Properties import org.gradle.api.GradleException import org.gradle.api.Project val Project.sdkDir: File get() { val properties = Properties() val localProperties = rootProject.file("local.properties") if (localProperties.exists()) { try { FileInputStream(localProperties).use { fis -> properties.load(fis) } } catch (ex: IOException) { throw GradleException("Could not load local.properties", ex) } } val sdkDir = properties.getProperty("sdk.dir") if (sdkDir != null) { return file(sdkDir) } val androidHome = System.getenv("ANDROID_HOME") ?: throw GradleException("No sdk.dir or ANDROID_HOME set.") return file(androidHome) } val Project.androidJar: File? get() { val android = project.extensions.findByType(LibraryExtension::class.java) ?: return null return File(sdkDir, String.format("/platforms/%s/android.jar", android.compileSdkVersion)) }
apache-2.0
391ba34d3f7cd11452fda796b75cfda0
34.895833
95
0.721416
4.171913
false
false
false
false
benjamin-bader/thrifty
thrifty-java-codegen/src/main/kotlin/com/microsoft.thrifty.gen/TypeResolver.kt
1
7373
/* * Thrifty * * Copyright (c) Microsoft Corporation * * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the License); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING * WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, * FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT. * * See the Apache Version 2.0 License for specific language governing permissions and limitations under the License. */ package com.microsoft.thrifty.gen import com.microsoft.thrifty.TType import com.microsoft.thrifty.schema.BuiltinType import com.microsoft.thrifty.schema.EnumType import com.microsoft.thrifty.schema.ListType import com.microsoft.thrifty.schema.MapType import com.microsoft.thrifty.schema.NamespaceScope import com.microsoft.thrifty.schema.ServiceType import com.microsoft.thrifty.schema.SetType import com.microsoft.thrifty.schema.StructType import com.microsoft.thrifty.schema.ThriftType import com.microsoft.thrifty.schema.TypedefType import com.microsoft.thrifty.schema.UserType import com.squareup.javapoet.ClassName import com.squareup.javapoet.ParameterizedTypeName import com.squareup.javapoet.TypeName import java.util.ArrayList import java.util.HashMap import java.util.HashSet import java.util.LinkedHashMap /** * Utility for getting JavaPoet [TypeName] and [TType] codes from * [ThriftType] instances. */ internal class TypeResolver { private var listClass = classNameOf<ArrayList<*>>() private var setClass = classNameOf<HashSet<*>>() private var mapClass = classNameOf<HashMap<*, *>>() fun setListClass(listClass: ClassName) { this.listClass = listClass } fun setSetClass(setClass: ClassName) { this.setClass = setClass } fun setMapClass(mapClass: ClassName) { this.mapClass = mapClass } /** * Returns the [TType] constant representing the type-code for the given * [thriftType]. */ fun getTypeCode(thriftType: ThriftType): Byte { return thriftType.trueType.accept(TypeCodeVisitor) } fun getJavaClass(thriftType: ThriftType): TypeName { return thriftType.accept(TypeNameVisitor) } fun listOf(elementType: TypeName): ParameterizedTypeName { return ParameterizedTypeName.get(listClass, elementType) } fun setOf(elementType: TypeName): ParameterizedTypeName { return ParameterizedTypeName.get(setClass, elementType) } fun mapOf(keyType: TypeName, valueType: TypeName): ParameterizedTypeName { return ParameterizedTypeName.get(mapClass, keyType, valueType) } } /** * A Visitor that converts a [ThriftType] into a [TypeName]. */ private object TypeNameVisitor : ThriftType.Visitor<TypeName> { private val nameCache = LinkedHashMap<String, ClassName>() override fun visitVoid(voidType: BuiltinType): TypeName { return TypeNames.VOID } override fun visitBool(boolType: BuiltinType): TypeName { return TypeNames.BOOLEAN } override fun visitByte(byteType: BuiltinType): TypeName { return TypeNames.BYTE } override fun visitI16(i16Type: BuiltinType): TypeName { return TypeNames.SHORT } override fun visitI32(i32Type: BuiltinType): TypeName { return TypeNames.INTEGER } override fun visitI64(i64Type: BuiltinType): TypeName { return TypeNames.LONG } override fun visitDouble(doubleType: BuiltinType): TypeName { return TypeNames.DOUBLE } override fun visitString(stringType: BuiltinType): TypeName { return TypeNames.STRING } override fun visitBinary(binaryType: BuiltinType): TypeName { return TypeNames.BYTE_STRING } override fun visitEnum(enumType: EnumType): TypeName { return visitUserType(enumType) } override fun visitList(listType: ListType): TypeName { val elementType = listType.elementType.trueType val elementTypeName = elementType.accept(this) return ParameterizedTypeName.get(TypeNames.LIST, elementTypeName) } override fun visitSet(setType: SetType): TypeName { val elementType = setType.elementType.trueType val elementTypeName = elementType.accept(this) return ParameterizedTypeName.get(TypeNames.SET, elementTypeName) } override fun visitMap(mapType: MapType): TypeName { val keyType = mapType.keyType.trueType val valueType = mapType.valueType.trueType val keyTypeName = keyType.accept(this) val valueTypeName = valueType.accept(this) return ParameterizedTypeName.get(TypeNames.MAP, keyTypeName, valueTypeName) } override fun visitStruct(structType: StructType): TypeName { return visitUserType(structType) } override fun visitTypedef(typedefType: TypedefType): TypeName { return typedefType.oldType.accept(this) } override fun visitService(serviceType: ServiceType): TypeName { return visitUserType(serviceType) } private fun visitUserType(userType: UserType): TypeName { val packageName = userType.getNamespaceFor(NamespaceScope.JAVA) if (packageName.isNullOrEmpty()) { throw AssertionError("Missing namespace. Did you forget to add 'namespace java'?") } val key = "$packageName##${userType.name}" return nameCache.computeIfAbsent(key) { ClassName.get(packageName, userType.name) } } } /** * A Visitor that converts a [ThriftType] into a [TType] * constant value. */ private object TypeCodeVisitor : ThriftType.Visitor<Byte> { override fun visitBool(boolType: BuiltinType): Byte { return TType.BOOL } override fun visitByte(byteType: BuiltinType): Byte { return TType.BYTE } override fun visitI16(i16Type: BuiltinType): Byte { return TType.I16 } override fun visitI32(i32Type: BuiltinType): Byte { return TType.I32 } override fun visitI64(i64Type: BuiltinType): Byte { return TType.I64 } override fun visitDouble(doubleType: BuiltinType): Byte { return TType.DOUBLE } override fun visitString(stringType: BuiltinType): Byte { return TType.STRING } override fun visitBinary(binaryType: BuiltinType): Byte { return TType.STRING } override fun visitVoid(voidType: BuiltinType): Byte { return TType.VOID } override fun visitEnum(enumType: EnumType): Byte { return TType.I32 } override fun visitList(listType: ListType): Byte { return TType.LIST } override fun visitSet(setType: SetType): Byte { return TType.SET } override fun visitMap(mapType: MapType): Byte { return TType.MAP } override fun visitStruct(structType: StructType): Byte { return TType.STRUCT } override fun visitTypedef(typedefType: TypedefType): Byte { return typedefType.oldType.accept(this) } override fun visitService(serviceType: ServiceType): Byte { throw AssertionError("Services do not have typecodes") } }
apache-2.0
5a0b0fda7ebb0b4816c70e1c1b27ee43
28.610442
116
0.705005
4.515003
false
false
false
false
DanielGrech/anko
dsl/src/org/jetbrains/android/anko/sources/sourceProviders.kt
3
2119
/* * 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.sources import com.github.javaparser.JavaParser import com.github.javaparser.ast.CompilationUnit import org.jetbrains.android.anko.getPackageName import sun.plugin.dom.exception.InvalidStateException import java.io.File public interface SourceProvider { fun parse(fqName: String): CompilationUnit? } public class CachingSourceProvider(private val underlyingProvider: SourceProvider) : SourceProvider { private val cache = hashMapOf<String, CompilationUnit>() override fun parse(fqName: String) = cache.getOrPut(fqName) { underlyingProvider.parse(fqName) } } public class AndroidHomeSourceProvider(version: Int) : SourceProvider { private val baseDir: File init { val androidHome = System.getenv("ANDROID_HOME") ?: throw InvalidStateException("ANDROID_HOME environment variable is not defined") baseDir = File(androidHome, "sources/android-$version") if (!baseDir.exists()) throw InvalidStateException("${baseDir.getAbsolutePath()} does not exist") } override fun parse(fqName: String): CompilationUnit? { val packageName = getPackageName(fqName) val packageDir = File(baseDir, packageName.replace('.', '/')) if (!packageDir.exists()) return null val filename = fqName.substring(packageName.length() + 1).substringBefore('.') + ".java" val file = File(packageDir, filename) if (!file.exists()) return null return JavaParser.parse(file) } }
apache-2.0
1c003769b95541e03e1b90096513e69c
35.551724
105
0.722039
4.518124
false
false
false
false
siosio/intellij-community
plugins/git4idea/src/git4idea/index/ui/SimpleTabTitleUpdater.kt
1
2955
// 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.index.ui import com.intellij.openapi.Disposable import com.intellij.openapi.vcs.VcsBundle import com.intellij.openapi.vcs.changes.ui.ChangesGroupingSupport import com.intellij.openapi.vcs.changes.ui.ChangesTree import com.intellij.openapi.vcs.changes.ui.ChangesViewContentManager import com.intellij.openapi.vcs.changes.ui.CurrentBranchComponent import com.intellij.openapi.vfs.VirtualFile import com.intellij.ui.content.Content import com.intellij.util.ui.update.UiNotifyConnector import com.intellij.vcs.branch.BranchData import com.intellij.vcs.branch.BranchPresentation import com.intellij.vcs.log.runInEdt import git4idea.repo.GitRepository import git4idea.repo.GitRepositoryChangeListener import org.jetbrains.annotations.Nls import org.jetbrains.annotations.NotNull import java.beans.PropertyChangeEvent abstract class SimpleTabTitleUpdater(private val tree: ChangesTree, private val tabName: String) : Disposable { private var branches = emptySet<BranchData>() set(value) { if (field == value) return field = value updatePresentation() } private val groupingListener: (evt: PropertyChangeEvent) -> Unit = { refresh() } init { UiNotifyConnector.doWhenFirstShown(tree, Runnable { refresh() }) tree.addGroupingChangeListener(groupingListener) tree.project.messageBus.connect(this).subscribe(GitRepository.GIT_REPO_CHANGE, GitRepositoryChangeListener { runInEdt(this) { refresh() } }) } abstract fun getRoots(): Collection<VirtualFile> fun refresh() { branches = getBranches() } private fun updatePresentation() { val tab = getTab() ?: return tab.displayName = getDisplayName() tab.description = BranchPresentation.getTooltip(branches) } private fun getDisplayName(): @NotNull @Nls String { val branchesText = BranchPresentation.getText(branches) if (branchesText.isBlank()) return VcsBundle.message("tab.title.commit") return VcsBundle.message("tab.title.commit.to.branch", branchesText) } private fun getBranches(): Set<BranchData> { if (!shouldShowBranches()) { return emptySet() } return getRoots().mapNotNull { CurrentBranchComponent.getCurrentBranch(tree.project, it) }.toSet() } protected open fun shouldShowBranches(): Boolean { val groupingSupport = tree.groupingSupport return !groupingSupport.isAvailable(ChangesGroupingSupport.REPOSITORY_GROUPING) || !groupingSupport[ChangesGroupingSupport.REPOSITORY_GROUPING] } private fun getTab(): Content? { return ChangesViewContentManager.getInstance(tree.project).findContents { it.tabName == tabName }.firstOrNull() } override fun dispose() { tree.removeGroupingChangeListener(groupingListener) branches = emptySet() } }
apache-2.0
e5668e8dad0d815194d60870aa29ff50
36.417722
140
0.754315
4.588509
false
false
false
false
ReplayMod/ReplayMod
src/main/kotlin/com/replaymod/core/gui/common/input/UIExpressionInput.kt
1
1348
package com.replaymod.core.gui.common.input import com.replaymod.core.gui.common.elementa.UITextInput import com.udojava.evalex.Expression import gg.essential.elementa.dsl.constrain import gg.essential.elementa.dsl.pixels import gg.essential.elementa.state.BasicState import gg.essential.elementa.state.State import gg.essential.elementa.state.toConstraint import java.awt.Color import java.math.MathContext class UIExpressionInput : UITextInput() { val value: Double? get() = try { expression.eval()?.toDouble() } catch (e: Expression.ExpressionException) { null } catch (e: ArithmeticException) { null } catch (e: NumberFormatException) { null } val expression: Expression get() = Expression(getText(), MathContext.DECIMAL64) val valid: State<Boolean> = BasicState(false) init { constrain { color = valid.map { if (it) Color.WHITE else Color.RED }.toConstraint() } onUpdate { valid.set(value != null) } } override fun afterInitialization() { // Right-align constrain { x = 2.pixels(alignOpposite = true) } super.afterInitialization() } companion object { val expressionChars = "+-*/%".toSet() } }
gpl-3.0
4e475719747ece0c94efb31db35bdcd2
24.942308
83
0.628338
4.292994
false
false
false
false
K0zka/kerub
src/test/kotlin/com/github/kerubistan/kerub/planner/steps/network/ovs/port/remove/RemoveOvsPortFactoryTest.kt
2
2593
package com.github.kerubistan.kerub.planner.steps.network.ovs.port.remove import com.github.kerubistan.kerub.hostUp import com.github.kerubistan.kerub.model.config.HostConfiguration import com.github.kerubistan.kerub.model.config.OvsDataPort import com.github.kerubistan.kerub.model.config.OvsNetworkConfiguration import com.github.kerubistan.kerub.model.devices.NetworkAdapterType import com.github.kerubistan.kerub.model.devices.NetworkDevice import com.github.kerubistan.kerub.planner.OperationalState import com.github.kerubistan.kerub.planner.steps.AbstractFactoryVerifications import com.github.kerubistan.kerub.testHost import com.github.kerubistan.kerub.testVirtualNetwork import com.github.kerubistan.kerub.testVm import com.github.kerubistan.kerub.vmUp import org.junit.jupiter.api.Test import kotlin.test.assertTrue internal class RemoveOvsPortFactoryTest : AbstractFactoryVerifications(RemoveOvsPortFactory) { @Test fun produce() { assertTrue("port is used by a vm, do not remove") { val vm = testVm.copy( devices = listOf( NetworkDevice(adapterType = NetworkAdapterType.virtio, networkId = testVirtualNetwork.id) ) ) RemoveOvsPortFactory.produce( OperationalState.fromLists( hosts = listOf(testHost), hostDyns = listOf(hostUp(testHost)), vms = listOf(vm), vmDyns = listOf(vmUp(vm, testHost)), hostCfgs = listOf( HostConfiguration( id = testHost.id, networkConfiguration = listOf( OvsNetworkConfiguration( virtualNetworkId = testVirtualNetwork.id, ports = listOf( OvsDataPort(vm.idStr) ) ) ) ) ), virtualNetworks = listOf(testVirtualNetwork) ) ).isEmpty() } assertTrue("Not used virtual network on a host - offer to remove") { RemoveOvsPortFactory.produce( OperationalState.fromLists( hosts = listOf(testHost), hostDyns = listOf(hostUp(testHost)), hostCfgs = listOf( HostConfiguration( id = testHost.id, networkConfiguration = listOf( OvsNetworkConfiguration( virtualNetworkId = testVirtualNetwork.id, ports = listOf( OvsDataPort("test-port") ) ) ) ) ), virtualNetworks = listOf(testVirtualNetwork) ) ) == listOf( RemoveOvsPort( host = testHost, portName = "test-port", virtualNetwork = testVirtualNetwork ) ) } } }
apache-2.0
416a673bfcbe682f0f02d380d90e82bf
31.024691
96
0.665638
4.115873
false
true
false
false
K0zka/kerub
src/main/kotlin/com/github/kerubistan/kerub/planner/steps/storage/fs/convert/inplace/InPlaceConvertImage.kt
2
2573
package com.github.kerubistan.kerub.planner.steps.storage.fs.convert.inplace import com.fasterxml.jackson.annotation.JsonTypeName import com.github.kerubistan.kerub.model.Host import com.github.kerubistan.kerub.model.VirtualStorageDevice import com.github.kerubistan.kerub.model.dynamic.VirtualStorageFsAllocation import com.github.kerubistan.kerub.model.io.VirtualDiskFormat import com.github.kerubistan.kerub.planner.OperationalState import com.github.kerubistan.kerub.planner.reservations.HostStorageReservation import com.github.kerubistan.kerub.planner.reservations.Reservation import com.github.kerubistan.kerub.planner.reservations.UseHostReservation import com.github.kerubistan.kerub.planner.steps.storage.fs.convert.AbstractConvertImage import io.github.kerubistan.kroki.collections.update @JsonTypeName("in-place-convert-image") data class InPlaceConvertImage( override val virtualStorage: VirtualStorageDevice, override val sourceAllocation: VirtualStorageFsAllocation, val host: Host, val targetFormat: VirtualDiskFormat ) : AbstractConvertImage() { init { check(host.id == sourceAllocation.hostId) { "allocation host id (${sourceAllocation.hostId}) does not match the host id (${host.id})" } check(host.capabilities?.index?.storageCapabilitiesById?.keys?.let { sourceAllocation.capabilityId in it } ?: false) { "source allocation refers to capability (${sourceAllocation.capabilityId}) not registered in the host record." + "known capabilities are ${host.capabilities?.index?.storageCapabilitiesById}" } check(sourceAllocation.type != targetFormat) { "It is pointless to have the same format as source and target ($targetFormat)" } } override fun take(state: OperationalState): OperationalState = state.copy( vStorage = state.vStorage.update(virtualStorage.id) { it.copy( dynamic = it.dynamic!!.copy( allocations = it.dynamic.allocations - sourceAllocation + sourceAllocation.copy( type = targetFormat, fileName = "${sourceAllocation.mountPoint}/${virtualStorage.id}.$targetFormat" ) ) ) } ) override fun reservations(): List<Reservation<*>> = listOf( //TODO: the allocation should be reserved exclusively UseHostReservation(host), HostStorageReservation( host = host, storageCapabilityId = sourceAllocation.capabilityId, // this may need some more precision // - consider the overhead of the format // - consider thin allocation if applicable to source / target reservedStorage = virtualStorage.size ) ) }
apache-2.0
bf29f7a29413646c7183e3df97aee0cf
40.516129
115
0.766421
4.32437
false
false
false
false
jwren/intellij-community
platform/lang-impl/src/com/intellij/util/indexing/diagnostic/ProjectIndexingHistoryImpl.kt
1
13199
// 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.openapi.diagnostic.thisLogger import com.intellij.openapi.project.Project import com.intellij.util.indexing.diagnostic.dto.JsonFileProviderIndexStatistics import com.intellij.util.indexing.diagnostic.dto.JsonScanningStatistics import com.intellij.util.indexing.diagnostic.dto.toJsonStatistics import com.intellij.util.indexing.snapshot.SnapshotInputMappingsStatistics import org.jetbrains.annotations.ApiStatus import org.jetbrains.annotations.TestOnly import java.time.Duration import java.time.Instant import java.time.ZoneOffset import java.time.ZonedDateTime import java.util.concurrent.atomic.AtomicLong import kotlin.reflect.KMutableProperty1 @ApiStatus.Internal data class ProjectIndexingHistoryImpl(override val project: Project, override val indexingReason: String?, private val wasFullIndexing: Boolean) : ProjectIndexingHistory { private companion object { val indexingSessionIdSequencer = AtomicLong() val log = thisLogger() } override val indexingSessionId = indexingSessionIdSequencer.getAndIncrement() private val biggestContributorsPerFileTypeLimit = 10 override val times: IndexingTimes by ::timesImpl private val timesImpl = IndexingTimesImpl(indexingReason = indexingReason, wasFullIndexing = wasFullIndexing, updatingStart = ZonedDateTime.now(ZoneOffset.UTC), totalUpdatingTime = System.nanoTime()) override val scanningStatistics = arrayListOf<JsonScanningStatistics>() override val providerStatistics = arrayListOf<JsonFileProviderIndexStatistics>() override val totalStatsPerFileType = hashMapOf<String /* File type name */, StatsPerFileTypeImpl>() override val totalStatsPerIndexer = hashMapOf<String /* Index ID */, StatsPerIndexerImpl>() override var visibleTimeToAllThreadsTimeRatio: Double = 0.0 private val events = mutableListOf<Event>() fun addScanningStatistics(statistics: ScanningStatistics) { scanningStatistics += statistics.toJsonStatistics() } fun addProviderStatistics(statistics: IndexingFileSetStatistics) { // Convert to Json to release memory occupied by statistic values. providerStatistics += statistics.toJsonStatistics(visibleTimeToAllThreadsTimeRatio) for ((fileType, fileTypeStats) in statistics.statsPerFileType) { val totalStats = totalStatsPerFileType.getOrPut(fileType) { StatsPerFileTypeImpl(0, 0, 0, 0, LimitedPriorityQueue(biggestContributorsPerFileTypeLimit, compareBy { it.processingTimeInAllThreads })) } totalStats.totalNumberOfFiles += fileTypeStats.numberOfFiles totalStats.totalBytes += fileTypeStats.totalBytes totalStats.totalProcessingTimeInAllThreads += fileTypeStats.processingTimeInAllThreads totalStats.totalContentLoadingTimeInAllThreads += fileTypeStats.contentLoadingTimeInAllThreads totalStats.biggestFileTypeContributors.addElement( BiggestFileTypeContributorImpl( statistics.fileSetName, fileTypeStats.numberOfFiles, fileTypeStats.totalBytes, fileTypeStats.processingTimeInAllThreads ) ) } for ((indexId, stats) in statistics.statsPerIndexer) { val totalStats = totalStatsPerIndexer.getOrPut(indexId) { StatsPerIndexerImpl( totalNumberOfFiles = 0, totalNumberOfFilesIndexedByExtensions = 0, totalBytes = 0, totalIndexingTimeInAllThreads = 0, snapshotInputMappingStats = SnapshotInputMappingStatsImpl( requests = 0, misses = 0 ) ) } totalStats.totalNumberOfFiles += stats.numberOfFiles totalStats.totalNumberOfFilesIndexedByExtensions += stats.numberOfFilesIndexedByExtensions totalStats.totalBytes += stats.totalBytes totalStats.totalIndexingTimeInAllThreads += stats.indexingTime } } fun addSnapshotInputMappingStatistics(snapshotInputMappingsStatistics: List<SnapshotInputMappingsStatistics>) { for (mappingsStatistic in snapshotInputMappingsStatistics) { val totalStats = totalStatsPerIndexer.getOrPut(mappingsStatistic.indexId.name) { StatsPerIndexerImpl( totalNumberOfFiles = 0, totalNumberOfFilesIndexedByExtensions = 0, totalBytes = 0, totalIndexingTimeInAllThreads = 0, snapshotInputMappingStats = SnapshotInputMappingStatsImpl(requests = 0, misses = 0)) } totalStats.snapshotInputMappingStats.requests += mappingsStatistic.totalRequests totalStats.snapshotInputMappingStats.misses += mappingsStatistic.totalMisses } } private sealed interface Event { val instant: Instant data class StageEvent(val stage: Stage, val started: Boolean, override val instant: Instant = Instant.now()) : Event data class SuspensionEvent(val started: Boolean, override val instant: Instant = Instant.now()) : Event } fun startStage(stage: Stage) { synchronized(events) { events.add(Event.StageEvent(stage, true)) } } fun stopStage(stage: Stage) { synchronized(events) { events.add(Event.StageEvent(stage, false)) } } fun suspendStages() { synchronized(events) { events.add(Event.SuspensionEvent(true)) } } fun stopSuspendingStages() { synchronized(events) { events.add(Event.SuspensionEvent(false)) } } fun indexingFinished() { writeStagesToDurations() } fun setWasInterrupted(interrupted: Boolean) { timesImpl.wasInterrupted = interrupted } fun finishTotalUpdatingTime() { timesImpl.updatingEnd = ZonedDateTime.now(ZoneOffset.UTC) timesImpl.totalUpdatingTime = System.nanoTime() - timesImpl.totalUpdatingTime } fun setScanFilesDuration(duration: Duration) { timesImpl.scanFilesDuration = duration } /** * Some StageEvent may appear between begin and end of suspension, because it actually takes place only on ProgressIndicator's check. * This normalizations moves moment of suspension start from declared to after all other events between it and suspension end: * suspended, event1, ..., eventN, unsuspended -> event1, ..., eventN, suspended, unsuspended * * Suspended and unsuspended events appear only on pairs with none in between. */ private fun getNormalizedEvents(): List<Event> { val normalizedEvents = mutableListOf<Event>() synchronized(events) { var suspensionStartTime: Instant? = null for (event in events) { when (event) { is Event.SuspensionEvent -> { if (event.started) { log.assertTrue(suspensionStartTime == null, "Two suspension starts, no stops. Events $events") suspensionStartTime = event.instant } else { //speculate suspension start as time of last meaningful event, if it ever happened if (suspensionStartTime == null) { suspensionStartTime = normalizedEvents.lastOrNull()?.instant } if (suspensionStartTime != null) { //observation may miss the start of suspension, see IDEA-281514 normalizedEvents.add(Event.SuspensionEvent(true, suspensionStartTime)) normalizedEvents.add(Event.SuspensionEvent(false, event.instant)) } suspensionStartTime = null } } is Event.StageEvent -> { normalizedEvents.add(event) if (suspensionStartTime != null) { //apparently we haven't stopped yet suspensionStartTime = event.instant } } } } } return normalizedEvents } private fun writeStagesToDurations() { val normalizedEvents = getNormalizedEvents() var suspendedDuration = Duration.ZERO val startMap = hashMapOf<Stage, Instant>() val durationMap = hashMapOf<Stage, Duration>() for (stage in Stage.values()) { durationMap[stage] = Duration.ZERO } var suspendStart: Instant? = null for (event in normalizedEvents) { when (event) { is Event.SuspensionEvent -> { if (event.started) { for (entry in startMap) { durationMap[entry.key] = durationMap[entry.key]!!.plus(Duration.between(entry.value, event.instant)) } suspendStart = event.instant } else { if (suspendStart != null) { suspendedDuration = suspendedDuration.plus(Duration.between(suspendStart, event.instant)) suspendStart = null } startMap.replaceAll { _, _ -> event.instant } //happens strictly after suspension start event, startMap shouldn't change } } is Event.StageEvent -> { if (event.started) { val oldStart = startMap.put(event.stage, event.instant) log.assertTrue(oldStart == null, "${event.stage} is already started. Events $normalizedEvents") } else { val start = startMap.remove(event.stage) log.assertTrue(start != null, "${event.stage} is not started, tries to stop. Events $normalizedEvents") durationMap[event.stage] = durationMap[event.stage]!!.plus(Duration.between(start, event.instant)) } } } for (stage in Stage.values()) { stage.getProperty().set(timesImpl, durationMap[stage]!!) } timesImpl.suspendedDuration = suspendedDuration } } /** Just a stage, don't have to cover whole indexing period, may intersect **/ enum class Stage { CreatingIterators { override fun getProperty(): KMutableProperty1<IndexingTimesImpl, Duration> = IndexingTimesImpl::creatingIteratorsDuration }, Scanning { override fun getProperty() = IndexingTimesImpl::scanFilesDuration }, Indexing { override fun getProperty() = IndexingTimesImpl::indexingDuration }, PushProperties { override fun getProperty() = IndexingTimesImpl::pushPropertiesDuration }; abstract fun getProperty(): KMutableProperty1<IndexingTimesImpl, Duration> } @TestOnly fun startStage(stage: Stage, instant: Instant) { synchronized(events) { events.add(Event.StageEvent(stage, true, instant)) } } @TestOnly fun stopStage(stage: Stage, instant: Instant) { synchronized(events) { events.add(Event.StageEvent(stage, false, instant)) } } @TestOnly fun suspendStages(instant: Instant) { synchronized(events) { events.add(Event.SuspensionEvent(true, instant)) } } @TestOnly fun stopSuspendingStages(instant: Instant) { synchronized(events) { events.add(Event.SuspensionEvent(false, instant)) } } data class StatsPerFileTypeImpl( override var totalNumberOfFiles: Int, override var totalBytes: BytesNumber, override var totalProcessingTimeInAllThreads: TimeNano, override var totalContentLoadingTimeInAllThreads: TimeNano, val biggestFileTypeContributors: LimitedPriorityQueue<BiggestFileTypeContributorImpl> ): StatsPerFileType { override val biggestFileTypeContributorList: List<BiggestFileTypeContributor> get() = biggestFileTypeContributors.biggestElements } data class BiggestFileTypeContributorImpl( override val providerName: String, override val numberOfFiles: Int, override val totalBytes: BytesNumber, override val processingTimeInAllThreads: TimeNano ): BiggestFileTypeContributor data class StatsPerIndexerImpl( override var totalNumberOfFiles: Int, override var totalNumberOfFilesIndexedByExtensions: Int, override var totalBytes: BytesNumber, override var totalIndexingTimeInAllThreads: TimeNano, override var snapshotInputMappingStats: SnapshotInputMappingStatsImpl ): StatsPerIndexer data class IndexingTimesImpl( override val indexingReason: String?, override val wasFullIndexing: Boolean, override val updatingStart: ZonedDateTime, override var totalUpdatingTime: TimeNano, override var updatingEnd: ZonedDateTime = updatingStart, override var indexingDuration: Duration = Duration.ZERO, override var contentLoadingVisibleDuration: Duration = Duration.ZERO, override var pushPropertiesDuration: Duration = Duration.ZERO, override var indexExtensionsDuration: Duration = Duration.ZERO, override var creatingIteratorsDuration: Duration = Duration.ZERO, override var scanFilesDuration: Duration = Duration.ZERO, override var suspendedDuration: Duration = Duration.ZERO, override var appliedAllValuesSeparately: Boolean = true, override var separateValueApplicationVisibleTime: TimeNano = 0, override var wasInterrupted: Boolean = false ): IndexingTimes data class SnapshotInputMappingStatsImpl(override var requests: Long, override var misses: Long): SnapshotInputMappingStats { override val hits: Long get() = requests - misses } }
apache-2.0
3c537bc89b29deb1caf7f6ad6ba64781
37.150289
135
0.707629
5.005309
false
false
false
false
jwren/intellij-community
platform/platform-impl/src/com/intellij/openapi/wm/impl/headertoolbar/TitleActionToolbar.kt
3
2775
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.openapi.wm.impl.headertoolbar import com.intellij.icons.AllIcons import com.intellij.openapi.actionSystem.ActionGroup import com.intellij.openapi.actionSystem.ActionPlaces import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.Presentation import com.intellij.openapi.actionSystem.ex.ActionButtonLook import com.intellij.openapi.actionSystem.impl.ActionButton import com.intellij.openapi.actionSystem.impl.ActionToolbarImpl import com.intellij.openapi.util.IconLoader import com.intellij.openapi.util.ScalableIcon import com.intellij.openapi.wm.impl.customFrameDecorations.header.toolbar.HeaderToolbarButtonLook import com.intellij.util.ui.JBUI import java.awt.Dimension import javax.swing.Icon import javax.swing.UIManager private const val iconSize = 20 internal class TitleActionToolbar(place: String, actionGroup: ActionGroup, horizontal: Boolean) : ActionToolbarImpl(place, actionGroup, horizontal) { override fun createToolbarButton(action: AnAction, look: ActionButtonLook?, place: String, presentation: Presentation, minimumSize: Dimension): ActionButton { scalePresentationIcons(presentation) if (presentation.icon == null) presentation.icon = AllIcons.Toolbar.Unknown val insets = UIManager.getInsets("MainToolbar.Icon.borderInsets") ?: JBUI.insets(10) val size = Dimension(iconSize + insets.left + insets.right, iconSize + insets.top + insets.bottom) val button = ActionButton(action, presentation, ActionPlaces.MAIN_TOOLBAR, size) button.setLook(HeaderToolbarButtonLook()) return button } override fun isAlignmentEnabled(): Boolean = false } fun scalePresentationIcons(presentation: Presentation) { presentation.scaleIcon({ icon }, { icon = it }, iconSize) presentation.scaleIcon({ hoveredIcon }, { hoveredIcon = it }, iconSize) presentation.addPropertyChangeListener { evt -> if (evt.propertyName == Presentation.PROP_ICON) presentation.scaleIcon({ icon }, { icon = it }, iconSize) if (evt.propertyName == Presentation.PROP_HOVERED_ICON) presentation.scaleIcon({ hoveredIcon }, { hoveredIcon = it }, iconSize) } } private fun Presentation.scaleIcon(getter: Presentation.() -> Icon?, setter: Presentation.(Icon) -> Unit, size: Int) { val currentIcon = this.getter() if (currentIcon == null) return if (currentIcon is ScalableIcon && currentIcon.iconWidth != size) { this.setter(IconLoader.loadCustomVersionOrScale(currentIcon, size.toFloat())) } }
apache-2.0
bed37346e8d0fa2bc7066ea7ab35d2cd
45.266667
131
0.738739
4.735495
false
false
false
false
GunoH/intellij-community
python/src/com/jetbrains/python/sdk/AddInterpreterActions.kt
1
5176
// 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. @file:JvmName("AddInterpreterActions") package com.jetbrains.python.sdk import com.intellij.execution.target.TargetCustomToolWizardStep import com.intellij.execution.target.TargetEnvironmentType import com.intellij.execution.target.TargetEnvironmentWizard import com.intellij.execution.target.getTargetType import com.intellij.icons.AllIcons import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.module.Module import com.intellij.openapi.project.DumbAware import com.intellij.openapi.project.DumbAwareAction import com.intellij.openapi.project.Project import com.intellij.openapi.projectRoots.Sdk import com.jetbrains.python.PyBundle import com.jetbrains.python.configuration.PyConfigurableInterpreterList import com.jetbrains.python.run.PythonInterpreterTargetEnvironmentFactory import com.jetbrains.python.sdk.add.PyAddSdkDialog import com.jetbrains.python.sdk.add.target.PyAddTargetBasedSdkDialog import com.jetbrains.python.target.PythonLanguageRuntimeType import java.util.function.Consumer fun collectAddInterpreterActions(project: Project, module: Module?, onSdkCreated: Consumer<Sdk>): List<AnAction> { // If module resides on this target, we can't use any target // example: on ``\\wsl$`` you can only use wsl target val targetTypeModuleSitsOn = module?.let { PythonInterpreterTargetEnvironmentFactory.getTargetModuleResidesOn(it)?.asTargetConfig?.getTargetType() } return mutableListOf<AnAction>().apply { if (targetTypeModuleSitsOn == null) { add(AddLocalInterpreterAction(project, module, onSdkCreated::accept)) } addAll(collectNewInterpreterOnTargetActions(project, targetTypeModuleSitsOn, onSdkCreated::accept)) } } private fun collectNewInterpreterOnTargetActions(project: Project, targetTypeModuleSitsOn: TargetEnvironmentType<*>?, onSdkCreated: Consumer<Sdk>): List<AnAction> = PythonInterpreterTargetEnvironmentFactory.EP_NAME.extensionList .filter { it.getTargetType().isSystemCompatible() } .filter { targetTypeModuleSitsOn == null || it.getTargetType() == targetTypeModuleSitsOn } .map { AddInterpreterOnTargetAction(project, it.getTargetType(), onSdkCreated) } private class AddLocalInterpreterAction(private val project: Project, private val module: Module?, private val onSdkCreated: Consumer<Sdk>) : AnAction(PyBundle.messagePointer("python.sdk.action.add.local.interpreter.text"), AllIcons.Nodes.HomeFolder), DumbAware { override fun actionPerformed(e: AnActionEvent) { val model = PyConfigurableInterpreterList.getInstance(project).model PyAddTargetBasedSdkDialog.show( project, module, model.sdks.asList(), Consumer { if (it != null && model.findSdk(it.name) == null) { model.addSdk(it) model.apply() onSdkCreated.accept(it) } } ) } } private class AddInterpreterOnTargetAction(private val project: Project, private val targetType: TargetEnvironmentType<*>, private val onSdkCreated: Consumer<Sdk>) : AnAction(PyBundle.messagePointer("python.sdk.action.add.interpreter.based.on.target.text", targetType.displayName), targetType.icon), DumbAware { override fun actionPerformed(e: AnActionEvent) { val wizard = TargetEnvironmentWizard.createWizard(project, targetType, PythonLanguageRuntimeType.getInstance()) if (wizard != null && wizard.showAndGet()) { val model = PyConfigurableInterpreterList.getInstance(project).model val sdk = (wizard.currentStepObject as? TargetCustomToolWizardStep)?.customTool as? Sdk if (sdk != null && model.findSdk(sdk.name) == null) { model.addSdk(sdk) model.apply() onSdkCreated.accept(sdk) } } } } class AddInterpreterAction(val project: Project, val module: Module, private val currentSdk: Sdk?) : DumbAwareAction(PyBundle.messagePointer("python.sdk.popup.add.interpreter")) { override fun actionPerformed(e: AnActionEvent) { val model = PyConfigurableInterpreterList.getInstance(project).model PyAddSdkDialog.show( project, module, model.sdks.asList(), Consumer { if (it != null && model.findSdk(it.name) == null) { model.addSdk(it) model.apply() switchToSdk(module, it, currentSdk) } } ) } } fun switchToSdk(module: Module, sdk: Sdk, currentSdk: Sdk?) { val project = module.project (sdk.sdkType as PythonSdkType).setupSdkPaths(sdk) removeTransferredRootsFromModulesWithInheritedSdk(project, currentSdk) project.pythonSdk = sdk transferRootsToModulesWithInheritedSdk(project, sdk) removeTransferredRoots(module, currentSdk) module.pythonSdk = sdk transferRoots(module, sdk) }
apache-2.0
46a21536e3a6b87a97056e2355ba316a
41.089431
158
0.721986
4.629696
false
false
false
false
junerver/CloudNote
app/src/main/java/com/junerver/cloudnote/ui/activity/NoteDetailActivity.kt
1
5443
package com.junerver.cloudnote.ui.activity import android.app.Activity import android.content.Intent import android.graphics.Bitmap import android.graphics.BitmapFactory import android.media.ThumbnailUtils import android.provider.MediaStore import android.view.View import androidx.appcompat.app.AlertDialog import androidx.lifecycle.lifecycleScope import com.junerver.cloudnote.net.BmobMethods import com.edusoa.ideallecturer.fetchNetwork import com.edusoa.ideallecturer.toBean import com.elvishew.xlog.XLog import com.junerver.cloudnote.R import com.junerver.cloudnote.bean.DelResp import com.junerver.cloudnote.bean.ErrorResp import com.junerver.cloudnote.databinding.ActivityNoteDetailBinding import com.junerver.cloudnote.databinding.BackBarBinding import com.junerver.cloudnote.db.NoteUtils import com.junerver.cloudnote.db.entity.NoteEntity import com.junerver.cloudnote.utils.NetUtils import kotlinx.coroutines.launch /** * 用于查看笔记的页面 */ class NoteDetailActivity : BaseActivity<ActivityNoteDetailBinding>() { //看起来是个entity,其实不是 private lateinit var mNote: NoteEntity private lateinit var backBarBinding: BackBarBinding override fun initData() { mNote = intent.getSerializableExtra("Note")!! as NoteEntity XLog.d(mNote) } override fun initView() { backBarBinding = BackBarBinding.bind(viewBinding.llRoot) backBarBinding.ivDone.visibility = View.GONE backBarBinding.tvBarTitle.text = "笔记详情" inflateView(mNote) } private fun inflateView(noteEntity: NoteEntity) { val title: String = noteEntity.title val content: String = noteEntity.content val image: String = noteEntity.image val video: String = noteEntity.video if (title.isNotEmpty()) { viewBinding.tvNoteTitle.text = title } if (content.isNotEmpty()) { viewBinding.tvNoteContent.text = content } if (image.isNullOrEmpty()) { var bitmap: Bitmap = BitmapFactory.decodeFile(image) bitmap = ThumbnailUtils.extractThumbnail( bitmap, Math.max(500, viewBinding.ivImage.width), Math.max(500, viewBinding.ivImage.height), ThumbnailUtils.OPTIONS_RECYCLE_INPUT ) viewBinding.ivImage.setImageBitmap(bitmap) } if (video.isNotEmpty()) { var bitmap: Bitmap = ThumbnailUtils.createVideoThumbnail( video, MediaStore.Images.Thumbnails.MICRO_KIND )!! bitmap = ThumbnailUtils.extractThumbnail( bitmap, Math.max(500, viewBinding.ibVideo.width), Math.max(500, viewBinding.ibVideo.height), ThumbnailUtils.OPTIONS_RECYCLE_INPUT ) viewBinding.ibVideo.setImageBitmap(bitmap) } } override fun setListeners() { viewBinding.btnEdit.setOnClickListener { val editIntent = Intent(mContext, EditNoteActivity::class.java) editIntent.putExtra("Note", mNote) startActivityForResult(editIntent, EDIT_NOTE) } viewBinding.btnDelete.setOnClickListener { val builder: AlertDialog.Builder = AlertDialog.Builder(mContext) builder.setTitle("确认要删除这个笔记么?") builder.setPositiveButton( "确认" ) { _, _ -> if (NetUtils.isConnected(mContext)) { lifecycleScope.launch { //云端删除 fetchNetwork { doNetwork { BmobMethods.INSTANCE.delNoteById(mNote.objId) } onSuccess { val delResp = it.toBean<DelResp>() //本地删除 NoteUtils.delNoteById(mNote.objId) showShortToast(getString(R.string.del_success)) finish() } onHttpError { errorBody, errorMsg, code -> errorBody?.let { val bean = it.toBean<ErrorResp>() delInLocalWithoutNetWork() } } } } } else { delInLocalWithoutNetWork() } } builder.setNegativeButton("取消", null) builder.show() } backBarBinding.ivBack.setOnClickListener { finish() } } private fun delInLocalWithoutNetWork() { mNote.isLocalDel = true mNote.saveOrUpdate("objId = ?", mNote.objId) showShortToast(getString(R.string.del_success)) finish() } //编辑后返回变更 override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) if (resultCode == Activity.RESULT_OK) { mNote = data?.getSerializableExtra("Note")!! as NoteEntity inflateView(mNote) } } companion object { private const val EDIT_NOTE = 3 } }
apache-2.0
c96ab345e93a42c85380e77eaf954eff
35.561644
85
0.585535
5.073194
false
false
false
false
smmribeiro/intellij-community
plugins/github/src/org/jetbrains/plugins/github/util/CachingGHUserAvatarLoader.kt
3
2781
// 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.github.util import com.github.benmanes.caffeine.cache.Caffeine import com.intellij.collaboration.async.CompletableFutureUtil.submitIOTask import com.intellij.collaboration.util.ProgressIndicatorsProvider import com.intellij.openapi.Disposable import com.intellij.openapi.components.service import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.progress.ProcessCanceledException import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.LowMemoryWatcher import com.intellij.util.ImageLoader import org.jetbrains.plugins.github.api.GithubApiRequestExecutor import org.jetbrains.plugins.github.api.GithubApiRequests import java.awt.Image import java.time.Duration import java.time.temporal.ChronoUnit import java.util.concurrent.CompletableFuture class CachingGHUserAvatarLoader : Disposable { private val indicatorProvider = ProgressIndicatorsProvider().also { Disposer.register(this, it) } private val avatarCache = Caffeine.newBuilder() .expireAfterAccess(Duration.of(5, ChronoUnit.MINUTES)) .build<String, CompletableFuture<Image?>>() init { LowMemoryWatcher.register(Runnable { avatarCache.invalidateAll() }, this) } fun requestAvatar(requestExecutor: GithubApiRequestExecutor, url: String): CompletableFuture<Image?> = avatarCache.get(url) { ProgressManager.getInstance().submitIOTask(indicatorProvider) { loadAndDownscale(requestExecutor, it, url, STORED_IMAGE_SIZE) } } private fun loadAndDownscale(requestExecutor: GithubApiRequestExecutor, indicator: ProgressIndicator, url: String, maximumSize: Int): Image? { try { val image = requestExecutor.execute(indicator, GithubApiRequests.CurrentUser.getAvatar(url)) return if (image.getWidth(null) <= maximumSize && image.getHeight(null) <= maximumSize) image else ImageLoader.scaleImage(image, maximumSize) } catch (e: ProcessCanceledException) { return null } catch (e: Exception) { LOG.debug("Error loading image from $url", e) return null } } override fun dispose() {} companion object { private val LOG = logger<CachingGHUserAvatarLoader>() @JvmStatic fun getInstance(): CachingGHUserAvatarLoader = service() private const val MAXIMUM_ICON_SIZE = 40 // store images at maximum used size with maximum reasonable scale to avoid upscaling (3 for system scale, 2 for user scale) private const val STORED_IMAGE_SIZE = MAXIMUM_ICON_SIZE * 6 } }
apache-2.0
274e5f0cf8009b8fbd5dd9bbba875a35
38.742857
140
0.770946
4.627288
false
false
false
false
smmribeiro/intellij-community
platform/lang-impl/src/com/intellij/model/search/impl/textSearch.kt
10
3798
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.model.search.impl import com.intellij.find.usages.api.PsiUsage import com.intellij.model.psi.impl.hasDeclarationsInElement import com.intellij.model.psi.impl.hasReferencesInElement import com.intellij.model.search.SearchContext import com.intellij.model.search.SearchRequest import com.intellij.model.search.SearchService import com.intellij.model.search.TextOccurrence import com.intellij.openapi.project.Project import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiElement import com.intellij.psi.search.SearchScope import com.intellij.psi.util.walkUp import com.intellij.refactoring.util.TextOccurrencesUtilBase import com.intellij.util.EmptyQuery import com.intellij.util.Query import com.intellij.util.codeInsight.CommentUtilCore internal fun buildTextUsageQuery( project: Project, searchRequest: SearchRequest, searchScope: SearchScope, searchContexts: Set<SearchContext> ): Query<out PsiUsage> { require(SearchContext.IN_CODE !in searchContexts) require(SearchContext.IN_CODE_HOSTS !in searchContexts) if (searchContexts.isEmpty()) { return EmptyQuery.getEmptyQuery() } val searchString = searchRequest.searchString val searchStringLength = searchString.length val effectiveSearchScope = searchRequest.searchScope?.let(searchScope::intersectWith) ?: searchScope val comments = SearchContext.IN_COMMENTS in searchContexts val strings = SearchContext.IN_STRINGS in searchContexts val plainText = SearchContext.IN_PLAIN_TEXT in searchContexts val occurrenceQuery = SearchService.getInstance() .searchWord(project, searchString) .inContexts(searchContexts) .inScope(effectiveSearchScope) .buildLeafOccurrenceQuery() val filteredOccurrenceQuery = if (comments && strings && plainText) { occurrenceQuery.filtering { isApplicableOccurrence(it, searchStringLength) } } else { occurrenceQuery.filtering { isApplicableOccurrence(it, searchStringLength, comments, strings, plainText) } } return filteredOccurrenceQuery.mapping { occurrence: TextOccurrence -> PsiUsage.textUsage(occurrence.element, TextRange.from(occurrence.offsetInElement, searchStringLength)) } } private fun isApplicableOccurrence(occurrence: TextOccurrence, searchStringLength: Int): Boolean { for ((element, offsetInElement) in occurrence.walkUp()) { if (hasDeclarationsOrReferences(element, offsetInElement, searchStringLength)) { return false } } return true } private fun isApplicableOccurrence( occurrence: TextOccurrence, searchStringLength: Int, comments: Boolean, strings: Boolean, plainText: Boolean ): Boolean { var isComment = false var isString = false for ((element, offsetInElement) in occurrence.walkUp()) { if (hasDeclarationsOrReferences(element, offsetInElement, searchStringLength)) { return false } isComment = isComment || CommentUtilCore.isCommentTextElement(element) isString = isString || TextOccurrencesUtilBase.isStringLiteralElement(element) } return comments && isComment || strings && isString || plainText && !isComment && !isString } private fun TextOccurrence.walkUp(): Iterator<Pair<PsiElement, Int>> = walkUp(element, offsetInElement) private fun hasDeclarationsOrReferences( element: PsiElement, startOffsetInElement: Int, searchStringLength: Int ): Boolean { val endOffsetInElement = startOffsetInElement + searchStringLength return hasDeclarationsInElement(element, startOffsetInElement, endOffsetInElement) || hasReferencesInElement(element, startOffsetInElement, endOffsetInElement) }
apache-2.0
3b294d5013580c23876b079844eca6d0
37.363636
140
0.780147
4.631707
false
false
false
false
mackristof/FollowMe
wear/src/main/java/org/mackristof/followme/fragment/StartFragment.kt
1
2162
package org.mackristof.followme.fragment import android.app.Fragment import android.content.Intent import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Button import org.mackristof.followme.Constants import org.mackristof.followme.GpsService import org.mackristof.followme.R import org.mackristof.followme.Utils import org.mackristof.followme.service.LocationPublisherService /** * Created by christophem on 29/07/2016. */ class StartFragment : Fragment() { // private var mClockView: TextView? = null private var mButtonStart: Button? = null private var mButtonStop: Button? = null override fun onCreateView( inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? { val view = inflater?.inflate(R.layout.start_stop_fragment, container, false)!! mButtonStart = view.findViewById(R.id.startButton) as Button mButtonStop = view.findViewById(R.id.stopButton) as Button mButtonStart?.setOnClickListener(View.OnClickListener { // start service Location val intentLoc = Intent(this.context, GpsService::class.java) intentLoc.putExtra(Constants.INTENT_LOCATION_EXTRA_PUBLISH,true) if (!Utils.isServiceRunning(context,GpsService::class.java.name)) { activity.startService(intentLoc) if (!Utils.isServiceRunning(context, LocationPublisherService::class.java.name)) { val intentMsg = Intent(context, LocationPublisherService::class.java) activity.startService(intentMsg) } } }) mButtonStop?.setOnClickListener(View.OnClickListener { val intent = Intent(this.context, GpsService::class.java) activity.stopService(intent) if (Utils.isServiceRunning(context, LocationPublisherService::class.java.name)) { val intentMsg = Intent(context, LocationPublisherService::class.java) activity.stopService(intentMsg) } }) return view } }
apache-2.0
5f363c026f3110325c2bbc3c2fa5998f
35.033333
120
0.689639
4.376518
false
false
false
false
EMResearch/EvoMaster
e2e-tests/spring-rest-openapi-v3/src/main/kotlin/com/foo/rest/examples/spring/openapi/v3/wiremock/harvestresponse/MetaDataDto.kt
1
259
package com.foo.rest.examples.spring.openapi.v3.wiremock.harvestresponse class MetaDataDto { var status : Int? = null var url : String? = null var name : String? = null val description : String? = null val images : List<String> ? = null }
lgpl-3.0
6026937cd49e248706242614a36e7c96
27.888889
72
0.675676
3.597222
false
false
false
false
savoirfairelinux/ring-client-android
ring-android/app/src/main/java/cx/ring/fragments/PluginHandlersListFragment.kt
1
2736
package cx.ring.fragments import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import cx.ring.databinding.FragPluginHandlersListBinding import cx.ring.plugins.PluginUtils import cx.ring.settings.pluginssettings.PluginDetails import cx.ring.settings.pluginssettings.PluginsListAdapter import cx.ring.settings.pluginssettings.PluginsListAdapter.PluginListItemListener import cx.ring.utils.ConversationPath import net.jami.daemon.JamiService class PluginHandlersListFragment : Fragment(), PluginListItemListener { private var binding: FragPluginHandlersListBinding? = null private lateinit var mPath: ConversationPath override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) mPath = ConversationPath.fromBundle(requireArguments())!! } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View { return FragPluginHandlersListBinding.inflate(inflater, container, false).also { b -> b.handlerList.setHasFixedSize(true) b.handlerList.adapter = PluginsListAdapter( PluginUtils.getChatHandlersDetails(b.handlerList.context, mPath.accountId, mPath.conversationId.removePrefix("swarm:")), this) binding = b }.root } override fun onDestroyView() { super.onDestroyView() binding = null } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) binding!!.chatPluginsToolbar.visibility = View.VISIBLE binding!!.chatPluginsToolbar.setOnClickListener { v: View? -> val fragment = parentFragment if (fragment is ConversationFragment) { fragment.hidePluginListHandlers() } } } override fun onPluginItemClicked(pluginDetails: PluginDetails) { JamiService.toggleChatHandler(pluginDetails.handlerId, mPath.accountId, mPath.conversationId.removePrefix("swarm:"), pluginDetails.isEnabled) } override fun onPluginEnabled(pluginDetails: PluginDetails) { JamiService.toggleChatHandler(pluginDetails.handlerId, mPath.accountId, mPath.conversationId.removePrefix("swarm:"), pluginDetails.isEnabled) } companion object { val TAG = PluginHandlersListFragment::class.simpleName!! fun newInstance(accountId: String, peerId: String): PluginHandlersListFragment { val fragment = PluginHandlersListFragment() fragment.arguments = ConversationPath.toBundle(accountId, peerId) return fragment } } }
gpl-3.0
391092d94f36e9d9c34acecd687533e2
40.469697
149
0.734649
4.992701
false
false
false
false
yrsegal/CommandControl
src/main/java/wiresegal/cmdctrl/common/commands/biome/CommandSetBiome.kt
1
4964
package wiresegal.cmdctrl.common.commands.biome import net.minecraft.command.CommandBase import net.minecraft.command.CommandException import net.minecraft.command.ICommandSender import net.minecraft.command.NumberInvalidException import net.minecraft.network.play.server.SPacketChunkData import net.minecraft.server.MinecraftServer import net.minecraft.util.ResourceLocation import net.minecraft.util.math.BlockPos import net.minecraft.world.World import net.minecraft.world.WorldServer import net.minecraft.world.biome.Biome import net.minecraft.world.chunk.Chunk import wiresegal.cmdctrl.common.CommandControl import wiresegal.cmdctrl.common.core.CTRLException import wiresegal.cmdctrl.common.core.CTRLUsageException import wiresegal.cmdctrl.common.core.Slice import wiresegal.cmdctrl.common.core.notifyCTRLListener /** * @author WireSegal * Created at 5:43 PM on 12/3/16. */ object CommandSetBiome : CommandBase() { val biomes by lazy { Biome.REGISTRY.map { Biome.REGISTRY.getNameForObject(it as Biome) } } fun parseBiome(string: String): Biome { var biome: Biome? try { val id = parseInt(string) biome = Biome.getBiome(id) } catch (e: NumberInvalidException) { val rl = ResourceLocation(string) biome = Biome.REGISTRY.getObject(rl) } if (biome == null) throw CTRLException("commandcontrol.setbiome.invalid", string) return biome } @Throws(CommandException::class) override fun execute(server: MinecraftServer, sender: ICommandSender, args: Array<out String>) { if (args.size > 2) { val senderPos = sender.position val x = parseDouble(senderPos.x.toDouble(), args[0], -3000000, 3000000, false).toInt() val z = parseDouble(senderPos.z.toDouble(), args[1], -3000000, 3000000, false).toInt() val pos = BlockPos(x, 0, z) val biomeid = args[2] val biome = parseBiome(biomeid) val world = sender.entityWorld val id = Biome.getIdForBiome(biome).toByte() val name = Biome.REGISTRY.getNameForObject(biome) if (world.isBlockLoaded(pos)) { notifyCTRLListener(sender, this, "commandcontrol.setbiome.success", x, z, id, name) if (setBiome(world.getChunkFromBlockCoords(pos), pos, biome)) updateBiomes(world, x..x, z..z) } else throw CTRLException("commandcontrol.setbiome.range", x, z) } else throw CTRLUsageException(getCommandUsage(sender)) } fun updateBiomes(world: World, slices: List<Slice>) { if (world !is WorldServer) return val validSlices = slices .flatMap { Array(25) { i -> val x = (i % 5) - 2 + it.x val z = (i / 5) - 2 + it.z Slice(x, z) }.toList() } .map { (it.x shr 4) to (it.z shr 4) } .toSet() for ((chunkX, chunkZ) in validSlices) forceChunk(world, chunkX, chunkZ) } fun updateBiomes(world: World, xRange: IntRange, zRange: IntRange) { if (world !is WorldServer) return val x1 = (Math.min(xRange.first, xRange.last) - 2) shr 4 val x2 = (Math.max(xRange.first, xRange.last) + 2) shr 4 val z1 = (Math.min(zRange.first, zRange.last) - 2) shr 4 val z2 = (Math.max(zRange.first, zRange.last) + 2) shr 4 for (chunkX in x1..x2) for (chunkZ in z1..z2) forceChunk(world, chunkX, chunkZ) } fun forceChunk(world: WorldServer, chunkX: Int, chunkZ: Int) { val entry = world.playerChunkMap.getEntry(chunkX, chunkZ) val chunk = entry?.chunk if (chunk != null && entry != null) entry.sendPacket(SPacketChunkData(chunk, 65535)) } fun setBiome(chunk: Chunk, pos: BlockPos, biome: Biome): Boolean { val i = pos.x and 15 val j = pos.z and 15 val id = Biome.REGISTRY.getIDForObject(biome) val prev = chunk.biomeArray[j shl 4 or i] if (prev.toInt() == id) return false chunk.biomeArray[j shl 4 or i] = (id and 255).toByte() return true } override fun getTabCompletionOptions(server: MinecraftServer, sender: ICommandSender, args: Array<out String>, pos: BlockPos?): List<String> { return when (args.size) { 1 -> getTabCompletionCoordinate(args, 0, pos) 2 -> getTabCompletionCoordinate(args, -1, pos) 3 -> getListOfStringsMatchingLastWord(args, biomes) else -> emptyList() } } override fun getRequiredPermissionLevel() = 2 override fun getCommandName() = "setbiome" override fun getCommandAliases() = mutableListOf("biomeset") override fun getCommandUsage(sender: ICommandSender?) = CommandControl.translate("commandcontrol.setbiome.usage") }
mit
6ecbed8dc432996d64016ee692c22c7c
37.184615
146
0.632554
3.902516
false
false
false
false
tommyettinger/SquidSetup
src/main/kotlin/com/github/czyzby/setup/data/templates/official/squidLibBasic.kt
1
58328
package com.github.czyzby.setup.data.templates.official import com.github.czyzby.setup.data.libs.unofficial.SquidLib import com.github.czyzby.setup.data.project.Project import com.github.czyzby.setup.data.templates.Template import com.github.czyzby.setup.views.ProjectTemplate /** * A (somewhat) simple project using SquidLib extension. * @author Tommy Ettinger */ @ProjectTemplate(official = true) class SquidLibBasicTemplate : Template { override val id = "squidLibBasicTemplate" override val width = "90 * 10" override val height = "(25 + 7) * 20" override val description: String get() = "Project template included simple launchers and an `ApplicationAdapter` extension showing usage of [SquidLib](https://github.com/SquidPony/SquidLib) for display and some logic." override fun apply(project: Project) { super.apply(project) // Including SquidLib dependency: SquidLib().initiate(project) } override fun getApplicationListenerContent(project: Project): String = """package ${project.basic.rootPackage}; import com.badlogic.gdx.ApplicationAdapter; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.InputAdapter; import com.badlogic.gdx.InputMultiplexer; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.scenes.scene2d.Stage; import com.badlogic.gdx.utils.viewport.StretchViewport; import squidpony.ArrayTools; import squidpony.FakeLanguageGen; import squidpony.NaturalLanguageCipher; import squidpony.panel.IColoredString; import squidpony.squidai.DijkstraMap; import squidpony.squidgrid.Direction; import squidpony.squidgrid.FOV; import squidpony.squidgrid.Measurement; import squidpony.squidgrid.Radius; import squidpony.squidgrid.gui.gdx.DefaultResources; import squidpony.squidgrid.gui.gdx.FilterBatch; import squidpony.squidgrid.gui.gdx.FloatFilters; import squidpony.squidgrid.gui.gdx.GDXMarkup; import squidpony.squidgrid.gui.gdx.MapUtility; import squidpony.squidgrid.gui.gdx.PanelEffect; import squidpony.squidgrid.gui.gdx.SColor; import squidpony.squidgrid.gui.gdx.SparseLayers; import squidpony.squidgrid.gui.gdx.SquidInput; import squidpony.squidgrid.gui.gdx.SquidMouse; import squidpony.squidgrid.gui.gdx.TextCellFactory; import squidpony.squidgrid.mapping.DungeonGenerator; import squidpony.squidgrid.mapping.DungeonUtility; import squidpony.squidgrid.mapping.LineKit; import squidpony.squidmath.Coord; import squidpony.squidmath.GWTRNG; import squidpony.squidmath.GreasedRegion; import squidpony.squidmath.NumberTools; import java.util.ArrayList; /** * This is a small, not-overly-simple demo that presents some important features of SquidLib and shows a faster, * cleaner, and more recently-introduced way of displaying the map and other text. Features include dungeon map * generation, field of view, pathfinding (to the mouse position), continuous noise (used for a wavering torch effect), * language generation/ciphering, a colorful glow effect, and ever-present random number generation (with a seed). * You can increase the size of the map on most target platforms (but GWT struggles with large... anything) by * changing gridHeight and gridWidth to affect the visible area or bigWidth and bigHeight to adjust the size of the * dungeon you can move through, with the camera following your '@' symbol. * <br> * The assets folder of this project, if it was created with SquidSetup, will contain the necessary font files (just one * .fnt file and one .png are needed, but many more are included by default). You should move any font files you don't * use out of the assets directory when you produce a release JAR, APK, or GWT build. */ public class ${project.basic.mainClass} extends ApplicationAdapter { // FilterBatch is almost the same as SpriteBatch, but is a bit faster with SquidLib and allows color filtering private FilterBatch batch; // a type of random number generator, see below private GWTRNG rng; // rendering classes that show only the chars and backgrounds that they've been told to render, unlike some earlier // classes in SquidLib. private SparseLayers display, languageDisplay; // generates a dungeon as a 2D char array; can also fill some simple features into the dungeon. private DungeonGenerator dungeonGen; // decoDungeon stores the dungeon map with features like grass and water, if present, as chars like '"' and '~'. // bareDungeon stores the dungeon map with just walls as '#' and anything not a wall as '.'. // Both of the above maps use '#' for walls, and the next two use box-drawing characters instead. // lineDungeon stores the whole map the same as decoDungeon except for walls, which are box-drawing characters here. // prunedDungeon takes lineDungeon and adjusts it so unseen segments of wall (represented by box-drawing characters) // are removed from rendering; unlike the others, it is frequently changed. private char[][] decoDungeon, bareDungeon, lineDungeon, prunedDungeon; private float[][] colors, bgColors; //Here, gridHeight refers to the total number of rows to be displayed on the screen. //We're displaying 25 rows of dungeon, then 7 more rows of text generation to show some tricks with language. //gridHeight is 25 because that variable will be used for generating the dungeon (the actual size of the dungeon //will be triple gridWidth and triple gridHeight), and determines how much off the dungeon is visible at any time. //The bonusHeight is the number of additional rows that aren't handled like the dungeon rows and are shown in a //separate area; here we use them for translations. The gridWidth is 90, which means we show 90 grid spaces //across the whole screen, but the actual dungeon is larger. The cellWidth and cellHeight are 10 and 20, which will //match the starting dimensions of a cell in pixels, but won't be stuck at that value because we use a "Stretchable" //font, and so the cells can change size (they don't need to be scaled by equal amounts, either). While gridWidth //and gridHeight are measured in spaces on the grid, cellWidth and cellHeight are the initial pixel dimensions of //one cell; resizing the window can make the units cellWidth and cellHeight use smaller or larger than a pixel. /** In number of cells */ private static final int gridWidth = 90; /** In number of cells */ private static final int gridHeight = 25; /** In number of cells */ private static final int bigWidth = gridWidth * 2; /** In number of cells */ private static final int bigHeight = gridHeight * 2; /** In number of cells */ private static final int bonusHeight = 7; /** The pixel width of a cell */ private static final int cellWidth = 10; /** The pixel height of a cell */ private static final int cellHeight = 20; private SquidInput input; private Color bgColor; private Stage stage, languageStage; private DijkstraMap playerToCursor; private Coord cursor, player; private ArrayList<Coord> toCursor; private ArrayList<Coord> awaitedMoves; private Vector2 screenPosition; // a passage from the ancient text The Art of War, which remains relevant in any era but is mostly used as a basis // for translation to imaginary languages using the NaturalLanguageCipher and FakeLanguageGen classes. // markup has been added to color some words differently and italicize/bold/upper-case/lower-case others. // see GDXMarkup's docs for more info. private final String artOfWar = "[@ 0.8 0.06329113 0.30980393][/]Sun Tzu[/] said: In the [!]practical[!] art of war, the best thing of all is " + "to take the enemy's country whole and intact; to shatter and destroy it is not so good. So, " + "too, it is better to recapture an army entire than to destroy it, to capture " + "a regiment, a detachment or a company entire than to destroy them. Hence to fight " + "and conquer in all your battles is not [!]supreme[,] excellence; [!]supreme[=] EXCELLENCE[,] " + "consists in breaking the enemy's resistance without fighting.[]"; // A translation dictionary for going back and forth between English and an imaginary language that this generates // words for, using some of the rules that the English language tends to follow to determine if two words should // share a common base word (such as "read" and "reader" needing similar translations). This is given randomly // selected languages from the FakeLanguageGen class, which is able to produce text that matches a certain style, // usually that of a natural language but some imitations of fictional languages, such as languages spoken by elves, // goblins, or demons, are present as well. An unusual trait of FakeLanguageGen is that it can mix two or more // languages to make a new one, which most other kinds of generators have a somewhat-hard time doing. private NaturalLanguageCipher translator; // this is initialized with the word-wrapped contents of artOfWar, then has translations of that text to imaginary // languages appended after the plain-English version. The contents have the first item removed with each step, and // have new translations added whenever the line count is too low. private ArrayList<IColoredString<Color>> lang; private double[][] resistance; private double[][] visible; // GreasedRegion is a hard-to-explain class, but it's an incredibly useful one for map generation and many other // tasks; it stores a region of "on" cells where everything not in that region is considered "off," and can be used // as a Collection of Coord points. However, it's more than that! Because of how it is implemented, it can perform // bulk operations on as many as 64 points at a time, and can efficiently do things like expanding the "on" area to // cover adjacent cells that were "off", retracting the "on" area away from "off" cells to shrink it, getting the // surface ("on" cells that are adjacent to "off" cells) or fringe ("off" cells that are adjacent to "on" cells), // and generally useful things like picking a random point from all "on" cells. // Here, we use a GreasedRegion to store all floors that the player can walk on, a small rim of cells just beyond // the player's vision that blocks pathfinding to areas we can't see a path to, and we also store all cells that we // have seen in the past in a GreasedRegion (in most roguelikes, there would be one of these per dungeon floor). private GreasedRegion floors, blockage, seen, currentlySeen; // a Glyph is a kind of scene2d Actor that only holds one char in a specific color, but is drawn using the behavior // of TextCellFactory (which most text in SquidLib is drawn with) instead of the different and not-very-compatible // rules of Label, which older SquidLib code used when it needed text in an Actor. Glyphs are also lighter-weight in // memory usage and time taken to draw than Labels. private TextCellFactory.Glyph pg; // libGDX can use a kind of packed float (yes, the number type) to efficiently store colors, but it also uses a // heavier-weight Color object sometimes; SquidLib has a large list of SColor objects that are often used as easy // predefined colors since SColor extends Color. SparseLayers makes heavy use of packed float colors internally, // but also allows Colors instead for most methods that take a packed float. Some cases, like very briefly-used // colors that are some mix of two other colors, are much better to create as packed floats from other packed // floats, usually using SColor.lerpFloatColors(), which avoids creating any objects. It's ideal to avoid creating // new objects (such as Colors) frequently for only brief usage, because this can cause temporary garbage objects to // build up and slow down the program while they get cleaned up (garbage collection, which is slower on Android). // Recent versions of SquidLib include the packed float literal in the JavaDocs for any SColor, along with previews // of that SColor as a background and foreground when used with other colors, plus more info like the hue, // saturation, and value of the color. Here we just use the packed floats directly from the SColor docs, but we also // mention what color it is in a line comment, which is a good habit so you can see a preview if needed. private static final float FLOAT_LIGHTING = -0x1.cff1fep126F, // same result as SColor.COSMIC_LATTE.toFloatBits() GRAY_FLOAT = -0x1.7e7e7ep125F; // same result as SColor.CW_GRAY_BLACK.toFloatBits() // This filters colors in a way we adjust over time, producing a sort of hue shift effect. // It can also be used to over- or under-saturate colors, change their brightness, or any combination of these. private FloatFilters.YCwCmFilter warmMildFilter; @Override public void create () { // gotta have a random number generator. We can seed an RNG with any long we want, or even a String. // if the seed is identical between two runs, any random factors will also be identical (until user input may // cause the usage of an RNG to change). You can randomize the dungeon and several other initial settings by // just removing the String seed, making the line "rng = new GWTRNG();" . Keeping the seed as a default allows // changes to be more easily reproducible, and using a fixed seed is strongly recommended for tests. // SquidLib has many methods that expect an IRNG instance, and there's several classes to choose from. // In this program we'll use GWTRNG, which will behave better on the HTML target than other generators. rng = new GWTRNG(artOfWar); // YCwCmFilter multiplies the brightness (Y), warmth (Cw), and mildness (Cm) of a color warmMildFilter = new FloatFilters.YCwCmFilter(0.875f, 0.6f, 0.6f); // FilterBatch is exactly like libGDX' SpriteBatch, except it is a fair bit faster when the Batch color is set // often (which is always true for SquidLib's text-based display), and it allows a FloatFilter to be optionally // set that can adjust colors in various ways. The FloatFilter here, a YCwCmFilter, can have its adjustments to // brightness (Y, also called luma), warmth (blue/green vs. red/yellow) and mildness (blue/red vs. green/yellow) // changed at runtime, and the putMap() method does this. This can be very powerful; you might increase the // warmth of all colors (additively) if the player is on fire, for instance. batch = new FilterBatch(warmMildFilter); StretchViewport mainViewport = new StretchViewport(gridWidth * cellWidth, gridHeight * cellHeight), languageViewport = new StretchViewport(gridWidth * cellWidth, bonusHeight * cellHeight); mainViewport.setScreenBounds(0, 0, gridWidth * cellWidth, gridHeight * cellHeight); languageViewport .setScreenBounds(0, 0, gridWidth * cellWidth, bonusHeight * cellHeight); //Here we make sure our Stage, which holds any text-based grids we make, uses our Batch. stage = new Stage(mainViewport, batch); languageStage = new Stage(languageViewport, batch); // the font will try to load Iosevka Slab as an embedded bitmap font with a MSDF effect (multi scale distance // field, a way to allow a bitmap font to stretch while still keeping sharp corners and round curves). // the MSDF effect is handled internally by a shader in SquidLib, and will switch to a different shader if a SDF // effect is used (SDF is called "Stretchable" in DefaultResources, where MSDF is called "Crisp"). // this font is covered under the SIL Open Font License (fully free), so there's no reason it can't be used. // it also includes 4 text faces (regular, bold, oblique, and bold oblique) so methods in GDXMarkup can make // italic or bold text without switching fonts (they can color sections of text too). display = new SparseLayers(bigWidth, bigHeight + bonusHeight, cellWidth, cellHeight, DefaultResources.getCrispSlabFamily()); // a bit of a hack to increase the text height slightly without changing the size of the cells they're in. // this causes a tiny bit of overlap between cells, which gets rid of an annoying gap between vertical lines. // if you use '#' for walls instead of box drawing chars, you don't need this. //display.font.tweakWidth(cellWidth * 1.075f).tweakHeight(cellHeight * 1.1f).initBySize(); languageDisplay = new SparseLayers(gridWidth, bonusHeight - 1, cellWidth, cellHeight, display.font); // SparseDisplay doesn't currently use the default background fields, but this isn't really a problem; we can // set the background colors directly as floats with the SparseDisplay.backgrounds field, and it can be handy // to hold onto the current color we want to fill that with in the defaultPackedBackground field. // SparseLayers has fillBackground() and fillArea() methods for coloring all or part of the backgrounds. languageDisplay.defaultPackedBackground = FLOAT_LIGHTING; // happens to be the same color used for lighting //This uses the seeded RNG we made earlier to build a procedural dungeon using a method that takes rectangular //sections of pre-drawn dungeon and drops them into place in a tiling pattern. It makes good winding dungeons //with rooms by default, but in the later call to dungeonGen.generate(), you can use a TilesetType such as //TilesetType.ROUND_ROOMS_DIAGONAL_CORRIDORS or TilesetType.CAVES_LIMIT_CONNECTIVITY to change the sections that //this will use, or just pass in a full 2D char array produced from some other generator, such as //SerpentMapGenerator, OrganicMapGenerator, or DenseRoomMapGenerator. dungeonGen = new DungeonGenerator(bigWidth, bigHeight, rng); //uncomment this next line to randomly add water to the dungeon in pools. //dungeonGen.addWater(15); //decoDungeon is given the dungeon with any decorations we specified. (Here, we didn't, unless you chose to add //water to the dungeon. In that case, decoDungeon will have different contents than bareDungeon, next.) decoDungeon = dungeonGen.generate(); //getBareDungeon provides the simplest representation of the generated dungeon -- '#' for walls, '.' for floors. bareDungeon = dungeonGen.getBareDungeon(); //When we draw, we may want to use a nicer representation of walls. DungeonUtility has lots of useful methods //for modifying char[][] dungeon grids, and this one takes each '#' and replaces it with a box-drawing char. //The end result looks something like this, for a smaller 60x30 map: // // ┌───┐┌──────┬──────┐┌──┬─────┐ ┌──┐ ┌──────────┬─────┐ // │...││......│......└┘..│.....│ │..├───┐│..........│.....└┐ // │...││......│..........├──┐..├───┤..│...└┴────......├┐.....│ // │...││.................│┌─┘..│...│..│...............││.....│ // │...││...........┌─────┘│....│...│..│...........┌───┴┴───..│ // │...│└─┐....┌───┬┘ │........│..│......─────┤..........│ // │...└─┐│....│...│ │.......................│..........│ // │.....││........└─┐ │....│..................│.....┌────┘ // │.....││..........│ │....├─┬───────┬─┐......│.....│ // └┬──..└┼───┐......│ ┌─┴─..┌┘ │.......│ │.....┌┴──┐..│ // │.....│ ┌┴─..───┴───┘.....└┐ │.......│┌┘.....└─┐ │..│ // │.....└──┘..................└─┤.......││........│ │..│ // │.............................│.......├┘........│ │..│ // │.............┌──────┐........│.......│...─┐....│ │..│ // │...........┌─┘ └──┐.....│..─────┘....│....│ │..│ // ┌┴─────......└─┐ ┌──┘..................│..──┴─┘..└─┐ // │..............└──────┘.....................│...........│ // │............................┌─┐.......│....│...........│ // │..│..│..┌┐..................│ │.......├────┤..──┬───┐..│ // │..│..│..│└┬──..─┬───┐......┌┘ └┐.....┌┘┌───┤....│ │..│ // │..├──┤..│ │.....│ │......├───┘.....│ │...│....│┌──┘..└──┐ // │..│┌─┘..└┐└┬─..─┤ │......│.........└─┘...│....││........│ // │..││.....│ │....│ │......│...............│....││........│ // │..││.....│ │....│ │......│..┌──┐.........├────┘│..│.....│ // ├──┴┤...│.└─┴─..┌┘ └┐....┌┤..│ │.....│...└─────┘..│.....│ // │...│...│.......└─────┴─..─┴┘..├──┘.....│............└─────┤ // │...│...│......................│........│..................│ // │.......├───┐..................│.......┌┤.......┌─┐........│ // │.......│ └──┐..┌────┐..┌────┤..┌────┘│.......│ │..┌──┐..│ // └───────┘ └──┘ └──┘ └──┘ └───────┘ └──┘ └──┘ //this is also good to compare against if the map looks incorrect, and you need an example of a correct map when //no parameters are given to generate(). lineDungeon = DungeonUtility.hashesToLines(decoDungeon); resistance = DungeonUtility.generateResistances(decoDungeon); visible = new double[bigWidth][bigHeight]; //Coord is the type we use as a general 2D point, usually in a dungeon. //Because we know dungeons won't be incredibly huge, Coord performs best for x and y values less than 256, but // by default it can also handle some negative x and y values (-3 is the lowest it can efficiently store). You // can call Coord.expandPool() or Coord.expandPoolTo() if you need larger maps to be just as fast. cursor = Coord.get(-1, -1); // here, we need to get a random floor cell to place the player upon, without the possibility of putting him // inside a wall. There are a few ways to do this in SquidLib. The most straightforward way is to randomly // choose x and y positions until a floor is found, but particularly on dungeons with few floor cells, this can // have serious problems -- if it takes too long to find a floor cell, either it needs to be able to figure out // that random choice isn't working and instead choose the first it finds in simple iteration, or potentially // keep trying forever on an all-wall map. There are better ways! These involve using a kind of specific storage // for points or regions, getting that to store only floors, and finding a random cell from that collection of // floors. The two kinds of such storage used commonly in SquidLib are the "packed data" as short[] produced by // CoordPacker (which use very little memory, but can be slow, and are treated as unchanging by CoordPacker so // any change makes a new array), and GreasedRegion objects (which use slightly more memory, tend to be faster // on almost all operations compared to the same operations with CoordPacker, and default to changing the // GreasedRegion object when you call a method on it instead of making a new one). Even though CoordPacker // sometimes has better documentation, GreasedRegion is generally a better choice; it was added to address // shortcomings in CoordPacker, particularly for speed, and the worst-case scenarios for data in CoordPacker are // no problem whatsoever for GreasedRegion. CoordPacker is called that because it compresses the information // for nearby Coords into a smaller amount of memory. GreasedRegion is called that because it encodes regions, // but is "greasy" both in the fatty-food sense of using more space, and in the "greased lightning" sense of // being especially fast. Both of them can be seen as storing regions of points in 2D space as "on" and "off." // Here we fill a GreasedRegion so it stores the cells that contain a floor, the '.' char, as "on." floors = new GreasedRegion(bareDungeon, '.'); //player is, here, just a Coord that stores his position. In a real game, you would probably have a class for //creatures, and possibly a subclass for the player. The singleRandom() method on GreasedRegion finds one Coord // in that region that is "on," or -1,-1 if there are no such cells. It takes an RNG object as a parameter, and // if you gave a seed to the RNG constructor, then the cell this chooses will be reliable for testing. If you // don't seed the RNG, any valid cell should be possible. player = floors.singleRandom(rng); //These need to have their positions set before adding any entities if there is an offset involved. //There is no offset used here, but it's still a good practice here to set positions early on. // display.setPosition(gridWidth * cellWidth * 0.5f - display.worldX(player.x), // gridHeight * cellHeight * 0.5f - display.worldY(player.y)); display.setPosition(0f, 0f); // Uses shadowcasting FOV and reuses the visible array without creating new arrays constantly. FOV.reuseFOV(resistance, visible, player.x, player.y, 9.0, Radius.CIRCLE);//, (System.currentTimeMillis() & 0xFFFF) * 0x1p-4, 60.0); // 0.01 is the upper bound (inclusive), so any Coord in visible that is more well-lit than 0.01 will _not_ be in // the blockage Collection, but anything 0.01 or less will be in it. This lets us use blockage to prevent access // to cells we can't see from the start of the move. blockage = new GreasedRegion(visible, 0.0); seen = blockage.not().copy(); currentlySeen = seen.copy(); blockage.fringe8way(); // prunedDungeon starts with the full lineDungeon, which includes features like water and grass but also stores // all walls as box-drawing characters. The issue with using lineDungeon as-is is that a character like '┬' may // be used because there are walls to the east, west, and south of it, even when the player is to the north of // that cell and so has never seen the southern connecting wall, and would have no reason to know it is there. // By calling LineKit.pruneLines(), we adjust prunedDungeon to hold a variant on lineDungeon that removes any // line segments that haven't ever been visible. This is called again whenever seen changes. prunedDungeon = ArrayTools.copy(lineDungeon); // We call pruneLines with an optional parameter here, LineKit.lightAlt, which will allow prunedDungeon to use // the half-line chars "╴╵╶╷". These chars aren't supported by all fonts, but they are by the one we use here. // The default is to use LineKit.light , which will replace '╴' and '╶' with '─' and '╷' and '╵' with '│'. LineKit.pruneLines(lineDungeon, seen, LineKit.lightAlt, prunedDungeon); //This is used to allow clicks or taps to take the player to the desired area. toCursor = new ArrayList<>(200); //When a path is confirmed by clicking, we draw from this List to find which cell is next to move into. awaitedMoves = new ArrayList<>(200); //DijkstraMap is the pathfinding swiss-army knife we use here to find a path to the latest cursor position. //Measurement is an enum that determines the possibility or preference to enter diagonals. Here, the // MANHATTAN value is used, which means 4-way movement only, no diagonals possible. Alternatives are CHEBYSHEV, // which allows 8 directions of movement at the same cost for all directions, and EUCLIDEAN, which allows 8 // directions, but will prefer orthogonal moves unless diagonal ones are clearly closer "as the crow flies." playerToCursor = new DijkstraMap(decoDungeon, Measurement.MANHATTAN); //These next two lines mark the player as something we want paths to go to or from, and get the distances to the // player from all walkable cells in the dungeon. playerToCursor.setGoal(player); playerToCursor.setGoal(player); // DijkstraMap.partialScan only finds the distance to get to a cell if that distance is less than some limit, // which is 13 here. It also won't try to find distances through an impassable cell, which here is the blockage // GreasedRegion that contains the cells just past the edge of the player's FOV area. playerToCursor.partialScan(13, blockage); //The next three lines set the background color for anything we don't draw on, but also create 2D arrays of the //same size as decoDungeon that store the colors for the foregrounds and backgrounds of each cell as packed //floats (a format SparseLayers can use throughout its API), using the colors for the cell with the same x and //y. By changing an item in SColor.LIMITED_PALETTE, we also change the color assigned by MapUtility to floors. bgColor = SColor.DARK_SLATE_GRAY; SColor.LIMITED_PALETTE[3] = SColor.DB_GRAPHITE; colors = MapUtility.generateDefaultColorsFloat(decoDungeon); bgColors = MapUtility.generateDefaultBGColorsFloat(decoDungeon); // for (int x = 0; x < bigWidth; x++) { // for (int y = 0; y < bigHeight; y++) { // colors[x][y] = f(colors[x][y]); // bgColors[x][y] = f(bgColors[x][y]); // } // } //places the player as an '@' at his position in orange. pg = display.glyph('@', SColor.SAFETY_ORANGE, player.x, player.y); // here we build up a List of IColoredString values formed by formatting the artOfWar text (this colors the // whole thing dark gray and puts the name at the start in italic/oblique face) and wrapping it to fit within // the width we want, filling up lang with the results. lang = new ArrayList<>(16); GDXMarkup.instance.colorString(artOfWar).wrap(gridWidth - 2, lang); // here we choose a random language from all the hand-made FakeLanguageGen text generators, and make a // NaturalLanguageCipher out of it. This Cipher takes words it finds in artOfWar and translates them to the // fictional language it selected. translator = new NaturalLanguageCipher(rng.getRandomElement(FakeLanguageGen.registered)); // this is just like the call above except we work on the translated artOfWar text instead of the original. GDXMarkup.instance.colorString(translator.cipher(artOfWar)).wrap(gridWidth - 2, lang); // now we change the language again and tell the NaturalLanguageCipher, translator, what we chose. translator.initialize(rng.getRandomElement(FakeLanguageGen.registered), 0L); // this is a big one. // SquidInput can be constructed with a KeyHandler (which just processes specific keypresses), a SquidMouse // (which is given an InputProcessor implementation and can handle multiple kinds of mouse move), or both. // keyHandler is meant to be able to handle complex, modified key input, typically for games that distinguish // between, say, 'q' and 'Q' for 'quaff' and 'Quip' or whatever obtuse combination you choose. The // implementation here handles hjkl keys (also called vi-keys), numpad, arrow keys, and wasd for 4-way movement. // Shifted letter keys produce capitalized chars when passed to KeyHandler.handle(), but we don't care about // that so we just use two case statements with the same body, i.e. one for 'A' and one for 'a'. // You can also set up a series of future moves by clicking within FOV range, using mouseMoved to determine the // path to the mouse position with a DijkstraMap (called playerToCursor), and using touchUp to actually trigger // the event when someone clicks. input = new SquidInput(new SquidInput.KeyHandler() { @Override public void handle(char key, boolean alt, boolean ctrl, boolean shift) { switch (key) { case SquidInput.UP_ARROW: // case 'k': // case 'K': case 'w': case 'W': { toCursor.clear(); //-1 is up on the screen awaitedMoves.add(player.translate(0, -1)); break; } case SquidInput.DOWN_ARROW: // case 'j': // case 'J': case 's': case 'S': { toCursor.clear(); //+1 is down on the screen awaitedMoves.add(player.translate(0, 1)); break; } case SquidInput.LEFT_ARROW: // case 'h': // case 'H': case 'a': case 'A': { toCursor.clear(); awaitedMoves.add(player.translate(-1, 0)); break; } case SquidInput.RIGHT_ARROW: // case 'l': // case 'L': case 'd': case 'D': { toCursor.clear(); awaitedMoves.add(player.translate(1, 0)); break; } case 'Q': case 'q': case SquidInput.ESCAPE: { Gdx.app.exit(); break; } case 'c': case 'C': { seen.fill(true); break; } } } }, //The second parameter passed to a SquidInput can be a SquidMouse, which takes mouse or touchscreen //input and converts it to grid coordinates (here, a cell is 10 wide and 20 tall, so clicking at the // pixel position 16,51 will pass screenX as 1 (since if you divide 16 by 10 and round down you get 1), // and screenY as 2 (since 51 divided by 20 rounded down is 2)). new SquidMouse(cellWidth, cellHeight, gridWidth, gridHeight, 0, 0, new InputAdapter() { // if the user clicks and there are no awaitedMoves queued up, generate toCursor if it // hasn't been generated already by mouseMoved, then copy it over to awaitedMoves. @Override public boolean touchUp(int screenX, int screenY, int pointer, int button) { // This is needed because we center the camera on the player as he moves through a dungeon that is three // screens wide and three screens tall, but the mouse still only can receive input on one screen's worth // of cells. (gridWidth >> 1) halves gridWidth, pretty much, and that we use to get the centered // position after adding to the player's position (along with the gridHeight). screenX += player.x - (gridWidth >> 1); screenY += player.y - (gridHeight >> 1); // we also need to check if screenX or screenY is out of bounds. if (screenX < 0 || screenY < 0 || screenX >= bigWidth || screenY >= bigHeight) return false; if (awaitedMoves.isEmpty()) { if (toCursor.isEmpty()) { cursor = Coord.get(screenX, screenY); //This uses DijkstraMap.findPathPreScannned() to get a path as a List of Coord from the current // player position to the position the user clicked on. The "PreScanned" part is an optimization // that's special to DijkstraMap; because the whole map has already been fully analyzed by the // DijkstraMap.scan() method at the start of the program, and re-calculated whenever the player // moves, we only need to do a fraction of the work to find the best path with that info. toCursor.clear(); playerToCursor.findPathPreScanned(toCursor, cursor); //findPathPreScanned includes the current cell (goal) by default, which is helpful when // you're finding a path to a monster or loot, and want to bump into it, but here can be // confusing because you would "move into yourself" as your first move without this. if(!toCursor.isEmpty()) toCursor.remove(0); } awaitedMoves.addAll(toCursor); } return true; } @Override public boolean touchDragged(int screenX, int screenY, int pointer) { return mouseMoved(screenX, screenY); } // causes the path to the mouse position to become highlighted (toCursor contains a list of Coords that // receive highlighting). Uses DijkstraMap.findPathPreScanned() to find the path, which is rather fast. @Override public boolean mouseMoved(int screenX, int screenY) { if(!awaitedMoves.isEmpty()) return false; // This is needed because we center the camera on the player as he moves through a dungeon that is three // screens wide and three screens tall, but the mouse still only can receive input on one screen's worth // of cells. (gridWidth >> 1) halves gridWidth, pretty much, and that we use to get the centered // position after adding to the player's position (along with the gridHeight). screenX += player.x - (gridWidth >> 1); screenY += player.y - (gridHeight >> 1); // we also need to check if screenX or screenY is out of bounds. if(screenX < 0 || screenY < 0 || screenX >= bigWidth || screenY >= bigHeight || (cursor.x == screenX && cursor.y == screenY)) { return false; } cursor = Coord.get(screenX, screenY); //This uses DijkstraMap.findPathPreScannned() to get a path as a List of Coord from the current // player position to the position the user clicked on. The "PreScanned" part is an optimization // that's special to DijkstraMap; because the whole map has already been fully analyzed by the // DijkstraMap.scan() method at the start of the program, and re-calculated whenever the player // moves, we only need to do a fraction of the work to find the best path with that info. toCursor.clear(); playerToCursor.findPathPreScanned(toCursor, cursor); //findPathPreScanned includes the current cell (goal) by default, which is helpful when // you're finding a path to a monster or loot, and want to bump into it, but here can be // confusing because you would "move into yourself" as your first move without this. if(!toCursor.isEmpty()) toCursor.remove(0); return false; } })); //Setting the InputProcessor is ABSOLUTELY NEEDED TO HANDLE INPUT Gdx.input.setInputProcessor(new InputMultiplexer(stage, input)); //You might be able to get by with the next line instead of the above line, but the former is preferred. //Gdx.input.setInputProcessor(input); // and then add display, our one visual component, to the list of things that act in Stage. stage.addActor(display); languageStage.addActor(languageDisplay); screenPosition = new Vector2(cellWidth, cellHeight); } /** * Move the player if he isn't bumping into a wall or trying to go off the map somehow. * In a fully-fledged game, this would not be organized like this, but this is a one-file demo. * @param xmod * @param ymod */ private void move(final int xmod, final int ymod) { int newX = player.x + xmod, newY = player.y + ymod; if (newX >= 0 && newY >= 0 && newX < bigWidth && newY < bigHeight && bareDungeon[newX][newY] != '#') { // we can call some methods on a SparseLayers to show effects on Glyphs it knows about. // sliding pg, the player glyph, makes that '@' move smoothly between grid cells. display.slide(pg, player.x, player.y, newX, newY, 0.12f, null); // this just moves the grid position of the player as it is internally tracked. player = player.translate(xmod, ymod); // calculates field of vision around the player again, in a circle of radius 9.0 . FOV.reuseFOV(resistance, visible, player.x, player.y, 9.0, Radius.CIRCLE); // This is just like the constructor used earlier, but affects an existing GreasedRegion without making // a new one just for this movement. blockage.refill(visible, 0.0); seen.or(currentlySeen.remake(blockage.not())); blockage.fringe8way(); // By calling LineKit.pruneLines(), we adjust prunedDungeon to hold a variant on lineDungeon that removes any // line segments that haven't ever been visible. This is called again whenever seen changes. LineKit.pruneLines(lineDungeon, seen, LineKit.lightAlt, prunedDungeon); } else { // A SparseLayers knows how to move a Glyph (like the one for the player, pg) out of its normal alignment // on the grid, and also how to move it back again. Using bump() will move pg quickly about a third of the // way into a wall, then back to its former position at normal speed. Direction.getRoughDirection is a // simple way to get which of the 8-way directions small xmod and ymod values point in. display.bump(pg, Direction.getRoughDirection(xmod, ymod), 0.25f); // PanelEffect (from SquidLib) is a type of Action (from libGDX) that can run on a SparseLayers. // This particular kind of PanelEffect creates a purple glow around the player when he bumps into a wall. // Other kinds can make explosions or projectiles appear. display.addAction(new PanelEffect.PulseEffect(display, 1f, currentlySeen, player, 3 , new float[]{SColor.CW_FADED_PURPLE.toFloatBits()} )); // recolor() will change the color of a cell over time from what it is currently to a target color, which is // DB_BLOOD here from a DawnBringer palette. We give it a Runnable to run after the effect finishes, which // permanently sets the color of the cell you bumped into to the color of your bloody nose. Without such a // Runnable, the cell would get drawn over with its normal wall color. display.recolor(0f, player.x + xmod, player.y + ymod, 0, SColor.DB_BLOOD.toFloatBits(), 0.4f, new Runnable() { int x = player.x + xmod; int y = player.y + ymod; @Override public void run() { colors[x][y] = SColor.DB_BLOOD.toFloatBits(); } }); //display.addAction(new PanelEffect.ExplosionEffect(display, 1f, floors, player, 6)); } // removes the first line displayed of the Art of War text or its translation. lang.remove(0); // if the last line reduced the number of lines we can show to less than what we try to show, we fill in more // lines using a randomly selected fake language to translate the same Art of War text. while (lang.size() < bonusHeight - 1) { // refills lang with wrapped lines from the translated artOfWar text GDXMarkup.instance.colorString(translator.cipher(artOfWar)).wrap(gridWidth - 2, lang); translator.initialize(rng.getRandomElement(FakeLanguageGen.registered), 0L); } } /** * Draws the map, applies any highlighting for the path to the cursor, and then draws the player. */ public void putMap() { //In many other situations, you would clear the drawn characters to prevent things that had been drawn in the //past from affecting the current frame. This isn't a problem here, but would probably be an issue if we had //monsters running in and out of our vision. If artifacts from previous frames show up, uncomment the next line. //display.clear(); // causes colors to cycle semi-randomly from warm reds and browns to cold cyan-blues warmMildFilter.cwMul = NumberTools.swayRandomized(123456789L, (System.currentTimeMillis() & 0x1FFFFFL) * 0x1.2p-10f) * 1.75f; // The loop here only will draw tiles if they are potentially in the visible part of the map. // It starts at an x,y position equal to the player's position minus half of the shown gridWidth and gridHeight, // minus one extra cell to allow the camera some freedom to move. This position won't go lower than 0. The // rendering in each direction ends when the edge of the map (bigWidth or bigHeight) is reached, or if // gridWidth/gridHeight + 2 cells have been rendered (the + 2 is also for the camera movement). for (int x = Math.max(0, player.x - (gridWidth >> 1) - 1), i = 0; x < bigWidth && i < gridWidth + 2; x++, i++) { for (int y = Math.max(0, player.y - (gridHeight >> 1) - 1), j = 0; y < bigHeight && j < gridHeight + 2; y++, j++) { if (visible[x][y] > 0.0) { // Here we use a convenience method in SparseLayers that puts a char at a specified position (the // first three parameters), with a foreground color for that char (fourth parameter), as well as // placing a background tile made of a one base color (fifth parameter) that is adjusted to bring it // closer to FLOAT_LIGHTING (sixth parameter) based on how visible the cell is (seventh parameter, // comes from the FOV calculations) in a way that fairly-quickly changes over time. // This effect appears to shrink and grow in a circular area around the player, with the lightest // cells around the player and dimmer ones near the edge of vision. This lighting is "consistent" // because all cells at the same distance will have the same amount of lighting applied. // We use prunedDungeon here so segments of walls that the player isn't aware of won't be shown. display.putWithConsistentLight(x, y, prunedDungeon[x][y], colors[x][y], bgColors[x][y], FLOAT_LIGHTING, visible[x][y]); } else if (seen.contains(x, y)) display.put(x, y, prunedDungeon[x][y], colors[x][y], SColor.lerpFloatColors(bgColors[x][y], GRAY_FLOAT, 0.45f)); } } Coord pt; for (int i = 0; i < toCursor.size(); i++) { pt = toCursor.get(i); // use a brighter light to trace the path to the cursor, mixing the background color with mostly white. display.put(pt.x, pt.y, SColor.lightenFloat(bgColors[pt.x][pt.y], 0.85f)); } languageDisplay.clear(0); languageDisplay.fillBackground(languageDisplay.defaultPackedBackground); for (int i = 0; i < 6; i++) { languageDisplay.put(1, i, lang.get(i)); } } @Override public void render () { // standard clear the background routine for libGDX Gdx.gl.glClearColor(bgColor.r / 255.0f, bgColor.g / 255.0f, bgColor.b / 255.0f, 1.0f); Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); stage.getCamera().position.x = pg.getX(); stage.getCamera().position.y = pg.getY(); putMap(); // if the user clicked, we have a list of moves to perform. if(!awaitedMoves.isEmpty()) { // this doesn't check for input, but instead processes and removes Coords from awaitedMoves. if (!display.hasActiveAnimations()) { Coord m = awaitedMoves.remove(0); if(!toCursor.isEmpty()) toCursor.remove(0); move(m.x - player.x, m.y - player.y); // this only happens if we just removed the last Coord from awaitedMoves, and it's only then that we need to // re-calculate the distances from all cells to the player. We don't need to calculate this information on // each part of a many-cell move (just the end), nor do we need to calculate it whenever the mouse moves. if (awaitedMoves.isEmpty()) { // the next two lines remove any lingering data needed for earlier paths playerToCursor.clearGoals(); playerToCursor.resetMap(); // the next line marks the player as a "goal" cell, which seems counter-intuitive, but it works because all // cells will try to find the distance between themselves and the nearest goal, and once this is found, the // distances don't change as long as the goals don't change. Since the mouse will move and new paths will be // found, but the player doesn't move until a cell is clicked, the "goal" is the non-changing cell (the // player's position), and the "target" of a pathfinding method like DijkstraMap.findPathPreScanned() is the // currently-moused-over cell, which we only need to set where the mouse is being handled. playerToCursor.setGoal(player); // DijkstraMap.partialScan only finds the distance to get to a cell if that distance is less than some limit, // which is 13 here. It also won't try to find distances through an impassable cell, which here is the blockage // GreasedRegion that contains the cells just past the edge of the player's FOV area. playerToCursor.partialScan(13, blockage); } } } // if we are waiting for the player's input and get input, process it. else if(input.hasNext()) { input.next(); } //else // move(0,0); // we need to do some work with viewports here so the language display (or game info messages in a real game) // will display in the same place even though the map view will move around. We have the language stuff set up // its viewport so it is in place and won't be altered by the map. Then we just tell the Stage for the language // texts to draw. languageStage.getViewport().apply(false); languageStage.draw(); // certain classes that use scene2d.ui widgets need to be told to act() to process input. stage.act(); // we have the main stage set itself up after the language stage has already drawn. stage.getViewport().apply(false); // stage has its own batch and must be explicitly told to draw(). batch.setProjectionMatrix(stage.getCamera().combined); screenPosition.set(cellWidth * 12, cellHeight); stage.screenToStageCoordinates(screenPosition); batch.begin(); stage.getRoot().draw(batch, 1); display.font.draw(batch, Gdx.graphics.getFramesPerSecond() + " FPS", screenPosition.x, screenPosition.y); batch.end(); Gdx.graphics.setTitle("SparseLayers Demo running at FPS: " + Gdx.graphics.getFramesPerSecond()); } @Override public void resize(int width, int height) { super.resize(width, height); // message box won't respond to clicks on the far right if the stage hasn't been updated with a larger size float currentZoomX = (float)width / gridWidth; // total new screen height in pixels divided by total number of rows on the screen float currentZoomY = (float)height / (gridHeight + bonusHeight); // message box should be given updated bounds since I don't think it will do this automatically languageDisplay.setBounds(0, 0, width, currentZoomY * bonusHeight); // SquidMouse turns screen positions to cell positions, and needs to be told that cell sizes have changed // a quirk of how the camera works requires the mouse to be offset by half a cell if the width or height is odd // (gridWidth & 1) is 1 if gridWidth is odd or 0 if it is even; it's good to know and faster than using % , plus // in some other cases it has useful traits (x % 2 can be 0, 1, or -1 depending on whether x is negative, while // x & 1 will always be 0 or 1). input.getMouse().reinitialize(currentZoomX, currentZoomY, gridWidth, gridHeight, (gridWidth & 1) * (int)(currentZoomX * -0.5f), (gridHeight & 1) * (int) (currentZoomY * -0.5f)); // the viewports are updated separately so each doesn't interfere with the other's drawn area. languageStage.getViewport().update(width, height, false); // we also set the bounds of that drawn area here for each viewport. languageStage.getViewport().setScreenBounds(0, 0, width, (int)languageDisplay.getHeight()); // we did this for the language viewport, now again for the main viewport stage.getViewport().update(width, height, false); stage.getViewport().setScreenBounds(0, (int)languageDisplay.getHeight(), width, height - (int)languageDisplay.getHeight()); } } // An explanation of hexadecimal float/double literals was mentioned earlier, so here it is. // The literal 0x1p-9f is a good example; it is essentially the same as writing 0.001953125f, // (float)Math.pow(2.0, -9.0), or (1f / 512f), but is possibly faster than the last two if the // compiler can't optimize float division effectively, and is a good tool to have because these // hexadecimal float or double literals always represent numbers accurately. To contrast, // 0.3 - 0.2 is not equal to 0.1 with doubles, because tenths are inaccurate with floats and // doubles, and hex literals won't have the option to write an inaccurate float or double. // There's some slightly confusing syntax used to write these literals; the 0x means the first // part uses hex digits (0123456789ABCDEF), but the p is not a hex digit and is used to start // the "p is for power" exponent section. In the example, I used -9 for the power; this is a // base 10 number, and is used to mean a power of 2 that the hex digits will be multiplied by. // Because the -9 is a base 10 number, the f at the end is not a hex digit, and actually just // means the literal is a float, in the same way 1.5f is a float. 2.0 to the -9 is the same as // 1.0 / Math.pow(2.0, 9.0), but re-calculating Math.pow() is considerably slower if you run it // for every cell during every frame. Though this is most useful for negative exponents because // there are a lot of numbers after the decimal point to write out with 0.001953125 or the like, // it is also sometimes handy when you have an integer or long written in hexadecimal and want // to make it a float or double. You could use the hex long 0x9E3779B9L, for instance, but to // write that as a double you would use 0x9E3779B9p0 , not the invalid syntax 0x9E3779B9.0 . // We use p0 there because 2 to the 0 is 1, so multiplying by 1 gets us the same hex number. // Very large numbers can also benefit by using a large positive exponent; using p10 and p+10 // as the last part of a hex literal are equivalent. You can see the hex literal for any given // float with Float.toHexString(float), or for a double with Double.toHexString(double) . // SColor provides the packed float versions of all color constants as hex literals in the // documentation for each SColor. // More information here: https://blogs.oracle.com/darcy/hexadecimal-floating-point-literals """ }
apache-2.0
9ee70fcf0b6848170bd6ce9c9da976ad
69.379778
214
0.642261
4.224558
false
false
false
false
hwki/SimpleBitcoinWidget
bitcoin/src/main/java/com/brentpanther/bitcoinwidget/ui/settings/SettingsScreen.kt
1
14695
package com.brentpanther.bitcoinwidget.ui.settings import android.app.Activity import android.app.Activity.RESULT_OK import android.graphics.Typeface import androidx.compose.foundation.layout.* import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.verticalScroll import androidx.compose.material.* import androidx.compose.runtime.Composable import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringArrayResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.lifecycle.viewmodel.compose.viewModel import androidx.navigation.NavController import com.brentpanther.bitcoinwidget.* import com.brentpanther.bitcoinwidget.R import com.brentpanther.bitcoinwidget.db.ConfigurationWithSizes import com.brentpanther.bitcoinwidget.db.Widget import com.brentpanther.bitcoinwidget.exchange.Exchange import com.brentpanther.bitcoinwidget.ui.BannersViewModel import com.brentpanther.bitcoinwidget.ui.WarningBanner import com.brentpanther.bitcoinwidget.ui.WidgetPreview @Composable fun SettingsScreen( navController: NavController, widgetId: Int, viewModel: SettingsViewModel = viewModel(), bannersViewModel: BannersViewModel = viewModel() ) { BaseSettingsScreen(navController, viewModel, bannersViewModel, widgetId) { when (WidgetApplication.instance.getWidgetType(widgetId)) { WidgetType.PRICE -> PriceSettings(it, viewModel) WidgetType.VALUE -> ValueSettings(it, viewModel) } } } @Composable fun BaseSettingsScreen( navController: NavController, viewModel: SettingsViewModel, bannersViewModel: BannersViewModel, widgetId: Int, content: @Composable (Widget) -> Unit ) { viewModel.loadData(widgetId) val widgetState by viewModel.widgetFlow.collectAsState(null) val widget = widgetState val config by viewModel.configFlow.collectAsState( ConfigurationWithSizes(15, false, 0, 0) ) val context = LocalContext.current val fromHome = navController.backQueue.any { it.destination.route == "home" } Scaffold( topBar = { TopAppBar( title = { when (widget?.state) { null -> {} WidgetState.DRAFT -> Text(stringResource(R.string.new_widget, widget.coinName())) else -> Text(stringResource(R.string.edit_widget, widget.coinName())) } } ) }, floatingActionButton = { widget?.let { ExtendedFloatingActionButton( onClick = { viewModel.save() if (fromHome) { navController.navigateUp() } else { (context as Activity).apply { setResult(RESULT_OK) WidgetProvider.refreshWidgets(this) finish() } } }, icon = { Icon(painterResource(R.drawable.ic_outline_check_24), null) }, text = { when (it.state) { WidgetState.DRAFT -> Text( stringResource(R.string.settings_create) .uppercase() ) else -> Text( stringResource(R.string.settings_update) .uppercase() ) } } ) } }, floatingActionButtonPosition = FabPosition.Center ) { paddingValues -> when (widget) { null -> { Box(contentAlignment = Alignment.Center, modifier = Modifier.fillMaxSize()) { CircularProgressIndicator(strokeWidth = 6.dp, modifier = Modifier.size(80.dp)) } } else -> { Column( Modifier .padding(paddingValues) .fillMaxWidth() ) { if (widget.state != WidgetState.DRAFT) { WarningBanner(bannersViewModel) } Text( text = stringResource(widget.widgetType.widgetSummary, widget.coinName()), fontSize = 14.sp, fontFamily = FontFamily(Typeface.create("sans-serif-light", Typeface.BOLD)), fontWeight = FontWeight.Bold, modifier = Modifier .padding(top = 8.dp) .padding(horizontal = 16.dp) ) SettingsHeader( title = R.string.title_preview, Modifier.padding(bottom = 16.dp), withDivider = false ) WidgetPreview( widget, config.consistentSize, Modifier .height(96.dp) .fillMaxWidth() ) Column(Modifier.verticalScroll(rememberScrollState())) { content(widget) Spacer(Modifier.height(80.dp)) } } } } } } @Composable fun ValueSettings(widget: Widget, settingsPriceViewModel: SettingsViewModel) { DataSection(settingsPriceViewModel, widget) SettingsEditText( icon = { Icon(painterResource(R.drawable.ic_outline_account_balance_wallet_24), null) }, title = { Text(stringResource(id = R.string.title_amount_held)) }, subtitle = { Text(widget.amountHeld.toString()) }, dialogText = { Text(stringResource(R.string.dialog_amount_held, widget.coinName())) }, value = widget.amountHeld.toString(), onChange = { it.toDoubleOrNull()?.apply { settingsPriceViewModel.setAmountHeld(this) } } ) FormatSection(settingsPriceViewModel, widget) StyleSection(settingsPriceViewModel, widget) DisplaySection(settingsPriceViewModel, widget) SettingsSwitch( icon = { Icon(painterResource(R.drawable.ic_outline_numbers_24), null) }, title = { Text(stringResource(R.string.title_amount_label)) }, value = widget.showAmountLabel, onChange = { settingsPriceViewModel.setShowAmountLabel(it) } ) } @Composable fun PriceSettings(widget: Widget, settingsPriceViewModel: SettingsViewModel) { DataSection(settingsPriceViewModel, widget) SettingsSwitch( icon = { Icon(painterResource(R.drawable.ic_outline_change_24), null) }, title = { Text(stringResource(R.string.title_inverse)) }, subtitle = { if (widget.useInverse) { Text(stringResource(R.string.summary_inverse, widget.currency, widget.coinName())) } else { Text(stringResource(R.string.summary_inverse, widget.coinName(), widget.currency)) } }, value = widget.useInverse, onChange = { settingsPriceViewModel.setInverse(it) } ) FormatSection(settingsPriceViewModel, widget) if (widget.coinUnit != null) { SettingsList( icon = { Icon(painterResource(R.drawable.ic_decimal_comma), null) }, title = { Text(stringResource(R.string.title_units)) }, subtitle = { value -> Text(stringResource(R.string.summary_units, widget.coinName(), value ?: widget.coinName())) }, value = widget.coinUnit, items = widget.coin.getUnits().map { it.text }, onChange = { settingsPriceViewModel.setCoinUnit(it) } ) } if (widget.currency in Coin.COIN_NAMES) { val currencyUnits = Coin.valueOf(widget.currency).getUnits() SettingsList( icon = { Icon(painterResource(R.drawable.ic_decimal_comma), null) }, title = { Text(stringResource(R.string.title_units)) }, subtitle = { value -> Text(stringResource(R.string.summary_units, widget.currency, value ?: widget.currency)) }, value = widget.currencyUnit ?: widget.currency, items = currencyUnits.map { it.text }, onChange = { settingsPriceViewModel.setCurrencyUnit(it) } ) } StyleSection(settingsPriceViewModel, widget) DisplaySection(settingsPriceViewModel, widget) } @Composable private fun DataSection( settingsPriceViewModel: SettingsViewModel, widget: Widget ) { SettingsHeader(title = R.string.title_data) SettingsList( icon = { Icon(painterResource(R.drawable.ic_outline_local_atm_24), null) }, title = { Text(stringResource(R.string.title_currency)) }, subtitle = { Text(stringResource(R.string.summary_currency, widget.currency)) }, value = widget.currency, items = settingsPriceViewModel.getCurrencies(), onChange = { settingsPriceViewModel.setCurrency(it) } ) SettingsList( icon = { Icon(painterResource(R.drawable.ic_outline_account_balance_24), null) }, title = { Text(stringResource(R.string.title_exchange)) }, subtitle = { Text(stringResource(R.string.summary_exchange, widget.exchange.exchangeName)) }, value = widget.exchange.toString(), items = settingsPriceViewModel.exchanges.map { it.exchangeName }, itemValues = settingsPriceViewModel.exchanges.map { it.name }, onChange = { settingsPriceViewModel.setExchange(Exchange.valueOf(it)) } ) } @Composable private fun FormatSection( settingsPriceViewModel: SettingsViewModel, widget: Widget ) { SettingsHeader( title = R.string.title_format ) val value = when (widget.currencySymbol) { null -> "ISO" "none" -> "NONE" else -> "LOCAL" } SettingsList( icon = { Icon(painterResource(R.drawable.ic_outline_attach_money_24), null) }, title = { Text(stringResource(R.string.title_currency_symbol)) }, subtitle = { Text(it ?: "") }, value = value, items = stringArrayResource(R.array.symbols).toList(), itemValues = stringArrayResource(R.array.symbolValues).toList(), onChange = { settingsPriceViewModel.setCurrencySymbol(it) } ) } @Composable private fun StyleSection( settingsPriceViewModel: SettingsViewModel, widget: Widget ) { SettingsHeader(title = R.string.title_style) SettingsList( icon = { Icon(painterResource(R.drawable.ic_outline_color_lens_24), null) }, title = { Text(stringResource(R.string.title_theme)) }, subtitle = { Text(it ?: "") }, value = widget.theme.name, items = stringArrayResource(R.array.themes).toList(), itemValues = stringArrayResource(R.array.themeValues).toList(), onChange = { settingsPriceViewModel.setTheme(Theme.valueOf(it)) } ) SettingsList( icon = { Icon(painterResource(R.drawable.ic_outline_nightlight_24), null) }, title = { Text(stringResource(R.string.title_night_mode)) }, subtitle = { Text(it ?: "") }, value = widget.nightMode.name, items = stringArrayResource(R.array.nightModes).toList(), itemValues = stringArrayResource(R.array.nightModeValues).toList(), onChange = { settingsPriceViewModel.setNightMode(NightMode.valueOf(it)) } ) } @Composable private fun DisplaySection( settingsViewModel: SettingsViewModel, widget: Widget ) { SettingsHeader(title = R.string.title_display) SettingsSlider( icon = { Icon(painterResource(R.drawable.ic_decimal), null) }, title = { Text(stringResource(R.string.title_decimals)) }, subtitle = { val value = if (widget.numDecimals == -1) { stringResource(R.string.summary_decimals_auto) } else { widget.numDecimals.toString() } Text(value) }, value = widget.numDecimals, range = -1..10, onChange = { settingsViewModel.setNumDecimals(it) } ) SettingsSwitch( icon = { Icon(painterResource(R.drawable.ic_bitcoin), null) }, title = { Text(stringResource(R.string.title_icon)) }, value = widget.showIcon, onChange = { settingsViewModel.setShowIcon(it) } ) SettingsSwitch( icon = { Icon(painterResource(R.drawable.ic_outline_label_24), null) }, title = { Text(stringResource(R.string.title_coin_label)) }, value = widget.showCoinLabel, onChange = { settingsViewModel.setShowCoinLabel(it) } ) SettingsSwitch( icon = { Icon(painterResource(R.drawable.ic_outline_label_24), null) }, title = { Text(stringResource(R.string.title_exchange_label)) }, value = widget.showExchangeLabel, onChange = { settingsViewModel.setShowExchangeLabel(it) } ) }
mit
358d2479b330a6db266ae37c8abc73e0
32.473804
107
0.55461
4.859458
false
false
false
false
pilot51/voicenotify
app/src/main/java/com/pilot51/voicenotify/AppListFragment.kt
1
10245
/* * Copyright 2012-2022 Mark Injerd * * 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.pilot51.voicenotify import android.content.Context import android.content.Context.LAYOUT_INFLATER_SERVICE import android.content.pm.PackageManager import android.os.Bundle import android.view.* import android.view.inputmethod.InputMethodManager import android.widget.* import android.widget.AdapterView.OnItemClickListener import androidx.appcompat.widget.SearchView import androidx.core.content.ContextCompat import androidx.core.view.MenuProvider import androidx.fragment.app.ListFragment import androidx.lifecycle.Lifecycle import com.pilot51.voicenotify.AppDatabase.Companion.db import com.pilot51.voicenotify.Common.getPrefs import com.pilot51.voicenotify.databinding.AppListItemBinding import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock class AppListFragment : ListFragment(), MenuProvider { private val prefs by lazy { getPrefs(requireContext()) } private val adapter by lazy { Adapter() } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) Common.init(requireActivity()) defEnable = prefs.getBoolean(KEY_DEFAULT_ENABLE, true) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) requireActivity().addMenuProvider(this, viewLifecycleOwner, Lifecycle.State.RESUMED) val lv = listView lv.isTextFilterEnabled = true lv.isFastScrollEnabled = true listAdapter = adapter lv.onItemClickListener = OnItemClickListener { _, _, position, _ -> setIgnore(adapter.getItem(position) as App, IGNORE_TOGGLE) adapter.notifyDataSetChanged() } updateAppsList() } private fun updateAppsList() { if (isUpdating) { adapter.setData(apps) return } setListShown(false) isUpdating = true CoroutineScope(Dispatchers.IO).launch { SYNC_APPS.withLock { apps = db.appDao.getAll().toMutableList() onListUpdated() val isFirstLoad = apps.isEmpty() val packMan = requireContext().packageManager // Remove uninstalled for (a in apps.indices.reversed()) { val app = apps[a] try { packMan.getApplicationInfo(app.packageName, 0) } catch (e: PackageManager.NameNotFoundException) { if (!isFirstLoad) app.remove() apps.removeAt(a) onListUpdated() } } // Add new inst@ for (appInfo in packMan.getInstalledApplications(0)) { for (app in apps) { if (app.packageName == appInfo.packageName) { continue@inst } } val app = App( packageName = appInfo.packageName, label = appInfo.loadLabel(packMan).toString(), isEnabled = defEnable ) apps.add(app) onListUpdated() if (!isFirstLoad) app.updateDb() } apps.sortWith { app1, app2 -> app1.label.compareTo(app2.label, ignoreCase = true) } onListUpdated() if (isFirstLoad) db.appDao.upsert(apps) } isUpdating = false CoroutineScope(Dispatchers.Main).launch { setListShown(true) } } } private fun onListUpdated() { CoroutineScope(Dispatchers.Main).launch { adapter.setData(apps) } } override fun onCreateMenu(menu: Menu, menuInflater: MenuInflater) { menuInflater.inflate(R.menu.app_list, menu) val menuFilter = menu.findItem(R.id.filter)!! val searchView = (menuFilter.actionView as SearchView).apply { setIconifiedByDefault(false) setOnQueryTextFocusChangeListener { view, hasFocus -> if (hasFocus) view.post { ContextCompat.getSystemService( view.context, InputMethodManager::class.java )!!.showSoftInput(view.findFocus(), 0) } } } menuFilter.setOnActionExpandListener(object : MenuItem.OnActionExpandListener { override fun onMenuItemActionExpand(p0: MenuItem): Boolean { searchView.run { requestFocus() setOnQueryTextListener(object : SearchView.OnQueryTextListener { override fun onQueryTextSubmit(query: String) = false override fun onQueryTextChange(newText: String): Boolean { adapter.filter.filter(newText) return true } }) } return true } override fun onMenuItemActionCollapse(p0: MenuItem): Boolean { searchView.setQuery(null, true) return true } }) } override fun onMenuItemSelected(menuItem: MenuItem): Boolean { when (menuItem.itemId) { R.id.ignore_all -> { setDefaultEnable(false) massIgnore(IGNORE_ALL) return true } R.id.ignore_none -> { setDefaultEnable(true) massIgnore(IGNORE_NONE) return true } } return false } private fun massIgnore(ignoreType: Int) { for (app in apps) { setIgnore(app, ignoreType) } adapter.notifyDataSetChanged() CoroutineScope(Dispatchers.IO).launch { db.appDao.upsert(apps) } } private fun setIgnore(app: App, ignoreType: Int) { if (!app.enabled && (ignoreType == IGNORE_TOGGLE || ignoreType == IGNORE_NONE)) { app.setEnabled(true, ignoreType == IGNORE_TOGGLE) if (ignoreType == IGNORE_TOGGLE) { Toast.makeText(requireContext(), getString(R.string.app_is_not_ignored, app.label), Toast.LENGTH_SHORT).show() } } else if (app.enabled && (ignoreType == IGNORE_TOGGLE || ignoreType == IGNORE_ALL)) { app.setEnabled(false, ignoreType == IGNORE_TOGGLE) if (ignoreType == IGNORE_TOGGLE) { Toast.makeText(requireContext(), getString(R.string.app_is_ignored, app.label), Toast.LENGTH_SHORT).show() } } } /** Set the default enabled value for new apps. */ private fun setDefaultEnable(enable: Boolean) { defEnable = enable prefs.edit().putBoolean(KEY_DEFAULT_ENABLE, defEnable).apply() } private inner class Adapter : BaseAdapter(), Filterable { private val baseData: MutableList<App> = ArrayList() private val adapterData: MutableList<App> = ArrayList() private val inflater = requireContext().getSystemService(LAYOUT_INFLATER_SERVICE) as LayoutInflater private val appFilter by lazy { SimpleFilter() } fun setData(list: List<App>?) { baseData.clear() baseData.addAll(list!!) refresh() } private fun refresh() { adapterData.clear() adapterData.addAll(baseData) notifyDataSetChanged() } override fun getCount(): Int { return adapterData.size } override fun getItem(position: Int): Any { return adapterData[position] } override fun getItemId(position: Int): Long { return position.toLong() } private inner class ViewHolder { lateinit var appLabel: TextView lateinit var appPackage: TextView lateinit var checkbox: CheckBox } override fun getView(position: Int, convertView: View?, parent: ViewGroup): View { lateinit var holder: ViewHolder val binding = convertView?.let { AppListItemBinding.bind(it).apply { holder = root.tag as ViewHolder } } ?: AppListItemBinding.inflate(inflater, parent, false).apply { holder = ViewHolder() holder.appLabel = appLabel holder.appPackage = appPackage holder.checkbox = checkbox root.tag = holder } holder.appLabel.text = adapterData[position].label holder.appPackage.text = adapterData[position].packageName holder.checkbox.isChecked = adapterData[position].enabled return binding.root } override fun getFilter() = appFilter inner class SimpleFilter : Filter() { override fun performFiltering(prefix: CharSequence?): FilterResults { val results = FilterResults() if (prefix.isNullOrEmpty()) { results.values = baseData results.count = baseData.size } else { val prefixString = prefix.toString().lowercase() val newValues: MutableList<App> = ArrayList() for (app in baseData) { if (app.label.lowercase().contains(prefixString) || app.packageName.lowercase().contains(prefixString)) { newValues.add(app) } } results.values = newValues results.count = newValues.size } return results } override fun publishResults(constraint: CharSequence?, results: FilterResults) { adapterData.clear() adapterData.addAll(results.values as List<App>) if (results.count > 0) notifyDataSetChanged() else notifyDataSetInvalidated() } } } companion object { private lateinit var apps: MutableList<App> private var defEnable = false private const val KEY_DEFAULT_ENABLE = "defEnable" private const val IGNORE_TOGGLE = 0 private const val IGNORE_ALL = 1 private const val IGNORE_NONE = 2 private val SYNC_APPS = Mutex() private var isUpdating = false /** * @param pkg Package name used to find [App] in current list or create a new one from system. * @param ctx Context required to get default enabled preference and to get package manager for searching system. * @return Found or created [App], otherwise null if app not found on system. */ fun findOrAddApp(pkg: String, ctx: Context): App? { return runBlocking(Dispatchers.IO) { SYNC_APPS.withLock { if (!::apps.isInitialized) { defEnable = getPrefs(ctx).getBoolean(KEY_DEFAULT_ENABLE, true) apps = db.appDao.getAll().toMutableList() } for (app in apps) { if (app.packageName == pkg) { return@runBlocking app } } return@runBlocking try { val packMan = ctx.packageManager val app = App( packageName = pkg, label = packMan.getApplicationInfo(pkg, 0).loadLabel(packMan).toString(), isEnabled = defEnable ) apps.add(app.updateDb()) app } catch (e: PackageManager.NameNotFoundException) { e.printStackTrace() null } } } } } }
apache-2.0
2bdf20f39915f5848662ca7bc8386ad1
29.58209
115
0.707467
3.822761
false
false
false
false
manami-project/manami
manami-app/src/main/kotlin/io/github/manamiproject/manami/app/state/InternalState.kt
1
3527
package io.github.manamiproject.manami.app.state import io.github.manamiproject.manami.app.lists.Link import io.github.manamiproject.manami.app.lists.animelist.AnimeListEntry import io.github.manamiproject.manami.app.lists.ignorelist.IgnoreListEntry import io.github.manamiproject.manami.app.lists.watchlist.WatchListEntry import io.github.manamiproject.manami.app.events.EventfulList import io.github.manamiproject.manami.app.events.EventListType.* import io.github.manamiproject.manami.app.state.snapshot.Snapshot import io.github.manamiproject.manami.app.state.snapshot.StateSnapshot import io.github.manamiproject.modb.core.extensions.RegularFile import io.github.manamiproject.modb.core.extensions.regularFileExists internal object InternalState : State { private val animeList: EventfulList<AnimeListEntry> = EventfulList(ANIME_LIST) private val watchList: EventfulList<WatchListEntry> = EventfulList(WATCH_LIST) private val ignoreList: EventfulList<IgnoreListEntry> = EventfulList(IGNORE_LIST) private var openedFile: OpenedFile = NoFile override fun setOpenedFile(file: RegularFile) { check(file.regularFileExists()) { "Path is not a regular file" } openedFile = CurrentFile(file) } override fun openedFile(): OpenedFile = openedFile override fun closeFile() { clear() openedFile = NoFile } override fun animeListEntrtyExists(anime: AnimeListEntry): Boolean = animeList.contains(anime) override fun animeList(): List<AnimeListEntry> = animeList.toList() override fun addAllAnimeListEntries(anime: Collection<AnimeListEntry>) { animeList.addAll(anime.distinct()) val uris = anime.map { it.link }.filterIsInstance<Link>().map { it.uri }.toSet() watchList.removeIf { uris.contains(it.link.uri) } ignoreList.removeIf { uris.contains(it.link.uri) } } override fun removeAnimeListEntry(entry: AnimeListEntry) { animeList.remove(entry) } override fun watchList(): Set<WatchListEntry> = watchList.toSet() override fun addAllWatchListEntries(anime: Collection<WatchListEntry>) { watchList.addAll(anime.distinct()) val uris = anime.map { it.link.uri }.toSet() ignoreList.removeIf { uris.contains(it.link.uri) } } override fun removeWatchListEntry(entry: WatchListEntry) { watchList.remove(entry) } override fun ignoreList(): Set<IgnoreListEntry> = ignoreList.toSet() override fun addAllIgnoreListEntries(anime: Collection<IgnoreListEntry>) { ignoreList.addAll(anime.distinct()) val uris = anime.map { it.link.uri }.toSet() watchList.removeIf { uris.contains(it.link.uri) } } override fun removeIgnoreListEntry(entry: IgnoreListEntry) { ignoreList.remove(entry) } override fun createSnapshot(): Snapshot = StateSnapshot( animeList = animeList(), watchList = watchList(), ignoreList = ignoreList(), ) override fun restore(snapshot: Snapshot) { animeList.clear() animeList.addAll(snapshot.animeList()) watchList.clear() watchList.addAll(snapshot.watchList()) ignoreList.clear() ignoreList.addAll(snapshot.ignoreList()) } override fun clear() { animeList.clear() watchList.clear() ignoreList.clear() } } internal sealed class OpenedFile internal object NoFile : OpenedFile() internal data class CurrentFile(val regularFile: RegularFile) : OpenedFile()
agpl-3.0
55c2371e1fd7a55f1e84996ea6ccd493
33.588235
98
0.719308
4.359703
false
false
false
false
arcao/Geocaching4Locus
app/src/main/java/com/arcao/geocaching4locus/authentication/util/PreferenceAccountManager.kt
1
3502
package com.arcao.geocaching4locus.authentication.util import android.content.Context import androidx.core.content.edit import com.arcao.geocaching4locus.base.constants.PrefConstants import com.arcao.geocaching4locus.data.account.AccountManager import com.arcao.geocaching4locus.data.account.GeocachingAccount import com.arcao.geocaching4locus.data.api.model.enums.MembershipType import com.github.scribejava.core.oauth.OAuth20Service import java.time.Instant import java.time.temporal.ChronoUnit class PreferenceAccountManager(context: Context, oAuthService: OAuth20Service) : AccountManager(oAuthService) { private val prefs = context.getSharedPreferences(PrefConstants.ACCOUNT_STORAGE_NAME, Context.MODE_PRIVATE) val restrictions = AccountRestrictions(context) init { upgradeStorage() account = loadAccount() } private fun loadAccount(): GeocachingAccount? { val accessToken = prefs.getString("accessToken", null) ?: return null val expiration = prefs.getLong("expiration", 0) val refreshToken = prefs.getString("refreshToken", null) ?: return null val userName = prefs.getString("userName", null) ?: return null val membership = prefs.getInt("membership", 0) val avatarUrl = prefs.getString("avatarUrl", null) val bannerUrl = prefs.getString("bannerUrl", null) val lastUserInfoUpdate = prefs.getLong("lastUserInfoUpdate", 0) return GeocachingAccount( accountManager = this, accessToken = accessToken, accessTokenExpiration = Instant.ofEpochMilli(expiration), refreshToken = refreshToken, userName = userName, membership = MembershipType.from(membership), avatarUrl = avatarUrl, bannerUrl = bannerUrl, lastUserInfoUpdate = Instant.ofEpochMilli(lastUserInfoUpdate) ) } override fun saveAccount(account: GeocachingAccount?) { super.saveAccount(account) if (account == null) { prefs.edit { clear() } restrictions.remove() return } prefs.edit { putString("accessToken", account.accessToken) putLong("expiration", account.accessTokenExpiration.toEpochMilli()) putString("refreshToken", account.refreshToken) putString("userName", account.userName) putInt("membership", account.membership.id) putString("avatarUrl", account.avatarUrl) putString("bannerUrl", account.bannerUrl) putLong("lastUserInfoUpdate", account.lastUserInfoUpdate.toEpochMilli()) } } @Suppress("DEPRECATION") private fun upgradeStorage() { val prefVersion = prefs.getInt(PrefConstants.PREF_VERSION, 0) if (prefVersion < 4) { // remove old Geocaching API account deleteAccount() } // update pref_version to latest one if (prefVersion != PrefConstants.CURRENT_PREF_VERSION) { prefs.edit { putInt(PrefConstants.PREF_VERSION, PrefConstants.CURRENT_PREF_VERSION) } } } } val AccountManager.isPremium: Boolean get() = account?.isPremium() ?: false fun AccountManager.restrictions(): AccountRestrictions = (this as PreferenceAccountManager).restrictions fun GeocachingAccount.isAccountUpdateRequired() = Instant.now().minus(1L, ChronoUnit.DAYS).isAfter(lastUserInfoUpdate)
gpl-3.0
2d212839a56d27afa9376c03bfe0b7c3
37.065217
94
0.677613
4.939351
false
false
false
false
RP-Kit/RPKit
bukkit/rpk-payments-bukkit/src/main/kotlin/com/rpkit/payments/bukkit/database/table/RPKPaymentGroupOwnerTable.kt
1
4862
/* * Copyright 2022 Ren Binden * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.rpkit.payments.bukkit.database.table import com.rpkit.characters.bukkit.character.RPKCharacterId import com.rpkit.characters.bukkit.character.RPKCharacterService import com.rpkit.core.database.Database import com.rpkit.core.database.Table import com.rpkit.core.service.Services import com.rpkit.payments.bukkit.RPKPaymentsBukkit import com.rpkit.payments.bukkit.database.create import com.rpkit.payments.bukkit.database.jooq.Tables.RPKIT_PAYMENT_GROUP_OWNER import com.rpkit.payments.bukkit.group.RPKPaymentGroup import com.rpkit.payments.bukkit.group.owner.RPKPaymentGroupOwner import java.util.concurrent.CompletableFuture import java.util.concurrent.CompletableFuture.runAsync import java.util.logging.Level import java.util.logging.Level.SEVERE /** * Represents payment group owner table. */ class RPKPaymentGroupOwnerTable( private val database: Database, private val plugin: RPKPaymentsBukkit ) : Table { fun insert(entity: RPKPaymentGroupOwner): CompletableFuture<Void> { val paymentGroupId = entity.paymentGroup.id ?: return CompletableFuture.completedFuture(null) val characterId = entity.character.id ?: return CompletableFuture.completedFuture(null) return CompletableFuture.runAsync { database.create .insertInto( RPKIT_PAYMENT_GROUP_OWNER, RPKIT_PAYMENT_GROUP_OWNER.PAYMENT_GROUP_ID, RPKIT_PAYMENT_GROUP_OWNER.CHARACTER_ID ) .values( paymentGroupId.value, characterId.value ) .execute() }.exceptionally { exception -> plugin.logger.log(Level.SEVERE, "Failed to insert payment group owner", exception) throw exception } } operator fun get(paymentGroup: RPKPaymentGroup): CompletableFuture<List<RPKPaymentGroupOwner>> { val paymentGroupId = paymentGroup.id ?: return CompletableFuture.completedFuture(emptyList()) return CompletableFuture.supplyAsync { val results = database.create .select(RPKIT_PAYMENT_GROUP_OWNER.CHARACTER_ID) .from(RPKIT_PAYMENT_GROUP_OWNER) .where(RPKIT_PAYMENT_GROUP_OWNER.PAYMENT_GROUP_ID.eq(paymentGroupId.value)) .fetch() val characterService = Services[RPKCharacterService::class.java] ?: return@supplyAsync emptyList() return@supplyAsync results.mapNotNull { result -> val character = characterService.getCharacter(RPKCharacterId(result[RPKIT_PAYMENT_GROUP_OWNER.CHARACTER_ID])).join() ?: return@mapNotNull null return@mapNotNull RPKPaymentGroupOwner( paymentGroup, character ) } }.exceptionally { exception -> plugin.logger.log(Level.SEVERE, "Failed to get payment group owner", exception) throw exception } } fun delete(entity: RPKPaymentGroupOwner): CompletableFuture<Void> { val paymentGroupId = entity.paymentGroup.id ?: return CompletableFuture.completedFuture(null) val characterId = entity.character.id ?: return CompletableFuture.completedFuture(null) return CompletableFuture.runAsync { database.create .deleteFrom(RPKIT_PAYMENT_GROUP_OWNER) .where(RPKIT_PAYMENT_GROUP_OWNER.PAYMENT_GROUP_ID.eq(paymentGroupId.value)) .and(RPKIT_PAYMENT_GROUP_OWNER.CHARACTER_ID.eq(characterId.value)) .execute() }.exceptionally { exception -> plugin.logger.log(Level.SEVERE, "Failed to delete payment group owner", exception) throw exception } } fun delete(characterId: RPKCharacterId): CompletableFuture<Void> = runAsync { database.create .deleteFrom(RPKIT_PAYMENT_GROUP_OWNER) .where(RPKIT_PAYMENT_GROUP_OWNER.CHARACTER_ID.eq(characterId.value)) .execute() }.exceptionally { exception -> plugin.logger.log(SEVERE, "Failed to delete payment group owners for character id", exception) throw exception } }
apache-2.0
a359a574a32ad90b08385f54ed02c50f
42.419643
120
0.67174
4.90121
false
false
false
false
LorittaBot/Loritta
discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/cinnamon/discord/interactions/commands/CinnamonApplicationCommandDeclarations.kt
1
3727
package net.perfectdreams.loritta.cinnamon.discord.interactions.commands import dev.kord.common.Locale import dev.kord.common.entity.Permissions import net.perfectdreams.discordinteraktions.common.commands.* import net.perfectdreams.i18nhelper.core.keydata.StringI18nData import net.perfectdreams.loritta.common.locale.LanguageManager import net.perfectdreams.loritta.cinnamon.discord.utils.SlashTextUtils import net.perfectdreams.loritta.common.commands.CommandCategory class CinnamonSlashCommandDeclaration( val declarationWrapper: CinnamonSlashCommandDeclarationWrapper, val languageManager: LanguageManager, val nameI18n: StringI18nData, val descriptionI18n: StringI18nData, val category: CommandCategory, override val executor: SlashCommandExecutor?, override val defaultMemberPermissions: Permissions?, override val dmPermission: Boolean?, override val subcommands: List<SlashCommandDeclaration>, override val subcommandGroups: List<SlashCommandGroupDeclaration>, ) : SlashCommandDeclaration() { override val name = languageManager.defaultI18nContext.get(nameI18n) override val nameLocalizations: Map<Locale, String> = SlashTextUtils.createLocalizedStringMapExcludingDefaultLocale(languageManager, nameI18n) override val description = SlashTextUtils.buildDescription(languageManager.defaultI18nContext, descriptionI18n, category) override val descriptionLocalizations = SlashTextUtils.createShortenedLocalizedDescriptionMapExcludingDefaultLocale(languageManager, descriptionI18n, category) } class CinnamonSlashCommandGroupDeclaration( val languageManager: LanguageManager, val nameI18n: StringI18nData, val descriptionI18n: StringI18nData, val category: CommandCategory, override val subcommands: List<SlashCommandDeclaration> ) : SlashCommandGroupDeclaration() { override val name = languageManager.defaultI18nContext.get(nameI18n) override val nameLocalizations: Map<Locale, String> = SlashTextUtils.createLocalizedStringMapExcludingDefaultLocale(languageManager, nameI18n) override val description = SlashTextUtils.buildDescription(languageManager.defaultI18nContext, descriptionI18n, category) override val descriptionLocalizations = SlashTextUtils.createShortenedLocalizedDescriptionMapExcludingDefaultLocale(languageManager, descriptionI18n, category) } class CinnamonUserCommandDeclaration( val declarationWrapper: CinnamonUserCommandDeclarationWrapper, val languageManager: LanguageManager, val nameI18n: StringI18nData, override val defaultMemberPermissions: Permissions?, override val dmPermission: Boolean?, override val executor: UserCommandExecutor // User/Message commands always requires an executor, that's why it is not nullable! ) : UserCommandDeclaration() { override val name = SlashTextUtils.shorten(languageManager.defaultI18nContext.get(nameI18n)) override val nameLocalizations = SlashTextUtils.createShortenedLocalizedStringMapExcludingDefaultLocale(languageManager, nameI18n) } class CinnamonMessageCommandDeclaration( val declarationWrapper: CinnamonMessageCommandDeclarationWrapper, val languageManager: LanguageManager, val nameI18n: StringI18nData, override val defaultMemberPermissions: Permissions?, override val dmPermission: Boolean?, override val executor: MessageCommandExecutor // User/Message commands always requires an executor, that's why it is not nullable! ) : MessageCommandDeclaration() { override val name = SlashTextUtils.shorten(languageManager.defaultI18nContext.get(nameI18n)) override val nameLocalizations = SlashTextUtils.createShortenedLocalizedStringMapExcludingDefaultLocale(languageManager, nameI18n) }
agpl-3.0
31813ee9d3b62e46d5857c13c4cd3760
57.25
163
0.832841
5.02969
false
false
false
false
angcyo/RLibrary
uiview/src/main/java/com/angcyo/uiview/widget/RRatingBar.kt
1
7821
package com.angcyo.uiview.widget import android.content.Context import android.graphics.Canvas import android.graphics.RectF import android.graphics.drawable.Drawable import android.support.v4.view.MotionEventCompat import android.util.AttributeSet import android.view.MotionEvent import android.view.View import com.angcyo.uiview.R import com.angcyo.uiview.kotlin.* import kotlin.properties.ReadWriteProperty import kotlin.reflect.KProperty /** * 评分控件 * Created by angcyo on 2017/09/18 0018. */ class RRatingBar(context: Context, attributeSet: AttributeSet? = null) : View(context, attributeSet) { /*五角星 选中的 图案*/ var ratingSelectorDrawable by LayoutProperty(getDrawable(R.drawable.base_wujiaoxing_20)!!) /*五角星 未选中的 图案*/ var ratingNormalDrawable by LayoutProperty(getDrawable(R.drawable.base_wujiaoxing_20_n)!!) /**星星的数量*/ var ratingNum: Float by RefreshProperty(5f) /**当前评分 [0-ratingNum], 小于0, 表示没有*/ var curRating = 0f set(value) { field = value.maxValue(ratingNum.toFloat()) postInvalidate() } /**评分最小允许的值*/ var minRating = 0 /**星星之间的间隙*/ var ratingSpace: Float by RefreshProperty(8 * density) init { val typedArray = context.obtainStyledAttributes(attributeSet, R.styleable.RRatingBar) curRating = typedArray.getFloat(R.styleable.RRatingBar_r_cur_rating, curRating) ratingNum = typedArray.getInteger(R.styleable.RRatingBar_r_rating_count, ratingNum.toInt()).toFloat() minRating = typedArray.getInteger(R.styleable.RRatingBar_r_min_rating, minRating) val normalDrawable = typedArray.getDrawable(R.styleable.RRatingBar_r_normal_rating) val selectorDrawable = typedArray.getDrawable(R.styleable.RRatingBar_r_selected_rating) if (normalDrawable != null) { ratingNormalDrawable = normalDrawable } if (selectorDrawable != null) { ratingSelectorDrawable = selectorDrawable } ratingSpace = typedArray.getDimensionPixelOffset(R.styleable.RRatingBar_r_rating_space, ratingSpace.toInt()).toFloat() typedArray.recycle() } override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { //super.onMeasure(widthMeasureSpec, heightMeasureSpec) var widthSize = MeasureSpec.getSize(widthMeasureSpec) val widthMode = MeasureSpec.getMode(widthMeasureSpec) var heightSize = MeasureSpec.getSize(heightMeasureSpec) val heightMode = MeasureSpec.getMode(heightMeasureSpec) if (widthMode != MeasureSpec.EXACTLY && heightMode == MeasureSpec.EXACTLY) { widthSize = ((heightSize - paddingTop - paddingBottom) * ratingNum + (ratingSpace * (ratingNum - 1)).max0() + paddingLeft + paddingRight).toInt() } else { if (widthMode != MeasureSpec.EXACTLY) { //如果宽度模式不是 指定的定值. (自适应宽度) widthSize = (Math.max(ratingSelectorDrawable.intrinsicWidth, ratingNormalDrawable.intrinsicWidth) * ratingNum + (ratingSpace * (ratingNum - 1)).max0() + paddingLeft + paddingRight).toInt() } else { } if (heightMode != MeasureSpec.EXACTLY) { //和宽度类似 heightSize = Math.max(ratingSelectorDrawable.intrinsicHeight, ratingNormalDrawable.intrinsicHeight) + paddingTop + paddingBottom } } setMeasuredDimension(widthSize, heightSize) } /*有效的绘制大小*/ private val viewDrawSize: Int get() = measuredHeight - paddingTop - paddingBottom override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) { //固定星星的bound ratingNormalDrawable.setBounds(0, 0, viewDrawSize, viewDrawSize) ratingSelectorDrawable.setBounds(0, 0, viewDrawSize, viewDrawSize) } /*星星的宽度*/ val ratingWidth: Int get() { return ratingNormalDrawable.bounds.width() } private val progressClipRect by lazy { RectF() } override fun onDraw(canvas: Canvas) { //调用此方法, 不禁用view本身的功能, 比如:原本的background属性 super.onDraw(canvas) //绘制未选中星星 drawDrawable(canvas, ratingNormalDrawable) //计算进度 val floor = Math.floor(curRating.toDouble()).toFloat() var right = paddingLeft + ratingWidth * floor + ratingSpace * floor // if (floor.compareTo(curRating) != 0) { // //半星 // right += ratingWidth / 2 // } right += ratingWidth * (curRating - floor) progressClipRect.set(0f, 0f, right, measuredHeight.toFloat()) canvas.clipRect(progressClipRect) //绘制选中星星 drawDrawable(canvas, ratingSelectorDrawable) } private fun drawDrawable(canvas: Canvas, drawable: Drawable) { var left = paddingLeft for (i in 0 until ratingNum.toInt()) { canvas.save() canvas.translate(left + i * ratingWidth + i * ratingSpace, paddingTop.toFloat()) drawable.draw(canvas) canvas.restore() } } override fun onTouchEvent(event: MotionEvent): Boolean { if (!isEnabled) { return super.onTouchEvent(event) } val action = MotionEventCompat.getActionMasked(event) when (action) { MotionEvent.ACTION_DOWN -> { parent.requestDisallowInterceptTouchEvent(true) calcRating(event.x) } MotionEvent.ACTION_MOVE -> { calcRating(event.x) } MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> { parent.requestDisallowInterceptTouchEvent(false) } } return true } /*根据x的坐标, 计算星星的个数*/ private fun calcRating(x: Float) { var left = paddingLeft var index = 0f for (i in 0 until ratingNum.toInt()) { if (x > left + i * ratingWidth + i * ratingSpace) { index = i.toFloat() + 1f } else if (x > left + (i - 1).minValue(0) * ratingWidth + ratingWidth / 2 + i * ratingSpace) { index = i.toFloat() + 0.5f } } val oldValue = curRating val value: Float = index.minValue(minRating) if (value != curRating) { curRating = value postInvalidate() onRatingChangeListener?.onRatingChange(oldValue, value) } } var onRatingChangeListener: OnRatingChangeListener? = null public abstract class OnRatingChangeListener { open fun onRatingChange(from: Float, to: Float) { } } } /*定义一个自动刷新的属性代理*/ class RefreshProperty<T>(var value: T) : ReadWriteProperty<View, T> { override fun getValue(thisRef: View, property: KProperty<*>): T = value override fun setValue(thisRef: View, property: KProperty<*>, value: T) { this.value = value thisRef.postInvalidate() } } class LayoutProperty<T>(var value: T) : ReadWriteProperty<View, T> { override fun getValue(thisRef: View, property: KProperty<*>): T = value override fun setValue(thisRef: View, property: KProperty<*>, value: T) { this.value = value thisRef.requestLayout() } }
apache-2.0
394d42337d3144478739b036d74cc1f5
33.438679
144
0.612036
4.449645
false
false
false
false
vsch/SmartData
src/com/vladsch/smart/Helpers.kt
1
15130
/* * Copyright (c) 2015-2020 Vladimir Schneider <[email protected]> * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package com.vladsch.smart import java.io.UnsupportedEncodingException import java.net.URLDecoder import java.net.URLEncoder import java.util.* fun String?.ifNullOr(condition: Boolean, altValue: String): String { return if (this == null || condition) altValue else this } fun String?.ifNullOrNot(condition: Boolean, altValue: String): String { return if (this == null || !condition) altValue else this } inline fun String?.ifNullOr(condition: (String) -> Boolean, altValue: String): String { return if (this == null || condition(this)) altValue else this } inline fun String?.ifNullOrNot(condition: (String) -> Boolean, altValue: String): String { return if (this == null || !condition(this)) altValue else this } fun String?.ifNullOrEmpty(altValue: String): String { return if (this == null || this.isEmpty()) altValue else this } fun String?.ifNullOrBlank(altValue: String): String { return if (this == null || this.isBlank()) altValue else this } fun String?.wrapWith(prefixSuffix: Char): String { return wrapWith(prefixSuffix, prefixSuffix) } fun String?.wrapWith(prefix: Char, suffix: Char): String { return if (this == null || this.isEmpty()) "" else prefix + this + suffix } fun String?.wrapWith(prefixSuffix: String): String { return wrapWith(prefixSuffix, prefixSuffix) } fun String?.wrapWith(prefix: String, suffix: String): String { return if (this == null || this.isEmpty()) "" else prefix + this + suffix } fun String?.suffixWith(suffix: Char): String { return suffixWith(suffix, false) } fun String?.suffixWith(suffix: Char, ignoreCase: Boolean): String { if (this != null && !isEmpty() && !endsWith(suffix, ignoreCase)) return plus(suffix) return orEmpty() } fun String?.suffixWith(suffix: String): String { return suffixWith(suffix, false) } fun String?.suffixWith(suffix: String, ignoreCase: Boolean): String { if (this != null && !isEmpty() && suffix.isNotEmpty() && !endsWith(suffix, ignoreCase)) return plus(suffix) return orEmpty() } fun String?.prefixWith(prefix: Char): String { return prefixWith(prefix, false) } fun String?.prefixWith(prefix: Char, ignoreCase: Boolean): String { if (this != null && !isEmpty() && !startsWith(prefix, ignoreCase)) return prefix.plus(this) return orEmpty() } fun String?.prefixWith(prefix: String): String { return prefixWith(prefix, false) } fun String?.prefixWith(prefix: String, ignoreCase: Boolean): String { if (this != null && !isEmpty() && prefix.isNotEmpty() && !startsWith(prefix, ignoreCase)) return prefix.plus(this) return orEmpty() } fun String?.isIn(vararg list: String): Boolean { return this != null && this in list; } fun String?.endsWith(vararg needles: String): Boolean { return endsWith(false, *needles) } fun String?.endsWith(ignoreCase: Boolean, vararg needles: String): Boolean { if (this == null) return false for (needle in needles) { if (endsWith(needle, ignoreCase)) { return true } } return false } fun String?.startsWith(vararg needles: String): Boolean { return startsWith(false, *needles) } fun String?.startsWith(ignoreCase: Boolean, vararg needles: String): Boolean { if (this == null) return false for (needle in needles) { if (startsWith(needle, ignoreCase)) { return true } } return false } fun String?.startsWithNotEqual(vararg needles: String): Boolean { return startsWithNotEqual(false, *needles) } fun String?.startsWithNotEqual(ignoreCase: Boolean, vararg needles: String): Boolean { if (this == null) return false for (needle in needles) { if (startsWith(needle, ignoreCase)) { return !equals(needle, ignoreCase) } } return false } fun String?.count(char: Char, startIndex: Int = 0, endIndex: Int = Integer.MAX_VALUE): Int { if (this == null) return 0 var count = 0 var pos = startIndex val lastIndex = Math.min(length, endIndex) while (pos >= 0 && pos <= lastIndex) { pos = indexOf(char, pos) if (pos < 0) break count++ pos++ } return count } fun String?.count(char: String, startIndex: Int = 0, endIndex: Int = Integer.MAX_VALUE): Int { if (this == null) return 0 var count = 0 var pos = startIndex val lastIndex = Math.min(length, endIndex) while (pos >= 0 && pos <= lastIndex) { pos = indexOf(char, pos) if (pos < 0) break count++ pos++ } return count } fun String?.urlDecode(charSet: String? = null): String { try { return URLDecoder.decode(this, charSet ?: "UTF-8") } catch (e: UnsupportedEncodingException) { //e.printStackTrace() return orEmpty() } catch (e: IllegalArgumentException) { // e.printStackTrace() return orEmpty() } } fun String?.urlEncode(charSet: String? = null): String { try { return URLEncoder.encode(this, charSet ?: "UTF-8") } catch (e: UnsupportedEncodingException) { //e.printStackTrace() return orEmpty() } } fun String?.ifEmpty(arg: String): String { if (this != null && !this.isEmpty()) return this return arg } fun String?.ifEmpty(ifEmptyArg: String, ifNotEmptyArg: String): String { return if (this == null || this.isEmpty()) ifEmptyArg else ifNotEmptyArg } fun String?.ifEmptyNullArgs(ifEmptyArg: String?, ifNotEmptyArg: String?): String? { return if (this == null || this.isEmpty()) ifEmptyArg else ifNotEmptyArg } fun String?.ifEmpty(arg: () -> String): String { if (this != null && !this.isEmpty()) return this return arg() } fun String?.ifEmpty(ifEmptyArg: () -> String?, ifNotEmptyArg: () -> String?): String? { return if (this == null || this.isEmpty()) ifEmptyArg() else ifNotEmptyArg() } fun String?.removeStart(prefix: Char): String { if (this != null) { return removePrefix(prefix.toString()) } return "" } fun <T> Collection<T>.stringSorted(stringer: DataValueComputable<T, String>):List<T> { return this.sortedBy { stringer.compute(it) } } fun String?.removeStart(prefix: String): String { if (this != null) { return removePrefix(prefix) } return "" } fun String?.removeEnd(prefix: Char): String { if (this != null) { return removeSuffix(prefix.toString()) } return "" } fun String?.removeEnd(suffix: String): String { if (this != null) { return removeSuffix(suffix) } return "" } fun String?.regexGroup(): String { return "(?:" + this.orEmpty() + ")" } fun splicer(delimiter: String): (accum: String, elem: String) -> String { return { accum, elem -> accum + delimiter + elem } } fun skipEmptySplicer(delimiter: String): (accum: String, elem: String) -> String { return { accum, elem -> if (elem.isEmpty()) accum else accum + delimiter + elem } } fun StringBuilder.regionMatches(thisOffset: Int, other: String, otherOffset: Int, length: Int, ignoreCase: Boolean = false): Boolean { for (i in 0..length - 1) { if (!this.get(i + thisOffset).equals(other[i + otherOffset], ignoreCase)) return false } return true } fun StringBuilder.endsWith(suffix: String, ignoreCase: Boolean = false): Boolean { return this.length >= suffix.length && this.regionMatches(this.length - suffix.length, suffix, 0, suffix.length, ignoreCase) } fun StringBuilder.startsWith(prefix: String, ignoreCase: Boolean = false): Boolean { return this.length >= prefix.length && this.regionMatches(0, prefix, 0, prefix.length, ignoreCase) } fun Array<String>.splice(delimiter: String): String { val result = StringBuilder(this.size * (delimiter.length + 10)) var first = true; for (elem in this) { if (!elem.isEmpty()) { if (!first && !elem.startsWith(delimiter) && !result.endsWith(delimiter)) result.append(delimiter) else first = false result.append(elem.orEmpty()) } } return result.toString() } fun List<String?>.splice(delimiter: String, skipNullOrEmpty: Boolean = true): String { val result = StringBuilder(this.size * (delimiter.length + 10)) var first = true; for (elem in this) { if (elem != null && !elem.isEmpty() || !skipNullOrEmpty) { if (!first && (!skipNullOrEmpty || !elem.startsWith(delimiter) && !result.endsWith(delimiter))) result.append(delimiter) else first = false result.append(elem.orEmpty()) } } return result.toString() } fun Collection<String?>.splice(delimiter: String, skipNullOrEmpty: Boolean = true): String { val result = StringBuilder(this.size * (delimiter.length + 10)) var first = true; for (elem in this) { if (elem != null && !elem.isEmpty() || !skipNullOrEmpty) { if (!first && (!skipNullOrEmpty || !elem.startsWith(delimiter) && !result.endsWith(delimiter))) result.append(delimiter) else first = false result.append(elem.orEmpty()) } } return result.toString() } fun Iterator<String>.splice(delimiter: String, skipEmpty: Boolean = true): String { val result = StringBuilder(10 * (delimiter.length + 10)) var first = true; for (elem in this) { if (!elem.isEmpty() || !skipEmpty) { if (!first && (!skipEmpty || !elem.startsWith(delimiter) && !result.endsWith(delimiter))) result.append(delimiter) else first = false result.append(elem.orEmpty()) } } return result.toString() } fun String?.appendDelim(delimiter: String, vararg args: String): String { return arrayListOf<String?>(this.orEmpty(), *args).splice(delimiter, true) } fun <T : Any> Any?.ifNotNull(eval: () -> T?): T? = if (this == null) null else eval() fun <T : String?> T.nullIfEmpty(): T? = if (this != null && !this.isEmpty()) this else null fun <T : Any?> T.nullIf(nullIfValue: T): T? = if (this == null || this == nullIfValue) null else this fun <T : Any?> T.nullIf(nullIfValue: Boolean): T? = if (this == null || nullIfValue) null else this fun <T : Any?> Boolean.ifElseNull(ifTrue: T): T? = if (this) ifTrue else null fun <T : Any?> Boolean.ifElse(ifTrue: T, ifFalse: T): T = if (this) ifTrue else ifFalse inline fun <T : Any?> Boolean.ifElse(ifTrue: () -> T, ifFalse: () -> T): T = if (this) ifTrue() else ifFalse() inline fun <T : Any?> Boolean.ifElse(ifTrue: T, ifFalse: () -> T): T = if (this) ifTrue else ifFalse() inline fun <T : Any?> Boolean.ifElse(ifTrue: () -> T, ifFalse: T): T = if (this) ifTrue() else ifFalse operator fun <T : Any> StringBuilder.plusAssign(text: T): Unit { this.append(text) } fun repeatChar(char: Char, count: Int): String { var result = "" for (i in 1..count) { result += char } return result } fun Int.max(vararg others: Int): Int { var max = this; for (other in others) { if (max < other) max = other } return max; } fun Int.min(vararg others: Int): Int { var min = this; for (other in others) { if (min > other) min = other } return min; } fun Double.max(vararg others: Double): Double { var max = this; for (other in others) { if (max < other) max = other } return max; } fun Double.min(vararg others: Double): Double { var min = this; for (other in others) { if (min > other) min = other } return min; } fun Float.max(vararg others: Float): Float { var max = this; for (other in others) { if (max < other) max = other } return max; } fun Float.min(vararg others: Float): Float { var min = this; for (other in others) { if (min > other) min = other } return min; } @Suppress("NOTHING_TO_INLINE") fun Int.minLimit(minBound: Int): Int { return if (this < minBound) minBound else this } @Suppress("NOTHING_TO_INLINE") fun Int.maxLimit(maxBound: Int): Int { return if (this > maxBound) maxBound else this } @Suppress("NOTHING_TO_INLINE") fun Int.rangeLimit(minBound: Int, maxBound: Int): Int { return if (this < minBound) minBound else if (this > maxBound) maxBound else this } @Suppress("NOTHING_TO_INLINE") fun Long.minLimit(minBound: Long): Long { return if (this < minBound) minBound else this } @Suppress("NOTHING_TO_INLINE") fun Long.maxLimit(maxBound: Long): Long { return if (this > maxBound) maxBound else this } @Suppress("NOTHING_TO_INLINE") fun Long.rangeLimit(minBound: Long, maxBound: Long): Long { return if (this < minBound) minBound else if (this > maxBound) maxBound else this } @Suppress("NOTHING_TO_INLINE") fun Float.minLimit(minBound: Float): Float { return if (this < minBound) minBound else this } @Suppress("NOTHING_TO_INLINE") fun Float.maxLimit(maxBound: Float): Float { return if (this > maxBound) maxBound else this } @Suppress("NOTHING_TO_INLINE") fun Float.rangeLimit(minBound: Float, maxBound: Float): Float { return if (this < minBound) minBound else if (this > maxBound) maxBound else this } @Suppress("NOTHING_TO_INLINE") fun Double.minLimit(minBound: Double): Double { return if (this < minBound) minBound else this } @Suppress("NOTHING_TO_INLINE") fun Double.maxLimit(maxBound: Double): Double { return if (this > maxBound) maxBound else this } @Suppress("NOTHING_TO_INLINE") fun Double.rangeLimit(minBound: Double, maxBound: Double): Double { return if (this < minBound) minBound else if (this > maxBound) maxBound else this } fun <K : Any, V : Any> Map<K, V>.withDefaults(defaults: Map<K, V>): Map<K, V> { val map = HashMap(defaults) map.putAll(this) return map } fun <K : Any, V : Any> MutableMap<K, V>.putIfMissing(key: K, value: () -> V): V { val elem = this[key] return if (elem == null) { val v = value() this[key] = v v } else { elem } } fun <T : Any> MutableList<T>.add(vararg items:T) { for (item in items) { this.add(item) } } //fun <K : Any, V : Any> MutableMap<K, V>.putIfMissing(key: K, value: V): V { // val elem = this[key] // if (elem == null) { // this[key] = value // return value // } else { // return elem // } //}
apache-2.0
4d3af2086e6153efecf35dbf00388688
28.435798
134
0.646794
3.62482
false
false
false
false
kotlintest/kotlintest
kotest-assertions/src/commonMain/kotlin/io/kotest/matchers/doubles/LessThanOrEqual.kt
1
1468
package io.kotest.matchers.doubles import io.kotest.matchers.Matcher import io.kotest.matchers.MatcherResult import io.kotest.matchers.shouldBe import io.kotest.matchers.shouldNotBe /** * Asserts that this [Double] is less than or equal to [x] * * Verifies that this [Double] is less than or equal to [x]. This assertion includes [x] itself * * Opposite of [Double.shouldNotBeLessThanOrEqual] * * ``` * 0.1 shouldBeLessThanOrEqual 0.0 // Assertion fails * 0.1 shouldBeLessThanOrEqual 0.1 // Assertion passes * 0.1 shouldBeLessThanOrEqual 0.2 // Assertion passes * ``` * * @see [Double.shouldBeLessThan] * @see [Double.shouldNotBeGreaterThanOrEqual] */ infix fun Double.shouldBeLessThanOrEqual(x: Double) = this shouldBe lte(x) /** * Asserts that this [Double] is not less than [x] nor equal to [x] * * Opposite of [Double.shouldBeLessThanOrEqual] * * ``` * 0.1 shouldNotBeLessThanOrEqual 0.0 // Assertion passes * 0.1 shouldNotBeLessThanOrEqual 0.1 // Assertion fails * 0.1 shouldNotBeLessThanOrEqual 0.2 // Assertion fails * ``` * * @see [Double.shouldNotBeLessThan] * @see [Double.shouldBeGreaterThanOrEqual] */ infix fun Double.shouldNotBeLessThanOrEqual(x: Double) = this shouldNotBe lte(x) fun lte(x: Double) = beLessThanOrEqualTo(x) fun beLessThanOrEqualTo(x: Double) = object : Matcher<Double> { override fun test(value: Double) = MatcherResult(value <= x, "$value should be <= $x", "$value should not be <= $x") }
apache-2.0
96983b0b089005933e12e65dd6419d0b
31.622222
118
0.723433
3.773779
false
true
false
false
softwareberg/rinca
httpclient/src/test/kotlin/com/softwareberg/HttpClientSpec.kt
1
2545
package com.softwareberg import com.softwareberg.HttpMethod.GET import com.softwareberg.HttpMethod.POST import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.AfterAll import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import org.mockserver.integration.ClientAndServer.startClientAndServer import org.mockserver.model.HttpRequest.request import org.mockserver.model.HttpResponse.response class HttpClientSpec { companion object { val httpClient = SimpleHttpClient.create() private val mockServerClient = startClientAndServer(1080) @AfterAll @JvmStatic fun `it should close http client`() { httpClient.close() } } @Test fun `it should do GET request`() { // given mockServerClient.`when`(request().withMethod("GET").withPath("/get")).respond(response().withStatusCode(200).withBody("OK")) // when val (statusCode, _, body) = httpClient.execute(HttpRequest(GET, "http://localhost:1080/get")).join() // then assertThat(statusCode).isEqualTo(200) assertThat(body).isEqualTo("OK") } @Test fun `it should do GET request with headers`() { // given mockServerClient.`when`(request().withMethod("GET").withPath("/get").withHeader("Accept", "text/plain").withHeader("Accept-Charset", "utf-8")).respond(response().withStatusCode(200).withHeader("Content-Type", "text/plain; utf-8").withBody("OK")) // when val (statusCode, headers, body) = httpClient.execute(HttpRequest(GET, "http://localhost:1080/get", listOf(HttpHeader("Accept", "text/plain"), HttpHeader("Accept-Charset", "utf-8")))).join() // then assertThat(statusCode).isEqualTo(200) assertThat(body).isEqualTo("OK") assertThat(headers).contains(HttpHeader("Content-Type", "text/plain; utf-8")) } @Test fun `it should do POST request`() { // given mockServerClient.`when`(request().withMethod("POST").withPath("/post").withBody("request")).respond(response().withStatusCode(201).withBody("created")) val httpClient = SimpleHttpClient.create() // when val (statusCode, _, body) = httpClient.execute(HttpRequest(POST, "http://localhost:1080/post", emptyList(), "request")).join() // then assertThat(statusCode).isEqualTo(201) assertThat(body).isEqualTo("created") } @BeforeEach fun resetBeforeTest() { mockServerClient.reset() } }
isc
6bc3a8b06b81797b8e7437cba4b43888
34.84507
253
0.665226
4.395509
false
true
false
false
cuebyte/rendition
src/main/kotlin/moe/cuebyte/rendition/util/RedisUtils.kt
1
458
package moe.cuebyte.rendition.util import moe.cuebyte.rendition.Column import moe.cuebyte.rendition.Model internal fun genId(m: Model, v: String): String = "${m.name}:$v" internal fun genKey(m: Model, c: Column) = "${m.name}:${c.name}" internal fun genKey(m: Model, c: Column, v: String) = "${m.name}:${c.name}:$v" internal fun genKey(m: Model, name: String) = "${m.name}:$name" internal fun genKey(m: Model, name: String, v: String) = "${m.name}:$name:$v"
lgpl-3.0
686f13cffcbe4cbbe2fa6938b21c82ea
44.9
78
0.681223
2.954839
false
false
false
false
epabst/kotlin-showcase
src/jsMain/kotlin/bootstrap/Toast.kt
1
932
@file:Suppress("INTERFACE_WITH_SUPERCLASS", "OVERRIDING_FINAL_MEMBER", "RETURN_TYPE_MISMATCH_ON_OVERRIDE", "CONFLICTING_OVERLOADS", "EXTERNAL_DELEGATION", "unused") @file:JsModule("react-bootstrap") package bootstrap import react.RProps external interface ToastProps : RProps { var animation: Boolean? get() = definedExternally; set(value) = definedExternally var autohide: Boolean? get() = definedExternally; set(value) = definedExternally var delay: Number? get() = definedExternally; set(value) = definedExternally var onClose: (() -> Unit)? get() = definedExternally; set(value) = definedExternally var show: Boolean? get() = definedExternally; set(value) = definedExternally var transition: dynamic /* Boolean | React.ElementType */ } abstract external class Toast : BsPrefixComponent<React.String /* 'div' */, ToastProps> { companion object { var Body: Any var Header: Any } }
apache-2.0
96206a0aff4971eeba612221d8337444
45.65
164
0.719957
4.375587
false
false
false
false
Zhuinden/simple-stack
samples/advanced-samples/extensions-compose-example/src/main/java/com/zhuinden/simplestackextensionscomposesample/features/registration/RegistrationViewModel.kt
1
3093
package com.zhuinden.simplestackextensionscomposesample.features.registration import com.jakewharton.rxrelay2.BehaviorRelay import com.zhuinden.rxvalidatebykt.validateBy import com.zhuinden.simplestack.* import com.zhuinden.simplestackextensionscomposesample.app.AuthenticationManager import com.zhuinden.simplestackextensionscomposesample.features.profile.ProfileKey import com.zhuinden.simplestackextensionscomposesample.utils.get import com.zhuinden.simplestackextensionscomposesample.utils.set import com.zhuinden.statebundle.StateBundle import io.reactivex.Observable import io.reactivex.disposables.CompositeDisposable import io.reactivex.rxkotlin.addTo import io.reactivex.rxkotlin.subscribeBy class RegistrationViewModel( private val authenticationManager: AuthenticationManager, private val backstack: Backstack ) : Bundleable, ScopedServices.Registered { private val compositeDisposable = CompositeDisposable() val fullName = BehaviorRelay.createDefault("") val bio = BehaviorRelay.createDefault("") val username = BehaviorRelay.createDefault("") val password = BehaviorRelay.createDefault("") private val isRegisterAndLoginEnabledRelay = BehaviorRelay.createDefault(false) val isRegisterAndLoginEnabled: Observable<Boolean> = isRegisterAndLoginEnabledRelay private val isEnterProfileNextEnabledRelay = BehaviorRelay.createDefault(false) val isEnterProfileNextEnabled: Observable<Boolean> = isEnterProfileNextEnabledRelay override fun onServiceRegistered() { validateBy( fullName.map { it.isNotBlank() }, bio.map { it.isNotBlank() } ).subscribeBy { isEnabled -> isEnterProfileNextEnabledRelay.set(isEnabled) }.addTo(compositeDisposable) validateBy( username.map { it.isNotBlank() }, password.map { it.isNotBlank() } ).subscribeBy { isEnabled -> isRegisterAndLoginEnabledRelay.set(isEnabled) }.addTo(compositeDisposable) } override fun onServiceUnregistered() { compositeDisposable.clear() } fun onRegisterAndLoginClicked() { if (isRegisterAndLoginEnabledRelay.get()) { val username = username.get() authenticationManager.saveRegistration(username) backstack.setHistory(History.of(ProfileKey(username)), StateChange.REPLACE) } } fun onEnterProfileNextClicked() { if (isEnterProfileNextEnabledRelay.get()) { backstack.goTo(CreateLoginCredentialsKey) } } override fun toBundle(): StateBundle = StateBundle().apply { putString("username", username.get()) putString("password", password.get()) putString("fullName", fullName.get()) putString("bio", bio.get()) } override fun fromBundle(bundle: StateBundle?) { bundle?.run { username.set(getString("username", "")) password.set(getString("password", "")) fullName.set(getString("fullName", "")) bio.set(getString("bio", "")) } } }
apache-2.0
44b7b2c7494d5e0c19f7067bdddc78d3
36.277108
87
0.714517
5.287179
false
false
false
false
josesamuel/remoter
remoter/src/main/java/remoter/compiler/kbuilder/KBindingManager.kt
1
11813
package remoter.compiler.kbuilder import com.squareup.kotlinpoet.* import remoter.annotations.Remoter import java.io.File import javax.annotation.processing.Messager import javax.annotation.processing.ProcessingEnvironment import javax.lang.model.element.Element import javax.lang.model.element.ElementKind import javax.lang.model.element.TypeElement import javax.lang.model.type.* import javax.lang.model.util.Elements import javax.lang.model.util.SimpleTypeVisitor6 /** * Manages kotlin file generation */ open class KBindingManager(private val processingEnvironment: ProcessingEnvironment) { companion object { const val KAPT_KOTLIN_GENERATED_OPTION_NAME = "kapt.kotlin.generated" const val PARCELER_ANNOTATION = "org.parceler.Parcel" } private val elementUtils: Elements = processingEnvironment.elementUtils private var typeUtils = processingEnvironment.typeUtils private var typeBuilderMap: MutableMap<TypeMirror, ParamBuilder> = mutableMapOf() private var stringTypeMirror: TypeMirror? = null private var charSequenceTypeMirror: TypeMirror? = null private var listTypeMirror: TypeMirror? = null private var setTypeMirror: TypeMirror? = null private var mapTypeMirror: TypeMirror? = null private var parcellableTypeMirror: TypeMirror? = null private var parcelClass: Class<*>? = null private var remoterBuilderClass: Class<*>? = null private val javaByeType = ClassName("java.lang", "Byte") private val javaBooleanType = ClassName("java.lang", "Boolean") private val javaIntegerType = ClassName("java.lang", "Integer") private val javaShortType = ClassName("java.lang", "Short") private val javaLongType = ClassName("java.lang", "Long") private val javaFloatType = ClassName("java.lang", "Float") private val javaDoubleType = ClassName("java.lang", "Double") private val javaCharType = ClassName("java.lang", "Character") init { stringTypeMirror = getType("java.lang.String") listTypeMirror = getType("java.util.List") setTypeMirror = getType("java.util.Set") mapTypeMirror = getType("java.util.Map") charSequenceTypeMirror = getType("java.lang.CharSequence") parcellableTypeMirror = getType("android.os.Parcelable") try { parcelClass = Class.forName("org.parceler.Parcel") } catch (ignored: ClassNotFoundException) { } try { remoterBuilderClass = Class.forName("remoter.builder.ServiceConnector") } catch (ignored: ClassNotFoundException) { } } /** * Returns a [TypeMirror] for the given class */ fun getType(className: String?): TypeMirror { return elementUtils.getTypeElement(className).asType() } /** * Returns a [Element] for the given class */ fun getElement(className: String): Element { var cName = className val templateStart = className.indexOf('<') if (templateStart != -1) { cName = className.substring(0, templateStart).trim() } return elementUtils.getTypeElement(cName) } /** * Generates the abstract publisher class */ fun generateProxy(element: Element) { val kaptKotlinGeneratedDir = processingEnvironment.options[KAPT_KOTLIN_GENERATED_OPTION_NAME]?.replace("kaptKotlin", "kapt") kaptKotlinGeneratedDir?.let { KClassBuilder(element, this).generateProxy().writeTo(File(kaptKotlinGeneratedDir)) } } /** * Generates the abstract publisher class */ fun generateStub(element: Element) { val kaptKotlinGeneratedDir = processingEnvironment.options[KAPT_KOTLIN_GENERATED_OPTION_NAME]?.replace("kaptKotlin", "kapt") kaptKotlinGeneratedDir?.let { KClassBuilder(element, this).generateStub().writeTo(File(kaptKotlinGeneratedDir)) } } fun getMessager(): Messager = processingEnvironment.messager fun hasRemoterBuilder() = remoterBuilderClass != null /** * Returns the [KFieldBuilder] that adds fields to the class spec */ internal fun getFieldBuilder(element: Element) = KFieldBuilder(element, this) internal fun getFunctiondBuilder(element: Element) = KMethodBuilder(element, this) /** * Returns the [ParamBuilder] that knows how to generate code for the given type of parameter */ internal open fun getBuilderForParam(remoteElement: Element, typeMirror: TypeMirror): ParamBuilder { val typeName = typeMirror.asTypeName() var typeElementType: Element? = null if (typeMirror is DeclaredType) { typeElementType = typeMirror.asElement() } var paramBuilder: ParamBuilder? = typeBuilderMap[typeMirror] if (paramBuilder == null) { when (typeMirror.kind) { TypeKind.BOOLEAN -> paramBuilder = BooleanParamBuilder(remoteElement, this) TypeKind.BYTE -> paramBuilder = ByteParamBuilder(remoteElement, this) TypeKind.CHAR -> paramBuilder = CharParamBuilder(remoteElement, this) TypeKind.DOUBLE -> paramBuilder = DoubleParamBuilder(remoteElement, this) TypeKind.FLOAT -> paramBuilder = FloatParamBuilder(remoteElement, this) TypeKind.INT -> paramBuilder = IntParamBuilder(remoteElement, this) TypeKind.LONG -> paramBuilder = LongParamBuilder(remoteElement, this) TypeKind.SHORT -> paramBuilder = ShortParamBuilder(remoteElement, this) TypeKind.ARRAY -> paramBuilder = getBuilderForParam(remoteElement, (typeMirror as ArrayType).componentType) TypeKind.DECLARED -> { when (typeName) { javaIntegerType -> paramBuilder = IntParamBuilder(remoteElement, this) javaByeType -> paramBuilder = ByteParamBuilder(remoteElement, this) javaBooleanType -> paramBuilder = BooleanParamBuilder(remoteElement, this) javaCharType -> paramBuilder = CharParamBuilder(remoteElement, this) javaDoubleType -> paramBuilder = DoubleParamBuilder(remoteElement, this) javaFloatType -> paramBuilder = FloatParamBuilder(remoteElement, this) javaLongType -> paramBuilder = LongParamBuilder(remoteElement, this) javaShortType -> paramBuilder = ShortParamBuilder(remoteElement, this) else -> { val baseElementName = typeElementType?.simpleName?.toString() val genericList: TypeElement? = getGenericType(typeMirror) if (genericList != null) { paramBuilder = ListOfParcelerParamBuilder(genericList, remoteElement, this) } else if (typeUtils.isAssignable(typeMirror, stringTypeMirror) || typeName == STRING || baseElementName == "String") { paramBuilder = StringParamBuilder(remoteElement, this) } else if (typeUtils.isAssignable(typeMirror, charSequenceTypeMirror) || typeName == CHAR_SEQUENCE || baseElementName == "CharSequence") { paramBuilder = CharSequenceParamBuilder(remoteElement, this) } else if (typeUtils.isAssignable(typeMirror, listTypeMirror) || typeMirror.toString() == "java.util.List<java.lang.String>" || typeName == MUTABLE_LIST || baseElementName == "List") { paramBuilder = ListParamBuilder(remoteElement, this) } else if (typeUtils.isAssignable(typeMirror, mapTypeMirror) || typeName == MUTABLE_MAP || baseElementName == "Map") { paramBuilder = MapParamBuilder(remoteElement, this) } else if (typeUtils.isAssignable(typeMirror, parcellableTypeMirror)) { paramBuilder = ParcellableParamBuilder(remoteElement, this) } else { val elementName = (typeMirror as DeclaredType).asElement().toString() val typeElement: TypeElement? = elementUtils.getTypeElement(elementName) if (typeElement != null) { if (typeElement.kind == ElementKind.INTERFACE && typeElement.getAnnotation(Remoter::class.java) != null) { paramBuilder = BinderParamBuilder(remoteElement, this) } else if (parcelClass != null && (typeElement.annotationMirrors.any { it.annotationType.toString() == PARCELER_ANNOTATION })) { paramBuilder = ParcelerParamBuilder(remoteElement, this) } } } } } } else -> { } } if (paramBuilder != null) { typeBuilderMap[typeMirror] = paramBuilder } else { paramBuilder = GenericParamBuilder(remoteElement, this) typeBuilderMap[typeMirror] = paramBuilder } } return paramBuilder } /** * Return the generic type if any */ private fun getGenericType(typeMirror: TypeMirror?): TypeElement? { return typeMirror?.accept(object : SimpleTypeVisitor6<TypeElement?, Void>() { override fun visitDeclared(declaredType: DeclaredType?, v: Void?): TypeElement? { var genericTypeElement: TypeElement? = null var typeElement = declaredType?.asElement() as TypeElement? if (parcelClass != null && typeElement != null && typeUtils.isAssignable(typeElement.asType(), listTypeMirror)) { val typeArguments = declaredType?.typeArguments if (typeArguments != null && typeArguments.isNotEmpty()) { for (genericType in typeArguments) { if (genericType is WildcardType) { val extendsType = genericType.extendsBound if (extendsType != null) { typeElement = elementUtils.getTypeElement(extendsType.toString()) if (typeElement.annotationMirrors.any { it.annotationType.toString() == PARCELER_ANNOTATION }) { genericTypeElement = typeElement break } } } else { typeElement = elementUtils.getTypeElement(genericType.toString()) if (typeElement.annotationMirrors.any { it.annotationType.toString() == PARCELER_ANNOTATION }) { genericTypeElement = typeElement break } } } } } return genericTypeElement } }, null) } }
apache-2.0
2bebe7cdda207563df251781dd697e6e
46.613169
166
0.578515
5.693012
false
false
false
false
yyued/CodeX-UIKit-Android
library/src/main/java/com/yy/codex/uikit/UIProgressView.kt
1
4073
package com.yy.codex.uikit import android.content.Context import android.os.Build import android.support.annotation.RequiresApi import android.util.AttributeSet import android.view.View import com.yy.codex.foundation.lets /** * Created by adi on 17/2/6. */ class UIProgressView : UIControl { /* initialize */ constructor(context: Context, view: View) : super(context, view) {} constructor(context: Context) : super(context) {} constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {} constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {} @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int, defStyleRes: Int) : super(context, attrs, defStyleAttr, defStyleRes) { } override fun init() { super.init() trackView = UIView(context) trackView.wantsLayer = true trackView.layer.backgroundColor = UIColor(0xb7 / 255.0, 0xb7 / 255.0, 0xb7 / 255.0, 1.0) trackView.layer.cornerRadius = 1.0 addSubview(trackView) progressView = UIView(context) progressView.wantsLayer = true progressView.layer.backgroundColor = tintColor progressView.layer.cornerRadius = 1.0 addSubview(progressView) } override fun intrinsicContentSize(): CGSize { return CGSize(0.0, 2.0) } override fun prepareProps(attrs: AttributeSet) { super.prepareProps(attrs) val typedArray = context.theme.obtainStyledAttributes(attrs, R.styleable.UIProgressView, 0, 0) typedArray.getFloat(R.styleable.UIProgressView_progressview_value, 0.0f)?.let { initializeAttributes.put("UIProgressView.value", it) } typedArray.getColor(R.styleable.UIProgressView_progressview_trackColor, -1)?.let { if (it != -1) { initializeAttributes.put("UIProgressView.trackColor", UIColor(it)) } } } override fun resetProps() { super.resetProps() initializeAttributes?.let { (it["UIProgressView.value"] as? Float)?.let { value = it.toDouble() } (it["UIProgressView.trackColor"] as? UIColor)?.let { trackColor = it } } } /* appearance */ private lateinit var progressView: UIView private lateinit var trackView: UIView var value: Double = 0.5 private set(value) { if (field == value){ return } else if (value < 0.0){ field = 0.0 } else if (value > 1.0){ field = 1.0 } else { field = value } onEvent(Event.ValueChanged) } var trackColor: UIColor = UIColor(0xb7 / 255.0, 0xb7 / 255.0, 0xb7 / 255.0, 1.0) set(value) { field = value trackView.layer.backgroundColor = value } private var currentAnimation: UIViewAnimation? = null override fun layoutSubviews() { super.layoutSubviews() trackView.frame = CGRect(0.0, 0.0, frame.size.width, 2.0) progressView.frame = CGRect(0.0, 0.0, frame.size.width * value, 2.0) } override fun tintColorDidChanged() { super.tintColorDidChanged() lets(progressView, tintColor, { progressView, tintColor -> progressView.layer.backgroundColor = tintColor }) } /* support */ fun setValue(value: Double, animated: Boolean){ this.value = value currentAnimation?.let(UIViewAnimation::cancel) if (animated) { currentAnimation = UIViewAnimator.springWithBounciness(1.0, 20.0, Runnable { progressView.frame = CGRect(0.0, 0.0, frame.size.width * value, 2.0) }, Runnable { }) } else { progressView.frame = CGRect(0.0, 0.0, frame.size.width * value, 2.0) } } }
gpl-3.0
8fbb81f89acc0a08ab1871bca863291f
29.863636
144
0.600049
4.238293
false
false
false
false
charlesmadere/smash-ranks-android
smash-ranks-android/app/src/test/java/com/garpr/android/data/database/ListOfSmashCharacterConverterTest.kt
1
3055
package com.garpr.android.data.database import com.garpr.android.data.models.SmashCharacter import com.garpr.android.test.BaseTest import com.squareup.moshi.JsonAdapter import com.squareup.moshi.Moshi import com.squareup.moshi.Types import org.junit.Assert.assertEquals import org.junit.Assert.assertFalse import org.junit.Assert.assertNull import org.junit.Before import org.junit.Test import org.koin.test.inject class ListOfSmashCharacterConverterTest : BaseTest() { private lateinit var jsonAdapter: JsonAdapter<List<SmashCharacter?>?> private val converter = ListOfSmashCharacterConverter() protected val moshi: Moshi by inject() @Before override fun setUp() { super.setUp() jsonAdapter = moshi.adapter(Types.newParameterizedType(List::class.java, SmashCharacter::class.java)) } @Test fun testListOfSmashCharacterFromStringWithDualMain() { val list = converter.listOfSmashCharacterFromString(DUAL_MAIN_JSON) assertEquals(2, list?.size) assertEquals(true, list?.contains(SmashCharacter.ICE_CLIMBERS)) assertEquals(true, list?.contains(SmashCharacter.JIGGLYPUFF)) } @Test fun testListOfSmashCharacterFromStringWithEmptyString() { assertNull(converter.listOfSmashCharacterFromString("")) } @Test fun testListOfSmashCharacterFromStringWithNull() { assertNull(converter.listOfSmashCharacterFromString(null)) } @Test fun testListOfSmashCharacterFromStringWithSoloMain() { val list = converter.listOfSmashCharacterFromString(SOLO_MAIN_JSON) assertEquals(1, list?.size) assertEquals(true, list?.contains(SmashCharacter.CPTN_FALCON)) } @Test fun testStringFromListOfSmashCharacterWithDualMain() { val string = converter.stringFromListOfSmashCharacter(DUAL_MAIN) assertFalse(string.isNullOrBlank()) val list = jsonAdapter.fromJson(string!!) assertEquals(2, list?.size) assertEquals(true, list?.contains(SmashCharacter.FALCO)) assertEquals(true, list?.contains(SmashCharacter.FOX)) } @Test fun testStringFromListOfSmashCharacterWithEmptyList() { assertNull(converter.stringFromListOfSmashCharacter(emptyList())) } @Test fun testStringFromListOfSmashCharacterWithNull() { assertNull(converter.stringFromListOfSmashCharacter(null)) } @Test fun testStringFromListOfSmashCharacterWithSoloMain() { val string = converter.stringFromListOfSmashCharacter(SOLO_MAIN) assertFalse(string.isNullOrBlank()) val list = jsonAdapter.fromJson(string!!) assertEquals(1, list?.size) assertEquals(true, list?.contains(SmashCharacter.SHEIK)) } companion object { private val DUAL_MAIN = listOf(SmashCharacter.FOX, SmashCharacter.FALCO) private val SOLO_MAIN = listOf(SmashCharacter.SHEIK) private const val DUAL_MAIN_JSON = "[\"ics\",\"puf\"]" private const val SOLO_MAIN_JSON = "[\"fcn\"]" } }
unlicense
f90f3d268fa64c1cb5d107fb446b2989
31.5
80
0.719149
4.587087
false
true
false
false
maxirosson/jdroid-gradle-plugin
buildSrc/src/main/kotlin/Libs.kt
1
1844
object Libs { // https://github.com/maxirosson/jdroid-java/blob/master/CHANGELOG.md const val JDROID_JAVA_CORE = "com.jdroidtools:jdroid-java-core:3.1.0" // https://plugins.gradle.org/plugin/com.gradle.plugin-publish const val GRADLE_PLUGIN_PUBLISH_PLUGIN = "com.gradle.publish:plugin-publish-plugin:0.16.0" // https://developer.android.com/tools/revisions/gradle-plugin.html // https://dl.google.com/dl/android/maven2/index.html const val ANDROID_GRADLE_PLUGIN = "com.android.tools.build:gradle:7.0.2" // https://firebase.google.com/docs/perf-mon/get-started-android#add-performance-monitoringto-your-app // https://jcenter.bintray.com/com/google/firebase/perf-plugin/ const val FIREBASE_PERFORMANCE_PLUGIN = "com.google.firebase:perf-plugin:1.3.4" // https://developers.google.com/android/guides/google-services-plugin // https://jcenter.bintray.com/com/google/gms/google-services/ const val GOOGLE_SERVICES_PLUGIN = "com.google.gms:google-services:4.3.5" // https://firebase.google.com/support/release-notes/android const val FIREBASE_CRASHLYTICS_GRADLE_PLUGIN = "com.google.firebase:firebase-crashlytics-gradle:2.5.0" // https://github.com/konifar/gradle-unused-resources-remover-plugin/releases const val UNUSED_RESOURCES_REMOVER_PLUGIN = "gradle.plugin.com.github.konifar.gradle:plugin:0.3.3" // https://github.com/Codearte/gradle-nexus-staging-plugin/ const val GRADLE_NEXUS_STAGING_PLUGIN = "io.codearte.gradle.nexus:gradle-nexus-staging-plugin:0.30.0" // https://github.com/Kotlin/dokka/releases const val DOKKA_PLUGIN = "org.jetbrains.dokka:dokka-gradle-plugin:1.5.0" // https://github.com/gretty-gradle-plugin/gretty/blob/master/changes.md const val GRETTY = "org.gretty:gretty:3.0.3" const val JUNIT = "junit:junit:4.13.2" }
apache-2.0
111b9a53fbfa092f3caa8512af28d174
48.837838
106
0.733189
3.120135
false
false
false
false
pabiagioli/gopro-showcase
app/src/main/java/com/aajtech/mobile/goproshowcase/GoProStatusDTOFragment.kt
1
6189
package com.aajtech.mobile.goproshowcase import android.Manifest import android.content.Context import android.content.pm.PackageManager import android.os.Bundle import android.support.v4.app.ActivityCompat import android.support.v4.app.Fragment import android.support.v7.widget.GridLayoutManager import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.RecyclerView import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.aajtech.mobile.goproshowcase.GoProStatusDTOFragment.OnListFragmentInteractionListener import com.aajtech.mobile.goproshowcase.dto.GoProStatusDTO import com.aajtech.mobile.goproshowcase.dto.buildViewHolderData import com.aajtech.mobile.goproshowcase.service.GoProInfoService import com.aajtech.mobile.goproshowcase.service.retrofit import com.aajtech.mobile.goproshowcase.service.sendWoL import java.net.SocketTimeoutException import kotlin.concurrent.thread /** * A fragment representing a list of Items. * * * Activities containing this fragment MUST implement the [OnListFragmentInteractionListener] * interface. */ class GoProStatusDTOFragment : Fragment() { // TODO: Customize parameters private var mColumnCount = 1 private var mListener: OnListFragmentInteractionListener? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) if (arguments != null) { mColumnCount = arguments.getInt(ARG_COLUMN_COUNT) } } override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? { val view = inflater!!.inflate(R.layout.fragment_goprostatusdto_list, container, false) // Set the adapter if (view is RecyclerView) { val context = view.getContext() if (mColumnCount <= 1) { view.layoutManager = LinearLayoutManager(context) } else { view.layoutManager = GridLayoutManager(context, mColumnCount) } val statusList = emptyList<GoProStatusDTO>().toMutableList() view.adapter = MyGoProStatusDTORecyclerViewAdapter(statusList, mListener) val statusService = retrofit.create(GoProInfoService::class.java) thread { if (ActivityCompat.checkSelfPermission([email protected], Manifest.permission.INTERNET) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission([email protected], Manifest.permission.INTERNET) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions([email protected], arrayOf(Manifest.permission.INTERNET), 200) return@thread } sendWoL() Log.d(this.tag, "before WoL") Log.d(this.tag, "before WS") try { var retryCount = 1 val totalRetries = 4 var response = statusService.status().execute() //I may have to retry the request a couple of times until the camera is fully initialized if (response.code() == 500) { do { println("First attempt failed!\nAttempting retry #$retryCount") response = statusService.status().execute() retryCount++ } while (response.code() != 200 && (retryCount < totalRetries)) } Log.d([email protected], "after WS") if (response != null && response.isSuccessful) { Log.d([email protected], "successful WS") [email protected] { statusList.addAll(response.body().buildViewHolderData()) view.adapter.notifyDataSetChanged() } } statusService.powerOff() Log.d([email protected], "successful powerOff") } catch (ste: SocketTimeoutException) { ste.printStackTrace() } finally { } } } return view } override fun onAttach(context: Context?) { super.onAttach(context) if (context is OnListFragmentInteractionListener) { mListener = context as OnListFragmentInteractionListener? } else { throw RuntimeException(context!!.toString() + " must implement OnListFragmentInteractionListener") } } override fun onDetach() { super.onDetach() mListener = null } /** * This interface must be implemented by activities that contain this * fragment to allow an interaction in this fragment to be communicated * to the activity and potentially other fragments contained in that * activity. * * * See the Android Training lesson [Communicating with Other Fragments](http://developer.android.com/training/basics/fragments/communicating.html) for more information. */ interface OnListFragmentInteractionListener { // TODO: Update argument type and name fun onListFragmentInteraction(item: GoProStatusDTO) } companion object { // TODO: Customize parameter argument names private val ARG_COLUMN_COUNT = "column-count" // TODO: Customize parameter initialization @SuppressWarnings("unused") fun newInstance(columnCount: Int): GoProStatusDTOFragment { val fragment = GoProStatusDTOFragment() val args = Bundle() args.putInt(ARG_COLUMN_COUNT, columnCount) fragment.arguments = args return fragment } } } /** * Mandatory empty constructor for the fragment manager to instantiate the * fragment (e.g. upon screen orientation changes). */
gpl-3.0
63228f3308ab61fce23ebd44818513b9
39.717105
172
0.641461
5.170426
false
false
false
false
RettyEng/redux-kt
redux-kt-core/src/main/kotlin/me/retty/reduxkt/internal/utils/Function.kt
1
1023
package me.retty.reduxkt.internal.utils /** * Created by yusaka on 3/15/17. */ internal infix fun <T, U, V> ((U) -> V).comp(g: (T) -> U): (T) -> V = { arg -> this(g(arg)) } internal infix fun <A1, A2, R> ((A1, A2) -> R).curry(a1: A1): (A2) -> R = { a2 -> this(a1, a2) } internal infix fun <A1, A2, A3, R> ((A1, A2, A3) -> R).curry(a1: A1): (A2, A3) -> R = { a2, a3 -> this(a1, a2, a3) } internal infix fun <A1, A2, A3, A4, R> ((A1, A2, A3, A4) -> R).curry(a1: A1): (A2, A3, A4) -> R = { a2, a3, a4 -> this(a1, a2, a3, a4) } internal infix fun <A1, A2, A3, A4, A5, R> ((A1, A2, A3, A4, A5) -> R).curry(a1: A1): (A2, A3, A4, A5) -> R = { a2, a3, a4, a5 -> this(a1, a2, a3, a4, a5) } internal infix fun <A1, A2, A3, A4, A5, A6, R> ((A1, A2, A3, A4, A5, A6) -> R).curry(a1: A1): (A2, A3, A4, A5, A6) -> R = { a2, a3, a4, a5, a6 -> this(a1, a2, a3, a4, a5, a6) }
mit
183f33f83fef4ad2b22d61b4c210cb95
30.96875
97
0.427175
2.0501
false
false
false
false
laurencegw/jenjin
jenjin-core/src/main/kotlin/com/binarymonks/jj/core/components/input/Draggable.kt
1
959
package com.binarymonks.jj.core.components.input import com.binarymonks.jj.core.pools.recycle import com.binarymonks.jj.core.pools.vec2 class Draggable : TouchHandler() { var velocityScale: Float = 50f private var touched = false override fun onTouchDown(touchX: Float, touchY: Float, button: Int): Boolean { if (!touched) { touched = true return true } return false } override fun onTouchMove(touchX: Float, touchY: Float, button: Int) { val currentPosition = me().physicsRoot.position() val direction = vec2(touchX, touchY).sub(currentPosition) me().physicsRoot.b2DBody.linearVelocity = direction.scl(velocityScale) recycle(direction) } override fun onTouchUp(touchX: Float, touchY: Float, button: Int) { me().physicsRoot.b2DBody.setLinearVelocity(0f, 0f) } override fun onAddToWorld() { touched = false } }
apache-2.0
2ec81840103f5d471a0e1c92fbb28355
23.589744
82
0.654849
3.914286
false
false
false
false
icanit/mangafeed
app/src/main/java/eu/kanade/tachiyomi/ui/library/LibraryCategoryFragment.kt
1
8383
package eu.kanade.tachiyomi.ui.library import android.content.res.Configuration import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.f2prateek.rx.preferences.Preference import eu.davidea.flexibleadapter.FlexibleAdapter import eu.kanade.tachiyomi.R import eu.kanade.tachiyomi.data.database.models.Manga import eu.kanade.tachiyomi.event.LibraryMangaEvent import eu.kanade.tachiyomi.ui.base.adapter.FlexibleViewHolder import eu.kanade.tachiyomi.ui.base.fragment.BaseFragment import eu.kanade.tachiyomi.ui.manga.MangaActivity import kotlinx.android.synthetic.main.fragment_library_category.* import rx.Subscription import java.util.* /** * Fragment containing the library manga for a certain category. * Uses R.layout.fragment_library_category. */ class LibraryCategoryFragment : BaseFragment(), FlexibleViewHolder.OnListItemClickListener { /** * Adapter to hold the manga in this category. */ lateinit var adapter: LibraryCategoryAdapter private set /** * Position in the adapter from [LibraryAdapter]. */ private var position: Int = 0 /** * Manga in this category. */ private var mangas: List<Manga>? = null set(value) { field = value ?: ArrayList() } /** * Subscription for the library manga. */ private var libraryMangaSubscription: Subscription? = null /** * Subscription of the number of manga per row. */ private var numColumnsSubscription: Subscription? = null /** * Subscription of the library search. */ private var searchSubscription: Subscription? = null companion object { /** * Key to save and restore [position] from a [Bundle]. */ const val POSITION_KEY = "position_key" /** * Creates a new instance of this class. * * @param position the position in the adapter from [LibraryAdapter]. * @return a new instance of [LibraryCategoryFragment]. */ fun newInstance(position: Int): LibraryCategoryFragment { val fragment = LibraryCategoryFragment() fragment.position = position return fragment } } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedState: Bundle?): View? { return inflater.inflate(R.layout.fragment_library_category, container, false) } override fun onViewCreated(view: View, savedState: Bundle?) { adapter = LibraryCategoryAdapter(this) recycler.setHasFixedSize(true) recycler.adapter = adapter if (libraryFragment.actionMode != null) { setSelectionMode(FlexibleAdapter.MODE_MULTI) } numColumnsSubscription = getColumnsPreferenceForCurrentOrientation().asObservable() .doOnNext { recycler.spanCount = it } .skip(1) // Set again the adapter to recalculate the covers height .subscribe { recycler.adapter = adapter } searchSubscription = libraryPresenter.searchSubject.subscribe { text -> adapter.searchText = text adapter.updateDataSet() } if (savedState != null) { position = savedState.getInt(POSITION_KEY) adapter.onRestoreInstanceState(savedState) if (adapter.mode == FlexibleAdapter.MODE_SINGLE) { adapter.clearSelection() } } } override fun onDestroyView() { numColumnsSubscription?.unsubscribe() searchSubscription?.unsubscribe() super.onDestroyView() } override fun onResume() { super.onResume() libraryMangaSubscription = libraryPresenter.libraryMangaSubject .subscribe { if (it != null) onNextLibraryManga(it) } } override fun onPause() { libraryMangaSubscription?.unsubscribe() super.onPause() } override fun onSaveInstanceState(outState: Bundle) { outState.putInt(POSITION_KEY, position) adapter.onSaveInstanceState(outState) super.onSaveInstanceState(outState) } /** * Subscribe to [LibraryMangaEvent]. When an event is received, it updates [mangas] if needed * and refresh the content of the adapter. * * @param event the event received. */ fun onNextLibraryManga(event: LibraryMangaEvent) { // Get the categories from the parent fragment. val categories = libraryFragment.adapter.categories ?: return // When a category is deleted, the index can be greater than the number of categories. if (position >= categories.size) return // Get the manga list for this category val mangaForCategory = event.getMangasForCategory(categories[position]) // Update the list only if the reference to the list is different, avoiding reseting the // adapter after every onResume. if (mangas !== mangaForCategory) { mangas = mangaForCategory adapter.setItems(mangas ?: emptyList()) } } /** * Called when a manga is clicked. * * @param position the position of the element clicked. * @return true if the item should be selected, false otherwise. */ override fun onListItemClick(position: Int): Boolean { // If the action mode is created and the position is valid, toggle the selection. val item = adapter.getItem(position) ?: return false if (libraryFragment.actionMode != null) { toggleSelection(position) return true } else { openManga(item) return false } } /** * Called when a manga is long clicked. * * @param position the position of the element clicked. */ override fun onListItemLongClick(position: Int) { libraryFragment.createActionModeIfNeeded() toggleSelection(position) } /** * Opens a manga. * * @param manga the manga to open. */ protected fun openManga(manga: Manga) { // Notify the presenter a manga is being opened. libraryPresenter.onOpenManga() // Create a new activity with the manga. val intent = MangaActivity.newIntent(activity, manga) startActivity(intent) } /** * Toggles the selection for a manga. * * @param position the position to toggle. */ private fun toggleSelection(position: Int) { val library = libraryFragment // Toggle the selection. adapter.toggleSelection(position, false) // Notify the selection to the presenter. library.presenter.setSelection(adapter.getItem(position), adapter.isSelected(position)) // Get the selected count. val count = library.presenter.selectedMangas.size if (count == 0) { // Destroy action mode if there are no items selected. library.destroyActionModeIfNeeded() } else { // Update action mode with the new selection. library.setContextTitle(count) library.setVisibilityOfCoverEdit(count) library.invalidateActionMode() } } /** * Returns a preference for the number of manga per row based on the current orientation. * * @return the preference. */ fun getColumnsPreferenceForCurrentOrientation(): Preference<Int> { return if (resources.configuration.orientation == Configuration.ORIENTATION_PORTRAIT) libraryPresenter.preferences.portraitColumns() else libraryPresenter.preferences.landscapeColumns() } /** * Sets the mode for the adapter. * * @param mode the mode to set. It should be MODE_SINGLE or MODE_MULTI. */ fun setSelectionMode(mode: Int) { adapter.mode = mode if (mode == FlexibleAdapter.MODE_SINGLE) { adapter.clearSelection() } } /** * Property to get the library fragment. */ private val libraryFragment: LibraryFragment get() = parentFragment as LibraryFragment /** * Property to get the library presenter. */ private val libraryPresenter: LibraryPresenter get() = libraryFragment.presenter }
apache-2.0
8a732dbfa0bdf5e075e53c40e9348c8d
30.633962
108
0.643564
5.04089
false
false
false
false
ankidroid/Anki-Android
AnkiDroid/src/main/java/com/ichi2/utils/VersionUtils.kt
1
4888
/**************************************************************************************** * Copyright (c) 2015 Timothy Rae <[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.utils import android.content.Context import android.content.pm.PackageManager import androidx.core.content.pm.PackageInfoCompat import com.ichi2.anki.AnkiDroidApp import com.ichi2.anki.CrashReportService import timber.log.Timber import java.lang.NullPointerException /** * Created by Tim on 11/04/2015. */ object VersionUtils { /** * Get package name as defined in the manifest. */ @Suppress("deprecation") // getPackageInfo val appName: String get() { var pkgName = AnkiDroidApp.TAG val context: Context = applicationInstance ?: return AnkiDroidApp.TAG try { val pInfo = context.packageManager.getPackageInfo(context.packageName, 0) pkgName = context.getString(pInfo.applicationInfo.labelRes) } catch (e: PackageManager.NameNotFoundException) { Timber.e(e, "Couldn't find package named %s", context.packageName) } return pkgName } /** * Get the package versionName as defined in the manifest. */ @Suppress("deprecation") // getPackageInfo val pkgVersionName: String get() { var pkgVersion = "?" val context: Context = applicationInstance ?: return pkgVersion try { val pInfo = context.packageManager.getPackageInfo(context.packageName, 0) pkgVersion = pInfo.versionName } catch (e: PackageManager.NameNotFoundException) { Timber.e(e, "Couldn't find package named %s", context.packageName) } return pkgVersion } /** * Get the package versionCode as defined in the manifest. */ @Suppress("deprecation") // getPackageInfo val pkgVersionCode: Long get() { val context: Context = applicationInstance ?: return 0 try { val pInfo = context.packageManager.getPackageInfo(context.packageName, 0) val versionCode = PackageInfoCompat.getLongVersionCode(pInfo) Timber.d("getPkgVersionCode() is %s", versionCode) return versionCode } catch (e: PackageManager.NameNotFoundException) { Timber.e(e, "Couldn't find package named %s", context.packageName) } catch (npe: NullPointerException) { if (context.packageManager == null) { Timber.e("getPkgVersionCode() null package manager?") } else if (context.packageName == null) { Timber.e("getPkgVersionCode() null package name?") } CrashReportService.sendExceptionReport(npe, "Unexpected exception getting version code?") Timber.e(npe, "Unexpected exception getting version code?") } return 0 } private val applicationInstance: Context? get() = if (AnkiDroidApp.isInitialized) { AnkiDroidApp.instance } else { Timber.w("AnkiDroid instance not set") null } /** * Return whether the package version code is set to that for release version * @return whether build number in manifest version code is '3' */ val isReleaseVersion: Boolean get() { val versionCode = java.lang.Long.toString(pkgVersionCode) Timber.d("isReleaseVersion() versionCode: %s", versionCode) return versionCode[versionCode.length - 3] == '3' } }
gpl-3.0
18965d0905edc90eb4f808198566eb0e
43.844037
105
0.548077
5.473684
false
false
false
false
JimSeker/threads
ThreadDemo_kt/app/src/main/java/edu/cs4730/threaddemo_kt/MainActivity.kt
1
7183
package edu.cs4730.threaddemo_kt import android.graphics.* import android.os.Bundle import android.os.Handler import android.view.MotionEvent import android.view.View import android.view.View.OnTouchListener import android.widget.ImageView import android.widget.TextView import androidx.appcompat.app.AppCompatActivity import java.util.concurrent.locks.ReentrantLock import kotlin.concurrent.withLock /** * This is a thread demo * When the user touches the image, a red bar will roll down. * If the user lifts before it is done, then it will pause the thread. */ class MainActivity : AppCompatActivity() { companion object { lateinit var log: TextView lateinit var theboardfield: ImageView lateinit var theboard: Bitmap lateinit var theboardc: Canvas val boardsize = 480 var isAnimation = false var pause: kotlin.Boolean = false lateinit var handler: Handler //for drawing lateinit var myRec: Rect lateinit var myColor: Paint //for the thread var myThread: Thread? = null val mylock = ReentrantLock() val condition = mylock.newCondition() fun sendmessage(logthis: String) { val b = Bundle() b.putString("logthis", logthis) val msg = handler.obtainMessage() msg.data = b msg.arg1 = 1 msg.what = 1 //so the empty message is not used! println("About to Send message$logthis") handler.sendMessage(msg) println("Sent message$logthis") } fun drawBmp() { theboardfield.setImageBitmap(theboard) theboardfield.invalidate() } /** * simple method to add the log TextView. */ fun logthis(newinfo: String) { if (newinfo.compareTo("") != 0) { log.append("\n" + newinfo) } } /** * attempts to start or restart a the thread */ fun go() { if (pause) { //The thread is paused, so attempt to restart it. logthis("About to notify!") pause = false //kotlin threading is different from java. **** mylock.withLock { condition.signal() //in theory, this should wakeup the thread. OR myThread.notifyAll() } logthis("waiting threads should be notified.") } else { //the thread is not running, so just start it. isAnimation = true if (myThread != null) myThread = null myThread = Thread(animator()) myThread!!.start() } } /** * attempt to stop/suspend a thread */ fun stop() { if (!pause) { //So it is running, now to stop it. if (myThread!!.isAlive) { //and still active pause = true } } } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) log = findViewById(R.id.log) //get the imageview and create a bitmap to put in the imageview. //also create the canvas to draw on. //get the imageview and create a bitmap to put in the imageview. //also create the canvas to draw on. theboardfield = findViewById(R.id.boardfield) theboard = Bitmap.createBitmap(boardsize, boardsize, Bitmap.Config.ARGB_8888) theboardc = Canvas(theboard) theboardc.drawColor(Color.WHITE) //background color for the board. theboardfield.setImageBitmap(theboard) theboardfield.setOnTouchListener(myTouchListener()) //For drawing //For drawing myRec = Rect(0, 0, 10, 10) myColor = Paint() //default black myColor.style = Paint.Style.FILL //message handler for the animation. //message handler for the animation. handler = Handler { msg -> if (msg.what == 0) { //redraw image //if (theboard != null && theboardfield != null) { drawBmp() //} } else { //get the data package out of the msg val stuff = msg.data logthis("Thread: " + stuff.getString("logthis")) } true } } /** * touch listener */ internal class myTouchListener : OnTouchListener { override fun onTouch(v: View, event: MotionEvent): Boolean { //This toggles back and forth the thread. Starting or stopping it, based on up/down events. val action = event.action when (action) { MotionEvent.ACTION_DOWN -> { logthis("onTouch called, DOWN") v.performClick() go() return true } MotionEvent.ACTION_UP -> { logthis("onTouch called, UP") stop() v.performClick() return true } } return false } } internal class animator : Runnable { override fun run() { var done = false var x = 0 //first draw a red down the board myColor.setColor(Color.RED) while (!done) { if (!isAnimation) { return } //To stop the thread, if the system is paused or killed. if (pause) { //We should wait now, until unpaused. println("Attempting to send message") sendmessage("Waiting!") println("Sent message: waiting") //logthis("Thread: Waiting!"); try { //kotlin is different then java *** mylock.withLock { condition.await() } } catch (e: InterruptedException) { sendmessage("Can't Wait!!!") //logthis("Thread: Can't WAIT!!!!"); } sendmessage("Resumed!") //logthis("Thread: Resumed!"); } theboardc.drawLine(0f, x.toFloat(), boardsize.toFloat(), x.toFloat(), myColor) x++ //send message to redraw handler.sendEmptyMessage(0) //now wait a little bit. try { Thread.sleep(10) //change to 100 for a commented out block, instead of just a line. } catch (e: InterruptedException) { //don't care } //determine if we are done or move the x? if (x >= boardsize) done = true } theboardc.drawColor(Color.WHITE) myColor.setColor(Color.BLACK) isAnimation = false } } }
apache-2.0
cd8427d34be5e3b4dfcb6aaa6010b0f0
30.787611
107
0.514827
5.138054
false
false
false
false
pdvrieze/ProcessManager
buildSrc/src/main/kotlin/versions/global.kt
1
3386
/* * Copyright (c) 2019. * * 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 versions import org.gradle.api.JavaVersion import org.gradle.api.Project val Project.jaxbVersion: String get() = project.property("jaxbVersion") as String val Project.kotlin_version: String get() = project.property("kotlin_version") as String val Project.kotlin_plugin_version: String get() = project.property("kotlin_plugin_version") as String val Project.serializationVersion: String get() = project.property("serializationVersion") as String val Project.serializationPluginVersion: String get() = project.property("serializationPluginVersion") as String val Project.jwsApiVersion: String get() = project.property("jwsApiVersion") as String val Project.activationVersion: String get() = project.property("activationVersion") as String val Project.xmlutilVersion: String get() = project.property("xmlutilVersion") as String val Project.kotlinsqlVersion: String get() = project.property("kotlinsqlVersion") as String val Project.androidPluginVersion: String get() = project.property("androidPluginVersion") as String val Project.databindingVersion: String get() = project.property("databindingVersion") as String val Project.kotlinx_html_version: String get() = project.property("kotlinx_html_version") as String val Project.codegen_version: String get() = project.property("codegen_version") as String val Project.junit5_version: String get() = project.property("junit5_version") as String val Project.jupiterVersion: String get() = project.property("jupiterVersion") as String val Project.spek2Version: String get() = project.property("spek2Version") as String val Project.testngVersion: String get() = project.property("testngVersion") as String val Project.tomcatPluginVersion: String get() = project.property("tomcatPluginVersion") as String val Project.tomcatVersion: String get() = project.property("tomcatVersion") as String val Project.mysqlConnectorVersion: String get() = project.property("mysqlConnectorVersion") as String val Project.mariaDbConnectorVersion: String get() = project.property("mariaDbConnectorVersion") as String val Project.androidTarget: String get() = project.property("androidTarget") as String val Project.androidCompatVersion: String get() = project.property("androidCompatVersion") as String val Project.androidCoroutinesVersion: String get() = project.property("androidCoroutinesVersion") as String val Project.requirejs_version: String get() = project.property("requirejs_version") as String val Project.easywsdlver: String get() = project.property("easywsdlver") as String val Project.myJavaVersion: JavaVersion get() = project.property("myJavaVersion") as JavaVersion val Project.argJvmDefault: String get() = project.property("argJvmDefault") as String
lgpl-3.0
545babad66895ba39cfd910c157f62e0
66.72
112
0.79179
4.324393
false
false
false
false
wordpress-mobile/WordPress-Stores-Android
example/src/main/java/org/wordpress/android/fluxc/example/ui/shippinglabels/WooShippingLabelFragment.kt
2
40564
package org.wordpress.android.fluxc.example.ui.shippinglabels import android.content.Context import android.content.Intent import android.os.Bundle import android.util.Base64 import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ArrayAdapter import android.widget.Button import android.widget.CheckBox import android.widget.EditText import android.widget.Spinner import androidx.appcompat.app.AlertDialog import androidx.core.content.FileProvider import kotlinx.android.synthetic.main.fragment_woo_shippinglabels.* import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.delay import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import org.wordpress.android.fluxc.Dispatcher import org.wordpress.android.fluxc.example.R import org.wordpress.android.fluxc.example.prependToLog import org.wordpress.android.fluxc.example.replaceFragment import org.wordpress.android.fluxc.example.ui.StoreSelectingFragment import org.wordpress.android.fluxc.example.utils.showSingleLineDialog import org.wordpress.android.fluxc.generated.WCOrderActionBuilder import org.wordpress.android.fluxc.model.SiteModel import org.wordpress.android.fluxc.model.OrderEntity import org.wordpress.android.fluxc.model.shippinglabels.WCContentType import org.wordpress.android.fluxc.model.shippinglabels.WCCustomsItem import org.wordpress.android.fluxc.model.shippinglabels.WCNonDeliveryOption import org.wordpress.android.fluxc.model.shippinglabels.WCPackagesResult.CustomPackage import org.wordpress.android.fluxc.model.shippinglabels.WCPackagesResult.PredefinedOption import org.wordpress.android.fluxc.model.shippinglabels.WCRestrictionType import org.wordpress.android.fluxc.model.shippinglabels.WCShippingAccountSettings import org.wordpress.android.fluxc.model.shippinglabels.WCShippingLabelModel import org.wordpress.android.fluxc.model.shippinglabels.WCShippingLabelModel.ShippingLabelAddress import org.wordpress.android.fluxc.model.shippinglabels.WCShippingLabelModel.ShippingLabelPackage import org.wordpress.android.fluxc.model.shippinglabels.WCShippingLabelPackageData import org.wordpress.android.fluxc.model.shippinglabels.WCShippingLabelPaperSize import org.wordpress.android.fluxc.model.shippinglabels.WCShippingPackageCustoms import org.wordpress.android.fluxc.store.WCOrderStore import org.wordpress.android.fluxc.store.WCOrderStore.FetchOrdersByIdsPayload import org.wordpress.android.fluxc.store.WCShippingLabelStore import org.wordpress.android.fluxc.store.WooCommerceStore import org.wordpress.android.fluxc.store.WooCommerceStore.WooPlugin.WOO_SERVICES import java.io.File import java.io.FileOutputStream import java.io.IOException import java.math.BigDecimal import java.net.URL import java.text.SimpleDateFormat import java.util.Date import java.util.Locale import javax.inject.Inject import kotlin.math.ceil private const val LOAD_DATA_DELAY = 5000L // 5 seconds @Suppress("LargeClass") class WooShippingLabelFragment : StoreSelectingFragment() { @Inject internal lateinit var dispatcher: Dispatcher @Inject internal lateinit var wooCommerceStore: WooCommerceStore @Inject internal lateinit var wcShippingLabelStore: WCShippingLabelStore @Inject internal lateinit var wcOrderStore: WCOrderStore private val coroutineScope = CoroutineScope(Dispatchers.Main) override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? = inflater.inflate(R.layout.fragment_woo_shippinglabels, container, false) @Suppress("LongMethod", "ComplexMethod", "SwallowedException", "TooGenericExceptionCaught") override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) fetch_shipping_labels.setOnClickListener { selectedSite?.let { site -> showSingleLineDialog(activity, "Enter the order ID:", isNumeric = true) { orderEditText -> if (orderEditText.text.isEmpty()) { prependToLog("OrderId is null so doing nothing") return@showSingleLineDialog } val orderId = orderEditText.text.toString().toLong() prependToLog("Submitting request to fetch shipping labels for order $orderId") coroutineScope.launch { try { val response = withContext(Dispatchers.Default) { wcShippingLabelStore.fetchShippingLabelsForOrder(site, orderId) } response.error?.let { prependToLog("${it.type}: ${it.message}") } response.model?.let { val labelIds = it.map { it.remoteShippingLabelId }.joinToString(",") prependToLog("Order $orderId has ${it.size} shipping labels with ids $labelIds") } } catch (e: Exception) { prependToLog("Error: ${e.message}") } } } } } refund_shipping_label.setOnClickListener { selectedSite?.let { site -> showSingleLineDialog(activity, "Enter the order ID:", isNumeric = true) { orderEditText -> if (orderEditText.text.isEmpty()) { prependToLog("OrderId is null so doing nothing") return@showSingleLineDialog } val orderId = orderEditText.text.toString().toLong() showSingleLineDialog( activity, "Enter the remote shipping Label Id:", isNumeric = true ) { remoteIdEditText -> if (remoteIdEditText.text.isEmpty()) { prependToLog("Remote Id is null so doing nothing") return@showSingleLineDialog } val remoteId = remoteIdEditText.text.toString().toLong() prependToLog("Submitting request to refund shipping label for order $orderId with id $remoteId") coroutineScope.launch { try { val response = withContext(Dispatchers.Default) { wcShippingLabelStore.refundShippingLabelForOrder(site, orderId, remoteId) } response.error?.let { prependToLog("${it.type}: ${it.message}") } response.model?.let { prependToLog( "Refund for $orderId with shipping label $remoteId is ${response.model}" ) } } catch (e: Exception) { prependToLog("Error: ${e.message}") } } } } } } print_shipping_label.setOnClickListener { selectedSite?.let { site -> showSingleLineDialog( activity, "Enter one or multiple shipping Label Ids (separated by commas):", isNumeric = false ) { remoteIdEditText -> if (remoteIdEditText.text.isEmpty()) { prependToLog("Remote Id is null so doing nothing") return@showSingleLineDialog } val remoteIds = try { remoteIdEditText.text.split(",").map { it.trim().toLong() } } catch (e: Exception) { prependToLog("please check that your input is valid") return@showSingleLineDialog } prependToLog( "Submitting request to print shipping label(s) ${remoteIds.joinToString(" and ")}" ) coroutineScope.launch { try { val response = withContext(Dispatchers.Default) { if (remoteIds.size == 1) { // Use the single label function here to confirm that it's working as well wcShippingLabelStore.printShippingLabel(site, "label", remoteIds.first()) } else { wcShippingLabelStore.printShippingLabels(site, "label", remoteIds) } } response.error?.let { prependToLog("${it.type}: ${it.message}") } response.model?.let { base64Content -> writePDFToFile(base64Content)?.let { openPdfReader(it) } } } catch (e: Exception) { prependToLog("Error: ${e.message}") } } } } } print_commercial_invoice.setOnClickListener { selectedSite?.let { site -> coroutineScope.launch { val orderId = showSingleLineDialog(requireActivity(), "Enter the order ID", isNumeric = true) ?.toLong() val labelId = showSingleLineDialog(requireActivity(), "Enter the label ID", isNumeric = true) ?.toLong() if (orderId == null || labelId == null) { prependToLog( "One of the submitted parameters is null\n" + "Order ID: $orderId\n" + "Label ID: $labelId" ) return@launch } val label: WCShippingLabelModel? = wcShippingLabelStore.getShippingLabelById(site, orderId, labelId) ?: suspend { prependToLog("Fetching label") wcShippingLabelStore.fetchShippingLabelsForOrder(site, orderId) wcShippingLabelStore.getShippingLabelById(site, orderId, labelId) }.invoke() if (label == null) { prependToLog("Couldn't find a label with the id $labelId") return@launch } if (label.commercialInvoiceUrl.isNullOrEmpty()) { prependToLog( "The label doesn't have a commercial invoice URL, " + "please make sure to use a international label with a carrier that requires " + "a commercial invoice URL (DHL for example)" ) return@launch } prependToLog("Downloading the commercial invoice") val invoiceFile = withContext(Dispatchers.IO) { downloadUrlOrLog(label.commercialInvoiceUrl!!) } invoiceFile?.let { openPdfReader(it) } } } } check_creation_eligibility.setOnClickListener { selectedSite?.let { coroutineScope.launch { val orderId = showSingleLineDialog(requireActivity(), "Order Id?", isNumeric = true)?.toLong() if (orderId == null) { prependToLog("Please enter a valid order id") return@launch } val canCreatePackage = showSingleLineDialog( requireActivity(), "Can Create Package? (true or false)" ).toBoolean() val canCreatePaymentMethod = showSingleLineDialog( requireActivity(), "Can Create Payment Method? (true or false)" ).toBoolean() val canCreateCustomsForm = showSingleLineDialog( requireActivity(), "Can Create Customs Form? (true or false)" ).toBoolean() var eligibility = wcShippingLabelStore.isOrderEligibleForShippingLabelCreation( site = it, orderId = orderId, canCreatePackage = canCreatePackage, canCreatePaymentMethod = canCreatePaymentMethod, canCreateCustomsForm = canCreateCustomsForm ) if (eligibility == null) { prependToLog("Fetching eligibility") val result = wcShippingLabelStore.fetchShippingLabelCreationEligibility( site = it, orderId = orderId, canCreatePackage = canCreatePackage, canCreatePaymentMethod = canCreatePaymentMethod, canCreateCustomsForm = canCreateCustomsForm ) if (result.isError) { prependToLog("${result.error.type}: ${result.error.message}") return@launch } eligibility = result.model!! } prependToLog( "The order is ${if (!eligibility.isEligible) "not " else ""}eligible " + "for Shipping Labels Creation" ) if (!eligibility.isEligible) { prependToLog("Reason for non eligibility: ${eligibility.reason}") } } } } verify_address.setOnClickListener { selectedSite?.let { site -> replaceFragment(WooVerifyAddressFragment.newInstance(site)) } } get_packages.setOnClickListener { selectedSite?.let { site -> coroutineScope.launch { val result = withContext(Dispatchers.Default) { wcShippingLabelStore.getPackageTypes(site) } result.error?.let { prependToLog("${it.type}: ${it.message}") } result.model?.let { prependToLog("$it") } } } } create_custom_package.setOnClickListener { selectedSite?.let { site -> coroutineScope.launch { val customPackageName = showSingleLineDialog( requireActivity(), "Enter Package name" ).toString() val customPackageDimension = showSingleLineDialog( requireActivity(), "Enter Package dimensions" ).toString() val customPackageIsLetter = showSingleLineDialog( requireActivity(), "Is it a letter? (true or false)" ).toBoolean() val customPackageWeightText = showSingleLineDialog( requireActivity(), "Enter Package weight" ).toString() val customPackageWeight = customPackageWeightText.toFloatOrNull() if (customPackageWeight == null) { prependToLog("Invalid float value for package weight: $customPackageWeightText\n") } else { val result = withContext(Dispatchers.Default) { val customPackage = CustomPackage( title = customPackageName, isLetter = customPackageIsLetter, dimensions = customPackageDimension, boxWeight = customPackageWeight ) wcShippingLabelStore.createPackages( site = site, customPackages = listOf(customPackage), predefinedPackages = emptyList() ) } result.error?.let { prependToLog("${it.type}: ${it.message}") } result.model?.let { prependToLog("Custom package created: $it") } } } } } // This test gets all available predefined options, picks one at random, then activates one package in it. // The end result can either it succeeds (if it hasn't been activated before), or it won't. For the // latter case, the button can be re-tried again by tester. activate_predefined_package.setOnClickListener { prependToLog("Grabbing all available predefined package options...") selectedSite?.let { site -> coroutineScope.launch { val allPredefinedOptions = mutableListOf<PredefinedOption>() val allPredefinedResult = withContext(Dispatchers.Default) { wcShippingLabelStore.getAllPredefinedOptions(site) } allPredefinedResult.error?.let { prependToLog("${it.type}: ${it.message}") return@launch } allPredefinedResult.model?.let { allPredefinedOptions.addAll(it) } // Pick a random Option, and then pick only one Package inside of it. val randomOption = allPredefinedOptions.random() val randomParam = PredefinedOption( title = randomOption.title, carrier = randomOption.carrier, predefinedPackages = listOf(randomOption.predefinedPackages.random()) ) prependToLog( "Activating ${randomParam.predefinedPackages.first().id} from ${randomParam.carrier}..." ) val result = withContext(Dispatchers.Default) { wcShippingLabelStore.createPackages( site = site, customPackages = emptyList(), predefinedPackages = listOf(randomParam) ) } result.error?.let { prependToLog("${it.type}: ${it.message}") return@launch } result.model?.let { prependToLog("Predefined package activated: $it") } } } } get_shipping_rates.setOnClickListener { selectedSite?.let { site -> coroutineScope.launch { val orderId = showSingleLineDialog(requireActivity(), "Enter order id:", isNumeric = true) ?.toLong() ?: return@launch val (order, origin, destination) = loadData(site, orderId) if (order == null) { prependToLog("Couldn't retrieve order data") return@launch } if (origin == null || destination == null) { prependToLog( "Invalid origin or destination address:\n" + "Origin:\n$origin\nDestination:\n$destination" ) return@launch } var name: String showSingleLineDialog(activity, "Enter package name:") { text -> name = text.text.toString() var height: Float? showSingleLineDialog(activity, "Enter height:", isNumeric = true) { h -> height = h.text.toString().toFloatOrNull() var width: Float? showSingleLineDialog(activity, "Enter width:", isNumeric = true) { w -> width = w.text.toString().toFloatOrNull() var length: Float? showSingleLineDialog(activity, "Enter length:", isNumeric = true) { l -> length = l.text.toString().toFloatOrNull() var weight: Float? showSingleLineDialog(activity, "Enter weight:", isNumeric = true) { t -> weight = t.text.toString().toFloatOrNull() val box: ShippingLabelPackage? @Suppress("ComplexCondition") if (height == null || width == null || length == null || weight == null) { prependToLog( "Invalid package parameters:\n" + "Height: $height\n" + "Width: $width\n" + "Length: $length\n" + "Weight: $weight" ) } else { box = ShippingLabelPackage( name, "medium_flat_box_top", height!!, length!!, width!!, weight!! ) coroutineScope.launch { val result = wcShippingLabelStore.getShippingRates( site, order.orderId, origin, destination, listOf(box), null ) result.error?.let { prependToLog("${it.type}: ${it.message}") } result.model?.let { prependToLog("$it") } } } } } } } } } } } purchase_label.setOnClickListener { selectedSite?.let { site -> coroutineScope.launch { val orderId = showSingleLineDialog(requireActivity(), "Enter order id:", isNumeric = true) ?.toLong() ?: return@launch val (order, origin, destination) = loadData(site, orderId) if (order == null) { prependToLog("Couldn't retrieve order data") return@launch } if (origin == null || destination == null) { prependToLog( "Invalid origin or destination address:\n" + "Origin:\n$origin\nDestination:\n$destination" ) return@launch } val boxId = showSingleLineDialog( requireActivity(), "Enter box Id", defaultValue = "medium_flat_box_top" ) val height = showSingleLineDialog(requireActivity(), "Enter height:", isNumeric = true) ?.toFloat() val width = showSingleLineDialog(requireActivity(), "Enter width:", isNumeric = true) ?.toFloat() val length = showSingleLineDialog(requireActivity(), "Enter length:", isNumeric = true) ?.toFloat() val weight = showSingleLineDialog(requireActivity(), "Enter weight:", isNumeric = true) ?.toFloat() @Suppress("ComplexCondition") if (boxId == null || height == null || width == null || length == null || weight == null) { prependToLog( "Invalid package parameters:\n" + "BoxId: $boxId\n" + "Height: $height\n" + "Width: $width\n" + "Length: $length\n" + "Weight: $weight" ) return@launch } prependToLog("Retrieving rates") val box = ShippingLabelPackage( "default", boxId, height, length, width, weight ) val isInternational = destination.country != origin.country val customsData = if (isInternational) { val customsItems = order.getLineItemList().map { val quantity = it.quantity ?: 0f WCCustomsItem( productId = it.productId!!, description = it.name.orEmpty(), value = (it.price?.toBigDecimal() ?: BigDecimal.ZERO), quantity = ceil(quantity).toInt(), weight = 1f, hsTariffNumber = null, originCountry = "US" ) } WCShippingPackageCustoms( id = "default", contentsType = if (isInternational) WCContentType.Merchandise else null, restrictionType = if (isInternational) WCRestrictionType.None else null, itn = "AES X20160406131357", nonDeliveryOption = if (isInternational) WCNonDeliveryOption.Return else null, customsItems = customsItems ) } else null val ratesResult = wcShippingLabelStore.getShippingRates( site, order.orderId, if (isInternational) origin.copy(phone = "0000000000") else origin, if (isInternational) destination.copy(phone = "0000000000") else destination, listOf(box), customsData?.let { listOf(it) } ) if (ratesResult.isError) { prependToLog( "Getting rates failed: " + "${ratesResult.error.type}: ${ratesResult.error.message}" ) return@launch } if (ratesResult.model!!.packageRates.isEmpty() || ratesResult.model!!.packageRates.first().shippingOptions.isEmpty() || ratesResult.model!!.packageRates.first().shippingOptions.first().rates.isEmpty()) { prependToLog("Couldn't find rates for the given input, please try with different parameters") return@launch } val rate = ratesResult.model!!.packageRates.first().shippingOptions.first().rates.first() val packageData = WCShippingLabelPackageData( id = "default", boxId = boxId, isLetter = box.isLetter, length = length, height = height, width = width, weight = weight, shipmentId = rate.shipmentId, rateId = rate.rateId, serviceId = rate.serviceId, serviceName = rate.title, carrierId = rate.carrierId, products = order.getLineItemList().map { it.productId!! } ) prependToLog("Purchasing label") val result = wcShippingLabelStore.purchaseShippingLabels( site, order.orderId, if (isInternational) origin.copy(phone = "0000000000") else origin, if (isInternational) destination.copy(phone = "0000000000") else destination, listOf(packageData), customsData?.let { listOf(it) }, emailReceipts = true ) result.error?.let { prependToLog("${it.type}: ${it.message}") } result.model?.let { val label = it.first() prependToLog( "Purchased a shipping label with the following details:\n" + "Order Id: ${label.remoteOrderId}\n" + "Products: ${label.productNames}\n" + "Label Id: ${label.remoteShippingLabelId}\n" + "Price: ${label.rate}" ) } } } } get_shipping_plugin_info.setOnClickListener { selectedSite?.let { site -> coroutineScope.launch { val result = withContext(Dispatchers.Default) { wooCommerceStore.fetchSitePlugins(site) } result.error?.let { prependToLog("${it.type}: ${it.message}") } val plugin = wooCommerceStore.getSitePlugin(site, WOO_SERVICES) plugin?.let { prependToLog("${it.displayName} ${it.version}") } } } } get_account_settings.setOnClickListener { selectedSite?.let { site -> coroutineScope.launch { val result = wcShippingLabelStore.getAccountSettings(site) result.error?.let { prependToLog("${it.type}: ${it.message}") } if (result.model != null) { prependToLog("${result.model}") } else { prependToLog("The WooCommerce services plugin is not installed") } } } } update_account_settings.setOnClickListener { selectedSite?.let { site -> coroutineScope.launch { val result = wcShippingLabelStore.getAccountSettings(site) result.error?.let { prependToLog("Can't fetch account settings\n${it.type}: ${it.message}") } if (result.model != null) { showAccountSettingsDialog(site, result.model!!) } else { prependToLog("The WooCommerce services plugin is not installed") } } } } } private fun showAccountSettingsDialog(selectedSite: SiteModel, accountSettings: WCShippingAccountSettings) { val dialog = AlertDialog.Builder(requireContext()).let { it.setView(R.layout.dialog_wc_shipping_label_settings) it.show() } dialog.findViewById<CheckBox>(R.id.enabled_checkbox)?.isChecked = accountSettings.isCreatingLabelsEnabled dialog.findViewById<EditText>(R.id.payment_method_id)?.setText( accountSettings.selectedPaymentMethodId?.toString() ?: "" ) dialog.findViewById<CheckBox>(R.id.email_receipts_checkbox)?.isChecked = accountSettings.isEmailReceiptEnabled dialog.findViewById<Spinner>(R.id.paper_size_spinner)?.let { val items = listOf("label", "legal", "letter") it.adapter = ArrayAdapter(requireContext(), android.R.layout.simple_dropdown_item_1line, items) it.setSelection(items.indexOf(accountSettings.paperSize.stringValue)) } dialog.findViewById<Button>(R.id.save_button)?.setOnClickListener { dialog.hide() coroutineScope.launch { val result = wcShippingLabelStore.updateAccountSettings( selectedSite, isCreatingLabelsEnabled = dialog.findViewById<CheckBox>(R.id.enabled_checkbox)?.isChecked, selectedPaymentMethodId = dialog.findViewById<EditText>(R.id.payment_method_id)?.text ?.toString()?.ifEmpty { null }?.toInt(), isEmailReceiptEnabled = dialog.findViewById<CheckBox>(R.id.email_receipts_checkbox)?.isChecked, paperSize = dialog.findViewById<Spinner>(R.id.paper_size_spinner)?.selectedItem?.let { WCShippingLabelPaperSize.fromString(it as String) } ) dialog.dismiss() result.error?.let { prependToLog("${it.type}: ${it.message}") } if (result.model == true) { prependToLog("Settings updated") } else { prependToLog("The WooCommerce services plugin is not installed") } } } } private suspend fun loadData(site: SiteModel, orderId: Long): Triple<OrderEntity?, ShippingLabelAddress?, ShippingLabelAddress?> { prependToLog("Loading shipping data...") val payload = FetchOrdersByIdsPayload(site, listOf(orderId)) dispatcher.dispatch(WCOrderActionBuilder.newFetchOrdersByIdsAction(payload)) delay(LOAD_DATA_DELAY) val origin = wooCommerceStore.fetchSiteGeneralSettings(site).model?.let { ShippingLabelAddress( name = "Test Name", address = it.address, city = it.city, postcode = it.postalCode, state = it.stateCode, country = it.countryCode ) } val order = wcOrderStore.getOrderByIdAndSite(orderId, site) val destination = order?.getShippingAddress()?.let { ShippingLabelAddress( name = "${it.firstName} ${it.lastName}", address = it.address1, city = it.city, postcode = it.postcode, state = it.state, country = it.country ) } return Triple(order, origin, destination) } /** * Creates a temporary file for storing captured photos */ @Suppress("PrintStackTrace") private fun createTempPdfFile(context: Context): File? { val timeStamp = SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US).format(Date()) val storageDir = context.externalCacheDir return try { File.createTempFile( "PDF_${timeStamp}_", ".pdf", storageDir ) } catch (ex: IOException) { ex.printStackTrace() prependToLog("Error when creating temp file: ${ex.message}") null } } @Suppress("PrintStackTrace", "TooGenericExceptionCaught") private fun writePDFToFile(base64Content: String): File? { return try { createTempPdfFile(requireContext())?.let { file -> val out = FileOutputStream(file) val pdfAsBytes = Base64.decode(base64Content, 0) out.write(pdfAsBytes) out.flush() out.close() file } } catch (e: Exception) { e.printStackTrace() prependToLog("Error when writing pdf to file: ${e.message}") null } } private fun openPdfReader(file: File) { val authority = requireContext().applicationContext.packageName + ".provider" val fileUri = FileProvider.getUriForFile( requireContext(), authority, file ) val sendIntent = Intent(Intent.ACTION_VIEW) sendIntent.setDataAndType(fileUri, "application/pdf") sendIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK sendIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION) startActivity(sendIntent) } @Suppress("PrintStackTrace", "TooGenericExceptionCaught") private fun downloadUrlOrLog(url: String): File? { return try { downloadUrl(url) } catch (e: Exception) { e.printStackTrace() prependToLog("Error downloading the file: ${e.message}") null } } private fun downloadUrl(url: String): File? { val file = URL(url).openConnection().inputStream.use { inputStream -> createTempPdfFile(requireContext())?.let { file -> file.outputStream().use { output -> inputStream.copyTo(output) } file } } return file } }
gpl-2.0
9965eceb1ed10b45e1f11a0d7bd46b22
46.722353
120
0.466621
6.404168
false
false
false
false
Team-Antimatter-Mod/AntiMatterMod
src/main/java/antimattermod/core/Util/ClickPos.kt
1
6737
package antimattermod.core.Util import net.minecraftforge.common.util.ForgeDirection /** * Created by kojin15. */ data class ClickPos(var side: Int, var posX: Float, var posY: Float, var posZ: Float) { /** * 変更を加えようとした面 * @return 数値はバニラのsideと同じ */ fun getClickedDirection(): Int { if (onUp(side, posX, posY, posZ)) { return 0 } if (onDown(side, posX, posY, posZ)) { return 1 } if (onNorth(side, posX, posY, posZ)) { return 2 } if (onSouth(side, posX, posY, posZ)) { return 3 } if (onEast(side, posX, posY, posZ)) { return 4 } if (onWest(side, posX, posY, posZ)) { return 5 } return -1 } private fun onUp(side: Int, hitX: Float, hitY: Float, hitZ: Float): Boolean { when (side) { 0 -> if (hitX >= 0.25 && hitX <= 0.75 && hitZ >= 0.25 && hitZ <= 0.75) { return true } 1 -> if ((hitX >= 0.0 && hitX <= 0.25 || hitX >= 0.75 && hitX <= 1.0) && (hitZ >= 0.0 && hitZ <= 0.25 || hitZ >= 0.75 && hitZ <= 1.0)) { return true } 2 -> if (hitX > 0.25 && hitX < 0.75 && hitY > 0.0 && hitY < 0.25) { return true } 3 -> if (hitX > 0.25 && hitX < 0.75 && hitY > 0.0 && hitY < 0.25) { return true } 4 -> if (hitY > 0.0 && hitY < 0.25 && hitZ > 0.25 && hitZ < 0.75) { return true } 5 -> if (hitY > 0.0 && hitY < 0.25 && hitZ > 0.25 && hitZ < 0.75) { return true } else -> return false } return false } private fun onDown(side: Int, hitX: Float, hitY: Float, hitZ: Float): Boolean { when (side) { 0 -> if ((hitX >= 0.0 && hitX <= 0.25 || hitX >= 0.75 && hitX <= 1.0) && (hitZ >= 0.0 && hitZ <= 0.25 || hitZ >= 0.75 && hitZ <= 1.0)) { return true } 1 -> if (hitX >= 0.25 && hitX <= 0.75 && hitZ >= 0.25 && hitZ <= 0.75) { return true } 2 -> if (hitX > 0.25 && hitX < 0.75 && hitY > 0.75 && hitY < 1.0) { return true } 3 -> if (hitX > 0.25 && hitX < 0.75 && hitY > 0.75 && hitY < 1.0) { return true } 4 -> if (hitY > 0.75 && hitY < 1.0 && hitZ > 0.25 && hitZ < 0.75) { return true } 5 -> if (hitY > 0.75 && hitY < 1.0 && hitZ > 0.25 && hitZ < 0.75) { return true } else -> return false } return false } private fun onNorth(side: Int, hitX: Float, hitY: Float, hitZ: Float): Boolean { when (side) { 0 -> if (hitX > 0.25 && hitX < 0.75 && hitZ > 0.0 && hitZ < 0.25) { return true } 1 -> if (hitX > 0.25 && hitX < 0.75 && hitZ > 0.0 && hitZ < 0.25) { return true } 2 -> if (hitX >= 0.25 && hitX <= 0.75 && hitY >= 0.25 && hitY <= 0.75) { return true } 3 -> if ((hitX >= 0.0 && hitX <= 0.25 || hitX >= 0.75 && hitX <= 1.0) && (hitY >= 0.0 && hitY <= 0.25 || hitY >= 0.75 && hitY <= 1.0)) { return true } 4 -> if (hitY > 0.25 && hitY < 0.75 && hitZ > 0.0 && hitZ < 0.25) { return true } 5 -> if (hitY > 0.25 && hitY < 0.75 && hitZ > 0.0 && hitZ < 0.25) { return true } else -> return false } return false } private fun onSouth(side: Int, hitX: Float, hitY: Float, hitZ: Float): Boolean { when (side) { 0 -> if (hitX > 0.25 && hitX < 0.75 && hitZ > 0.75 && hitZ < 1.0) { return true } 1 -> if (hitX > 0.25 && hitX < 0.75 && hitZ > 0.75 && hitZ < 1.0) { return true } 2 -> if ((hitX >= 0.0 && hitX <= 0.25 || hitX >= 0.75 && hitX <= 1.0) && (hitY >= 0.0 && hitY <= 0.25 || hitY >= 0.75 && hitY <= 1.0)) { return true } 3 -> if (hitX >= 0.25 && hitX <= 0.75 && hitY >= 0.25 && hitY <= 0.75) { return true } 4 -> if (hitY > 0.25 && hitY < 0.75 && hitZ > 0.75 && hitZ < 1.0) { return true } 5 -> if (hitY > 0.25 && hitY < 0.75 && hitZ > 0.75 && hitZ < 1.0) { return true } else -> return false } return false } private fun onEast(side: Int, hitX: Float, hitY: Float, hitZ: Float): Boolean { when (side) { 0 -> if (hitX > 0.0 && hitX < 0.25 && hitZ > 0.25 && hitZ < 0.75) { return true } 1 -> if (hitX > 0.0 && hitX < 0.25 && hitZ > 0.25 && hitZ < 0.75) { return true } 2 -> if (hitX > 0.0 && hitX < 0.25 && hitY > 0.25 && hitY < 0.75) { return true } 3 -> if (hitX > 0.0 && hitX < 0.25 && hitY > 0.25 && hitY < 0.75) { return true } 4 -> if (hitY >= 0.25 && hitY <= 0.75 && hitZ >= 0.25 && hitZ <= 0.75) { return true } 5 -> if ((hitY >= 0.0 && hitY <= 0.25 || hitY >= 0.75 && hitY <= 1.0) && (hitZ >= 0.0 && hitZ <= 0.25 || hitZ >= 0.75 && hitZ <= 1.0)) { return true } else -> return false } return false } private fun onWest(side: Int, hitX: Float, hitY: Float, hitZ: Float): Boolean { when (side) { 0 -> if (hitX > 0.75 && hitX < 1.0 && hitZ > 0.25 && hitZ < 0.75) { return true } 1 -> if (hitX > 0.75 && hitX < 1.0 && hitZ > 0.25 && hitZ < 0.75) { return true } 2 -> if (hitX > 0.75 && hitX < 1.0 && hitY > 0.25 && hitY < 0.75) { return true } 3 -> if (hitX > 0.75 && hitX < 1.0 && hitY > 0.25 && hitY < 0.75) { return true } 4 -> if ((hitY >= 0.0 && hitY <= 0.25 || hitY >= 0.75 && hitY <= 1.0) && (hitZ >= 0.0 && hitZ <= 0.25 || hitZ >= 0.75 && hitZ <= 1.0)) { return true } 5 -> if (hitY >= 0.25 && hitY <= 0.75 && hitZ >= 0.25 && hitZ <= 0.75) { return true } else -> return false } return false } }
gpl-3.0
8bdd76d90a51770c9b8aa24a3af7a01b
35
148
0.380134
3.447477
false
false
false
false
ekager/focus-android
app/src/main/java/org/mozilla/focus/firstrun/FirstrunPagerAdapter.kt
1
3653
/* -*- Mode: Java; c-basic-offset: 4; tab-width: 4; indent-tabs-mode: nil; -*- * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package org.mozilla.focus.firstrun import android.content.Context import android.support.v4.view.PagerAdapter import android.support.v4.view.ViewPager import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Button import android.widget.ImageView import android.widget.TextView import org.mozilla.focus.R class FirstrunPagerAdapter( private val context: Context, private val listener: View.OnClickListener ) : PagerAdapter() { private data class FirstrunPage(val title: String, val text: String, val imageResource: Int) { val contentDescription = title + text } private val pages: Array<FirstrunPage> init { val appName = context.getString(R.string.app_name) this.pages = arrayOf( FirstrunPage( context.getString(R.string.firstrun_defaultbrowser_title), context.getString(R.string.firstrun_defaultbrowser_text_new), R.drawable.onboarding_img1), FirstrunPage( context.getString(R.string.firstrun_search_title), context.getString(R.string.firstrun_search_text), R.drawable.onboarding_img4), FirstrunPage( context.getString(R.string.firstrun_shortcut_title), context.getString(R.string.firstrun_shortcut_text, appName), R.drawable.onboarding_img3), FirstrunPage( context.getString(R.string.firstrun_privacy_title), context.getString(R.string.firstrun_privacy_text, appName), R.drawable.onboarding_img2)) } private fun getView(position: Int, pager: ViewPager): View { val view = LayoutInflater.from(context).inflate(R.layout.firstrun_page, pager, false) val page = pages[position] val titleView: TextView = view.findViewById(R.id.title) titleView.text = page.title val textView: TextView = view.findViewById(R.id.text) textView.text = page.text val imageView: ImageView = view.findViewById(R.id.image) imageView.setImageResource(page.imageResource) val buttonView: Button = view.findViewById(R.id.button) buttonView.setOnClickListener(listener) if (position == pages.size - 1) { buttonView.setText(R.string.firstrun_close_button) buttonView.id = R.id.finish buttonView.contentDescription = buttonView.text.toString().toLowerCase() } else { buttonView.setText(R.string.firstrun_next_button) buttonView.id = R.id.next } return view } fun getPageAccessibilityDescription(position: Int): String = pages[position].contentDescription override fun isViewFromObject(view: View, any: Any) = view === any override fun getCount() = pages.size override fun instantiateItem(container: ViewGroup, position: Int): Any { container as ViewPager val view = getView(position, container) container.addView(view) return view } override fun destroyItem(container: ViewGroup, position: Int, view: Any) { view as View container.removeView(view) } }
mpl-2.0
b19aa57d1c349f8c69f491c06ee8eff7
35.53
98
0.641664
4.411836
false
false
false
false
Kotlin/kotlinx.serialization
buildSrc/src/main/kotlin/Publishing.kt
1
2542
/* * Copyright 2016-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. */ @file:Suppress("UnstableApiUsage") import org.gradle.api.* import org.gradle.api.artifacts.dsl.* import org.gradle.api.provider.* import org.gradle.api.publish.maven.* import org.gradle.plugins.signing.* import java.net.* // Pom configuration infix fun <T> Property<T>.by(value: T) { set(value) } fun MavenPom.configureMavenCentralMetadata(project: Project) { name by project.name description by "Kotlin multiplatform serialization runtime library" url by "https://github.com/Kotlin/kotlinx.serialization" licenses { license { name by "The Apache Software License, Version 2.0" url by "https://www.apache.org/licenses/LICENSE-2.0.txt" distribution by "repo" } } developers { developer { id by "JetBrains" name by "JetBrains Team" organization by "JetBrains" organizationUrl by "https://www.jetbrains.com" } } scm { url by "https://github.com/Kotlin/kotlinx.serialization" } } fun mavenRepositoryUri(): URI { // TODO -SNAPSHOT detection can be made here as well val repositoryId: String? = System.getenv("libs.repository.id") return if (repositoryId == null) { URI("https://oss.sonatype.org/service/local/staging/deploy/maven2/") } else { URI("https://oss.sonatype.org/service/local/staging/deployByRepositoryId/$repositoryId") } } fun configureMavenPublication(rh: RepositoryHandler, project: Project) { rh.maven { url = mavenRepositoryUri() credentials { username = project.getSensitiveProperty("libs.sonatype.user") password = project.getSensitiveProperty("libs.sonatype.password") } } } fun signPublicationIfKeyPresent(project: Project, publication: MavenPublication) { val keyId = project.getSensitiveProperty("libs.sign.key.id") val signingKey = project.getSensitiveProperty("libs.sign.key.private") val signingKeyPassphrase = project.getSensitiveProperty("libs.sign.passphrase") if (!signingKey.isNullOrBlank()) { project.extensions.configure<SigningExtension>("signing") { useInMemoryPgpKeys(keyId, signingKey, signingKeyPassphrase) sign(publication) } } } private fun Project.getSensitiveProperty(name: String): String? { return project.findProperty(name) as? String ?: System.getenv(name) }
apache-2.0
38582ed71820efa7fd139a4b1e9144e7
30.382716
102
0.675059
4.093398
false
false
false
false
hellenxu/AndroidAdvanced
Custom/app/src/main/java/six/ca/custom/loading/skeleton/DataAdapter.kt
1
1442
package six.ca.custom.loading.skeleton import android.content.Context import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.TextView import androidx.recyclerview.widget.RecyclerView import six.ca.custom.R class DataAdapter(ctx: Context): RecyclerView.Adapter<DataViewHolder>() { private val layoutInflater = LayoutInflater.from(ctx) private var sourceData: MutableList<NewsData> = mutableListOf() fun setData(data: MutableList<NewsData>) { sourceData.addAll(data) notifyDataSetChanged() } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): DataViewHolder { val itemView = layoutInflater.inflate(R.layout.data_item, parent, false) return DataViewHolder(itemView) } override fun getItemCount(): Int { return sourceData.size } override fun onBindViewHolder(holder: DataViewHolder, position: Int) { holder.icon.setImageResource(sourceData[position].iconResId) holder.title.text = sourceData[position].title holder.content.text = sourceData[position].content } } class DataViewHolder(itemView: View): RecyclerView.ViewHolder(itemView) { val icon: ImageView = itemView.findViewById(R.id.icon) val title: TextView = itemView.findViewById(R.id.itemTitle) val content: TextView = itemView.findViewById(R.id.itemContent) }
apache-2.0
b6b67603bb74052a91f0f914c824537f
33.357143
87
0.74896
4.50625
false
false
false
false
TheComputerGeek2/MagicSpells
core/src/main/java/com/nisovin/magicspells/volatilecode/v1_17_R1/VolatileCode1_17_R1.kt
1
6048
package com.nisovin.magicspells.volatilecode.v1_17_R1 /* import java.lang.reflect.Field import org.bukkit.Bukkit import org.bukkit.entity.* import org.bukkit.Location import org.bukkit.util.Vector import org.bukkit.inventory.ItemStack import org.bukkit.craftbukkit.v1_17_R1.entity.* import org.bukkit.craftbukkit.v1_17_R1.CraftWorld import org.bukkit.event.entity.ExplosionPrimeEvent import org.bukkit.craftbukkit.v1_17_R1.CraftServer import org.bukkit.craftbukkit.v1_17_R1.inventory.CraftItemStack import com.nisovin.magicspells.util.* import com.nisovin.magicspells.MagicSpells import com.nisovin.magicspells.util.compat.EventUtil import com.nisovin.magicspells.volatilecode.VolatileCodeHandle import net.minecraft.world.phys.Vec3D import net.minecraft.network.protocol.game.* import net.minecraft.network.chat.ChatMessage import net.minecraft.world.entity.EntityTypes import net.minecraft.world.entity.EntityLiving import net.minecraft.world.item.alchemy.PotionUtil import net.minecraft.network.syncher.DataWatcherObject import net.minecraft.world.entity.item.EntityTNTPrimed import net.minecraft.world.entity.item.EntityFallingBlock import net.minecraft.world.entity.boss.enderdragon.EntityEnderDragon private typealias nmsItemStack = net.minecraft.world.item.ItemStack class VolatileCode1_17_R1: VolatileCodeHandle { private var entityFallingBlockFallHurtAmountField: Field? = null private var entityFallingBlockFallHurtMaxField: Field? = null private var entityLivingPotionEffectColor: DataWatcherObject<Int>? = null init { try { this.entityFallingBlockFallHurtAmountField = EntityFallingBlock::class.java.getDeclaredField("ar") this.entityFallingBlockFallHurtAmountField!!.isAccessible = true this.entityFallingBlockFallHurtMaxField = EntityFallingBlock::class.java.getDeclaredField("aq") this.entityFallingBlockFallHurtMaxField!!.isAccessible = true val entityLivingPotionEffectColorField = EntityLiving::class.java.getDeclaredField("bK") entityLivingPotionEffectColorField.isAccessible = true; this.entityLivingPotionEffectColor = entityLivingPotionEffectColorField.get(null) as DataWatcherObject<Int> } catch (e: Exception) { MagicSpells.error("THIS OCCURRED WHEN CREATING THE VOLATILE CODE HANDLE FOR 1.17, THE FOLLOWING ERROR IS MOST LIKELY USEFUL IF YOU'RE RUNNING THE LATEST VERSION OF MAGICSPELLS.") e.printStackTrace() } } override fun addPotionGraphicalEffect(entity: LivingEntity, color: Int, duration: Int) { val livingEntity = (entity as CraftLivingEntity).handle; val dataWatcher = livingEntity.dataWatcher; dataWatcher.set(entityLivingPotionEffectColor, color) if (duration > 0) { MagicSpells.scheduleDelayedTask({ var c = 0 if (livingEntity.effects.isNotEmpty()) { c = PotionUtil.a(livingEntity.effects) } dataWatcher.set(entityLivingPotionEffectColor, c) }, duration) } } override fun sendFakeSlotUpdate(player: Player, slot: Int, item: ItemStack?) { val nmsItem: nmsItemStack? if (item != null) { nmsItem = CraftItemStack.asNMSCopy(item) } else { nmsItem = null } val packet = PacketPlayOutSetSlot(0, 0, slot.toShort() + 36, nmsItem!!) (player as CraftPlayer).handle.b.sendPacket(packet) } override fun simulateTnt(target: Location, source: LivingEntity, explosionSize: Float, fire: Boolean): Boolean { val e = EntityTNTPrimed((target.world as CraftWorld).handle, target.x, target.y, target.z, (source as CraftLivingEntity).handle) val c = CraftTNTPrimed(Bukkit.getServer() as CraftServer, e) val event = ExplosionPrimeEvent(c, explosionSize, fire) EventUtil.call(event) return event.isCancelled } override fun setFallingBlockHurtEntities(block: FallingBlock, damage: Float, max: Int) { val efb = (block as CraftFallingBlock).handle try { block.setHurtEntities(true) this.entityFallingBlockFallHurtAmountField!!.setFloat(efb, damage) this.entityFallingBlockFallHurtMaxField!!.setInt(efb, max) } catch (e: Exception) { e.printStackTrace() } } override fun playDragonDeathEffect(location: Location) { val dragon = EntityEnderDragon(EntityTypes.v, (location.world as CraftWorld).handle) dragon.setPositionRotation(location.x, location.y, location.z, location.yaw, 0f) val packet24 = PacketPlayOutSpawnEntityLiving(dragon) val packet38 = PacketPlayOutEntityStatus(dragon, 3.toByte()) val packet29 = PacketPlayOutEntityDestroy(dragon.bukkitEntity.entityId) val box = BoundingBox(location, 64.0) val players = ArrayList<Player>() for (player in location.world!!.players) { if (!box.contains(player)) continue players.add(player) (player as CraftPlayer).handle.b.sendPacket(packet24) player.handle.b.sendPacket(packet38) } MagicSpells.scheduleDelayedTask({ for (player in players) { if (player.isValid) { (player as CraftPlayer).handle.b.sendPacket(packet29) } } }, 250) } override fun setClientVelocity(player: Player, velocity: Vector) { val packet = PacketPlayOutEntityVelocity(player.entityId, Vec3D(velocity.x, velocity.y, velocity.z)) (player as CraftPlayer).handle.b.sendPacket(packet) } override fun setInventoryTitle(player: Player, title: String) { val entityPlayer = (player as CraftPlayer).handle val container = entityPlayer.bV val packet = PacketPlayOutOpenWindow(container.j, container.type, ChatMessage(title)) entityPlayer.b.sendPacket(packet) player.updateInventory() } } */
gpl-3.0
f88b55ba3442742edc9bb48cf1ba50c9
41.293706
190
0.702877
4.128328
false
false
false
false
ykrank/S1-Next
app/src/main/java/me/ykrank/s1next/view/fragment/FavouriteListPagerFragment.kt
1
2761
package me.ykrank.s1next.view.fragment import android.os.Bundle import androidx.recyclerview.widget.LinearLayoutManager import android.view.View import com.github.ykrank.androidtools.ui.internal.PagerCallback import com.github.ykrank.androidtools.ui.vm.LoadingViewModel import com.github.ykrank.androidtools.util.MathUtil import io.reactivex.Single import me.ykrank.s1next.data.api.model.collection.Favourites import me.ykrank.s1next.data.api.model.wrapper.BaseResultWrapper import me.ykrank.s1next.view.adapter.FavouriteRecyclerViewAdapter /** * A Fragment representing one of the pages of favourites. * * * Activity or Fragment containing this must implement [PagerCallback]. */ class FavouriteListPagerFragment : BaseRecyclerViewFragment<BaseResultWrapper<Favourites>>() { private var mPageNum: Int = 0 private lateinit var mRecyclerAdapter: FavouriteRecyclerViewAdapter private var mPagerCallback: PagerCallback? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) mPagerCallback = parentFragment as PagerCallback } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) mPageNum = arguments?.getInt(ARG_PAGE_NUM) ?: 0 leavePageMsg("FavouriteListPagerFragment##mPageNum$mPageNum") val recyclerView = recyclerView recyclerView.layoutManager = androidx.recyclerview.widget.LinearLayoutManager(context) mRecyclerAdapter = FavouriteRecyclerViewAdapter(activity) recyclerView.adapter = mRecyclerAdapter } override fun onDestroy() { mPagerCallback = null super.onDestroy() } override fun getSourceObservable(@LoadingViewModel.LoadingDef loading: Int): Single<BaseResultWrapper<Favourites>> { return mS1Service.getFavouritesWrapper(mPageNum) } override fun onNext(data: BaseResultWrapper<Favourites>) { val favourites = data.data if (favourites.favouriteList == null) { consumeResult(data.result) } else { super.onNext(data) mRecyclerAdapter.diffNewDataSet(favourites.favouriteList, true) // update total page mPagerCallback?.setTotalPages(MathUtil.divide(favourites.total, favourites.favouritesPerPage)) } } companion object { private const val ARG_PAGE_NUM = "page_num" fun newInstance(pageNum: Int): FavouriteListPagerFragment { val fragment = FavouriteListPagerFragment() val bundle = Bundle() bundle.putInt(ARG_PAGE_NUM, pageNum) fragment.arguments = bundle return fragment } } }
apache-2.0
337e83dd5df02070c4cb9c353f71697a
32.670732
120
0.716407
4.878092
false
false
false
false
didi/DoraemonKit
Android/dokit-ft/src/main/java/com/didichuxing/doraemonkit/kit/filemanager/convert/GsonConverter.kt
1
2933
package com.didichuxing.doraemonkit.kit.filemanager.convert import com.google.gson.Gson import com.google.gson.GsonBuilder import io.ktor.application.ApplicationCall import io.ktor.application.call import io.ktor.features.ContentConverter import io.ktor.features.ContentNegotiation import io.ktor.features.ContentTransformationException import io.ktor.features.suitableCharset import io.ktor.http.ContentType import io.ktor.http.content.TextContent import io.ktor.http.withCharset import io.ktor.request.ApplicationReceiveRequest import io.ktor.request.contentCharset import io.ktor.util.pipeline.PipelineContext import io.ktor.utils.io.ByteReadChannel import io.ktor.utils.io.jvm.javaio.toInputStream import kotlinx.coroutines.CopyableThrowable import kotlin.reflect.KClass import kotlin.reflect.jvm.jvmName /** * ================================================ * 作 者:jint(金台) * 版 本:1.0 * 创建日期:2020/7/16-18:05 * 描 述: * 修订历史: * ================================================ */ class GsonConverter(private val gson: Gson = Gson()) : ContentConverter { override suspend fun convertForSend( context: PipelineContext<Any, ApplicationCall>, contentType: ContentType, value: Any ): Any? { return TextContent(gson.toJson(value), contentType.withCharset(context.call.suitableCharset())) } override suspend fun convertForReceive(context: PipelineContext<ApplicationReceiveRequest, ApplicationCall>): Any? { val request = context.subject val channel = request.value as? ByteReadChannel ?: return null val reader = channel.toInputStream().reader(context.call.request.contentCharset() ?: Charsets.UTF_8) val type = request.type if (gson.isExcluded(type)) { throw ExcludedTypeGsonException(type) } return gson.fromJson(reader, type.javaObjectType) ?: throw UnsupportedNullValuesException() } } /** * Register GSON to [ContentNegotiation] feature */ fun ContentNegotiation.Configuration.gson( contentType: ContentType = ContentType.Application.Json, block: GsonBuilder.() -> Unit = {} ) { val builder = GsonBuilder() builder.apply(block) val converter = GsonConverter(builder.create()) register(contentType, converter) } internal class ExcludedTypeGsonException( val type: KClass<*> ) : Exception("Type ${type.jvmName} is excluded so couldn't be used in receive"), CopyableThrowable<ExcludedTypeGsonException> { override fun createCopy(): ExcludedTypeGsonException? = ExcludedTypeGsonException(type).also { it.initCause(this) } } internal class UnsupportedNullValuesException : ContentTransformationException("Receiving null values is not supported") private fun Gson.isExcluded(type: KClass<*>) = excluder().excludeClass(type.java, false)
apache-2.0
3aefab564479e37111973e050281eb1c
33.783133
120
0.708348
4.448382
false
false
false
false