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
qaware/kubepad
src/main/kotlin/de/qaware/cloud/nativ/kpad/ClusterNodeGrid.kt
1
11118
/* * The MIT License (MIT) * * Copyright (c) 2016 QAware GmbH, Munich, Germany * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package de.qaware.cloud.nativ.kpad import de.qaware.cloud.nativ.kpad.launchpad.LaunchpadMK2 import org.slf4j.Logger import java.util.concurrent.ExecutorService import javax.annotation.PostConstruct import javax.annotation.PreDestroy import javax.enterprise.context.ApplicationScoped import javax.enterprise.event.Event import javax.enterprise.event.Observes import javax.enterprise.util.AnnotationLiteral import javax.inject.Inject import javax.inject.Named /** * The grid of 8x8 of the cloud nodes. */ @ApplicationScoped open class ClusterNodeGrid @Inject constructor(@Named("default") private val executor: ExecutorService, private val events: Event<ClusterNodeEvent>, private val cluster: Cluster, private val logger: Logger) { private var initialized: Boolean = false private val grid = arrayOf( mutableListOf<ClusterNode>(), mutableListOf<ClusterNode>(), mutableListOf<ClusterNode>(), mutableListOf<ClusterNode>(), mutableListOf<ClusterNode>(), mutableListOf<ClusterNode>(), mutableListOf<ClusterNode>(), mutableListOf<ClusterNode>()) private val colors = Array(8, { i -> LaunchpadMK2.Color.values()[i + 1] }) /** * Initialize the cloud node grid. */ @PostConstruct open fun init() { logger.debug("Initialize 8x8 cluster node grid.") grid.forEachIndexed { row, instances -> IntRange(0, 7).forEach { instances.add(ClusterNode(row, it)) } } initialized = true } @PreDestroy open fun shutdown() { grid.forEach { row -> row.forEach { it.deactivate() } } } /** * Start a new node in the cluster grid. * * @param event the node event data */ open fun start(@Observes @ClusterNodeEvent.Start event: ClusterNodeEvent) { logger.debug("Start cluster node {}", event) val node = grid[event.row][event.column] val running = cluster.replicas(event.row) node.activate().update(ClusterNode.Phase.Pending) starting(node) executor.execute { cluster.scale(event.row, running + 1) } } /** * Stop a node in the cluster grid. * * @param event the node event data */ open fun stop(@Observes @ClusterNodeEvent.Stop event: ClusterNodeEvent) { logger.debug("Stop cluster node {}", event) val node = grid[event.row][event.column] val running = cluster.replicas(event.row) node.update(ClusterNode.Phase.Succeeded) stopping(node) executor.execute { cluster.scale(event.row, running - 1) } } open fun stopAll() { 0.until(8).forEach { if (cluster.replicas(it) > 0) { scale(it, 0) } } } open fun startAll() { 0.until(8).forEach { if (cluster.replicas(it) == 0) { scale(it, 1) } } } /** * Scale the deployment at given row to number of specified replicas. * * @param row the row * @param replicas number of replicas */ open fun scale(row: Int, replicas: Int) { executor.execute { cluster.scale(row, replicas) } val active = grid[row].filter { it.active.get() } if (active.count() > replicas) { // scale down, stop nodes and update display 0.until(active.count() - replicas).forEach { val node = active[active.count() - it - 1] node.update(ClusterNode.Phase.Succeeded) // stopping(node) node.deactivate() stopped(node) } } else if (active.count() < replicas) { // scale up, start nodes and update display 0.until(replicas - active.count()).forEach { val node = grid[row].first { !it.active.get() } // node.activate().update(ClusterNode.Phase.Pending) // starting(node) node.activate().update(ClusterNode.Phase.Running) started(node) } } } open fun reset() { logger.info("Reloading all apps.") if (initialized) { grid.forEach { it.forEach { it.deactivate() } } colors.indices.forEach { colors[it] = LaunchpadMK2.Color.values()[it + 1] } cluster.reset() } } /** * The event callback in case there is a deployment event in the cluster. * * @param event the deployment event */ open fun onAppEvent(@Observes event: ClusterAppEvent) { if (!initialized) { logger.debug("Ignoring event {}.", event) return } val nodes = grid[event.index] when (event.type) { ClusterAppEvent.Type.ADDED -> { if (event.labels.containsKey("LAUNCHPAD_COLOR")) { try { colors[event.index] = LaunchpadMK2.Color.valueOf(event.labels["LAUNCHPAD_COLOR"]!!) } catch (e: Exception) { logger.error("Unknown color: {}!", event.labels["LAUNCHPAD_COLOR"]) } } started(ClusterNode(event.index, 8)) 0.until(event.replicas).forEach { val node = nodes[it].activate() started(node) } } ClusterAppEvent.Type.DELETED -> { colors[event.index] = LaunchpadMK2.Color.values()[event.index + 1] stopped(ClusterNode(event.index, 8)) 0.until(8).forEach { val node = nodes[it] if (node.active.get()) { node.deactivate() stopped(node) } } } ClusterAppEvent.Type.SCALED_UP -> { val nonRunning = nodes.filter { !it.active.get() } val toStart = event.replicas - (nodes.size - nonRunning.size) val range = 0..Math.min(toStart - 1, nonRunning.size - 1) range.forEach { val node = nonRunning[it] // node.activate().update(ClusterNode.Phase.Pending) // starting(node) node.activate().update(ClusterNode.Phase.Running) started(node) } } ClusterAppEvent.Type.SCALED_DOWN -> { val running = nodes.filter { it.active.get() } val toStop = running.size - event.replicas running.reversed().subList(0, toStop).forEach { it.update(ClusterNode.Phase.Succeeded) // stopping(it) it.deactivate() stopped(it) } } ClusterAppEvent.Type.DEPLOYED -> { nodes.forEach { when (it.phase) { ClusterNode.Phase.Pending -> { it.update(ClusterNode.Phase.Running) started(it) } ClusterNode.Phase.Succeeded -> { it.deactivate() stopped(it) } else -> { } } } } } } private fun starting(node: ClusterNode) { events.select(object : AnnotationLiteral<ClusterNodeEvent.Starting>() {}) .fire(ClusterNodeEvent(node.row, node.column)) } private fun started(node: ClusterNode) { events.select(object : AnnotationLiteral<ClusterNodeEvent.Started>() {}) .fire(ClusterNodeEvent(node.row, node.column)) } private fun stopping(node: ClusterNode) { events.select(object : AnnotationLiteral<ClusterNodeEvent.Stopping>() {}) .fire(ClusterNodeEvent(node.row, node.column)) } private fun stopped(node: ClusterNode) { events.select(object : AnnotationLiteral<ClusterNodeEvent.Stopped>() {}) .fire(ClusterNodeEvent(node.row, node.column)) } open fun color(row: Int): LaunchpadMK2.Color { return if (colors.indices.contains(row)) colors[row] else LaunchpadMK2.Color.LIGHT_GREEN } /** * Get the next not running instance index for the given row. * * @param row the row index */ open fun next(row: Int): Int { val nodes = grid[row] return nodes.find { !it.active.get() }!!.column } /** * Find the last running instance index for the given row. * * @param row the row index */ open fun last(row: Int): Int { val nodes = grid[row] return nodes.findLast { it.active.get() }!!.column } open operator fun get(row: Int): List<ClusterNode> { return grid[row] } /** * Returns the number of active nodes for a row. * * @param row the row * @return number of active nodes */ open fun active(row: Int): Int = grid[row].count { it.active.get() } /** * Check if the given row is initialized meaning is there a deployment. * * @param row the row * @return true if row is initialized with a deployment */ open fun initialized(row: Int): Boolean = cluster.appExists(row) /** * Returns the set of row indexes that have a deployment. * * @return a set of row index with an associated deployment */ open fun rows(): List<Int> { return 0.until(8).filter { i -> cluster.appExists(i) } } }
mit
16ddc1ac599aabfc970f6070ea2255fc
33.209231
107
0.555226
4.580964
false
false
false
false
FHannes/intellij-community
platform/testGuiFramework/src/com/intellij/testGuiFramework/recorder/GlobalActionRecorder.kt
3
3245
/* * 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.recorder import com.intellij.ide.IdeEventQueue import com.intellij.openapi.actionSystem.ActionManager import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.DataContext import com.intellij.openapi.actionSystem.ex.AnActionListener import com.intellij.openapi.diagnostic.Logger import com.intellij.testGuiFramework.recorder.components.GuiRecorderComponent import com.intellij.testGuiFramework.recorder.ui.GuiScriptEditorPanel import java.awt.event.KeyEvent import java.awt.event.MouseEvent /** * @author Sergey Karashevich */ object GlobalActionRecorder { private val LOG by lazy { Logger.getInstance("#${GlobalActionRecorder::class.qualifiedName}") } private var active = false fun isActive() = active private val globalActionListener = object : AnActionListener { override fun beforeActionPerformed(anActionToBePerformed: AnAction?, p1: DataContext?, anActionEvent: AnActionEvent?) { if (anActionEvent?.place == GuiScriptEditorPanel.GUI_SCRIPT_EDITOR_PLACE) return //avoid GUI Script Editor Actions EventDispatcher.processActionEvent(anActionToBePerformed!!, anActionEvent) LOG.info("IDEA is going to perform action ${anActionToBePerformed.templatePresentation.text}") } override fun beforeEditorTyping(p0: Char, p1: DataContext?) { LOG.info("IDEA typing detected: ${p0!!}") } override fun afterActionPerformed(p0: AnAction?, p1: DataContext?, p2: AnActionEvent?) { if (p2?.place == GuiScriptEditorPanel.GUI_SCRIPT_EDITOR_PLACE) return //avoid GUI Script Editor Actions LOG.info("IDEA action performed ${p0!!.templatePresentation.text}") } } private val globalAwtProcessor = IdeEventQueue.EventDispatcher { awtEvent -> when (awtEvent) { is MouseEvent -> EventDispatcher.processMouseEvent(awtEvent) is KeyEvent -> EventDispatcher.processKeyBoardEvent(awtEvent) } false } fun activate() { if (active) return LOG.info("Global action recorder is active") ActionManager.getInstance().addAnActionListener(globalActionListener) IdeEventQueue.getInstance().addDispatcher(globalAwtProcessor, GuiRecorderComponent) //todo: add disposal dependency on component active = true } fun deactivate() { if (active) { LOG.info("Global action recorder is non active") ActionManager.getInstance().removeAnActionListener(globalActionListener) IdeEventQueue.getInstance().removeDispatcher(globalAwtProcessor) } active = false ScriptGenerator.clearContext() } }
apache-2.0
ab7bd8d378f2141a6596b07d15e8a500
35.886364
132
0.761479
4.648997
false
false
false
false
RanKKI/PSNine
app/src/main/java/xyz/rankki/psnine/ui/anko/GameUI.kt
1
2528
package xyz.rankki.psnine.ui.anko import android.view.View import android.widget.RelativeLayout import org.jetbrains.anko.* import xyz.rankki.psnine.R import xyz.rankki.psnine.utils.RelativeLayoutParams class GameUI<T> : AnkoComponent<T> { companion object { const val ID_GameAvatar = 1 const val ID_Edition = 2 const val ID_GameName = 3 const val ID_Trophy = 4 const val ID_Comment = 5 } override fun createView(ui: AnkoContext<T>): View = with(ui) { relativeLayout { padding = 10 imageView { id = ID_GameAvatar val rules: MutableMap<Int, Int> = HashMap() rules[RelativeLayoutParams.ID_Margin] = 10 layoutParams = RelativeLayoutParams().build(dip(91), dip(50), null) } textView { id = ID_Edition val rules: MutableMap<Int, Int> = HashMap() rules[RelativeLayout.RIGHT_OF] = ID_GameAvatar rules[RelativeLayout.ALIGN_TOP] = ID_GameAvatar rules[RelativeLayoutParams.ID_MarginRight] = 5 rules[RelativeLayoutParams.ID_MarginLeft] = 5 layoutParams = RelativeLayoutParams().build(wrapContent, wrapContent, rules) } textView { id = ID_GameName val rules: MutableMap<Int, Int> = HashMap() rules[RelativeLayout.RIGHT_OF] = ID_Edition rules[RelativeLayout.ALIGN_BASELINE] = ID_Edition layoutParams = RelativeLayoutParams().build(wrapContent, wrapContent, rules) } textView { id = ID_Trophy val rules: MutableMap<Int, Int> = HashMap() rules[RelativeLayout.RIGHT_OF] = ID_GameAvatar rules[RelativeLayout.ALIGN_BOTTOM] = ID_GameAvatar layoutParams = RelativeLayoutParams().build(wrapContent, wrapContent, rules) } textView { id = ID_Comment visibility = View.GONE padding = 10 backgroundColor = resources.getColor(R.color.colorBlockQuoteBackground) val rules: MutableMap<Int, Int> = HashMap() rules[RelativeLayout.RIGHT_OF] = ID_GameAvatar rules[RelativeLayout.BELOW] = ID_Trophy layoutParams = RelativeLayoutParams().build(matchParent, wrapContent, rules) } } } }
apache-2.0
267a9faa1aed15cb4921f9889736c8ed
35.652174
92
0.56962
4.956863
false
false
false
false
TeamAmaze/AmazeFileManager
app/src/main/java/com/amaze/filemanager/adapters/holders/CompressedItemViewHolder.kt
3
2007
/* * Copyright (C) 2014-2021 Arpit Khurana <[email protected]>, Vishal Nehra <[email protected]>, * Emmanuel Messulam<[email protected]>, Raymond Lai <airwave209gt at gmail.com> and Contributors. * * This file is part of Amaze File Manager. * * Amaze File Manager is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.amaze.filemanager.adapters.holders import android.view.View import android.widget.ImageView import android.widget.TextView import androidx.recyclerview.widget.RecyclerView import com.amaze.filemanager.R import com.amaze.filemanager.ui.views.ThemedTextView class CompressedItemViewHolder(view: View) : RecyclerView.ViewHolder(view) { // each data item is just a string in this case @JvmField val pictureIcon: ImageView = view.findViewById(R.id.picture_icon) @JvmField val genericIcon: ImageView = view.findViewById(R.id.generic_icon) @JvmField val apkIcon: ImageView = view.findViewById(R.id.apk_icon) @JvmField val txtTitle: ThemedTextView = view.findViewById(R.id.firstline) @JvmField val txtDesc: TextView = view.findViewById(R.id.secondLine) @JvmField val date: TextView = view.findViewById(R.id.date) val perm: TextView = view.findViewById(R.id.permis) @JvmField val rl: View = view.findViewById(R.id.second) @JvmField val checkImageView: ImageView = view.findViewById(R.id.check_icon) }
gpl-3.0
d1098d58434c5814742a2b577e7bfb8d
34.210526
107
0.747384
3.974257
false
false
false
false
valerio-bozzolan/bus-torino
src/it/reyboz/bustorino/fragments/LinesViewModel.kt
1
3047
package it.reyboz.bustorino.fragments import android.app.Application import android.util.Log import androidx.lifecycle.* import it.reyboz.bustorino.backend.Stop import it.reyboz.bustorino.data.GtfsRepository import it.reyboz.bustorino.data.NextGenDB import it.reyboz.bustorino.data.OldDataRepository import it.reyboz.bustorino.data.gtfs.GtfsDatabase import it.reyboz.bustorino.data.gtfs.GtfsRoute import it.reyboz.bustorino.data.gtfs.MatoPatternWithStops import it.reyboz.bustorino.data.gtfs.PatternStop import java.util.concurrent.Executors class LinesViewModel(application: Application) : AndroidViewModel(application) { private val gtfsRepo: GtfsRepository private val oldRepo: OldDataRepository //val patternsByRouteLiveData: LiveData<List<MatoPattern>> private val routeIDToSearch = MutableLiveData<String>() private var lastShownPatternStops = ArrayList<String>() val currentPatternStops = MutableLiveData<List<PatternStop>>() val selectedPatternLiveData = MutableLiveData<MatoPatternWithStops>() val stopsForPatternLiveData = MutableLiveData<List<Stop>>() private val executor = Executors.newFixedThreadPool(2) init { val gtfsDao = GtfsDatabase.getGtfsDatabase(application).gtfsDao() gtfsRepo = GtfsRepository(gtfsDao) oldRepo = OldDataRepository(executor, NextGenDB.getInstance(application)) } val routesGTTLiveData: LiveData<List<GtfsRoute>> by lazy{ gtfsRepo.getLinesLiveDataForFeed("gtt") } val patternsWithStopsByRouteLiveData = routeIDToSearch.switchMap { gtfsRepo.getPatternsWithStopsForRouteID(it) } fun setRouteIDQuery(routeID: String){ routeIDToSearch.value = routeID } fun getRouteIDQueried(): String?{ return routeIDToSearch.value } var shouldShowMessage = true /** * Find the */ private fun requestStopsForGTFSIDs(gtfsIDs: List<String>){ if (gtfsIDs.equals(lastShownPatternStops)){ //nothing to do return } oldRepo.requestStopsWithGtfsIDs(gtfsIDs) { if (it.isSuccess) { stopsForPatternLiveData.postValue(it.result) } else { Log.e("BusTO-LinesVM", "Got error on callback with stops for gtfsID") it.exception?.printStackTrace() } } lastShownPatternStops.clear() for(id in gtfsIDs) lastShownPatternStops.add(id) } fun requestStopsForPatternWithStops(patternStops: MatoPatternWithStops){ val gtfsIDs = ArrayList<String>() for(pat in patternStops.stopsIndices){ gtfsIDs.add(pat.stopGtfsId) } requestStopsForGTFSIDs(gtfsIDs) } /*fun getLinesGTT(): MutableLiveData<List<GtfsRoute>> { val routesData = MutableLiveData<List<GtfsRoute>>() viewModelScope.launch { val routes=gtfsRepo.getLinesForFeed("gtt") routesData.postValue(routes) } return routesData }*/ }
gpl-3.0
009eff06aa5df03a4c3730168827a03a
31.084211
85
0.694454
4.243733
false
false
false
false
henrikfroehling/timekeeper
models/src/main/kotlin/de/froehling/henrik/timekeeper/models/Project.kt
1
987
package de.froehling.henrik.timekeeper.models import android.graphics.Color import android.support.annotation.ColorInt import io.realm.RealmList import io.realm.RealmObject import io.realm.annotations.PrimaryKey import io.realm.annotations.Required class Project : RealmObject() { @PrimaryKey var uuid: String? = null @Required var name: String? = null @Required var description: String? = null @ColorInt var color: Int = Color.TRANSPARENT var hourlyWage: Float = 0.0f var isBillable: Boolean = false var isArchived: Boolean = false var location: Location? = null var customers: RealmList<Customer>? = null var categories: RealmList<Category>? = null var tags: RealmList<Tag>? = null var durations: RealmList<ProjectDuration>? = null @Required var kickOff: Long = 0 @Required var finish: Long = 0 @Required var lastTouched: Long = 0 @Required var modified: Long = 0 @Required var created: Long = 0 }
gpl-3.0
ab212014d8affe9429c2e6450abfce9f
20.933333
53
0.710233
4.129707
false
false
false
false
sleonidy/griffon-gorm-plugin
subprojects/griffon-gorm-hibernate-core/src/main/kotlin/org/griffon/plugins/gorm/runtime/HibernateGormFactory.kt
1
2310
/* * Copyright 2016 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.griffon.plugins.gorm.runtime import griffon.core.Configuration import griffon.core.GriffonApplication import java.util.* import javax.annotation.Nonnull import javax.inject.Inject import javax.inject.Named /** * Created by Leon on 26-Feb-16. */ abstract class HibernateGormFactory @Inject constructor(@Nonnull @Named("gorm") configuration: Configuration, @Nonnull application: GriffonApplication) : DefaultGormFactory(configuration, application) { override fun getConfigurationAsMap(): MutableMap<String, Map<*, *>> { val configurationMap = super.getConfigurationAsMap() configurationMap.putAll(getHibernateConfigurationAsMapOfDataSourceNameToConfigurationMap()) return configurationMap } @Suppress("UNCHECKED_CAST") fun getHibernateConfigurationAsMapOfDataSourceNameToConfigurationMap(): Map<String, Map<*, *>> { return dataSourceFactory.dataSourceNames.associate { val dataSourceName = if (it == "default") "" else it var config: MutableMap<Any, Any> = HashMap() if (configuration.get("$GORM_CONFIG.${HIBERNATE}") != null) { config.putAll(configuration.get("$GORM_CONFIG.${HIBERNATE}") as Map<Any, Any>) } if (configuration.get("$GORM_CONFIG.${HIBERNATE}_$dataSourceName") != null) { config.putAll(configuration.get("$GORM_CONFIG.${HIBERNATE}_$dataSourceName") as Map<Any, Any>) } if (dataSourceName.isBlank()) "${HIBERNATE}" to config else "${HIBERNATE}_$dataSourceName" to config } } companion object { val HIBERNATE = "hibernate" } }
apache-2.0
8d82e39bfc47b8eaed3df6dc8615e29b
37.516667
151
0.687446
4.375
false
true
false
false
bihe/mydms-java
Api/src/main/kotlin/net/binggl/mydms/infrastructure/error/MydmsErrorController.kt
1
1462
package net.binggl.mydms.infrastructure.error import net.binggl.mydms.shared.application.AppVersionInfo import org.springframework.beans.factory.annotation.Autowired import org.springframework.beans.factory.annotation.Value import org.springframework.boot.web.servlet.error.ErrorAttributes import org.springframework.boot.web.servlet.error.ErrorController import org.springframework.stereotype.Controller import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.context.request.WebRequest import org.springframework.web.servlet.ModelAndView import java.time.Year @Controller class MydmsErrorController(@Autowired private val errorAttributes: ErrorAttributes, @Value("\${application.detailedErrors}") private val detailedErrors: Boolean) : ErrorController { @RequestMapping(value = [PATH]) fun error(request: WebRequest): ModelAndView { val mv = ModelAndView("error", this.getErrorAttributes(request, detailedErrors)) mv.model["year"] = Year.now() mv.model["appName"] = AppVersionInfo.versionInfo.artifactId return mv } override fun getErrorPath(): String { return PATH } private fun getErrorAttributes(request: WebRequest, includeStackTrace: Boolean): Map<String, Any> { return errorAttributes.getErrorAttributes(request, includeStackTrace) } companion object { private const val PATH = "/error" } }
apache-2.0
95bed66f27d4a3fdb33a8d9ff0c30e0c
37.5
124
0.75855
4.656051
false
false
false
false
Kerr1Gan/ShareBox
netcore/src/main/java/com/common/netcore/network/AsyncNetwork.kt
1
1332
package com.common.netcore.network import android.util.Log import java.lang.Exception import java.util.concurrent.* import java.util.concurrent.atomic.AtomicInteger /** * Created by KerriGan on 2017/7/14. */ class AsyncNetwork : BaseNetwork() { companion object { private const val TAG = "AsyncNetwork" private var sThreadsCount: AtomicInteger = AtomicInteger(0) @JvmStatic private val sFixedThreadPool = ThreadPoolExecutor(1, Runtime.getRuntime().availableProcessors() + 1, 30L, TimeUnit.SECONDS, LinkedBlockingQueue()) // 阻塞队列防止Rejection异常 } private var mFuture: Future<*>? = null override fun request(urlStr: String, mutableMap: MutableMap<String, String>?): BaseNetwork { mFuture = sFixedThreadPool.submit { Log.e(TAG, "task begin " + toString() + " task count:" + sThreadsCount.incrementAndGet()) try { super.request(urlStr, mutableMap) } catch (e: Exception) { Log.e(TAG, "task exception " + e.toString()) } Log.e(TAG, "task end " + toString() + " task count:" + sThreadsCount.decrementAndGet()) } return this } override fun cancel() { super.cancel() mFuture?.cancel(true) } }
apache-2.0
4ae195166a79f4abe1a103a6e2301956
29.627907
108
0.617781
4.372093
false
false
false
false
mockk/mockk
modules/mockk-agent/src/jvmMain/kotlin/io/mockk/proxy/jvm/ObjenesisInstantiator.kt
1
2767
package io.mockk.proxy.jvm import io.mockk.proxy.MockKAgentLogger import io.mockk.proxy.MockKInstantiatior import io.mockk.proxy.jvm.transformation.CacheKey import net.bytebuddy.ByteBuddy import net.bytebuddy.TypeCache import org.objenesis.ObjenesisStd import org.objenesis.instantiator.ObjectInstantiator import java.lang.reflect.Modifier import java.util.* class ObjenesisInstantiator( private val log: MockKAgentLogger, private val byteBuddy: ByteBuddy ) : MockKInstantiatior { private val objenesis = ObjenesisStd(false) private val typeCache = TypeCache<CacheKey>(TypeCache.Sort.WEAK) private val instantiators = Collections.synchronizedMap(WeakHashMap<Class<*>, ObjectInstantiator<*>>()) override fun <T> instance(cls: Class<T>): T { if (cls == Any::class.java) { @Suppress("UNCHECKED_CAST") return Any() as T } else if (!Modifier.isFinal(cls.modifiers)) { try { val instance = instantiateViaProxy(cls) if (instance != null) { return instance } } catch (ex: Exception) { log.trace( ex, "Failed to instantiate via proxy " + cls + ". " + "Doing objenesis instantiation" ) } } return instanceViaObjenesis(cls) } private fun <T> instantiateViaProxy(cls: Class<T>): T? { val proxyCls = if (!Modifier.isAbstract(cls.modifiers)) { log.trace("Skipping instantiation subsclassing $cls because class is not abstract.") cls } else { log.trace("Instantiating $cls via subclass proxy") val classLoader = cls.classLoader typeCache.findOrInsert( classLoader, CacheKey(cls, setOf()), { byteBuddy.subclass(cls) .annotateType(*cls.annotations) .make() .load(classLoader) .loaded }, classLoader ?: bootstrapMonitor ) } return cls.cast(instanceViaObjenesis(proxyCls)) } private fun <T> instanceViaObjenesis(clazz: Class<T>): T { log.trace("Creating new empty instance of $clazz") return clazz.cast( getOrCreateInstantiator(clazz) .newInstance() ) } private fun <T> getOrCreateInstantiator(clazz: Class<T>) = instantiators[clazz] ?: let { objenesis.getInstantiatorOf(clazz).also { instantiators[clazz] = it } } companion object { private val bootstrapMonitor = Any() } }
apache-2.0
64e47d21fc9b9a4d047265c33f6ec8af
30.089888
107
0.573545
4.673986
false
false
false
false
DemonWav/IntelliJBukkitSupport
src/main/kotlin/nbt/editor/NbtToolbar.kt
1
1642
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2021 minecraft-dev * * MIT License */ package com.demonwav.mcdev.nbt.editor import com.demonwav.mcdev.nbt.NbtVirtualFile import com.demonwav.mcdev.util.runWriteTaskLater import javax.swing.JButton import javax.swing.JComboBox import javax.swing.JPanel class NbtToolbar(nbtFile: NbtVirtualFile) { lateinit var panel: JPanel private lateinit var compressionBox: JComboBox<CompressionSelection> lateinit var saveButton: JButton private var lastSelection: CompressionSelection init { compressionBox.addItem(CompressionSelection.GZIP) compressionBox.addItem(CompressionSelection.UNCOMPRESSED) compressionBox.selectedItem = if (nbtFile.isCompressed) CompressionSelection.GZIP else CompressionSelection.UNCOMPRESSED lastSelection = selection saveButton.isVisible = false if (!nbtFile.isWritable || !nbtFile.parseSuccessful) { compressionBox.isEnabled = false } else { compressionBox.addActionListener { checkModified() } } if (!nbtFile.parseSuccessful) { panel.isVisible = false } saveButton.addActionListener { lastSelection = selection checkModified() runWriteTaskLater { nbtFile.writeFile(this) } } } private fun checkModified() { saveButton.isVisible = lastSelection != selection } val selection get() = compressionBox.selectedItem as CompressionSelection }
mit
54f7fe9965ddd5d08ec1e5cce64c3a88
25.063492
102
0.666261
5.03681
false
false
false
false
bozaro/git-as-svn
src/test/kotlin/svnserver/ext/gitlab/GitLabIntegrationTest.kt
1
9184
/* * This file is part of git-as-svn. It is subject to the license terms * in the LICENSE file found in the top-level directory of this distribution * and at http://www.gnu.org/licenses/gpl-2.0.html. No part of git-as-svn, * including this file, may be copied, modified, propagated, or distributed * except according to the terms contained in the LICENSE file. */ package svnserver.ext.gitlab import org.gitlab.api.GitlabAPI import org.gitlab.api.http.Query import org.gitlab.api.models.* import org.rnorth.ducttape.unreliables.Unreliables import org.testcontainers.DockerClientFactory import org.testcontainers.containers.GenericContainer import org.testcontainers.containers.wait.strategy.AbstractWaitStrategy import org.testng.Assert import org.testng.annotations.AfterClass import org.testng.annotations.BeforeClass import org.testng.annotations.Ignore import org.testng.annotations.Test import org.tmatesoft.svn.core.SVNAuthenticationException import org.tmatesoft.svn.core.io.SVNRepository import svnserver.KFixedHostPortGenericContainer import svnserver.SvnTestHelper import svnserver.SvnTestServer import svnserver.UserType import svnserver.auth.User import svnserver.auth.User.LfsCredentials import svnserver.config.RepositoryMappingConfig import svnserver.ext.gitlab.auth.GitLabUserDBConfig import svnserver.ext.gitlab.config.GitLabConfig import svnserver.ext.gitlab.config.GitLabContext import svnserver.ext.gitlab.config.GitLabToken import svnserver.ext.gitlab.mapping.GitLabMappingConfig import svnserver.ext.gitlfs.storage.local.LfsLocalStorageTest import svnserver.ext.web.config.WebServerConfig import svnserver.repository.git.GitCreateMode import java.io.IOException import java.nio.file.Path import java.time.Duration import java.time.temporal.ChronoUnit import java.util.concurrent.TimeUnit import java.util.function.Function /** * @author Marat Radchenko <[email protected]> */ class GitLabIntegrationTest { private var gitlab: GenericContainer<*>? = null private var gitlabUrl: String? = null private var rootToken: GitLabToken? = null private var gitlabProject: GitlabProject? = null private var gitlabPublicProject: GitlabProject? = null @BeforeClass fun before() { SvnTestHelper.skipTestIfDockerUnavailable() var gitlabVersion = System.getenv("GITLAB_VERSION") if (gitlabVersion == null) { SvnTestHelper.skipTestIfRunningOnCI() gitlabVersion = "9.3.3-ce.0" } val hostPort = 9999 // containerPort is supposed to be 80, but GitLab binds to port from external_url // See https://stackoverflow.com/questions/39351563/gitlab-docker-not-working-if-external-url-is-set val containerPort = 9999 val hostname = DockerClientFactory.instance().dockerHostIpAddress() gitlabUrl = String.format("http://%s:%s", hostname, hostPort) gitlab = KFixedHostPortGenericContainer("gitlab/gitlab-ce:$gitlabVersion") // We have a chicken-and-egg problem here. In order to set external_url, we need to know container address, // but we do not know container address until container is started. // So, for now use fixed port :( .withFixedExposedPort(hostPort, containerPort) // This is kinda stupid that we need to do withExposedPorts even when we have withFixedExposedPort .withExposedPorts(containerPort) .withEnv("GITLAB_OMNIBUS_CONFIG", String.format("external_url '%s'", gitlabUrl)) .withEnv("GITLAB_ROOT_PASSWORD", rootPassword) .waitingFor( WaitForChefComplete() .withStartupTimeout(Duration.of(10, ChronoUnit.MINUTES)) ) gitlab!!.start() rootToken = createToken(root, rootPassword, true) val rootAPI = GitLabContext.connect(gitlabUrl!!, rootToken!!) val createUserRequest = CreateUserRequest(user, user, "git-as-svn@localhost") .setPassword(userPassword) .setSkipConfirmation(true) val gitlabUser = rootAPI.createUser(createUserRequest) Assert.assertNotNull(gitlabUser) val group = rootAPI.createGroup(CreateGroupRequest("testGroup").setVisibility(GitlabVisibility.PUBLIC), null) Assert.assertNotNull(group) Assert.assertNotNull(rootAPI.addGroupMember(group.id, gitlabUser.id, GitlabAccessLevel.Developer)) gitlabProject = createGitlabProject(rootAPI, group, "test", GitlabVisibility.INTERNAL, setOf("git-as-svn:master")) gitlabPublicProject = createGitlabProject(rootAPI, group, "publik", GitlabVisibility.PUBLIC, setOf("git-as-svn:master")) } private fun createToken(username: String, password: String, sudoScope: Boolean): GitLabToken { return GitLabContext.obtainAccessToken(gitlabUrl!!, username, password, sudoScope) } private fun createGitlabProject(rootAPI: GitlabAPI, group: GitlabGroup, name: String, visibility: GitlabVisibility, tags: Set<String>): GitlabProject { // java-gitlab-api doesn't handle tag_list, so we have to do this manually val query = Query() .append("name", name) .appendIf("namespace_id", group.id) .appendIf("visibility", visibility.toString()) .appendIf("tag_list", java.lang.String.join(",", tags)) val tailUrl = GitlabProject.URL + query.toString() return rootAPI.dispatch().to(tailUrl, GitlabProject::class.java) } @AfterClass fun after() { if (gitlab != null) { gitlab!!.stop() gitlab = null } } @Test fun validUser() { checkUser(root, rootPassword) } private fun checkUser(login: String, password: String) { createServer(rootToken!!, null).use { server -> server.openSvnRepository(login, password).latestRevision } } private fun createServer(token: GitLabToken, mappingConfigCreator: Function<Path, RepositoryMappingConfig>?): SvnTestServer { val gitLabConfig = GitLabConfig(gitlabUrl!!, token) return SvnTestServer.createEmpty(GitLabUserDBConfig(), mappingConfigCreator, false, SvnTestServer.LfsMode.None, gitLabConfig, WebServerConfig()) } @Test fun invalidPassword() { Assert.expectThrows(SVNAuthenticationException::class.java) { checkUser(root, "wrongpassword") } } @Test fun invalidUser() { Assert.expectThrows(SVNAuthenticationException::class.java) { checkUser("wronguser", rootPassword) } } @Test fun gitlabMappingAsRoot() { createServer(rootToken!!) { dir: Path? -> GitLabMappingConfig(dir!!, GitCreateMode.EMPTY) }.use { server -> openSvnRepository(server, gitlabProject!!, user, userPassword).latestRevision } } private fun openSvnRepository(server: SvnTestServer, gitlabProject: GitlabProject, username: String, password: String): SVNRepository { return SvnTestServer.openSvnRepository(server.getUrl(false).appendPath(gitlabProject.pathWithNamespace + "/master", false), username, password) } @Test fun testLfs() { val storage = GitLabConfig.createLfsStorage(gitlabUrl!!, gitlabProject!!.pathWithNamespace, root, rootPassword, null) val user = User.create(root, root, root, root, UserType.GitLab, LfsCredentials(root, rootPassword)) LfsLocalStorageTest.checkLfs(storage, user) LfsLocalStorageTest.checkLfs(storage, user) LfsLocalStorageTest.checkLocks(storage, user) } @Test fun gitlabMappingForAnonymous() { createServer(rootToken!!) { dir: Path? -> GitLabMappingConfig(dir!!, GitCreateMode.EMPTY) }.use { server -> openSvnRepository(server, gitlabPublicProject!!, "nobody", "nopassword").latestRevision } } /** * Test for #119. */ @Ignore @Test fun gitlabMappingAsUser() { val userToken = createToken(user, userPassword, false) createServer(userToken) { dir: Path? -> GitLabMappingConfig(dir!!, GitCreateMode.EMPTY) }.use { server -> openSvnRepository(server, gitlabProject!!, root, rootPassword).latestRevision } } private class WaitForChefComplete : AbstractWaitStrategy() { override fun waitUntilReady() { Unreliables.retryUntilSuccess(startupTimeout.seconds.toInt(), TimeUnit.SECONDS) { rateLimiter.doWhenReady { try { val execResult = waitStrategyTarget.execInContainer("grep", "-R", "-E", "Chef.* Run complete", "/var/log/gitlab/reconfigure/") if (execResult.exitCode != 0) { throw RuntimeException("Not ready") } } catch (e: IOException) { throw RuntimeException(e) } catch (e: InterruptedException) { throw RuntimeException(e) } } true } } } companion object { private const val root = "root" private const val rootPassword = "12345678" private const val user = "git-as-svn" private const val userPassword = "git-as-svn" } }
gpl-2.0
7fbe7f0ca60cfbda138ac0e3ed12927a
44.465347
205
0.694142
4.394258
false
true
false
false
is00hcw/anko
preview/intentions/src/org/jetbrains/anko/idea/intentions/ToastMakeTextShowIntention.kt
2
2404
/* * Copyright 2010-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.anko.idea.intentions import org.jetbrains.kotlin.psi.* public class ToastMakeTextShowIntention : AnkoIntention<JetExpression>(JetExpression::class.java, "Simplify Toast.makeText().show() with Anko") { override fun isApplicableTo(element: JetExpression, caretOffset: Int): Boolean { return element.require<JetDotQualifiedExpression> { receiver.require<JetDotQualifiedExpression> { receiver.require<JetReferenceExpression>("Toast") && selector.requireCall("makeText", 3) { isLongToast() != null && isValueParameterTypeOf(0, null, FqNames.CONTEXT_FQNAME) } } && selector.requireCall("show", 0) } } private fun JetCallExpression.isLongToast(): Boolean? { return when (valueArguments[2].getText()) { "Toast.LENGTH_SHORT", "LENGTH_SHORT" -> false "Toast.LENGTH_LONG", "LENGTH_LONG" -> true else -> null } } override fun replaceWith(element: JetExpression, psiFactory: JetPsiFactory): NewElement? { element.require<JetDotQualifiedExpression> { receiver.require<JetDotQualifiedExpression> { selector.requireCall("makeText") { val args = valueArguments val ctxArg = args[0].text val textArg = args[1].text val funName = if (isLongToast()!!) "longToast" else "toast" val receiver = if (ctxArg == "this") "" else ".$ctxArg" val newExpression = psiFactory.createExpression("$receiver$funName($textArg)") return NewElement(newExpression, funName) } } } return null } }
apache-2.0
df3f105831a2630aa52e2e1651428bfb
37.774194
145
0.625208
4.732283
false
false
false
false
bozaro/git-as-svn
src/main/kotlin/svnserver/ext/gitea/mapping/GiteaMapping.kt
1
2664
/* * This file is part of git-as-svn. It is subject to the license terms * in the LICENSE file found in the top-level directory of this distribution * and at http://www.gnu.org/licenses/gpl-2.0.html. No part of git-as-svn, * including this file, may be copied, modified, propagated, or distributed * except according to the terms contained in the LICENSE file. */ package svnserver.ext.gitea.mapping import io.gitea.model.Repository import svnserver.StringHelper import svnserver.config.ConfigHelper import svnserver.context.LocalContext import svnserver.context.SharedContext import svnserver.repository.RepositoryMapping import svnserver.repository.VcsAccess import java.io.IOException import java.util.* import java.util.concurrent.ConcurrentSkipListMap /** * Simple repository mapping by predefined list. * * @author Artem V. Navrotskiy <[email protected]> * @author Andrew Thornton <[email protected]> */ internal class GiteaMapping(val context: SharedContext, private val config: GiteaMappingConfig) : RepositoryMapping<GiteaProject> { override val mapping: NavigableMap<String, GiteaProject> = ConcurrentSkipListMap() @Throws(IOException::class) fun addRepository(repository: Repository): GiteaProject? { val projectName = repository.fullName val projectKey = StringHelper.normalizeDir(projectName) val oldProject = mapping[projectKey] if (oldProject == null || oldProject.projectId != repository.id) { val basePath = ConfigHelper.joinPath(context.basePath, config.path) // the repository name is lowercased as per gitea cmd/serv.go:141 val repoPath = ConfigHelper.joinPath(basePath, repository.fullName.lowercase() + ".git") val local = LocalContext(context, repository.fullName) local.add(VcsAccess::class.java, GiteaAccess(local, config, repository)) val vcsRepository = config.template.create(local, repoPath) val newProject = GiteaProject(local, vcsRepository, repository.id, repository.owner.login, projectName) if (mapping.compute(projectKey) { _: String?, value: GiteaProject? -> if (value != null && value.projectId == repository.id) value else newProject } == newProject) { return newProject } } return null } fun removeRepository(projectName: String) { val projectKey = StringHelper.normalizeDir(projectName) val project = mapping[projectKey] if (project != null) { if (mapping.remove(projectKey, project)) { project.close() } } } }
gpl-2.0
9fb2a77b3e4fbf7c7d9f5c1c3224ca81
44.152542
177
0.707958
4.276083
false
true
false
false
pennlabs/penn-mobile-android
PennMobile/src/main/java/com/pennapps/labs/pennmobile/classes/Contact.kt
1
575
package com.pennapps.labs.pennmobile.classes /** * Created by Adel on 12/16/14. * Class for a Person from Directory */ class Contact { var name: String var phone: String var phoneWords: String constructor(name: String, phone: String) { this.name = name this.phone = phone this.phoneWords = "" } constructor(name: String, phone: String, phone_words: String) { this.name = name this.phone = phone this.phoneWords = phone_words } val isURL: Boolean get() = phone.startsWith("http") }
mit
19645e11e52f932a61cc39f6b9bf578b
21.153846
67
0.613913
3.885135
false
false
false
false
matejdro/WearMusicCenter
mobile/src/main/java/com/matejdro/wearmusiccenter/view/settings/MiscSettingsFragment.kt
1
7750
package com.matejdro.wearmusiccenter.view.settings import android.Manifest import android.content.ComponentName import android.content.DialogInterface import android.content.Intent import android.content.SharedPreferences import android.content.pm.PackageManager import android.net.Uri import android.os.Build import android.os.Bundle import android.service.notification.NotificationListenerService import androidx.appcompat.app.AlertDialog import androidx.lifecycle.lifecycleScope import androidx.preference.ListPreference import androidx.preference.Preference import com.matejdro.wearmusiccenter.NotificationService import com.matejdro.wearmusiccenter.R import com.matejdro.wearmusiccenter.common.CommPaths import com.matejdro.wearmusiccenter.common.MiscPreferences import com.matejdro.wearmusiccenter.common.model.AutoStartMode import com.matejdro.wearmusiccenter.util.launchWithPlayServicesErrorHandling import com.matejdro.wearutils.logging.LogRetrievalTask import com.matejdro.wearutils.preferences.compat.PreferenceFragmentCompatEx import com.matejdro.wearutils.preferences.definition.Preferences import com.matejdro.wearutils.preferencesync.PreferencePusher import de.psdev.licensesdialog.LicensesDialog class MiscSettingsFragment : PreferenceFragmentCompatEx(), SharedPreferences.OnSharedPreferenceChangeListener { companion object { private const val VIBRATION_CENTER_PACKAGE = "com.matejdro.wearvibrationcenter" } override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) { addPreferencesFromResource(R.xml.settings) initAutomationSection() initNotificationsSection() initAboutSection() } private fun initAutomationSection() { migrateOldAutoStartSetting() findPreference<Preference>("auto_start_apps_blacklist")?.isEnabled = Preferences.getEnum(preferenceManager.sharedPreferences, MiscPreferences.AUTO_START_MODE) != AutoStartMode.OFF findPreference<Preference>("auto_start_mode")!!.onPreferenceChangeListener = Preference.OnPreferenceChangeListener { _, newValue -> newValue as String val mode = enumValueOf<AutoStartMode>(newValue) findPreference<Preference>("auto_start_apps_blacklist")?.isEnabled = mode != AutoStartMode.OFF // On Android N and above we unbind notification service when autostart is disabled and // rebind when enabled if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { if (newValue != AutoStartMode.OFF) { NotificationListenerService.requestRebind( ComponentName(requireContext(), NotificationService::class.java) ) } else { val serviceStopIntent = Intent(requireContext(), NotificationService::class.java) serviceStopIntent.action = NotificationService.ACTION_UNBIND_SERVICE requireContext().startService(serviceStopIntent) } } true } } private fun migrateOldAutoStartSetting() { val preferences = preferenceManager.sharedPreferences!! if (preferences.contains("auto_start")) { val legacyAutoStart = Preferences.getBoolean(preferences, MiscPreferences.AUTO_START) val autoStartMode = if (legacyAutoStart) AutoStartMode.OPEN_APP else AutoStartMode.OFF findPreference<ListPreference>("auto_start_mode")?.value = autoStartMode.name preferences.edit().remove("auto_start").apply() } } private fun initNotificationsSection() { findPreference<Preference>("enable_notification_popup")!!.onPreferenceChangeListener = Preference.OnPreferenceChangeListener { _: Preference, value: Any -> if (value == false) { return@OnPreferenceChangeListener true } if (!isVibrationCenterInstalledAndEnabled()) { AlertDialog.Builder(requireContext()) .setTitle(R.string.app_required) .setMessage(R.string.vibration_center_required_description) .setNegativeButton(android.R.string.cancel, null) .setPositiveButton(R.string.open_play_store) { _: DialogInterface, _: Int -> openVibrationCenterPlayStore() } .show() return@OnPreferenceChangeListener false } true } } private fun initAboutSection() { findPreference<Preference>("supportButton")!!.onPreferenceClickListener = Preference.OnPreferenceClickListener { sendLogs() true } try { findPreference<Preference>("version")!!.summary = requireActivity().packageManager.getPackageInfo(requireActivity().packageName, 0).versionName } catch (ignored: PackageManager.NameNotFoundException) { } findPreference<Preference>("licenses")!!.onPreferenceClickListener = Preference.OnPreferenceClickListener { LicensesDialog.Builder(activity) .setNotices(R.raw.notices) .setIncludeOwnLicense(true) .build() .show() true } } private fun isVibrationCenterInstalledAndEnabled(): Boolean { return try { val appInfo = requireContext().packageManager.getApplicationInfo(VIBRATION_CENTER_PACKAGE, 0) appInfo.enabled } catch (e: PackageManager.NameNotFoundException) { false } } private fun openVibrationCenterPlayStore() { try { startActivity(Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=$VIBRATION_CENTER_PACKAGE"))) } catch (_: android.content.ActivityNotFoundException) { startActivity(Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=$VIBRATION_CENTER_PACKAGE"))) } } private fun sendLogs() { LogRetrievalTask(activity, CommPaths.MESSAGE_SEND_LOGS, "[email protected]", "com.matejdro.wearmusiccenter.logs").execute(null as Void?) } override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) { super.onRequestPermissionsResult(requestCode, permissions, grantResults) if (permissions.isNotEmpty() && permissions[0] == Manifest.permission.WRITE_EXTERNAL_STORAGE && grantResults[0] == PackageManager.PERMISSION_GRANTED) { sendLogs() } } override fun onStart() { super.onStart() preferenceManager.sharedPreferences!!.registerOnSharedPreferenceChangeListener(this) } override fun onStop() { super.onStop() preferenceManager.sharedPreferences!!.unregisterOnSharedPreferenceChangeListener(this) } override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences?, key: String?) { pushPreferencesToWatch() } private fun pushPreferencesToWatch() { lifecycleScope.launchWithPlayServicesErrorHandling(requireContext().applicationContext) { PreferencePusher.pushPreferences( requireContext().applicationContext, preferenceManager.sharedPreferences!!, CommPaths.PREFERENCES_PREFIX, false ) } } }
gpl-3.0
fb3f2ae4d508c2113226523706208c76
39.364583
163
0.65871
5.800898
false
false
false
false
SapuSeven/BetterUntis
app/src/main/java/com/sapuseven/untis/models/untis/masterdata/EventReason.kt
1
1687
package com.sapuseven.untis.models.untis.masterdata import android.content.ContentValues import android.database.Cursor import com.sapuseven.untis.annotations.Table import com.sapuseven.untis.annotations.TableColumn import com.sapuseven.untis.data.databases.TABLE_NAME_EVENT_REASONS import com.sapuseven.untis.interfaces.TableModel import kotlinx.serialization.Serializable @Serializable @Table(TABLE_NAME_EVENT_REASONS) data class EventReason( @field:TableColumn("INTEGER NOT NULL") val id: Int, @field:TableColumn("VARCHAR(255) NOT NULL") val name: String, @field:TableColumn("VARCHAR(255) NOT NULL") val longName: String, @field:TableColumn("VARCHAR(255) NOT NULL") val elementType: String, @field:TableColumn("INTEGER NOT NULL") val groupId: Int, @field:TableColumn("BOOLEAN NOT NULL") val active: Boolean ) : TableModel { companion object { const val TABLE_NAME = TABLE_NAME_EVENT_REASONS } override val tableName = TABLE_NAME override val elementId = id override fun generateValues(): ContentValues { val values = ContentValues() values.put("id", id) values.put("name", name) values.put("longName", longName) values.put("elementType", elementType) values.put("groupId", groupId) values.put("active", active) return values } override fun parseCursor(cursor: Cursor): TableModel { return EventReason( cursor.getInt(cursor.getColumnIndex("id")), cursor.getString(cursor.getColumnIndex("name")), cursor.getString(cursor.getColumnIndex("longName")), cursor.getString(cursor.getColumnIndex("elementType")), cursor.getInt(cursor.getColumnIndex("groupId")), cursor.getInt(cursor.getColumnIndex("active")) != 0 ) } }
gpl-3.0
91cc9dc59a6cf2dceccb4e89fadbfe57
32.078431
70
0.757558
3.791011
false
false
false
false
Popalay/Cardme
presentation/src/main/kotlin/com/popalay/cardme/presentation/screens/Adapters.kt
1
2630
package com.popalay.cardme.presentation.screens import android.databinding.BindingAdapter import android.databinding.Observable import android.databinding.ObservableBoolean import android.support.v7.widget.RecyclerView import com.github.nitrico.lastadapter.ItemType import com.github.nitrico.lastadapter.LastAdapter import com.jakewharton.rxrelay2.Relay import com.popalay.cardme.BR import com.popalay.cardme.R import com.popalay.cardme.data.models.Card import com.popalay.cardme.data.models.Debt import com.popalay.cardme.data.models.Holder import com.popalay.cardme.databinding.ItemCardBinding import com.popalay.cardme.databinding.ItemHolderBinding typealias LastAdapterHolder<V> = com.github.nitrico.lastadapter.Holder<V> @BindingAdapter(value = *arrayOf("cardsAdapter", "cardClick", "showImage"), requireAll = false) fun RecyclerView.cardsAdapter(items: List<Card>?, publisher: Relay<Card>?, showImage: ObservableBoolean?) { if (this.adapter != null || items == null || items.isEmpty()) return LastAdapter(items, BR.item) .map<Card>(object : ItemType<ItemCardBinding>(R.layout.item_card) { override fun onCreate(holder: LastAdapterHolder<ItemCardBinding>) { super.onCreate(holder) holder.binding.publisher = publisher holder.binding.cardView.isWithImage = showImage?.get() ?: false showImage?.addOnPropertyChangedCallback(object : Observable.OnPropertyChangedCallback() { override fun onPropertyChanged(observable: Observable, i: Int) { holder.binding.cardView.isWithImage = showImage.get() } }) } }).into(this) } @BindingAdapter("debtsAdapter") fun RecyclerView.debtsAdapter(items: List<Debt>?) { if (this.adapter != null || items == null || items.isEmpty()) return LastAdapter(items, BR.item) .map<Debt>(R.layout.item_debt) .into(this) } @BindingAdapter(value = *arrayOf("holdersAdapter", "holderClick"), requireAll = false) fun RecyclerView.holdersAdapter(items: List<Holder>?, publisher: Relay<Holder>?) { if (this.adapter != null || items == null || items.isEmpty()) return LastAdapter(items, BR.item) .map<Holder>(object : ItemType<ItemHolderBinding>(R.layout.item_holder) { override fun onCreate(holder: LastAdapterHolder<ItemHolderBinding>) { super.onCreate(holder) holder.binding.publisher = publisher } }) .into(this) }
apache-2.0
33c77fd6df94c3abf602383f3609a6a8
43.576271
109
0.673384
4.480409
false
false
false
false
gmariotti/intro-big-data
04_potential-friends/src/main/kotlin/PotentialFriendsReducer.kt
1
856
import common.hadoop.extensions.split import common.hadoop.extensions.toText import org.apache.hadoop.io.Text import org.apache.hadoop.mapreduce.Reducer class PotentialFriendsReducer : Reducer<Text, Text, Text, Text>() { private val friends = mutableMapOf<String, List<String>>() public override fun reduce(key: Text, values: Iterable<Text>, context: Context) { this.friends[key.toString()] = values.flatMap { it.split(",") }.distinct() } public override fun cleanup(context: Context) { friends.forEach { entry -> val potentialFriends = friends.filter { it != entry } .asSequence() .filter { !entry.value.contains(it.key) } .filter { it.value.any { user -> entry.value.contains(user) } } .map { it.key } .toList() context.write(entry.key.toText(), potentialFriends.joinToString(separator = ",").toText()) } } }
mit
9ec3d856dc965901f2f900cf3be5eb39
33.28
93
0.699766
3.522634
false
false
false
false
Undin/intellij-rust
src/main/kotlin/org/rust/ide/template/postfix/MatchPostfixTemplate.kt
3
5239
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.ide.template.postfix import com.intellij.codeInsight.template.TemplateResultListener import com.intellij.codeInsight.template.postfix.templates.PostfixTemplateWithExpressionSelector import com.intellij.openapi.editor.Editor import com.intellij.psi.PsiDocumentManager import com.intellij.psi.PsiElement import org.rust.ide.inspections.fixes.AddRemainingArmsFix import org.rust.ide.inspections.fixes.AddWildcardArmFix import org.rust.ide.utils.checkMatch.checkExhaustive import org.rust.ide.utils.template.buildAndRunTemplate import org.rust.lang.core.psi.* import org.rust.lang.core.psi.ext.RsElement import org.rust.lang.core.psi.ext.descendantsOfType import org.rust.lang.core.resolve.knownItems import org.rust.lang.core.types.ty.Ty import org.rust.lang.core.types.ty.TyAdt import org.rust.lang.core.types.ty.TyReference import org.rust.lang.core.types.ty.TyStr import org.rust.lang.core.types.type import org.rust.openapiext.createSmartPointer class MatchPostfixTemplate(provider: RsPostfixTemplateProvider) : PostfixTemplateWithExpressionSelector( null, "match", "match expr {...}", RsExprParentsSelector(), provider ) { override fun expandForChooseExpression(expression: PsiElement, editor: Editor) { if (expression !is RsExpr) return val project = expression.project val factory = RsPsiFactory(project) val type = expression.type val processor = getMatchProcessor(type, expression) val match = processor.createMatch(factory, expression) val matchExpr = expression.replace(match) as RsMatchExpr PsiDocumentManager.getInstance(project).doPostponedOperationsAndUnblockDocument(editor.document) processor.normalizeMatch(matchExpr) PsiDocumentManager.getInstance(project).doPostponedOperationsAndUnblockDocument(editor.document) val matchBody = matchExpr.matchBody ?: return val arm = matchBody.matchArmList.firstOrNull() ?: return val blockExpr = arm.expr as? RsBlockExpr ?: return val toBeReplaced = processor.getElementsToReplace(matchBody) if (toBeReplaced.isEmpty()) { moveCaretToMatchArmBlock(editor, blockExpr) } else { val blockExprPointer = blockExpr.createSmartPointer() editor.buildAndRunTemplate( matchBody, toBeReplaced.map { it.createSmartPointer() }, TemplateResultListener { if (it == TemplateResultListener.TemplateResult.Finished) { val restoredBlockExpr = blockExprPointer.element ?: return@TemplateResultListener moveCaretToMatchArmBlock(editor, restoredBlockExpr) } } ) } } private fun moveCaretToMatchArmBlock(editor: Editor, blockExpr: RsBlockExpr) { editor.caretModel.moveToOffset(blockExpr.block.lbrace.textOffset + 1) } } private fun getMatchProcessor(ty: Ty, context: RsElement): MatchProcessor { return when { ty is TyAdt && ty.item == context.knownItems.String -> StringMatchProcessor ty is TyReference && ty.referenced is TyStr -> StringLikeMatchProcessor() else -> GenericMatchProcessor } } private abstract class MatchProcessor { abstract fun createMatch(factory: RsPsiFactory, expression: RsExpr): RsMatchExpr open fun normalizeMatch(matchExpr: RsMatchExpr) {} open fun getElementsToReplace(matchBody: RsMatchBody): List<RsElement> = emptyList() } private object GenericMatchProcessor : MatchProcessor() { override fun createMatch(factory: RsPsiFactory, expression: RsExpr): RsMatchExpr { val exprText = if (expression is RsStructLiteral) "(${expression.text})" else expression.text return factory.createExpression("match $exprText {}") as RsMatchExpr } override fun normalizeMatch(matchExpr: RsMatchExpr) { val patterns = matchExpr.checkExhaustive().orEmpty() val fix = if (patterns.isEmpty()) { AddWildcardArmFix(matchExpr) } else { AddRemainingArmsFix(matchExpr, patterns) } fix.invoke(matchExpr.project, matchExpr.containingFile, matchExpr, matchExpr) } override fun getElementsToReplace(matchBody: RsMatchBody): List<RsElement> = matchBody.descendantsOfType<RsPatWild>().toList() } private open class StringLikeMatchProcessor : MatchProcessor() { open fun expressionToText(expression: RsExpr): String = expression.text override fun createMatch(factory: RsPsiFactory, expression: RsExpr): RsMatchExpr { val exprText = expressionToText(expression) return factory.createExpression("match $exprText {\n\"\" => {}\n_ => {} }") as RsMatchExpr } override fun getElementsToReplace(matchBody: RsMatchBody): List<RsElement> = listOfNotNull(matchBody.matchArmList.getOrNull(0)?.pat as? RsPatConst) } private object StringMatchProcessor : StringLikeMatchProcessor() { override fun expressionToText(expression: RsExpr): String = "${expression.text}.as_str()" }
mit
d5fdc882e438435c4dddb3131bf0ab4c
38.689394
105
0.717122
4.728339
false
false
false
false
MeilCli/Twitter4HK
library/src/main/kotlin/com/twitter/meil_mitu/twitter4hk/api/directmessages/DirectMessagesAPI.kt
1
626
package com.twitter.meil_mitu.twitter4hk.api.directmessages import com.twitter.meil_mitu.twitter4hk.AbsAPI import com.twitter.meil_mitu.twitter4hk.AbsOauth import com.twitter.meil_mitu.twitter4hk.converter.api.IDirectMessagesConverter class DirectMessagesAPI<TDirectMessage>( oauth: AbsOauth, protected val json: IDirectMessagesConverter<TDirectMessage>) : AbsAPI(oauth) { fun sent() = Sent(oauth, json) fun show(id: Long) = Show(oauth, json, id) fun get() = Get(oauth, json) fun destroy(id: Long) = Destroy(oauth, json, id) fun postNew(text: String) = PostNew(oauth, json, text) }
mit
59c7a47bb3fb0abd797a80bda88ae945
28.809524
87
0.731629
3.347594
false
false
false
false
satamas/fortran-plugin
src/main/kotlin/org/jetbrains/fortran/ide/FortranCodeModificationListener.kt
1
1528
package org.jetbrains.fortran.ide import com.intellij.openapi.project.Project import com.intellij.pom.PomManager import com.intellij.pom.PomModelAspect import com.intellij.pom.event.PomModelEvent import com.intellij.pom.event.PomModelListener import com.intellij.pom.tree.TreeAspect import com.intellij.pom.tree.events.TreeChangeEvent import com.intellij.psi.impl.PsiModificationTrackerImpl import com.intellij.psi.util.PsiModificationTracker import org.jetbrains.fortran.lang.psi.FortranFile class FortranCodeModificationListener( modificationTracker: PsiModificationTracker, project: Project, private val treeAspect: TreeAspect ) { init { val model = PomManager.getModel(project) @Suppress("NAME_SHADOWING") val modificationTracker = modificationTracker as PsiModificationTrackerImpl model.addModelListener(object: PomModelListener { override fun isAspectChangeInteresting(aspect: PomModelAspect): Boolean { return aspect == treeAspect } override fun modelChanged(event: PomModelEvent) { val changeSet = event.getChangeSet(treeAspect) as TreeChangeEvent? ?: return val file = changeSet.rootElement.psi.containingFile as? FortranFile ?: return if (changeSet.changedElements.isNotEmpty()) { if (file.isPhysical) { modificationTracker.incCounter() } } } }) } }
apache-2.0
787b9bdc85d5587d5a530b23dee83b36
37.2
93
0.687827
5.009836
false
false
false
false
jorjoluiso/QuijoteLui
src/main/kotlin/com/quijotelui/model/ReporteRetencion.kt
1
1165
package com.quijotelui.model import org.hibernate.annotations.Immutable import org.hibernate.annotations.Type import java.io.Serializable import java.util.* import javax.persistence.Column import javax.persistence.Entity import javax.persistence.Id import javax.persistence.Table @Entity @Immutable @Table(name = "v_ele_reporte_retenciones") class ReporteRetencion : Serializable { @Id @Column(name = "id") var id : Long? = null @Column(name = "codigo") var codigo : String? = null @Column(name = "numero") var numero : String? = null @Column(name = "establecimiento") var establecimiento : String? = null @Column(name = "punto_emision") var puntoEmision : String? = null @Column(name = "secuencial") var secuencial : String? = null @Column(name = "fecha") @Type(type="date") var fecha : Date? = null @Column(name = "documento") var documento : String? = null @Column(name = "razon_social") var razonSocial : String? = null @Column(name = "correo_electronico") var correo_electronico : String? = null @Column(name = "estado") var estado : String? = null }
gpl-3.0
ab71ad820997a54bc357ec1b04efcdb0
21.423077
43
0.670386
3.426471
false
false
false
false
googlemaps/android-maps-compose
maps-compose/src/main/java/com/google/maps/android/compose/MapApplier.kt
1
5483
// Copyright 2021 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.maps.android.compose import androidx.compose.runtime.AbstractApplier import com.google.android.gms.maps.GoogleMap import com.google.android.gms.maps.MapView import com.google.android.gms.maps.model.Circle import com.google.android.gms.maps.model.GroundOverlay import com.google.android.gms.maps.model.Marker import com.google.android.gms.maps.model.Polygon import com.google.android.gms.maps.model.Polyline internal interface MapNode { fun onAttached() {} fun onRemoved() {} fun onCleared() {} } private object MapNodeRoot : MapNode internal class MapApplier( val map: GoogleMap, private val mapView: MapView, ) : AbstractApplier<MapNode>(MapNodeRoot) { private val decorations = mutableListOf<MapNode>() init { attachClickListeners() } override fun onClear() { map.clear() decorations.forEach { it.onCleared() } decorations.clear() } override fun insertBottomUp(index: Int, instance: MapNode) { decorations.add(index, instance) instance.onAttached() } override fun insertTopDown(index: Int, instance: MapNode) { // insertBottomUp is preferred } override fun move(from: Int, to: Int, count: Int) { decorations.move(from, to, count) } override fun remove(index: Int, count: Int) { repeat(count) { decorations[index + it].onRemoved() } decorations.remove(index, count) } private fun attachClickListeners() { map.setOnCircleClickListener { decorations.nodeForCircle(it) ?.onCircleClick ?.invoke(it) } map.setOnGroundOverlayClickListener { decorations.nodeForGroundOverlay(it) ?.onGroundOverlayClick ?.invoke(it) } map.setOnPolygonClickListener { decorations.nodeForPolygon(it) ?.onPolygonClick ?.invoke(it) } map.setOnPolylineClickListener { decorations.nodeForPolyline(it) ?.onPolylineClick ?.invoke(it) } // Marker map.setOnMarkerClickListener { marker -> decorations.nodeForMarker(marker) ?.onMarkerClick ?.invoke(marker) ?: false } map.setOnInfoWindowClickListener { marker -> decorations.nodeForMarker(marker) ?.onInfoWindowClick ?.invoke(marker) } map.setOnInfoWindowCloseListener { marker -> decorations.nodeForMarker(marker) ?.onInfoWindowClose ?.invoke(marker) } map.setOnInfoWindowLongClickListener { marker -> decorations.nodeForMarker(marker) ?.onInfoWindowLongClick ?.invoke(marker) } map.setOnMarkerDragListener(object : GoogleMap.OnMarkerDragListener { override fun onMarkerDrag(marker: Marker) { with(decorations.nodeForMarker(marker)) { this?.markerState?.position = marker.position this?.markerState?.dragState = DragState.DRAG } } override fun onMarkerDragEnd(marker: Marker) { with(decorations.nodeForMarker(marker)) { this?.markerState?.position = marker.position this?.markerState?.dragState = DragState.END } } override fun onMarkerDragStart(marker: Marker) { with(decorations.nodeForMarker(marker)) { this?.markerState?.position = marker.position this?.markerState?.dragState = DragState.START } } }) map.setInfoWindowAdapter( ComposeInfoWindowAdapter( mapView, markerNodeFinder = { decorations.nodeForMarker(it) } ) ) } } private fun MutableList<MapNode>.nodeForCircle(circle: Circle): CircleNode? = firstOrNull { it is CircleNode && it.circle == circle } as? CircleNode private fun MutableList<MapNode>.nodeForMarker(marker: Marker): MarkerNode? = firstOrNull { it is MarkerNode && it.marker == marker } as? MarkerNode private fun MutableList<MapNode>.nodeForPolygon(polygon: Polygon): PolygonNode? = firstOrNull { it is PolygonNode && it.polygon == polygon } as? PolygonNode private fun MutableList<MapNode>.nodeForPolyline(polyline: Polyline): PolylineNode? = firstOrNull { it is PolylineNode && it.polyline == polyline } as? PolylineNode private fun MutableList<MapNode>.nodeForGroundOverlay( groundOverlay: GroundOverlay ): GroundOverlayNode? = firstOrNull { it is GroundOverlayNode && it.groundOverlay == groundOverlay } as? GroundOverlayNode
apache-2.0
37414936be732d97ca1145a7ca0a8112
33.055901
102
0.627576
4.730802
false
false
false
false
androidx/androidx
window/window/src/main/java/androidx/window/embedding/SplitPairFilter.kt
3
8693
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.window.embedding import android.app.Activity import android.content.ComponentName import android.content.Intent import android.util.Log import androidx.window.core.ActivityComponentInfo import androidx.window.embedding.MatcherUtils.areComponentsMatching import androidx.window.embedding.MatcherUtils.isIntentMatching import androidx.window.embedding.MatcherUtils.sDebugMatchers import androidx.window.embedding.MatcherUtils.sMatchersTag /** * Filter for [SplitPairRule] and used to find if a pair of activities should be put in a split. * It is used when a new activity is started from the primary activity. * If the filter matches the primary [Activity.getComponentName] and the new started activity * [Intent], it matches the [SplitPairRule] that holds this filter. * * @param primaryActivityName Component name of the primary activity in the split. Must be * non-empty. Can contain a single wildcard at the end. * Supported formats: * - package/class * - `package/*` * - `package/suffix.*` * - `*/*` * @param secondaryActivityName Component name of the secondary activity in the split. Must be * non-empty. Can contain a single wildcard at the end. * Supported formats: * - package/class * - `package/*` * - `package/suffix.*` * - `*/*` * @param secondaryActivityIntentAction action used for secondary activity launch Intent. If it is * not `null`, the [SplitPairFilter] will check the activity [Intent.getAction] besides the * component name. If it is `null`, [Intent.getAction] will be ignored. */ class SplitPairFilter( /** * Component name of the primary activity in the split. Must be non-empty. Can contain a single * wildcard at the end. * Supported formats: * - package/class * - `package/*` * - `package/suffix.*` * - `*/*` */ val primaryActivityName: ComponentName, /** * Component name of the secondary activity in the split. Must be non-empty. Can contain a * single wildcard at the end. * Supported formats: * - package/class * - `package/*` * - `package/suffix.*` * - `*/*` */ val secondaryActivityName: ComponentName, /** * Action used for secondary activity launch Intent. * * If it is not `null`, the [SplitPairFilter] will check the activity [Intent.getAction] besides * the component name. If it is `null`, [Intent.getAction] will be ignored. */ val secondaryActivityIntentAction: String? ) { private val secondaryActivityInfo: ActivityComponentInfo get() = ActivityComponentInfo(secondaryActivityName) /** * Returns `true` if this [SplitPairFilter] matches [primaryActivity] and [secondaryActivity]. * If the [SplitPairFilter] is created with [secondaryActivityIntentAction], the filter will * also compare it with [Intent.getAction] of [Activity.getIntent] of [secondaryActivity]. * * @param primaryActivity the [Activity] to test against with the [primaryActivityName] * @param secondaryActivity the [Activity] to test against with the [secondaryActivityName] */ fun matchesActivityPair(primaryActivity: Activity, secondaryActivity: Activity): Boolean { // Check if the activity component names match var match = areComponentsMatching(primaryActivity.componentName, primaryActivityName) && areComponentsMatching(secondaryActivity.componentName, secondaryActivityName) // If the intent is not empty - check that the rest of the filter fields match if (secondaryActivity.intent != null) { match = match && matchesActivityIntentPair(primaryActivity, secondaryActivity.intent) } if (sDebugMatchers) { val matchString = if (match) "MATCH" else "NO MATCH" Log.d( sMatchersTag, "Checking filter $this against activity pair: (${primaryActivity.componentName}, " + "${secondaryActivity.componentName}) - $matchString" ) } return match } /** * Returns `true` if this [SplitPairFilter] matches the [primaryActivity] and the * [secondaryActivityIntent] * If the [SplitPairFilter] is created with [secondaryActivityIntentAction], the filter will * also compare it with [Intent.getAction] of the [secondaryActivityIntent]. * * @param primaryActivity the [Activity] to test against with the [primaryActivityName] * @param secondaryActivityIntent the [Intent] to test against with the [secondaryActivityName] */ fun matchesActivityIntentPair( primaryActivity: Activity, secondaryActivityIntent: Intent ): Boolean { val inPrimaryActivityName = primaryActivity.componentName val match = if ( !areComponentsMatching(inPrimaryActivityName, primaryActivityName) ) { false } else if ( !isIntentMatching(secondaryActivityIntent, secondaryActivityInfo) ) { false } else { secondaryActivityIntentAction == null || secondaryActivityIntentAction == secondaryActivityIntent.action } if (sDebugMatchers) { val matchString = if (match) "MATCH" else "NO MATCH" Log.w( sMatchersTag, "Checking filter $this against activity-intent pair: " + "(${primaryActivity.componentName}, $secondaryActivityIntent) - $matchString" ) } return match } init { val primaryPackageName = primaryActivityName.packageName val primaryClassName = primaryActivityName.className val secondaryPackageName = secondaryActivityName.packageName val secondaryClassName = secondaryActivityName.className require( !(primaryPackageName.isEmpty() || secondaryPackageName.isEmpty()) ) { "Package name must not be empty" } require( !(primaryClassName.isEmpty() || secondaryClassName.isEmpty()) ) { "Activity class name must not be empty." } require( !( primaryPackageName.contains("*") && primaryPackageName.indexOf("*") != primaryPackageName.length - 1 ) ) { "Wildcard in package name is only allowed at the end." } require( !( primaryClassName.contains("*") && primaryClassName.indexOf("*") != primaryClassName.length - 1 ) ) { "Wildcard in class name is only allowed at the end." } require( !( secondaryPackageName.contains("*") && secondaryPackageName.indexOf("*") != secondaryPackageName.length - 1 ) ) { "Wildcard in package name is only allowed at the end." } require( !( secondaryClassName.contains("*") && secondaryClassName.indexOf("*") != secondaryClassName.length - 1 ) ) { "Wildcard in class name is only allowed at the end." } } override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is SplitPairFilter) return false if (primaryActivityName != other.primaryActivityName) return false if (secondaryActivityName != other.secondaryActivityName) return false if (secondaryActivityIntentAction != other.secondaryActivityIntentAction) return false return true } override fun hashCode(): Int { var result = primaryActivityName.hashCode() result = 31 * result + secondaryActivityName.hashCode() result = 31 * result + (secondaryActivityIntentAction?.hashCode() ?: 0) return result } override fun toString(): String { return "SplitPairFilter{primaryActivityName=$primaryActivityName, " + "secondaryActivityName=$secondaryActivityName, " + "secondaryActivityAction=$secondaryActivityIntentAction}" } }
apache-2.0
a1ef47b3693519f14c34fcfb1a84dac1
40.4
100
0.659611
4.861857
false
false
false
false
EventFahrplan/EventFahrplan
app/src/main/java/nerd/tuxmobil/fahrplan/congress/schedule/SessionViewDrawer.kt
1
6654
package nerd.tuxmobil.fahrplan.congress.schedule import android.content.Context import android.view.View import android.widget.ImageView import android.widget.TextView import androidx.annotation.ColorInt import androidx.annotation.ColorRes import androidx.core.content.ContextCompat import androidx.core.view.ViewCompat import androidx.core.view.isVisible import nerd.tuxmobil.fahrplan.congress.R import nerd.tuxmobil.fahrplan.congress.extensions.requireViewByIdCompat import nerd.tuxmobil.fahrplan.congress.models.Session import nerd.tuxmobil.fahrplan.congress.repositories.AppRepository import nerd.tuxmobil.fahrplan.congress.utils.Font import nerd.tuxmobil.fahrplan.congress.utils.TypefaceFactory internal class SessionViewDrawer @JvmOverloads constructor( context: Context, private val getSessionPadding: () -> Int, private val isAlternativeHighlightingEnabled: () -> Boolean = { // Must load the latest alternative highlighting value every time a session is redrawn. AppRepository.readAlternativeHighlightingEnabled() } ) { private val resources = context.resources private val boldCondensed = TypefaceFactory.getNewInstance(context).getTypeface(Font.Roboto.BoldCondensed) private val sessionDrawableInsetTop = resources.getDimensionPixelSize(R.dimen.session_drawable_inset_top) private val sessionDrawableInsetLeft = resources.getDimensionPixelSize(R.dimen.session_drawable_inset_left) private val sessionDrawableInsetRight = resources.getDimensionPixelSize(R.dimen.session_drawable_inset_right) private val sessionDrawableCornerRadius = resources.getDimensionPixelSize(R.dimen.session_drawable_corner_radius) private val sessionDrawableStrokeWidth = resources.getDimensionPixelSize(R.dimen.session_drawable_selection_stroke_width) private val sessionDrawableStrokeColor = ContextCompat.getColor(context, R.color.session_drawable_selection_stroke) private val sessionDrawableRippleColor = ContextCompat.getColor(context, R.color.session_drawable_ripple) private val trackNameBackgroundColorDefaultPairs = TrackBackgrounds.getTrackNameBackgroundColorDefaultPairs(context) private val trackNameBackgroundColorHighlightPairs = TrackBackgrounds.getTrackNameBackgroundColorHighlightPairs(context) fun updateSessionView(sessionView: View, session: Session) { val bell = sessionView.requireViewByIdCompat<ImageView>(R.id.session_bell_view) bell.isVisible = session.hasAlarm var textView = sessionView.requireViewByIdCompat<TextView>(R.id.session_title_view) textView.typeface = boldCondensed textView.text = session.title textView = sessionView.requireViewByIdCompat(R.id.session_subtitle_view) textView.text = session.subtitle textView.contentDescription = Session.getSubtitleContentDescription(sessionView.context, session.subtitle) textView = sessionView.requireViewByIdCompat(R.id.session_speakers_view) textView.text = session.formattedSpeakers textView.contentDescription = Session.getSpeakersContentDescription(sessionView.context, session.speakers.size, session.formattedSpeakers) textView = sessionView.requireViewByIdCompat(R.id.session_track_view) textView.text = session.formattedTrackLanguageText textView.contentDescription = Session.getFormattedTrackContentDescription(sessionView.context, session.track, session.lang) val recordingOptOut = sessionView.findViewById<View>(R.id.session_no_video_view) if (recordingOptOut != null) { recordingOptOut.isVisible = session.recordingOptOut } ViewCompat.setStateDescription(sessionView, Session.getHighlightContentDescription(sessionView.context, session.highlight)) setSessionBackground(session, sessionView) setSessionTextColor(session, sessionView) sessionView.tag = session } fun setSessionBackground(session: Session, sessionView: View) { val context = sessionView.context val sessionIsFavored = session.highlight @ColorRes val backgroundColorResId = if (sessionIsFavored) { trackNameBackgroundColorHighlightPairs[session.track] ?: R.color.track_background_highlight } else { trackNameBackgroundColorDefaultPairs[session.track] ?: R.color.track_background_default } @ColorInt val backgroundColor = ContextCompat.getColor(context, backgroundColorResId) val sessionDrawable = if (sessionIsFavored && isAlternativeHighlightingEnabled()) { SessionDrawable( backgroundColor, sessionDrawableCornerRadius.toFloat(), sessionDrawableRippleColor, sessionDrawableStrokeColor, sessionDrawableStrokeWidth.toFloat()) } else { SessionDrawable( backgroundColor, sessionDrawableCornerRadius.toFloat(), sessionDrawableRippleColor) } sessionDrawable.setLayerInset(SessionDrawable.BACKGROUND_LAYER_INDEX, sessionDrawableInsetLeft, sessionDrawableInsetTop, sessionDrawableInsetRight, 0) sessionDrawable.setLayerInset(SessionDrawable.STROKE_LAYER_INDEX, sessionDrawableInsetLeft, sessionDrawableInsetTop, sessionDrawableInsetRight, 0) ViewCompat.setBackground(sessionView, sessionDrawable) val padding = getSessionPadding() sessionView.setPadding(padding, padding, padding, padding) } companion object { const val LOG_TAG = "SessionViewDrawer" @JvmStatic fun setSessionTextColor(session: Session, view: View) { val title = view.requireViewByIdCompat<TextView>(R.id.session_title_view) val subtitle = view.requireViewByIdCompat<TextView>(R.id.session_subtitle_view) val speakers = view.requireViewByIdCompat<TextView>(R.id.session_speakers_view) val track = view.requireViewByIdCompat<TextView>(R.id.session_track_view) val colorResId = if (session.highlight) R.color.session_item_text_on_highlight_background else R.color.session_item_text_on_default_background val textColor = ContextCompat.getColor(view.context, colorResId) title.setTextColor(textColor) subtitle.setTextColor(textColor) speakers.setTextColor(textColor) track.setTextColor(textColor) } } }
apache-2.0
a642c2a29b544f7417ea2e44a5072355
52.669355
146
0.730989
5.079389
false
false
false
false
google/android-auto-companion-android
loggingsupport/tests/unit/src/com/google/android/libraries/car/loggingsupport/LoggingManagerTest.kt
1
4773
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.android.libraries.car.loggingsupport import android.content.Context import androidx.test.core.app.ApplicationProvider import androidx.test.ext.junit.runners.AndroidJUnit4 import com.google.android.companionprotos.LoggingMessageProto.LoggingMessage import com.google.android.companionprotos.LoggingMessageProto.LoggingMessage.MessageType import com.google.android.libraries.car.trustagent.Car import com.google.android.libraries.car.trustagent.util.LogRecord import com.google.gson.Gson import com.nhaarman.mockitokotlin2.any import com.nhaarman.mockitokotlin2.argumentCaptor import com.nhaarman.mockitokotlin2.eq import com.nhaarman.mockitokotlin2.mock import com.nhaarman.mockitokotlin2.verify import com.nhaarman.mockitokotlin2.whenever import java.io.File import java.util.UUID import org.junit.Before import org.junit.Test import org.junit.runner.RunWith /** Unit tests for the [LoggingManager] */ @RunWith(AndroidJUnit4::class) class LoggingManagerTest { private val testConnectedCar = UUID.randomUUID() private val mockCar: Car = mock() private val mockFileUtils: FileUtil = mock() private val mockListener: LoggingManager.OnLogFilesUpdatedListener = mock() private val context = ApplicationProvider.getApplicationContext<Context>() private lateinit var loggingManager: LoggingManager private val util = FileUtil() @Before fun setUp() { loggingManager = LoggingManager(context) loggingManager.util = mockFileUtils loggingManager.onLogFilesUpdatedListener = mockListener whenever(mockCar.deviceId).thenAnswer { testConnectedCar } loggingManager.notifyCarConnected(mockCar) } @Test fun onMessageReceived_sendRequest() { val mockLogRequestMessage = LogMessageUtil .createRequestMessage(LoggingManager.LOGGING_MESSAGE_VERSION) loggingManager.onMessageReceived(mockLogRequestMessage, testConnectedCar) argumentCaptor<ByteArray>().apply { verify(mockCar).sendMessage(capture(), eq(LoggingManager.FEATURE_ID)) val message = LoggingMessage.parseFrom(lastValue) assert(message.type == MessageType.LOG) } } @Test fun onMessageReceived_logMessage() { val receivedLogs = mockLogMessageReceived(5) verify(mockFileUtils).writeToFile(eq(receivedLogs), any(), any()) verify(mockListener).onLogFilesUpdated() } @Test fun getLogFiles() { loggingManager.loadLogFiles() verify(mockFileUtils).readFiles(any()) } @Test fun generateLogFile() { loggingManager.generateLogFile() verify(mockListener).onLogFilesUpdated() } @Test fun sendLogRequest() { loggingManager.sendLogRequest() argumentCaptor<ByteArray>().apply { verify(mockCar).sendMessage(capture(), eq(LoggingManager.FEATURE_ID)) val message = LoggingMessage.parseFrom(lastValue) assert(message.type == MessageType.START_SENDING) } } @Test fun removeOldLogFiles() { val logFiles = createRandomLogFiles(LoggingManager.LOG_FILES_MAX_NUM + 1) whenever(mockFileUtils.readFiles(any())).thenAnswer { logFiles } val receivedLogs = mockLogMessageReceived(5) verify(mockFileUtils).writeToFile(eq(receivedLogs), any(), any()) verify(logFiles[0]).delete() } private fun mockLogMessageReceived(size: Int): ByteArray { val mockReceivedLogs = createRandomLogRecords(size) val mockLogMessage = LogMessageUtil.createMessage( mockReceivedLogs, LoggingManager.LOGGING_MESSAGE_VERSION ) loggingManager.onMessageReceived(mockLogMessage, testConnectedCar) return mockReceivedLogs } private fun createRandomLogFiles(size: Int): List<File> { val logFiles = mutableListOf<File>() for (i in 1..size) { val file: File = mock() whenever(file.isFile).thenAnswer { true } whenever(file.lastModified()).thenAnswer { i.toLong() } logFiles.add(file) } return logFiles } private fun createRandomLogRecords(size: Int): ByteArray { val logRecords = mutableListOf<LogRecord>() var count = size for (i in 1..count) { logRecords.add(LogRecord(LogRecord.Level.INFO, "TEST_TAG", "TEST_MESSAGE")) } return Gson().toJson(logRecords).toByteArray() } }
apache-2.0
0a0e7ee234e38ef37b40040cfd1c35a6
34.095588
88
0.754243
4.315552
false
true
false
false
andstatus/andstatus
app/src/main/kotlin/org/andstatus/app/util/ViewUtils.kt
1
2829
/* * Copyright (c) 2016 yvolk (Yuri Volkov), http://yurivolkov.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.andstatus.app.util import android.app.Activity import android.view.View import android.view.ViewGroup.MarginLayoutParams /** * @author [email protected] */ object ViewUtils { fun getHeightWithMargins(view: View): Int { var height = view.measuredHeight if (MarginLayoutParams::class.java.isAssignableFrom(view.layoutParams.javaClass)) { val layoutParams = view.layoutParams as MarginLayoutParams if (height == 0) { height += layoutParams.height } height += layoutParams.topMargin + layoutParams.bottomMargin } return height } fun getWidthWithMargins(view: View): Int { var width = view.measuredWidth if (MarginLayoutParams::class.java.isAssignableFrom(view.layoutParams.javaClass)) { val layoutParams = view.layoutParams as MarginLayoutParams if (width == 0) { width += layoutParams.width } width += layoutParams.leftMargin + layoutParams.rightMargin } return width } /** * @return true if succeeded */ fun showView(activity: Activity?, viewId: Int, show: Boolean): Boolean { return activity != null && showView(activity.findViewById(viewId), show) } /** * @return true if succeeded */ fun showView(parentView: View?, viewId: Int, show: Boolean): Boolean { return parentView != null && showView(parentView.findViewById(viewId), show) } /** * @return true if succeeded */ fun showView(view: View?, show: Boolean): Boolean { if (view != null) { if (show) { if (view.visibility != View.VISIBLE) { view.setVisibility(View.VISIBLE) } } else { if (view.visibility != View.GONE) { view.setVisibility(View.GONE) } } } return view != null } fun isVisible(activity: Activity, viewId: Int): Boolean { val view = activity.findViewById<View?>(viewId) ?: return false return view.visibility == View.VISIBLE } }
apache-2.0
8cc5de96d637f492e1655adc01052110
31.895349
91
0.617533
4.683775
false
false
false
false
Tvede-dk/CommonsenseAndroidKotlin
base/src/main/kotlin/com/commonsense/android/kotlin/base/patterns/Observer.kt
1
735
@file:Suppress("unused", "NOTHING_TO_INLINE", "MemberVisibilityCanBePrivate") package com.commonsense.android.kotlin.base.patterns import com.commonsense.android.kotlin.base.* import com.commonsense.android.kotlin.base.extensions.collections.* /** * Created by kasper on 23/05/2017. * TODO remove / refactor make this more useable / accessible ? */ class ObserverPattern<T> { private var listOfListeners = mutableListOf<FunctionUnit<T>>() fun addListener(callback: FunctionUnit<T>) = listOfListeners.add(callback) fun removeListener(callback: FunctionUnit<T>) = listOfListeners.remove(callback) fun clearListeners() = listOfListeners.clear() fun notify(item: T) = listOfListeners.invokeEachWith(item) }
mit
85cfb9adf89347fb74c35d3cc2130bcc
28.44
84
0.759184
3.994565
false
false
false
false
Gnar-Team/Gnar-bot
src/main/kotlin/xyz/gnarbot/gnar/commands/admin/EvalCommand.kt
1
2232
package xyz.gnarbot.gnar.commands.admin import xyz.gnarbot.gnar.BotLoader import xyz.gnarbot.gnar.commands.* import xyz.gnarbot.gnar.utils.DiscordBotsVotes import javax.script.* @Command( aliases = ["eval"], description = "Run Groovy scripts." ) @BotInfo( id = 35, admin = true, category = Category.NONE ) class EvalCommand : CommandExecutor() { private val scriptEngines: Map<String, ScriptEngine> = ScriptEngineManager().let { mapOf( "js" to it.getEngineByName("javascript"), // "kt" to it.getEngineByName("kotlin"), "gv" to it.getEngineByName("groovy") ) } override fun execute(context: Context, label: String, args: Array<String>) { if (args.isEmpty()) { context.send().error("Available engines: `${scriptEngines.keys}`").queue() return } val scriptEngine = scriptEngines[args[0]] if (scriptEngine == null) { context.send().error("Not a valid engine: `${scriptEngines.keys}`.").queue() return } if (args.size == 1) { context.send().error("Script can not be empty.").queue() return } val script = args.copyOfRange(1, args.size).joinToString(" ") val variables = hashMapOf<String, Any>().apply { put("context", context) put("Bot", BotLoader.BOT) put("DiscordBotsVotes", DiscordBotsVotes::class.java) } val scope = SimpleScriptContext().apply { getBindings(ScriptContext.ENGINE_SCOPE).apply { variables.forEach { k, o -> this[k] = o } // if (args[0] == "kt") { // variables.forEach { k, _ -> script = "val $k = bindings[\"$k\"]\n$script" } // } } } val result = try { scriptEngine.eval(script, scope) } catch (e: ScriptException) { return context.send().exception(e).queue() } if (result != null) { context.send().text(result.toString()).queue() } else { context.message.addReaction("\uD83D\uDC4C").queue() } } }
mit
8570eca52359198cf0040ad3c06b61ae
29.589041
97
0.541219
4.219282
false
false
false
false
JavaEden/Orchid
OrchidCore/src/main/kotlin/com/eden/orchid/impl/compilers/markdown/MarkdownCompiler.kt
2
2412
package com.eden.orchid.impl.compilers.markdown import com.eden.orchid.api.compilers.OrchidCompiler import com.eden.orchid.api.options.annotations.Archetype import com.eden.orchid.api.options.archetypes.ConfigArchetype import com.eden.orchid.api.resources.resource.OrchidResource import com.vladsch.flexmark.ext.attributes.AttributesExtension import com.vladsch.flexmark.ext.attributes.FencedCodeAddType import com.vladsch.flexmark.ext.anchorlink.AnchorLinkExtension import com.vladsch.flexmark.html.HtmlRenderer import com.vladsch.flexmark.parser.Parser import com.vladsch.flexmark.util.ast.IRender import com.vladsch.flexmark.util.data.MutableDataSet import com.vladsch.flexmark.util.misc.Extension import java.io.OutputStream import java.io.OutputStreamWriter import javax.inject.Inject import javax.inject.Singleton @Singleton @JvmSuppressWildcards @Archetype(value = ConfigArchetype::class, key = "services.compilers.md") class MarkdownCompiler @Inject constructor( extensionSet: Set<Extension>, injectedOptions: Set<MutableDataSet> ) : OrchidCompiler(900) { private val parser: Parser private val renderer: IRender init { val options = MutableDataSet() options.set(HtmlRenderer.GENERATE_HEADER_ID, true) options.set(HtmlRenderer.RENDER_HEADER_ID, true) options.set(Parser.HTML_BLOCK_DEEP_PARSE_BLANK_LINE_INTERRUPTS, false) options.set(Parser.HTML_BLOCK_DEEP_PARSER, true) options.set(AnchorLinkExtension.ANCHORLINKS_WRAP_TEXT, false) options.set(AnchorLinkExtension.ANCHORLINKS_ANCHOR_CLASS, "anchor") options.set(AttributesExtension.FENCED_CODE_ADD_ATTRIBUTES, FencedCodeAddType.ADD_TO_PRE_CODE) options.set(Parser.EXTENSIONS, extensionSet) for (injectedOption in injectedOptions) { options.setAll(injectedOption) } parser = Parser.builder(options).build() renderer = HtmlRenderer.builder(options).build() } override fun compile(os: OutputStream, resource: OrchidResource?, extension: String, input: String, data: MutableMap<String, Any>?) { val writer = OutputStreamWriter(os) renderer.render(parser.parse(input), writer) writer.close() } override fun getOutputExtension(): String { return "html" } override fun getSourceExtensions(): Array<String> { return arrayOf("md", "markdown") } }
lgpl-3.0
233efcbd5ec3cf11ee86a24d23871856
35
137
0.750415
4.060606
false
false
false
false
wax911/AniTrendApp
app/src/main/java/com/mxt/anitrend/presenter/base/BasePresenter.kt
1
7337
package com.mxt.anitrend.presenter.base import android.content.Context import android.content.Intent import androidx.annotation.IdRes import androidx.fragment.app.FragmentActivity import com.annimon.stream.Stream import com.mxt.anitrend.R import com.mxt.anitrend.base.custom.async.WebTokenRequest import com.mxt.anitrend.base.custom.presenter.CommonPresenter import com.mxt.anitrend.model.entity.anilist.user.UserStatisticTypes import com.mxt.anitrend.model.entity.base.UserBase import com.mxt.anitrend.model.entity.crunchy.MediaContent import com.mxt.anitrend.model.entity.crunchy.Thumbnail import com.mxt.anitrend.service.TagGenreService import com.mxt.anitrend.util.CompatUtil import com.mxt.anitrend.util.migration.MigrationUtil import com.mxt.anitrend.util.migration.Migrations import timber.log.Timber import java.util.* import java.util.concurrent.TimeUnit /** * Created by max on 2017/09/16. * General presenter for most objects */ open class BasePresenter(context: Context?) : CommonPresenter(context) { private var favouriteGenres: List<String>? = null private var favouriteTags: List<String>? = null private var favouriteYears: List<String>? = null private var favouriteFormats: List<String>? = null @IdRes fun getNavigationItem(): Int { return when (settings.startupPage) { "0" -> R.id.nav_home_feed "1" -> R.id.nav_anime "2" -> R.id.nav_manga "3" -> R.id.nav_trending "4" -> R.id.nav_airing "5" -> R.id.nav_myanime "6" -> R.id.nav_mymanga "7" -> R.id.nav_hub "8" -> R.id.nav_reviews else -> R.id.nav_airing } } fun checkIfMigrationIsNeeded(): Boolean { if (!settings.isFreshInstall) { val migrationUtil = MigrationUtil.Builder() .addMigration(Migrations.MIGRATION_101_108) .addMigration(Migrations.MIGRATION_109_134) .addMigration(Migrations.MIGRATION_135_136) .build() return migrationUtil.applyMigration() } return true } fun checkGenresAndTags(fragmentActivity: FragmentActivity) { val intent = Intent(fragmentActivity, TagGenreService::class.java) fragmentActivity.startService(intent) } fun getThumbnail(thumbnails: List<Thumbnail>): String? { return if (CompatUtil.isEmpty(thumbnails)) null else thumbnails[0].url } fun getDuration(mediaContent: MediaContent): String { if (mediaContent.duration != null) { val timeSpan = Integer.valueOf(mediaContent.duration).toLong() val minutes = TimeUnit.SECONDS.toMinutes(timeSpan) val seconds = timeSpan - TimeUnit.MINUTES.toSeconds(minutes) return String.format(Locale.getDefault(), if (seconds < 10) "%d:0%d" else "%d:%d", minutes, seconds) } return "00:00" } fun getTopFavouriteGenres(limit: Int): List<String>? { if (CompatUtil.isEmpty(favouriteGenres)) { val userStats: UserStatisticTypes? = database.currentUser?.statistics if (database.currentUser != null && userStats != null) { if (!userStats.anime.genres.isNullOrEmpty()) { favouriteGenres = userStats.anime.genres .sortedByDescending { it.count }.filter { it.genre != null }.map { it.genre!! }.take(limit) } } } return favouriteGenres } fun getTopFavouriteTags(limit: Int): List<String>? { if (CompatUtil.isEmpty(favouriteTags)) { val userStats: UserStatisticTypes? = database.currentUser?.statistics if (database.currentUser != null && userStats != null) { if (!userStats.anime.tags.isNullOrEmpty()) { favouriteTags = Stream.of(userStats.anime.tags) .sortBy { (_, _, count) -> -count } .filter { (tag) -> tag != null } .map { (tag) -> tag!!.name } .limit(limit.toLong()).toList() favouriteTags = userStats.anime.tags.sortedByDescending { it.count }.filter { it.tag != null }.map { it.tag!!.name }.take(limit) } } } return favouriteTags } fun getTopFavouriteYears(limit: Int): List<String>? { if (CompatUtil.isEmpty(favouriteYears)) { val userStats: UserStatisticTypes? = database.currentUser?.statistics if (database.currentUser != null && userStats != null) { if (!userStats.anime.releaseYears.isNullOrEmpty()) { favouriteYears = userStats.anime.releaseYears .sortedByDescending { it.count }.filter { it.releaseYear != null }.map { it.releaseYear?.toString()!! }.take(limit) } } } return favouriteTags } fun getTopFormats(limit: Int): List<String>? { if (CompatUtil.isEmpty(favouriteFormats)) { val userStats: UserStatisticTypes? = database.currentUser?.statistics if (database.currentUser != null && userStats != null) { if (!userStats.anime.formats.isNullOrEmpty()) { favouriteFormats = userStats.anime.formats .sortedByDescending { it.count }.filter { it.format != null }.map { it.format!! }.take(limit) } } } return favouriteFormats } fun isCurrentUser(userId: Long): Boolean { return settings.isAuthenticated && database.currentUser != null && userId != 0L && database.currentUser?.id == userId } fun isCurrentUser(userName: String?): Boolean { return settings.isAuthenticated && database.currentUser != null && userName != null && database.currentUser?.name == userName } fun isCurrentUser(userId: Long, userName: String?): Boolean { return userName?.let { isCurrentUser(it) } ?: isCurrentUser(userId) } fun isCurrentUser(userBase: UserBase?): Boolean { return userBase != null && isCurrentUser(userBase.id) } fun checkValidAuth() { if (settings.isAuthenticated) { if (database.currentUser == null) { Timber.tag(TAG).w("Last attempt to authenticate failed, refreshing session!") WebTokenRequest.invalidateInstance(context) } } } companion object { private val TAG = BasePresenter::class.java.simpleName } }
lgpl-3.0
4f53991dcea9baed0790b5dd202f8fce
37.213542
112
0.553632
4.868613
false
false
false
false
PassionateWsj/YH-Android
app/src/main/java/com/intfocus/template/subject/nine/collectionlist/CollectionListActivity.kt
1
5155
package com.intfocus.template.subject.nine.collectionlist import android.animation.ObjectAnimator import android.os.Bundle import android.support.v4.content.ContextCompat import android.support.v7.widget.LinearLayoutManager import android.text.Editable import android.text.TextWatcher import android.view.View import android.view.animation.LinearInterpolator import com.intfocus.template.R import com.intfocus.template.listener.NoDoubleClickListener import com.intfocus.template.model.entity.Collection import com.intfocus.template.subject.nine.collectionlist.adapter.CollectionListAdapter import com.intfocus.template.ui.BaseActivity import com.intfocus.template.ui.view.DefaultRefreshView import com.intfocus.template.util.SnackbarUtil import com.lcodecore.tkrefreshlayout.RefreshListenerAdapter import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout import kotlinx.android.synthetic.main.activity_collection_list.* import kotlinx.android.synthetic.main.content_collection_list.* import java.util.* class CollectionListActivity : BaseActivity(), CollectionListContract.View { override lateinit var presenter: CollectionListContract.Presenter private lateinit var mAdapter: CollectionListAdapter private var startSync = false private var animator: ObjectAnimator? = null private var timer: Timer? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_collection_list) initView() initAdapter() initListener() initData() } private fun initView() { val headerView = DefaultRefreshView(this) headerView.setArrowResource(R.drawable.loading_up) refresh_collection_list_layout.setHeaderView(headerView) refresh_collection_list_layout.setEnableLoadmore(false) } private fun initListener() { fab_collection_list.setOnClickListener(object : NoDoubleClickListener() { override fun onNoDoubleClick(view: View) { startSync = !startSync if (startSync) { SnackbarUtil.shortSnackbar(view, "正在同步", ContextCompat.getColor(this@CollectionListActivity,R.color.co10_syr), ContextCompat.getColor(this@CollectionListActivity,R.color.co1_syr)) .show() timer = Timer() timer?.schedule(object : TimerTask() { override fun run() { runOnUiThread { startSyncAnim(view) } } }, 0, 1000) } else { SnackbarUtil.shortSnackbar(view, "取消同步", ContextCompat.getColor(this@CollectionListActivity,R.color.co10_syr), ContextCompat.getColor(this@CollectionListActivity,R.color.co11_syr)) .show() stopSyncAnim() } } }) edit_collection_list_search.addTextChangedListener(object : TextWatcher { override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) { } override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) { } override fun afterTextChanged(s: Editable?) { presenter.loadData(s.toString()) } }) refresh_collection_list_layout.setOnRefreshListener(object : RefreshListenerAdapter() { override fun onRefresh(refreshLayout: TwinklingRefreshLayout?) { super.onRefresh(refreshLayout) presenter.loadData() } }) } private fun startSyncAnim(view: View) { animator = ObjectAnimator.ofFloat(view, "rotation", 0f, 360f) animator?.interpolator = LinearInterpolator() animator?.duration = 1000 animator?.start() } private fun stopSyncAnim() { animator?.cancel() timer?.cancel() } private fun initAdapter() { mAdapter = CollectionListAdapter() mAdapter.openLoadAnimation() // 默认提供5种方法(渐显、缩放、从下到上,从左到右、从右到左) // mAdapter.openLoadAnimation(BaseQuickAdapter.SLIDEIN_LEFT) rv_collection_list.layoutManager = LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false) rv_collection_list.adapter = mAdapter } private fun initData() { CollectionListPresenter(CollectionListModelImpl.getInstance(), this) presenter.loadData() } override fun updateData(dataList: List<Collection>) { mAdapter.setNewData(dataList) finishRequest() } private fun finishRequest() { refresh_collection_list_layout.finishRefreshing() } override fun dismissActivity(v: View) { super.dismissActivity(v) stopSyncAnim() } }
gpl-3.0
6729e87c80bae4e451220df56ec6e11a
35.818841
105
0.639047
4.976494
false
false
false
false
PassionateWsj/YH-Android
app/src/main/java/com/intfocus/template/login/bean/DeviceRequest.kt
1
1416
package com.intfocus.template.login.bean /** * **************************************************** * author: JamesWong * created on: 17/08/11 上午10:26 * e-mail: [email protected] * name: * desc: * **************************************************** */ class DeviceRequest { /** * api_token : 75d2a2f04ed551ce1988c8d8f3b02241 * user_num : 13913778859 * device : {"uuid":"25525ea79879905bf2f492d3f52sdfasfbc15f3e3ac409c","os":"iPhonasdfe 6 (A1549/A1586)","name":"junjieasdfsdfasf的 iPhone💋","os_version":"9.2asdf.a1","platform":"ios"} * app_version : i1.3.0 * ip : 223.104.5.206 * browser : Mozilla/5.0 (iPhone; CPU iPhone OS 9_2_1 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Mobile/13D15 */ var api_token: String? = null var user_num: String? = null var device: DeviceBean? = null var app_version: String? = null var ip: String? = null var browser: String? = null class DeviceBean { /** * uuid : 25525ea79879905bf2f492d3f52sdfasfbc15f3e3ac409c * os : iPhonasdfe 6 (A1549/A1586) * name : junjieasdfsdfasf的 iPhone💋 * os_version : 9.2asdf.a1 * platform : ios */ var uuid: String? = null var os: String? = null var name: String? = null var os_version: String? = null var platform: String? = null } }
gpl-3.0
270bbb70c61f1fdb4339150bfb724c22
29.478261
186
0.563481
3.094923
false
false
false
false
PoweRGbg/AndroidAPS
app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSAMA/OpenAPSAMAFragment.kt
3
4735
package info.nightscout.androidaps.plugins.aps.openAPSAMA import android.os.Bundle import android.text.TextUtils import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import info.nightscout.androidaps.MainApp import info.nightscout.androidaps.R import info.nightscout.androidaps.logging.L import info.nightscout.androidaps.plugins.aps.openAPSMA.events.EventOpenAPSUpdateGui import info.nightscout.androidaps.plugins.aps.openAPSMA.events.EventOpenAPSUpdateResultGui import info.nightscout.androidaps.plugins.bus.RxBus import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.FabricPrivacy import info.nightscout.androidaps.utils.JSONFormatter import info.nightscout.androidaps.utils.plusAssign import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.disposables.CompositeDisposable import kotlinx.android.synthetic.main.openapsama_fragment.* import org.json.JSONArray import org.json.JSONException import org.slf4j.LoggerFactory class OpenAPSAMAFragment : Fragment() { private val log = LoggerFactory.getLogger(L.APS) private var disposable: CompositeDisposable = CompositeDisposable() override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { return inflater.inflate(R.layout.openapsama_fragment, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) openapsma_run.setOnClickListener { OpenAPSAMAPlugin.getPlugin().invoke("OpenAPSAMA button", false) } } @Synchronized override fun onResume() { super.onResume() disposable += RxBus .toObservable(EventOpenAPSUpdateGui::class.java) .observeOn(AndroidSchedulers.mainThread()) .subscribe({ updateGUI() }, { FabricPrivacy.logException(it) }) disposable += RxBus .toObservable(EventOpenAPSUpdateResultGui::class.java) .observeOn(AndroidSchedulers.mainThread()) .subscribe({ updateResultGUI(it.text) }, { FabricPrivacy.logException(it) }) updateGUI() } @Synchronized override fun onPause() { super.onPause() disposable.clear() } @Synchronized private fun updateGUI() { if (openapsma_result == null) return OpenAPSAMAPlugin.getPlugin().lastAPSResult?.let { lastAPSResult -> openapsma_result.text = JSONFormatter.format(lastAPSResult.json) openapsma_request.text = lastAPSResult.toSpanned() } OpenAPSAMAPlugin.getPlugin().lastDetermineBasalAdapterAMAJS?.let { determineBasalAdapterAMAJS -> openapsma_glucosestatus.text = JSONFormatter.format(determineBasalAdapterAMAJS.glucoseStatusParam) openapsma_currenttemp.text = JSONFormatter.format(determineBasalAdapterAMAJS.currentTempParam) try { val iobArray = JSONArray(determineBasalAdapterAMAJS.iobDataParam) openapsma_iobdata.text = TextUtils.concat(String.format(MainApp.gs(R.string.array_of_elements), iobArray.length()) + "\n", JSONFormatter.format(iobArray.getString(0))) } catch (e: JSONException) { log.error("Unhandled exception", e) openapsma_iobdata.text = "JSONException see log for details" } openapsma_profile.text = JSONFormatter.format(determineBasalAdapterAMAJS.profileParam) openapsma_mealdata.text = JSONFormatter.format(determineBasalAdapterAMAJS.mealDataParam) openapsma_scriptdebugdata.text = determineBasalAdapterAMAJS.scriptDebug } if (OpenAPSAMAPlugin.getPlugin().lastAPSRun != 0L) { openapsma_lastrun.text = DateUtil.dateAndTimeFullString(OpenAPSAMAPlugin.getPlugin().lastAPSRun) } OpenAPSAMAPlugin.getPlugin().lastAutosensResult?.let { openapsma_autosensdata.text = JSONFormatter.format(it.json()) } } private fun updateResultGUI(text: String) { openapsma_result.text = text openapsma_glucosestatus.text = "" openapsma_currenttemp.text = "" openapsma_iobdata.text = "" openapsma_profile.text = "" openapsma_mealdata.text = "" openapsma_autosensdata.text = "" openapsma_scriptdebugdata.text = "" openapsma_request.text = "" openapsma_lastrun.text = "" } }
agpl-3.0
b9a1f6b7430e45ec586e1bc4ce3f1de1
40.173913
183
0.684688
4.963312
false
false
false
false
GLodi/GitNav
app/src/main/java/giuliolodi/gitnav/ui/adapters/GistFileAdapter.kt
1
3547
/* * Copyright 2017 GLodi * * 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 giuliolodi.gitnav.ui.adapters import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import giuliolodi.gitnav.R import io.reactivex.Observable import io.reactivex.subjects.PublishSubject import kotlinx.android.synthetic.main.row_gist_file.view.* import org.eclipse.egit.github.core.GistFile /** * Created by giulio on 28/05/2017. */ class GistFileAdapter : RecyclerView.Adapter<RecyclerView.ViewHolder>() { private var mGistFileList: MutableList<GistFile?> = arrayListOf() private val onFileClick: PublishSubject<GistFile> = PublishSubject.create() fun getPositionClicks(): Observable<GistFile> { return onFileClick } class GistFileHolder(root: View) : RecyclerView.ViewHolder(root) { fun bind (file: GistFile) = with(itemView) { row_gist_file_icon.setImageResource(R.drawable.octicons_430_file_256_0_757575_none) row_gist_file_name.text = file.filename } } class LoadingHolder(root: View) : RecyclerView.ViewHolder(root) override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): RecyclerView.ViewHolder { val root: RecyclerView.ViewHolder if (viewType == 1) { val view = (LayoutInflater.from(parent?.context).inflate(R.layout.row_gist_file, parent, false)) root = GistFileHolder(view) } else { val view = (LayoutInflater.from(parent?.context).inflate(R.layout.row_loading, parent, false)) root = LoadingHolder(view) } return root } override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) { if (holder is GistFileHolder) { val file = mGistFileList[position]!! holder.bind(file) holder.itemView.setOnClickListener { onFileClick.onNext(file) } } } override fun getItemViewType(position: Int): Int { return if (mGistFileList[position] != null) 1 else 0 } override fun getItemCount(): Int { return mGistFileList.size } override fun getItemId(position: Int): Long { return position.toLong() } fun addGistFileList(gistFileList: List<GistFile>) { if (mGistFileList.isEmpty()) { mGistFileList.addAll(gistFileList) notifyDataSetChanged() } else if (!gistFileList.isEmpty()) { val lastItemIndex = if (mGistFileList.size > 0) mGistFileList.size else 0 mGistFileList.addAll(gistFileList) notifyItemRangeInserted(lastItemIndex, mGistFileList.size) } } fun addGistFile(gistFile: GistFile) { mGistFileList.add(gistFile) notifyItemInserted(mGistFileList.size - 1) } fun addLoading() { mGistFileList.add(null) notifyItemInserted(mGistFileList.size - 1) } fun clear() { mGistFileList.clear() notifyDataSetChanged() } }
apache-2.0
d9b7580f9092afe0c11600590746debd
33.446602
109
0.684804
4.252998
false
false
false
false
StepicOrg/stepic-android
app/src/main/java/org/stepic/droid/features/stories/ui/delegate/PlainTextWithButtonStoryPartDelegate.kt
2
5258
package org.stepic.droid.features.stories.ui.delegate import android.content.Context import android.content.res.ColorStateList import android.net.Uri import android.view.View import android.view.ViewGroup import androidx.annotation.ColorInt import androidx.appcompat.app.AppCompatActivity import androidx.core.view.ViewCompat import androidx.core.view.isVisible import androidx.swiperefreshlayout.widget.CircularProgressDrawable import com.bumptech.glide.Glide import kotlinx.android.synthetic.main.view_story_plain_text_with_button.view.* import org.stepic.droid.R import org.stepic.droid.analytic.AmplitudeAnalytic import org.stepic.droid.analytic.Analytic import org.stepic.droid.features.stories.model.PlainTextWithButtonStoryPart import org.stepik.android.domain.story.model.StoryReaction import org.stepik.android.model.StoryTemplate import org.stepik.android.view.base.routing.InternalDeeplinkRouter import ru.nobird.android.stories.model.Story import ru.nobird.android.stories.model.StoryPart import ru.nobird.android.stories.ui.custom.StoryView import ru.nobird.android.stories.ui.delegate.StoryPartViewDelegate import ru.nobird.android.view.base.ui.extension.inflate class PlainTextWithButtonStoryPartDelegate( private val analytic: Analytic, private val context: Context, private val storyReactions: Map<Long, StoryReaction>, private val storyReactionListener: (storyId: Long, storyPosition: Int, storyReaction: StoryReaction) -> Unit ) : StoryPartViewDelegate() { companion object { private const val COLOR_MASK = 0xFF000000.toInt() } private val progressDrawable = CircularProgressDrawable(context).apply { alpha = 0x77 strokeWidth = 5f centerRadius = 30f setColorSchemeColors(0xFFFFFF) start() } override fun isForViewType(part: StoryPart): Boolean = part is PlainTextWithButtonStoryPart override fun onBindView(storyView: StoryView, container: ViewGroup, position: Int, part: StoryPart): View = container.inflate(R.layout.view_story_plain_text_with_button, false).apply { part as PlainTextWithButtonStoryPart (context as? AppCompatActivity)?.currentFocus?.clearFocus() Glide.with(context) .load(part.cover) .placeholder(progressDrawable) .into(this.storyCover) val story = storyView.adapter?.story if (story != null) { analytic.reportAmplitudeEvent(AmplitudeAnalytic.Stories.STORY_PART_OPENED, mapOf( AmplitudeAnalytic.Stories.Values.STORY_ID to story.id, AmplitudeAnalytic.Stories.Values.POSITION to position )) } setUpText(this, part.text) setUpButton(story, this, part.button, position) setUpReactions(story, this, position) } private fun setUpText(view: View, text: StoryTemplate.Text?) { if (text != null) { val storyTitle = view.storyTitle val storyText = view.storyText @ColorInt val textColor = COLOR_MASK or text.textColor.toInt(16) storyTitle.setTextColor(textColor) storyText.setTextColor(textColor) storyTitle.text = text.title storyText.text = text.text storyText.isVisible = text.text?.isNotBlank() ?: false } } private fun setUpButton(story: Story?, view: View, button: StoryTemplate.Button?, position: Int) { val storyButton = view.storyButton if (button != null) { ViewCompat.setBackgroundTintList(storyButton, ColorStateList.valueOf(COLOR_MASK or button.backgroundColor.toInt(16))) storyButton.setTextColor(COLOR_MASK or button.textColor.toInt(16)) storyButton.text = button.title storyButton.setOnClickListener { val uri = Uri.parse(button.url) InternalDeeplinkRouter.openInternalDeeplink(context, uri) if (story != null) { analytic.reportAmplitudeEvent(AmplitudeAnalytic.Stories.BUTTON_PRESSED, mapOf( AmplitudeAnalytic.Stories.Values.STORY_ID to story.id, AmplitudeAnalytic.Stories.Values.POSITION to position )) } } storyButton.isVisible = true } else { storyButton.isVisible = false } } fun setUpReactions(story: Story?, view: View, position: Int) { val storyId = story?.id ?: 0 val vote = storyReactions[storyId] with(view.storyReactionLike) { setOnClickListener { val id = story?.id ?: return@setOnClickListener storyReactionListener.invoke(id, position, StoryReaction.LIKE) } isActivated = vote == StoryReaction.LIKE } with(view.storyReactionDislike) { setOnClickListener { val id = story?.id ?: return@setOnClickListener storyReactionListener.invoke(id, position, StoryReaction.DISLIKE) } isActivated = vote == StoryReaction.DISLIKE } } }
apache-2.0
65f805b269c62fc223d5ca871508002c
38.541353
129
0.664701
4.677936
false
false
false
false
Lucas-Lu/KotlinWorld
KT09/src/main/java/net/println/kt09/Tailrec.kt
1
529
package net.println.kt09 import java.math.BigInteger /** * Created by luliju on 2017/7/6. */ class Result(var value: BigInteger = BigInteger.valueOf(1L)) tailrec fun factorial(num: Int, result: Result){ if(num == 0) result.value = result.value.times(BigInteger.valueOf(1L)) else { result.value = result.value.times(BigInteger.valueOf(num.toLong())) factorial(num - 1, result) } } fun main(args: Array<String>) { val result = Result() factorial(10000, result) println(result.value) }
mit
d697c4beff21a42f8a635d1f1d2ccd60
22.043478
75
0.672968
3.348101
false
false
false
false
zlyne0/colonization
core/src/net/sf/freecol/common/model/ai/missions/pioneer/RequestGoodsMission.kt
1
4689
package net.sf.freecol.common.model.ai.missions.pioneer import net.sf.freecol.common.model.Colony import net.sf.freecol.common.model.Game import net.sf.freecol.common.model.GoodsContainer import net.sf.freecol.common.model.ai.missions.AbstractMission import net.sf.freecol.common.model.ai.missions.UnitMissionsMapping import net.sf.freecol.common.model.colonyproduction.GoodsCollection import net.sf.freecol.common.model.colonyproduction.amount import net.sf.freecol.common.model.colonyproduction.type import net.sf.freecol.common.model.specification.GoodsType import net.sf.freecol.common.util.Predicate import promitech.colonization.ai.MissionHandlerLogger.logger import promitech.colonization.savegame.ObjectFromNodeSetter import promitech.colonization.savegame.XmlNodeAttributes import promitech.colonization.savegame.XmlNodeAttributesWriter class RequestGoodsMission : AbstractMission { companion object { @JvmField val isBoughtPredicate = object: Predicate<RequestGoodsMission> { override fun test(mission: RequestGoodsMission): Boolean { return mission.boughtInEurope } } } var colonyId: String private set lateinit var goodsCollection: GoodsCollection private set val purpose: String var boughtInEurope = false private set constructor( colony: Colony, goodsCollection: GoodsCollection, purpose: String = "", boughtInEurope: Boolean = false ) : super(Game.idGenerator.nextId(RequestGoodsMission::class.java)) { this.colonyId = colony.id this.goodsCollection = goodsCollection this.purpose = purpose this.boughtInEurope = boughtInEurope } private constructor(missionId: String, colonyId: String, purpose: String = "", boughtInEurope: Boolean = false) : super(missionId) { this.colonyId = colonyId this.purpose = purpose this.boughtInEurope = boughtInEurope } override fun blockUnits(unitMissionsMapping: UnitMissionsMapping) { } override fun unblockUnits(unitMissionsMapping: UnitMissionsMapping) { } fun amount(type: GoodsType): Int { return goodsCollection.amount(type) } fun addGoodsToColony(colony: Colony) { for (goods in goodsCollection) { colony.goodsContainer.increaseGoodsQuantity(goods.type(), goods.amount()) } if (logger.isDebug) { logger.debug("player[%s].RequestGoodsMissionHandler.colony[%s] add goods %s", colony.owner.id, colony.id, goodsCollection.toPrettyString() ) } } override fun toString(): String { return "id: " + getId() + ", colonyId: " + colonyId + ", purpose: " + purpose + ", goodsCollection: " + goodsCollection.toPrettyString() } fun setAsBoughtInEurope() { boughtInEurope = true } class Xml : AbstractMission.Xml<RequestGoodsMission>() { private val ATTR_COLONY = "colony" private val ATTR_PURPOSE = "purpose" private val ATTR_BOUGHT_IN_EUROPE = "bought" init { addNode(GoodsCollection::class.java, object: ObjectFromNodeSetter<RequestGoodsMission, GoodsCollection> { override fun set(target: RequestGoodsMission, entity: GoodsCollection) { target.goodsCollection = entity } override fun generateXml(source: RequestGoodsMission, xmlGenerator: ObjectFromNodeSetter.ChildObject2XmlCustomeHandler<GoodsCollection>) { xmlGenerator.generateXml(source.goodsCollection) } }) } override fun startElement(attr: XmlNodeAttributes) { nodeObject = RequestGoodsMission( attr.id, attr.getStrAttribute(ATTR_COLONY), attr.getStrAttribute(ATTR_PURPOSE, ""), attr.getBooleanAttribute(ATTR_BOUGHT_IN_EUROPE, false) ) super.startElement(attr) } override fun startWriteAttr(mission: RequestGoodsMission, attr: XmlNodeAttributesWriter) { super.startWriteAttr(mission, attr) attr.setId(mission) attr.set(ATTR_COLONY, mission.colonyId) attr.set(ATTR_PURPOSE, mission.purpose, "") attr.set(ATTR_BOUGHT_IN_EUROPE, mission.boughtInEurope, false) } override fun getTagName(): String { return tagName() } companion object { @JvmStatic fun tagName(): String { return "requestGoodsMission" } } } }
gpl-2.0
e8c83de9df602edebe84eebcf51d6dcb
34.801527
154
0.656003
4.47851
false
false
false
false
grenzfrequence/showMyCar
app/src/main/java/com/grenzfrequence/showmycar/car_types/viewmodel/SummarizeViewModel.kt
1
1562
package com.grenzfrequence.showmycar.car_types.viewmodel import android.databinding.ObservableField import android.os.Bundle import com.grenzfrequence.showmycar.car_types.data.model.SummarizeModel import com.grenzfrequence.showmycar.car_types.ui.base.MvvmView import com.grenzfrequence.showmycar.car_types.viewmodel.base.BaseViewModel /** * Created by grenzfrequence on 21.08.17. */ class SummarizeViewModel : BaseViewModel<MvvmView, SummarizeModel>() { companion object { val TAG_SAVE_INSTANCE: String = SummarizeViewModel::class.java.simpleName } val manufacturer: ObservableField<String> = ObservableField("") val mainType: ObservableField<String> = ObservableField("") val builtDate: ObservableField<String> = ObservableField("") override fun saveInstanceState(outState: Bundle) { super.saveInstanceState(outState) outState.putString(TAG_SAVE_INSTANCE, manufacturer.get()) outState.putString(TAG_SAVE_INSTANCE+1, mainType.get()) outState.putString(TAG_SAVE_INSTANCE+2, builtDate.get()) } override fun restoreInstanceState(savedInstanceState: Bundle) { super.restoreInstanceState(savedInstanceState) manufacturer.set(savedInstanceState.getString(TAG_SAVE_INSTANCE)) mainType.set(savedInstanceState.getString(TAG_SAVE_INSTANCE+1)) builtDate.set(savedInstanceState.getString(TAG_SAVE_INSTANCE+2)) } override var modelData: SummarizeModel? = null override fun loadData(reset: Boolean) {} override fun isLastPage(): Boolean = false }
mit
7b9e5a04ed6ecdb2fa39b0af5eb33ea9
38.075
81
0.754161
4.412429
false
false
false
false
geeteshk/Hyper
app/src/main/java/io/geeteshk/hyper/ui/widget/ScrimInsetsFrameLayout.kt
1
3929
/* * Copyright 2014 Google 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 io.geeteshk.hyper.ui.widget import android.content.Context import android.content.res.TypedArray import android.graphics.Canvas import android.graphics.Rect import android.graphics.drawable.Drawable import androidx.core.view.ViewCompat import android.util.AttributeSet import android.widget.FrameLayout import io.geeteshk.hyper.R class ScrimInsetsFrameLayout : FrameLayout { private var mInsetForeground: Drawable? = null private var mInsets: Rect? = null private val mTempRect = Rect() private var mOnInsetsCallback: OnInsetsCallback? = null constructor(context: Context) : super(context) { init(context, null, 0) } constructor(context: Context, attrs: AttributeSet) : super(context, attrs) { init(context, attrs, 0) } constructor( context: Context, attrs: AttributeSet, defStyle: Int) : super(context, attrs, defStyle) { init(context, attrs, defStyle) } private fun init(context: Context, attrs: AttributeSet?, defStyle: Int) { val a = context.obtainStyledAttributes(attrs, R.styleable.ScrimInsetsFrameLayout, defStyle, 0) mInsetForeground = a.getDrawable( R.styleable.ScrimInsetsFrameLayout_insetForeground) a.recycle() setWillNotDraw(true) } override fun fitSystemWindows(insets: Rect): Boolean { mInsets = Rect(insets) setWillNotDraw(mInsetForeground == null) ViewCompat.postInvalidateOnAnimation(this) mOnInsetsCallback?.let { mOnInsetsCallback!!.onInsetsChanged(insets) } return true } override fun draw(canvas: Canvas) { super.draw(canvas) val width = width val height = height if (mInsets != null && mInsetForeground != null) { val sc = canvas.save() canvas.translate(scrollX.toFloat(), scrollY.toFloat()) mTempRect.set(0, 0, width, mInsets!!.top) mInsetForeground!!.bounds = mTempRect mInsetForeground!!.draw(canvas) mTempRect.set(0, height - mInsets!!.bottom, width, height) mInsetForeground!!.bounds = mTempRect mInsetForeground!!.draw(canvas) mTempRect.set( 0, mInsets!!.top, mInsets!!.left, height - mInsets!!.bottom) mInsetForeground!!.bounds = mTempRect mInsetForeground!!.draw(canvas) mTempRect.set( width - mInsets!!.right, mInsets!!.top, width, height - mInsets!!.bottom) mInsetForeground!!.bounds = mTempRect mInsetForeground!!.draw(canvas) canvas.restoreToCount(sc) } } override fun onAttachedToWindow() { super.onAttachedToWindow() mInsetForeground?.let { mInsetForeground!!.callback = this } } override fun onDetachedFromWindow() { super.onDetachedFromWindow() mInsetForeground?.let { mInsetForeground!!.callback = null } } fun setOnInsetsCallback(onInsetsCallback: OnInsetsCallback) { mOnInsetsCallback = onInsetsCallback } interface OnInsetsCallback { fun onInsetsChanged(insets: Rect) } }
apache-2.0
dc338d6353edbdb870e758d849e6d587
29.944882
101
0.639094
4.573923
false
false
false
false
hurricup/intellij-community
platform/projectModel-api/src/org/jetbrains/concurrency/AsyncPromise.kt
1
8496
/* * Copyright 2000-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.concurrency import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.util.Getter import com.intellij.util.Consumer import com.intellij.util.Function import java.util.* import java.util.concurrent.atomic.AtomicReference private val LOG = Logger.getInstance(AsyncPromise::class.java) @SuppressWarnings("ThrowableResultOfMethodCallIgnored") private val OBSOLETE_ERROR = Promise.createError("Obsolete") open class AsyncPromise<T> : Promise<T>(), Getter<T> { @Volatile private var done: Consumer<in T>? = null @Volatile private var rejected: Consumer<in Throwable>? = null private val state = AtomicReference(Promise.State.PENDING) // result object or error message @Volatile private var result: Any? = null override fun getState() = state.get()!! override fun done(done: Consumer<in T>): Promise<T> { if (isObsolete(done)) { return this } when (state.get()!!) { Promise.State.PENDING -> { this.done = setHandler(this.done, done, State.FULFILLED) } Promise.State.FULFILLED -> { @Suppress("UNCHECKED_CAST") done.consume(result as T?) } Promise.State.REJECTED -> { } } return this } override fun rejected(rejected: Consumer<Throwable>): Promise<T> { if (isObsolete(rejected)) { return this } when (state.get()!!) { Promise.State.PENDING -> { this.rejected = setHandler(this.rejected, rejected, State.REJECTED) } Promise.State.FULFILLED -> { } Promise.State.REJECTED -> { rejected.consume(result as Throwable?) } } return this } @Suppress("UNCHECKED_CAST") override fun get() = if (state.get() == Promise.State.FULFILLED) result as T? else null override fun <SUB_RESULT> then(fulfilled: Function<in T, out SUB_RESULT>): Promise<SUB_RESULT> { @Suppress("UNCHECKED_CAST") when (state.get()!!) { Promise.State.PENDING -> { } Promise.State.FULFILLED -> return DonePromise<SUB_RESULT>( fulfilled.`fun`(result as T?)) Promise.State.REJECTED -> return rejectedPromise(result as Throwable) } val promise = AsyncPromise<SUB_RESULT>() addHandlers(Consumer({ result -> promise.catchError { if (fulfilled is Obsolescent && fulfilled.isObsolete) { promise.cancel() } else { promise.setResult(fulfilled.`fun`(result)) } } }), Consumer({ promise.setError(it) })) return promise } override fun notify(child: AsyncPromise<in T>) { LOG.assertTrue(child !== this) when (state.get()!!) { Promise.State.PENDING -> { addHandlers(Consumer({ child.catchError { child.setResult(it) } }), Consumer({ child.setError(it) })) } Promise.State.FULFILLED -> { @Suppress("UNCHECKED_CAST") child.setResult(result as T) } Promise.State.REJECTED -> { child.setError((result as Throwable?)!!) } } } override fun <SUB_RESULT> thenAsync(fulfilled: Function<in T, Promise<SUB_RESULT>>): Promise<SUB_RESULT> { @Suppress("UNCHECKED_CAST") when (state.get()!!) { Promise.State.PENDING -> { } Promise.State.FULFILLED -> return fulfilled.`fun`(result as T?) Promise.State.REJECTED -> return rejectedPromise(result as Throwable) } val promise = AsyncPromise<SUB_RESULT>() val rejectedHandler = Consumer<Throwable>({ promise.setError(it) }) addHandlers(Consumer({ promise.catchError { fulfilled.`fun`(it) .done { promise.catchError { promise.setResult(it) } } .rejected(rejectedHandler) } }), rejectedHandler) return promise } override fun processed(fulfilled: AsyncPromise<in T>): Promise<T> { when (state.get()!!) { Promise.State.PENDING -> { addHandlers(Consumer({ result -> fulfilled.catchError { fulfilled.setResult(result) } }), Consumer({ fulfilled.setError(it) })) } Promise.State.FULFILLED -> { @Suppress("UNCHECKED_CAST") fulfilled.setResult(result as T) } Promise.State.REJECTED -> { fulfilled.setError((result as Throwable?)!!) } } return this } private fun addHandlers(done: Consumer<T>, rejected: Consumer<Throwable>) { this.done = setHandler(this.done, done, State.FULFILLED) this.rejected = setHandler(this.rejected, rejected, State.REJECTED) } fun setResult(result: T?) { if (!state.compareAndSet(Promise.State.PENDING, Promise.State.FULFILLED)) { return } this.result = result val done = this.done clearHandlers() if (done != null && !isObsolete(done)) { done.consume(result) } } fun setError(error: String) = setError(Promise.createError(error)) fun cancel() { setError(OBSOLETE_ERROR) } open fun setError(error: Throwable): Boolean { if (!state.compareAndSet(Promise.State.PENDING, Promise.State.REJECTED)) { return false } result = error val rejected = this.rejected clearHandlers() if (rejected == null) { Promise.logError(LOG, error) } else if (!isObsolete(rejected)) { rejected.consume(error) } return true } private fun clearHandlers() { done = null rejected = null } override fun processed(processed: Consumer<in T>): Promise<T> { done(processed) rejected { processed.consume(null) } return this } private fun <T> setHandler(oldConsumer: Consumer<in T>?, newConsumer: Consumer<in T>, targetState: State): Consumer<in T>? = when (oldConsumer) { null -> newConsumer is CompoundConsumer<*> -> { @Suppress("UNCHECKED_CAST") val compoundConsumer = oldConsumer as CompoundConsumer<T> synchronized(compoundConsumer) { compoundConsumer.consumers.let { if (it == null) { // clearHandlers was called - just execute newConsumer if (state.get() == targetState) { @Suppress("UNCHECKED_CAST") newConsumer.consume(result as T?) } return null } else { it.add(newConsumer) return compoundConsumer } } } } else -> CompoundConsumer(oldConsumer, newConsumer) } } private class CompoundConsumer<T>(c1: Consumer<in T>, c2: Consumer<in T>) : Consumer<T> { var consumers: MutableList<Consumer<in T>>? = ArrayList() init { synchronized(this) { consumers!!.add(c1) consumers!!.add(c2) } } override fun consume(t: T) { val list = synchronized(this) { val list = consumers consumers = null list } ?: return for (consumer in list) { if (!isObsolete(consumer)) { consumer.consume(t) } } } fun add(consumer: Consumer<in T>) { synchronized(this) { consumers.let { if (it == null) { // it means that clearHandlers was called } consumers?.add(consumer) } } } } internal fun isObsolete(consumer: Consumer<*>?) = consumer is Obsolescent && consumer.isObsolete inline fun <T> AsyncPromise<*>.catchError(runnable: () -> T): T? { try { return runnable() } catch (e: Throwable) { setError(e) return null } } private val cancelledPromise = RejectedPromise<Any?>(OBSOLETE_ERROR) @Suppress("CAST_NEVER_SUCCEEDS") fun <T> cancelledPromise(): Promise<T> = cancelledPromise as Promise<T> fun <T> rejectedPromise(error: Throwable): Promise<T> = Promise.reject(error)
apache-2.0
f8331a97c492ba5eb0128588f9a688ce
27.901361
147
0.610758
4.356923
false
false
false
false
bluelinelabs/Conductor
demo/src/main/java/com/bluelinelabs/conductor/demo/controllers/NavigationDemoController.kt
1
3060
package com.bluelinelabs.conductor.demo.controllers import android.os.Bundle import android.view.View import androidx.core.os.bundleOf import androidx.core.view.isVisible import com.bluelinelabs.conductor.ControllerChangeHandler import com.bluelinelabs.conductor.ControllerChangeType import com.bluelinelabs.conductor.RouterTransaction import com.bluelinelabs.conductor.changehandler.HorizontalChangeHandler import com.bluelinelabs.conductor.demo.R import com.bluelinelabs.conductor.demo.controllers.base.BaseController import com.bluelinelabs.conductor.demo.databinding.ControllerNavigationDemoBinding import com.bluelinelabs.conductor.demo.util.getMaterialColor import com.bluelinelabs.conductor.demo.util.viewBinding class NavigationDemoController(args: Bundle) : BaseController(R.layout.controller_navigation_demo, args) { private val binding: ControllerNavigationDemoBinding by viewBinding(ControllerNavigationDemoBinding::bind) private val index = args.getInt(KEY_INDEX) private val displayUpMode = DisplayUpMode.values()[args.getInt(KEY_DISPLAY_UP_MODE)] override val title = "Navigation Demos" constructor(index: Int, displayUpMode: DisplayUpMode) : this( bundleOf( KEY_INDEX to index, KEY_DISPLAY_UP_MODE to displayUpMode.ordinal ) ) override fun onViewCreated(view: View) { binding.root.setBackgroundColor(view.resources.getMaterialColor(index)) binding.goUp.isVisible = displayUpMode == DisplayUpMode.SHOW binding.title.text = view.resources.getString(R.string.navigation_title, index) binding.popToRoot.setOnClickListener { router.popToRoot() } binding.goUp.setOnClickListener { router.popToTag(TAG_UP_TRANSACTION) } binding.goToNext.setOnClickListener { router.pushController( RouterTransaction.with(NavigationDemoController(index + 1, displayUpMode.displayUpModeForChild)) .pushChangeHandler(HorizontalChangeHandler()) .popChangeHandler(HorizontalChangeHandler()) ) } } override fun onChangeEnded( changeHandler: ControllerChangeHandler, changeType: ControllerChangeType ) { super.onChangeEnded(changeHandler, changeType) if (changeType.isEnter) { setButtonsEnabled(true) } } override fun onChangeStarted( changeHandler: ControllerChangeHandler, changeType: ControllerChangeType ) { super.onChangeStarted(changeHandler, changeType) setButtonsEnabled(false) } private fun setButtonsEnabled(enabled: Boolean) { binding.goToNext.isEnabled = enabled binding.goUp.isEnabled = enabled binding.popToRoot.isEnabled = enabled } companion object { const val TAG_UP_TRANSACTION = "NavigationDemoController.up" private const val KEY_INDEX = "NavigationDemoController.index" private const val KEY_DISPLAY_UP_MODE = "NavigationDemoController.displayUpMode" } enum class DisplayUpMode { SHOW, SHOW_FOR_CHILDREN_ONLY, HIDE; val displayUpModeForChild: DisplayUpMode get() = when (this) { HIDE -> HIDE else -> SHOW } } }
apache-2.0
e151db551ddb35018260c9f82bbd777f
33.784091
108
0.770588
4.493392
false
false
false
false
Maccimo/intellij-community
plugins/kotlin/native/src/org/jetbrains/kotlin/ide/konan/NativeIdePlatformKindTooling.kt
1
4131
// 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.ide.konan import com.intellij.execution.actions.RunConfigurationProducer import com.intellij.openapi.project.Project import com.intellij.openapi.roots.libraries.PersistentLibraryKind import com.intellij.openapi.roots.ui.configuration.libraries.CustomLibraryDescription import org.jetbrains.kotlin.asJava.classes.KtLightClass import org.jetbrains.kotlin.asJava.toLightClass import org.jetbrains.kotlin.asJava.toLightMethods import org.jetbrains.kotlin.descriptors.DeclarationDescriptor import org.jetbrains.kotlin.idea.base.facet.isTestModule import org.jetbrains.kotlin.idea.base.platforms.KotlinNativeLibraryKind import org.jetbrains.kotlin.idea.facet.externalSystemNativeMainRunTasks import org.jetbrains.kotlin.idea.highlighter.KotlinTestRunLineMarkerContributor.Companion.getTestStateIcon import org.jetbrains.kotlin.idea.isMainFunction import org.jetbrains.kotlin.idea.platform.IdePlatformKindTooling import org.jetbrains.kotlin.idea.platform.isKotlinTestDeclaration import org.jetbrains.kotlin.idea.projectModel.KotlinPlatform import org.jetbrains.kotlin.idea.base.util.module import org.jetbrains.kotlin.platform.impl.NativeIdePlatformKind import org.jetbrains.kotlin.psi.KtClassOrObject import org.jetbrains.kotlin.psi.KtFunction import org.jetbrains.kotlin.psi.KtNamedDeclaration import org.jetbrains.kotlin.psi.KtNamedFunction import org.jetbrains.kotlin.resolve.descriptorUtil.module import javax.swing.Icon class NativeIdePlatformKindTooling : IdePlatformKindTooling() { override val kind = NativeIdePlatformKind override val mavenLibraryIds: List<String> get() = emptyList() override val gradlePluginId: String get() = "" override val gradlePlatformIds: List<KotlinPlatform> get() = listOf(KotlinPlatform.NATIVE) override val libraryKind: PersistentLibraryKind<*> = KotlinNativeLibraryKind override fun getLibraryDescription(project: Project): CustomLibraryDescription? = null override fun getTestIcon( declaration: KtNamedDeclaration, descriptorProvider: () -> DeclarationDescriptor?, includeSlowProviders: Boolean? ): Icon? { if (includeSlowProviders == false) return null val descriptor = descriptorProvider() ?: return null if (!descriptor.isKotlinTestDeclaration()) return null val moduleName = descriptor.module.stableName?.asString() ?: "" val targetName = moduleName.substringAfterLast(".").removeSuffix("Test>") val urls = when (declaration) { is KtClassOrObject -> { val lightClass = declaration.toLightClass() ?: return null listOf("java:suite://${lightClass.qualifiedName}") } is KtNamedFunction -> { val lightMethod = declaration.toLightMethods().firstOrNull() ?: return null val lightClass = lightMethod.containingClass as? KtLightClass ?: return null val baseName = "java:test://${lightClass.qualifiedName}.${lightMethod.name}" listOf("$baseName[${targetName}X64]", "$baseName[$targetName]", baseName) } else -> return null } return getTestStateIcon(urls, declaration) } override fun acceptsAsEntryPoint(function: KtFunction): Boolean { if (!function.isMainFunction()) return false val functionName = function.fqName?.asString() ?: return false val module = function.module ?: return false if (module.isTestModule) return false val hasRunTask = module.externalSystemNativeMainRunTasks().any { it.entryPoint == functionName } if (!hasRunTask) return false val hasRunConfigurations = RunConfigurationProducer .getProducers(function.project) .asSequence() .filterIsInstance<KotlinNativeRunConfigurationProvider>() .any { !it.isForTests } if (!hasRunConfigurations) return false return true } }
apache-2.0
936cbae1db22eabd6ce2dfe6b2265047
44.406593
158
0.740983
5.222503
false
true
false
false
Maccimo/intellij-community
plugins/kotlin/gradle/gradle-java/src/org/jetbrains/kotlin/idea/gradleJava/scripting/GradleScriptNotificationProvider.kt
2
11199
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.gradleJava.scripting import com.intellij.icons.AllIcons import com.intellij.ide.actions.ImportModuleAction import com.intellij.ide.util.PropertiesComponent import com.intellij.openapi.externalSystem.service.project.wizard.AbstractExternalProjectImportProvider import com.intellij.openapi.externalSystem.util.ExternalSystemApiUtil import com.intellij.openapi.fileEditor.FileEditor import com.intellij.openapi.fileTypes.FileTypeRegistry import com.intellij.openapi.project.Project import com.intellij.openapi.vfs.VirtualFile import com.intellij.projectImport.ProjectImportProvider import com.intellij.ui.EditorNotificationPanel import com.intellij.ui.EditorNotificationProvider import com.intellij.ui.EditorNotificationProvider.CONST_NULL import org.jetbrains.annotations.Nls import org.jetbrains.kotlin.idea.KotlinFileType import org.jetbrains.kotlin.idea.base.scripting.KotlinBaseScriptingBundle import org.jetbrains.kotlin.idea.configuration.GRADLE_SYSTEM_ID import org.jetbrains.kotlin.idea.core.util.KotlinIdeaCoreBundle import org.jetbrains.kotlin.idea.gradle.KotlinIdeaGradleBundle import org.jetbrains.kotlin.idea.gradleJava.scripting.legacy.GradleStandaloneScriptActionsManager import org.jetbrains.kotlin.idea.gradleJava.scripting.roots.GradleBuildRootsLocator import org.jetbrains.kotlin.idea.gradleJava.scripting.roots.GradleBuildRootsLocator.NotificationKind.* import org.jetbrains.kotlin.idea.gradleJava.scripting.roots.GradleBuildRootsManager import org.jetbrains.kotlin.idea.gradleJava.scripting.roots.Imported import org.jetbrains.kotlin.idea.util.isKotlinFileType import java.io.File import java.util.function.Function import javax.swing.JComponent internal class GradleScriptNotificationProvider : EditorNotificationProvider { override fun collectNotificationData( project: Project, file: VirtualFile, ): Function<in FileEditor, out JComponent?> { if (!isGradleKotlinScript(file) || !file.isKotlinFileType()) { return CONST_NULL } val standaloneScriptActions = GradleStandaloneScriptActionsManager.getInstance(project) val rootsManager = GradleBuildRootsManager.getInstance(project) val scriptUnderRoot = rootsManager?.findScriptBuildRoot(file) ?: return CONST_NULL // todo: this actions will be usefull only when gradle fix https://github.com/gradle/gradle/issues/12640 fun EditorNotificationPanel.showActionsToFixNotEvaluated() { // suggest to reimport project if something changed after import val build: Imported = scriptUnderRoot.nearest as? Imported ?: return val importTs = build.data.importTs if (!build.areRelatedFilesChangedBefore(file, importTs)) { createActionLabel(getConfigurationsActionText()) { rootsManager.updateStandaloneScripts { runPartialGradleImport(project, build) } } } // suggest to choose new gradle project createActionLabel(KotlinIdeaGradleBundle.message("notification.outsideAnything.linkAction")) { linkProject(project, scriptUnderRoot) } } return Function { fileEditor -> when (scriptUnderRoot.notificationKind) { dontCare -> null legacy -> { val actions = standaloneScriptActions[file] if (actions == null) null else { object : EditorNotificationPanel(fileEditor) { val contextHelp = KotlinIdeaGradleBundle.message("notification.gradle.legacy.firstLoad.info") init { if (actions.isFirstLoad) { text(KotlinIdeaGradleBundle.message("notification.gradle.legacy.firstLoad")) toolTipText = contextHelp } else { text(KotlinIdeaGradleBundle.message("notification.text.script.configuration.has.been.changed")) } createActionLabel(KotlinIdeaCoreBundle.message("notification.action.text.load.script.configuration")) { actions.reload() } createActionLabel(KotlinBaseScriptingBundle.message("notification.action.text.enable.auto.reload")) { actions.enableAutoReload() } if (actions.isFirstLoad) { contextHelp(contextHelp) } } } } } legacyOutside -> EditorNotificationPanel(fileEditor).apply { text(KotlinIdeaGradleBundle.message("notification.gradle.legacy.outsideProject")) createActionLabel(KotlinIdeaGradleBundle.message("notification.notEvaluatedInLastImport.addAsStandaloneAction")) { rootsManager.updateStandaloneScripts { addStandaloneScript(file.path) } } contextHelp(KotlinIdeaGradleBundle.message("notification.gradle.legacy.outsideProject.addToStandaloneHelp")) } outsideAnything -> EditorNotificationPanel(fileEditor).apply { text(KotlinIdeaGradleBundle.message("notification.outsideAnything.text")) createActionLabel(KotlinIdeaGradleBundle.message("notification.outsideAnything.linkAction")) { linkProject(project, scriptUnderRoot) } } wasNotImportedAfterCreation -> EditorNotificationPanel(fileEditor).apply { text(configurationsAreMissingRequestNeeded()) createActionLabel(getConfigurationsActionText()) { val root = scriptUnderRoot.nearest if (root != null) { runPartialGradleImport(project, root) } } val help = configurationsAreMissingRequestNeededHelp() contextHelp(help) } notEvaluatedInLastImport -> EditorNotificationPanel(fileEditor).apply { text(configurationsAreMissingAfterRequest()) // todo: this actions will be usefull only when gradle fix https://github.com/gradle/gradle/issues/12640 // showActionsToFixNotEvaluated() createActionLabel(KotlinIdeaGradleBundle.message("notification.notEvaluatedInLastImport.addAsStandaloneAction")) { rootsManager.updateStandaloneScripts { addStandaloneScript(file.path) } } contextHelp(KotlinIdeaGradleBundle.message("notification.notEvaluatedInLastImport.info")) } standalone, standaloneLegacy -> EditorNotificationPanel(fileEditor).apply { val actions = standaloneScriptActions[file] if (actions != null) { text( KotlinIdeaGradleBundle.message("notification.standalone.text") + ". " + KotlinIdeaGradleBundle.message("notification.text.script.configuration.has.been.changed") ) createActionLabel(KotlinIdeaCoreBundle.message("notification.action.text.load.script.configuration")) { actions.reload() } createActionLabel(KotlinBaseScriptingBundle.message("notification.action.text.enable.auto.reload")) { actions.enableAutoReload() } } else { text(KotlinIdeaGradleBundle.message("notification.standalone.text")) } createActionLabel(KotlinIdeaGradleBundle.message("notification.standalone.disableScriptAction")) { rootsManager.updateStandaloneScripts { removeStandaloneScript(file.path) } } if (scriptUnderRoot.notificationKind == standaloneLegacy) { contextHelp(KotlinIdeaGradleBundle.message("notification.gradle.legacy.standalone.info")) } else { contextHelp(KotlinIdeaGradleBundle.message("notification.standalone.info")) } } } } } private fun linkProject( project: Project, scriptUnderRoot: GradleBuildRootsLocator.ScriptUnderRoot, ) { val settingsFile: File? = tryFindGradleSettings(scriptUnderRoot) // from AttachExternalProjectAction val manager = ExternalSystemApiUtil.getManager(GRADLE_SYSTEM_ID) ?: return val provider = ProjectImportProvider.PROJECT_IMPORT_PROVIDER.extensions.find { it is AbstractExternalProjectImportProvider && GRADLE_SYSTEM_ID == it.externalSystemId } ?: return val projectImportProviders = arrayOf(provider) if (settingsFile != null) { PropertiesComponent.getInstance().setValue( "last.imported.location", settingsFile.canonicalPath ) } val wizard = ImportModuleAction.selectFileAndCreateWizard( project, null, manager.externalProjectDescriptor, projectImportProviders ) ?: return if (wizard.stepCount <= 0 || wizard.showAndGet()) { ImportModuleAction.createFromWizard(project, wizard) } } private fun tryFindGradleSettings(scriptUnderRoot: GradleBuildRootsLocator.ScriptUnderRoot): File? { try { var parent = File(scriptUnderRoot.filePath).canonicalFile.parentFile while (parent.isDirectory) { listOf("settings.gradle", "settings.gradle.kts").forEach { val settings = parent.resolve(it) if (settings.isFile) { return settings } } parent = parent.parentFile } } catch (t: Throwable) { // ignore } return null } private fun EditorNotificationPanel.contextHelp(@Nls text: String) { val helpIcon = createActionLabel("") {} helpIcon.icon = AllIcons.General.ContextHelp helpIcon.setUseIconAsLink(true) helpIcon.toolTipText = text } }
apache-2.0
40d701a2e72b9edf887c82adecc4e55a
46.655319
135
0.604518
6.284512
false
false
false
false
JetBrains/ideavim
vim-engine/src/main/kotlin/com/maddyhome/idea/vim/vimscript/model/datatypes/VimFuncref.kt
1
3567
/* * Copyright 2003-2022 The IdeaVim authors * * Use of this source code is governed by an MIT-style * license that can be found in the LICENSE.txt file or at * https://opensource.org/licenses/MIT. */ package com.maddyhome.idea.vim.vimscript.model.datatypes import com.maddyhome.idea.vim.api.ExecutionContext import com.maddyhome.idea.vim.api.VimEditor import com.maddyhome.idea.vim.api.injector import com.maddyhome.idea.vim.ex.ExException import com.maddyhome.idea.vim.vimscript.model.VimLContext import com.maddyhome.idea.vim.vimscript.model.expressions.Expression import com.maddyhome.idea.vim.vimscript.model.expressions.Scope import com.maddyhome.idea.vim.vimscript.model.expressions.SimpleExpression import com.maddyhome.idea.vim.vimscript.model.expressions.Variable import com.maddyhome.idea.vim.vimscript.model.functions.DefinedFunctionHandler import com.maddyhome.idea.vim.vimscript.model.functions.FunctionHandler import com.maddyhome.idea.vim.vimscript.model.statements.FunctionFlag data class VimFuncref( val handler: FunctionHandler, val arguments: VimList, var dictionary: VimDictionary?, val type: Type, ) : VimDataType() { var isSelfFixed = false companion object { var lambdaCounter = 1 var anonymousCounter = 1 } override fun asDouble(): Double { throw ExException("E703: using Funcref as a Number") } override fun asString(): String { throw ExException("E729: using Funcref as a String") } override fun toString(): String { return if (arguments.values.isEmpty() && dictionary == null) { when (type) { Type.LAMBDA -> "function('${handler.name}')" Type.FUNCREF -> "function('${handler.name}')" Type.FUNCTION -> handler.name } } else { val result = StringBuffer("function('${handler.name}'") if (arguments.values.isNotEmpty()) { result.append(", ").append(arguments.toString()) } result.append(")") return result.toString() } } override fun toVimNumber(): VimInt { throw ExException("E703: using Funcref as a Number") } fun execute(name: String, args: List<Expression>, editor: VimEditor, context: ExecutionContext, vimContext: VimLContext): VimDataType { if (handler is DefinedFunctionHandler && handler.function.flags.contains(FunctionFlag.DICT)) { if (dictionary == null) { throw ExException("E725: Calling dict function without Dictionary: $name") } else { injector.variableService.storeVariable( Variable(Scope.LOCAL_VARIABLE, "self"), dictionary!!, editor, context, handler.function ) } } val allArguments = listOf(this.arguments.values.map { SimpleExpression(it) }, args).flatten() if (handler is DefinedFunctionHandler && handler.function.isDeleted) { throw ExException("E933: Function was deleted: ${handler.name}") } val handler = when (type) { Type.LAMBDA, Type.FUNCREF -> this.handler Type.FUNCTION -> { injector.functionService.getFunctionHandlerOrNull(handler.scope, handler.name, vimContext) ?: throw ExException("E117: Unknown function: ${handler.name}") } } return handler.executeFunction(allArguments, editor, context, vimContext) } override fun deepCopy(level: Int): VimFuncref { return copy() } override fun lockVar(depth: Int) { this.isLocked = true } override fun unlockVar(depth: Int) { this.isLocked = false } enum class Type { LAMBDA, FUNCREF, FUNCTION, } }
mit
78378f90ee3a92fce1ef02ff21df42db
30.566372
137
0.695542
4.133256
false
false
false
false
LittleLightCz/SheepsGoHome
core/src/com/sheepsgohome/screens/SettingsScreen.kt
1
1546
package com.sheepsgohome.screens import com.badlogic.gdx.Gdx import com.badlogic.gdx.scenes.scene2d.ui.Label import com.badlogic.gdx.scenes.scene2d.ui.Table import com.sheepsgohome.gdx.screens.switchScreen import com.sheepsgohome.gdx.screens.switchToMainMenuScreen import com.sheepsgohome.shared.GameData import com.sheepsgohome.shared.GameData.loc import com.sheepsgohome.shared.GameSkins.skin import com.sheepsgohome.ui.BigSheepButton import com.sheepsgohome.ui.SmallSheepButton import com.sheepsgohome.ui.onClick class SettingsScreen : MenuScreen() { private val buttonControls = BigSheepButton(loc.get("controls")) private val buttonSound = BigSheepButton(loc.get("sound")) private val buttonBack = SmallSheepButton(loc.get("back")) private val title = Label(loc.get("settings"), skin, "menuTitle") init { buttonControls.onClick { switchScreen(ControlsSettingsScreen()) } buttonSound.onClick { switchScreen(SoundSettingsScreen()) } buttonBack.onClick { switchToMainMenuScreen() } title.setFontScale(GameData.SETTINGS_TITLE_FONT_SCALE) table.add(title) .top() .row() val buttonsTable = Table() buttonControls.addTo(buttonsTable).row() buttonSound.addTo(buttonsTable).row() table.add(buttonsTable).expandY().row() buttonBack.addTo(table) .bottom() .row() Gdx.input.inputProcessor = stage } }
gpl-3.0
9404bab4a894610054d1fde8362a2ed4
26.122807
69
0.679819
4.224044
false
false
false
false
android/architecture-components-samples
GithubBrowserSample/app/src/main/java/com/android/example/github/ui/user/UserViewModel.kt
1
2099
/* * Copyright (C) 2017 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.example.github.ui.user import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.switchMap import com.android.example.github.repository.RepoRepository import com.android.example.github.repository.UserRepository import com.android.example.github.testing.OpenForTesting import com.android.example.github.util.AbsentLiveData import com.android.example.github.vo.Repo import com.android.example.github.vo.Resource import com.android.example.github.vo.User import javax.inject.Inject @OpenForTesting class UserViewModel @Inject constructor(userRepository: UserRepository, repoRepository: RepoRepository) : ViewModel() { private val _login = MutableLiveData<String?>() val login: LiveData<String?> get() = _login val repositories: LiveData<Resource<List<Repo>>> = _login.switchMap { login -> if (login == null) { AbsentLiveData.create() } else { repoRepository.loadRepos(login) } } val user: LiveData<Resource<User>> = _login.switchMap { login -> if (login == null) { AbsentLiveData.create() } else { userRepository.loadUser(login) } } fun setLogin(login: String?) { if (_login.value != login) { _login.value = login } } fun retry() { _login.value?.let { _login.value = it } } }
apache-2.0
82d9aa55d86355199e7412279e2619ce
31.796875
99
0.69414
4.240404
false
false
false
false
ingokegel/intellij-community
plugins/markdown/core/src/org/intellij/plugins/markdown/editor/tables/actions/TableActionKeys.kt
1
1601
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.intellij.plugins.markdown.editor.tables.actions import com.intellij.openapi.actionSystem.* import com.intellij.openapi.editor.Editor import com.intellij.psi.PsiElement import java.awt.Container import java.lang.ref.WeakReference import javax.swing.JComponent internal object TableActionKeys { val ELEMENT = DataKey.create<WeakReference<PsiElement>>("TableBarElement") val COLUMN_INDEX = DataKey.create<Int>("TableBarColumnIndex") private class TableWrappingBackgroundDataProvider( private val base: JComponent, private val provider: DataProvider ) : JComponent(), DataProvider { override fun getParent(): Container = base override fun isShowing() = true override fun getData(dataId: String): Any? { return when { PlatformDataKeys.BGT_DATA_PROVIDER.`is`(dataId) -> provider else -> null } } } fun createActionToolbar(group: ActionGroup, isHorizontal: Boolean, editor: Editor, dataProvider: DataProvider? = null): ActionToolbar { val actionToolbar = ActionManager.getInstance().createActionToolbar(ActionPlaces.EDITOR_POPUP, group, isHorizontal) val dataContextComponent = dataProvider?.let { TableWrappingBackgroundDataProvider(editor.contentComponent, dataProvider) } actionToolbar.targetComponent = dataContextComponent actionToolbar.adjustTheSameSize(true) actionToolbar.setReservePlaceAutoPopupIcon(false) return actionToolbar } }
apache-2.0
a7b1da97354dd0916cae5076391843bf
40.051282
158
0.771393
4.779104
false
false
false
false
hzsweers/CatchUp
app/src/main/kotlin/io/sweers/catchup/data/GithubApolloModule.kt
1
5403
/* * Copyright (C) 2019. Zac Sweers * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.sweers.catchup.data import android.content.Context import com.apollographql.apollo3.ApolloClient import com.apollographql.apollo3.api.CompiledField import com.apollographql.apollo3.api.CustomScalarAdapters import com.apollographql.apollo3.api.Executable.Variables import com.apollographql.apollo3.api.http.DefaultHttpRequestComposer import com.apollographql.apollo3.api.http.HttpRequestComposer import com.apollographql.apollo3.cache.http.CachingHttpEngine import com.apollographql.apollo3.cache.http.DiskLruHttpCache import com.apollographql.apollo3.cache.http.internal.FileSystem import com.apollographql.apollo3.cache.normalized.CacheKey import com.apollographql.apollo3.cache.normalized.CacheKeyResolver import com.apollographql.apollo3.cache.normalized.MemoryCacheFactory import com.apollographql.apollo3.cache.normalized.NormalizedCacheFactory import com.apollographql.apollo3.cache.normalized.ObjectIdGenerator import com.apollographql.apollo3.cache.normalized.ObjectIdGeneratorContext import com.apollographql.apollo3.cache.normalized.withNormalizedCache import com.apollographql.apollo3.network.NetworkTransport import com.apollographql.apollo3.network.http.DefaultHttpEngine import com.apollographql.apollo3.network.http.HttpEngine import com.apollographql.apollo3.network.http.HttpNetworkTransport import dagger.Lazy import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent import io.sweers.catchup.BuildConfig import io.sweers.catchup.data.github.type.DateTime import io.sweers.catchup.data.github.type.URI import io.sweers.catchup.util.injection.qualifiers.ApplicationContext import io.sweers.catchup.util.network.AuthInterceptor import okhttp3.OkHttpClient import javax.inject.Qualifier import javax.inject.Singleton @InstallIn(SingletonComponent::class) @Module internal object GithubApolloModule { private const val SERVER_URL = "https://api.github.com/graphql" @Qualifier private annotation class InternalApi /** * TODO this hits disk on startup -_- */ @Provides @Singleton internal fun provideHttpCacheStore(@ApplicationContext context: Context): DiskLruHttpCache = DiskLruHttpCache(FileSystem.SYSTEM, context.cacheDir, 1_000_000) @Provides @InternalApi @Singleton internal fun provideGitHubOkHttpClient( client: OkHttpClient ): OkHttpClient = client.newBuilder() .addInterceptor(AuthInterceptor("token", BuildConfig.GITHUB_DEVELOPER_TOKEN)) .build() @Provides @Singleton internal fun provideObjectIdGenerator(): ObjectIdGenerator = object : ObjectIdGenerator { private val formatter = { id: String -> if (id.isEmpty()) { null } else { CacheKey.from(id) } } override fun cacheKeyForObject( obj: Map<String, Any?>, context: ObjectIdGeneratorContext ): CacheKey? { // Most objects use id obj["id"].let { return when (val value = it) { is String -> formatter(value) else -> null } } } } @Provides @Singleton internal fun provideCacheKeyResolver(): CacheKeyResolver = object : CacheKeyResolver() { override fun cacheKeyForField(field: CompiledField, variables: Variables): CacheKey? { return null } } @Provides @Singleton internal fun provideNormalizedCacheFactory(): NormalizedCacheFactory = MemoryCacheFactory() @Provides @Singleton internal fun provideHttpEngine( @InternalApi client: Lazy<OkHttpClient>, @ApplicationContext context: Context, ): HttpEngine { val delegate = DefaultHttpEngine { client.get().newCall(it) } return CachingHttpEngine( directory = context.cacheDir, maxSize = 1_000_000, delegate = delegate ) } @Provides @Singleton internal fun provideHttpRequestComposer(): HttpRequestComposer { return DefaultHttpRequestComposer(SERVER_URL) } @Provides @Singleton internal fun provideNetworkTransport( httpEngine: HttpEngine, httpRequestComposer: HttpRequestComposer ): NetworkTransport { return HttpNetworkTransport(httpRequestComposer, httpEngine) } @Provides @Singleton internal fun provideApolloClient( networkTransport: NetworkTransport, cacheFactory: NormalizedCacheFactory, cacheKeyResolver: CacheKeyResolver, objectIdGenerator: ObjectIdGenerator ): ApolloClient { return ApolloClient( networkTransport = networkTransport, customScalarAdapters = CustomScalarAdapters( mapOf( DateTime.type.name to ISO8601InstantApolloAdapter, URI.type.name to HttpUrlApolloAdapter, ) ), ).withNormalizedCache( cacheFactory, cacheResolver = cacheKeyResolver, objectIdGenerator = objectIdGenerator ) } }
apache-2.0
32e81d7e8fbd5c1be58696a225e0558f
31.353293
94
0.762909
4.582697
false
false
false
false
GunoH/intellij-community
plugins/kotlin/j2k/post-processing/src/org/jetbrains/kotlin/idea/j2k/post/processing/processings/ConvertGettersAndSettersToPropertyProcessing.kt
1
35027
// 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.j2k.post.processing.processings import com.intellij.psi.PsiComment import com.intellij.psi.PsiElement import com.intellij.psi.search.LocalSearchScope import com.intellij.psi.search.searches.OverridingMethodsSearch import com.intellij.refactoring.rename.RenamePsiElementProcessor import org.jetbrains.kotlin.asJava.toLightMethods import org.jetbrains.kotlin.caches.resolve.KotlinCacheService import org.jetbrains.kotlin.descriptors.ClassDescriptor import org.jetbrains.kotlin.descriptors.DeclarationDescriptor import org.jetbrains.kotlin.descriptors.FunctionDescriptor import org.jetbrains.kotlin.descriptors.VariableDescriptor import org.jetbrains.kotlin.idea.base.util.or import org.jetbrains.kotlin.idea.base.util.projectScope import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny import org.jetbrains.kotlin.idea.codeinsight.utils.isRedundantGetter import org.jetbrains.kotlin.idea.codeinsight.utils.isRedundantSetter import org.jetbrains.kotlin.idea.core.setVisibility import org.jetbrains.kotlin.idea.j2k.post.processing.* import org.jetbrains.kotlin.idea.refactoring.isAbstract import org.jetbrains.kotlin.idea.refactoring.isInterfaceClass import org.jetbrains.kotlin.idea.references.KtSimpleNameReference import org.jetbrains.kotlin.idea.references.mainReference import org.jetbrains.kotlin.idea.references.readWriteAccess import org.jetbrains.kotlin.idea.resolve.ResolutionFacade import org.jetbrains.kotlin.idea.search.usagesSearch.descriptor import org.jetbrains.kotlin.idea.util.CommentSaver import org.jetbrains.kotlin.idea.util.IdeDescriptorRenderers import com.intellij.openapi.application.runReadAction import org.jetbrains.kotlin.js.resolve.diagnostics.findPsi import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.nj2k.NewJ2kConverterContext import org.jetbrains.kotlin.nj2k.asGetterName import org.jetbrains.kotlin.nj2k.asSetterName import org.jetbrains.kotlin.nj2k.externalCodeProcessing.JKFakeFieldData import org.jetbrains.kotlin.nj2k.externalCodeProcessing.JKFieldData import org.jetbrains.kotlin.nj2k.externalCodeProcessing.JKPhysicalMethodData import org.jetbrains.kotlin.nj2k.externalCodeProcessing.NewExternalCodeProcessing import org.jetbrains.kotlin.nj2k.fqNameWithoutCompanions import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.* import org.jetbrains.kotlin.resolve.descriptorUtil.getSuperClassNotAny import org.jetbrains.kotlin.resolve.descriptorUtil.getSuperInterfaces import org.jetbrains.kotlin.resolve.sam.getSingleAbstractMethodOrNull import org.jetbrains.kotlin.resolve.scopes.DescriptorKindFilter import org.jetbrains.kotlin.resolve.scopes.getDescriptorsFiltered import org.jetbrains.kotlin.types.KotlinType import org.jetbrains.kotlin.types.checker.KotlinTypeChecker import org.jetbrains.kotlin.types.isError import org.jetbrains.kotlin.types.typeUtil.isUnit import org.jetbrains.kotlin.util.capitalizeDecapitalize.decapitalizeAsciiOnly import org.jetbrains.kotlin.util.isJavaDescriptor import org.jetbrains.kotlin.utils.addToStdlib.cast import org.jetbrains.kotlin.utils.addToStdlib.firstIsInstanceOrNull import org.jetbrains.kotlin.utils.addToStdlib.safeAs import org.jetbrains.kotlin.utils.mapToIndex internal class ConvertGettersAndSettersToPropertyProcessing : ElementsBasedPostProcessing() { override val options: PostProcessingOptions = PostProcessingOptions( disablePostprocessingFormatting = false // without it comment saver will make the file invalid :( ) override fun runProcessing(elements: List<PsiElement>, converterContext: NewJ2kConverterContext) { val ktElements = elements.filterIsInstance<KtElement>() if (ktElements.isEmpty()) return val resolutionFacade = runReadAction { KotlinCacheService.getInstance(converterContext.project).getResolutionFacade(ktElements) } ConvertGettersAndSettersToPropertyStatefulProcessing( resolutionFacade, ktElements, converterContext.externalCodeProcessor ).runProcessing() } } private class ConvertGettersAndSettersToPropertyStatefulProcessing( private val resolutionFacade: ResolutionFacade, private val elements: List<KtElement>, private val externalCodeUpdater: NewExternalCodeProcessing ) { private val searcher = JKInMemoryFilesSearcher.create(elements) fun runProcessing() { val collectingState = CollectingState() val classesWithPropertiesData = runReadAction { elements .descendantsOfType<KtClassOrObject>() .sortedByInheritance() .map { klass -> klass to klass.collectPropertiesData(collectingState) } } if (classesWithPropertiesData.isEmpty()) return runUndoTransparentActionInEdt(inWriteAction = true) { for ((klass, propertiesData) in classesWithPropertiesData) { convertClass(klass, propertiesData) } } } private fun KtNamedFunction.hasOverrides(): Boolean = toLightMethods().singleOrNull()?.let { lightMethod -> if (OverridingMethodsSearch.search(lightMethod).findFirst() != null) return@let true if (elements.size == 1) return@let false elements.any { element -> OverridingMethodsSearch.search(lightMethod, LocalSearchScope(element), true).findFirst() != null } } == true private fun KtNamedFunction.hasSuperFunction(): Boolean = resolveToDescriptorIfAny(resolutionFacade)?.original?.overriddenDescriptors?.isNotEmpty() == true private fun KtNamedFunction.hasInvalidSuperDescriptors(): Boolean = resolveToDescriptorIfAny(resolutionFacade) ?.original ?.overriddenDescriptors ?.any { it.isJavaDescriptor || it is FunctionDescriptor } == true private fun KtExpression.statements() = if (this is KtBlockExpression) statements else listOf(this) private fun KtNamedFunction.asGetter(): Getter? { val name = name?.asGetterName() ?: return null if (valueParameters.isNotEmpty()) return null if (typeParameters.isNotEmpty()) return null val singleTimeUsedTarget = bodyExpression ?.statements() ?.singleOrNull() ?.safeAs<KtReturnExpression>() ?.returnedExpression ?.unpackedReferenceToProperty() ?.takeIf { it.type() == (type() ?: return@takeIf false) } return RealGetter(this, singleTimeUsedTarget, name, singleTimeUsedTarget != null) } private fun KtNamedFunction.asSetter(): Setter? { val name = name?.asSetterName() ?: return null if (typeParameters.isNotEmpty()) return null if (valueParameters.size != 1) return null val descriptor = resolveToDescriptorIfAny() ?: return null if (descriptor.returnType?.isUnit() != true) return null val singleTimeUsedTarget = bodyExpression ?.statements() ?.singleOrNull() ?.let { expression -> if (expression is KtBinaryExpression) { if (expression.operationToken != KtTokens.EQ) return@let null val right = expression.right as? KtNameReferenceExpression ?: return@let null if (right.resolve() != valueParameters.single()) return@let null expression.left?.unpackedReferenceToProperty() } else null }?.takeIf { it.type() == valueParameters.single().type() } return RealSetter(this, singleTimeUsedTarget, name, singleTimeUsedTarget != null) } private fun KtDeclaration.asPropertyAccessor(): PropertyInfo? { return when (this) { is KtProperty -> RealProperty(this, name ?: return null) is KtNamedFunction -> asGetter() ?: asSetter() else -> null } } private fun KtElement.forAllUsages(action: (KtElement) -> Unit) { usages().forEach { action(it.element as KtElement) } } private fun addGetter( getter: Getter, property: KtProperty, factory: KtPsiFactory, isFakeProperty: Boolean ): KtPropertyAccessor { val body = if (isFakeProperty) getter.body else getter.body?.withReplacedExpressionInBody( property, factory.createExpression(KtTokens.FIELD_KEYWORD.value), replaceOnlyWriteUsages = false ) val ktGetter = factory.createGetter(body, getter.modifiersText) ktGetter.filterModifiers() if (getter is RealGetter) { savePossibleLeadingAndTrailingComments(getter, ktGetter, factory) } property.add(factory.createNewLine(1)) return property.add(ktGetter).cast<KtPropertyAccessor>().also { if (getter is RealGetter) { getter.function.forAllUsages { usage -> val callExpression = usage.getStrictParentOfType<KtCallExpression>() ?: return@forAllUsages val qualifier = callExpression.getQualifiedExpressionForSelector() if (qualifier != null) { qualifier.replace(factory.createExpression("${qualifier.receiverExpression.text}.${getter.name}")) } else { callExpression.replace(factory.createExpression("this.${getter.name}")) } } } } } private fun KtParameter.rename(newName: String) { val renamer = RenamePsiElementProcessor.forElement(this) val searchScope = project.projectScope() or useScope val findReferences = renamer.findReferences(this, searchScope, false) val usageInfos = findReferences.mapNotNull { reference -> val element = reference.element val isBackingField = element is KtNameReferenceExpression && element.text == KtTokens.FIELD_KEYWORD.value && element.mainReference.resolve() == this && isAncestor(element) if (isBackingField) return@mapNotNull null renamer.createUsageInfo(this, reference, reference.element) }.toTypedArray() renamer.renameElement(this, newName, usageInfos, null) } private fun createSetter( setter: Setter, property: KtProperty, factory: KtPsiFactory, isFakeProperty: Boolean ): KtPropertyAccessor { if (setter is RealSetter) { setter.function.valueParameters.single().rename(setter.parameterName) } val body = if (isFakeProperty) setter.body else setter.body?.withReplacedExpressionInBody( property, factory.createExpression(KtTokens.FIELD_KEYWORD.value), true ) val modifiers = setter.modifiersText?.takeIf { it.isNotEmpty() } ?: setter.safeAs<RealSetter>()?.function?.visibilityModifierTypeOrDefault()?.value ?: property.visibilityModifierTypeOrDefault().value val ktSetter = factory.createSetter( body, setter.parameterName, modifiers ) ktSetter.filterModifiers() val propertyName = property.name if (setter is RealSetter) { savePossibleLeadingAndTrailingComments(setter, ktSetter, factory) setter.function.forAllUsages { usage -> val callExpression = usage.getStrictParentOfType<KtCallExpression>() ?: return@forAllUsages val qualifier = callExpression.getQualifiedExpressionForSelector() val newValue = callExpression.valueArguments.single() if (qualifier != null) { qualifier.replace( factory.createExpression("${qualifier.receiverExpression.text}.$propertyName = ${newValue.text}") ) } else { callExpression.replace(factory.createExpression("this.$propertyName = ${newValue.text}")) } } } return ktSetter } private fun savePossibleLeadingAndTrailingComments( accessor: RealAccessor, ktAccessor: KtPropertyAccessor, factory: KtPsiFactory ) { if (accessor.function.firstChild is PsiComment) { ktAccessor.addBefore(factory.createWhiteSpace(), ktAccessor.firstChild) ktAccessor.addBefore(accessor.function.firstChild, ktAccessor.firstChild) } if (accessor.function.lastChild is PsiComment) { ktAccessor.add(factory.createWhiteSpace()) ktAccessor.add(accessor.function.lastChild) } } private fun KtPropertyAccessor.filterModifiers() { removeModifier(KtTokens.OVERRIDE_KEYWORD) removeModifier(KtTokens.FINAL_KEYWORD) removeModifier(KtTokens.OPEN_KEYWORD) } private fun KtExpression.isReferenceToThis() = when (this) { is KtThisExpression -> instanceReference is KtReferenceExpression -> this is KtQualifiedExpression -> selectorExpression as? KtReferenceExpression else -> null }?.resolve() == getStrictParentOfType<KtClassOrObject>() private fun KtElement.usages(scope: PsiElement? = null) = searcher.search(this, scope) private fun <T : KtExpression> T.withReplacedExpressionInBody( from: KtElement, to: KtExpression, replaceOnlyWriteUsages: Boolean ): T = also { from.usages(this) .asSequence() .map { it.element } .forEach { reference -> val parent = reference.parent val referenceExpression = when { parent is KtQualifiedExpression && parent.receiverExpression.isReferenceToThis() -> parent else -> reference } if (!replaceOnlyWriteUsages || (referenceExpression.parent as? KtExpression)?.asAssignment()?.left == referenceExpression ) { referenceExpression.replace(to) } } } private fun List<KtClassOrObject>.sortedByInheritance(): List<KtClassOrObject> { fun ClassDescriptor.superClassAndSuperInterfaces() = getSuperInterfaces() + listOfNotNull(getSuperClassNotAny()) val sorted = mutableListOf<KtClassOrObject>() val visited = Array(size) { false } val descriptors = map { it.resolveToDescriptorIfAny(resolutionFacade)!! } val descriptorToIndex = descriptors.mapToIndex() val outers = descriptors.map { descriptor -> descriptor.superClassAndSuperInterfaces().mapNotNull { descriptorToIndex[it] } } fun dfs(current: Int) { visited[current] = true for (outer in outers[current]) { if (!visited[outer]) { dfs(outer) } } sorted.add(get(current)) } for (index in descriptors.indices) { if (!visited[index]) { dfs(index) } } return sorted } private fun causesNameConflictInCurrentDeclarationAndItsParents(name: String, declaration: DeclarationDescriptor?): Boolean = when (declaration) { is ClassDescriptor -> { declaration.unsubstitutedMemberScope.getDescriptorsFiltered(DescriptorKindFilter.VARIABLES) { it.asString() == name }.isNotEmpty() || causesNameConflictInCurrentDeclarationAndItsParents(name, declaration.containingDeclaration) } else -> false } private fun calculatePropertyType(getterType: KotlinType?, setterType: KotlinType?): KotlinType? = when { getterType != null && getterType.isMarkedNullable -> getterType setterType != null && setterType.isMarkedNullable -> setterType else -> getterType ?: setterType } private fun calculatePropertyType(getter: KtNamedFunction?, setter: KtNamedFunction?): KotlinType? { val getterType = getter?.resolveToDescriptorIfAny(resolutionFacade)?.returnType val setterType = setter?.resolveToDescriptorIfAny(resolutionFacade)?.valueParameters?.singleOrNull()?.type return calculatePropertyType(getterType, setterType) } private inline fun <reified A : RealAccessor> A.withTargetSet(property: RealProperty?): A { if (property == null) return this if (target != null) return this return if (property.property.usages(function).any()) updateTarget(property.property) as A else this } private fun KtClassOrObject.collectPropertiesData(collectingState: CollectingState): List<PropertyData> { return declarations .asSequence() .mapNotNull { it.asPropertyAccessor() } .groupBy { it.name.removePrefix("is").decapitalizeAsciiOnly() } .values .mapNotNull { group -> val realGetter = group.firstIsInstanceOrNull<RealGetter>() val realSetter = group.firstIsInstanceOrNull<RealSetter>()?.takeIf { setter -> if (realGetter == null) return@takeIf true val setterType = setter.function.valueParameters.first().type() val getterType = realGetter.function.type() if (setterType == null || getterType == null || !KotlinTypeChecker.DEFAULT.isSubtypeOf(getterType, setterType) ) { if (isInterfaceClass()) return@mapNotNull null false } else true } if (realGetter == null && realSetter == null) return@mapNotNull null val realProperty = group.firstIsInstanceOrNull<RealProperty>() val name = realGetter?.name ?: realSetter?.name!! val functionDescriptor = (realGetter?.function ?: realSetter?.function) ?.resolveToDescriptorIfAny(resolutionFacade) if (functionDescriptor != null && isSamDescriptor(functionDescriptor)) return@mapNotNull null val superDeclarationOwner = functionDescriptor ?.overriddenDescriptors ?.firstOrNull() ?.findPsi() ?.safeAs<KtDeclaration>() ?.containingClassOrObject val type = collectingState.propertyNameToSuperType[superDeclarationOwner to name] ?: calculatePropertyType( realGetter?.function, realSetter?.function ) ?: return@mapNotNull null collectingState.propertyNameToSuperType[this to name] = type PropertyData( realProperty, realGetter?.withTargetSet(realProperty), realSetter?.withTargetSet(realProperty), type ) } } private fun KtClassOrObject.isSamDescriptor(functionDescriptor: FunctionDescriptor): Boolean { val classDescriptor = descriptor as? ClassDescriptor ?: return false return getSingleAbstractMethodOrNull(classDescriptor) == functionDescriptor } private fun List<PropertyData>.filterGettersAndSetters( klass: KtClassOrObject, factory: KtPsiFactory ): List<PropertyWithAccessors> { val classDescriptor = klass.resolveToDescriptorIfAny(resolutionFacade) ?: return emptyList() val variablesDescriptorsMap = (listOfNotNull(classDescriptor.getSuperClassNotAny()) + classDescriptor.getSuperInterfaces()) .flatMap { superClass -> superClass .unsubstitutedMemberScope .getDescriptorsFiltered(DescriptorKindFilter.VARIABLES) } .asSequence() .filterIsInstance<VariableDescriptor>() .associateBy { it.name.asString() } return mapNotNull { (realProperty, realGetter, realSetter, type) -> val name = realGetter?.name ?: realSetter!!.name val typeStringified = type .takeUnless { it.isError } ?.let { IdeDescriptorRenderers.SOURCE_CODE.renderType(it) } ?: realGetter?.function?.typeReference?.text ?: realSetter?.function?.valueParameters?.firstOrNull()?.typeReference?.text!! if (realSetter != null && realGetter != null && klass.isInterfaceClass() && realSetter.function.hasOverrides() != realGetter.function.hasOverrides() ) return@mapNotNull null if (realSetter != null && realGetter != null && realSetter.function.hasSuperFunction() != realGetter.function.hasSuperFunction() ) return@mapNotNull null if (realProperty != null && realGetter?.target != null && realGetter.target != realProperty.property && realProperty.property.hasInitializer() ) return@mapNotNull null if (realGetter?.function?.hasInvalidSuperDescriptors() == true || realSetter?.function?.hasInvalidSuperDescriptors() == true ) return@mapNotNull null if (realProperty == null) { if (causesNameConflictInCurrentDeclarationAndItsParents( name, classDescriptor.containingDeclaration ) ) return@mapNotNull null } if (realProperty != null && (realGetter != null && !realGetter.isPure || realSetter != null && !realSetter.isPure)) { if (!realProperty.property.isPrivate()) return@mapNotNull null val hasUsages = realProperty.property.hasUsagesOutsideOf( klass.containingKtFile, listOfNotNull(realGetter?.function, realSetter?.function) ) if (hasUsages) return@mapNotNull null } if (realSetter != null && realProperty != null) { val assignFieldOfOtherInstance = realProperty.property.usages().any { usage -> val element = usage.safeAs<KtSimpleNameReference>()?.element ?: return@any false if (!element.readWriteAccess(useResolveForReadWrite = true).isWrite) return@any false val parent = element.parent parent is KtQualifiedExpression && !parent.receiverExpression.isReferenceToThis() } if (assignFieldOfOtherInstance) return@mapNotNull null } if (realGetter != null && realProperty != null) { val getFieldOfOtherInstanceInGetter = realProperty.property.usages().any { usage -> val element = usage.safeAs<KtSimpleNameReference>()?.element ?: return@any false val parent = element.parent parent is KtQualifiedExpression && !parent.receiverExpression.isReferenceToThis() && realGetter.function.isAncestor(element) } if (getFieldOfOtherInstanceInGetter) return@mapNotNull null } val getter = realGetter ?: when { realProperty?.property?.resolveToDescriptorIfAny(resolutionFacade)?.overriddenDescriptors?.any { it.safeAs<VariableDescriptor>()?.isVar == true } == true -> FakeGetter(name, null, "") variablesDescriptorsMap[name]?.let { variable -> variable.isVar && variable.containingDeclaration != classDescriptor } == true -> FakeGetter(name, factory.createExpression("super.$name"), "") else -> return@mapNotNull null } val mergedProperty = if (getter is RealGetter && getter.target != null && getter.target!!.name != getter.name && (realSetter == null || realSetter.target != null) ) { MergedProperty(name, typeStringified, realSetter != null, getter.target!!) } else null val setter = realSetter ?: when { realProperty?.property?.isVar == true -> FakeSetter(name, null, "") realProperty?.property?.resolveToDescriptorIfAny(resolutionFacade)?.overriddenDescriptors?.any { it.safeAs<VariableDescriptor>()?.isVar == true } == true || variablesDescriptorsMap[name]?.isVar == true -> FakeSetter( name, factory.createBlock("super.$name = $name"), "" ) realGetter != null && (realProperty != null && realProperty.property.visibilityModifierTypeOrDefault() != realGetter.function.visibilityModifierTypeOrDefault() && realProperty.property.isVar || mergedProperty != null && mergedProperty.mergeTo.visibilityModifierTypeOrDefault() != realGetter.function.visibilityModifierTypeOrDefault() && mergedProperty.mergeTo.isVar ) -> FakeSetter(name, null, null) else -> null } val isVar = setter != null val property = mergedProperty?.copy(isVar = isVar) ?: realProperty?.copy(isVar = isVar) ?: FakeProperty(name, typeStringified, isVar) PropertyWithAccessors( property, getter, setter ) } } private fun KtProperty.renameTo(newName: String, factory: KtPsiFactory) { for (usage in usages()) { val element = usage.element val isBackingField = element is KtNameReferenceExpression && element.text == KtTokens.FIELD_KEYWORD.value && element.mainReference.resolve() == this && isAncestor(element) if (isBackingField) continue val replacer = if (element.parent is KtQualifiedExpression) factory.createExpression(newName) else factory.createExpression("this.$newName") element.replace(replacer) } setName(newName) } private fun convertClass( klass: KtClassOrObject, propertiesData: List<PropertyData> ) { val factory = KtPsiFactory(klass) val accessors = propertiesData.filterGettersAndSetters(klass, factory) for ((property, getter, setter) in accessors) { val ktProperty = when (property) { is RealProperty -> { if (property.property.isVar != property.isVar) { property.property.valOrVarKeyword.replace( if (property.isVar) factory.createVarKeyword() else factory.createValKeyword() ) } property.property } is FakeProperty -> factory.createProperty(property.name, property.type, property.isVar).let { val anchor = getter.safeAs<RealAccessor>()?.function ?: setter.cast<RealAccessor>().function klass.addDeclarationBefore(it, anchor) } is MergedProperty -> { property.mergeTo } } val propertyInfo = when (property) { is RealProperty -> property.property.let(externalCodeUpdater::getMember) is MergedProperty -> property.mergeTo.let(externalCodeUpdater::getMember) is FakeProperty -> JKFakeFieldData( isStatic = klass is KtObjectDeclaration, kotlinElementPointer = null, fqName = klass.fqNameWithoutCompanions.child(Name.identifier(property.name)), name = property.name ).also { externalCodeUpdater.addMember(it) } }?.also { it.name = property.name } as? JKFieldData fun KtNamedDeclaration.setPropertyInfo(info: JKFieldData) { externalCodeUpdater.getMember(this)?.safeAs<JKPhysicalMethodData>()?.let { it.usedAsAccessorOfProperty = info } } if (propertyInfo != null) { getter.safeAs<RealGetter>()?.function?.setPropertyInfo(propertyInfo) setter.safeAs<RealSetter>()?.function?.setPropertyInfo(propertyInfo) } val isOpen = getter.safeAs<RealGetter>()?.function?.hasModifier(KtTokens.OPEN_KEYWORD) == true || setter.safeAs<RealSetter>()?.function?.hasModifier(KtTokens.OPEN_KEYWORD) == true val ktGetter = addGetter(getter, ktProperty, factory, property.isFake) val ktSetter = setter?.let { createSetter(it, ktProperty, factory, property.isFake) } val getterVisibility = getter.safeAs<RealGetter>()?.function?.visibilityModifierTypeOrDefault() if (getter is RealGetter) { if (getter.function.isAbstract()) { ktProperty.addModifier(KtTokens.ABSTRACT_KEYWORD) } if (ktGetter.isRedundantGetter()) { val commentSaver = CommentSaver(getter.function) commentSaver.restore(ktProperty) } getter.function.delete() } if (setter is RealSetter) { if (ktSetter?.isRedundantSetter() == true) { val commentSaver = CommentSaver(setter.function) commentSaver.restore(ktProperty) } setter.function.delete() } // If getter & setter do not have backing fields we should remove initializer // As we already know that property is not directly used in the code if (getter.target == null && setter?.target == null) { ktProperty.initializer = null } val propertyVisibility = ktProperty.visibilityModifierTypeOrDefault() getterVisibility?.let { ktProperty.setVisibility(it) } if (ktSetter != null) { if (setter !is RealSetter) { ktSetter.setVisibility(propertyVisibility) } ktProperty.addAfter(ktSetter, ktGetter) } if (property is MergedProperty) { ktProperty.renameTo(property.name, factory) } if (isOpen) { ktProperty.addModifier(KtTokens.OPEN_KEYWORD) } } } } private data class PropertyWithAccessors( val property: Property, val getter: Getter, val setter: Setter? ) private data class PropertyData( val realProperty: RealProperty?, val realGetter: RealGetter?, val realSetter: RealSetter?, val type: KotlinType ) private interface PropertyInfo { val name: String } private interface Accessor : PropertyInfo { val target: KtProperty? val body: KtExpression? val modifiersText: String? val isPure: Boolean } private sealed class Property : PropertyInfo { abstract val isVar: Boolean } private data class RealProperty( val property: KtProperty, override val name: String, override val isVar: Boolean = property.isVar ) : Property() private data class FakeProperty(override val name: String, val type: String, override val isVar: Boolean) : Property() private data class MergedProperty( override val name: String, val type: String, override val isVar: Boolean, val mergeTo: KtProperty ) : Property() private sealed class Getter : Accessor private sealed class Setter : Accessor { abstract val parameterName: String } private interface FakeAccessor : Accessor { override val target: KtProperty? get() = null override val isPure: Boolean get() = true } private interface RealAccessor : Accessor { val function: KtNamedFunction override val body: KtExpression? get() = function.bodyExpression override val modifiersText: String get() = function.modifierList?.text.orEmpty() fun updateTarget(newTarget: KtProperty): RealAccessor } private data class RealGetter( override val function: KtNamedFunction, override val target: KtProperty?, override val name: String, override val isPure: Boolean ) : Getter(), RealAccessor { override fun updateTarget(newTarget: KtProperty): RealGetter = copy(target = newTarget) } private data class FakeGetter( override val name: String, override val body: KtExpression?, override val modifiersText: String ) : Getter(), FakeAccessor private data class RealSetter( override val function: KtNamedFunction, override val target: KtProperty?, override val name: String, override val isPure: Boolean ) : Setter(), RealAccessor { override val parameterName: String get() = (function.valueParameters.first().name ?: name).fixSetterParameterName() override fun updateTarget(newTarget: KtProperty): RealSetter = copy(target = newTarget) } private data class FakeSetter( override val name: String, override val body: KtExpression?, override val modifiersText: String? ) : Setter(), FakeAccessor { override val parameterName: String get() = name.fixSetterParameterName() } private data class CollectingState( val propertyNameToSuperType: MutableMap<Pair<KtClassOrObject, String>, KotlinType> = mutableMapOf() ) private fun String.fixSetterParameterName() = if (this == KtTokens.FIELD_KEYWORD.value) "value" else this private val PropertyInfo.isFake: Boolean get() = this is FakeAccessor
apache-2.0
62808e9d25d5bae1a2381377dfe685b6
41.09976
140
0.621349
5.802054
false
false
false
false
Shoebill/shoebill-common
src/main/java/net/gtaun/shoebill/common/vehicle/VehicleLifecycleHolder.kt
1
1654
package net.gtaun.shoebill.common.vehicle import net.gtaun.shoebill.Shoebill import net.gtaun.shoebill.common.LifecycleHolder import net.gtaun.shoebill.entities.Vehicle import net.gtaun.shoebill.event.destroyable.DestroyEvent import net.gtaun.shoebill.event.vehicle.VehicleCreateEvent import net.gtaun.util.event.EventManager import net.gtaun.util.event.HandlerPriority import kotlin.reflect.KClass class VehicleLifecycleHolder @JvmOverloads constructor(eventManager: EventManager = Shoebill.get().eventManager) : LifecycleHolder<Vehicle>(eventManager) { init { eventManagerNode.registerHandler(VehicleCreateEvent::class, { buildObjects(it.vehicle) }, HandlerPriority.MONITOR) eventManagerNode.registerHandler(DestroyEvent::class, { if (it.destroyable is Vehicle) { destroyObjects(it.destroyable as Vehicle) } }, HandlerPriority.BOTTOM) } fun <B : VehicleLifecycleObject> registerClass(lifecycleObject: Class<B>) = registerClass(lifecycleObject, makeFactory(lifecycleObject.kotlin)) companion object { fun <B : VehicleLifecycleObject> makeFactory(clazz: KClass<B>) = object : LifecycleFactory<Vehicle, B> { override fun create(input: Vehicle): B { val constructor = clazz.constructors.firstOrNull { it.parameters.size == 1 && it.parameters.first().type == Vehicle::class } ?: throw Exception("No valid constructor available for class $clazz.") return constructor.call(input) } } } }
apache-2.0
6963ff41a000d55b0ed0ee8ea2ddf7c7
34.956522
114
0.67896
4.659155
false
false
false
false
google/accompanist
insets-ui/src/main/java/com/google/accompanist/insets/ui/BottomNavigation.kt
1
3512
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.accompanist.insets.ui import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.RowScope import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.selection.selectableGroup import androidx.compose.material.BottomNavigation import androidx.compose.material.BottomNavigationDefaults import androidx.compose.material.MaterialTheme import androidx.compose.material.Surface import androidx.compose.material.contentColorFor import androidx.compose.material.primarySurface import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp /** * A wrapper around [BottomNavigation] which supports the setting of [contentPadding] to add * internal padding. This is especially useful in conjunction with insets. * * For an edge-to-edge layout, typically you would use the * [com.google.accompanist.insets.WindowInsets.navigationBars] insets like so below: * * @sample com.google.accompanist.sample.insets.BottomNavigation_Insets */ @Composable fun BottomNavigation( modifier: Modifier = Modifier, contentPadding: PaddingValues = PaddingValues(0.dp), backgroundColor: Color = MaterialTheme.colors.primarySurface, contentColor: Color = contentColorFor(backgroundColor), elevation: Dp = BottomNavigationDefaults.Elevation, content: @Composable RowScope.() -> Unit, ) { BottomNavigationSurface(modifier, backgroundColor, contentColor, elevation) { BottomNavigationContent(Modifier.padding(contentPadding)) { content() } } } @Composable fun BottomNavigationSurface( modifier: Modifier = Modifier, backgroundColor: Color = MaterialTheme.colors.primarySurface, contentColor: Color = contentColorFor(backgroundColor), elevation: Dp = BottomNavigationDefaults.Elevation, content: @Composable () -> Unit ) { Surface( color = backgroundColor, contentColor = contentColor, elevation = elevation, modifier = modifier, ) { content() } } @Composable fun BottomNavigationContent( modifier: Modifier = Modifier, content: @Composable RowScope.() -> Unit, ) { Row( modifier = modifier .fillMaxWidth() .height(BottomNavigationHeight) .selectableGroup(), horizontalArrangement = Arrangement.SpaceBetween, content = content, ) } /** * Copied from [androidx.compose.material.BottomNavigationHeight] * Height of a [BottomNavigation] component */ private val BottomNavigationHeight = 56.dp
apache-2.0
b5f529762ad3fa825a4561d542d25b1b
33.772277
92
0.756549
4.739541
false
false
false
false
abertschi/ad-free
app/src/main/java/ch/abertschi/adfree/view/about/AboutActivity.kt
1
2508
/* * Ad Free * Copyright (c) 2017 by abertschi, www.abertschi.ch * See the file "LICENSE" for the full license governing this code. */ package ch.abertschi.adfree.view.setting import android.annotation.SuppressLint import android.content.Intent import android.graphics.Typeface import android.net.Uri import android.os.Bundle import android.support.v4.app.Fragment import android.text.Html import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.TextView import ch.abertschi.adfree.BuildConfig import ch.abertschi.adfree.R import ch.abertschi.adfree.di.AboutModul import ch.abertschi.adfree.presenter.AboutPresenter import ch.abertschi.adfree.view.ViewSettings import ch.abertschi.adfree.view.about.AboutView import org.jetbrains.anko.onClick /** * Created by abertschi on 21.04.17. */ class AboutActivity : Fragment(), AboutView { lateinit var typeFace: Typeface lateinit var presenter: AboutPresenter override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { return inflater?.inflate(R.layout.about_view, container, false) } @SuppressLint("SetTextI18n") override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) typeFace = ViewSettings.instance(this.context!!).typeFace presenter = AboutModul(this.activity!!, this).provideAboutPresenter() val textView = view?.findViewById(R.id.authorTitle) as TextView textView.typeface = typeFace val text = "built with much &lt;3 by <font color=#FFFFFF>abertschi</font>. " + "get my latest hacks and follow me on twitter." textView?.text = Html.fromHtml(text) view.findViewById<ImageView>(R.id.twitter).onClick { val browserIntent = Intent(Intent.ACTION_VIEW, Uri.parse("https://twitter.com/andrinbertschi?rel=adfree")) this.context!!.startActivity(browserIntent) } view.findViewById<ImageView>(R.id.website).onClick { val browserIntent = Intent(Intent.ACTION_VIEW, Uri.parse("http://abertschi.ch?rel=adfree")) this.context!!.startActivity(browserIntent) } view.findViewById<ImageView>(R.id.moresettings).onClick { presenter.showMoreSettings() } } }
apache-2.0
6dcefaec7449fe55f7f3a10fb4a05298
32.891892
83
0.697368
4.376963
false
false
false
false
JetBrains-Research/viktor
src/test/kotlin/org/jetbrains/bio/viktor/SerializationTests.kt
1
2098
package org.jetbrains.bio.viktor import org.jetbrains.bio.npy.NpyFile import org.jetbrains.bio.npy.NpzFile import org.junit.Test import kotlin.test.assertEquals class TestReadWriteNpy { @Test fun vector() = withTempFile("v", ".npy") { path -> val v = F64Array.of(1.0, 2.0, 3.0, 4.0) NpyFile.write(path, v) assertEquals(v, NpyFile.read(path).asF64Array()) } @Test fun matrix2() = withTempFile("m2", ".npy") { path -> val m = F64Array.of(1.0, 2.0, 3.0, 4.0, 5.0, 6.0).reshape(2, 3) NpyFile.write(path, m) assertEquals(m, NpyFile.read(path).asF64Array()) } @Test fun matrix3() = withTempFile("m3", ".npy") { path -> val m = F64Array.of(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0) .reshape(1, 4, 2) NpyFile.write(path, m) assertEquals(m, NpyFile.read(path).asF64Array()) } @Test fun nonFlattenable() = withTempFile("nf", ".npy") { path -> val m = F64Array.of( 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0 ).reshape(2, 2, 2).view(1, 1) NpyFile.write(path, m) assertEquals(m, NpyFile.read(path).asF64Array()) } } class TestReadWriteNpz { @Test fun combined() { val v = F64Array.of(1.0, 2.0, 3.0, 4.0) val m2 = F64Array.of(1.0, 2.0, 3.0, 4.0, 5.0, 6.0).reshape(2, 3) val m3 = F64Array.of( 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0 ).reshape(1, 4, 2) val nf = F64Array.of( 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0 ).reshape(2, 2, 2).view(1, 1) withTempFile("vm2m3", ".npz") { path -> NpzFile.write(path).use { it.write("v", v) it.write("m2", m2) it.write("m3", m3) it.write("nf", nf) } NpzFile.read(path).use { assertEquals(v, it["v"].asF64Array()) assertEquals(m2, it["m2"].asF64Array()) assertEquals(m3, it["m3"].asF64Array()) assertEquals(nf, it["nf"].asF64Array()) } } } }
mit
4ba86f75aba0699171f094e2ad5ded15
31.292308
72
0.505243
2.67602
false
true
false
false
google/android-fhir
demo/src/main/java/com/google/android/fhir/demo/AddPatientFragment.kt
1
3886
/* * Copyright 2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.fhir.demo import android.os.Bundle import android.view.Menu import android.view.MenuInflater import android.view.MenuItem import android.view.View import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import androidx.core.os.bundleOf import androidx.fragment.app.Fragment import androidx.fragment.app.commit import androidx.fragment.app.viewModels import androidx.navigation.fragment.NavHostFragment import com.google.android.fhir.datacapture.QuestionnaireFragment import org.hl7.fhir.r4.model.QuestionnaireResponse /** A fragment class to show patient registration screen. */ class AddPatientFragment : Fragment(R.layout.add_patient_fragment) { private val viewModel: AddPatientViewModel by viewModels() override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) setUpActionBar() setHasOptionsMenu(true) updateArguments() if (savedInstanceState == null) { addQuestionnaireFragment() } observePatientSaveAction() (activity as MainActivity).setDrawerEnabled(false) } override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { super.onCreateOptionsMenu(menu, inflater) inflater.inflate(R.menu.add_patient_fragment_menu, menu) } override fun onOptionsItemSelected(item: MenuItem): Boolean { return when (item.itemId) { R.id.action_add_patient_submit -> { onSubmitAction() true } android.R.id.home -> { NavHostFragment.findNavController(this).navigateUp() true } else -> super.onOptionsItemSelected(item) } } private fun setUpActionBar() { (requireActivity() as AppCompatActivity).supportActionBar?.apply { title = requireContext().getString(R.string.add_patient) setDisplayHomeAsUpEnabled(true) } } private fun updateArguments() { requireArguments() .putString(QUESTIONNAIRE_FILE_PATH_KEY, "new-patient-registration-paginated.json") } private fun addQuestionnaireFragment() { val fragment = QuestionnaireFragment() fragment.arguments = bundleOf(QuestionnaireFragment.EXTRA_QUESTIONNAIRE_JSON_STRING to viewModel.questionnaire) childFragmentManager.commit { add(R.id.add_patient_container, fragment, QUESTIONNAIRE_FRAGMENT_TAG) } } private fun onSubmitAction() { val questionnaireFragment = childFragmentManager.findFragmentByTag(QUESTIONNAIRE_FRAGMENT_TAG) as QuestionnaireFragment savePatient(questionnaireFragment.getQuestionnaireResponse()) } private fun savePatient(questionnaireResponse: QuestionnaireResponse) { viewModel.savePatient(questionnaireResponse) } private fun observePatientSaveAction() { viewModel.isPatientSaved.observe(viewLifecycleOwner) { if (!it) { Toast.makeText(requireContext(), "Inputs are missing.", Toast.LENGTH_SHORT).show() return@observe } Toast.makeText(requireContext(), "Patient is saved.", Toast.LENGTH_SHORT).show() NavHostFragment.findNavController(this).navigateUp() } } companion object { const val QUESTIONNAIRE_FILE_PATH_KEY = "questionnaire-file-path-key" const val QUESTIONNAIRE_FRAGMENT_TAG = "questionnaire-fragment-tag" } }
apache-2.0
9fd379b71d7fa2bdfa05ba09449118e1
32.5
97
0.743695
4.62069
false
false
false
false
techlung/MortalityDayAndroid
app/src/main/java/com/techlung/android/mortalityday/notification/NotifyMortalReceiver.kt
1
3542
package com.techlung.android.mortalityday.notification import android.app.Notification import android.app.NotificationChannel import android.app.NotificationManager import android.app.PendingIntent import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.graphics.Color import android.os.Build import androidx.annotation.RequiresApi import androidx.core.app.NotificationCompat import androidx.core.app.TaskStackBuilder import androidx.core.content.ContextCompat import com.techlung.android.mortalityday.MessageActivity import com.techlung.android.mortalityday.R import com.techlung.android.mortalityday.settings.Preferences import com.techlung.android.mortalityday.settings.PreferencesActivity import com.techlung.android.mortalityday.util.MortalityDayUtil class NotifyMortalReceiver : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { Preferences.initPreferences(context) if (MortalityDayUtil.isMortalityDay) { showNotification(context) } MortalityDayNotificationManager.setNextNotification(context, false) } companion object { private const val ANDROID_CHANNEL_ID = "com.techlung.android.mortalityday.Notifications" private const val ANDROID_CHANNEL_NAME = "Regular Reminders" fun showNotification(context: Context) { if (!Preferences.isNotifyEnabled) { return } val notificationManager = getManager(context) val quote = MortalityDayUtil.getQuote(context) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { createChannel(context) } val builder = NotificationCompat.Builder(context, ANDROID_CHANNEL_ID) .setSmallIcon(R.mipmap.ic_launcher) .setColor(ContextCompat.getColor(context, R.color.colorAccent)) .setContentTitle(context.getString(R.string.notification_title)) .setAutoCancel(true) .setContentText(quote.message) val resultIntent = Intent(context, MessageActivity::class.java) resultIntent.putExtra(MessageActivity.MESSAGE_EXTRA, quote.message) resultIntent.putExtra(MessageActivity.AUTHOR_EXTRA, quote.author) val stackBuilder = TaskStackBuilder.create(context) stackBuilder.addParentStack(PreferencesActivity::class.java) stackBuilder.addNextIntent(resultIntent) val resultPendingIntent = stackBuilder.getPendingIntent( 0, PendingIntent.FLAG_UPDATE_CURRENT ) builder.setContentIntent(resultPendingIntent) notificationManager.notify(1000, builder.build()) } @RequiresApi(api = Build.VERSION_CODES.O) private fun createChannel(context: Context) { val channel = NotificationChannel(ANDROID_CHANNEL_ID, ANDROID_CHANNEL_NAME, NotificationManager.IMPORTANCE_DEFAULT) channel.enableLights(true) channel.enableVibration(true) channel.lightColor = Color.GREEN channel.lockscreenVisibility = Notification.VISIBILITY_PUBLIC getManager(context).createNotificationChannel(channel) } private fun getManager(context: Context): NotificationManager { return context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager } } }
apache-2.0
1d5bd8718f883eb9095733d512323d05
37.086022
127
0.701299
5.038407
false
false
false
false
mdanielwork/intellij-community
platform/platform-impl/src/com/intellij/internal/heatmap/fus/StatisticsUtil.kt
2
12323
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.internal.heatmap.fus import com.google.gson.JsonArray import com.google.gson.JsonElement import com.google.gson.JsonObject import com.google.gson.JsonParser import com.intellij.internal.heatmap.actions.LOG import com.intellij.internal.heatmap.actions.MetricEntity import com.intellij.internal.heatmap.actions.ProductBuildInfo import com.intellij.internal.heatmap.actions.ShowHeatMapAction import com.intellij.notification.Notification import com.intellij.notification.NotificationType import com.intellij.notification.Notifications import com.intellij.openapi.project.Project import com.intellij.openapi.util.text.StringUtil import com.intellij.util.PlatformIcons import com.intellij.util.containers.ContainerUtil import com.intellij.xml.util.XmlStringUtil import org.apache.http.HttpHeaders import org.apache.http.HttpResponse import org.apache.http.NameValuePair import org.apache.http.client.methods.CloseableHttpResponse import org.apache.http.client.methods.HttpGet import org.apache.http.client.methods.HttpPost import org.apache.http.client.methods.HttpUriRequest import org.apache.http.client.utils.URIBuilder import org.apache.http.entity.ContentType import org.apache.http.entity.StringEntity import org.apache.http.impl.client.HttpClientBuilder import org.apache.http.message.BasicNameValuePair import org.apache.http.util.EntityUtils import java.util.* val DEFAULT_SERVICE_URLS = arrayListOf("https://prod.fus.aws.intellij.net", "https://qa.fus.aws.intellij.net") private const val METRICS_PATH = "/peacock/api/rest/v1/metrics" private const val ASYNC = "/async" private const val DATA_SERVICE_URL = "https://data.services.jetbrains.com/products" fun fetchStatistics(dateFrom: String, dateTo: String, productCode: String, buildNumbers: List<String>, groups: List<String>, accessToken: String, filter: String? = null, minUsers: Int = 5): List<MetricEntity> { myAccessToken = accessToken val query = formQuery(dateFrom, dateTo, productCode, buildNumbers, groups, StringUtil.notNullize(filter)) val postAsync = async() val entity = StringEntity(query, ContentType.APPLICATION_JSON) postAsync.entity = entity val httpClient = HttpClientBuilder.create().build() val response: CloseableHttpResponse? return try { LOG.debug("Executing request: $postAsync") response = httpClient.execute(postAsync) LOG.debug("Response: $response") if (response.statusLine.statusCode != 200) { val message = "Request failed with code: ${response.statusLine.statusCode}. Reason: ${response.statusLine.reasonPhrase}" LOG.warn(message) var placeMessage = "group: $groups" if (filter != null && filter.isNotBlank()) placeMessage += ", $filter" showWarnNotification("Statistics fetch failed for $placeMessage", message) return emptyList() } getStats(response, minUsers) } catch (e: Exception) { LOG.warn("Request failed: ${e.message};\n${e.stackTrace}") emptyList() } } fun getStats(asyncResponse: HttpResponse, minUsers: Int): List<MetricEntity> { try { val asyncEntity = asyncResponse.entity ?: return emptyList() var responseEntity = EntityUtils.toString(asyncEntity) ?: return emptyList() val httpClient = HttpClientBuilder.create().build() fun execute(httpRequest: HttpUriRequest): String? { LOG.info("Executing request: $httpRequest") val httpEntity = httpClient.execute(httpRequest)?.entity ?: return null val resultString = EntityUtils.toString(httpEntity) LOG.debug("Got result: $resultString") return resultString } val queryId = getQueryId(responseEntity) ?: return emptyList() var status = getQueryStatus(responseEntity) while ("running".equals(status, true)) { Thread.sleep(500) responseEntity = execute(status(queryId)) ?: break status = getQueryStatus(responseEntity) } val rowsResult = mutableListOf<MetricEntity>() LOG.info("Got JSON result: $responseEntity") var rows = parseRows(responseEntity) rowsResult.addAll(parseRows(responseEntity)) var nextPageToken = getNextPageToken(responseEntity) while (nextPageToken != null && rows.isNotEmpty() && rows[0].users >= minUsers) { Thread.sleep(500) responseEntity = execute(queries(queryId, nextPageToken)) ?: break rows = parseRows(responseEntity) rowsResult.addAll(rows) nextPageToken = getNextPageToken(responseEntity) } return rowsResult } catch (e: Exception) { LOG.warn("Error: ${e.message};\n${e.stackTrace}") return emptyList() } } fun queries(queryId: String, pageToken: String): HttpGet { val params = ArrayList<NameValuePair>() params.add(BasicNameValuePair("nextPageToken", pageToken)) params.add(BasicNameValuePair("queryId", queryId)) return metricsGet("/queries", params) } fun parseRows(string: String): List<MetricEntity> { val json = JsonParser().parse(string) val rows = json.asJsonObject.get("rows") ?: return emptyList() val result = mutableListOf<MetricEntity>() for (el in rows.asJsonArray) { val stat = createMetricEntity(el) if (stat != null) result.add(stat) } return result } private fun createMetricEntity(el: JsonElement): MetricEntity? { val o = el.asJsonObject val metricId = o.get("metric_id")?.asString ?: return null val sampleSize = o.get("sample_size")?.asInt ?: return null val groupSize = o.get("group_size")?.asInt ?: return null val metricUsers = o.get("metric_users")?.asInt ?: return null val metricUsages = o.get("metric_usages")?.asInt ?: return null val usagesPerUser = (metricUsages / metricUsers.toFloat()) val metricShare = metricUsers * 100 / sampleSize.toFloat() //metric_users * 100 / sample_size return MetricEntity(metricId, sampleSize, groupSize, metricUsers, metricUsages, usagesPerUser, metricShare) } fun getNextPageToken(string: String): String? { val json = JsonParser().parse(string) val queryId = json.asJsonObject.get("nextPageToken") return queryId?.asString } private fun status(queryId: String): HttpGet { return metricsGet("/$queryId/status") } private fun async(): HttpPost { return metrics(ASYNC) } private fun metrics(path: String): HttpPost { val url = ShowHeatMapAction.getSelectedServiceUrl() + METRICS_PATH + path return postRequest(url) } private fun metricsGet(path: String, params: MutableList<NameValuePair>? = null): HttpGet { val url = ShowHeatMapAction.getSelectedServiceUrl() + METRICS_PATH + path return getRequest(url, params) } private fun postRequest(url: String): HttpPost { val uriBuilder = URIBuilder(url) val uri = uriBuilder.build() val request = HttpPost(uri) request.setHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON.mimeType) val token = getAccessToken() val authHeader = "Bearer $token" request.setHeader(HttpHeaders.AUTHORIZATION, authHeader) return request } private var myAccessToken: String? = null private fun getAccessToken(): String? { return myAccessToken } private fun getRequest(url: String, params: List<NameValuePair>?): HttpGet { val uriBuilder = URIBuilder(url) if (params != null) uriBuilder.addParameters(params) val uri = uriBuilder.build() val request = HttpGet(uri) request.setHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON.mimeType) val token = getAccessToken() val authHeader = "Bearer $token" request.setHeader(HttpHeaders.AUTHORIZATION, authHeader) return request } private fun getProductJson(productCode: String): JsonObject? { val jsonResult = execute(jsonGetRequest(DATA_SERVICE_URL)) val json = JsonParser().parse(jsonResult) return findProduct(json.asJsonArray, productCode) } fun getProductBuildInfos(productCode: String): List<ProductBuildInfo> { val productJson = getProductJson(productCode) if (productJson == null) return emptyList() return parseProductReleases(productJson, productCode) } fun parseProductReleases(productJson: JsonObject, productCode: String): List<ProductBuildInfo> { val releases = productJson.get("releases").asJsonArray val result = mutableListOf<ProductBuildInfo>() for (release in releases) { val type = release.asJsonObject.get("type")?.asString val version = release.asJsonObject.get("version")?.asString val majorVersion = release.asJsonObject.get("majorVersion")?.asString val build = release.asJsonObject.get("build")?.asString if (type != null && version != null && majorVersion != null && build != null) result.add( ProductBuildInfo(productCode, type, version, majorVersion, build)) } return result } fun findProduct(products: JsonArray, productCode: String): JsonObject? { products.forEach { product -> val code = product.asJsonObject.get("code")?.asString if (productCode == code) return product.asJsonObject val altCodes = product.asJsonObject.get("alternativeCodes")?.asJsonArray if (altCodes?.find { it.asString == productCode } != null) return product.asJsonObject } return null } fun jsonGetRequest(url: String, params: List<NameValuePair>? = null): HttpGet { val uriBuilder = URIBuilder(url) if (params != null) uriBuilder.addParameters(params) val uri = uriBuilder.build() val request = HttpGet(uri) request.setHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON.mimeType) return request } fun execute(httpRequest: HttpUriRequest): String? { val httpClient = HttpClientBuilder.create().build() LOG.debug("Executing request: $httpRequest") val httpEntity = httpClient.execute(httpRequest)?.entity ?: return null val resultString = EntityUtils.toString(httpEntity) LOG.debug("Got result: $resultString") return resultString } fun getQueryStatus(response: String): String? { val json = JsonParser().parse(response) val queryId = json.asJsonObject.get("status") return queryId?.asString } fun getQueryId(response: String): String? { val json = JsonParser().parse(response) val queryId = json.asJsonObject.get("queryId") return queryId?.asString } fun formQuery(dateFrom: String, dateTo: String, productCode: String, builds: List<String>, groups: List<String>, filter: String): String { val sb = StringBuilder() sb.append("{\"dateFrom\":\"$dateFrom\",\"dateTo\":\"$dateTo\",\"products\":[\"$productCode\"],\"builds\":[") builds.forEachIndexed { i, v -> sb.append("\"$v\"") if (i < builds.size - 1) sb.append(",") } sb.append("],\"groups\":[") groups.forEachIndexed { i, s -> sb.append("\"$s\"") if (i < groups.size - 1) sb.append(",") } sb.append("],\"filter\":\"$filter\"}") LOG.debug("Formed query: $sb") return sb.toString() } fun getBuildsForIDEVersions(ideVersions: List<String>, includeEap: Boolean): List<String> { val result = ContainerUtil.newArrayList<String>() for (buildInfo in ShowHeatMapAction.getOurIdeBuildInfos()) { if (!includeEap && buildInfo.isEap()) continue if (ideVersions.contains(buildInfo.version)) result.add(buildInfo.build) } return result } fun filterByPlaceToolbar(toFilter: List<MetricEntity>, place: String): List<MetricEntity> { val filtered = mutableListOf<MetricEntity>() toFilter.forEach { if (place.equals(getToolBarButtonPlace(it), true)) { filtered.add(it) } } return filtered } fun filterByMenuName(toFilter: List<MetricEntity>, menuName: String): List<MetricEntity> { val filtered = mutableListOf<MetricEntity>() toFilter.forEach { if (menuName.equals(getMenuName(it), true)) { filtered.add(it) } } return filtered } fun showWarnNotification(title: String, message: String, project: Project? = null) { val warn = Notification("IDE Click Map", PlatformIcons.WARNING_INTRODUCTION_ICON, title, null, XmlStringUtil.wrapInHtml(message), NotificationType.WARNING, null) Notifications.Bus.notify(warn, project) } fun getToolBarButtonPlace(metricEntity: MetricEntity): String = metricEntity.id.substringAfter('@') fun getMenuName(metricEntity: MetricEntity): String = metricEntity.id.substringBefore("->").trim()
apache-2.0
27b1f84abc55937ed6e0a2dfb2554ac2
36.458967
140
0.730179
4.160365
false
false
false
false
android/project-replicator
model/src/test/kotlin/com/android/gradle/replicator/model/internal/fixtures/BuildFeaturesBuilder.kt
1
1603
/* * Copyright (C) 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.gradle.replicator.model.internal.fixtures import com.android.gradle.replicator.model.BuildFeaturesInfo import com.android.gradle.replicator.model.internal.DefaultBuildFeaturesInfo class BuildFeaturesBuilder { var aidl: Boolean? = null var androidResources: Boolean? = null var buildConfig: Boolean? = null var compose: Boolean? = null var dataBinding: Boolean? = null var mlModelBinding: Boolean? = null var prefab: Boolean? = null var prefabPublishing: Boolean? = null var renderScript: Boolean? = null var resValues: Boolean? = null var shaders: Boolean? = null var viewBinding: Boolean? = null fun toInfo(): BuildFeaturesInfo = DefaultBuildFeaturesInfo( aidl, androidResources, buildConfig, compose, dataBinding, mlModelBinding, prefab, prefabPublishing, renderScript, resValues, shaders, viewBinding ) }
apache-2.0
bda87a553b56bf554fa9452b023609ce
31.08
76
0.701809
4.332432
false
false
false
false
McMoonLakeDev/MoonLake
API/src/main/kotlin/com/mcmoonlake/api/packet/PacketOutVehicleMove.kt
1
1462
/* * Copyright (C) 2016-Present The MoonLake ([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.mcmoonlake.api.packet class PacketOutVehicleMove( var x: Double, var y: Double, var z: Double, var yaw: Float, var pitch: Float ) : PacketOutBukkitAbstract("PacketPlayOutVehicleMove"), PacketBukkitFreshly { @Deprecated("") constructor() : this(.0, .0, .0, 0f, 0f) override fun read(data: PacketBuffer) { x = data.readDouble() y = data.readDouble() z = data.readDouble() yaw = data.readFloat() pitch = data.readFloat() } override fun write(data: PacketBuffer) { data.writeDouble(x) data.writeDouble(y) data.writeDouble(z) data.writeFloat(yaw) data.writeFloat(pitch) } }
gpl-3.0
163e8b5fba419ad4590c80223890fdc9
30.106383
72
0.663475
4.129944
false
false
false
false
leandroBorgesFerreira/LoadingButtonAndroid
app/src/main/java/br/com/simplepass/loadingbuttonsample/MainActivity.kt
1
3978
package br.com.simplepass.loadingbuttonsample import android.animation.ValueAnimator import android.content.Context import android.content.res.Resources import android.graphics.Bitmap import android.graphics.BitmapFactory import android.os.Bundle import android.os.Handler import androidx.appcompat.app.AppCompatActivity import androidx.core.content.ContextCompat import br.com.simplepass.loadingbutton.animatedDrawables.ProgressType import br.com.simplepass.loadingbutton.customViews.ProgressButton import kotlinx.android.synthetic.main.activity_main.* import android.widget.Toast class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) imgBtnTest0.run { setOnClickListener { morphDoneAndRevert(this@MainActivity) } } imgBtnTest1.run { setOnClickListener { morphDoneAndRevert(this@MainActivity) } } buttonTest1.run { setOnClickListener { morphDoneAndRevert(this@MainActivity) } } buttonTest2.run { setOnClickListener { morphAndRevert() } } buttonTest3.run { setOnClickListener { morphAndRevert(100) } } buttonTest4.run { setOnClickListener { morphDoneAndRevert(this@MainActivity, doneTime = 100) } } buttonTest5.run { setOnClickListener { morphDoneAndRevert(this@MainActivity, doneTime = 100, revertTime = 200) } } buttonTest6.run { setOnClickListener { progressType = ProgressType.INDETERMINATE startAnimation() progressAnimator(this).start() Handler().run { postDelayed({ doneLoadingAnimation(defaultColor(context), defaultDoneImage(context.resources)) }, 2500) postDelayed({ revertAnimation() }, 3500) } } } buttonTest7.run { setOnClickListener { morphStopRevert() } } buttonTest8.run { setOnClickListener { morphStopRevert(100, 1000) } } buttonTest9.run { setOnClickListener { morphAndRevert { Toast.makeText(this@MainActivity, getString(R.string.start_done), Toast.LENGTH_SHORT).show() } } } buttonTest10.run { setOnClickListener { morphDoneAndRevert(this@MainActivity) } } } } private fun defaultColor(context: Context) = ContextCompat.getColor(context, android.R.color.black) private fun defaultDoneImage(resources: Resources) = BitmapFactory.decodeResource(resources, R.drawable.ic_pregnant_woman_white_48dp) private fun ProgressButton.morphDoneAndRevert( context: Context, fillColor: Int = defaultColor(context), bitmap: Bitmap = defaultDoneImage(context.resources), doneTime: Long = 3000, revertTime: Long = 4000 ) { progressType = ProgressType.INDETERMINATE startAnimation() Handler().run { postDelayed({ doneLoadingAnimation(fillColor, bitmap) }, doneTime) postDelayed(::revertAnimation, revertTime) } } private fun ProgressButton.morphAndRevert(revertTime: Long = 3000, startAnimationCallback: () -> Unit = {}) { startAnimation(startAnimationCallback) Handler().postDelayed(::revertAnimation, revertTime) } private fun ProgressButton.morphStopRevert(stopTime: Long = 1000, revertTime: Long = 2000) { startAnimation() Handler().postDelayed(::stopAnimation, stopTime) Handler().postDelayed(::revertAnimation, revertTime) } private fun progressAnimator(progressButton: ProgressButton) = ValueAnimator.ofFloat(0F, 100F).apply { duration = 1500 startDelay = 500 addUpdateListener { animation -> progressButton.setProgress(animation.animatedValue as Float) } }
mit
dc89d7a72d15f56b7279d7f68bdf2440
33.591304
109
0.669935
4.758373
false
true
false
false
ogarcia/ultrasonic
core/subsonic-api/src/main/kotlin/org/moire/ultrasonic/api/subsonic/models/MusicDirectoryChild.kt
2
1131
package org.moire.ultrasonic.api.subsonic.models import java.util.Calendar data class MusicDirectoryChild( val id: String = "", val parent: String = "", val isDir: Boolean = false, val title: String = "", val album: String = "", val artist: String = "", val track: Int = -1, val year: Int? = null, val genre: String = "", val coverArt: String = "", val size: Long = -1, val contentType: String = "", val suffix: String = "", val transcodedContentType: String = "", val transcodedSuffix: String = "", val duration: Int = -1, val bitRate: Int = -1, val path: String = "", val isVideo: Boolean = false, val playCount: Int = 0, val discNumber: Int = -1, val created: Calendar? = null, val albumId: String = "", val artistId: String = "", val type: String = "", val starred: Calendar? = null, val streamId: String = "", val channelId: String = "", val description: String = "", val status: String = "", val publishDate: Calendar? = null, val userRating: Int? = null, val averageRating: Float? = null )
gpl-3.0
43cb7bd632abdee8ce2cd5cd4bd24762
28
48
0.590628
3.846939
false
false
false
false
flesire/ontrack
ontrack-ui-graphql/src/main/java/net/nemerosa/ontrack/graphql/schema/GQLRootQueryProjects.kt
1
4534
package net.nemerosa.ontrack.graphql.schema import graphql.Scalars.* import graphql.schema.DataFetcher import graphql.schema.GraphQLArgument.newArgument import graphql.schema.GraphQLFieldDefinition import graphql.schema.GraphQLFieldDefinition.newFieldDefinition import net.nemerosa.ontrack.common.and import net.nemerosa.ontrack.graphql.support.GraphqlUtils import net.nemerosa.ontrack.graphql.support.GraphqlUtils.checkArgList import net.nemerosa.ontrack.graphql.support.GraphqlUtils.stdList import net.nemerosa.ontrack.model.structure.ID import net.nemerosa.ontrack.model.structure.Project import net.nemerosa.ontrack.model.structure.StructureService import org.apache.commons.lang3.StringUtils import org.springframework.stereotype.Component @Component class GQLRootQueryProjects( private val structureService: StructureService, private val project: GQLTypeProject, private val propertyFilter: GQLInputPropertyFilter ) : GQLRootQuery { override fun getFieldDefinition(): GraphQLFieldDefinition { return newFieldDefinition() .name("projects") .type(stdList(project.typeRef)) .argument( newArgument() .name(ARG_ID) .description("ID of the project to look for") .type(GraphQLInt) .build() ) .argument( newArgument() .name(ARG_NAME) .description("Name of the project to look for") .type(GraphQLString) .build() ) .argument { a -> a.name(ARG_FAVOURITES) .description("Favourite projects only") .type(GraphQLBoolean) } .argument(propertyFilter.asArgument()) .dataFetcher(projectFetcher()) .build() } private fun projectFetcher(): DataFetcher<List<Project>> { return DataFetcher { environment -> val id: Int? = environment.getArgument(ARG_ID) val name: String? = environment.getArgument(ARG_NAME) val favourites = GraphqlUtils.getBooleanArgument(environment, ARG_FAVOURITES, false) // Per ID when { id != null -> { // No other argument is expected checkArgList(environment, ARG_ID) // Fetch by ID val project = structureService.getProject(ID.of(id)) // As list return@DataFetcher listOf(project) } name != null -> { // No other argument is expected checkArgList(environment, ARG_NAME) return@DataFetcher structureService .findProjectByNameIfAuthorized(name) ?.let { listOf(it) } ?: listOf<Project>() } favourites -> { // No other argument is expected checkArgList(environment, ARG_FAVOURITES) return@DataFetcher structureService.projectFavourites } else -> { // Filter to use var filter: (Project) -> Boolean = { _ -> true } // Property filter? val propertyFilterArg: Map<String, *>? = environment.getArgument(GQLInputPropertyFilter.ARGUMENT_NAME) if (propertyFilterArg != null) { val filterObject = propertyFilter.convert(propertyFilterArg) if (filterObject != null && StringUtils.isNotBlank(filterObject.type)) { val propertyPredicate = propertyFilter.getFilter(filterObject) filter = filter and { propertyPredicate.test(it) } } } // Whole list return@DataFetcher structureService.projectList.filter(filter) } } } } companion object { @JvmField val ARG_ID = "id" @JvmField val ARG_NAME = "name" @JvmField val ARG_FAVOURITES = "favourites" } }
mit
98abef7c5f237c797a670b00d008fe7e
40.981481
122
0.53176
5.827763
false
false
false
false
kurtyan/fanfou4j
src/main/java/com/github/kurtyan/fanfou4j/entity/User.kt
1
1169
package com.github.kurtyan.fanfou4j.entity import java.util.* /** * Created by yanke on 2016/4/24. */ class User { var id: String? = null var name: String? = null var screenName: String? = null var uniqueId: String? = null var location: String? = null var gender: String? = null var birthday: String? = null var description: String? = null var profileImageUrl: String? = null var profileImageUrlLarge: String? = null var url: String? = null var protected: Boolean? = null val followersCount: Long? = null var friendsCount: Long? = null var favouritesCount: Long? = null var statusesCount: Long? = null var photoCount: Long? = null var following: Boolean? = null var notifications: Boolean? = null var createdAt: Date? = null var utcOffset: Long? = null var profileBackgroundColor: String? = null var profileTextColor: String? = null var profileLinkColor: String? = null var profileSidebarFillColor: String? = null var profileSidebarBorderColor: String? = null var profileBackgroundImageUrl: String? = null var profileBackgroundTile: Boolean? = null }
mit
490abe3edfa618c57c5d7c3a0b369dd4
29.763158
49
0.678358
4.044983
false
false
false
false
earizon/java-vertx-ledger
src/main/java/com/everis/everledger/impl/Transfer.kt
1
13065
package com.everis.everledger.impl import io.vertx.core.json.JsonArray import io.vertx.core.json.JsonObject import org.interledger.Condition import org.interledger.Fulfillment import org.interledger.InterledgerAddress import java.time.ZonedDateTime import javax.money.MonetaryAmount import java.util.Random import java.util.UUID import org.javamoney.moneta.Money import org.interledger.ledger.model.TransferStatus import com.everis.everledger.util.Config import com.everis.everledger.ifaces.account.IfaceLocalAccount import com.everis.everledger.ifaces.transfer.ILocalTransfer import com.everis.everledger.ifaces.transfer.IfaceTransfer import com.everis.everledger.util.TimeUtils import com.everis.everledger.impl .manager.SimpleAccountManager // FIXME:(1) Allow multiple debit/credits (Remove all code related to index [0]) val random = Random() val a : ByteArray = ByteArray(size = 32) public val FF_NOT_PROVIDED : Fulfillment = { random.nextBytes(a) ; Fulfillment.builder().preimage(a).build() }() public val CC_NOT_PROVIDED : Condition = { random.nextBytes(a) ; Condition .builder().hash(a) .build() }() internal val AM = SimpleAccountManager // TODO:(?) Recheck this Credit/Debit classes public data class Credit (val account: IfaceLocalAccount, val _amount: MonetaryAmount/*, InterledgerPacketHeader ph*/)// this.ph = ph; : ILocalTransfer.Debit { override fun getLocalAccount() : IfaceLocalAccount = account override fun getAmount() : MonetaryAmount = amount } public data class Debit (val account: IfaceLocalAccount, val _amount: MonetaryAmount, val authorized : Boolean = true) : ILocalTransfer.Debit { override fun getLocalAccount() : IfaceLocalAccount = account override fun getAmount() : MonetaryAmount = amount } data class LocalTransferID(val transferID: String) : ILocalTransfer.LocalTransferID { override fun getUniqueID() : String = transferID } public fun ILPSpec2LocalTransferID(ilpTransferID: UUID): LocalTransferID { return LocalTransferID(ilpTransferID.toString()) } data class SimpleTransfer ( val id: LocalTransferID, val debit_list: Array<ILocalTransfer.Debit>, val credit_list: Array<ILocalTransfer.Credit>, val executionCond: Condition, val cancelationCond: Condition, val int_DTTM_proposed: ZonedDateTime = ZonedDateTime.now(), val int_DTTM_prepared: ZonedDateTime = ZonedDateTime.now(), val int_DTTM_expires : ZonedDateTime = TimeUtils.future, val int_DTTM_executed: ZonedDateTime = TimeUtils.future, val int_DTTM_rejected: ZonedDateTime = TimeUtils.future, val data: String = "", val noteToSelf: String = "", var int_transferStatus: TransferStatus = TransferStatus.PROPOSED, val sMemo: String, val executionFF : Fulfillment = FF_NOT_PROVIDED, val cancelationFF : Fulfillment = FF_NOT_PROVIDED ) : IfaceTransfer { internal val fromAccount: IfaceLocalAccount init { // TODO:(0) Check this is executed after val initialization checkBalancedTransaction() fromAccount = AM.getAccountByName(credit_list[0].localAccount.localID) // TODO:(1) Check that debit_list[idx].ammount.currency is always the same and match the ledger // TODO:(1) Check that credit_list[idx].ammount.currency is always the same. // FIXME: TODO: If fromAccount.ledger != "our ledger" throw RuntimeException. int_transferStatus = if (transferStatus == TransferStatus.PROPOSED) { // Temporal patch since proposed was not contemplated initialy TransferStatus.PREPARED } else { transferStatus } if (cancelationFF !== FF_NOT_PROVIDED && this.executionFF !== FF_NOT_PROVIDED) throw RuntimeException("Cancelation and Execution Fulfillment can not be set simultaneously") } // Implement ILPSpec interface{ override fun getId(): UUID { // TODO:(0) Check LocalTransferID LocalTransferID.ILPSpec2LocalTransferID // Create inverse and use val result = UUID.randomUUID() // TODO:(0) FIX get from getTransferID return result } override fun getFromAccount(): InterledgerAddress { val result = InterledgerAddress.Builder().value("TODO(0)").build() return result } override fun getToAccount(): InterledgerAddress { val result = InterledgerAddress.Builder().value("TODO(0)").build() return result } override fun getAmount(): MonetaryAmount { val result = Money.of(0, debit_list[0].amount.currency) return result } override fun getInvoice(): String { val result = "" // TODO:(0) return result } override fun getData(): ByteArray { return data.toByteArray() } override fun getNoteToSelf(): ByteArray { return noteToSelf.toByteArray() } override fun isRejected(): Boolean { val result = false // TODO:(0) return result } override fun getRejectionMessage(): String { val result = "" return result } override fun getExecutionCondition(): Condition { return executionCond } // @Override // public Condition getCancellationCondition() { // return cancelationCond; // } override fun getExpiresAt(): ZonedDateTime { return int_DTTM_expires } // } End ILPSpec interface private fun checkBalancedTransaction() { val totalDebits = Money.of(0, debit_list[0].amount.currency) for (debit in debit_list) { totalDebits.add(debit.amount) } val totalCredits = Money.of(0, credit_list[0].amount.currency) for (credit in credit_list) { totalCredits.add(credit.amount) } if (!totalDebits.isEqualTo(totalCredits)) { throw RuntimeException("transfer not balanced between credits and debits") } } override fun getTransferID(): LocalTransferID { return id } override fun getDebits(): Array<ILocalTransfer.Debit> { return debit_list } override fun getCredits(): Array<ILocalTransfer.Credit> { return credit_list } override fun getTransferStatus(): TransferStatus { return int_transferStatus } override fun getDTTM_prepared(): ZonedDateTime { return int_DTTM_prepared } override fun getDTTM_executed(): ZonedDateTime { return int_DTTM_executed } override fun getDTTM_rejected(): ZonedDateTime { return int_DTTM_rejected } override fun getDTTM_expires(): ZonedDateTime { return int_DTTM_expires } override fun getDTTM_proposed(): ZonedDateTime { return int_DTTM_proposed } override fun getExecutionFulfillment(): Fulfillment { return executionFF } override fun getCancellationFulfillment(): Fulfillment { return cancelationFF } // NOTE: The JSON returned to the ILP connector and the Wallet must not necesarelly match // since the data about the transfer needed by the wallet and the connector differ. // That's why two different JSON encoders exist fun toILPJSONStringifiedFormat(): JsonObject { // REF: convertToExternalTransfer@ // https://github.com/interledger/five-bells-ledger/blob/master/src/models/converters/transfers.js val jo = JsonObject() val ledger = Config.publicURL.toString().trimEnd('/') val id = /* TODO:(doubt) add ledger as prefix ?? */"/transfers/" /* TODO:(1) Get from Config */ + transferID.transferID jo.put("id", id) jo.put("ledger", ledger) jo.put("debits", entryList2Json(debit_list as Array<ILocalTransfer.TransferHalfEntry>)) jo.put("credits", entryList2Json(credit_list as Array<ILocalTransfer.TransferHalfEntry>)) if (this.executionCondition != CC_NOT_PROVIDED) { jo.put("execution_condition", this.executionCondition.toString()) } // if (! this.getCancellationCondition().equals(SimpleTransfer.CC_NOT_PROVIDED)) { // jo.put("cancellation_condition", this.getCancellationCondition().toString()); // } jo.put("state", this.getTransferStatus().toString().toLowerCase()) // if (!this.getCancellationCondition().equals(Condition....NOT_PROVIDED)) { // jo.put("cancellation_condition", this.getCancellationCondition()); // } // FIXME: Cancelation_condition? if (this.int_DTTM_expires !== TimeUtils.future) { jo.put("expires_at", this.int_DTTM_expires.format(TimeUtils.ilpFormatter)) } run { val timeline = JsonObject() if (Config.unitTestsActive) { timeline.put("proposed_at", TimeUtils.testingDate.format(TimeUtils.ilpFormatter)) val sTestingDate = TimeUtils.testingDate.format(TimeUtils.ilpFormatter) if (this.int_DTTM_prepared !== TimeUtils.future) { timeline.put("prepared_at", sTestingDate) } if (this.int_DTTM_executed !== TimeUtils.future) { timeline.put("executed_at", sTestingDate) } if (this.int_DTTM_rejected !== TimeUtils.future) { timeline.put("rejected_at", sTestingDate) } } else { timeline.put("proposed_at", this.int_DTTM_proposed.format(TimeUtils.ilpFormatter)) if (this.int_DTTM_prepared !== TimeUtils.future) { timeline.put("prepared_at", this.int_DTTM_prepared.format(TimeUtils.ilpFormatter)) } if (this.int_DTTM_executed !== TimeUtils.future) { timeline.put("executed_at", this.int_DTTM_executed.format(TimeUtils.ilpFormatter)) } if (this.int_DTTM_rejected !== TimeUtils.future) { timeline.put("rejected_at", this.int_DTTM_rejected.format(TimeUtils.ilpFormatter)) } } jo.put("timeline", timeline) } if (sMemo !== "") { jo.put("memo", JsonObject(sMemo)) } return jo } private fun entryList2Json(input_list: Array<out ILocalTransfer.TransferHalfEntry>): JsonArray { val ja = JsonArray() for (entry in input_list) { // FIXME: This code to calculate amount is PLAIN WRONG. Just to pass five-bells-ledger tests val jo = JsonObject() jo.put("account", "/accounts/" /* TODO: Get from config.*/ + entry.localAccount.localID) val sAmount = "" + entry.amount.number.toFloat().toLong() jo.put("amount", sAmount) if (entry is Debit) { jo.put("authorized", entry.authorized) } else if (entry is Credit) { // Add memo: // "memo":{ // "ilp_header":{ // "account":"ledger3.eur.alice.fe773626-81fb-4294-9a60-dc7b15ea841e", // "amount":"1", // "data":{"expires_at":"2016-11-10T15:51:27.134Z"} // } // } // COMMENTED OLD API JsonObject memo = new JsonObject()/*, ilp_header = new JsonObject()*/, data = new JsonObject(); // COMMENTED OLD API ilp_header.put("account", ((Credit)entry).ph.getDestinationAddress()); // COMMENTED OLD API ilp_header.put("amount", ""+((Credit)entry).ph.getAmount());// TODO: Recheck // COMMENTED OLD API data.put("expires_at", /*((Credit)entry).ph.getExpiry().toString()*/int_DTTM_expires.toString()); // TODO: Recheck. // COMMENTED OLD API ilp_header.put("data", data); // COMMENTED OLD API memo.put("ilp_header", ilp_header); // COMMENTED OLD API jo.put("memo", memo); } ja.add(jo) } return ja } override fun isAuthorized(): Boolean = true }
apache-2.0
6e3a6f6b3099d3521cbee5a3c6f4ce9d
40.60828
157
0.5876
4.545929
false
false
false
false
PlanBase/PdfLayoutMgr2
src/main/java/com/planbase/pdf/lm2/contents/TableRow.kt
1
6366
// Copyright 2017 PlanBase Inc. // // This file is part of PdfLayoutMgr2 // // PdfLayoutMgr is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // PdfLayoutMgr 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 Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with PdfLayoutMgr. If not, see <https://www.gnu.org/licenses/agpl-3.0.en.html>. // // If you wish to use this code with proprietary software, // contact PlanBase Inc. <https://planbase.com> to purchase a commercial license. package com.planbase.pdf.lm2.contents import com.planbase.pdf.lm2.attributes.Align import com.planbase.pdf.lm2.attributes.CellStyle import com.planbase.pdf.lm2.attributes.DimAndPageNums import com.planbase.pdf.lm2.attributes.TextStyle import com.planbase.pdf.lm2.lineWrapping.LineWrappable import com.planbase.pdf.lm2.pages.RenderTarget import com.planbase.pdf.lm2.utils.Coord import com.planbase.pdf.lm2.utils.Dim import java.util.ArrayList import kotlin.math.max /** * Unsynchronized mutable class which is not thread-safe. The internal tracking of cells and widths * allows you to make a cell builder for a cell at a given column, add cells in subsequent columns, * then complete (buildCell()) the cell and have it find its proper (now previous) column. */ class TableRow @JvmOverloads constructor(private val table: Table, private val rowClosedCallback: (() -> Unit)? = null) { var textStyle: TextStyle? = table.textStyle private var cellStyle: CellStyle = table.cellStyle private val cells: MutableList<Cell> = ArrayList(table.cellWidths.size) var minRowHeight = table.minRowHeight private var nextCellIdx = 0 // fun textStyle(x: TextStyle): TableRow { // textStyle = x // return this // } fun align(a: Align) : TableRow { cellStyle = cellStyle.withAlign(a) return this } fun addTextCells(vararg ss: String): TableRow { if (textStyle == null) { throw IllegalStateException("Tried to add a text cell without setting a default text style") } for (s in ss) { cell(cellStyle, listOf(Text(textStyle!!, s))) } return this } fun minRowHeight(f: Double): TableRow { minRowHeight = f return this } fun cell(cs: CellStyle = cellStyle, contents: List<LineWrappable>): TableRow { if (table.cellWidths.size < (nextCellIdx + 1)) { throw IllegalStateException("Can't add another cell because there are only ${table.cellWidths.size}" + " cell widths and already $nextCellIdx cells") } cells.add(Cell(cs, table.cellWidths[nextCellIdx++], contents)) return this } fun endRow(): Table { // Do we want to fill out the row with blank cells? // if (cells.contains(null)) { // throw IllegalStateException("Cannot build row when some TableRowCellBuilders have been" + // " created but the cells not built and added back to the row.") // } val table = table.addRow(this) if (rowClosedCallback != null) { rowClosedCallback.invoke() } return table } fun finalRowHeight(): Double { // cells.map { c -> c?.wrap() ?: LineWrapped.ZeroLineWrapped } cells.map { c -> c.wrap() } .forEach{ c -> minRowHeight = Math.max(minRowHeight, c.dim.height)} // println("finalRowHeight() returns: ${minRowHeight}") return minRowHeight } class WrappedTableRow(row: TableRow) { val dim = Dim(row.table.cellWidths.sum(), row.finalRowHeight()) private val minRowHeight: Double = row.minRowHeight private val fixedCells:List<WrappedCell> = row.cells.map { c -> c.wrap() } .toList() fun render(lp: RenderTarget, topLeft: Coord, reallyRender: Boolean): DimAndPageNums { // cells.map { c -> c?.wrap() ?: LineWrapped.ZeroLineWrapped } // .forEach{ c -> minRowHeight = Math.max(minRowHeight, c.dim.height)} var pageNums:IntRange = DimAndPageNums.INVALID_PAGE_RANGE var x = topLeft.x var maxRowHeight = minRowHeight // println(" minRowHeight=$minRowHeight") // Find the height of the tallest cell before rendering any cells. for (fixedCell in fixedCells) { // println(" beforeRender height=${fixedCell.dim.height}") val dimAndPageNums: DimAndPageNums = fixedCell.renderCustom(lp, topLeft.withX(x), maxRowHeight, reallyRender = false, preventWidows = false) // println(" afterRender height=$height") // Size is wrong here! maxRowHeight = max(maxRowHeight, dimAndPageNums.dim.height) // println(" maxRowHeight=$maxRowHeight") x += dimAndPageNums.dim.width pageNums = dimAndPageNums.maxExtents(pageNums) } val maxWidth = x - topLeft.x if (reallyRender) { // Now render the cells x = topLeft.x for (fixedCell in fixedCells) { val width = fixedCell.renderCustom(lp, topLeft.withX(x), maxRowHeight, reallyRender = true, preventWidows = false).dim.width x += width } } return DimAndPageNums(Dim(maxWidth, maxRowHeight), pageNums) } } override fun toString(): String = // "TableRow($cells)" cells.fold(StringBuilder(""), {sB, cell -> sB.append(cell.toStringTable())}) .toString() }
agpl-3.0
94d6500bc524310072421ad0cb2e000d
40.607843
114
0.606503
4.569993
false
false
false
false
Zeyad-37/RxRedux
core/src/main/java/com/zeyad/rxredux/core/v2/Extensions.kt
1
806
package com.zeyad.rxredux.core.v2 import io.reactivex.Flowable fun Flowable<RxOutcome>.executeInParallel(): AsyncOutcomeFlowable = AsyncOutcomeFlowable(this) fun <E : Effect> E.toEffectOutcome(): RxOutcome = RxReduxViewModel.RxEffect(this) fun <E : Effect> E.toEffectOutcomeFlowable(): Flowable<RxOutcome> = toEffectOutcome().toFlowable() fun <R : Result> R.toResultOutcome(): RxOutcome = RxReduxViewModel.RxResult(this) fun <R : Result> R.toResultOutcomeFlowable(): Flowable<RxOutcome> = toResultOutcome().toFlowable() fun Throwable.toErrorOutcome(errorMessage: String? = null): RxOutcome = RxError(Error(errorMessage ?: message.orEmpty(), this)) fun Throwable.toErrorOutcomeFlowable(): Flowable<RxOutcome> = toErrorOutcome().toFlowable() fun RxOutcome.toFlowable() = Flowable.just(this)
apache-2.0
4be2b2c30d7a3394d8d9f0ea70ee9c32
39.3
98
0.774194
3.95098
false
false
false
false
google/intellij-community
platform/lang-impl/src/com/intellij/codeInsight/codeVision/EditorCodeVisionContext.kt
2
7716
package com.intellij.codeInsight.codeVision import com.intellij.codeInsight.codeVision.ui.CodeVisionView import com.intellij.codeInsight.codeVision.ui.model.PlaceholderCodeVisionEntry import com.intellij.openapi.components.ServiceManager import com.intellij.openapi.components.service import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.editor.Document import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.RangeMarker import com.intellij.openapi.editor.impl.EditorImpl import com.intellij.openapi.rd.createLifetime import com.intellij.openapi.util.Key import com.intellij.openapi.util.TextRange import com.intellij.util.application import com.jetbrains.rd.util.first import com.jetbrains.rd.util.lifetime.SequentialLifetimes import com.jetbrains.rd.util.lifetime.onTermination import java.awt.event.MouseEvent val editorLensContextKey: Key<EditorCodeVisionContext> = Key<EditorCodeVisionContext>("EditorCodeLensContext") val codeVisionEntryOnHighlighterKey: Key<CodeVisionEntry> = Key.create<CodeVisionEntry>("CodeLensEntryOnHighlighter") val codeVisionEntryMouseEventKey: Key<MouseEvent> = Key.create<MouseEvent>("CodeVisionEntryMouseEventKey") val Editor.lensContext: EditorCodeVisionContext? get() = getOrCreateCodeVisionContext(this) val Editor.lensContextOrThrow: EditorCodeVisionContext get() = lensContext ?: error("No EditorCodeVisionContext were provided") val RangeMarker.codeVisionEntryOrThrow: CodeVisionEntry get() = getUserData(codeVisionEntryOnHighlighterKey) ?: error("No CodeLensEntry for highlighter $this") open class EditorCodeVisionContext( private val codeVisionHost: CodeVisionHost, val editor: Editor ) { val outputLifetimes: SequentialLifetimes = SequentialLifetimes((editor as EditorImpl).disposable.createLifetime()) private var frontendResults: List<RangeMarker> = listOf() companion object { val logger: Logger = Logger.getInstance(EditorCodeVisionContext::class.java) } private var hasPendingLenses = false private val submittedGroupings = ArrayList<Pair<TextRange, (Int) -> Unit>>() init { (editor as EditorImpl).disposable.createLifetime().onTermination { frontendResults.forEach { it.dispose() } } } fun notifyPendingLenses() { application.assertIsDispatchThread() if (!hasPendingLenses) logger.trace("Have pending lenses") hasPendingLenses = true } open val hasAnyPendingLenses: Boolean get() = hasPendingLenses fun setResults(lenses: List<Pair<TextRange, CodeVisionEntry>>) { application.assertIsDispatchThread() logger.trace("Have new frontend lenses ${lenses.size}") frontendResults.forEach { it.dispose() } frontendResults = lenses.mapNotNull { (range, entry) -> if(!range.isValidFor(editor.document)) return@mapNotNull null editor.document.createRangeMarker(range).apply { putUserData(codeVisionEntryOnHighlighterKey, entry) } } resubmitThings() hasPendingLenses = false } fun discardPending(){ hasPendingLenses = false } protected fun resubmitThings() { val viewService = ServiceManager.getService( editor.project!!, CodeVisionView::class.java ) viewService.runWithReusingLenses { val lifetime = outputLifetimes.next() val mergedLenses = getValidResult().groupBy { editor.document.getLineNumber(it.startOffset) } submittedGroupings.clear() mergedLenses.forEach { (_, lineLenses) -> if (lineLenses.isEmpty()) return@forEach val lastFilteredLineLenses = lineLenses.groupBy { it.codeVisionEntryOrThrow.providerId }.map { it.value.last() } val groupedLenses = lastFilteredLineLenses.groupBy { codeVisionHost.getAnchorForEntry(it.codeVisionEntryOrThrow) } val anchoringRange = groupedLenses.first().value.first() val range = TextRange(anchoringRange.startOffset, anchoringRange.endOffset) val handlerLambda = viewService.addCodeLenses(lifetime, editor, range, groupedLenses.map { it.key to it.value.map { it.codeVisionEntryOrThrow }.sortedBy { codeVisionHost.getPriorityForEntry(it) } }.associate { it }) val moreRange = TextRange(editor.document.getLineStartOffset(editor.document.getLineNumber(range.startOffset)), range.endOffset) submittedGroupings.add(moreRange to handlerLambda) } submittedGroupings.sortBy { it.first.startOffset } } } open fun clearLenses() { setResults(emptyList()) } protected open fun getValidResult(): Sequence<RangeMarker> = frontendResults.asSequence().filter { it.isValid } protected fun TextRange.isValidFor(document: Document): Boolean { return this.startOffset >= 0 && this.endOffset <= document.textLength } fun invokeMoreMenu(caretOffset: Int) { val selectedLens = submittedGroupings.binarySearchBy(caretOffset) { it.first.startOffset }.let { if (it < 0) -(it + 1) - 1 else it } if (selectedLens < 0 || selectedLens > submittedGroupings.lastIndex) return submittedGroupings[selectedLens].second(caretOffset) } fun hasProviderCodeVision(id: String): Boolean { return frontendResults.mapNotNull { it.getUserData(codeVisionEntryOnHighlighterKey) }.any { it.providerId == id } } open fun hasOnlyPlaceholders(): Boolean{ return frontendResults.all { it.getUserData(codeVisionEntryOnHighlighterKey) is PlaceholderCodeVisionEntry } } } private fun getOrCreateCodeVisionContext(editor: Editor): EditorCodeVisionContext? { val context = editor.getUserData(editorLensContextKey) if (context != null) return context val newContext = editor.project!!.service<CodeVisionContextProvider>().createCodeVisionContext(editor) editor.putUserData(editorLensContextKey, newContext) return newContext } internal fun List<Pair<String, CodeVisionProvider<*>>>.getTopSortedIdList(): List<String> { val fakeFirstNode = "!first!" val fakeLastNode = "!last!" val nodesAfter = HashMap<String, ArrayList<String>>() nodesAfter.getOrPut(fakeFirstNode) { ArrayList() }.add(fakeLastNode) this.forEach { (k, v) -> v.relativeOrderings.forEach { when (it) { is CodeVisionRelativeOrdering.CodeVisionRelativeOrderingBefore -> nodesAfter.getOrPut(k) { ArrayList() }.add(it.id) is CodeVisionRelativeOrdering.CodeVisionRelativeOrderingAfter -> nodesAfter.getOrPut(it.id) { ArrayList() }.add(k) is CodeVisionRelativeOrdering.CodeVisionRelativeOrderingFirst -> nodesAfter.getOrPut(fakeFirstNode) { ArrayList() }.add(k) is CodeVisionRelativeOrdering.CodeVisionRelativeOrderingLast -> nodesAfter.getOrPut(fakeLastNode) { ArrayList() }.add(k) else -> error("Unknown node ordering class ${it.javaClass.simpleName}") } } } val dfsVisited = HashSet<String>() val sortedList = ArrayList<String>() fun dfsTopSort(currentId: String) { if (!dfsVisited.add(currentId)) return nodesAfter[currentId]?.forEach { dfsTopSort(it) } if (currentId != fakeFirstNode && currentId != fakeLastNode) sortedList.add(currentId) } dfsTopSort(fakeLastNode) this.forEach { dfsTopSort(it.first) } dfsTopSort(fakeFirstNode) sortedList.reverse() return sortedList } internal fun <T> MutableList<T>.swap(i1: Int, i2: Int) { val t = get(i1) set(i1, get(i2)) set(i2, t) }
apache-2.0
6aa06f936b97c15574baf65f29a10222
36.280193
136
0.714619
4.512281
false
false
false
false
apache/isis
incubator/clients/kroviz/src/main/kotlin/org/apache/causeway/client/kroviz/utils/js/PdfJs.kt
2
2509
/* * 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 org.apache.causeway.client.kroviz.utils.js @JsModule("pdfjs") @JsNonModule // https://stackoverflow.com/questions/9328551/how-to-use-pdf-js external object PdfJs { // Fetch the PDF document from the URL using promises // PDFJS.getDocument('helloworld.pdf').then(function(pdf) { // Using promise to fetch the page // pdf.getPage(1).then(function(page) { // var scale = 1.5; // var viewport = page.getViewport(scale); // Prepare canvas using PDF page dimensions // var canvas = document.getElementById('the-canvas'); // var context = canvas.getContext('2d'); // canvas.height = viewport.height; // canvas.width = viewport.width; // Render PDF page into canvas context // var renderContext = { // canvasContext: context, // viewport: viewport // }; // page.render(renderContext); // }); // }); /* fun createDoc(): PdfJs { var doc = PdfJs() doc.text(20, 20, 'hello, I am PDF.'); doc.text(20, 30, 'i was created in the browser using javascript.'); doc.text(20, 40, 'i can also be created from node.js'); doc.setProperties({ title: 'A sample document created by pdf.js', subject: 'PDFs are kinda cool, i guess', author: 'Marak Squires', keywords: 'pdf.js, javascript, Marak, Marak Squires', creator: 'pdf.js' }); doc.addPage(); doc.setFontSize(22); doc.text(20, 20, 'This is a title'); doc.setFontSize(16); doc.text(20, 30, 'This is some normal sized text underneath.'); }*/ }
apache-2.0
6994170b33e9c77eedc28f5c0fce08e2
36.447761
75
0.628936
3.920313
false
false
false
false
JetBrains/intellij-community
platform/lang-impl/src/com/intellij/refactoring/rename/inplace/ImaginaryInplaceRefactoring.kt
1
6895
// 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.refactoring.rename.inplace import com.intellij.codeInsight.highlighting.HighlightManager import com.intellij.codeInsight.template.Expression import com.intellij.codeInsight.template.TemplateBuilderImpl import com.intellij.lang.Language import com.intellij.openapi.command.impl.StartMarkAction import com.intellij.openapi.editor.Document import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.markup.RangeHighlighter import com.intellij.openapi.editor.markup.TextAttributes import com.intellij.openapi.project.Project import com.intellij.openapi.ui.popup.BalloonBuilder import com.intellij.openapi.util.Pair import com.intellij.openapi.util.TextRange import com.intellij.openapi.vfs.VirtualFile import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import com.intellij.psi.PsiNamedElement import com.intellij.psi.PsiReference import com.intellij.psi.search.SearchScope import com.intellij.refactoring.RefactoringActionHandler import com.intellij.refactoring.rename.inplace.ImaginaryInplaceRefactoring.startsOnTheSameElements import com.intellij.util.ObjectUtils import javax.swing.JComponent /** * This object exists for the only sake of returning non-null value from [InplaceRefactoring.getActiveInplaceRenamer]. * Methods (except [startsOnTheSameElements]) throw an exception to avoid calling them unintentionally. */ internal object ImaginaryInplaceRefactoring : InplaceRefactoring( ObjectUtils.sentinel("imaginary editor", Editor::class.java), null, ObjectUtils.sentinel("imaginary project", Project::class.java) ) { override fun startsOnTheSameElements(editor: Editor?, handler: RefactoringActionHandler?, element: Array<out PsiElement>?): Boolean { return false } override fun setAdvertisementText(advertisementText: String?): Unit = error("must not be called") override fun performInplaceRefactoring(nameSuggestions: LinkedHashSet<String>?): Boolean = error("must not be called") override fun notSameFile(file: VirtualFile?, containingFile: PsiFile): Boolean = error("must not be called") override fun getReferencesSearchScope(file: VirtualFile?): SearchScope = error("must not be called") override fun checkLocalScope(): PsiElement = error("must not be called") override fun collectAdditionalElementsToRename(stringUsages: MutableList<in Pair<PsiElement, TextRange>>): Unit = error("must not be called") override fun createLookupExpression(selectedElement: PsiElement?): MyLookupExpression = error("must not be called") override fun createTemplateExpression(selectedElement: PsiElement?): Expression = error("must not be called") override fun acceptReference(reference: PsiReference?): Boolean = error("must not be called") override fun collectRefs(referencesSearchScope: SearchScope?): MutableCollection<PsiReference> = error("must not be called") override fun shouldStopAtLookupExpression(expression: Expression?): Boolean = error("must not be called") override fun isReferenceAtCaret(selectedElement: PsiElement?, ref: PsiReference?): Boolean = error("must not be called") override fun beforeTemplateStart(): Unit = error("must not be called") override fun afterTemplateStart(): Unit = error("must not be called") override fun restoreSelection(): Unit = error("must not be called") override fun restoreCaretOffset(offset: Int): Int = error("must not be called") override fun stopIntroduce(editor: Editor?): Unit = error("must not be called") override fun navigateToAlreadyStarted(oldDocument: Document?, exitCode: Int): Unit = error("must not be called") override fun getNameIdentifier(): PsiElement = error("must not be called") override fun startRename(): StartMarkAction = error("must not be called") override fun getVariable(): PsiNamedElement = error("must not be called") override fun moveOffsetAfter(success: Boolean): Unit = error("must not be called") override fun addAdditionalVariables(builder: TemplateBuilderImpl?): Unit = error("must not be called") override fun addReferenceAtCaret(refs: MutableCollection<in PsiReference>): Unit = error("must not be called") override fun showDialogAdvertisement(actionId: String?): Unit = error("must not be called") override fun getInitialName(): String = error("must not be called") override fun revertState(): Unit = error("must not be called") override fun finish(success: Boolean): Unit = error("must not be called") override fun performCleanup(): Unit = error("must not be called") override fun getRangeToRename(element: PsiElement): TextRange = error("must not be called") override fun getRangeToRename(reference: PsiReference): TextRange = error("must not be called") override fun setElementToRename(elementToRename: PsiNamedElement?): Unit = error("must not be called") override fun isIdentifier(newName: String?, language: Language?): Boolean = error("must not be called") override fun isRestart(): Boolean = error("must not be called") override fun startsOnTheSameElement(handler: RefactoringActionHandler?, element: PsiElement?): Boolean = error("must not be called") override fun releaseResources(): Unit = error("must not be called") override fun getComponent(): JComponent = error("must not be called") override fun showBalloon(): Unit = error("must not be called") override fun showBalloonInEditor(): Unit = error("must not be called") override fun adjustBalloon(builder: BalloonBuilder?): Unit = error("must not be called") override fun releaseIfNotRestart(): Unit = error("must not be called") override fun shouldSelectAll(): Boolean = error("must not be called") override fun getCommandName(): String = error("must not be called") override fun performRefactoring(): Boolean = error("must not be called") override fun getSelectedInEditorElement(nameIdentifier: PsiElement?, refs: MutableCollection<out PsiReference>?, stringUsages: MutableCollection<out Pair<PsiElement, TextRange>>?, offset: Int): PsiElement = error("must not be called") override fun addHighlights(ranges: MutableMap<TextRange, TextAttributes>, editor: Editor, highlighters: MutableCollection<RangeHighlighter>, highlightManager: HighlightManager): Unit = error("must not be called") override fun buildTemplateAndStart(refs: MutableCollection<PsiReference>?, stringUsages: MutableCollection<Pair<PsiElement, TextRange>>?, scope: PsiElement?, containingFile: PsiFile?): Boolean = error("must not be called") }
apache-2.0
2dd1bc2151ac00ed4a9f2c05adf01fae
67.267327
143
0.752429
5
false
false
false
false
JetBrains/intellij-community
platform/lang-impl/src/com/intellij/util/indexing/RescanIndexesAction.kt
1
5132
// 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 import com.intellij.ide.actions.cache.* import com.intellij.lang.LangBundle import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.progress.util.ProgressIndicatorUtils import com.intellij.openapi.project.DumbModeTask import com.intellij.openapi.vfs.VirtualFile import com.intellij.openapi.vfs.VirtualFileWithId import com.intellij.psi.stubs.StubTreeBuilder import com.intellij.psi.stubs.StubUpdatingIndex import com.intellij.util.BooleanFunction import com.intellij.util.indexing.diagnostic.ProjectIndexingHistoryImpl import com.intellij.util.indexing.diagnostic.ScanningType import com.intellij.util.indexing.roots.IndexableFilesIterator import com.intellij.util.indexing.roots.ProjectIndexableFilesIteratorImpl import org.jetbrains.annotations.ApiStatus import org.jetbrains.annotations.Nls import java.util.* import java.util.concurrent.CompletableFuture @ApiStatus.Internal class RescanIndexesAction : RecoveryAction { override val performanceRate: Int get() = 9990 override val presentableName: @Nls(capitalization = Nls.Capitalization.Title) String get() = LangBundle.message("rescan.indexes.recovery.action.name") override val actionKey: String get() = "rescan" override fun performSync(recoveryScope: RecoveryScope): List<CacheInconsistencyProblem> { val project = recoveryScope.project val historyFuture = CompletableFuture<ProjectIndexingHistoryImpl>() val stubAndIndexingStampInconsistencies = Collections.synchronizedList(arrayListOf<CacheInconsistencyProblem>()) var predefinedIndexableFilesIterators: List<IndexableFilesIterator>? = null if (recoveryScope is FilesRecoveryScope) { predefinedIndexableFilesIterators = recoveryScope.files.map { ProjectIndexableFilesIteratorImpl(it) } if (predefinedIndexableFilesIterators.isEmpty()) return emptyList() } object : UnindexedFilesScanner(project, false, false, predefinedIndexableFilesIterators, null, "Rescanning indexes recovery action", if(predefinedIndexableFilesIterators == null) ScanningType.FULL_FORCED else ScanningType.PARTIAL_FORCED) { private val stubIndex = runCatching { (FileBasedIndex.getInstance() as FileBasedIndexImpl).getIndex(StubUpdatingIndex.INDEX_ID) } .onFailure { logger<RescanIndexesAction>().error(it) }.getOrNull() private inner class StubAndIndexStampInconsistency(private val path: String): CacheInconsistencyProblem { override val message: String get() = "`$path` should have already indexed stub but it's not present" } override fun getForceReindexingTrigger(): BooleanFunction<IndexedFile>? { if (stubIndex != null) { return BooleanFunction<IndexedFile> { val fileId = (it.file as VirtualFileWithId).id if (stubIndex.getIndexingStateForFile(fileId, it) == FileIndexingState.UP_TO_DATE && stubIndex.getIndexedFileData(fileId).isEmpty() && isAbleToBuildStub(it.file)) { stubAndIndexingStampInconsistencies.add(StubAndIndexStampInconsistency(it.file.path)) return@BooleanFunction true } false } } return null } private fun isAbleToBuildStub(file: VirtualFile): Boolean = runCatching { StubTreeBuilder.buildStubTree(FileContentImpl.createByFile(file)) }.getOrNull() != null override fun performScanningAndIndexing(indicator: ProgressIndicator): ProjectIndexingHistoryImpl { try { IndexingFlag.cleanupProcessedFlag() val history = super.performScanningAndIndexing(indicator) historyFuture.complete(history) return history } catch (e: Exception) { historyFuture.completeExceptionally(e) throw e } } override fun tryMergeWith(taskFromQueue: UnindexedFilesScanner): UnindexedFilesScanner? = if (project == taskFromQueue.myProject && taskFromQueue.javaClass == javaClass) this else null }.queue(project) try { return ProgressIndicatorUtils.awaitWithCheckCanceled(historyFuture).extractConsistencyProblems() + stubAndIndexingStampInconsistencies } catch (e: Exception) { return listOf(ExceptionalCompletionProblem(e)) } } private fun ProjectIndexingHistoryImpl.extractConsistencyProblems(): List<CacheInconsistencyProblem> = scanningStatistics.filter { it.numberOfFilesForIndexing != 0 }.map { UnindexedFilesInconsistencyProblem(it.numberOfFilesForIndexing, it.providerName) } private class UnindexedFilesInconsistencyProblem(private val numberOfFilesForIndexing: Int, private val providerName: String) : CacheInconsistencyProblem { override val message: String get() = "Provider `$providerName` had $numberOfFilesForIndexing unindexed files" } }
apache-2.0
b62a1c47f256f34828a46f2e574cb1ef
46.091743
157
0.74318
5.001949
false
false
false
false
youdonghai/intellij-community
platform/built-in-server/src/org/jetbrains/builtInWebServer/DefaultWebServerRootsProvider.kt
1
9708
/* * Copyright 2000-2014 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.builtInWebServer import com.intellij.openapi.application.runReadAction import com.intellij.openapi.module.Module import com.intellij.openapi.module.ModuleManager import com.intellij.openapi.project.Project import com.intellij.openapi.projectRoots.ProjectJdkTable import com.intellij.openapi.projectRoots.Sdk import com.intellij.openapi.roots.* import com.intellij.openapi.roots.impl.DirectoryIndex import com.intellij.openapi.roots.impl.ModuleLibraryOrderEntryImpl import com.intellij.openapi.roots.libraries.LibraryTable import com.intellij.openapi.roots.libraries.LibraryTablesRegistrar import com.intellij.openapi.util.SystemInfo import com.intellij.openapi.util.text.StringUtil import com.intellij.openapi.vfs.JarFileSystem import com.intellij.openapi.vfs.VfsUtilCore import com.intellij.openapi.vfs.VirtualFile import com.intellij.project.rootManager import com.intellij.util.PlatformUtils import com.intellij.util.containers.computeOrNull private class DefaultWebServerRootsProvider : WebServerRootsProvider() { override fun resolve(path: String, project: Project): PathInfo? { var effectivePath = path if (PlatformUtils.isIntelliJ()) { val index = effectivePath.indexOf('/') if (index > 0 && !effectivePath.regionMatches(0, project.name, 0, index, !SystemInfo.isFileSystemCaseSensitive)) { val moduleName = effectivePath.substring(0, index) val module = runReadAction { ModuleManager.getInstance(project).findModuleByName(moduleName) } if (module != null && !module.isDisposed) { effectivePath = effectivePath.substring(index + 1) val resolver = WebServerPathToFileManager.getInstance(project).getResolver(effectivePath) val result = RootProvider.values().computeOrNull { findByRelativePath(effectivePath, it.getRoots(module.rootManager), resolver, moduleName) } ?: findInModuleLibraries(effectivePath, module, resolver) if (result != null) { return result } } } } val resolver = WebServerPathToFileManager.getInstance(project).getResolver(effectivePath) val modules = runReadAction { ModuleManager.getInstance(project).modules } for (rootProvider in RootProvider.values()) { for (module in modules) { if (module.isDisposed) { continue } findByRelativePath(path, rootProvider.getRoots(module.rootManager), resolver, null)?.let { it.moduleName = getModuleNameQualifier(project, module) return it } } } // https://youtrack.jetbrains.com/issue/WEB-24283 for (rootProvider in RootProvider.values()) { for (module in modules) { if (module.isDisposed) { continue } for (root in rootProvider.getRoots(module.rootManager)) { if (resolver.resolve("/config.json", root) != null) { resolver.resolve("/index.html", root)?.let { it.moduleName = getModuleNameQualifier(project, module) return it } } } } } return findInLibraries(project, effectivePath, resolver) } override fun getPathInfo(file: VirtualFile, project: Project): PathInfo? { return runReadAction { val directoryIndex = DirectoryIndex.getInstance(project) val info = directoryIndex.getInfoForFile(file) // we serve excluded files if (!info.isExcluded && !info.isInProject) { // javadoc jars is "not under project", but actually is, so, let's check library or SDK if (file.fileSystem == JarFileSystem.getInstance()) getInfoForDocJar(file, project) else null } else { var root = info.sourceRoot val isRootNameOptionalInPath: Boolean val isLibrary: Boolean if (root == null) { isRootNameOptionalInPath = false root = info.contentRoot if (root == null) { root = info.libraryClassRoot isLibrary = true assert(root != null) { file.presentableUrl } } else { isLibrary = false } } else { isLibrary = info.isInLibrarySource isRootNameOptionalInPath = !isLibrary } var module = info.module if (isLibrary && module == null) { for (entry in directoryIndex.getOrderEntries(info)) { if (entry is ModuleLibraryOrderEntryImpl) { module = entry.ownerModule break } } } PathInfo(null, file, root!!, getModuleNameQualifier(project, module), isLibrary, isRootNameOptionalInPath = isRootNameOptionalInPath) } } } } private enum class RootProvider { SOURCE { override fun getRoots(rootManager: ModuleRootManager): Array<VirtualFile> = rootManager.sourceRoots }, CONTENT { override fun getRoots(rootManager: ModuleRootManager): Array<VirtualFile> = rootManager.contentRoots }, EXCLUDED { override fun getRoots(rootManager: ModuleRootManager): Array<VirtualFile> = rootManager.excludeRoots }; abstract fun getRoots(rootManager: ModuleRootManager): Array<VirtualFile> } private val ORDER_ROOT_TYPES by lazy { val javaDocRootType = getJavadocOrderRootType() if (javaDocRootType == null) arrayOf(OrderRootType.DOCUMENTATION, OrderRootType.SOURCES, OrderRootType.CLASSES) else arrayOf(javaDocRootType, OrderRootType.DOCUMENTATION, OrderRootType.SOURCES, OrderRootType.CLASSES) } private fun getJavadocOrderRootType(): OrderRootType? { try { return JavadocOrderRootType.getInstance() } catch (e: Throwable) { return null } } private fun findInModuleLibraries(path: String, module: Module, resolver: FileResolver): PathInfo? { val index = path.indexOf('/') if (index <= 0) { return null } val libraryFileName = path.substring(0, index) val relativePath = path.substring(index + 1) return ORDER_ROOT_TYPES.computeOrNull { findInModuleLevelLibraries(module, it) { root, module -> if (StringUtil.equalsIgnoreCase(root.nameSequence, libraryFileName)) resolver.resolve(relativePath, root, isLibrary = true) else null } } } private fun findInLibraries(project: Project, path: String, resolver: FileResolver): PathInfo? { val index = path.indexOf('/') if (index < 0) { return null } val libraryFileName = path.substring(0, index) val relativePath = path.substring(index + 1) return findInLibrariesAndSdk(project, ORDER_ROOT_TYPES) { root, module -> if (StringUtil.equalsIgnoreCase(root.nameSequence, libraryFileName)) resolver.resolve(relativePath, root, isLibrary = true) else null } } private fun getInfoForDocJar(file: VirtualFile, project: Project): PathInfo? { val javaDocRootType = getJavadocOrderRootType() ?: return null return findInLibrariesAndSdk(project, arrayOf(javaDocRootType)) { root, module -> if (VfsUtilCore.isAncestor(root, file, false)) PathInfo(null, file, root, getModuleNameQualifier(project, module), true) else null } } private fun getModuleNameQualifier(project: Project, module: Module?): String? { if (module != null && PlatformUtils.isIntelliJ() && !(module.name.equals(project.name, ignoreCase = true) || compareNameAndProjectBasePath(module.name, project))) { return module.name } return null } private fun findByRelativePath(path: String, roots: Array<VirtualFile>, resolver: FileResolver, moduleName: String?) = roots.computeOrNull { resolver.resolve(path, it, moduleName) } private fun findInLibrariesAndSdk(project: Project, rootTypes: Array<OrderRootType>, fileProcessor: (root: VirtualFile, module: Module?) -> PathInfo?): PathInfo? { fun findInLibraryTable(table: LibraryTable, rootType: OrderRootType) = table.libraryIterator.computeOrNull { it.getFiles(rootType).computeOrNull { fileProcessor(it, null) } } fun findInProjectSdkOrInAll(rootType: OrderRootType): PathInfo? { val inSdkFinder = { sdk: Sdk -> sdk.rootProvider.getFiles(rootType).computeOrNull { fileProcessor(it, null) } } val projectSdk = ProjectRootManager.getInstance(project).projectSdk return projectSdk?.let(inSdkFinder) ?: ProjectJdkTable.getInstance().allJdks.computeOrNull { if (it === projectSdk) null else inSdkFinder(it) } } return rootTypes.computeOrNull { rootType -> runReadAction { findInLibraryTable(LibraryTablesRegistrar.getInstance().getLibraryTable(project), rootType) ?: findInProjectSdkOrInAll(rootType) ?: ModuleManager.getInstance(project).modules.computeOrNull { if (it.isDisposed) null else findInModuleLevelLibraries(it, rootType, fileProcessor) } ?: findInLibraryTable(LibraryTablesRegistrar.getInstance().libraryTable, rootType) } } } private fun findInModuleLevelLibraries(module: Module, rootType: OrderRootType, fileProcessor: (root: VirtualFile, module: Module?) -> PathInfo?): PathInfo? { return module.rootManager.orderEntries.computeOrNull { if (it is LibraryOrderEntry && it.isModuleLevel) it.getFiles(rootType).computeOrNull { fileProcessor(it, module) } else null } }
apache-2.0
eea7333d6c9427d6ab36ada8ade2ff2e
39.454167
181
0.713226
4.772861
false
false
false
false
JetBrains/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/conventionNameCalls/ReplaceContainsIntention.kt
1
3532
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.intentions.conventionNameCalls import com.intellij.codeInsight.intention.HighPriorityAction import com.intellij.openapi.editor.Editor import com.intellij.openapi.util.TextRange import org.jetbrains.kotlin.descriptors.FunctionDescriptor import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingRangeIntention import org.jetbrains.kotlin.idea.codeinsight.utils.appendSemicolonBeforeLambdaContainingElement import org.jetbrains.kotlin.idea.intentions.* import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.resolve.calls.model.ArgumentMatch import org.jetbrains.kotlin.resolve.calls.model.isReallySuccess import org.jetbrains.kotlin.resolve.descriptorUtil.builtIns import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.util.OperatorNameConventions class ReplaceContainsIntention : SelfTargetingRangeIntention<KtDotQualifiedExpression>( KtDotQualifiedExpression::class.java, KotlinBundle.lazyMessage("replace.contains.call.with.in.operator") ), HighPriorityAction { override fun applicabilityRange(element: KtDotQualifiedExpression): TextRange? { if (element.calleeName != OperatorNameConventions.CONTAINS.asString()) return null val resolvedCall = element.toResolvedCall(BodyResolveMode.PARTIAL) ?: return null if (!resolvedCall.isReallySuccess()) return null val argument = resolvedCall.call.valueArguments.singleOrNull() ?: return null if ((resolvedCall.getArgumentMapping(argument) as ArgumentMatch).valueParameter.index != 0) return null val target = resolvedCall.resultingDescriptor val returnType = target.returnType ?: return null if (!target.builtIns.isBooleanOrSubtype(returnType)) return null if (!element.isReceiverExpressionWithValue()) return null val functionDescriptor = getFunctionDescriptor(element) ?: return null if (!functionDescriptor.isOperatorOrCompatible) return null return element.callExpression!!.calleeExpression!!.textRange } override fun applyTo(element: KtDotQualifiedExpression, editor: Editor?) { val argument = element.callExpression!!.valueArguments.single().getArgumentExpression()!! val receiver = element.receiverExpression val psiFactory = KtPsiFactory(element.project) val prefixExpression = element.parent as? KtPrefixExpression val expression = if (prefixExpression != null && prefixExpression.operationToken == KtTokens.EXCL) { prefixExpression.replace(psiFactory.createExpressionByPattern("$0 !in $1", argument, receiver)) } else { element.replace(psiFactory.createExpressionByPattern("$0 in $1", argument, receiver)) } // Append semicolon to previous statement if needed if (argument is KtLambdaExpression) { psiFactory.appendSemicolonBeforeLambdaContainingElement(expression) } } private fun getFunctionDescriptor(element: KtDotQualifiedExpression): FunctionDescriptor? { val resolvedCall = element.resolveToCall() ?: return null return resolvedCall.resultingDescriptor as? FunctionDescriptor } }
apache-2.0
9bc2876be5b878a7f18843e9f9393afd
50.188406
158
0.775481
5.425499
false
false
false
false
JetBrains/intellij-community
platform/lang-impl/src/com/intellij/refactoring/rename/ui/renameUi.kt
1
2491
// 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.refactoring.rename.ui import com.intellij.model.Pointer import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.readAction import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.progress.Task import com.intellij.openapi.project.Project import com.intellij.openapi.util.NlsContexts.Command import com.intellij.openapi.util.NlsContexts.ProgressTitle import com.intellij.refactoring.RefactoringBundle import com.intellij.refactoring.rename.api.RenameTarget import kotlinx.coroutines.* import java.util.concurrent.locks.LockSupport /** * Shows a background progress indicator in the UI, * the indicator cancels the coroutine when cancelled from the UI. */ internal suspend fun <T> withBackgroundIndicator( project: Project, @ProgressTitle progressTitle: String, action: suspend CoroutineScope.() -> T ): T = coroutineScope { if (ApplicationManager.getApplication().isUnitTestMode) { return@coroutineScope action() } val deferred = async(block = action) launch(Dispatchers.IO) { // block some thread while [action] is not completed CoroutineBackgroundTask(project, progressTitle, deferred).queue() } deferred.await() } /** * - stays in progress while the [job] is running; * - cancels the [job] then user cancels the progress in the UI. */ private class CoroutineBackgroundTask( project: Project, @ProgressTitle progressTitle: String, private val job: Job ) : Task.Backgroundable(project, progressTitle) { override fun run(indicator: ProgressIndicator) { while (job.isActive) { if (indicator.isCanceled) { job.cancel() return } LockSupport.parkNanos(10_000_000) } } } private suspend fun Pointer<out RenameTarget>.presentableText(): String? { return readAction { dereference()?.presentation()?.presentableText } } @ProgressTitle internal suspend fun Pointer<out RenameTarget>.progressTitle(): String? { val presentableText = presentableText() ?: return null return RefactoringBundle.message("rename.progress.title.0", presentableText) } @Command internal suspend fun Pointer<out RenameTarget>.commandName(newName: String): String? { val presentableText = presentableText() ?: return null return RefactoringBundle.message("rename.command.name.0.1", presentableText, newName) }
apache-2.0
fab8085bd8071f689d1f32851f9d2e66
33.123288
120
0.766359
4.440285
false
false
false
false
JetBrains/intellij-community
platform/build-scripts/dev-server/src/IdeBuilder.kt
1
16355
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. @file:Suppress("ReplaceGetOrSet", "ReplacePutWithAssignment", "BlockingMethodInNonBlockingContext", "ReplaceNegatedIsEmptyWithIsNotEmpty") package org.jetbrains.intellij.build.devServer import com.intellij.diagnostic.telemetry.useWithScope import com.intellij.diagnostic.telemetry.useWithScope2 import com.intellij.openapi.util.io.NioFiles import com.intellij.util.PathUtilRt import com.intellij.util.lang.PathClassLoader import com.intellij.util.lang.UrlClassLoader import io.opentelemetry.api.common.AttributeKey import io.opentelemetry.api.trace.Span import kotlinx.collections.immutable.persistentListOf import kotlinx.coroutines.* import org.jetbrains.intellij.build.* import org.jetbrains.intellij.build.TraceManager.spanBuilder import org.jetbrains.intellij.build.dependencies.BuildDependenciesCommunityRoot import org.jetbrains.intellij.build.impl.* import org.jetbrains.intellij.build.impl.projectStructureMapping.LibraryFileEntry import org.jetbrains.intellij.build.impl.projectStructureMapping.ModuleOutputEntry import org.jetbrains.jps.model.artifact.JpsArtifactService import org.jetbrains.jps.model.library.JpsOrderRootType import org.jetbrains.jps.util.JpsPathUtil import org.jetbrains.xxh3.Xx3UnencodedString import java.lang.invoke.MethodHandles import java.lang.invoke.MethodType import java.nio.file.Files import java.nio.file.NoSuchFileException import java.nio.file.Path import kotlin.time.Duration.Companion.seconds internal const val UNMODIFIED_MARK_FILE_NAME = ".unmodified" private const val PLUGIN_CACHE_DIR_NAME = "plugin-cache" data class BuildRequest( @JvmField val platformPrefix: String, @JvmField val additionalModules: List<String>, @JvmField val isIdeProfileAware: Boolean = false, @JvmField val homePath: Path, @JvmField val productionClassOutput: Path = Path.of(System.getenv("CLASSES_DIR") ?: homePath.resolve("out/classes/production").toString()).toAbsolutePath(), @JvmField val keepHttpClient: Boolean = true, ) private suspend fun computeLibClassPath(targetFile: Path, homePath: Path, context: BuildContext) { spanBuilder("compute lib classpath").useWithScope2 { Files.writeString(targetFile, createLibClassPath(homePath, context)) } } internal class IdeBuilder(internal val pluginBuilder: PluginBuilder, outDir: Path, moduleNameToPlugin: Map<String, PluginBuildDescriptor>) { private class ModuleChangeInfo(@JvmField val moduleName: String, @JvmField var checkFile: Path, @JvmField var plugin: PluginBuildDescriptor) private val moduleChanges = moduleNameToPlugin.entries.map { val checkFile = outDir.resolve(it.key).resolve(UNMODIFIED_MARK_FILE_NAME) ModuleChangeInfo(moduleName = it.key, checkFile = checkFile, plugin = it.value) } fun checkChanged() { spanBuilder("check changes").useWithScope { span -> var changedModules = 0 for (item in moduleChanges) { if (Files.notExists(item.checkFile)) { pluginBuilder.addDirtyPluginDir(item.plugin, item.moduleName) changedModules++ } } span.setAttribute(AttributeKey.longKey("changedModuleCount"), changedModules.toLong()) } } } internal suspend fun buildProduct(productConfiguration: ProductConfiguration, request: BuildRequest, isServerMode: Boolean): IdeBuilder { val runDir = withContext(Dispatchers.IO) { var rootDir = request.homePath.resolve("out/dev-run") // if symlinked to ram disk, use real path for performance reasons and avoid any issues in ant/other code if (Files.exists(rootDir)) { // toRealPath must be called only on existing file rootDir = rootDir.toRealPath() } val classifier = if (request.isIdeProfileAware) computeAdditionalModulesFingerprint(request.additionalModules) else "" val runDir = rootDir.resolve((if (request.platformPrefix == "Idea") "idea-community" else request.platformPrefix) + classifier) // on start delete everything to avoid stale data if (Files.isDirectory(runDir)) { val usePluginCache = spanBuilder("check plugin cache applicability").useWithScope2 { checkBuildModulesModificationAndMark(productConfiguration, request.productionClassOutput) } prepareExistingRunDirForProduct(runDir = runDir, usePluginCache = usePluginCache) } else { Files.createDirectories(runDir) Span.current().addEvent("plugin cache is not reused because run dir doesn't exist") } runDir } val context = createBuildContext(productConfiguration = productConfiguration, request = request, runDir = runDir) val bundledMainModuleNames = getBundledMainModuleNames(context.productProperties, request.additionalModules) val pluginRootDir = runDir.resolve("plugins") val pluginCacheRootDir = runDir.resolve(PLUGIN_CACHE_DIR_NAME) val moduleNameToPluginBuildDescriptor = HashMap<String, PluginBuildDescriptor>() val pluginBuildDescriptors = mutableListOf<PluginBuildDescriptor>() for (plugin in getPluginLayoutsByJpsModuleNames(bundledMainModuleNames, context.productProperties.productLayout)) { if (!isPluginApplicable(bundledMainModuleNames = bundledMainModuleNames, plugin = plugin, context = context)) { continue } // remove all modules without content root val modules = plugin.includedModuleNames .filter { it == plugin.mainModule || !context.findRequiredModule(it).contentRootsList.urls.isEmpty() } .toList() val pluginBuildDescriptor = PluginBuildDescriptor(dir = pluginRootDir.resolve(plugin.directoryName), layout = plugin, moduleNames = modules) for (name in modules) { moduleNameToPluginBuildDescriptor.put(name, pluginBuildDescriptor) } pluginBuildDescriptors.add(pluginBuildDescriptor) } val artifactOutDir = request.homePath.resolve("out/classes/artifacts").toString() for (artifact in JpsArtifactService.getInstance().getArtifacts(context.project)) { artifact.outputPath = "$artifactOutDir/${PathUtilRt.getFileName(artifact.outputPath)}" } val pluginBuilder = PluginBuilder(outDir = request.productionClassOutput, pluginCacheRootDir = pluginCacheRootDir, context = context) coroutineScope { withContext(Dispatchers.IO) { Files.createDirectories(pluginRootDir) } launch { buildPlugins(pluginBuildDescriptors = pluginBuildDescriptors, pluginBuilder = pluginBuilder) } launch { computeLibClassPath(targetFile = runDir.resolve(if (isServerMode) "libClassPath.txt" else "core-classpath.txt"), homePath = request.homePath, context = context) } } return IdeBuilder(pluginBuilder = pluginBuilder, outDir = request.productionClassOutput, moduleNameToPlugin = moduleNameToPluginBuildDescriptor) } private suspend fun createBuildContext(productConfiguration: ProductConfiguration, request: BuildRequest, runDir: Path): BuildContext { return coroutineScope { // ~1 second val productProperties = async { withTimeout(30.seconds) { createProductProperties(productConfiguration = productConfiguration, request = request) } } // load project is executed as part of compilation context creation - ~1 second val compilationContext = async { spanBuilder("create build context").useWithScope2 { CompilationContextImpl.createCompilationContext( communityHome = getCommunityHomePath(request.homePath), projectHome = request.homePath, buildOutputRootEvaluator = { _ -> runDir }, setupTracer = false, options = createBuildOptions(runDir), ) } } BuildContextImpl.createContext(compilationContext = compilationContext.await(), projectHome = request.homePath, productProperties = productProperties.await() ) } } private fun isPluginApplicable(bundledMainModuleNames: Set<String>, plugin: PluginLayout, context: BuildContext): Boolean { if (!bundledMainModuleNames.contains(plugin.mainModule)) { return false } if (plugin.bundlingRestrictions == PluginBundlingRestrictions.NONE) { return true } return satisfiesBundlingRequirements(plugin = plugin, osFamily = OsFamily.currentOs, arch = JvmArchitecture.currentJvmArch, withEphemeral = false, context = context) || satisfiesBundlingRequirements(plugin = plugin, osFamily = null, arch = JvmArchitecture.currentJvmArch, withEphemeral = false, context = context) } private suspend fun createProductProperties(productConfiguration: ProductConfiguration, request: BuildRequest): ProductProperties { val classPathFiles = getBuildModules(productConfiguration).map { request.productionClassOutput.resolve(it) }.toList() val classLoader = spanBuilder("create product properties classloader").useWithScope2 { PathClassLoader(UrlClassLoader.build().files(classPathFiles).parent(IdeBuilder::class.java.classLoader)) } val productProperties = spanBuilder("create product properties").useWithScope2 { val productPropertiesClass = try { classLoader.loadClass(productConfiguration.className) } catch (e: ClassNotFoundException) { val classPathString = classPathFiles.joinToString(separator = "\n") { file -> "$file (" + (if (Files.isDirectory(file)) "dir" else if (Files.exists(file)) "exists" else "doesn't exist") + ")" } throw RuntimeException("cannot create product properties (classPath=$classPathString") } MethodHandles.lookup() .findConstructor(productPropertiesClass, MethodType.methodType(Void.TYPE, Path::class.java)) .invoke(request.homePath) as ProductProperties } return productProperties } private fun checkBuildModulesModificationAndMark(productConfiguration: ProductConfiguration, outDir: Path): Boolean { // intellij.platform.devBuildServer var isApplicable = true for (module in getBuildModules(productConfiguration) + sequenceOf("intellij.platform.devBuildServer", "intellij.platform.buildScripts", "intellij.platform.buildScripts.downloader", "intellij.idea.community.build.tasks")) { val markFile = outDir.resolve(module).resolve(UNMODIFIED_MARK_FILE_NAME) if (Files.exists(markFile)) { continue } if (isApplicable) { Span.current().addEvent("plugin cache is not reused because at least $module is changed") isApplicable = false } createMarkFile(markFile) } if (isApplicable) { Span.current().addEvent("plugin cache will be reused (build modules were not changed)") } return isApplicable } private fun getBuildModules(productConfiguration: ProductConfiguration): Sequence<String> { return sequenceOf("intellij.idea.community.build") + productConfiguration.modules.asSequence() } @Suppress("SpellCheckingInspection") private val extraJarNames = arrayOf("ideaLicenseDecoder.jar", "ls-client-api.jar", "y.jar", "ysvg.jar") @Suppress("KotlinConstantConditions") private suspend fun createLibClassPath(homePath: Path, context: BuildContext): String { val platformLayout = createPlatformLayout(pluginsToPublish = emptySet(), context = context) val isPackagedLib = System.getProperty("dev.server.pack.lib") == "true" val projectStructureMapping = processLibDirectoryLayout(moduleOutputPatcher = ModuleOutputPatcher(), platform = platformLayout, context = context, copyFiles = isPackagedLib) // for some reasons maybe duplicated paths - use set val classPath = LinkedHashSet<String>() if (isPackagedLib) { projectStructureMapping.mapTo(classPath) { it.path.toString() } } else { for (entry in projectStructureMapping) { when (entry) { is ModuleOutputEntry -> { if (isPackagedLib) { classPath.add(entry.path.toString()) } else { classPath.add(context.getModuleOutputDir(context.findRequiredModule(entry.moduleName)).toString()) } } is LibraryFileEntry -> { if (isPackagedLib) { classPath.add(entry.path.toString()) } else { classPath.add(entry.libraryFile.toString()) } } else -> throw UnsupportedOperationException("Entry $entry is not supported") } } for (libName in platformLayout.projectLibrariesToUnpack.values()) { val library = context.project.libraryCollection.findLibrary(libName) ?: throw IllegalStateException("Cannot find library $libName") library.getRootUrls(JpsOrderRootType.COMPILED).mapTo(classPath, JpsPathUtil::urlToPath) } } val projectLibDir = homePath.resolve("lib") for (extraJarName in extraJarNames) { val extraJar = projectLibDir.resolve(extraJarName) if (Files.exists(extraJar)) { classPath.add(extraJar.toString()) } } return classPath.joinToString(separator = "\n") } private fun getBundledMainModuleNames(productProperties: ProductProperties, additionalModules: List<String>): Set<String> { val bundledPlugins = LinkedHashSet(productProperties.productLayout.bundledPluginModules) bundledPlugins.addAll(additionalModules) return bundledPlugins } fun getAdditionalModules(): Sequence<String>? { return (System.getProperty("additional.modules") ?: return null) .splitToSequence(',') .map(String::trim) .filter { it.isNotEmpty() } } fun computeAdditionalModulesFingerprint(additionalModules: List<String>): String { if (additionalModules.isEmpty()) { return "" } val string = additionalModules.sorted().joinToString (",") val result = Xx3UnencodedString.hashUnencodedString(string, 0).toString(26) + Xx3UnencodedString.hashUnencodedString(string, 301236010888646397L).toString(36) // - maybe here due to negative number return if (result.startsWith('-')) result else "-$result" } private fun CoroutineScope.prepareExistingRunDirForProduct(runDir: Path, usePluginCache: Boolean) { launch { for (child in Files.newDirectoryStream(runDir).use { it.sorted() }) { if (child.endsWith("plugins") || child.endsWith(PLUGIN_CACHE_DIR_NAME)) { continue } if (Files.isDirectory(child)) { doClearDirContent(child) } else { Files.delete(child) } } } launch { val pluginCacheDir = runDir.resolve(PLUGIN_CACHE_DIR_NAME) val pluginDir = runDir.resolve("plugins") NioFiles.deleteRecursively(pluginCacheDir) if (usePluginCache) { // move to cache try { Files.move(pluginDir, pluginCacheDir) } catch (ignore: NoSuchFileException) { } } else { NioFiles.deleteRecursively(pluginDir) } } } private fun getCommunityHomePath(homePath: Path): BuildDependenciesCommunityRoot { val communityDotIdea = homePath.resolve("community/.idea") return BuildDependenciesCommunityRoot(if (Files.isDirectory(communityDotIdea)) communityDotIdea.parent else homePath) } private fun createBuildOptions(runDir: Path): BuildOptions { val options = BuildOptions() options.printFreeSpace = false options.useCompiledClassesFromProjectOutput = true options.targetOs = persistentListOf() options.cleanOutputFolder = false options.skipDependencySetup = true options.outputRootPath = runDir options.buildStepsToSkip.add(BuildOptions.PREBUILD_SHARED_INDEXES) return options }
apache-2.0
ee50a3b448cd2040235c0d6cd5d24066
41.59375
146
0.699725
4.956061
false
false
false
false
ViolentOr/RWinquisition
src/main/kotlin/me/violentor/rwinquisition/model/result/ConverterImpl.kt
1
1245
package me.violentor.rwinquisition.model.result import com.fasterxml.jackson.core.JsonProcessingException import com.fasterxml.jackson.databind.ObjectMapper import com.fasterxml.jackson.databind.ObjectReader import com.fasterxml.jackson.databind.ObjectWriter import java.io.IOException object ConverterImpl : Converter { override var reader: ObjectReader? = null override var writer: ObjectWriter? = null override val objectReader: ObjectReader? get() { if (reader == null) instantiateMapper() return reader } override val objectWriter: ObjectWriter? get() { if (writer == null) instantiateMapper() return writer } // Serialize/deserialize helpers @Throws(IOException::class) override fun fromJsonString(json: String): Result { return objectReader!!.readValue(json) } @Throws(JsonProcessingException::class) override fun toJsonString(obj: Result): String { return objectWriter!!.writeValueAsString(obj) } override fun instantiateMapper() { val mapper = ObjectMapper() reader = mapper.readerFor(Result::class.java) writer = mapper.writerFor(Result::class.java) } }
apache-2.0
bce984e25e8e1eb808746038285d8491
27.953488
57
0.688353
4.73384
false
false
false
false
android/wear-os-samples
WearStandaloneGoogleSignIn/app/src/main/java/com/example/android/wearable/wear/wearstandalonegooglesignin/GoogleSignInActivity.kt
1
6285
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.wearable.wear.wearstandalonegooglesignin import android.content.Context import android.content.Intent import android.os.Bundle import android.util.Log import android.widget.Toast import androidx.activity.ComponentActivity import androidx.activity.compose.rememberLauncherForActivityResult import androidx.activity.compose.setContent import androidx.activity.result.contract.ActivityResultContract import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import androidx.compose.ui.viewinterop.AndroidView import androidx.wear.compose.material.Chip import androidx.wear.compose.material.Text import com.google.android.gms.auth.api.signin.GoogleSignIn import com.google.android.gms.auth.api.signin.GoogleSignInAccount import com.google.android.gms.auth.api.signin.GoogleSignInClient import com.google.android.gms.auth.api.signin.GoogleSignInOptions import com.google.android.gms.auth.api.signin.GoogleSignInStatusCodes import com.google.android.gms.common.SignInButton import com.google.android.gms.common.api.ApiException import kotlinx.coroutines.launch import kotlinx.coroutines.tasks.await /** * Demonstrates using Google Sign-In on Android Wear */ class GoogleSignInActivity : ComponentActivity() { private val googleSignInClient by lazy { GoogleSignIn.getClient( this, GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN) .requestEmail() .build() ) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { var googleSignInAccount by remember { mutableStateOf(GoogleSignIn.getLastSignedInAccount(this)) } val signInRequestLauncher = rememberLauncherForActivityResult( contract = GoogleSignInContract(googleSignInClient) ) { googleSignInAccount = it if (googleSignInAccount != null) { Toast.makeText( this, R.string.google_signin_successful, Toast.LENGTH_SHORT ).show() } } val coroutineScope = rememberCoroutineScope() GoogleSignInScreen( googleSignInAccount = googleSignInAccount, onSignInClicked = { signInRequestLauncher.launch(Unit) }, onSignOutClicked = { coroutineScope.launch { try { googleSignInClient.signOut().await() googleSignInAccount = null Toast.makeText( this@GoogleSignInActivity, R.string.signout_successful, Toast.LENGTH_SHORT ).show() } catch (apiException: ApiException) { Log.w("GoogleSignInActivity", "Sign out failed: $apiException") } } } ) } } } @Composable fun GoogleSignInScreen( googleSignInAccount: GoogleSignInAccount?, onSignInClicked: () -> Unit, onSignOutClicked: () -> Unit ) { Column( modifier = Modifier .fillMaxSize() .padding(16.dp), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally ) { if (googleSignInAccount == null) { AndroidView(::SignInButton) { signInButton -> signInButton.setOnClickListener { onSignInClicked() } } } else { Chip( onClick = onSignOutClicked, label = { Text(text = stringResource(id = R.string.wear_signout_button_text)) } ) } } } /** * An [ActivityResultContract] for signing in with the given [GoogleSignInClient]. */ private class GoogleSignInContract( private val googleSignInClient: GoogleSignInClient ) : ActivityResultContract<Unit, GoogleSignInAccount?>() { override fun createIntent(context: Context, input: Unit): Intent = googleSignInClient.signInIntent override fun parseResult(resultCode: Int, intent: Intent?): GoogleSignInAccount? { val task = GoogleSignIn.getSignedInAccountFromIntent(intent) // As documented, this task must be complete check(task.isComplete) return if (task.isSuccessful) { task.result } else { val exception = task.exception check(exception is ApiException) Log.w( "GoogleSignInContract", "Sign in failed: code=${ exception.statusCode }, message=${ GoogleSignInStatusCodes.getStatusCodeString(exception.statusCode) }" ) null } } }
apache-2.0
b5e2d70716bc121b8fca0b0f4314584e
34.710227
91
0.640255
5.303797
false
false
false
false
Kotlin/kotlinx.coroutines
kotlinx-coroutines-core/js/src/Promise.kt
1
2829
/* * Copyright 2016-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. */ package kotlinx.coroutines import kotlin.coroutines.* import kotlin.js.* /** * Starts new coroutine and returns its result as an implementation of [Promise]. * * Coroutine context is inherited from a [CoroutineScope], additional context elements can be specified with [context] argument. * If the context does not have any dispatcher nor any other [ContinuationInterceptor], then [Dispatchers.Default] is used. * The parent job is inherited from a [CoroutineScope] as well, but it can also be overridden * with corresponding [context] element. * * By default, the coroutine is immediately scheduled for execution. * Other options can be specified via `start` parameter. See [CoroutineStart] for details. * * @param context additional to [CoroutineScope.coroutineContext] context of the coroutine. * @param start coroutine start option. The default value is [CoroutineStart.DEFAULT]. * @param block the coroutine code. */ public fun <T> CoroutineScope.promise( context: CoroutineContext = EmptyCoroutineContext, start: CoroutineStart = CoroutineStart.DEFAULT, block: suspend CoroutineScope.() -> T ): Promise<T> = async(context, start, block).asPromise() /** * Converts this deferred value to the instance of [Promise]. */ public fun <T> Deferred<T>.asPromise(): Promise<T> { val promise = Promise<T> { resolve, reject -> invokeOnCompletion { val e = getCompletionExceptionOrNull() if (e != null) { reject(e) } else { resolve(getCompleted()) } } } promise.asDynamic().deferred = this return promise } /** * Converts this promise value to the instance of [Deferred]. */ public fun <T> Promise<T>.asDeferred(): Deferred<T> { val deferred = asDynamic().deferred @Suppress("UnsafeCastFromDynamic") return deferred ?: GlobalScope.async(start = CoroutineStart.UNDISPATCHED) { await() } } /** * Awaits for completion of the promise without blocking. * * This suspending function is cancellable. * If the [Job] of the current coroutine is cancelled or completed while this suspending function is waiting, this function * stops waiting for the promise and immediately resumes with [CancellationException]. * There is a **prompt cancellation guarantee**. If the job was cancelled while this function was * suspended, it will not resume successfully. See [suspendCancellableCoroutine] documentation for low-level details. */ public suspend fun <T> Promise<T>.await(): T = suspendCancellableCoroutine { cont: CancellableContinuation<T> -> [email protected]( onFulfilled = { cont.resume(it) }, onRejected = { cont.resumeWithException(it) }) }
apache-2.0
27d7b5acd34ab09352dcc9e47a7a9bea
38.291667
128
0.710852
4.6
false
false
false
false
leafclick/intellij-community
platform/statistics/uploader/src/com/intellij/internal/statistic/eventLog/EventLogFile.kt
1
1648
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.internal.statistic.eventLog import java.io.File import java.nio.file.Path import java.util.* import kotlin.math.max class EventLogFile(val file: File) { companion object { @JvmStatic fun create(dir: Path, buildType: EventLogBuildType, suffix: String): EventLogFile { var file = dir.resolve(newName(buildType, suffix)).toFile() while (file.exists()) { file = dir.resolve(newName(buildType, suffix)).toFile() } return EventLogFile(file) } private fun newName(buildType: EventLogBuildType, suffix: String): String { val rand = UUID.randomUUID().toString() val start = rand.indexOf('-') val unique = if (start > 0 && start + 1 < rand.length) rand.substring(start + 1) else rand return if (suffix.isNotEmpty()) "$unique-$suffix-${buildType.text}.log" else "$unique-${buildType.text}.log" } } fun getType(): EventLogBuildType { return when (parseType()) { EventLogBuildType.EAP.text -> EventLogBuildType.EAP EventLogBuildType.RELEASE.text -> EventLogBuildType.RELEASE else -> EventLogBuildType.UNKNOWN } } private fun parseType(): String { val name = file.name val separator = name.lastIndexOf("-") if (separator + 1 < name.length) { val startIndex = max(separator + 1, 0) val endIndex = name.indexOf(".", startIndex) return if (endIndex < 0) name.substring(startIndex) else name.substring(startIndex, endIndex) } return name } }
apache-2.0
7113be03168e14035bffd72b0f7e4338
34.085106
140
0.675364
4.130326
false
false
false
false
anthonycr/Lightning-Browser
app/src/test/java/acr/browser/lightning/adblock/allowlist/SessionAllowListModelTest.kt
1
5448
package acr.browser.lightning.adblock.allowlist import acr.browser.lightning.SDK_VERSION import acr.browser.lightning.TestApplication import acr.browser.lightning.database.allowlist.AdBlockAllowListRepository import acr.browser.lightning.database.allowlist.AllowListEntry import acr.browser.lightning.log.NoOpLogger import com.nhaarman.mockito_kotlin.any import com.nhaarman.mockito_kotlin.mock import com.nhaarman.mockito_kotlin.whenever import io.reactivex.Completable import io.reactivex.Maybe import io.reactivex.Single import io.reactivex.schedulers.Schedulers import org.assertj.core.api.Assertions.assertThat import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner import org.robolectric.annotation.Config /** * Unit tests for [SessionAllowListModel]. */ @RunWith(RobolectricTestRunner::class) @Config(application = TestApplication::class, sdk = [SDK_VERSION]) class SessionAllowListModelTest { private val adBlockAllowListModel = mock<AdBlockAllowListRepository>() @Test fun `isUrlAllowListed checks domain`() { whenever(adBlockAllowListModel.allAllowListItems()).thenReturn(Single.just(listOf(AllowListEntry("test.com", 0)))) val sessionAllowListModel = SessionAllowListModel(adBlockAllowListModel, Schedulers.trampoline(), NoOpLogger()) assertThat(sessionAllowListModel.isUrlAllowedAds("http://test.com/12345")).isTrue() assertThat(sessionAllowListModel.isUrlAllowedAds("https://test.com")).isTrue() assertThat(sessionAllowListModel.isUrlAllowedAds("https://tests.com")).isFalse() } @Test fun `addUrlToAllowList updates immediately`() { whenever(adBlockAllowListModel.allAllowListItems()).thenReturn(Single.just(emptyList())) whenever(adBlockAllowListModel.allowListItemForUrl(any())).thenReturn(Maybe.empty()) whenever(adBlockAllowListModel.addAllowListItem(any())).thenReturn(Completable.complete()) val sessionAllowListModel = SessionAllowListModel(adBlockAllowListModel, Schedulers.trampoline(), NoOpLogger()) assertThat(sessionAllowListModel.isUrlAllowedAds("http://test.com")).isFalse() sessionAllowListModel.addUrlToAllowList("https://test.com/12345") assertThat(sessionAllowListModel.isUrlAllowedAds("http://test.com")).isTrue() } @Test fun `removeUrlFromAllowList updates immediately`() { whenever(adBlockAllowListModel.allAllowListItems()).thenReturn(Single.just(listOf(AllowListEntry("test.com", 0)))) whenever(adBlockAllowListModel.allowListItemForUrl(any())).thenReturn(Maybe.empty()) whenever(adBlockAllowListModel.removeAllowListItem(any())).thenReturn(Completable.complete()) val sessionAllowListModel = SessionAllowListModel(adBlockAllowListModel, Schedulers.trampoline(), NoOpLogger()) assertThat(sessionAllowListModel.isUrlAllowedAds("http://test.com")).isTrue() sessionAllowListModel.removeUrlFromAllowList("https://test.com/12345") assertThat(sessionAllowListModel.isUrlAllowedAds("http://test.com")).isFalse() } @Test fun `addUrlToAllowList persists across instances`() { val mutableList = mutableListOf<AllowListEntry>() whenever(adBlockAllowListModel.allAllowListItems()).thenReturn(Single.just(mutableList)) whenever(adBlockAllowListModel.allowListItemForUrl(any())).thenReturn(Maybe.empty()) whenever(adBlockAllowListModel.addAllowListItem(any())).then { invocation -> return@then Completable.fromAction { mutableList.add(invocation.arguments[0] as AllowListEntry) } } val oldAllowListModel = SessionAllowListModel(adBlockAllowListModel, Schedulers.trampoline(), NoOpLogger()) assertThat(oldAllowListModel.isUrlAllowedAds("http://test.com")).isFalse() oldAllowListModel.addUrlToAllowList("https://test.com/12345") val newAllowListModel = SessionAllowListModel(adBlockAllowListModel, Schedulers.trampoline(), NoOpLogger()) assertThat(newAllowListModel.isUrlAllowedAds("http://test.com")).isTrue() } @Test fun `removeUrlFromAllowList persists across instances`() { val mutableList = mutableListOf(AllowListEntry("test.com", 0)) whenever(adBlockAllowListModel.allAllowListItems()).thenReturn(Single.just(mutableList)) whenever(adBlockAllowListModel.allAllowListItems()).thenReturn(Single.just(mutableList)) whenever(adBlockAllowListModel.allowListItemForUrl(any())).then { invocation -> return@then Maybe.fromCallable { return@fromCallable mutableList.find { it.domain == (invocation.arguments[0] as String) } } } whenever(adBlockAllowListModel.removeAllowListItem(any())).then { invocation -> return@then Completable.fromAction { mutableList.remove(invocation.arguments[0] as AllowListEntry) } } val oldAllowListModel = SessionAllowListModel(adBlockAllowListModel, Schedulers.trampoline(), NoOpLogger()) assertThat(oldAllowListModel.isUrlAllowedAds("http://test.com")).isTrue() oldAllowListModel.removeUrlFromAllowList("https://test.com/12345") val newAllowListModel = SessionAllowListModel(adBlockAllowListModel, Schedulers.trampoline(), NoOpLogger()) assertThat(newAllowListModel.isUrlAllowedAds("http://test.com")).isFalse() } }
mpl-2.0
fff20541b2f7032990afd9001a9cdff4
45.965517
122
0.745962
4.692506
false
true
false
false
edvin/kdbc
src/main/kotlin/kdbc/query.kt
1
10734
package kdbc import java.io.Closeable import java.io.InputStream import java.math.BigDecimal import java.sql.Connection import java.sql.PreparedStatement import java.sql.ResultSet import java.sql.SQLException import java.time.LocalDate import java.time.LocalDateTime import java.time.LocalTime import java.util.* import java.util.concurrent.atomic.AtomicInteger import java.util.logging.Level abstract class Query<T>(var connection: Connection? = null, var autoclose: Boolean = true, op: (Query<T>.() -> Unit)? = null) : Expr(null), Closeable { private var withGeneratedKeys: (ResultSet.(Int) -> Unit)? = null val tables = mutableListOf<Table>() lateinit var stmt: PreparedStatement private var vetoclose: Boolean = false private var mapper: () -> T = { throw SQLException("You must provide a mapper to this query by calling mapper { () -> T } or override `get(): T`.\n\n${describe()}") } init { op?.invoke(this) } /** * Convert a result row into the query result object. Extract the data from * the Table instances you used to construct the query. */ open fun get(): T = mapper() fun map(mapper: () -> T) { this.mapper = mapper } fun generatedKeys(op: ResultSet.(Int) -> Unit) { withGeneratedKeys = op } /** * Add table and configure alias if more than one table. Also configure alias for the first table if you add a second */ internal fun addTable(table: Table) { if (!tables.contains(table)) { tables.add(table) if (tables.size > 1) table.configureAlias() if (tables.size == 2) tables.first().configureAlias() } } private fun Table.configureAlias() { if (tableAlias == null) { if (tables.find { it.tableAlias == tableName } == null) tableAlias = tableName else tableAlias = "$tableName${tables.indexOf(this) + 1}" } } override fun render(s: StringBuilder) = renderChildren(s) fun first(op: (Query<T>.() -> Unit)? = null): T { op?.invoke(this) return firstOrNull()!! } fun firstOrNull(op: (Query<T>.() -> Unit)? = null): T? { op?.invoke(this) val rs = requireResultSet() try { return if (rs.next()) { tables.forEach { it.rs = rs } get() } else null } finally { checkClose() } } fun list(op: (Query<T>.() -> Unit)? = null): List<T> { op?.invoke(this) val rs = requireResultSet() val list = mutableListOf<T>() while (rs.next()) { tables.forEach { it.rs = rs } list.add(get()) } try { return list } finally { checkClose() } } fun sequence(op: (Query<T>.() -> Unit)? = null) = iterator(op).asSequence() fun iterator(op: (Query<T>.() -> Unit)? = null): Iterator<T> { op?.invoke(this) val rs = requireResultSet() return object : Iterator<T> { override fun next(): T { tables.forEach { it.rs = rs } return get() } override fun hasNext(): Boolean { val hasNext = rs.next() if (!hasNext) { rs.close() checkClose() } return hasNext } } } private fun requireResultSet(): ResultSet { vetoclose = true try { val result = execute() if (!result.hasResultSet) { checkClose() throw SQLException("List was requested but query returned no ResultSet.\n${describe()}") } } finally { vetoclose = false } return stmt.resultSet } /** * Should we close this connection? Unless spesifically stopped via vetoclose * a connection will close if autoclose is set or if this query does not * participate in a transaction. */ private fun checkClose() { if (!vetoclose && !ConnectionFactory.isTransactionActive && autoclose) close() } override fun close() { logErrors("Closing connection") { connection!!.close() } } val resultSet: ResultSet get() = stmt.resultSet!! operator fun invoke() = execute() /** * Gather parameters, render the SQL, prepare the statement and execute the query. */ fun execute(op: (Query<T>.() -> Unit)? = null): ExecutionResult<T> { op?.invoke(this) if (connection == null) { connection(KDBC.connectionFactory.borrow(this)) } else { val activeTransaction = ConnectionFactory.transactionContext.get() if (activeTransaction != null && activeTransaction.connection == null) activeTransaction.connection = connection } var hasResultSet: Boolean? = null try { val keyStrategy = if (withGeneratedKeys != null) PreparedStatement.RETURN_GENERATED_KEYS else PreparedStatement.NO_GENERATED_KEYS val batch = expressions.first() as? BatchExpr<Any> if (batch != null) { val wasAutoCommit = connection!!.autoCommit connection!!.autoCommit = false val iterator = batch.entities.iterator() if (!iterator.hasNext()) throw SQLException("Batch expression with no entities.\n${describe()}") var first = true while (iterator.hasNext()) { batch.op(batch, iterator.next()) if (first) { stmt = render().let { if (KDBC.debug) logger.log(Level.INFO, it) connection!!.prepareStatement(it, keyStrategy) } first = false } applyParameters() handleGeneratedKeys() stmt.addBatch() batch.expressions.clear() } val updates = if (batch.large) stmt.executeLargeBatch().toList() else stmt.executeBatch().map { it.toLong() } connection!!.commit() if (wasAutoCommit) connection!!.autoCommit = true return ExecutionResult(this, false, updates) } else { stmt = render().let { if (KDBC.debug) logger.log(Level.INFO, it) connection!!.prepareStatement(it, keyStrategy) } applyParameters() hasResultSet = stmt.execute() handleGeneratedKeys() return ExecutionResult(this, hasResultSet, listOf(stmt.updateCount.toLong())) } } catch (ex: Exception) { throw SQLException("${ex.message}\n\n${describe()}", ex) } finally { if (hasResultSet == false) checkClose() } } private fun handleGeneratedKeys() { withGeneratedKeys?.apply { val keysRs = stmt.generatedKeys val counter = AtomicInteger() while (keysRs.next()) this.invoke(keysRs, counter.andIncrement) } } val params: List<Param> get() { val list = mutableListOf<Param>() gatherParams(list) return list } fun applyParameters() { params.filterNot { it.value is Column<*> }.forEachIndexed { pos, param -> applyParameter(param, pos + 1) } } private fun applyParameter(param: Param, pos: Int) { val handler: TypeHandler<Any?>? = param.handler ?: if (param.value != null) typeHandlers[param.value.javaClass.kotlin] else null if (handler != null) { handler.setParam(stmt, pos, param.value) } else if (param.type != null) { if (param.value == null) stmt.setNull(pos, param.type!!) else stmt.setObject(pos, param.value, param.type!!) } else { when (param.value) { is UUID -> stmt.setObject(pos, param.value) is Int -> stmt.setInt(pos, param.value) is String -> stmt.setString(pos, param.value) is Double -> stmt.setDouble(pos, param.value) is Boolean -> stmt.setBoolean(pos, param.value) is Float -> stmt.setFloat(pos, param.value) is Long -> stmt.setLong(pos, param.value) is LocalTime -> stmt.setTime(pos, java.sql.Time.valueOf(param.value)) is LocalDate -> stmt.setDate(pos, java.sql.Date.valueOf(param.value)) is LocalDateTime -> stmt.setTimestamp(pos, java.sql.Timestamp.valueOf(param.value)) is BigDecimal -> stmt.setBigDecimal(pos, param.value) is InputStream -> stmt.setBinaryStream(pos, param.value) is Enum<*> -> stmt.setObject(pos, param.value) null -> throw SQLException("Parameter #$pos is null, you must provide a handler or sql type.\n${describe()}") else -> throw SQLException("Don't know how to handle parameters of type ${param.value.javaClass}.\n${describe()}") } } } fun describe(): String { val s = StringBuilder() s.append("Query : ${this}\n") s.append("SQL : ${render().replace("\n", " \n")}\n") s.append("Params : $params") val transaction = ConnectionFactory.transactionContext.get() if (transaction != null) s.append("\nTX ID : ${transaction.id}") return s.toString() } } abstract class Insert(connection: Connection? = null, autoclose: Boolean = true) : Query<Any>(connection, autoclose) abstract class Update(connection: Connection? = null, autoclose: Boolean = true) : Query<Any>(connection, autoclose) abstract class Delete(connection: Connection? = null, autoclose: Boolean = true) : Query<Any>(connection, autoclose) fun <Q : Query<*>> Q.connection(connection: Connection): Q { this.connection = connection return this } fun <Q : Query<*>> Q.autoclose(autoclose: Boolean): Q { this.autoclose = autoclose return this } data class ExecutionResult<T>(val query: Query<T>, val hasResultSet: Boolean, val updates: List<Long>) { val updatedRows: Long get() = updates.sum() } inline fun <DomainType> query(connection: Connection? = null, autoclose: Boolean = true, crossinline op: Query<DomainType>.() -> Unit) = object : Query<DomainType>(connection, autoclose) { init { op(this) } }
apache-2.0
2ea53ba9f16337dc7820ff8f070f30c4
35.144781
188
0.559065
4.491213
false
false
false
false
smmribeiro/intellij-community
platform/platform-impl/src/com/intellij/notification/impl/ui/DoNotAskConfigurableUi.kt
1
3908
// 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.notification.impl.ui import com.intellij.ide.DataManager import com.intellij.ide.IdeBundle import com.intellij.ide.util.BasePropertyService import com.intellij.ide.util.PropertiesComponent import com.intellij.openapi.actionSystem.CommonDataKeys import com.intellij.openapi.project.Project import com.intellij.openapi.wm.WindowManager import com.intellij.ui.SimpleListCellRenderer import com.intellij.ui.ToolbarDecorator import com.intellij.ui.components.JBList import javax.swing.DefaultListModel import javax.swing.JComponent import kotlin.math.min private const val DO_NOT_ASK_KEY_PREFIX = "Notification.DoNotAsk-" internal class DoNotAskConfigurableUi { private var myCreated = false private lateinit var myList: JBList<DoNotAskInfo> private val myRemoveList = ArrayList<DoNotAskInfo>() private fun createDoNotAskList(): JBList<DoNotAskInfo> { val result = JBList(*getDoNotAskValues().toTypedArray()) result.emptyText.clear() val projectTitle = IdeBundle.message("notifications.configurable.do.not.ask.project.title") result.cellRenderer = SimpleListCellRenderer.create("") { if (it.forProject) it.name + " (${projectTitle})" else it.name } return result } fun getDoNotAskValues(): List<DoNotAskInfo> { val list = ArrayList<DoNotAskInfo>() getValues(PropertiesComponent.getInstance(), list, false) val project = getProject() if (project != null) { getValues(PropertiesComponent.getInstance(project), list, true) } list.sortWith(Comparator { o1, o2 -> o1.id.compareTo(o2.id) }) return list } private fun getProject(): Project? { return CommonDataKeys.PROJECT.getData(DataManager.getInstance().getDataContext(WindowManager.getInstance().mostRecentFocusedWindow)) } private fun getValues(manager: PropertiesComponent, list: ArrayList<DoNotAskInfo>, forProject: Boolean) { if (manager is BasePropertyService) { manager.forEachPrimitiveValue { key, value -> if (key.startsWith(DO_NOT_ASK_KEY_PREFIX)) { list.add(DoNotAskInfo(key.substring(DO_NOT_ASK_KEY_PREFIX.length), value, forProject)) } } } } fun createComponent(): JComponent { myList = createDoNotAskList() myCreated = true return ToolbarDecorator.createDecorator(myList).disableUpDownActions().setRemoveAction { removeSelectedItems() }.createPanel() } private fun removeSelectedItems() { val indices = myList.selectedIndices val model = myList.model as DefaultListModel<DoNotAskInfo> for (index in indices.reversed()) { myRemoveList.add(model.getElementAt(index)) model.remove(index) } val size = model.size() if (size > 0) { myList.selectedIndex = min(size - 1, indices.last()) } } fun isModified(): Boolean { return myCreated && myRemoveList.isNotEmpty() } fun reset() { if (myCreated) { myRemoveList.clear() val selectedIndices = myList.selectedIndices myList.model = createDoNotAskList().model myList.selectedIndices = selectedIndices } } fun apply() { val manager = PropertiesComponent.getInstance() val project = getProject() val projectManager = if (project == null) null else PropertiesComponent.getInstance(project) for (info in myRemoveList) { if (info.forProject) { if (projectManager != null) { removeKey(projectManager, info.id) } } else { removeKey(manager, info.id) } } } private fun removeKey(manager: PropertiesComponent, id: String) { manager.unsetValue("Notification.DoNotAsk-$id") manager.unsetValue("Notification.DisplayName-DoNotAsk-$id") } } data class DoNotAskInfo(val id: String, val name: String, val forProject: Boolean)
apache-2.0
bf87cb6b881a2ee72e442ee6fb3ce678
30.780488
136
0.71827
4.337403
false
false
false
false
smmribeiro/intellij-community
platform/platform-impl/src/com/intellij/diagnostic/hprof/analysis/AnalyzeGraph.kt
10
17681
/* * Copyright (C) 2018 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.diagnostic.hprof.analysis import com.google.common.base.Stopwatch import com.intellij.diagnostic.DiagnosticBundle import com.intellij.diagnostic.hprof.classstore.ClassDefinition import com.intellij.diagnostic.hprof.histogram.Histogram import com.intellij.diagnostic.hprof.navigator.ObjectNavigator import com.intellij.diagnostic.hprof.util.HeapReportUtils.sectionHeader import com.intellij.diagnostic.hprof.util.HeapReportUtils.toPaddedShortStringAsCount import com.intellij.diagnostic.hprof.util.HeapReportUtils.toPaddedShortStringAsSize import com.intellij.diagnostic.hprof.util.HeapReportUtils.toShortStringAsCount import com.intellij.diagnostic.hprof.util.HeapReportUtils.toShortStringAsSize import com.intellij.diagnostic.hprof.util.PartialProgressIndicator import com.intellij.diagnostic.hprof.visitors.HistogramVisitor import com.intellij.openapi.progress.ProgressIndicator import it.unimi.dsi.fastutil.ints.* import it.unimi.dsi.fastutil.longs.LongArrayList fun analyzeGraph(analysisContext: AnalysisContext, progress: ProgressIndicator): String { return AnalyzeGraph(analysisContext).analyze(progress) } open class AnalyzeGraph(protected val analysisContext: AnalysisContext) { private var strongRefHistogram: Histogram? = null private var softWeakRefHistogram: Histogram? = null private val parentList = analysisContext.parentList private fun setParentForObjectId(objectId: Long, parentId: Long) { parentList[objectId.toInt()] = parentId.toInt() } private fun getParentIdForObjectId(objectId: Long): Long { return parentList[objectId.toInt()].toLong() } private val nominatedInstances = HashMap<ClassDefinition, IntSet>() open fun analyze(progress: ProgressIndicator): String { val sb = StringBuilder() val includePerClassSection = analysisContext.config.perClassOptions.classNames.isNotEmpty() val traverseProgress = if (includePerClassSection) PartialProgressIndicator(progress, 0.0, 0.5) else progress traverseInstanceGraph(traverseProgress) val analyzeDisposer = AnalyzeDisposer(analysisContext) analyzeDisposer.computeDisposedObjectsIDs() // Histogram section val histogramOptions = analysisContext.config.histogramOptions if (histogramOptions.includeByCount || histogramOptions.includeBySize) { sb.appendLine(sectionHeader("Histogram")) sb.append(prepareHistogramSection()) } // Per-class section if (includePerClassSection) { val perClassProgress = PartialProgressIndicator(progress, 0.5, 0.5) sb.appendLine(sectionHeader("Instances of each nominated class")) sb.append(preparePerClassSection(perClassProgress)) } // Disposer sections if (config.disposerOptions.includeDisposerTree) { sb.appendLine(sectionHeader("Disposer tree")) sb.append(analyzeDisposer.prepareDisposerTreeSection()) } if (config.disposerOptions.includeDisposedObjectsSummary || config.disposerOptions.includeDisposedObjectsDetails) { sb.appendLine(sectionHeader("Disposed objects")) sb.append(analyzeDisposer.prepareDisposedObjectsSection()) } return sb.toString() } private fun preparePerClassSection(progress: PartialProgressIndicator): String { val sb = StringBuilder() val histogram = analysisContext.histogram val perClassOptions = analysisContext.config.perClassOptions if (perClassOptions.includeClassList) { sb.appendLine("Nominated classes:") perClassOptions.classNames.forEach { name -> val (classDefinition, totalInstances, totalBytes) = histogram.entries.find { entry -> entry.classDefinition.name == name } ?: return@forEach val prettyName = classDefinition.prettyName sb.appendLine(" --> [${toShortStringAsCount(totalInstances)}/${toShortStringAsSize(totalBytes)}] " + prettyName) } sb.appendLine() } val nav = analysisContext.navigator var counter = 0 val nominatedClassNames = config.perClassOptions.classNames val stopwatch = Stopwatch.createUnstarted() nominatedClassNames.forEach { className -> val classDefinition = nav.classStore[className] val set = nominatedInstances[classDefinition]!! progress.fraction = counter.toDouble() / nominatedInstances.size progress.text2 = DiagnosticBundle.message("hprof.analysis.progress", set.size, classDefinition.prettyName) stopwatch.reset().start() sb.appendLine("CLASS: ${classDefinition.prettyName} (${set.size} objects)") val referenceRegistry = GCRootPathsTree(analysisContext, perClassOptions.treeDisplayOptions, classDefinition) set.forEach { objectId -> referenceRegistry.registerObject(objectId) } set.clear() sb.append(referenceRegistry.printTree()) if (config.metaInfoOptions.include) { sb.appendLine("Report for ${classDefinition.prettyName} created in $stopwatch") } sb.appendLine() counter++ } progress.fraction = 1.0 return sb.toString() } private fun prepareHistogramSection(): String { val result = StringBuilder() val strongRefHistogram = getAndClearStrongRefHistogram() val softWeakRefHistogram = getAndClearSoftWeakHistogram() val histogram = analysisContext.histogram val histogramOptions = analysisContext.config.histogramOptions result.append( Histogram.prepareMergedHistogramReport(histogram, "All", strongRefHistogram, "Strong-ref", histogramOptions)) val unreachableObjectsCount = histogram.instanceCount - strongRefHistogram.instanceCount - softWeakRefHistogram.instanceCount val unreachableObjectsSize = histogram.bytesCount - strongRefHistogram.bytesCount - softWeakRefHistogram.bytesCount result.appendLine("Unreachable objects: ${toPaddedShortStringAsCount(unreachableObjectsCount)} ${toPaddedShortStringAsSize(unreachableObjectsSize)}") return result.toString() } enum class WalkGraphPhase { StrongReferencesNonLocalVariables, StrongReferencesLocalVariables, SoftReferences, WeakReferences, CleanerFinalizerReferences, Finished } private val config = analysisContext.config protected fun traverseInstanceGraph(progress: ProgressIndicator): String { val result = StringBuilder() val nav = analysisContext.navigator val classStore = analysisContext.classStore val sizesList = analysisContext.sizesList val visitedList = analysisContext.visitedList val refIndexList = analysisContext.refIndexList val roots = nav.createRootsIterator() nominatedInstances.clear() val nominatedClassNames = config.perClassOptions.classNames nominatedClassNames.forEach { nominatedInstances.put(classStore.get(it), IntOpenHashSet()) } progress.text2 = DiagnosticBundle.message("analyze.graph.progress.details.collect.roots") var toVisit = IntArrayList() var toVisit2 = IntArrayList() val rootsSet = IntOpenHashSet() val frameRootsSet = IntOpenHashSet() // Mark all roots to be visited, set them as their own parents while (roots.hasNext()) { val rootObject = roots.next() val rootObjectId = rootObject.id.toInt() if (rootObject.reason.javaFrame) { frameRootsSet.add(rootObjectId) } else { addIdToSetIfOrphan(rootsSet, rootObjectId) } } if (analysisContext.config.traverseOptions.includeClassesAsRoots) { // Mark all class object as to be visited, set them as their own parents classStore.forEachClass { classDefinition -> addIdToSetIfOrphan(rootsSet, classDefinition.id.toInt()) classDefinition.objectStaticFields.forEach { staticField -> addIdToSetIfOrphan(rootsSet, staticField.value.toInt()) } classDefinition.constantFields.forEach { objectId -> addIdToSetIfOrphan(rootsSet, objectId.toInt()) } } } toVisit.addAll(rootsSet) rootsSet.clear() rootsSet.trim() var leafCounter = 0 result.appendLine("Roots count: ${toVisit.size}") result.appendLine("Classes count: ${classStore.size()}") progress.text2 = DiagnosticBundle.message("analyze.graph.progress.details.traversing.instance.graph") val strongRefHistogramEntries = HashMap<ClassDefinition, HistogramVisitor.InternalHistogramEntry>() val reachableNonStrongHistogramEntries = HashMap<ClassDefinition, HistogramVisitor.InternalHistogramEntry>() val softReferenceIdToParentMap = Int2IntOpenHashMap() val weakReferenceIdToParentMap = Int2IntOpenHashMap() var visitedInstancesCount = 0 val stopwatch = Stopwatch.createStarted() val references = LongArrayList() var visitedCount = 0 var strongRefVisitedCount = 0 var softWeakVisitedCount = 0 var finalizableBytes = 0L var softBytes = 0L var weakBytes = 0L var phase = WalkGraphPhase.StrongReferencesNonLocalVariables // initial state val cleanerObjects = IntArrayList() val sunMiscCleanerClass = classStore.getClassIfExists("sun.misc.Cleaner") val finalizerClass = classStore.getClassIfExists("java.lang.ref.Finalizer") val onlyStrongReferences = config.traverseOptions.onlyStrongReferences while (!toVisit.isEmpty) { for (i in 0 until toVisit.size) { val id = toVisit.getInt(i) nav.goTo(id.toLong(), ObjectNavigator.ReferenceResolution.ALL_REFERENCES) val currentObjectClass = nav.getClass() if ((currentObjectClass == sunMiscCleanerClass || currentObjectClass == finalizerClass) && phase < WalkGraphPhase.CleanerFinalizerReferences) { if (!onlyStrongReferences) { // Postpone visiting sun.misc.Cleaner and java.lang.ref.Finalizer objects until later phase cleanerObjects.add(id) } continue } visitedInstancesCount++ nominatedInstances[currentObjectClass]?.add(id) var isLeaf = true nav.copyReferencesTo(references) val currentObjectIsArray = currentObjectClass.isArray() if (phase < WalkGraphPhase.SoftReferences && nav.getSoftReferenceId() != 0L) { // Postpone soft references if (!onlyStrongReferences) { softReferenceIdToParentMap.put(nav.getSoftReferenceId().toInt(), id) } references[nav.getSoftWeakReferenceIndex()] = 0L } if (phase < WalkGraphPhase.WeakReferences && nav.getWeakReferenceId() != 0L) { // Postpone weak references if (!onlyStrongReferences) { weakReferenceIdToParentMap.put(nav.getWeakReferenceId().toInt(), id) } references[nav.getSoftWeakReferenceIndex()] = 0L } for (j in 0 until references.size) { val referenceId = references.getLong(j).toInt() if (addIdToListAndSetParentIfOrphan(toVisit2, referenceId, id)) { if (!currentObjectIsArray && j <= 254) { refIndexList[referenceId] = j + 1 } isLeaf = false } } visitedList[visitedCount++] = id val size = nav.getObjectSize() var sizeDivBy4 = (size + 3) / 4 if (sizeDivBy4 == 0) sizeDivBy4 = 1 sizesList[id] = sizeDivBy4 var histogramEntries: HashMap<ClassDefinition, HistogramVisitor.InternalHistogramEntry> if (phase == WalkGraphPhase.StrongReferencesNonLocalVariables || phase == WalkGraphPhase.StrongReferencesLocalVariables) { histogramEntries = strongRefHistogramEntries if (isLeaf) { leafCounter++ } strongRefVisitedCount++ } else { histogramEntries = reachableNonStrongHistogramEntries when (phase) { WalkGraphPhase.CleanerFinalizerReferences -> { finalizableBytes += size } WalkGraphPhase.SoftReferences -> { softBytes += size } else -> { assert(phase == WalkGraphPhase.WeakReferences) weakBytes += size } } softWeakVisitedCount++ } histogramEntries.getOrPut(currentObjectClass) { HistogramVisitor.InternalHistogramEntry(currentObjectClass) }.addInstance(size.toLong()) } progress.fraction = (1.0 * visitedInstancesCount / nav.instanceCount) toVisit.clear() val tmp = toVisit toVisit = toVisit2 toVisit2 = tmp // Handle state transitions while (toVisit.size == 0 && phase != WalkGraphPhase.Finished) { // Next state phase = WalkGraphPhase.values()[phase.ordinal + 1] when (phase) { WalkGraphPhase.StrongReferencesLocalVariables -> frameRootsSet.forEach { id -> addIdToListAndSetParentIfOrphan(toVisit, id, id) } WalkGraphPhase.CleanerFinalizerReferences -> { toVisit.addAll(cleanerObjects) cleanerObjects.clear() } WalkGraphPhase.SoftReferences -> { for (entry in softReferenceIdToParentMap.int2IntEntrySet().fastIterator()) { addIdToListAndSetParentIfOrphan(toVisit, entry.intKey, entry.intValue) } // No need to store the list anymore softReferenceIdToParentMap.clear() softReferenceIdToParentMap.trim() } WalkGraphPhase.WeakReferences -> { for (entry in weakReferenceIdToParentMap.int2IntEntrySet().fastIterator()) { addIdToListAndSetParentIfOrphan(toVisit, entry.intKey, entry.intValue) } // No need to store the list anymore weakReferenceIdToParentMap.clear() weakReferenceIdToParentMap.trim() } else -> Unit // No work for other state transitions } } } assert(cleanerObjects.isEmpty) assert(softReferenceIdToParentMap.isEmpty()) assert(weakReferenceIdToParentMap.isEmpty()) result.appendLine("Finalizable size: ${toShortStringAsSize(finalizableBytes)}") result.appendLine("Soft-reachable size: ${toShortStringAsSize(softBytes)}") result.appendLine("Weak-reachable size: ${toShortStringAsSize(weakBytes)}") strongRefHistogram = Histogram( strongRefHistogramEntries .values .map { it.asHistogramEntry() } .sortedByDescending { it.totalInstances }, strongRefVisitedCount.toLong()) softWeakRefHistogram = Histogram( reachableNonStrongHistogramEntries .values .map { it.asHistogramEntry() } .sortedByDescending { it.totalInstances }, softWeakVisitedCount.toLong()) val stopwatchUpdateSizes = Stopwatch.createStarted() // Update sizes for non-leaves var index = visitedCount - 1 while (index >= 0) { val id = visitedList[index] val parentId = parentList[id] if (id != parentId) { sizesList[parentId] += sizesList[id] } index-- } stopwatchUpdateSizes.stop() if (config.metaInfoOptions.include) { result.appendLine("Analysis completed! Visited instances: $visitedInstancesCount, time: $stopwatch") result.appendLine("Update sizes time: $stopwatchUpdateSizes") result.appendLine("Leaves found: $leafCounter") } return result.toString() } /** * Adds object id to the list, only if the object does not have a parent object. Object will * also have a parent assigned. * For root objects, parentId should point back to the object making the object its own parent. * For other cases parentId can be provided. * * @return true if object was added to the list. */ private fun addIdToListAndSetParentIfOrphan(list: IntList, id: Int, parentId: Int = id): Boolean { if (id != 0 && getParentIdForObjectId(id.toLong()) == 0L) { setParentForObjectId(id.toLong(), parentId.toLong()) list.add(id) return true } return false } /** * Adds object id to the set, only if the object does not have a parent object and is not yet in the set. * Object will also have a parent assigned. * For root objects, parentId should point back to the object making the object its own parent. * For other cases parentId can be provided. * * @return true if object was added to the set. */ private fun addIdToSetIfOrphan(set: IntSet, id: Int, parentId: Int = id): Boolean { if (id != 0 && getParentIdForObjectId(id.toLong()) == 0L && set.add(id)) { setParentForObjectId(id.toLong(), parentId.toLong()) return true } return false } private fun getAndClearStrongRefHistogram(): Histogram { val result = strongRefHistogram strongRefHistogram = null return result ?: throw IllegalStateException("Graph not analyzed.") } private fun getAndClearSoftWeakHistogram(): Histogram { val result = softWeakRefHistogram softWeakRefHistogram = null return result ?: throw IllegalStateException("Graph not analyzed.") } }
apache-2.0
4f27ceaa7d38ec75e8c478f56413e6ff
37.023656
154
0.701035
4.599636
false
false
false
false
gen1nya/lfg_player-android
app/src/main/java/ru/ltcnt/lfg_player_android/presentation/navigation/MainRouter.kt
1
1573
package ru.ltcnt.lfg_player_android.presentation.navigation import ru.terrakok.cicerone.BaseRouter import ru.terrakok.cicerone.commands.* /** * Author 1 * Since 21.10.2017. */ class MainRouter: BaseRouter() { fun openDrawer(){ executeCommand(OpenDrawer()) } fun enableDrawer(){ executeCommand(LockDrawer(true)) } fun disableDrawer(){ executeCommand(LockDrawer(false)) } fun navigateWithReplace(screenKey: String, data: Any? = null) { executeCommand(NavigateWithReplace(screenKey, data)) } fun navigateTo(screenKey: String, data: Any? = null) { executeCommand(Forward(screenKey, data)) } fun newScreenChain(screenKey: String, data: Any? = null) { executeCommand(BackTo(null)) executeCommand(Forward(screenKey, data)) } fun newRootScreen(screenKey: String, data: Any? = null) { executeCommand(BackTo(null)) executeCommand(Replace(screenKey, data)) } fun replaceScreen(screenKey: String, data: Any? = null) { executeCommand(Replace(screenKey, data)) } fun backTo(screenKey: String?) { executeCommand(BackTo(screenKey)) } fun finishChain() { executeCommand(BackTo(null)) executeCommand(Back()) } fun exit() { executeCommand(Back()) } fun exitWithMessage(message: String) { executeCommand(Back()) executeCommand(SystemMessage(message)) } fun showSystemMessage(message: String) { executeCommand(SystemMessage(message)) } }
apache-2.0
18ba51c07d76f96ddadf940bd53b8a24
22.848485
67
0.6459
4.286104
false
false
false
false
alibaba/p3c
p3c-pmd/src/main/kotlin/com/alibaba/p3c/pmd/lang/java/rule/concurrent/LockShouldWithTryFinallyRule.kt
1
4558
package com.alibaba.p3c.pmd.lang.java.rule.concurrent import com.alibaba.p3c.pmd.lang.java.rule.AbstractAliRule import com.alibaba.p3c.pmd.lang.java.rule.util.NodeUtils.LOCK_INTERRUPTIBLY_NAME import com.alibaba.p3c.pmd.lang.java.rule.util.NodeUtils.LOCK_NAME import com.alibaba.p3c.pmd.lang.java.rule.util.NodeUtils.UN_LOCK_NAME import net.sourceforge.pmd.lang.java.ast.ASTBlock import net.sourceforge.pmd.lang.java.ast.ASTBlockStatement import net.sourceforge.pmd.lang.java.ast.ASTFinallyStatement import net.sourceforge.pmd.lang.java.ast.ASTName import net.sourceforge.pmd.lang.java.ast.ASTStatementExpression import net.sourceforge.pmd.lang.java.ast.ASTTryStatement import net.sourceforge.pmd.lang.java.ast.AbstractJavaNode import java.util.concurrent.locks.Lock /** * @author caikang * @date 2019/09/29 */ open class LockShouldWithTryFinallyRule : AbstractAliRule() { override fun visit(node: ASTBlock, data: Any): Any? { checkBlock(node, data) return super.visit(node, data) } private fun checkBlock(block: ASTBlock, data: Any) { val statements = block.findChildrenOfType(ASTBlockStatement::class.java) if (statements.isNullOrEmpty()) { return } var lockExpression: ASTStatementExpression? = null for (statement in statements) { if (lockExpression != null) { // check try finally val tryStatement = findNodeByXpath( statement, XPATH_TRY_STATEMENT, ASTTryStatement::class.java ) if (!checkTryStatement(tryStatement)) { addLockViolation(data, lockExpression) } lockExpression = null continue } // find lock expression val expression = findNodeByXpath( statement, XPATH_LOCK_STATEMENT, ASTStatementExpression::class.java ) ?: continue if (!expression.isLock) { continue } val astName = expression.getFirstDescendantOfType(ASTName::class.java) val lockMethod = astName?.image?.let { it.endsWith(".$LOCK_NAME") || it.endsWith(".$LOCK_INTERRUPTIBLY_NAME") } ?: false if (!lockMethod) { continue } lockExpression = expression } lockExpression?.let { addLockViolation(data, it) } } private fun addLockViolation(data: Any, lockExpression: ASTStatementExpression) { addViolationWithMessage( data, lockExpression, "java.concurrent.LockShouldWithTryFinallyRule.violation.msg", arrayOf<Any>(getExpressName(lockExpression)) ) } private fun checkTryStatement(tryStatement: ASTTryStatement?): Boolean { if (tryStatement == null) { return false } val finallyStatement = tryStatement.getFirstChildOfType(ASTFinallyStatement::class.java) ?: return false val statementExpression = findNodeByXpath( finallyStatement, XPATH_UNLOCK_STATEMENT, ASTStatementExpression::class.java ) ?: return false if (!statementExpression.isLock) { return false } val astName = statementExpression.getFirstDescendantOfType(ASTName::class.java) ?: return false return astName.image?.endsWith(".$UN_LOCK_NAME") ?: false } private fun <T> findNodeByXpath(statement: AbstractJavaNode, xpath: String, clazz: Class<T>): T? { val nodes = statement.findChildNodesWithXPath(xpath) if (nodes == null || nodes.isEmpty()) { return null } val node = nodes[0] return if (!clazz.isAssignableFrom(node.javaClass)) { null } else clazz.cast(node) } private fun getExpressName(statementExpression: ASTStatementExpression): String { val name = statementExpression.getFirstDescendantOfType(ASTName::class.java) return name.image } companion object { private const val XPATH_LOCK_STATEMENT = "Statement/StatementExpression" private const val XPATH_UNLOCK_STATEMENT = "Block/BlockStatement/Statement/StatementExpression" private const val XPATH_TRY_STATEMENT = "Statement/TryStatement" } private val ASTStatementExpression?.isLock: Boolean get() = this?.type?.let { Lock::class.java.isAssignableFrom(it) } ?: false }
apache-2.0
c3388a9c864802ac9916f560ff9a7520
36.983333
112
0.639754
4.438169
false
false
false
false
anitawoodruff/habitica-android
Habitica/src/main/java/com/habitrpg/android/habitica/ui/fragments/tasks/RewardsRecyclerviewFragment.kt
1
5690
package com.habitrpg.android.habitica.ui.fragments.tasks import android.app.Activity import android.content.Context import android.content.Intent import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.core.content.ContextCompat import androidx.recyclerview.widget.GridLayoutManager import androidx.recyclerview.widget.LinearLayoutManager import com.habitrpg.android.habitica.R import com.habitrpg.android.habitica.extensions.subscribeWithErrorHandler import com.habitrpg.android.habitica.helpers.RxErrorHandler import com.habitrpg.android.habitica.models.shops.ShopItem import com.habitrpg.android.habitica.models.user.User import com.habitrpg.android.habitica.ui.activities.MainActivity import com.habitrpg.android.habitica.ui.activities.SkillMemberActivity import com.habitrpg.android.habitica.ui.adapter.tasks.RewardsRecyclerViewAdapter import com.habitrpg.android.habitica.ui.helpers.SafeDefaultItemAnimator import com.habitrpg.android.habitica.ui.views.HabiticaSnackbar import io.reactivex.functions.Consumer import kotlinx.android.synthetic.main.fragment_refresh_recyclerview.* import java.util.* class RewardsRecyclerviewFragment : TaskRecyclerViewFragment() { private var selectedCard: ShopItem? = null override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { compositeSubscription.add(inventoryRepository.retrieveInAppRewards().subscribe(Consumer { }, RxErrorHandler.handleEmptyError())) return super.onCreateView(inflater, container, savedInstanceState) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) (layoutManager as? GridLayoutManager)?.spanSizeLookup = object : GridLayoutManager.SpanSizeLookup() { override fun getSpanSize(position: Int): Int { return if (recyclerAdapter?.getItemViewType(position) ?: 0 < 2) { (layoutManager as? GridLayoutManager)?.spanCount ?: 1 } else { 1 } } } view.post { setGridSpanCount(view.width) } context?.let { recyclerView.setBackgroundColor(ContextCompat.getColor(it, R.color.white)) } recyclerView.itemAnimator = SafeDefaultItemAnimator() compositeSubscription.add(inventoryRepository.getInAppRewards().subscribe(Consumer { (recyclerAdapter as? RewardsRecyclerViewAdapter)?.updateItemRewards(it) }, RxErrorHandler.handleEmptyError())) (recyclerAdapter as? RewardsRecyclerViewAdapter)?.purchaseCardEvents?.subscribe(Consumer { selectedCard = it val intent = Intent(activity, SkillMemberActivity::class.java) startActivityForResult(intent, 11) }, RxErrorHandler.handleEmptyError())?.let { compositeSubscription.add(it) } } override fun getLayoutManager(context: Context?): LinearLayoutManager { return GridLayoutManager(context, 4) } override fun onRefresh() { refreshLayout.isRefreshing = true compositeSubscription.add(userRepository.retrieveUser(true, true) .flatMap<List<ShopItem>> { inventoryRepository.retrieveInAppRewards() } .doOnTerminate { refreshLayout?.isRefreshing = false }.subscribe(Consumer { }, RxErrorHandler.handleEmptyError())) } private fun setGridSpanCount(width: Int) { var spanCount = 0 if (context != null && context?.resources != null) { val itemWidth: Float = context?.resources?.getDimension(R.dimen.reward_width) ?: 0f spanCount = (width / itemWidth).toInt() } if (spanCount == 0) { spanCount = 1 } (layoutManager as? GridLayoutManager)?.spanCount = spanCount } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) if (data != null) { when (requestCode) { 11 -> { if (resultCode == Activity.RESULT_OK) { userRepository.useSkill(user, selectedCard?.key ?: "", "member", data.getStringExtra("member_id")) .subscribeWithErrorHandler(Consumer { val activity = (activity as? MainActivity) ?: return@Consumer HabiticaSnackbar.showSnackbar(activity.snackbarContainer, context?.getString(R.string.sent_card, selectedCard?.text), HabiticaSnackbar.SnackbarDisplayType.BLUE) }) } } } } } companion object { fun newInstance(context: Context?, user: User?, classType: String): RewardsRecyclerviewFragment { val fragment = RewardsRecyclerviewFragment() fragment.retainInstance = true fragment.user = user fragment.classType = classType if (context != null) { fragment.tutorialStepIdentifier = "rewards" fragment.tutorialTexts = ArrayList(listOf(context.getString(R.string.tutorial_rewards_1), context.getString(R.string.tutorial_rewards_2))) } fragment.tutorialCanBeDeferred = false return fragment } } }
gpl-3.0
b2728db6a6c24134c5510a4891a4820e
42.106061
154
0.650439
5.52964
false
false
false
false
anitawoodruff/habitica-android
Habitica/src/main/java/com/habitrpg/android/habitica/ui/activities/GroupInviteActivity.kt
1
5859
package com.habitrpg.android.habitica.ui.activities import android.app.Activity import android.content.Intent import android.os.Bundle import android.view.Menu import android.view.MenuItem import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.fragment.app.FragmentPagerAdapter import androidx.viewpager.widget.ViewPager import com.google.android.material.tabs.TabLayout import com.habitrpg.android.habitica.R import com.habitrpg.android.habitica.components.UserComponent import com.habitrpg.android.habitica.data.SocialRepository import com.habitrpg.android.habitica.data.UserRepository import com.habitrpg.android.habitica.extensions.runDelayed import com.habitrpg.android.habitica.helpers.RxErrorHandler import com.habitrpg.android.habitica.models.user.User import com.habitrpg.android.habitica.modules.AppModule import com.habitrpg.android.habitica.ui.fragments.social.party.PartyInviteFragment import com.habitrpg.android.habitica.ui.helpers.bindView import com.habitrpg.android.habitica.ui.helpers.dismissKeyboard import com.habitrpg.android.habitica.ui.views.HabiticaSnackbar import com.habitrpg.android.habitica.ui.views.HabiticaSnackbar.Companion.showSnackbar import io.reactivex.functions.Consumer import kotlinx.android.synthetic.main.activity_prefs.* import java.util.* import java.util.concurrent.TimeUnit import javax.inject.Inject import javax.inject.Named class GroupInviteActivity : BaseActivity() { @field:[Inject Named(AppModule.NAMED_USER_ID)] lateinit var userId: String @Inject lateinit var socialRepository: SocialRepository @Inject lateinit var userRepository: UserRepository internal val tabLayout: TabLayout by bindView(R.id.tab_layout) internal val viewPager: ViewPager by bindView(R.id.viewPager) private val snackbarView: ViewGroup by bindView(R.id.snackbar_view) internal var fragments: MutableList<PartyInviteFragment> = ArrayList() private var userIdToInvite: String? = null override fun getLayoutResId(): Int { return R.layout.activity_party_invite } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setupToolbar(toolbar) viewPager.currentItem = 0 supportActionBar?.title = null setViewPagerAdapter() } override fun injectActivity(component: UserComponent?) { component?.inject(this) } override fun onCreateOptionsMenu(menu: Menu): Boolean { // Inflate the menu; this adds items to the action bar if it is present. menuInflater.inflate(R.menu.menu_party_invite, menu) return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { return when (item.itemId) { R.id.action_send_invites -> { setResult(Activity.RESULT_OK, createResultIntent()) dismissKeyboard() if (fragments.size > viewPager.currentItem && fragments[viewPager.currentItem].values.isNotEmpty()) { showSnackbar(snackbarView, "Invite Sent!", HabiticaSnackbar.SnackbarDisplayType.SUCCESS) runDelayed(1, TimeUnit.SECONDS, this::finish) } else { finish() } true } android.R.id.home -> { onBackPressed() true } else -> super.onOptionsItemSelected(item) } } private fun createResultIntent(): Intent { val intent = Intent() if (fragments.size == 0) return intent val fragment = fragments[viewPager.currentItem] if (viewPager.currentItem == 1) { intent.putExtra(IS_EMAIL_KEY, true) intent.putExtra(EMAILS_KEY, fragment.values) } else { intent.putExtra(IS_EMAIL_KEY, false) intent.putExtra(USER_IDS_KEY, fragment.values) } return intent } private fun setViewPagerAdapter() { val fragmentManager = supportFragmentManager viewPager.adapter = object : FragmentPagerAdapter(fragmentManager) { override fun getItem(position: Int): Fragment { val fragment = PartyInviteFragment() fragment.isEmailInvite = position == 1 if (fragments.size > position) { fragments[position] = fragment } else { fragments.add(fragment) } return fragment } override fun getCount(): Int { return 2 } override fun getPageTitle(position: Int): CharSequence? { return when (position) { 0 -> getString(R.string.invite_existing_users) 1 -> getString(R.string.by_email) else -> "" } } } tabLayout.setupWithViewPager(viewPager) } private fun handleUserReceived(user: User) { if (this.userIdToInvite == null) { return } val inviteData = HashMap<String, Any>() val invites = ArrayList<String>() userIdToInvite?.let { invites.add(it) } inviteData["uuids"] = invites compositeSubscription.add(this.socialRepository.inviteToGroup(user.party?.id ?: "", inviteData) .subscribe(Consumer { }, RxErrorHandler.handleEmptyError())) } companion object { const val RESULT_SEND_INVITES = 100 const val USER_IDS_KEY = "userIDs" const val IS_EMAIL_KEY = "isEmail" const val EMAILS_KEY = "emails" } }
gpl-3.0
2f2ed660307e5de1a6eb49a248f6bb7d
33.083832
117
0.633897
4.898829
false
false
false
false
zdary/intellij-community
plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/ui/util/MigLayoutExtensions.kt
1
868
@file:Suppress("MagicNumber") // Swing APIs... package com.jetbrains.packagesearch.intellij.plugin.ui.util import net.miginfocom.layout.LC internal fun LC.noInsets() = insets("0") internal fun LC.scaledInsets( @ScalableUnits top: Int = 0, @ScalableUnits left: Int = 0, @ScalableUnits bottom: Int = 0, @ScalableUnits right: Int = 0 ) = insets(top.scaled(), left.scaled(), bottom.scaled(), right.scaled()) internal fun LC.insets( @ScaledPixels top: Int = 0, @ScaledPixels left: Int = 0, @ScaledPixels bottom: Int = 0, @ScaledPixels right: Int = 0 ) = insets(top.toString(), left.toString(), bottom.toString(), right.toString()) internal fun LC.skipInvisibleComponents() = hideMode(3) internal fun LC.gridGap(@ScalableUnits hSize: Int = 0, @ScalableUnits vSize: Int = 0) = gridGap(hSize.scaledAsString(), vSize.scaledAsString())
apache-2.0
96c18642ba4f984aafd871b55e87b2c9
33.72
87
0.701613
3.586777
false
false
false
false
siosio/intellij-community
plugins/kotlin/common/src/org/jetbrains/kotlin/idea/analysis/AnalyzerUtil.kt
2
4976
// 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.analysis import org.jetbrains.kotlin.idea.FrontendInternals import org.jetbrains.kotlin.idea.caches.resolve.getResolutionFacade import org.jetbrains.kotlin.idea.resolve.ResolutionFacade import org.jetbrains.kotlin.idea.resolve.frontendService import org.jetbrains.kotlin.idea.util.getResolutionScope import org.jetbrains.kotlin.psi.KtExpression import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.BindingTrace import org.jetbrains.kotlin.resolve.BindingTraceContext import org.jetbrains.kotlin.resolve.DelegatingBindingTrace import org.jetbrains.kotlin.resolve.bindingContextUtil.getDataFlowInfoBefore import org.jetbrains.kotlin.resolve.bindingContextUtil.isUsedAsStatement import org.jetbrains.kotlin.resolve.calls.components.InferenceSession import org.jetbrains.kotlin.resolve.calls.context.ContextDependency import org.jetbrains.kotlin.resolve.calls.smartcasts.DataFlowInfo import org.jetbrains.kotlin.resolve.scopes.LexicalScope import org.jetbrains.kotlin.types.KotlinType import org.jetbrains.kotlin.types.TypeUtils import org.jetbrains.kotlin.types.expressions.ExpressionTypingServices import org.jetbrains.kotlin.types.expressions.KotlinTypeInfo import org.jetbrains.kotlin.types.expressions.PreliminaryDeclarationVisitor @JvmOverloads @OptIn(FrontendInternals::class) fun KtExpression.computeTypeInfoInContext( scope: LexicalScope, contextExpression: KtExpression = this, trace: BindingTrace = BindingTraceContext(), dataFlowInfo: DataFlowInfo = DataFlowInfo.EMPTY, expectedType: KotlinType = TypeUtils.NO_EXPECTED_TYPE, isStatement: Boolean = false, contextDependency: ContextDependency = ContextDependency.INDEPENDENT, expressionTypingServices: ExpressionTypingServices = contextExpression.getResolutionFacade().frontendService<ExpressionTypingServices>() ): KotlinTypeInfo { PreliminaryDeclarationVisitor.createForExpression(this, trace, expressionTypingServices.languageVersionSettings) return expressionTypingServices.getTypeInfo( scope, this, expectedType, dataFlowInfo, InferenceSession.default, trace, isStatement, contextExpression, contextDependency ) } @JvmOverloads @OptIn(FrontendInternals::class) fun KtExpression.analyzeInContext( scope: LexicalScope, contextExpression: KtExpression = this, trace: BindingTrace = BindingTraceContext(), dataFlowInfo: DataFlowInfo = DataFlowInfo.EMPTY, expectedType: KotlinType = TypeUtils.NO_EXPECTED_TYPE, isStatement: Boolean = false, contextDependency: ContextDependency = ContextDependency.INDEPENDENT, expressionTypingServices: ExpressionTypingServices = contextExpression.getResolutionFacade().frontendService<ExpressionTypingServices>() ): BindingContext { computeTypeInfoInContext( scope, contextExpression, trace, dataFlowInfo, expectedType, isStatement, contextDependency, expressionTypingServices ) return trace.bindingContext } @JvmOverloads fun KtExpression.computeTypeInContext( scope: LexicalScope, contextExpression: KtExpression = this, trace: BindingTrace = BindingTraceContext(), dataFlowInfo: DataFlowInfo = DataFlowInfo.EMPTY, expectedType: KotlinType = TypeUtils.NO_EXPECTED_TYPE ): KotlinType? = computeTypeInfoInContext(scope, contextExpression, trace, dataFlowInfo, expectedType).type @JvmOverloads fun KtExpression.analyzeAsReplacement( expressionToBeReplaced: KtExpression, bindingContext: BindingContext, scope: LexicalScope, trace: BindingTrace = DelegatingBindingTrace(bindingContext, "Temporary trace for analyzeAsReplacement()"), contextDependency: ContextDependency = ContextDependency.INDEPENDENT ): BindingContext = analyzeInContext( scope, expressionToBeReplaced, dataFlowInfo = bindingContext.getDataFlowInfoBefore(expressionToBeReplaced), expectedType = bindingContext[BindingContext.EXPECTED_EXPRESSION_TYPE, expressionToBeReplaced] ?: TypeUtils.NO_EXPECTED_TYPE, isStatement = expressionToBeReplaced.isUsedAsStatement(bindingContext), trace = trace, contextDependency = contextDependency ) @JvmOverloads fun KtExpression.analyzeAsReplacement( expressionToBeReplaced: KtExpression, bindingContext: BindingContext, resolutionFacade: ResolutionFacade = expressionToBeReplaced.getResolutionFacade(), trace: BindingTrace = DelegatingBindingTrace(bindingContext, "Temporary trace for analyzeAsReplacement()"), contextDependency: ContextDependency = ContextDependency.INDEPENDENT ): BindingContext { val scope = expressionToBeReplaced.getResolutionScope(bindingContext, resolutionFacade) return analyzeAsReplacement(expressionToBeReplaced, bindingContext, scope, trace, contextDependency) }
apache-2.0
09846a059fdf7f07ea3309d6bee1f024
45.504673
158
0.815113
5.498343
false
false
false
false
siosio/intellij-community
plugins/kotlin/completion/src/org/jetbrains/kotlin/idea/completion/BasicCompletionSession.kt
1
43042
// 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.completion import com.intellij.codeInsight.CodeInsightSettings import com.intellij.codeInsight.completion.* import com.intellij.codeInsight.completion.impl.BetterPrefixMatcher import com.intellij.codeInsight.lookup.LookupElement import com.intellij.codeInsight.lookup.LookupElementBuilder import com.intellij.codeInsight.lookup.LookupElementDecorator import com.intellij.codeInsight.lookup.LookupElementPresentation import com.intellij.codeInsight.template.TemplateManager import com.intellij.patterns.PatternCondition import com.intellij.patterns.StandardPatterns import com.intellij.psi.* import com.intellij.psi.impl.source.tree.LeafPsiElement import com.intellij.psi.search.GlobalSearchScope import com.intellij.util.ProcessingContext import org.jetbrains.kotlin.descriptors.* import org.jetbrains.kotlin.idea.analysis.analyzeInContext import org.jetbrains.kotlin.idea.caches.resolve.util.resolveToDescriptor import org.jetbrains.kotlin.idea.codeInsight.ReferenceVariantsHelper import org.jetbrains.kotlin.idea.completion.handlers.createKeywordConstructLookupElement import org.jetbrains.kotlin.idea.completion.smart.ExpectedInfoMatch import org.jetbrains.kotlin.idea.completion.smart.SMART_COMPLETION_ITEM_PRIORITY_KEY import org.jetbrains.kotlin.idea.completion.smart.SmartCompletion import org.jetbrains.kotlin.idea.completion.smart.SmartCompletionItemPriority import org.jetbrains.kotlin.idea.core.ExpectedInfo import org.jetbrains.kotlin.idea.core.NotPropertiesService import org.jetbrains.kotlin.idea.core.completion.DeclarationLookupObject import org.jetbrains.kotlin.idea.imports.importableFqName import org.jetbrains.kotlin.idea.project.TargetPlatformDetector import org.jetbrains.kotlin.idea.references.KtSimpleNameReference.ShorteningMode.FORCED_SHORTENING import org.jetbrains.kotlin.idea.references.mainReference import org.jetbrains.kotlin.idea.stubindex.PackageIndexUtil import org.jetbrains.kotlin.idea.util.CallType import org.jetbrains.kotlin.idea.util.CallTypeAndReceiver import org.jetbrains.kotlin.idea.util.getResolutionScope import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.load.java.descriptors.JavaClassDescriptor import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.platform.jvm.isJvm import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.* import org.jetbrains.kotlin.renderer.render import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.descriptorUtil.* import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.resolve.sam.SamConstructorDescriptor import org.jetbrains.kotlin.resolve.sam.SamConstructorDescriptorKindExclude import org.jetbrains.kotlin.resolve.scopes.DescriptorKindExclude import org.jetbrains.kotlin.resolve.scopes.DescriptorKindFilter import org.jetbrains.kotlin.resolve.scopes.ExplicitImportsScope import org.jetbrains.kotlin.resolve.scopes.utils.addImportingScope import org.jetbrains.kotlin.util.kind import org.jetbrains.kotlin.util.supertypesWithAny import org.jetbrains.kotlin.utils.addIfNotNull import org.jetbrains.kotlin.utils.addToStdlib.firstIsInstanceOrNull import org.jetbrains.kotlin.utils.addToStdlib.safeAs class BasicCompletionSession( configuration: CompletionSessionConfiguration, parameters: CompletionParameters, resultSet: CompletionResultSet, ) : CompletionSession(configuration, parameters, resultSet) { private interface CompletionKind { val descriptorKindFilter: DescriptorKindFilter? fun doComplete() fun shouldDisableAutoPopup() = false fun addWeighers(sorter: CompletionSorter) = sorter } private val completionKind by lazy { detectCompletionKind() } override val descriptorKindFilter: DescriptorKindFilter? get() = completionKind.descriptorKindFilter private val smartCompletion = expression?.let { SmartCompletion( expression = it, resolutionFacade = resolutionFacade, bindingContext = bindingContext, moduleDescriptor = moduleDescriptor, visibilityFilter = isVisibleFilter, indicesHelper = indicesHelper(false), prefixMatcher = prefixMatcher, inheritorSearchScope = GlobalSearchScope.EMPTY_SCOPE, toFromOriginalFileMapper = toFromOriginalFileMapper, callTypeAndReceiver = callTypeAndReceiver, isJvmModule = isJvmModule, forBasicCompletion = true, ) } override val expectedInfos: Collection<ExpectedInfo> get() = smartCompletion?.expectedInfos ?: emptyList() private fun detectCompletionKind(): CompletionKind { if (nameExpression == null) { return if ((position.parent as? KtNamedDeclaration)?.nameIdentifier == position) DECLARATION_NAME else KEYWORDS_ONLY } if (OPERATOR_NAME.isApplicable()) { return OPERATOR_NAME } if (NamedArgumentCompletion.isOnlyNamedArgumentExpected(nameExpression, resolutionFacade)) { return NAMED_ARGUMENTS_ONLY } if (nameExpression.getStrictParentOfType<KtSuperExpression>() != null) { return SUPER_QUALIFIER } return ALL } fun shouldDisableAutoPopup(): Boolean = completionKind.shouldDisableAutoPopup() override fun shouldCompleteTopLevelCallablesFromIndex() = super.shouldCompleteTopLevelCallablesFromIndex() && prefix.isNotEmpty() override fun doComplete() { assert(parameters.completionType == CompletionType.BASIC) if (parameters.isAutoPopup) { collector.addLookupElementPostProcessor { lookupElement -> lookupElement.putUserData(LookupCancelService.AUTO_POPUP_AT, position.startOffset) lookupElement } if (isInFunctionLiteralStart(position)) { collector.addLookupElementPostProcessor { lookupElement -> lookupElement.putUserData(KotlinCompletionCharFilter.SUPPRESS_ITEM_SELECTION_BY_CHARS_ON_TYPING, Unit) lookupElement } } } collector.addLookupElementPostProcessor { lookupElement -> position.argList?.let { lookupElement.argList = it } lookupElement } completionKind.doComplete() } private fun isInFunctionLiteralStart(position: PsiElement): Boolean { var prev = position.prevLeaf { it !is PsiWhiteSpace && it !is PsiComment } if (prev?.node?.elementType == KtTokens.LPAR) { prev = prev?.prevLeaf { it !is PsiWhiteSpace && it !is PsiComment } } if (prev?.node?.elementType != KtTokens.LBRACE) return false val functionLiteral = prev!!.parent as? KtFunctionLiteral ?: return false return functionLiteral.lBrace == prev } override fun createSorter(): CompletionSorter { var sorter = super.createSorter() if (smartCompletion != null) { val smartCompletionInBasicWeigher = SmartCompletionInBasicWeigher( smartCompletion, callTypeAndReceiver, resolutionFacade, bindingContext, ) sorter = sorter.weighBefore( KindWeigher.toString(), smartCompletionInBasicWeigher, CallableReferenceWeigher(callTypeAndReceiver.callType), ) } sorter = completionKind.addWeighers(sorter) return sorter } private val ALL = object : CompletionKind { override val descriptorKindFilter: DescriptorKindFilter by lazy { callTypeAndReceiver.callType.descriptorKindFilter.let { filter -> filter.takeIf { it.kindMask.and(DescriptorKindFilter.PACKAGES_MASK) != 0 } ?.exclude(DescriptorKindExclude.TopLevelPackages) ?: filter } } override fun shouldDisableAutoPopup(): Boolean = isStartOfExtensionReceiverFor() is KtProperty && wasAutopopupRecentlyCancelled(parameters) override fun doComplete() { val declaration = isStartOfExtensionReceiverFor() if (declaration != null) { completeDeclarationNameFromUnresolvedOrOverride(declaration) if (declaration is KtProperty) { // we want to insert type only if the property is lateinit, // because lateinit var cannot have its type deduced from initializer completeParameterOrVarNameAndType(withType = declaration.hasModifier(KtTokens.LATEINIT_KEYWORD)) } // no auto-popup on typing after "val", "var" and "fun" because it's likely the name of the declaration which is being typed by user if (parameters.invocationCount == 0 && ( // suppressOtherCompletion declaration !is KtNamedFunction && declaration !is KtProperty || prefixMatcher.prefix.let { it.isEmpty() || it[0].isLowerCase() /* function name usually starts with lower case letter */ } ) ) { return } } fun completeWithSmartCompletion(lookupElementFactory: LookupElementFactory) { if (smartCompletion != null) { val (additionalItems, @Suppress("UNUSED_VARIABLE") inheritanceSearcher) = smartCompletion.additionalItems( lookupElementFactory ) // all additional items should have SMART_COMPLETION_ITEM_PRIORITY_KEY to be recognized by SmartCompletionInBasicWeigher for (item in additionalItems) { if (item.getUserData(SMART_COMPLETION_ITEM_PRIORITY_KEY) == null) { item.putUserData(SMART_COMPLETION_ITEM_PRIORITY_KEY, SmartCompletionItemPriority.DEFAULT) } } collector.addElements(additionalItems) } } withCollectRequiredContextVariableTypes { lookupFactory -> DslMembersCompletion( prefixMatcher, lookupFactory, receiverTypes, collector, indicesHelper(true), callTypeAndReceiver, ).completeDslFunctions() } KEYWORDS_ONLY.doComplete() val contextVariableTypesForSmartCompletion = withCollectRequiredContextVariableTypes(::completeWithSmartCompletion) val contextVariableTypesForReferenceVariants = withCollectRequiredContextVariableTypes { lookupElementFactory -> when { prefix.isEmpty() || callTypeAndReceiver.receiver != null || CodeInsightSettings.getInstance().completionCaseSensitive == CodeInsightSettings.NONE -> { addReferenceVariantElements(lookupElementFactory, descriptorKindFilter) } prefix[0].isLowerCase() -> { addReferenceVariantElements(lookupElementFactory, USUALLY_START_LOWER_CASE.intersect(descriptorKindFilter)) addReferenceVariantElements(lookupElementFactory, USUALLY_START_UPPER_CASE.intersect(descriptorKindFilter)) } else -> { addReferenceVariantElements(lookupElementFactory, USUALLY_START_UPPER_CASE.intersect(descriptorKindFilter)) addReferenceVariantElements(lookupElementFactory, USUALLY_START_LOWER_CASE.intersect(descriptorKindFilter)) } } referenceVariantsCollector!!.collectingFinished() } // getting root packages from scope is very slow so we do this in alternative way if (callTypeAndReceiver.receiver == null && callTypeAndReceiver.callType.descriptorKindFilter.kindMask.and(DescriptorKindFilter.PACKAGES_MASK) != 0 ) { //TODO: move this code somewhere else? val packageNames = PackageIndexUtil.getSubPackageFqNames(FqName.ROOT, searchScope, project, prefixMatcher.asNameFilter()) .toMutableSet() if (TargetPlatformDetector.getPlatform(parameters.originalFile as KtFile).isJvm()) { JavaPsiFacade.getInstance(project).findPackage("")?.getSubPackages(searchScope)?.forEach { psiPackage -> val name = psiPackage.name if (Name.isValidIdentifier(name!!)) { packageNames.add(FqName(name)) } } } packageNames.forEach { collector.addElement(basicLookupElementFactory.createLookupElementForPackage(it)) } } flushToResultSet() NamedArgumentCompletion.complete(collector, expectedInfos, callTypeAndReceiver.callType) flushToResultSet() val contextVariablesProvider = RealContextVariablesProvider(referenceVariantsHelper, position) withContextVariablesProvider(contextVariablesProvider) { lookupElementFactory -> if (receiverTypes != null) { ExtensionFunctionTypeValueCompletion(receiverTypes, callTypeAndReceiver.callType, lookupElementFactory) .processVariables(contextVariablesProvider) .forEach { val lookupElements = it.factory.createStandardLookupElementsForDescriptor( it.invokeDescriptor, useReceiverTypes = true, ) collector.addElements(lookupElements) } } if (contextVariableTypesForSmartCompletion.any { contextVariablesProvider.functionTypeVariables(it).isNotEmpty() }) { completeWithSmartCompletion(lookupElementFactory) } if (contextVariableTypesForReferenceVariants.any { contextVariablesProvider.functionTypeVariables(it).isNotEmpty() }) { val (imported, notImported) = referenceVariantsWithSingleFunctionTypeParameter()!! collector.addDescriptorElements(imported, lookupElementFactory) collector.addDescriptorElements(notImported, lookupElementFactory, notImported = true) } val staticMembersCompletion = StaticMembersCompletion( prefixMatcher, resolutionFacade, lookupElementFactory, referenceVariantsCollector!!.allCollected.imported, isJvmModule ) if (callTypeAndReceiver is CallTypeAndReceiver.DEFAULT) { staticMembersCompletion.completeFromImports(file, collector) } completeNonImported(lookupElementFactory) flushToResultSet() if (isDebuggerContext) { val variantsAndFactory = getRuntimeReceiverTypeReferenceVariants(lookupElementFactory) if (variantsAndFactory != null) { val variants = variantsAndFactory.first val resultLookupElementFactory = variantsAndFactory.second collector.addDescriptorElements(variants.imported, resultLookupElementFactory, withReceiverCast = true) collector.addDescriptorElements( variants.notImportedExtensions, resultLookupElementFactory, withReceiverCast = true, notImported = true ) flushToResultSet() } } if (!receiverTypes.isNullOrEmpty()) { // N.B.: callable references to member extensions are forbidden val shouldCompleteExtensionsFromObjects = when (callTypeAndReceiver.callType) { CallType.DEFAULT, CallType.DOT, CallType.SAFE, CallType.INFIX -> true else -> false } if (shouldCompleteExtensionsFromObjects) { staticMembersCompletion.completeObjectMemberExtensionsFromIndices( indicesHelper(false), receiverTypes.map { it.type }, callTypeAndReceiver, collector ) } } if (configuration.staticMembers && prefix.isNotEmpty()) { if (callTypeAndReceiver is CallTypeAndReceiver.DEFAULT) { staticMembersCompletion.completeFromIndices(indicesHelper(false), collector) } } } } private fun completeNonImported(lookupElementFactory: LookupElementFactory) { if (shouldCompleteTopLevelCallablesFromIndex()) { processTopLevelCallables { collector.addDescriptorElements(it, lookupElementFactory, notImported = true) flushToResultSet() } } if (callTypeAndReceiver.receiver == null && prefix.isNotEmpty()) { val classKindFilter: ((ClassKind) -> Boolean)? = when (callTypeAndReceiver) { is CallTypeAndReceiver.ANNOTATION -> { { it == ClassKind.ANNOTATION_CLASS } } is CallTypeAndReceiver.DEFAULT, is CallTypeAndReceiver.TYPE -> { { it != ClassKind.ENUM_ENTRY } } else -> null } if (classKindFilter != null) { val prefixMatcher = if (configuration.useBetterPrefixMatcherForNonImportedClasses) BetterPrefixMatcher(prefixMatcher, collector.bestMatchingDegree) else prefixMatcher addClassesFromIndex(classKindFilter, prefixMatcher) } } else if (callTypeAndReceiver is CallTypeAndReceiver.DOT) { val qualifier = bindingContext[BindingContext.QUALIFIER, callTypeAndReceiver.receiver] if (qualifier != null) return val receiver = callTypeAndReceiver.receiver as? KtSimpleNameExpression ?: return val helper = indicesHelper(false) val descriptors = mutableListOf<ClassifierDescriptorWithTypeParameters>() val fullTextPrefixMatcher = object : PrefixMatcher(receiver.getReferencedName()) { override fun prefixMatches(name: String): Boolean = name == prefix override fun cloneWithPrefix(prefix: String): PrefixMatcher = throw UnsupportedOperationException("Not implemented") } AllClassesCompletion( parameters = parameters.withPosition(receiver, receiver.startOffset), kotlinIndicesHelper = helper, prefixMatcher = fullTextPrefixMatcher, resolutionFacade = resolutionFacade, kindFilter = { true }, includeTypeAliases = true, includeJavaClassesNotToBeUsed = configuration.javaClassesNotToBeUsed, ).collect({ descriptors += it }, { descriptors.addIfNotNull(it.resolveToDescriptor(resolutionFacade)) }) val foundDescriptors = mutableSetOf<DeclarationDescriptor>() val classifiers = descriptors.asSequence().filter { it.kind == ClassKind.OBJECT || it.kind == ClassKind.ENUM_CLASS || it.kind == ClassKind.ENUM_ENTRY || it.hasCompanionObject || it is JavaClassDescriptor } for (classifier in classifiers) { val scope = nameExpression?.getResolutionScope(bindingContext) ?: return val desc = classifier.getImportableDescriptor() val newScope = scope.addImportingScope(ExplicitImportsScope(listOf(desc))) val newContext = (nameExpression.parent as KtExpression).analyzeInContext(newScope) val rvHelper = ReferenceVariantsHelper( newContext, resolutionFacade, moduleDescriptor, isVisibleFilter, NotPropertiesService.getNotProperties(position) ) val rvCollector = ReferenceVariantsCollector( rvHelper, indicesHelper(true), prefixMatcher, nameExpression, callTypeAndReceiver, resolutionFacade, newContext, importableFqNameClassifier, configuration ) val receiverTypes = detectReceiverTypes(newContext, nameExpression, callTypeAndReceiver) val factory = lookupElementFactory.copy( receiverTypes = receiverTypes, standardLookupElementsPostProcessor = { lookupElement -> val lookupDescriptor = lookupElement.`object` .safeAs<DeclarationLookupObject>() ?.descriptor as? MemberDescriptor ?: return@copy lookupElement if (!desc.isAncestorOf(lookupDescriptor, false)) return@copy lookupElement if (lookupDescriptor is CallableMemberDescriptor && lookupDescriptor.isExtension && lookupDescriptor.extensionReceiverParameter?.importableFqName != desc.fqNameSafe ) { return@copy lookupElement } val fqNameToImport = lookupDescriptor.containingDeclaration.importableFqName ?: return@copy lookupElement object : LookupElementDecorator<LookupElement>(lookupElement) { val name = fqNameToImport.shortName() val packageName = fqNameToImport.parent() override fun handleInsert(context: InsertionContext) { super.handleInsert(context) context.commitDocument() val file = context.file as? KtFile if (file != null) { val receiverInFile = file.findElementAt(receiver.startOffset) ?.getParentOfType<KtSimpleNameExpression>(false) ?: return receiverInFile.mainReference.bindToFqName(fqNameToImport, FORCED_SHORTENING) } } override fun renderElement(presentation: LookupElementPresentation?) { super.renderElement(presentation) presentation?.appendTailText( KotlinIdeaCompletionBundle.message( "presentation.tail.for.0.in.1", name, packageName, ), true, ) } } }, ) rvCollector.collectReferenceVariants(descriptorKindFilter) { (imported, notImportedExtensions) -> val unique = imported.asSequence() .filterNot { it.original in foundDescriptors } .onEach { foundDescriptors += it.original } val uniqueNotImportedExtensions = notImportedExtensions.asSequence() .filterNot { it.original in foundDescriptors } .onEach { foundDescriptors += it.original } collector.addDescriptorElements( unique.toList(), factory, prohibitDuplicates = true ) collector.addDescriptorElements( uniqueNotImportedExtensions.toList(), factory, notImported = true, prohibitDuplicates = true ) flushToResultSet() } } } } private fun isStartOfExtensionReceiverFor(): KtCallableDeclaration? { val userType = nameExpression!!.parent as? KtUserType ?: return null if (userType.qualifier != null) return null val typeRef = userType.parent as? KtTypeReference ?: return null if (userType != typeRef.typeElement) return null return when (val parent = typeRef.parent) { is KtNamedFunction -> parent.takeIf { typeRef == it.receiverTypeReference } is KtProperty -> parent.takeIf { typeRef == it.receiverTypeReference } else -> null } } } private fun wasAutopopupRecentlyCancelled(parameters: CompletionParameters) = LookupCancelService.getInstance(project).wasAutoPopupRecentlyCancelled(parameters.editor, position.startOffset) private val KEYWORDS_ONLY = object : CompletionKind { override val descriptorKindFilter: DescriptorKindFilter? get() = null override fun doComplete() { val keywordsToSkip = HashSet<String>() val keywordValueConsumer = object : KeywordValues.Consumer { override fun consume( lookupString: String, expectedInfoMatcher: (ExpectedInfo) -> ExpectedInfoMatch, suitableOnPsiLevel: PsiElement.() -> Boolean, priority: SmartCompletionItemPriority, factory: () -> LookupElement ) { keywordsToSkip.add(lookupString) val lookupElement = factory() val matched = expectedInfos.any { val match = expectedInfoMatcher(it) assert(!match.makeNotNullable) { "Nullable keyword values not supported" } match.isMatch() } // 'expectedInfos' is filled with the compiler's insight. // In cases like missing import statement or undeclared variable desired data cannot be retrieved. Here is where we can // analyse PSI and calling 'suitableOnPsiLevel()' does the trick. if (matched || (expectedInfos.isEmpty() && position.suitableOnPsiLevel())) { lookupElement.putUserData(SmartCompletionInBasicWeigher.KEYWORD_VALUE_MATCHED_KEY, Unit) lookupElement.putUserData(SMART_COMPLETION_ITEM_PRIORITY_KEY, priority) } collector.addElement(lookupElement) } } KeywordValues.process( keywordValueConsumer, callTypeAndReceiver, bindingContext, resolutionFacade, moduleDescriptor, isJvmModule ) val isUseSiteAnnotationTarget = position.prevLeaf()?.node?.elementType == KtTokens.AT KeywordCompletion.complete(expression ?: position, resultSet.prefixMatcher, isJvmModule) { lookupElement -> when (val keyword = lookupElement.lookupString) { in keywordsToSkip -> return@complete // if "this" is parsed correctly in the current context - insert it and all this@xxx items "this" -> { if (expression != null) { collector.addElements( thisExpressionItems( bindingContext, expression, prefix, resolutionFacade ).map { it.createLookupElement() }) } else { // for completion in secondary constructor delegation call collector.addElement(lookupElement) } } // if "return" is parsed correctly in the current context - insert it and all return@xxx items "return" -> { if (expression != null) { collector.addElements(returnExpressionItems(bindingContext, expression)) } } "break", "continue" -> { if (expression != null) { collector.addElements(breakOrContinueExpressionItems(expression, keyword)) } } "override" -> { collector.addElement(lookupElement) OverridesCompletion(collector, basicLookupElementFactory).complete(position, declaration = null) } "class" -> { if (callTypeAndReceiver !is CallTypeAndReceiver.CALLABLE_REFERENCE) { // otherwise it should be handled by KeywordValues collector.addElement(lookupElement) } } "get" -> { collector.addElement(lookupElement) if (!isUseSiteAnnotationTarget) { collector.addElement(createKeywordConstructLookupElement(project, keyword, "val v:Int get()=caret")) collector.addElement( createKeywordConstructLookupElement( project, keyword, "val v:Int get(){caret}", trimSpacesAroundCaret = true ) ) } } "set" -> { collector.addElement(lookupElement) if (!isUseSiteAnnotationTarget) { collector.addElement(createKeywordConstructLookupElement(project, keyword, "var v:Int set(value)=caret")) collector.addElement( createKeywordConstructLookupElement( project, keyword, "var v:Int set(value){caret}", trimSpacesAroundCaret = true ) ) } } "contract" -> { } else -> collector.addElement(lookupElement) } } } } private val NAMED_ARGUMENTS_ONLY = object : CompletionKind { override val descriptorKindFilter: DescriptorKindFilter? get() = null override fun doComplete(): Unit = NamedArgumentCompletion.complete(collector, expectedInfos, callTypeAndReceiver.callType) } private val OPERATOR_NAME = object : CompletionKind { override val descriptorKindFilter: DescriptorKindFilter? get() = null fun isApplicable(): Boolean { if (nameExpression == null || nameExpression != expression) return false val func = position.getParentOfType<KtNamedFunction>(strict = false) ?: return false val funcNameIdentifier = func.nameIdentifier ?: return false val identifierInNameExpression = nameExpression.nextLeaf { it is LeafPsiElement && it.elementType == KtTokens.IDENTIFIER } ?: return false if (!func.hasModifier(KtTokens.OPERATOR_KEYWORD) || identifierInNameExpression != funcNameIdentifier) return false val originalFunc = toFromOriginalFileMapper.toOriginalFile(func) ?: return false return !originalFunc.isTopLevel || (originalFunc.isExtensionDeclaration()) } override fun doComplete() { OperatorNameCompletion.doComplete(collector, descriptorNameFilter) flushToResultSet() } } private val DECLARATION_NAME = object : CompletionKind { override val descriptorKindFilter: DescriptorKindFilter? get() = null override fun doComplete() { val declaration = declaration() if (declaration is KtParameter && !shouldCompleteParameterNameAndType()) return // do not complete also keywords and from unresolved references in such case collector.addLookupElementPostProcessor { lookupElement -> lookupElement.putUserData(KotlinCompletionCharFilter.SUPPRESS_ITEM_SELECTION_BY_CHARS_ON_TYPING, Unit) lookupElement } KEYWORDS_ONLY.doComplete() completeDeclarationNameFromUnresolvedOrOverride(declaration) when (declaration) { is KtParameter -> completeParameterOrVarNameAndType(withType = true) is KtClassOrObject -> { if (declaration.isTopLevel()) { completeTopLevelClassName() } } } } override fun shouldDisableAutoPopup(): Boolean = when { TemplateManager.getInstance(project).getActiveTemplate(parameters.editor) != null -> true declaration() is KtParameter && wasAutopopupRecentlyCancelled(parameters) -> true else -> false } override fun addWeighers(sorter: CompletionSorter): CompletionSorter = if (shouldCompleteParameterNameAndType()) sorter.weighBefore("prefix", VariableOrParameterNameWithTypeCompletion.Weigher) else sorter private fun completeTopLevelClassName() { val name = parameters.originalFile.virtualFile.nameWithoutExtension if (!(Name.isValidIdentifier(name) && Name.identifier(name).render() == name && name[0].isUpperCase())) return if ((parameters.originalFile as KtFile).declarations.any { it is KtClassOrObject && it.name == name }) return collector.addElement(LookupElementBuilder.create(name)) } private fun declaration() = position.parent as KtNamedDeclaration private fun shouldCompleteParameterNameAndType(): Boolean { val parameter = declaration() as? KtParameter ?: return false val list = parameter.parent as? KtParameterList ?: return false return when (val owner = list.parent) { is KtCatchClause, is KtPropertyAccessor, is KtFunctionLiteral -> false is KtNamedFunction -> owner.nameIdentifier != null is KtPrimaryConstructor -> !owner.getContainingClassOrObject().isAnnotation() else -> true } } } private val SUPER_QUALIFIER = object : CompletionKind { override val descriptorKindFilter: DescriptorKindFilter get() = DescriptorKindFilter.NON_SINGLETON_CLASSIFIERS override fun doComplete() { val classOrObject = position.parents.firstIsInstanceOrNull<KtClassOrObject>() ?: return val classDescriptor = resolutionFacade.resolveToDescriptor(classOrObject, BodyResolveMode.PARTIAL) as ClassDescriptor var superClasses = classDescriptor.defaultType.constructor.supertypesWithAny() .mapNotNull { it.constructor.declarationDescriptor as? ClassDescriptor } if (callTypeAndReceiver.receiver != null) { val referenceVariantsSet = referenceVariantsCollector!!.collectReferenceVariants(descriptorKindFilter).imported.toSet() superClasses = superClasses.filter { it in referenceVariantsSet } } superClasses .map { basicLookupElementFactory.createLookupElement(it, qualifyNestedClasses = true, includeClassTypeArguments = false) } .forEach { collector.addElement(it) } } } private fun completeDeclarationNameFromUnresolvedOrOverride(declaration: KtNamedDeclaration) { if (declaration is KtCallableDeclaration && declaration.hasModifier(KtTokens.OVERRIDE_KEYWORD)) { OverridesCompletion(collector, basicLookupElementFactory).complete(position, declaration) } else { val referenceScope = referenceScope(declaration) ?: return val originalScope = toFromOriginalFileMapper.toOriginalFile(referenceScope) ?: return val afterOffset = if (referenceScope is KtBlockExpression) parameters.offset else null val descriptor = bindingContext[BindingContext.DECLARATION_TO_DESCRIPTOR, declaration] FromUnresolvedNamesCompletion(collector, prefixMatcher).addNameSuggestions(originalScope, afterOffset, descriptor) } } private fun referenceScope(declaration: KtNamedDeclaration): KtElement? = when (val parent = declaration.parent) { is KtParameterList -> parent.parent as KtElement is KtClassBody -> { val classOrObject = parent.parent as KtClassOrObject if (classOrObject is KtObjectDeclaration && classOrObject.isCompanion()) { classOrObject.containingClassOrObject } else { classOrObject } } is KtFile -> parent is KtBlockExpression -> parent else -> null } private fun addClassesFromIndex(kindFilter: (ClassKind) -> Boolean, prefixMatcher: PrefixMatcher) { val classifierDescriptorCollector = { descriptor: ClassifierDescriptorWithTypeParameters -> collector.addElement(basicLookupElementFactory.createLookupElement(descriptor), notImported = true) } val javaClassCollector = { javaClass: PsiClass -> collector.addElement(basicLookupElementFactory.createLookupElementForJavaClass(javaClass), notImported = true) } AllClassesCompletion( parameters = parameters, kotlinIndicesHelper = indicesHelper(true), prefixMatcher = prefixMatcher, resolutionFacade = resolutionFacade, kindFilter = kindFilter, includeTypeAliases = true, includeJavaClassesNotToBeUsed = configuration.javaClassesNotToBeUsed, ).collect(classifierDescriptorCollector, javaClassCollector) } private fun addReferenceVariantElements(lookupElementFactory: LookupElementFactory, descriptorKindFilter: DescriptorKindFilter) { fun addReferenceVariants(referenceVariants: ReferenceVariants) { collector.addDescriptorElements( referenceVariantsHelper.excludeNonInitializedVariable(referenceVariants.imported, position), lookupElementFactory, prohibitDuplicates = true ) collector.addDescriptorElements( referenceVariants.notImportedExtensions, lookupElementFactory, notImported = true, prohibitDuplicates = true ) } val referenceVariantsCollector = referenceVariantsCollector!! referenceVariantsCollector.collectReferenceVariants(descriptorKindFilter) { referenceVariants -> addReferenceVariants(referenceVariants) flushToResultSet() } } private fun completeParameterOrVarNameAndType(withType: Boolean) { val nameWithTypeCompletion = VariableOrParameterNameWithTypeCompletion( collector, basicLookupElementFactory, prefixMatcher, resolutionFacade, withType, ) // if we are typing parameter name, restart completion each time we type an upper case letter // because new suggestions will appear (previous words can be used as user prefix) val prefixPattern = StandardPatterns.string().with(object : PatternCondition<String>("Prefix ends with uppercase letter") { override fun accepts(prefix: String, context: ProcessingContext?) = prefix.isNotEmpty() && prefix.last().isUpperCase() }) collector.restartCompletionOnPrefixChange(prefixPattern) nameWithTypeCompletion.addFromParametersInFile(position, resolutionFacade, isVisibleFilterCheckAlways) flushToResultSet() nameWithTypeCompletion.addFromImportedClasses(position, bindingContext, isVisibleFilterCheckAlways) flushToResultSet() nameWithTypeCompletion.addFromAllClasses(parameters, indicesHelper(false)) } } private val USUALLY_START_UPPER_CASE = DescriptorKindFilter( DescriptorKindFilter.CLASSIFIERS_MASK or DescriptorKindFilter.FUNCTIONS_MASK, listOf(NonSamConstructorFunctionExclude, DescriptorKindExclude.Extensions /* needed for faster getReferenceVariants */) ) private val USUALLY_START_LOWER_CASE = DescriptorKindFilter( DescriptorKindFilter.CALLABLES_MASK or DescriptorKindFilter.PACKAGES_MASK, listOf(SamConstructorDescriptorKindExclude) ) private object NonSamConstructorFunctionExclude : DescriptorKindExclude() { override fun excludes(descriptor: DeclarationDescriptor) = descriptor is FunctionDescriptor && descriptor !is SamConstructorDescriptor override val fullyExcludedDescriptorKinds: Int get() = 0 }
apache-2.0
dfc54bcd24401bf04f76dce28925bdc8
47.253363
168
0.601482
6.600521
false
false
false
false
BijoySingh/Quick-Note-Android
base/src/main/java/com/maubis/scarlet/base/note/reminders/sheet/ReminderBottomSheet.kt
1
8308
package com.maubis.scarlet.base.note.reminders.sheet import android.app.DatePickerDialog import android.app.Dialog import android.app.TimePickerDialog import android.view.View.GONE import android.widget.TextView import com.github.bijoysingh.starter.util.DateFormatter import com.github.bijoysingh.uibasics.views.UIActionView import com.maubis.scarlet.base.R import com.maubis.scarlet.base.config.ApplicationBase.Companion.sAppTheme import com.maubis.scarlet.base.core.note.Reminder import com.maubis.scarlet.base.core.note.ReminderInterval import com.maubis.scarlet.base.core.note.getReminderV2 import com.maubis.scarlet.base.core.note.setReminderV2 import com.maubis.scarlet.base.database.room.note.Note import com.maubis.scarlet.base.main.sheets.GenericOptionsBottomSheet import com.maubis.scarlet.base.note.reminders.ReminderJob import com.maubis.scarlet.base.note.saveWithoutSync import com.maubis.scarlet.base.support.sheets.LithoChooseOptionsItem import com.maubis.scarlet.base.support.ui.ThemeColorType import com.maubis.scarlet.base.support.ui.ThemedActivity import com.maubis.scarlet.base.support.ui.ThemedBottomSheetFragment import com.maubis.scarlet.base.support.utils.sDateFormat import java.util.* // TODO: Upgrade to Litho class ReminderBottomSheet : ThemedBottomSheetFragment() { var selectedNote: Note? = null var reminder: Reminder = Reminder( 0, Calendar.getInstance().timeInMillis, ReminderInterval.ONCE) override fun getBackgroundView(): Int { return R.id.container_layout } override fun setupView(dialog: Dialog?) { super.setupView(dialog) if (dialog == null) { return } val note = selectedNote if (note === null) { return } val calendar = Calendar.getInstance() reminder = note.getReminderV2() ?: Reminder( 0, calendar.timeInMillis, ReminderInterval.ONCE) val isNewReminder = reminder.uid == 0 if (isNewReminder) { calendar.set(Calendar.HOUR_OF_DAY, 8) calendar.set(Calendar.MINUTE, 0) calendar.set(Calendar.SECOND, 0) if (Calendar.getInstance().after(calendar)) { calendar.add(Calendar.HOUR_OF_DAY, 24) } reminder.timestamp = calendar.timeInMillis } setColors() setContent(reminder) setListeners(note, isNewReminder) makeBackgroundTransparent(dialog, R.id.root_layout) } fun setListeners(note: Note, isNewReminder: Boolean) { val dlg = dialog if (dlg === null) { return } val reminderDate = dlg.findViewById<UIActionView>(R.id.reminder_date) val reminderTime = dlg.findViewById<UIActionView>(R.id.reminder_time) val reminderRepeat = dlg.findViewById<UIActionView>(R.id.reminder_repeat) reminderDate.setOnClickListener { if (reminder.interval == ReminderInterval.ONCE) { openDatePickerDialog() } } reminderTime.setOnClickListener { openTimePickerDialog() } reminderRepeat.setOnClickListener { openFrequencyDialog() } val removeAlarm = dlg.findViewById<TextView>(R.id.remove_alarm) val setAlarm = dlg.findViewById<TextView>(R.id.set_alarm) if (isNewReminder) { removeAlarm.visibility = GONE } removeAlarm.setOnClickListener { ReminderJob.cancelJob(reminder.uid) note.meta = "" note.saveWithoutSync(themedContext()) dismiss() } setAlarm.setOnClickListener { if (Calendar.getInstance().after(reminder.toCalendar())) { dismiss() return@setOnClickListener } val uid = ReminderJob.scheduleJob(note.uuid, reminder) if (uid == -1) { dismiss() return@setOnClickListener } reminder.uid = uid note.setReminderV2(reminder) note.saveWithoutSync(themedContext()) dismiss() } } fun getReminderIntervalLabel(interval: ReminderInterval): Int { return when (interval) { ReminderInterval.ONCE -> R.string.reminder_frequency_once ReminderInterval.DAILY -> R.string.reminder_frequency_daily } } fun openFrequencyDialog() { val isSelected = fun(interval: ReminderInterval): Boolean = interval == reminder.interval com.maubis.scarlet.base.support.sheets.openSheet( themedActivity() as ThemedActivity, GenericOptionsBottomSheet().apply { title = R.string.reminder_sheet_repeat options = arrayListOf( LithoChooseOptionsItem( title = getReminderIntervalLabel(ReminderInterval.ONCE), listener = { reminder.interval = ReminderInterval.ONCE setContent(reminder) }, selected = isSelected(ReminderInterval.ONCE) ), LithoChooseOptionsItem( title = getReminderIntervalLabel(ReminderInterval.DAILY), listener = { reminder.interval = ReminderInterval.DAILY setContent(reminder) }, selected = isSelected(ReminderInterval.DAILY) ) ) } ) } fun openDatePickerDialog() { val calendar = reminder.toCalendar() val dialog = DatePickerDialog( themedContext(), R.style.DialogTheme, DatePickerDialog.OnDateSetListener { _, year, month, day -> calendar.set(Calendar.YEAR, year) calendar.set(Calendar.MONTH, month) calendar.set(Calendar.DAY_OF_MONTH, day) reminder.timestamp = calendar.timeInMillis setContent(reminder) }, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH)) dialog.show() } fun openTimePickerDialog() { val calendar = reminder.toCalendar() val dialog = TimePickerDialog( themedContext(), R.style.DialogTheme, TimePickerDialog.OnTimeSetListener { _, hourOfDay, minute -> calendar.set(Calendar.HOUR_OF_DAY, hourOfDay) calendar.set(Calendar.MINUTE, minute) calendar.set(Calendar.SECOND, 0) reminder.timestamp = calendar.timeInMillis setContent(reminder) }, calendar.get(Calendar.HOUR_OF_DAY), calendar.get(Calendar.MINUTE), false) dialog.show() } fun setContent(reminder: Reminder) { val dlg = dialog if (dlg === null) { return } val reminderDate = dlg.findViewById<UIActionView>(R.id.reminder_date) val reminderTime = dlg.findViewById<UIActionView>(R.id.reminder_time) val reminderRepeat = dlg.findViewById<UIActionView>(R.id.reminder_repeat) reminderRepeat.setSubtitle(getReminderIntervalLabel(reminder.interval)) reminderTime.setSubtitle(sDateFormat.readableTime(DateFormatter.Formats.HH_MM_A.format, reminder.timestamp)) reminderDate.setSubtitle(sDateFormat.readableTime(DateFormatter.Formats.DD_MMM_YYYY.format, reminder.timestamp)) reminderDate.alpha = if (reminder.interval == ReminderInterval.ONCE) 1.0f else 0.5f } fun setColors() { val dlg = dialog if (dlg === null) { return } val reminderDate = dlg.findViewById<UIActionView>(R.id.reminder_date) val reminderTime = dlg.findViewById<UIActionView>(R.id.reminder_time) val reminderRepeat = dlg.findViewById<UIActionView>(R.id.reminder_repeat) val iconColor = sAppTheme.get(ThemeColorType.TOOLBAR_ICON) val textColor = sAppTheme.get(ThemeColorType.TERTIARY_TEXT) val titleColor = sAppTheme.get(ThemeColorType.SECTION_HEADER) reminderDate.setTitleColor(titleColor) reminderDate.setSubtitleColor(textColor) reminderDate.setImageTint(iconColor) reminderDate.setActionTint(iconColor) reminderTime.setTitleColor(titleColor) reminderTime.setSubtitleColor(textColor) reminderTime.setImageTint(iconColor) reminderTime.setActionTint(iconColor) reminderRepeat.setTitleColor(titleColor) reminderRepeat.setSubtitleColor(textColor) reminderRepeat.setImageTint(iconColor) reminderRepeat.setActionTint(iconColor) } override fun getLayout(): Int = R.layout.bottom_sheet_reminder override fun getBackgroundCardViewIds(): Array<Int> = arrayOf(R.id.card_layout) companion object { fun openSheet(activity: ThemedActivity, note: Note) { val sheet = ReminderBottomSheet() sheet.selectedNote = note sheet.show(activity.supportFragmentManager, sheet.tag) } } }
gpl-3.0
2c1a2d633826ed8e31121b16fd5dbc42
31.330739
116
0.705104
4.329338
false
false
false
false
nrizzio/Signal-Android
app/src/main/java/org/thoughtcrime/securesms/stories/StoryFirstTimeNavigationView.kt
1
4944
package org.thoughtcrime.securesms.stories import android.animation.Animator import android.animation.AnimatorListenerAdapter import android.content.Context import android.graphics.Color import android.graphics.drawable.ColorDrawable import android.graphics.drawable.Drawable import android.os.Build import android.util.AttributeSet import android.view.View import android.widget.ImageView import androidx.constraintlayout.widget.ConstraintLayout import com.airbnb.lottie.LottieAnimationView import com.bumptech.glide.load.DataSource import com.bumptech.glide.load.engine.GlideException import com.bumptech.glide.request.RequestListener import com.bumptech.glide.request.target.Target import org.thoughtcrime.securesms.R import org.thoughtcrime.securesms.blurhash.BlurHash import org.thoughtcrime.securesms.mms.GlideApp import org.thoughtcrime.securesms.util.ContextUtil import org.thoughtcrime.securesms.util.visible class StoryFirstTimeNavigationView @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null ) : ConstraintLayout(context, attrs) { companion object { private const val BLUR_ALPHA = 0x3D private const val NO_BLUR_ALPHA = 0xCC } init { inflate(context, R.layout.story_first_time_navigation_view, this) } private val tapToAdvance: LottieAnimationView = findViewById(R.id.edu_tap_icon) private val swipeUp: LottieAnimationView = findViewById(R.id.edu_swipe_up_icon) private val swipeRight: LottieAnimationView = findViewById(R.id.edu_swipe_right_icon) private val blurHashView: ImageView = findViewById(R.id.edu_blur_hash) private val overlayView: ImageView = findViewById(R.id.edu_overlay) private val gotIt: View = findViewById(R.id.edu_got_it) private val close: View = findViewById(R.id.edu_close) private var isPlayingAnimations = false var callback: Callback? = null init { if (isRenderEffectSupported()) { blurHashView.visible = false overlayView.visible = true overlayView.setImageDrawable(ColorDrawable(Color.argb(BLUR_ALPHA, 0, 0, 0))) } gotIt.setOnClickListener { callback?.onGotItClicked() GlideApp.with(this).clear(blurHashView) blurHashView.setImageDrawable(null) hide() } close.setOnClickListener { callback?.onCloseClicked() GlideApp.with(this).clear(blurHashView) blurHashView.setImageDrawable(null) hide() } setOnClickListener { } } fun setBlurHash(blurHash: BlurHash?) { if (isRenderEffectSupported() || callback?.userHasSeenFirstNavigationView() == true) { return } if (blurHash == null) { blurHashView.visible = false overlayView.visible = true overlayView.setImageDrawable(ColorDrawable(Color.argb(NO_BLUR_ALPHA, 0, 0, 0))) GlideApp.with(this).clear(blurHashView) return } else { blurHashView.visible = true overlayView.visible = true overlayView.setImageDrawable(ColorDrawable(Color.argb(BLUR_ALPHA, 0, 0, 0))) } GlideApp.with(this) .load(blurHash) .addListener(object : RequestListener<Drawable> { override fun onLoadFailed(e: GlideException?, model: Any?, target: Target<Drawable>?, isFirstResource: Boolean): Boolean { setBlurHash(null) return false } override fun onResourceReady(resource: Drawable?, model: Any?, target: Target<Drawable>?, dataSource: DataSource?, isFirstResource: Boolean): Boolean { return false } }) .into(blurHashView) } fun show() { if (callback?.userHasSeenFirstNavigationView() == true) { return } visible = true startLottieAnimations() } fun hide() { visible = false endLottieAnimations() } private fun startLottieAnimations() { if (ContextUtil.getAnimationScale(context) == 0f) { return } isPlayingAnimations = true tapToAdvance.addAnimatorListener(object : AnimatorListenerAdapter() { override fun onAnimationEnd(animation: Animator?) { if (isPlayingAnimations) { swipeUp.playAnimation() } } }) swipeUp.addAnimatorListener(object : AnimatorListenerAdapter() { override fun onAnimationEnd(animation: Animator?) { if (isPlayingAnimations) { swipeRight.playAnimation() } } }) swipeRight.addAnimatorListener(object : AnimatorListenerAdapter() { override fun onAnimationEnd(animation: Animator?) { postDelayed({ if (isPlayingAnimations) { startLottieAnimations() } }, 300) } }) tapToAdvance.playAnimation() } private fun endLottieAnimations() { isPlayingAnimations = false } private fun isRenderEffectSupported(): Boolean { return Build.VERSION.SDK_INT >= 31 } interface Callback { fun userHasSeenFirstNavigationView(): Boolean fun onGotItClicked() fun onCloseClicked() } }
gpl-3.0
9c286b8ba9c50969598f42a16eabd671
28.254438
159
0.708536
4.450045
false
false
false
false
SDS-Studios/ScoreKeeper
app/src/main/java/io/github/sdsstudios/ScoreKeeper/Game/Results.kt
1
691
package io.github.sdsstudios.ScoreKeeper.Game import android.arch.persistence.room.ColumnInfo import android.arch.persistence.room.Relation import io.github.sdsstudios.ScoreKeeper.Database.Dao.PlayerDao import io.github.sdsstudios.ScoreKeeper.Database.Dao.ScoresDao import java.util.* /** * Created by sethsch1 on 01/01/18. */ class Results( @Relation( parentColumn = PlayerDao.KEY_ID, entityColumn = ScoresDao.KEY_PLAYER_ID, entity = Scores::class, projection = [ScoresDao.KEY_RESULT]) var results: List<String> = ArrayList(), @ColumnInfo(name = PlayerDao.KEY_ID) var playerId: Long = 0 )
gpl-3.0
35e8150968910c6dd63cb778c7f4b584
29.086957
62
0.675832
4.088757
false
false
false
false
siosio/intellij-community
platform/vcs-impl/src/com/intellij/openapi/vcs/changes/ui/browser/ChangesFilterer.kt
1
11199
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.vcs.changes.ui.browser import com.intellij.diff.DiffContentFactory import com.intellij.diff.comparison.ComparisonManagerImpl import com.intellij.diff.comparison.trimExpandText import com.intellij.diff.lang.DiffIgnoredRangeProvider import com.intellij.icons.AllIcons import com.intellij.openapi.Disposable import com.intellij.openapi.actionSystem.* import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.ModalityState import com.intellij.openapi.progress.EmptyProgressIndicator import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.project.DumbAware import com.intellij.openapi.project.Project import com.intellij.openapi.vcs.FileStatus import com.intellij.openapi.vcs.VcsBundle import com.intellij.openapi.vcs.changes.ByteBackedContentRevision import com.intellij.openapi.vcs.changes.Change import com.intellij.openapi.vcs.changes.ui.ChangesComparator import com.intellij.util.ModalityUiUtil import com.intellij.util.concurrency.annotations.RequiresEdt import com.intellij.util.containers.ContainerUtil import com.intellij.util.ui.update.DisposableUpdate import com.intellij.util.ui.update.MergingUpdateQueue import org.jetbrains.annotations.Nls import org.jetbrains.annotations.NotNull class ChangesFilterer(val project: Project?, val listener: Listener) : Disposable { companion object { @JvmField val DATA_KEY: DataKey<ChangesFilterer> = DataKey.create("com.intellij.openapi.vcs.changes.ui.browser.ChangesFilterer") } private val LOCK = Any() private val updateQueue = MergingUpdateQueue("ChangesFilterer", 300, true, MergingUpdateQueue.ANY_COMPONENT, this) private var progressIndicator: ProgressIndicator = EmptyProgressIndicator() private var rawChanges: List<Change>? = null private var activeFilter: Filter? = null private var processedChanges: List<Change>? = null private var pendingChanges: List<Change>? = null private var filteredOutChanges: List<Change>? = null override fun dispose() { resetFilter() } @RequiresEdt fun setChanges(changes: List<Change>?) { val oldChanges = rawChanges if (oldChanges == null && changes == null) return if (oldChanges != null && changes != null && ContainerUtil.equalsIdentity(oldChanges, changes)) return rawChanges = changes?.toList() restartLoading() } @RequiresEdt fun getFilteredChanges(): FilteredState { synchronized(LOCK) { val processed = processedChanges val pending = pendingChanges val filteredOut = filteredOutChanges return when { processed != null && pending != null && filteredOut != null -> FilteredState.create(processed, pending, filteredOut) else -> FilteredState.create(rawChanges ?: emptyList()) } } } @RequiresEdt fun getProgress(): Float { val pendingCount = synchronized(LOCK) { pendingChanges?.size } val totalCount = rawChanges?.size if (pendingCount == null || totalCount == null || totalCount == 0) return 1.0f return (1.0f - pendingCount.toFloat() / totalCount).coerceAtLeast(0.0f) } @NotNull fun hasActiveFilter(): Boolean = activeFilter != null fun clearFilter() = setFilter(null) private fun setFilter(filter: Filter?) { activeFilter = filter restartLoading() } private fun restartLoading() { val indicator = resetFilter() val filter = activeFilter val changesToFilter = rawChanges if (filter == null || changesToFilter == null) { updatePresentation() return } val changes = changesToFilter.sortedWith(ChangesComparator.getInstance(false)) // Work around expensive removeAt(0) with double reversion val pending = changes.asReversed().asSequence().map { Change(it.beforeRevision, it.afterRevision, FileStatus.OBSOLETE) } .toMutableList().asReversed() val processed = mutableListOf<Change>() val filteredOut = mutableListOf<Change>() synchronized(LOCK) { processedChanges = processed pendingChanges = pending filteredOutChanges = filteredOut } updatePresentation() ApplicationManager.getApplication().executeOnPooledThread { ProgressManager.getInstance().runProcess( { filterChanges(changes, filter, pending, processed, filteredOut) }, indicator) } } private fun filterChanges(changes: List<Change>, filter: Filter, pending: MutableList<Change>, processed: MutableList<Change>, filteredOut: MutableList<Change>) { queueUpdatePresentation() val filteredChanges = filter.acceptBulk(this, changes) if (filteredChanges != null) { synchronized(LOCK) { ProgressManager.checkCanceled() pending.clear() processed.addAll(filteredChanges) val filteredOutSet = changes.toMutableSet() filteredOutSet.removeAll(filteredChanges) filteredOut.addAll(filteredOutSet) } updatePresentation() return } for (change in changes) { ProgressManager.checkCanceled() val accept = filter.accept(this, change) synchronized(LOCK) { ProgressManager.checkCanceled() pending.removeAt(0) if (accept) { processed.add(change) } else { filteredOut.add(change) } } queueUpdatePresentation() } updatePresentation() } private fun queueUpdatePresentation() { updateQueue.queue(DisposableUpdate.createDisposable(updateQueue, "update") { updatePresentation() }) } private fun updatePresentation() { ModalityUiUtil.invokeLaterIfNeeded( { updateQueue.cancelAllUpdates() listener.updateChanges() }, ModalityState.any()) } private fun resetFilter(): ProgressIndicator { synchronized(LOCK) { processedChanges = null pendingChanges = null filteredOutChanges = null progressIndicator.cancel() progressIndicator = EmptyProgressIndicator() return progressIndicator } } private interface Filter { fun isAvailable(filterer: ChangesFilterer): Boolean = true fun accept(filterer: ChangesFilterer, change: Change): Boolean fun acceptBulk(filterer: ChangesFilterer, changes: List<Change>): Collection<Change>? = null @Nls fun getText(): String @Nls fun getDescription(): String? = null } private object MovesOnlyFilter : Filter { override fun getText(): String = VcsBundle.message("action.filter.moved.files.text") override fun acceptBulk(filterer: ChangesFilterer, changes: List<Change>): Collection<Change>? { for (epFilter in BulkMovesOnlyChangesFilter.EP_NAME.extensionList) { val filteredChanges = epFilter.filter(filterer.project, changes) if (filteredChanges != null) { return filteredChanges } } return null } override fun accept(filterer: ChangesFilterer, change: Change): Boolean { val bRev = change.beforeRevision ?: return true val aRev = change.afterRevision ?: return true if (bRev.file == aRev.file) return true if (bRev is ByteBackedContentRevision && aRev is ByteBackedContentRevision) { val bytes1 = bRev.contentAsBytes ?: return true val bytes2 = aRev.contentAsBytes ?: return true return !bytes1.contentEquals(bytes2) } else { val content1 = bRev.content ?: return true val content2 = aRev.content ?: return true return content1 != content2 } } } private object NonImportantFilter : Filter { override fun getText(): String = VcsBundle.message("action.filter.non.important.files.text") override fun isAvailable(filterer: ChangesFilterer): Boolean = filterer.project != null override fun accept(filterer: ChangesFilterer, change: Change): Boolean { val project = filterer.project val bRev = change.beforeRevision ?: return true val aRev = change.afterRevision ?: return true val content1 = bRev.content ?: return true val content2 = aRev.content ?: return true val diffContent1 = DiffContentFactory.getInstance().create(project, content1, bRev.file) val diffContent2 = DiffContentFactory.getInstance().create(project, content2, aRev.file) val provider = DiffIgnoredRangeProvider.EP_NAME.extensions.find { it.accepts(project, diffContent1) && it.accepts(project, diffContent2) } if (provider == null) return content1 != content2 val ignoredRanges1 = provider.getIgnoredRanges(project, content1, diffContent1) val ignoredRanges2 = provider.getIgnoredRanges(project, content2, diffContent2) val ignored1 = ComparisonManagerImpl.collectIgnoredRanges(ignoredRanges1) val ignored2 = ComparisonManagerImpl.collectIgnoredRanges(ignoredRanges2) val range = trimExpandText(content1, content2, 0, 0, content1.length, content2.length, ignored1, ignored2) return !range.isEmpty } } interface Listener { fun updateChanges() } class FilteredState private constructor(val changes: List<Change>, val pending: List<Change>, val filteredOut: List<Change>) { companion object { @JvmStatic fun create(changes: List<Change>): FilteredState = create(changes, emptyList(), emptyList()) fun create(changes: List<Change>, pending: List<Change>, filteredOut: List<Change>): FilteredState = FilteredState(changes.toList(), pending.toList(), filteredOut.toList()) } } class FilterGroup : DefaultActionGroup(), Toggleable, DumbAware { init { isPopup = true templatePresentation.text = VcsBundle.message("action.filter.filter.by.text") templatePresentation.icon = AllIcons.General.Filter } override fun update(e: AnActionEvent) { val filterer = e.getData(DATA_KEY) if (filterer == null) { e.presentation.isEnabledAndVisible = false return } e.presentation.isVisible = true e.presentation.isEnabled = filterer.rawChanges != null Toggleable.setSelected(e.presentation, filterer.activeFilter != null) } override fun getChildren(e: AnActionEvent?): Array<AnAction> { val filterer = e?.getData(DATA_KEY) ?: return AnAction.EMPTY_ARRAY return listOf(MovesOnlyFilter, NonImportantFilter) .filter { it.isAvailable(filterer) } .map { ToggleFilterAction(filterer, it) } .toTypedArray() } override fun disableIfNoVisibleChildren(): Boolean = false } private class ToggleFilterAction(val filterer: ChangesFilterer, val filter: Filter) : ToggleAction(filter.getText(), filter.getDescription(), null), DumbAware { override fun isSelected(e: AnActionEvent): Boolean = filterer.activeFilter == filter override fun setSelected(e: AnActionEvent, state: Boolean) { filterer.setFilter(if (state) filter else null) } } }
apache-2.0
324d4a0c5652f033a4463db07aa5d388
33.671827
140
0.706224
4.83132
false
false
false
false
smmribeiro/intellij-community
platform/platform-impl/src/com/intellij/ui/charts/ChartWrapper.kt
3
12995
package com.intellij.ui.charts import com.intellij.ui.ColorUtil import com.intellij.ui.JBColor import com.intellij.util.ui.GraphicsUtil import com.intellij.util.ui.JBUI import com.intellij.util.ui.components.BorderLayoutPanel import org.intellij.lang.annotations.MagicConstant import java.awt.* import java.awt.event.MouseAdapter import java.awt.event.MouseEvent import java.util.function.Consumer import javax.swing.JComponent import javax.swing.SwingConstants import kotlin.math.absoluteValue import kotlin.math.roundToInt import kotlin.math.sign interface ChartComponent { fun paintComponent(g: Graphics2D) } /** * Holds instance of ChartWrapper in which has been added. */ abstract class Overlay<T: ChartWrapper>: ChartComponent { var wrapper: ChartWrapper? = null set(value) { field = value afterChartInitialized() } var mouseLocation: Point? = null /** * Typed value for {@code wrapper}. * * Normally wrapper is already initialized when added to ChartWrapper. */ val chart: T @Suppress("UNCHECKED_CAST") get() = wrapper as T open fun afterChartInitialized() { } fun Point.toChartSpace(): Point? = wrapper?.let { if (it.margins.left < x && x < it.width - it.margins.right && it.margins.top < y && y < it.height - it.margins.bottom) { Point(x - it.margins.left, y - it.margins.top) } else null } } interface XYChartComponent<X: Number, Y: Number> { val ranges: MinMax<X, Y> } abstract class GridChartWrapper<X: Number, Y: Number>: ChartWrapper(), XYChartComponent<X, Y> { abstract override val ranges: Grid<X, Y> val grid: Grid<X, Y> get() = ranges val gridWidth: Int get() = width - (margins.left + margins.right) val gridHeight: Int get() = height - (margins.top + margins.bottom) var gridColor: Color = JBColor(Color(0xF0F0F0), Color(0x313335)) var gridLabelColor: Color = ColorUtil.withAlpha(JBColor.foreground(), 0.6) protected fun paintGrid(grid: Graphics2D, chart: Graphics2D, xy: MinMax<X, Y>) { val gc = Color(gridColor.rgb) val gcd = gc.darker() val bounds = grid.clipBounds val xOrigin: Int = if (ranges.xOriginInitialized) findX(xy, ranges.xOrigin).toInt() else 0 val yOrigin: Int = if (ranges.yOriginInitialized) findY(xy, ranges.yOrigin).toInt() else height var tmp: Int // — helps to filter line drawing, when lines are met too often // draws vertical grid lines tmp = -1 ranges.xLines.apply { min = xy.xMin max = xy.xMax }.forEach { val gl = GridLine(it, xy, SwingConstants.VERTICAL).apply(ranges.xPainter::accept) val px = findGridLineX(gl, it).roundToInt() if (gl.paintLine) { if ((tmp - px).absoluteValue < 1) { return@forEach } else { tmp = px } grid.color = if (gl.majorLine) gcd else gc grid.drawLine(px, bounds.y, px, bounds.y + bounds.height) } gl.label?.let { label -> chart.color = gridLabelColor val (x, y) = findGridLabelOffset(gl, chart) chart.drawString(label, px + margins.left - x.toInt(), yOrigin - margins.bottom + y.toInt()) } } // draws horizontal grid lines tmp = -1 ranges.yLines.apply { min = xy.yMin max = xy.yMax }.forEach { val gl = GridLine(it, xy).apply(ranges.yPainter::accept) val py = findGridLineY(gl, it).roundToInt() if (gl.paintLine) { if ((tmp - py).absoluteValue < 1) { return@forEach } else { tmp = py } grid.color = if (gl.majorLine) gcd else gc grid.drawLine(bounds.x, py, bounds.x + bounds.width, py) } gl.label?.let { label -> chart.color = gridLabelColor val (x, y) = findGridLabelOffset(gl, chart) chart.drawString(label, xOrigin + margins.left - x.toInt(), py + margins.top + y.toInt() ) } } } protected open fun findGridLineX(gl: GridLine<X, Y, *>, x: X) = findX(gl.xy, x) protected open fun findGridLineY(gl: GridLine<X, Y, *>, y: Y) = findY(gl.xy, y) abstract fun findMinMax(): MinMax<X, Y> protected open fun findX(xy: MinMax<X, Y>, x: X): Double { val width = width - (margins.left + margins.right) return width * (x.toDouble() - xy.xMin.toDouble()) / (xy.xMax.toDouble() - xy.xMin.toDouble()) } protected open fun findY(xy: MinMax<X, Y>, y: Y): Double { val height = height - (margins.top + margins.bottom) return height - height * (y.toDouble() - xy.yMin.toDouble()) / (xy.yMax.toDouble() - xy.yMin.toDouble()) } protected open fun findGridLabelOffset(line: GridLine<*, *, *>, g: Graphics2D): Coordinates<Double, Double> { val s = JBUI.scale(4).toDouble() val b = g.fontMetrics.getStringBounds(line.label, null) val x = when (line.horizontalAlignment) { SwingConstants.RIGHT -> -s SwingConstants.CENTER -> b.width / 2 SwingConstants.LEFT -> b.width + s else -> -s } val y = b.height - when (line.verticalAlignment) { SwingConstants.TOP -> b.height + s SwingConstants.CENTER -> b.height / 2 + s / 2 // compensate SwingConstants.BOTTOM -> 0.0 else -> 0.0 } return x to y } } abstract class ChartWrapper : ChartComponent { var width: Int = 0 private set var height: Int = 0 private set var background: Color = JBColor.background() var overlays: List<ChartComponent> = mutableListOf() set(value) { field.forEach { if (it is Overlay<*>) it.wrapper = null } (field as MutableList<ChartComponent>).addAll(value) field.forEach { if (it is Overlay<*>) it.wrapper = this } } var margins = Insets(0, 0, 0, 0) open fun paintOverlay(g: Graphics2D) { overlays.forEach { it.paintComponent(g) } } open val component: JComponent by lazy { createCentralPanel().apply { with(MouseAware()) { addMouseMotionListener(this) addMouseListener(this) } } } fun update() = component.repaint() protected open fun createCentralPanel(): JComponent = CentralPanel() protected var mouseLocation: Point? = null private set(value) { field = value overlays.forEach { if (it is Overlay<*>) it.mouseLocation = value } } private inner class MouseAware : MouseAdapter() { override fun mouseMoved(e: MouseEvent) { mouseLocation = e.point component.repaint() } override fun mouseEntered(e: MouseEvent) { mouseLocation = e.point component.repaint() } override fun mouseExited(e: MouseEvent) { mouseLocation = null component.repaint() } override fun mouseDragged(e: MouseEvent) { mouseLocation = e.point component.repaint() } } private inner class CentralPanel : JComponent() { override fun paintComponent(g: Graphics) { g.clip = Rectangle(0, 0, width, height) g.color = [email protected] (g as Graphics2D).fill(g.clip) [email protected] = height [email protected] = width val gridGraphics = (g.create(0, 0, [email protected], [email protected]) as Graphics2D).apply { setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON) setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_SPEED) setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE) GraphicsUtil.setupAntialiasing(this) } try { [email protected](gridGraphics) } finally { gridGraphics.dispose() } val overlayGraphics = (g.create() as Graphics2D).apply { setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON) setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_SPEED) setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE) GraphicsUtil.setupAntialiasing(this) } try { [email protected](overlayGraphics) } finally { overlayGraphics.dispose() } } } } open class Dataset<T> { var label: String? = null var lineColor: Paint? = JBColor.foreground() var fillColor: Paint? = null open var data: Iterable<T> = mutableListOf() fun add(vararg values: T) { addAll(values.toList()) } @Suppress("UNCHECKED_CAST") fun addAll(values: Collection<T>) { (data as? MutableList<T>)?.addAll(values) ?: throw UnsupportedOperationException() } fun Color.transparent(alpha: Double) = ColorUtil.withAlpha(this, alpha) } data class Coordinates<X: Number, Y: Number>(val x: X, val y: Y) { companion object { @JvmStatic fun <X: Number, Y: Number> of(x: X, y: Y) : Coordinates<X, Y> = Coordinates(x, y) } } infix fun <X: Number, Y: Number> X.to(y: Y): Coordinates<X, Y> = Coordinates(this, y) open class MinMax<X: Number, Y: Number> { lateinit var xMin: X val xMinInitialized get() = this::xMin.isInitialized lateinit var xMax: X val xMaxInitialized get() = this::xMax.isInitialized lateinit var yMin: Y val yMinInitialized get() = this::yMin.isInitialized lateinit var yMax: Y val yMaxInitialized get() = this::yMax.isInitialized fun process(point: Coordinates<X, Y>) { val (x, y) = point process(x, y) } fun process(x: X, y: Y) { processX(x) processY(y) } fun processX(x: X) { xMin = if (!xMinInitialized || xMin.toDouble() > x.toDouble()) x else xMin xMax = if (!xMaxInitialized || xMax.toDouble() < x.toDouble()) x else xMax } fun processY(y: Y) { yMin = if (!yMinInitialized || yMin.toDouble() > y.toDouble()) y else yMin yMax = if (!yMaxInitialized || yMax.toDouble() < y.toDouble()) y else yMax } operator fun times(other: MinMax<X, Y>): MinMax<X, Y> { val my = MinMax<X, Y>() if (this.xMinInitialized) my.xMin = this.xMin else if (other.xMinInitialized) my.xMin = other.xMin if (this.xMaxInitialized) my.xMax = this.xMax else if (other.xMaxInitialized) my.xMax = other.xMax if (this.yMinInitialized) my.yMin = this.yMin else if (other.yMinInitialized) my.yMin = other.yMin if (this.yMaxInitialized) my.yMax = this.yMax else if (other.yMaxInitialized) my.yMax = other.yMax return my } operator fun plus(other: MinMax<X, Y>) : MinMax<X, Y> { val my = MinMax<X, Y>() help(this.xMinInitialized, this::xMin, other.xMinInitialized, other::xMin, -1, my::xMin.setter) help(this.xMaxInitialized, this::xMax, other.xMaxInitialized, other::xMax, 1, my::xMax.setter) help(this.yMinInitialized, this::yMin, other.yMinInitialized, other::yMin, -1, my::yMin.setter) help(this.yMaxInitialized, this::yMax, other.yMaxInitialized, other::yMax, 1, my::yMax.setter) return my } private fun <T: Number> help(thisInitialized: Boolean, thisGetter: () -> T, otherInitialized: Boolean, otherGetter: () -> T, sign: Int, calc: (T) -> Unit) { when { thisInitialized && otherInitialized -> { val thisValue = thisGetter().toDouble() val thatValue = otherGetter().toDouble() calc(if (thisValue.compareTo(thatValue).sign == sign) thisGetter() else otherGetter()) } thisInitialized && !otherInitialized -> calc((thisGetter())) !thisInitialized && otherInitialized -> calc(otherGetter()) } } operator fun component1(): X = xMin operator fun component2(): X = xMax operator fun component3(): Y = yMin operator fun component4(): Y = yMax val isInitialized get() = xMinInitialized && xMaxInitialized && yMinInitialized && yMaxInitialized } class Grid<X: Number, Y: Number>: MinMax<X, Y>() { lateinit var xOrigin: X val xOriginInitialized get() = this::xOrigin.isInitialized var xLines: ValueIterable<X> = ValueIterable.createStub() var xPainter: (Consumer<GridLine<X, Y, X>>) = Consumer { } lateinit var yOrigin: Y val yOriginInitialized get() = this::yOrigin.isInitialized var yLines: ValueIterable<Y> = ValueIterable.createStub() var yPainter: (Consumer<GridLine<X, Y, Y>>) = Consumer { } } class GridLine<X: Number, Y: Number, T: Number>(val value: T, @get:JvmName("getXY") val xy: MinMax<X, Y>, @MagicConstant val orientation: Int = SwingConstants.HORIZONTAL) { var paintLine = true var majorLine = false var label: String? = null @MagicConstant var horizontalAlignment = SwingConstants.CENTER @MagicConstant var verticalAlignment = SwingConstants.BOTTOM } abstract class ValueIterable<X: Number> : Iterable<X> { lateinit var min: X lateinit var max: X open fun prepare(min: X, max: X): ValueIterable<X> { this.min = min this.max = max return this } companion object { fun <T: Number> createStub(): ValueIterable<T> { return object: ValueIterable<T>() { val iter = object: Iterator<T> { override fun hasNext() = false override fun next(): T { error("not implemented") } } override fun iterator(): Iterator<T> = iter } } } }
apache-2.0
b784680f35f3bf41926dfdfb91f42802
31.243176
172
0.661202
3.784736
false
false
false
false
Waboodoo/HTTP-Shortcuts
HTTPShortcuts/app/src/main/kotlin/ch/rmy/android/http_shortcuts/activities/widget/WidgetSettingsActivity.kt
1
5350
package ch.rmy.android.http_shortcuts.activities.widget import android.app.Activity import android.content.Intent import android.os.Bundle import android.view.Menu import android.view.MenuItem import androidx.core.view.isVisible import ch.rmy.android.framework.extensions.bindViewModel import ch.rmy.android.framework.extensions.collectEventsWhileActive import ch.rmy.android.framework.extensions.collectViewStateWhileActive import ch.rmy.android.framework.extensions.consume import ch.rmy.android.framework.extensions.createIntent import ch.rmy.android.framework.ui.BaseActivityResultContract import ch.rmy.android.framework.ui.BaseIntentBuilder import ch.rmy.android.http_shortcuts.R import ch.rmy.android.http_shortcuts.activities.BaseActivity import ch.rmy.android.http_shortcuts.data.domains.shortcuts.ShortcutId import ch.rmy.android.http_shortcuts.data.dtos.LauncherShortcut import ch.rmy.android.http_shortcuts.databinding.ActivityWidgetSettingsBinding import ch.rmy.android.http_shortcuts.icons.ShortcutIcon class WidgetSettingsActivity : BaseActivity() { private lateinit var binding: ActivityWidgetSettingsBinding private val viewModel: WidgetSettingsViewModel by bindViewModel() override fun onCreated(savedState: Bundle?) { viewModel.initialize( WidgetSettingsViewModel.InitData( shortcutId = intent.getStringExtra(EXTRA_SHORTCUT_ID)!!, shortcutName = intent.getStringExtra(EXTRA_SHORTCUT_NAME)!!, shortcutIcon = ShortcutIcon.fromName(intent.getStringExtra(EXTRA_SHORTCUT_ICON)!!), ), ) initViews() initUserInputBindings() initViewModelBindings() } private fun initViews() { binding = applyBinding(ActivityWidgetSettingsBinding.inflate(layoutInflater)) setTitle(R.string.title_configure_widget) } private fun initUserInputBindings() { binding.inputLabelColor.setOnClickListener { viewModel.onLabelColorInputClicked() } binding.inputShowLabel.setOnCheckedChangeListener { _, isChecked -> viewModel.onShowLabelChanged(isChecked) } } private fun initViewModelBindings() { collectViewStateWhileActive(viewModel) { viewState -> binding.widgetLabel.isVisible = viewState.showLabel binding.inputLabelColor.isEnabled = viewState.showLabel binding.widgetIcon.setIcon(viewState.shortcutIcon) binding.widgetLabel.text = viewState.shortcutName binding.inputLabelColor.subtitle = viewState.labelColorFormatted binding.widgetLabel.setTextColor(viewState.labelColor) setDialogState(viewState.dialogState, viewModel) } collectEventsWhileActive(viewModel, ::handleEvent) } override fun onCreateOptionsMenu(menu: Menu): Boolean { menuInflater.inflate(R.menu.widget_settings_activity_menu, menu) return super.onCreateOptionsMenu(menu) } override fun onOptionsItemSelected(item: MenuItem) = when (item.itemId) { R.id.action_create_widget -> consume { viewModel.onCreateButtonClicked() } else -> super.onOptionsItemSelected(item) } override val navigateUpIcon = R.drawable.ic_clear object OpenWidgetSettings : BaseActivityResultContract<IntentBuilder, OpenWidgetSettings.Result?>(::IntentBuilder) { private const val EXTRA_SHOW_LABEL = "ch.rmy.android.http_shortcuts.activities.widget.WidgetSettingsActivity.show_label" private const val EXTRA_LABEL_COLOR = "ch.rmy.android.http_shortcuts.activities.widget.WidgetSettingsActivity.label_color" override fun parseResult(resultCode: Int, intent: Intent?): Result? = if (resultCode == Activity.RESULT_OK && intent != null) { Result( shortcutId = intent.getStringExtra(EXTRA_SHORTCUT_ID)!!, labelColor = intent.getStringExtra(EXTRA_LABEL_COLOR)!!, showLabel = intent.getBooleanExtra(EXTRA_SHOW_LABEL, true), ) } else null fun createResult(shortcutId: ShortcutId, labelColor: String, showLabel: Boolean): Intent = createIntent { putExtra(EXTRA_SHORTCUT_ID, shortcutId) putExtra(EXTRA_LABEL_COLOR, labelColor) putExtra(EXTRA_SHOW_LABEL, showLabel) } data class Result( val shortcutId: ShortcutId, val labelColor: String, val showLabel: Boolean, ) } class IntentBuilder : BaseIntentBuilder(WidgetSettingsActivity::class) { fun shortcut(shortcut: LauncherShortcut) = also { intent.putExtra(EXTRA_SHORTCUT_ID, shortcut.id) intent.putExtra(EXTRA_SHORTCUT_NAME, shortcut.name) intent.putExtra(EXTRA_SHORTCUT_ICON, shortcut.icon.toString()) } } companion object { private const val EXTRA_SHORTCUT_ID = "ch.rmy.android.http_shortcuts.activities.widget.WidgetSettingsActivity.shortcut_id" private const val EXTRA_SHORTCUT_NAME = "ch.rmy.android.http_shortcuts.activities.widget.WidgetSettingsActivity.shortcut_name" private const val EXTRA_SHORTCUT_ICON = "ch.rmy.android.http_shortcuts.activities.widget.WidgetSettingsActivity.shortcut_icon" } }
mit
9f0c0b116453abbaa4585d8bef6dfe0a
42.145161
134
0.710467
4.885845
false
false
false
false
7449/Album
wechat/src/main/java/com/gallery/ui/wechat/adapter/WeChatPrevSelectAdapter.kt
1
2530
package com.gallery.ui.wechat.adapter import android.view.LayoutInflater import android.view.ViewGroup import android.widget.FrameLayout import androidx.recyclerview.widget.RecyclerView import com.gallery.compat.finder.GalleryFinderAdapter import com.gallery.core.entity.ScanEntity import com.gallery.ui.wechat.R import com.gallery.ui.wechat.databinding.WechatGalleryItemPrevSelectBinding class WeChatPrevSelectAdapter( private val listener: GalleryFinderAdapter.AdapterFinderListener, ) : RecyclerView.Adapter<WeChatPrevSelectAdapter.ViewHolder>() { private val list: ArrayList<ScanEntity> = arrayListOf() override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { return ViewHolder( WechatGalleryItemPrevSelectBinding.inflate( LayoutInflater.from(parent.context), parent, false ) ).apply { itemView.setOnClickListener { listener.onGalleryAdapterItemClick( it, bindingAdapterPosition, list[bindingAdapterPosition] ) } } } override fun getItemCount(): Int = list.size override fun onBindViewHolder(holder: ViewHolder, position: Int) { val entity: ScanEntity = list[position] val frameLayout: FrameLayout = holder.binding.prevSelectFrame frameLayout.setBackgroundResource(if (entity.isSelected) R.drawable.wechat_gallery_selector_gallery_select else 0) listener.onGalleryFinderThumbnails(entity, frameLayout) } fun updateSelect(entities: List<ScanEntity>) { list.clear() list.addAll(entities.map { it.copy() }) notifyDataSetChanged() } fun index(scanEntity: ScanEntity): Int { return list.indexOfFirst { it.id == scanEntity.id } } fun addSelect(entity: ScanEntity) { list.forEach { it.isSelected = false } list.find { it.id == entity.id }?.let { it.isSelected = true } ?: list.add(entity.copy(isSelected = true)) notifyDataSetChanged() } fun refreshItem(scanEntity: ScanEntity) { list.forEach { it.isSelected = it.id == scanEntity.id } notifyDataSetChanged() } class ViewHolder(val binding: WechatGalleryItemPrevSelectBinding) : RecyclerView.ViewHolder(binding.root) }
mpl-2.0
91aa5931362a31225de2720f262999e6
33.661972
122
0.63834
5.07014
false
false
false
false
Waboodoo/HTTP-Shortcuts
HTTPShortcuts/app/src/main/kotlin/ch/rmy/android/http_shortcuts/data/models/HeaderModel.kt
1
547
package ch.rmy.android.http_shortcuts.data.models import ch.rmy.android.framework.utils.UUIDUtils.newUUID import io.realm.RealmModel import io.realm.annotations.PrimaryKey import io.realm.annotations.RealmClass import io.realm.annotations.Required @RealmClass(name = "Header") open class HeaderModel( @PrimaryKey @Required var id: String = newUUID(), @Required var key: String = "", @Required var value: String = "", ) : RealmModel { fun isSameAs(other: HeaderModel) = other.key == key && other.value == value }
mit
39875c4e9eb555ce9e81e07d368495e7
25.047619
79
0.720293
3.721088
false
false
false
false
vector-im/vector-android
vector/src/main/java/im/vector/activity/KeysBackupRestoreActivity.kt
2
4664
/* * Copyright 2019 New Vector Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package im.vector.activity import android.app.Activity import android.content.Context import android.content.Intent import androidx.appcompat.app.AlertDialog import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProviders import im.vector.R import im.vector.fragments.keysbackup.restore.KeysBackupRestoreFromKeyFragment import im.vector.fragments.keysbackup.restore.KeysBackupRestoreFromPassphraseFragment import im.vector.fragments.keysbackup.restore.KeysBackupRestoreSharedViewModel import im.vector.fragments.keysbackup.restore.KeysBackupRestoreSuccessFragment class KeysBackupRestoreActivity : SimpleFragmentActivity() { companion object { fun intent(context: Context, matrixID: String): Intent { val intent = Intent(context, KeysBackupRestoreActivity::class.java) intent.putExtra(EXTRA_MATRIX_ID, matrixID) return intent } } override fun getTitleRes() = R.string.title_activity_keys_backup_restore private lateinit var viewModel: KeysBackupRestoreSharedViewModel override fun initUiAndData() { super.initUiAndData() viewModel = ViewModelProviders.of(this).get(KeysBackupRestoreSharedViewModel::class.java) viewModel.initSession(mSession) viewModel.keyVersionResult.observe(this, Observer { keyVersion -> if (keyVersion != null && supportFragmentManager.fragments.isEmpty()) { val isBackupCreatedFromPassphrase = keyVersion.getAuthDataAsMegolmBackupAuthData()?.privateKeySalt != null if (isBackupCreatedFromPassphrase) { supportFragmentManager.beginTransaction() .replace(R.id.container, KeysBackupRestoreFromPassphraseFragment.newInstance()) .commitNow() } else { supportFragmentManager.beginTransaction() .replace(R.id.container, KeysBackupRestoreFromKeyFragment.newInstance()) .commitNow() } } }) viewModel.keyVersionResultError.observe(this, Observer { uxStateEvent -> uxStateEvent?.getContentIfNotHandled()?.let { AlertDialog.Builder(this) .setTitle(R.string.unknown_error) .setMessage(it) .setCancelable(false) .setPositiveButton(R.string.ok) { _, _ -> //nop finish() } .show() } }) if (viewModel.keyVersionResult.value == null) { //We need to fetch from API viewModel.getLatestVersion(this) } viewModel.navigateEvent.observe(this, Observer { uxStateEvent -> when (uxStateEvent?.getContentIfNotHandled()) { KeysBackupRestoreSharedViewModel.NAVIGATE_TO_RECOVER_WITH_KEY -> { supportFragmentManager.beginTransaction() .replace(R.id.container, KeysBackupRestoreFromKeyFragment.newInstance()) .addToBackStack(null) .commit() } KeysBackupRestoreSharedViewModel.NAVIGATE_TO_SUCCESS -> { supportFragmentManager.popBackStack(null, androidx.fragment.app.FragmentManager.POP_BACK_STACK_INCLUSIVE) supportFragmentManager.beginTransaction() .replace(R.id.container, KeysBackupRestoreSuccessFragment.newInstance()) .commit() } } }) viewModel.loadingEvent.observe(this, Observer { updateWaitingView(it) }) viewModel.importRoomKeysFinishWithResult.observe(this, Observer { it?.getContentIfNotHandled()?.let { //set data? setResult(Activity.RESULT_OK) finish() } }) } }
apache-2.0
c70bcc45232347bef352757a98e703d2
39.565217
125
0.621998
5.461358
false
false
false
false
glorantq/KalanyosiRamszesz
src/glorantq/ramszesz/commands/PlayingTextCommand.kt
1
1946
package glorantq.ramszesz.commands import glorantq.ramszesz.utils.BotUtils import glorantq.ramszesz.Ramszesz import sx.blah.discord.handle.impl.events.guild.channel.message.MessageReceivedEvent /** * Created by glora on 2017. 07. 23.. */ class PlayingTextCommand : ICommand { override val commandName: String get() = "playingtext" override val description: String get() = "Change the playing text" override val permission: Permission get() = Permission.BOT_OWNER override val aliases: List<String> get() = listOf("playing", "pt") override val undocumented: Boolean get() = true override val availableInDM: Boolean get() = true override fun execute(event: MessageReceivedEvent, args: List<String>) { val builder: StringBuilder = StringBuilder() for(part: String in args) { builder.append(part) builder.append(" ") } var status: String = builder.toString().trim() status = when(status) { "guild_count" -> buildString { append("in ") append(event.client.guilds.size) append(" guilds") } "user_count" -> buildString { var users: Int = 0 event.client.guilds.forEach { users += it.users.size } append("with ") append(users) append(" users") } else -> if(status.isEmpty()) { "default" } else { status } } if(status.equals("default", true)) { Ramszesz.instance.updatePlayingText = true } else { Ramszesz.instance.updatePlayingText = false event.client.changePlayingText(status) } BotUtils.sendMessage(BotUtils.createSimpleEmbed("Change Playing Text", "Successfully changed playing text to: `$status`", event.author), event.channel) } }
gpl-3.0
438e8ea57334447f906a590bcb046a52
31.45
159
0.59147
4.578824
false
false
false
false